Algorithmcore
Compiled-code logic simulation
Also called levelized compiled-code simulation, LCC simulation.
Levelizes a combinational netlist once and turns it into straight-line code with one statement per gate; with bit-parallel words, one run evaluates W input vectors.
- Solves
- Logic simulation
- Time
- O(G log G + P + (m / W + 1) (G + P)) worst · best
- Space
- O(N + P) extra
- Where
- G = the number of gates; N = the number of nets; P = the number of gate input pins; W = the word width; m = the number of input vectors
- Model
- Word RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Zeev Barzilai, J. Lawrence Carter, Barry K. Rosen, Joseph D. Rutledge, 1987
Compiled-code logic simulation evaluates a combinational netlist by running a program made from it. The netlist is put in levelized order once, so that every gate comes after the gates that drive its inputs, and each gate becomes one statement of straight-line code with no tests and no loops. The delay model is zero delay: every gate is evaluated once per input vector, and only the settled values are computed. If each variable is a machine word and each statement uses the bitwise operations of the machine, bit of every word belongs to input vector , and one run of the program simulates vectors. This page is in the logic simulation half of logic and circuit simulation, with the values 0 and 1. Compared with event-driven simulation, it does more evaluations, since it evaluates every gate even when nothing changed, but each evaluation is one machine instruction with no queue and no branch.
In plain words
Sort the gates so that each gate comes after the gates it reads. Then write one line of code per gate, in that order, such as y = p | q. Running these lines once gives every gate its value, because each line reads values that the lines above it have already set.
A computer word has 64 bits, and an AND of two words does 64 separate ANDs at once. So put the value of input for 64 different test vectors into the 64 bits of one word, and do the same for each input. One run of the code then gives the outputs for all 64 vectors.
The price is that the code says nothing about time. It gives the final values only, not glitches or delays.
The problem
The input is a combinational netlist with gates, nets and gate input pins, and a list of input vectors in . The output is the value of every primary output for every vector. The gates must not form a loop. A sequential design is first cut at its registers, which is what cycle-based simulation does.
The algorithm
COMPILE(C, W)- 1
levelize C by Kahn's algorithm: level(input) = 0, level(out(g)) = 1 + the largest level of the inputs of g; stop with "loop" if some gate gets no level - 2
for each gate g in order of increasing level do - 3
emit the statement word[out(g)] ← f_g(word of each input), with bitwise AND, OR and XOR, and XOR with the all-ones word for NOT - 4
translate the straight-line program to machine code SIMULATE(program, vectors v_1, ..., v_m)- 5
for each block of W consecutive vectors do - 6
for each input i: word[i] ← the W bits of input i, bit j from vector j of the block - 7
run the program once - 8
for each output o and each j: the value of o in vector j is bit j of word[o]
Kahn's algorithm (see topological sort) keeps a queue of gates whose inputs are all levelized. It takes a gate, gives it its level and lowers the count of missing inputs of each gate in its fanout. Any order in which every gate follows its drivers would do; the order by level also groups gates that do not depend on each other, which helps when the code is spread over parallel units.
A NAND is an AND followed by XOR with the all-ones word , so that only the lanes are inverted. Line L4 is the compile step. A production simulator emits C or machine code; the implementation of this page emits Python source and calls the Python compiler on it.
Example
Take with gates , , and , given in the netlist in the order . Kahn's algorithm gives and level 1, level 2 and level 3. The implementation names the nets as to and emits:
def run(w):
v0 = w[0] # a
v1 = w[1] # b
v2 = w[2] # c
v5 = v0 & v1 # p = a AND b
v6 = v0 ^ M # not a
v4 = v6 & v2 # q = (not a) AND c
v3 = v5 | v4 # y = p OR q
return [v3]
With , put the eight vectors into lanes to , so bit of each word holds the bits of :
| word | lane 7 to lane 0 |
|---|---|
| 1 1 1 1 0 0 0 0 | |
| 1 1 0 0 1 1 0 0 | |
| 1 0 1 0 1 0 1 0 | |
| 1 1 0 0 0 0 0 0 | |
| 0 0 0 0 1 1 1 1 | |
| 0 0 0 0 1 0 1 0 | |
| 1 1 0 0 1 0 1 0 |
So is the word 0b11001010, which is the truth table of read from lane 7 down to lane 0. One run of four instructions gave all eight vectors. The event-driven run on the event-driven page shows a glitch on when falls with ; the compiled code cannot show it, since it has no time.
Correctness
The proof in proofs/correctness.md has two parts. Kahn's algorithm gives every gate a level exactly when the netlist has no loop, and then every gate comes after the drivers of its inputs. The bitwise operations act on each lane alone, so lane of the program is the program for vector . Induction along the program shows that after the statement of gate , lane of is the value of under vector . The tests compare every output against a one-vector evaluation of the netlist, on all vectors of random circuits with up to 10 inputs and 60 gates, with the word widths 64, 7 and 1.
Proof: The levelized bit-parallel program computes every output for every vector of the blockfull
Let be a netlist with primary inputs, gates with functions built from AND, OR, NAND, NOR, XOR, XNOR, NOT and BUF, and nets that are each driven by one input or one gate. Lines L1 to L8 refer to the pseudocode of the page. The gate graph has an edge from gate to gate when is an input of .
Lemma 1 (levelization). Line L1 gives a level to every gate if and only if the gate graph has no cycle. When it does, the order by increasing level puts every gate after each gate that drives one of its inputs.
Proof. Kahn's algorithm keeps, for each gate, the number of distinct gate-driven inputs that have no level yet, and puts a gate into the queue when the number reaches 0. If the graph has a cycle, no gate on the cycle can enter the queue first, because each of them waits for its predecessor on the cycle. So some gate gets no level. If the graph has no cycle, suppose some gates never enter the queue. Each of them has an input driven by another gate that never enters the queue, since all its other inputs got levels and lowered its count. Following these inputs backwards gives an infinite walk among finitely many gates, so a cycle, which is a contradiction. When gate gets its level, all its inputs have levels, and of them, so every driver of an input of has a smaller level and comes before in the order by level.
Lemma 2 (lanes). For words of bits and , bit of , , and is the AND, OR, XOR of bit of and of , and the NOT of bit of . So, for every gate function , bit of the word expression of L3 equals applied to bit of the input words.
Proof. The bitwise operations are defined bit by bit. Bit of is 1 for , and . The expressions for NAND, NOR and XNOR are the expressions for AND, OR and XOR followed by XOR with .
Theorem. Let have no loop. For every block of vectors with and every , after line L7, bit of is the value of net in under vector , for every net . So line L8 returns the correct output values.
Proof. Line L6 makes the claim true for the primary inputs. The program assigns each gate output once, in the order of Lemma 1. Induction along the program: when the statement of gate runs, every input of is a primary input or the output of a gate whose statement came earlier, so by induction its word holds the correct value in every lane. By Lemma 2, lane of the new word is of the correct input values under , which is the value of under , since in a loop-free circuit the value of each net is fixed by its function and the values of its inputs.
The lanes of a short last block hold the values for the all-zero vector. Line L8 reads only the lanes to , so they do no harm.
Complexity
Levelization costs for Kahn's algorithm plus the sort by level, which is in the implementation and with a bucket per level. Emitting the code costs . Each run of the program costs one word operation per gate input pin, so , and there are runs. Packing and unpacking cost bit moves for the inputs and per output. For an exhaustive check of a block with inputs, , and the run count is .
Compared with event-driven simulation, the work per vector does not depend on how many nets change. When the activity is high, as with random vectors in fault simulation, compiled code is faster by a large factor. When only a few nets change per vector, event-driven simulation can do less work.
Properties
- Zero delay only. The result is the settled value. Hazards, glitches and the order of changes are lost.
- No branches. The code has no data-dependent tests. This suits pipelined processors and was the base of hardware simulation engines such as IBM's Yorktown Simulation Engine.
- Lanes are independent. The vectors in a word never mix, so the lanes can hold different vectors, different faulty circuits, or both.
- Exact. On loop-free netlists the outputs equal the Boolean function of the circuit on each vector.
Variants and improvements
- Parallel fault simulation. The lanes hold one good and faulty circuits, each with a fault forced in its lane. See parallel fault simulation and PPSFP, which puts patterns in the lanes and handles one fault at a time.
- Three values. With X, each net needs two words, for example one with the lanes that can be 1 and one with the lanes that can be 0, and each gate becomes a few word operations. See multi-valued logic simulation.
- Unit-delay compiled code. Keeping one word per net per time step gives the unit-delay waveforms, at the cost of the depth of the circuit in extra statements.
- Sequential designs. Cut the loops at the registers and run the program once per clock: this is cycle-based simulation.
- Other parallelism. Bit slicing is the same idea in cryptography: a circuit in bitwise operations that processes blocks at once.
When to use it
Use compiled code for functional simulation of synchronous logic where only the values at the clock edges matter, for exhaustive checks of small blocks, and for fault simulation with many patterns. Do not use it when the timing of signals inside a clock cycle matters, for asynchronous logic, or for circuits with combinational loops; an event-driven simulator with delays is the right tool there.
Pitfalls
- Combinational loops. A netlist with a loop has no levelized order. Latches and loops that settle must be cut or simulated by events. The implementation reports such a netlist instead of emitting wrong code.
- NOT without the mask. In a language with unbounded integers, such as Python,
~xgives a negative number. Use XOR with the all-ones word of width . - The last block. When is not a multiple of , the unused lanes hold zeros. Unpack only the lanes in use.
- Expecting glitches. Zero-delay compiled code is blind to hazards. Use event-driven simulation with delays to see them.
- Code size. One statement per gate gives a large program for a large netlist. Compile time and instruction cache misses can then dominate, which is why some simulators keep the levelized netlist as a table and run a small interpreter over it.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/compiled-code-logic-simulation/. The authors are listed in prov/6EDHZJ.jsonl.
"""Levelized compiled-code logic simulation with bit-parallel words.
The netlist is levelized once (Kahn's algorithm) and turned into straight-line
code with one statement for each gate. The delay model is zero delay, and the
values are 0 and 1. Bit j of every word belongs to input vector j, so one run
of the code simulates W vectors at once.
"""
from __future__ import annotations
from typing import Callable, Dict, List, Sequence, Tuple
from logicnet import Circuit
class CombinationalLoop(ValueError):
"""The netlist has a loop, so it has no levelized order."""
def levelize(c: Circuit) -> Tuple[List[int], Dict[str, int]]:
"""Kahn's algorithm: gates in an order where every gate follows the drivers of its inputs."""
level = {n: 0 for n in c.inputs}
waiting = [len({n for n in ins if n in c.driver}) for _, _, ins in c.gates]
ready = [i for i in range(len(c.gates)) if waiting[i] == 0]
order: List[int] = []
head = 0
while head < len(ready):
g = ready[head]
head += 1
out, op, ins = c.gates[g]
level[out] = 1 + max(level[n] for n in ins)
order.append(g)
for h in c.fanout[out]:
waiting[h] -= 1
if waiting[h] == 0:
ready.append(h)
if len(order) != len(c.gates):
raise CombinationalLoop("the circuit has a loop of gates")
order.sort(key=lambda g: level[c.gates[g][0]]) # stable: ties keep the Kahn order
return order, level
def _expr(op: str, args: List[str]) -> str:
if op == "BUF":
return args[0]
if op == "NOT":
return f"{args[0]} ^ M"
sym = {"AND": " & ", "NAND": " & ", "OR": " | ", "NOR": " | ", "XOR": " ^ ", "XNOR": " ^ "}[op]
body = sym.join(args)
return f"({body}) ^ M" if op in ("NAND", "NOR", "XNOR") else body
def compile_circuit(c: Circuit, width: int = 64) -> Tuple[str, Callable[[Sequence[int]], List[int]]]:
"""Return the source of the straight-line program and the compiled function.
The function takes one word for each primary input and returns one word
for each primary output.
"""
order, _ = levelize(c) # @line L1
name = {n: f"v{k}" for k, n in enumerate(c.nets)}
lines = ["def run(w):"]
lines += [f" {name[n]} = w[{k}]" for k, n in enumerate(c.inputs)]
for g in order: # @line L2
out, op, ins = c.gates[g]
lines.append(f" {name[out]} = {_expr(op, [name[n] for n in ins])}") # @line L3
lines.append(" return [" + ", ".join(name[n] for n in c.outputs) + "]")
src = "\n".join(lines) + "\n"
env = {"M": (1 << width) - 1}
exec(compile(src, "<compiled circuit>", "exec"), env) # @line L4
return src, env["run"]
def simulate(c: Circuit, vectors: Sequence[Dict[str, int]], width: int = 64) -> List[Dict[str, int]]:
"""Output values for each vector, W vectors per run of the compiled code."""
_, run = compile_circuit(c, width)
result: List[Dict[str, int]] = []
for start in range(0, len(vectors), width): # @line L5
block = vectors[start:start + width]
words = [sum(vec[n] << j for j, vec in enumerate(block)) for n in c.inputs] # @line L6
outs = run(words) # @line L7
for j in range(len(block)): # @line L8
result.append({o: (w >> j) & 1 for o, w in zip(c.outputs, outs)})
return result
logicnet.py 173 lines
# SPDX-License-Identifier: MIT
# Shared helper of the sim1 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Gate netlists and gate functions for the logic simulation pages.
A value is 0, 1 or X = 2, where X means "unknown, it can be 0 or 1".
A circuit has named primary inputs, gates (out, op, ins) and named primary
outputs. Every net is a primary input or the output of exactly one gate.
The gates may form loops, but direct_eval needs a circuit without loops.
This module holds no simulation algorithm. It gives the gate functions, the
netlist, a direct recursive evaluation that serves as the reference, random
circuits for tests and the binary completions of a three-valued vector.
"""
from __future__ import annotations
import itertools
import random
from typing import Dict, Iterator, List, Optional, Sequence, Tuple
X = 2
OPS = ("AND", "OR", "NAND", "NOR", "XOR", "XNOR", "NOT", "BUF")
ONE_INPUT = ("NOT", "BUF")
def eval2(op: str, vals: Sequence[int]) -> int:
"""The gate function on values in {0, 1}."""
if op == "AND":
return int(all(vals))
if op == "OR":
return int(any(vals))
if op == "NAND":
return 1 - int(all(vals))
if op == "NOR":
return 1 - int(any(vals))
if op == "XOR":
return sum(vals) & 1
if op == "XNOR":
return 1 - (sum(vals) & 1)
if op == "NOT":
return 1 - vals[0]
if op == "BUF":
return vals[0]
raise ValueError(f"unknown gate {op}")
def not3(v: int) -> int:
return X if v == X else 1 - v
def eval3(op: str, vals: Sequence[int]) -> int:
"""Kleene's strong three-valued gate function on values in {0, 1, X}."""
if op in ("AND", "NAND"):
r = 0 if 0 in vals else (X if X in vals else 1)
return r if op == "AND" else not3(r)
if op in ("OR", "NOR"):
r = 1 if 1 in vals else (X if X in vals else 0)
return r if op == "OR" else not3(r)
if op in ("XOR", "XNOR"):
r = X if X in vals else sum(vals) & 1
return r if op == "XOR" else not3(r)
if op == "NOT":
return not3(vals[0])
if op == "BUF":
return vals[0]
raise ValueError(f"unknown gate {op}")
class Circuit:
"""A gate netlist. gates is a list of (output net, op, list of input nets)."""
def __init__(self, inputs: Sequence[str], gates: Sequence[Tuple[str, str, Sequence[str]]], outputs: Sequence[str]):
self.inputs: List[str] = list(inputs)
self.gates: List[Tuple[str, str, List[str]]] = [(out, op, list(ins)) for out, op, ins in gates]
self.outputs: List[str] = list(outputs)
self.driver: Dict[str, int] = {}
for i, (out, op, ins) in enumerate(self.gates):
if op not in OPS:
raise ValueError(f"unknown gate {op}")
if not ins or (op in ONE_INPUT and len(ins) != 1):
raise ValueError(f"gate {out} has a wrong number of inputs")
if out in self.driver or out in self.inputs:
raise ValueError(f"net {out} has two drivers")
self.driver[out] = i
self.nets: List[str] = self.inputs + [g[0] for g in self.gates]
self.fanout: Dict[str, List[int]] = {n: [] for n in self.nets}
for i, (out, op, ins) in enumerate(self.gates):
for n in ins:
if n not in self.fanout:
raise ValueError(f"net {n} has no driver")
if i not in self.fanout[n]:
self.fanout[n].append(i)
for n in self.outputs:
if n not in self.fanout:
raise ValueError(f"output {n} has no driver")
def is_acyclic(self) -> bool:
"""True when no gate depends on its own output (three-colour depth-first search)."""
colour = [0] * len(self.gates)
for root in range(len(self.gates)):
if colour[root]:
continue
colour[root] = 1
stack = [(root, iter(self.gates[root][2]))]
while stack:
g, it = stack[-1]
nxt = None
for n in it:
if n in self.driver:
nxt = self.driver[n]
break
if nxt is None:
colour[g] = 2
stack.pop()
elif colour[nxt] == 1:
return False
elif colour[nxt] == 0:
colour[nxt] = 1
stack.append((nxt, iter(self.gates[nxt][2])))
return True
def direct_eval(self, vec: Dict[str, int], three: bool = False) -> Dict[str, int]:
"""Value of every net, each computed from its definition with memoization."""
f = eval3 if three else eval2
val: Dict[str, int] = {n: vec[n] for n in self.inputs}
busy = set()
def get(n: str) -> int:
if n in val:
return val[n]
if n in busy:
raise ValueError("the circuit has a loop")
busy.add(n)
out, op, ins = self.gates[self.driver[n]]
val[n] = f(op, [get(m) for m in ins])
return val[n]
for n in self.nets:
get(n)
return val
def random_circuit(rng: random.Random, n_inputs: int, n_gates: int, n_outputs: Optional[int] = None,
loops: bool = False, ops: Sequence[str] = OPS) -> Circuit:
"""A random circuit. Without loops, gate k reads only inputs and gates 0..k-1."""
inputs = [f"i{k}" for k in range(n_inputs)]
names = [f"g{k}" for k in range(n_gates)]
gates = []
for k in range(n_gates):
op = rng.choice(ops)
pool = inputs + (names if loops else names[:k])
arity = 1 if op in ONE_INPUT else rng.randint(2, 3)
ins = rng.sample(pool, min(arity, len(pool)))
if op not in ONE_INPUT and len(ins) < 2:
op = "BUF"
gates.append((names[k], op, ins))
if n_outputs is None:
n_outputs = min(3, n_gates)
return Circuit(inputs, gates, names[n_gates - n_outputs:])
def all_vectors(names: Sequence[str]) -> Iterator[Dict[str, int]]:
"""Every assignment of 0 and 1 to the names."""
for bits in itertools.product((0, 1), repeat=len(names)):
yield dict(zip(names, bits))
def completions(vec: Dict[str, int]) -> Iterator[Dict[str, int]]:
"""Every binary vector that agrees with vec wherever vec is not X."""
free = [n for n, v in vec.items() if v == X]
for bits in itertools.product((0, 1), repeat=len(free)):
out = dict(vec)
out.update(zip(free, bits))
yield out
test_compiled_code_logic_simulation.py 72 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/compiled-code-logic-simulation/. The authors are listed in prov/6EDHZJ.jsonl.
import random
import pytest
from compiled_code_logic_simulation import CombinationalLoop, compile_circuit, levelize, simulate
from logicnet import Circuit, all_vectors, random_circuit
# The page example: y = ab + a'c.
HAZARD = Circuit(
["a", "b", "c"],
[("y", "OR", ["p", "q"]), ("q", "AND", ["na", "c"]), ("p", "AND", ["a", "b"]), ("na", "NOT", ["a"])],
["y"],
)
def one_vector(c, vec):
full = c.direct_eval(vec)
return {o: full[o] for o in c.outputs}
@pytest.mark.parametrize("seed", range(10))
def test_bit_parallel_equals_one_vector_evaluation(seed):
rng = random.Random(seed)
c = random_circuit(rng, rng.randint(1, 10), rng.randint(1, 60), n_outputs=rng.randint(1, 4))
vectors = list(all_vectors(c.inputs))
rng.shuffle(vectors)
for width in (64, 7, 1):
got = simulate(c, vectors, width)
assert got == [one_vector(c, v) for v in vectors]
@pytest.mark.parametrize("seed", range(10))
def test_levels_respect_every_gate(seed):
rng = random.Random(50 + seed)
c = random_circuit(rng, rng.randint(1, 8), rng.randint(1, 80))
rng.shuffle(c.gates)
c = Circuit(c.inputs, c.gates, c.outputs)
order, level = levelize(c)
assert sorted(order) == list(range(len(c.gates)))
pos = {c.gates[g][0]: k for k, g in enumerate(order)}
for out, op, ins in c.gates:
assert level[out] == 1 + max(level[n] for n in ins)
assert all(n in c.inputs or pos[n] < pos[out] for n in ins)
for k in range(1, len(order)):
assert level[c.gates[order[k - 1]][0]] <= level[c.gates[order[k]][0]]
def test_one_statement_per_gate():
rng = random.Random(7)
c = random_circuit(rng, 5, 30)
src, _ = compile_circuit(c)
body = src.splitlines()[1:]
assert len(body) == len(c.inputs) + len(c.gates) + 1
assert not any(w in src for w in ("if ", "for ", "while "))
def test_loop_is_rejected():
latch = Circuit(["s", "r"], [("q", "NOR", ["r", "qn"]), ("qn", "NOR", ["s", "q"])], ["q"])
with pytest.raises(CombinationalLoop):
compile_circuit(latch)
def test_page_example():
src, run = compile_circuit(HAZARD, width=8)
assert src.splitlines()[4:8] == [" v5 = v0 & v1", " v6 = v0 ^ M", " v4 = v6 & v2", " v3 = v5 | v4"]
a, b, c = 0b11110000, 0b11001100, 0b10101010
assert run([a, b, c]) == [0b11001010]
vectors = [{"a": (a >> j) & 1, "b": (b >> j) & 1, "c": (c >> j) & 1} for j in range(8)]
assert simulate(HAZARD, vectors, 8) == [one_vector(HAZARD, v) for v in vectors]
History
Compiled simulation, in which a netlist is translated into a program, was used for zero-delay functional checking from the early days of logic simulation. In the 1980s IBM built it into both hardware and software. The Yorktown Simulation Engine (Pfister, 1982) was a parallel machine that ran a fixed compiled list of gate evaluations with no branches. HSS (Barzilai, Carter, Rosen and Rutledge, 1987) compiled the cycle-free parts of a design into machine instructions, simulated 16 or 32 patterns in one word, and injected faults by changing instructions. The same bit-parallel idea is the base of parallel-pattern fault simulation and of cycle-based simulators.
References
- Zeev Barzilai, J. Lawrence Carter, Barry K. Rosen and Joseph D. Rutledge, HSS, a high-speed simulator, IEEE Transactions on Computer-Aided Design 6(4), 601 to 617, 1987, the compilation of the cycle-free parts of the netlist to machine instructions and the simulation of many patterns in parallel in one word
- G. F. Pfister, The Yorktown Simulation Engine, introduction, Proceedings of the 19th Design Automation Conference, 51 to 54, 1982, a special-purpose machine that runs a fixed compiled program of gate evaluations with no branches
- Miron Abramovici, Melvin A. Breuer and Arthur D. Friedman, Digital Systems Testing and Testable Design, IEEE Press, 1994, the chapter Logic Simulation (compiled simulation, levelization and its limits)
- Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein, Introduction to Algorithms, 4th edition, MIT Press, 2022, Section 20.4, Topological sort
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 6EDHZJ Edit this page History Report an error Markdown