Algorithm Search⌘K

Algorithmadvanced

Symbolic trajectory evaluation

Also called STE, Seger-Bryant trajectory evaluation.

Seger and Bryant's model checking of bounded properties over a lattice of ternary states by symbolic simulation, used on large memories and datapaths.

Time
O(d P B^2) worst
Space
O(d P B^2) extra
Where
B = the number of nodes of the largest rail BDD of the run (at most 2^(v + 1), v the number of symbolic variables of the assertion); P = the number of gate inputs of the circuit; d = the largest time in the assertion
Properties
not completedeterministicnot exactiterative
Origin
Carl Johan H. Seger, Randal E. Bryant, 1995

Symbolic trajectory evaluation (STE) checks an assertion A⇒CA \Rightarrow C on a gate-level circuit. Here AA and CC are trajectory formulas, which say which nodes hold which values at which of the first few clock cycles, under guards over symbolic variables. The method runs ternary simulation with BDD values, so each node holds 0, 1 or X under each assignment of the variables. Nodes that AA does not mention stay X and cost nothing. One run of this simulation builds the defining trajectory of AA, the least information that every run satisfying AA must contain. Then a single comparison in the information order tests whether that trajectory already contains what CC asks for. If the comparison holds for all assignments, every binary run of the circuit that satisfies AA satisfies CC. The method checks bounded properties: the depth of the check is the largest time in the formulas. Assertion graphs for unbounded time are the subject of generalized STE.

In plain words

You want to prove: "if the inputs aa and bb hold xx and yy now, and cc holds zz in the next cycle, then two cycles from now the register r2r_2 holds (x∧y)⊕z(x \wedge y) \oplus z". Here xx, yy and zz are names for any bits.

STE simulates the circuit once. It puts xx, yy and zz where the assertion says, and X (unknown) on every other input and register. A node gets a formula only when its inputs force one, so a node that does not matter stays X. At the end, STE asks if r2r_2 holds the wanted formula at cycle 2. If yes, the property holds for all values of xx, yy, zz and of the X nodes. If no, the failing cases form a formula. X only hides information, so it can make a true property fail but never makes a false property pass.

The problem

The lattice. A node value is one of X, 0, 1 and ⊤\top, ordered by information: X ⊑\sqsubseteq 0, X ⊑\sqsubseteq 1, 0 ⊑⊤\sqsubseteq \top and 1 ⊑⊤\sqsubseteq \top, with 0 and 1 not comparable. X means "no information", and ⊤\top means "conflicting information", which no real run has. The join a⊔ba \sqcup b is the least upper bound, so 0⊔1=⊤0 \sqcup 1 = \top. A binary value bb is above aa exactly when aa is X or a=ba = b. This page puts X at the bottom. The ternary simulation page uses the order of definedness with 0 and 1 below X, so the two orders are opposite. The meaning is the same.

The circuit. A synchronous circuit has primary inputs, latches with a next-state node next(s)\mathrm{next}(s), and gates in topological order. In the binary model a run gives every node uu a value ρt(u)∈{0,1}\rho_t(u) \in \{0, 1\} at each time t≥0t \ge 0. The inputs and the initial latch values are free. Each gate has the value of its function on its fanins at the same time, and ρt+1(s)=ρt(next(s))\rho_{t+1}(s) = \rho_t(\mathrm{next}(s)). Seger and Bryant allow any monotone next-state function on the lattice of states. This page uses the zero-delay gate model, which is one instance.

Ternary gates. Each gate operator op\mathrm{op} is extended to op^\widehat{\mathrm{op}} on the lattice. On X, 0 and 1 the result is binary when all ways of replacing the X arguments by 0 or 1 give the same binary result, and X otherwise. So AND^(0,X)=0\widehat{\mathrm{AND}}(0, \mathrm{X}) = 0 and AND^(1,X)=X\widehat{\mathrm{AND}}(1, \mathrm{X}) = \mathrm{X}. The extension agrees with op\mathrm{op} on binary arguments and is monotone: ai⊑bia_i \sqsubseteq b_i for all ii gives op^(a)⊑op^(b)\widehat{\mathrm{op}}(a) \sqsubseteq \widehat{\mathrm{op}}(b).

Trajectory formulas. Let VV be a set of symbolic variables and ϕ\phi an assignment of them. The formulas here are conjunctions of constraints (t,u,e,g)(t, u, e, g), read "if gg then node uu is ee at time tt", where ee and gg are Boolean expressions over VV. In Seger and Bryant's syntax this is Nt(g→(u is e))\mathbf{N}^t (g \rightarrow (u \text{ is } e)), built from the atoms "uu is 0" and "uu is 1", conjunction, a Boolean guard →\rightarrow and the next-time operator N\mathbf{N}. A run ρ\rho satisfies a formula FF at ϕ\phi when every constraint with g(ϕ)=1g(\phi) = 1 has ρt(u)=e(ϕ)\rho_t(u) = e(\phi). The assertion A⇒CA \Rightarrow C holds when, for every ϕ\phi, every run that satisfies AA at ϕ\phi satisfies CC at ϕ\phi.

Defining sequence and trajectory. The defining sequence δF\delta_F of a formula gives each node at each time the least lattice value that the formula asks for: the join, over the constraints on (t,u)(t, u) whose guard holds, of the value of ee. A run satisfies FF at ϕ\phi exactly when δF(ϕ)⊑ρ\delta_F(\phi) \sqsubseteq \rho at every node and time. The defining trajectory τA\tau_A is the least sequence above δA\delta_A that is closed under the circuit: each gate holds at least op^\widehat{\mathrm{op}} of its fanins, and each latch at time t+1t + 1 holds at least the value of its next-state node at time tt. The task is to compute, as a BDD, the set of assignments ϕ\phi where δC(ϕ)⊑τA(ϕ)\delta_C(\phi) \sqsubseteq \tau_A(\phi) fails.

The algorithm

Each lattice value under all assignments is a pair of BDDs (one, zero): at ϕ\phi the value is X when neither holds, 1 when only one holds, 0 when only zero holds, and ⊤\top when both hold. The join is the OR of the rails, and a⊑ba \sqsubseteq b is (a1→b1)∧(a0→b0)(a_1 \rightarrow b_1) \wedge (a_0 \rightarrow b_0). A constraint (t,u,e,g)(t, u, e, g) adds (g∧e, g∧¬e)(g \wedge e,\ g \wedge \neg e) to δ(t,u)\delta(t, u).

  1. STE(C, A, Cons)
  2. 1d ← the largest time in A and Cons
  3. 2for t ← 0 to d do
  4. 3for each node u do τ_t(u) ← δ_A,t(u)
  5. 4if t > 0 then for each latch s do τ_t(s) ← τ_t(s) ⊔ τ_(t−1)(next(s))
  6. 5for each gate u in topological order do τ_t(u) ← τ_t(u) ⊔ op̂(u)(τ_t of the fanins of u)
  7. 6AF ← the OR over all t and u of [τ_t(u) = ⊤]
  8. 7OK ← the AND over all t and u of [δ_Cons,t(u) ⊑ τ_t(u)]
  9. 8return the residual ¬(OK ∨ AF), and AF

Lines L2 to L5 are one pass of ternary symbolic simulation. Line L3 puts in the antecedent. Line L4 is the clock edge. Line L5 evaluates each gate on dual rails: for AND, the one-rail is the AND of the one-rails of the fanins and the zero-rail is the OR of their zero-rails, and NOT swaps the rails. The join at L5 keeps a value that the antecedent puts on an internal node. Line L6 collects the assignments where the antecedent contradicts itself or the circuit. At those ϕ\phi no run satisfies AA, so the assertion holds there without content. This is an antecedent failure, and a tool reports it, since it often means a wrong antecedent. Line L7 is the one-step check. The assertion holds where the residual is 0, and any assignment in the residual is a counterexample to inspect.

Example

The circuit has inputs aa, bb, cc, latches r1r_1 with next(r1)=g1=a∧b\mathrm{next}(r_1) = g_1 = a \wedge b and r2r_2 with next(r2)=g2=r1⊕c\mathrm{next}(r_2) = g_2 = r_1 \oplus c, and an unrelated latch qq with next(q)=¬q\mathrm{next}(q) = \neg q. The assertion is

AA: aa is xx at time 0, bb is yy at time 0, cc is zz at time 1, and CC: r2r_2 is (x∧y)⊕z(x \wedge y) \oplus z at time 2.

The defining trajectory, with each node shown by its value as a function of xx, yy, zz:

time aa bb cc r1r_1 r2r_2 qq g1g_1 g2g_2
0 xx yy X X X X x∧yx \wedge y X
1 X X zz x∧yx \wedge y X X X (x∧y)⊕z(x \wedge y) \oplus z
2 X X X X (x∧y)⊕z(x \wedge y) \oplus z X X X

At time 0, g2=XOR^(X,X)=Xg_2 = \widehat{\mathrm{XOR}}(\mathrm{X}, \mathrm{X}) = \mathrm{X}, and g1g_1 is binary under every ϕ\phi. At time 1, r1r_1 takes g1g_1 from time 0 at line L4. At time 2 the consequent asks r2r_2 for (x∧y)⊕z(x \wedge y) \oplus z, and τ2(r2)\tau_2(r_2) is that value, so OK is the constant 1. No node is ⊤\top, so AF is 0, and the residual is 0. The assertion holds.

The run used three variables. Symbolic simulation of the same three cycles needs a variable for each input in each cycle and for each latch, which is 12 variables, and qq would carry them through every cycle. Here qq stays X.

Now replace g2g_2 by r1∨cr_1 \vee c. Then τ2(r2)=(x∧y)∨z\tau_2(r_2) = (x \wedge y) \vee z. The two values differ exactly when x∧yx \wedge y and zz are both 1, where the circuit gives 1 and CC asks for 0. So τ2(r2)\tau_2(r_2) has one-rail 1 and δC\delta_C has zero-rail 1 there, and the residual is x∧y∧zx \wedge y \wedge z. The counterexample is x=y=z=1x = y = z = 1. The tests build both runs and compare them with all binary runs of the circuit.

Correctness

Claim (soundness). For every assignment ϕ\phi where the residual is 0 and every binary run ρ\rho that satisfies AA at ϕ\phi, ρ\rho satisfies CC at ϕ\phi. Where AF holds, no run satisfies AA.

The proof rests on one lemma: if ρ\rho satisfies AA at ϕ\phi, then τt(u)(ϕ)⊑ρt(u)\tau_t(u)(\phi) \sqsubseteq \rho_t(u) at every node and time. It goes by induction on tt and, inside a time, on the order inputs, latches, gates. Each line that writes τt(u)\tau_t(u) joins values that are all below ρt(u)\rho_t(u). The antecedent part is below because ρ\rho satisfies AA. The latch part is below by induction at time t−1t - 1, because ρt(s)=ρt−1(next(s))\rho_t(s) = \rho_{t-1}(\mathrm{next}(s)). The gate part is below because op^\widehat{\mathrm{op}} is monotone and agrees with op\mathrm{op} on binary values: op^(τ of the fanins)⊑op^(ρ of the fanins)=ρt(u)\widehat{\mathrm{op}}(\tau \text{ of the fanins}) \sqsubseteq \widehat{\mathrm{op}}(\rho \text{ of the fanins}) = \rho_t(u). A join of values below a binary value is below it, since the join is the least upper bound. Monotonicity is the reason X is safe. Replacing a binary argument by X can only move the result down, to X, and never to the other binary value.

With the lemma, take ϕ\phi where OK holds. Then δC(ϕ)⊑τ(ϕ)⊑ρ\delta_C(\phi) \sqsubseteq \tau(\phi) \sqsubseteq \rho, so ρ\rho satisfies CC. If AF holds at ϕ\phi, some τt(u)(ϕ)=⊤\tau_t(u)(\phi) = \top, and no binary value lies above ⊤\top, so no run satisfies AA at ϕ\phi. A residual of 0 means that one of the two cases holds at each ϕ\phi. The full proof, with the dual-rail encoding, is in the correctness proof.

The converse fails for binary runs. Seger and Bryant prove that the check is exact for the ternary model: the assertion holds in every trajectory of the ternary circuit exactly when δC⊑τA\delta_C \sqsubseteq \tau_A. But a ternary trajectory need not be the image of a binary run. With z=a∨¬az = a \vee \neg a and aa left at X, τ(z)=X\tau(z) = \mathrm{X}, so the check "zz is 1" fails, though zz is 1 in every binary run. When the antecedent fixes every input and every initial latch value to an expression, the trajectory is binary at each ϕ\phi, and the check is then exact for binary runs too.

Proof: The one-step lattice check of STE is sound for binary runsfull

Setting. The lattice is L={X,0,1,⊤}L = \{\mathrm{X}, 0, 1, \top\} with X⊑0⊑⊤\mathrm{X} \sqsubseteq 0 \sqsubseteq \top and X⊑1⊑⊤\mathrm{X} \sqsubseteq 1 \sqsubseteq \top. The circuit has inputs, latches ss with next-state nodes next(s)\mathrm{next}(s), and gates uu with operators op(u)\mathrm{op}(u) in topological order. A binary run ρ\rho gives each node uu and time tt a value ρt(u)∈{0,1}\rho_t(u) \in \{0, 1\}, with ρt(u)=op(u)(ρt of the fanins)\rho_t(u) = \mathrm{op}(u)(\rho_t \text{ of the fanins}) for each gate and ρt+1(s)=ρt(next(s))\rho_{t+1}(s) = \rho_t(\mathrm{next}(s)) for each latch. Inputs and initial latch values are free. An assignment ϕ\phi gives 0 or 1 to each symbolic variable. A constraint (t,u,e,g)(t, u, e, g) holds in ρ\rho at ϕ\phi when g(ϕ)=0g(\phi) = 0 or ρt(u)=e(ϕ)\rho_t(u) = e(\phi). A formula is a finite set of constraints, and ρ\rho satisfies it at ϕ\phi when all its constraints hold.

Encoding. A value under all assignments is a pair of BDDs (a1,a0)(a_1, a_0). At ϕ\phi it denotes X if a1(ϕ)=a0(ϕ)=0a_1(\phi) = a_0(\phi) = 0, 1 if only a1(ϕ)=1a_1(\phi) = 1, 0 if only a0(ϕ)=1a_0(\phi) = 1, and ⊤\top if both are 1. In this encoding, a⊑ba \sqsubseteq b at ϕ\phi is (a1→b1)∧(a0→b0)(a_1 \rightarrow b_1) \wedge (a_0 \rightarrow b_0) at ϕ\phi, and the join is (a1∨b1,a0∨b0)(a_1 \vee b_1, a_0 \vee b_0). Both are checked on the 16 pairs of LL. The value of δF(t,u)\delta_F(t, u) is the join over the constraints (t,u,e,g)(t, u, e, g) of FF of (g∧e,g∧¬e)(g \wedge e, g \wedge \neg e). All statements below are about one fixed ϕ\phi, and we write τt(u)\tau_t(u) for the lattice value that the pair denotes at ϕ\phi.

Claim. Let R=¬(OK∨AF)R = \neg(\mathrm{OK} \vee \mathrm{AF}) be the residual of line L8. For every ϕ\phi with R(ϕ)=0R(\phi) = 0 and every run ρ\rho that satisfies AA at ϕ\phi, ρ\rho satisfies CC at ϕ\phi. Moreover, if AF(ϕ)=1\mathrm{AF}(\phi) = 1, no run satisfies AA at ϕ\phi.

Fact 1 (satisfaction is being above). For a binary value bb and a∈La \in L, a⊑ba \sqsubseteq b exactly when a=Xa = \mathrm{X} or a=ba = b. A constraint (t,u,e,g)(t, u, e, g) contributes X when g(ϕ)=0g(\phi) = 0 and the binary value e(ϕ)e(\phi) when g(ϕ)=1g(\phi) = 1. So ρ\rho satisfies FF at ϕ\phi exactly when each contribution is below ρt(u)\rho_t(u). A set of values is below ρt(u)\rho_t(u) exactly when its join is, because the join is the least upper bound. Hence ρ\rho satisfies FF at ϕ\phi if and only if δF(ϕ)(t,u)⊑ρt(u)\delta_F(\phi)(t, u) \sqsubseteq \rho_t(u) for all tt and uu.

Fact 2 (monotone gates). The dual-rail gate of line L5 is monotone and agrees with op\mathrm{op} on binary arguments. For NOT the rails swap, which keeps ⊑\sqsubseteq. For AND the one-rail is ⋀iai,1\bigwedge_i a_{i,1} and the zero-rail is ⋁iai,0\bigvee_i a_{i,0}. Both are positive in the rails, so raising any rail of an argument from 0 to 1 can only raise the rails of the result, and ⊑\sqsubseteq is the rail-wise order. OR is the dual. For XOR the rails are built by the recurrence o′=oa0∨za1o' = o a_0 \vee z a_1, z′=oa1∨za0z' = o a_1 \vee z a_0 from (o,z)=(0,1)(o, z) = (0, 1), which is again positive in all rails. NAND, NOR and XNOR swap the rails at the end. On binary arguments the rails of each argument are (b,¬b)(b, \neg b), and each formula then gives (op(b),¬op(b))(\mathrm{op}(b), \neg\mathrm{op}(b)). The tests check monotonicity on all argument tuples of LL. On arguments in {X,0,1}\{\mathrm{X}, 0, 1\} they also check that the result is the exact ternary extension: binary exactly when all completions of the X arguments agree.

Lemma (the defining trajectory is below every run). If ρ\rho satisfies AA at ϕ\phi, then τt(u)⊑ρt(u)\tau_t(u) \sqsubseteq \rho_t(u) for every t≤dt \le d and every node uu.

Proof. By induction on tt, and inside a time on the order of lines L3, L4, L5: inputs, then latches, then gates in topological order. Each line that writes τt(u)\tau_t(u) sets it to a join. It is enough to show that each joined term is below ρt(u)\rho_t(u), since the join of values below a binary value bb is below bb.

  • Line L3: the term is δA(ϕ)(t,u)\delta_A(\phi)(t, u), which is below ρt(u)\rho_t(u) by Fact 1, since ρ\rho satisfies AA. For inputs and for latches at time 0 this is the only term.
  • Line L4, t>0t > 0: the new term is τt−1(next(s))\tau_{t-1}(\mathrm{next}(s)). By induction at time t−1t - 1 it is below ρt−1(next(s))=ρt(s)\rho_{t-1}(\mathrm{next}(s)) = \rho_t(s).
  • Line L5: the new term is op^(u)\widehat{\mathrm{op}}(u) of the fanin values τt(f)\tau_t(f). Each fanin is an input, a latch or an earlier gate, so its value is final and τt(f)⊑ρt(f)\tau_t(f) \sqsubseteq \rho_t(f) by induction. By Fact 2, op^(u)(τt(f)f)⊑op^(u)(ρt(f)f)=op(u)(ρt(f)f)=ρt(u)\widehat{\mathrm{op}}(u)(\tau_t(f)_f) \sqsubseteq \widehat{\mathrm{op}}(u)(\rho_t(f)_f) = \mathrm{op}(u)(\rho_t(f)_f) = \rho_t(u).

No later line changes τt(u)\tau_t(u). □\square

Proof of the claim. First let AF(ϕ)=1\mathrm{AF}(\phi) = 1. Line L6 gives some tt and uu with τt(u)=⊤\tau_t(u) = \top. If a run ρ\rho satisfied AA at ϕ\phi, the Lemma would give ⊤⊑ρt(u)\top \sqsubseteq \rho_t(u), but no binary value is above ⊤\top. So no run satisfies AA at ϕ\phi, and the assertion holds at ϕ\phi without content.

Now let R(ϕ)=0R(\phi) = 0 and AF(ϕ)=0\mathrm{AF}(\phi) = 0, so OK(ϕ)=1\mathrm{OK}(\phi) = 1. Line L7 gives δC(ϕ)(t,u)⊑τt(u)\delta_C(\phi)(t, u) \sqsubseteq \tau_t(u) for all t≤dt \le d and uu, where dd bounds the times of CC by line L1. Let ρ\rho satisfy AA at ϕ\phi. By the Lemma and transitivity, δC(ϕ)(t,u)⊑ρt(u)\delta_C(\phi)(t, u) \sqsubseteq \rho_t(u) for all tt and uu, and by Fact 1 ρ\rho satisfies CC at ϕ\phi. If R(ϕ)=0R(\phi) = 0 and AF(ϕ)=1\mathrm{AF}(\phi) = 1, the first case applies. ■\blacksquare

What is not claimed. The check is not complete for binary runs. With z=a∨¬az = a \vee \neg a and no constraint on aa, line L5 gives τ0(z)=OR^(X,X)=X\tau_0(z) = \widehat{\mathrm{OR}}(\mathrm{X}, \mathrm{X}) = \mathrm{X}, so the consequent "zz is 1" fails although every run has z=1z = 1. Seger and Bryant (1995) prove that the check is exact for the ternary circuit model: it passes exactly when every ternary trajectory above δA\delta_A is above δC\delta_C. This page relies on that result only for the remark and does not prove it. One case of completeness for binary runs follows from the Lemma. If AA sets every input at every time t≤dt \le d and every latch at time 0 to an expression with guard 1, then at ϕ\phi there is exactly one run ρ\rho that satisfies AA. Each τt(u)\tau_t(u) is then binary or ⊤\top. When it is binary it equals ρt(u)\rho_t(u), by the Lemma and induction. So OK is false at ϕ\phi exactly when ρ\rho breaks CC. The tests check this case against all runs.

Complexity

The model is the word RAM with hashing in expected constant time. Let dd be the largest time, PP the number of gate inputs, vv the number of symbolic variables and BB the largest rail BDD.

  • Lines L3 and L4 cost one OR of rails per node and latch per time, and line L5 costs O(1)O(1) BDD operations per gate input. Each operation costs O(B2)O(B^2) by Apply. Over d+1d + 1 times this is O(dPB2)O(d P B^2).
  • Lines L6 and L7 cost O(1)O(1) operations per node and time, which stays within the same bound.
  • The BDDs are over vv variables, so B≤2v+1−1B \le 2^{v + 1} - 1. The variables come from the assertion only, not from the circuit.

The last point is the gain. A circuit with a million latches costs a million X values, not a million variables. For a memory, an antecedent that writes one symbolic word to one address and reads it back leaves all other cells at X. The exponent cannot be removed in general: with AA empty except for the inputs set to variables, and CC asking one output to be 1, the residual is 0 exactly when the output function is a tautology, which is coNP-hard to decide.

Properties

  • Sound for binary runs: a passing check proves the assertion for all binary runs and all values of the variables. A failing check gives a set of assignments to inspect, which may be false failures caused by X.
  • Exact for the ternary model of the circuit (Seger and Bryant 1995).
  • Bounded: the check covers times 00 to dd, and every run of the circuit from any state, since the latches start at X unless AA sets them.
  • The cost depends on the variables in the assertion and the depth, not on the number of latches.
  • Deterministic. The result is the same BDD for every gate order that is topological.

Variants and improvements

  • Generalized STE. GSTE replaces the linear sequence of times by an assertion graph and computes a fixed point, so a property can talk about unbounded time.
  • Theorem proving on top. Hazelhurst and Seger (1995) give inference rules that join STE results, for example two assertions checked apart whose conjunction or sequential composition is then known to hold. This splits a check that is too large for one run.
  • Refinement by variables. When a check fails because of X, the user replaces the X on a node by a fresh variable, as in the a∨¬aa \vee \neg a case. This is a manual form of abstraction refinement. Too many fresh variables bring back the cost of symbolic simulation.
  • Abstract interpretation. The ternary lattice is an abstract domain for sets of binary values, with a Galois connection between sets of bits and lattice values. STE is a forward abstract run with one step per clock cycle.
  • Other value encodings. The dual-rail pair of BDDs can be replaced by a pair of SAT formulas, so the check becomes a SAT call. This is close to bounded model checking with an X abstraction of the unconstrained nodes.

When to use it

Use STE for properties of bounded length on large circuits where most of the state does not matter for the property: a read after a write in a memory array, one pass of a datapath pipeline, the result of one instruction from any state. It was built for these cases, and the X abstraction keeps the cost to the part of the circuit that the property reads. For properties over unbounded time use GSTE or a symbolic model checker. For small control circuits where much of the state matters, plain symbolic simulation or bounded model checking has no false failures to deal with.

Pitfalls

  • False failures from X. A node that the property needs but that the antecedent leaves at X gives a failing check with no real bug, as in z=a∨¬az = a \vee \neg a. Before you report a bug, replay the counterexample in a binary simulator with values for the X nodes. If the failure goes away, add a variable to the antecedent.
  • Vacuous passes. Where AF holds, the assertion passes because no run satisfies AA. An antecedent with "aa is 1" and "aa is 0" at the same time passes every consequent. Check that AF is 0, or at least that it is the expected set.
  • The order of the lattice. Code that copies the convention of ternary simulation with 0 below X computes the join as a meet. Fix one order for the whole tool.
  • Values on internal nodes. An antecedent may set an internal node, and line L5 joins it with the gate output. If the circuit drives the other value, the result is ⊤\top and the assertion passes without content there. Use this on purpose only, for example to cut a part of the circuit, and look at AF.
  • Depth one too short. A latch takes its value at the next time. A consequent at time 1 on a register that is written from a value at time 1 sees only X.

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.

bdd.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the hv2 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A small reduced ordered BDD package with a unique table and an ITE cache.

A node is an integer. The terminals are 0 (false) and 1 (true). A variable is a
non-negative integer, and a smaller integer is nearer the root. Every inner node
is a triple (var, lo, hi) with lo != hi, and the unique table keeps one node per
triple, so two BDDs of the same manager are equal functions exactly when they
are the same integer.
"""

from __future__ import annotations

from typing import Iterable, Optional

FALSE = 0
TRUE = 1
_TERMINAL_VAR = 1 << 30


class BDD:
    """One manager. All BDDs that are combined must come from the same manager."""

    def __init__(self) -> None:
        self._var: list[int] = [_TERMINAL_VAR, _TERMINAL_VAR]
        self._lo: list[int] = [0, 1]
        self._hi: list[int] = [0, 1]
        self._unique: dict[tuple[int, int, int], int] = {}
        self._ite_cache: dict[tuple[int, int, int], int] = {}

    # -- construction -------------------------------------------------------
    def mk(self, v: int, lo: int, hi: int) -> int:
        """The node (v, lo, hi), reduced: equal children give the child."""
        if lo == hi:
            return lo
        key = (v, lo, hi)
        n = self._unique.get(key)
        if n is None:
            n = len(self._var)
            self._var.append(v)
            self._lo.append(lo)
            self._hi.append(hi)
            self._unique[key] = n
        return n

    def var(self, v: int) -> int:
        """The BDD of the single variable v."""
        return self.mk(v, FALSE, TRUE)

    def top(self, f: int) -> int:
        return self._var[f]

    def low(self, f: int) -> int:
        return self._lo[f]

    def high(self, f: int) -> int:
        return self._hi[f]

    def _cof(self, f: int, v: int, b: int) -> int:
        if self._var[f] != v:
            return f
        return self._hi[f] if b else self._lo[f]

    def ite(self, f: int, g: int, h: int) -> int:
        """If f then g else h, by Shannon expansion on the top variable."""
        if f == TRUE:
            return g
        if f == FALSE:
            return h
        if g == h:
            return g
        if g == TRUE and h == FALSE:
            return f
        key = (f, g, h)
        r = self._ite_cache.get(key)
        if r is not None:
            return r
        v = min(self._var[f], self._var[g], self._var[h])
        lo = self.ite(self._cof(f, v, 0), self._cof(g, v, 0), self._cof(h, v, 0))
        hi = self.ite(self._cof(f, v, 1), self._cof(g, v, 1), self._cof(h, v, 1))
        r = self.mk(v, lo, hi)
        self._ite_cache[key] = r
        return r

    def neg(self, f: int) -> int:
        return self.ite(f, FALSE, TRUE)

    def conj(self, f: int, g: int) -> int:
        return self.ite(f, g, FALSE)

    def disj(self, f: int, g: int) -> int:
        return self.ite(f, TRUE, g)

    def xor(self, f: int, g: int) -> int:
        return self.ite(f, self.neg(g), g)

    def xnor(self, f: int, g: int) -> int:
        return self.ite(f, g, self.neg(g))

    def restrict(self, f: int, v: int, b: int) -> int:
        """f with the variable v set to the constant b."""
        memo: dict[int, int] = {}

        def go(n: int) -> int:
            if n <= 1 or self._var[n] > v:
                return n
            if n in memo:
                return memo[n]
            if self._var[n] == v:
                r = self._hi[n] if b else self._lo[n]
            else:
                r = self.mk(self._var[n], go(self._lo[n]), go(self._hi[n]))
            memo[n] = r
            return r

        return go(f)

    def exists(self, f: int, vs: Iterable[int]) -> int:
        """Existential quantification of the variables vs."""
        for v in sorted(set(vs), reverse=True):
            f = self.disj(self.restrict(f, v, 0), self.restrict(f, v, 1))
        return f

    # -- queries ------------------------------------------------------------
    def evaluate(self, f: int, assignment: dict[int, int]) -> int:
        """The value of f at a point; a missing variable counts as 0."""
        while f > 1:
            f = self._hi[f] if assignment.get(self._var[f], 0) else self._lo[f]
        return f

    def size(self, f: int) -> int:
        """The number of nodes of f, terminals included."""
        seen: set[int] = set()
        stack = [f]
        while stack:
            n = stack.pop()
            if n in seen:
                continue
            seen.add(n)
            if n > 1:
                stack.append(self._lo[n])
                stack.append(self._hi[n])
        return len(seen)

    def support(self, f: int) -> set[int]:
        out: set[int] = set()
        seen: set[int] = set()
        stack = [f]
        while stack:
            n = stack.pop()
            if n <= 1 or n in seen:
                continue
            seen.add(n)
            out.add(self._var[n])
            stack.append(self._lo[n])
            stack.append(self._hi[n])
        return out

    def sat_one(self, f: int) -> Optional[dict[int, int]]:
        """One point where f is 1 (variables not on the path are left out), or None."""
        if f == FALSE:
            return None
        out: dict[int, int] = {}
        while f > 1:
            if self._lo[f] != FALSE:
                out[self._var[f]] = 0
                f = self._lo[f]
            else:
                out[self._var[f]] = 1
                f = self._hi[f]
        return out
symbolic_trajectory_evaluation.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/symbolic-trajectory-evaluation/. The authors are listed in prov/NEAHJQ.jsonl.
"""Symbolic trajectory evaluation (Seger and Bryant 1995) on a gate-level circuit.

Values lie in the lattice X below 0 and 1, and 0 and 1 below TOP. A symbolic
value is a dual-rail pair (one, zero) of BDDs over the symbolic variables: for
an assignment phi of the variables the node is X when neither holds, 1 when only
one holds, 0 when only zero holds, and TOP when both hold. The join is the OR of
the rails, and a <= b is (a.one -> b.one) and (a.zero -> b.zero).

An assertion A ==> C is given by two lists of constraints (t, node, e, g), each
meaning "if g then node is e at time t", with e and g BDDs over the variables.
The check builds the defining trajectory of A by ternary simulation and tests
that the defining sequence of C lies below it, for each phi at once.

Precondition: gates in topological order, as in the Circuit of the page. Cost:
O(d P) dual-rail operations for depth d and P gate inputs, each a BDD operation
on BDDs over the variables of the assertion only.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional

from bdd import BDD, FALSE, TRUE

Val = tuple[int, int]          # (one, zero)
XV: Val = (FALSE, FALSE)


@dataclass(frozen=True)
class Circuit:
    """inputs; latches as (name, next_state_node); gates as (name, op, fanins) in topological order."""

    inputs: tuple[str, ...]
    latches: tuple[tuple[str, str], ...]
    gates: tuple[tuple[str, str, tuple[str, ...]], ...]


Constraint = tuple[int, str, int, int]   # (time, node, value BDD, guard BDD)


@dataclass
class Result:
    passed: bool
    residual: int                 # the assignments phi where the assertion fails
    antecedent_failure: int       # the assignments phi where the trajectory reaches TOP
    trajectory: list[dict[str, Val]]


def join(m: BDD, a: Val, b: Val) -> Val:
    return (m.disj(a[0], b[0]), m.disj(a[1], b[1]))


def leq(m: BDD, a: Val, b: Val) -> int:
    """The BDD of the assignments where a is below or equal to b."""
    return m.conj(m.disj(m.neg(a[0]), b[0]), m.disj(m.neg(a[1]), b[1]))


def gate_value(m: BDD, op: str, args: list[Val]) -> Val:
    """The monotone ternary extension of a gate on dual-rail values."""
    if op == "BUF":
        return args[0]
    if op == "NOT":
        return (args[0][1], args[0][0])
    if op in ("AND", "NAND", "OR", "NOR"):
        conj_like = op in ("AND", "NAND")
        one, zero = (TRUE, FALSE) if conj_like else (FALSE, TRUE)
        for a1, a0 in args:
            if conj_like:          # 1 when all are 1, 0 when some is 0
                one, zero = m.conj(one, a1), m.disj(zero, a0)
            else:                  # 1 when some is 1, 0 when all are 0
                one, zero = m.disj(one, a1), m.conj(zero, a0)
        return (zero, one) if op in ("NAND", "NOR") else (one, zero)
    if op in ("XOR", "XNOR"):
        one, zero = FALSE, TRUE
        for a1, a0 in args:
            one, zero = (m.disj(m.conj(one, a0), m.conj(zero, a1)),
                         m.disj(m.conj(one, a1), m.conj(zero, a0)))
        return (zero, one) if op == "XNOR" else (one, zero)
    raise ValueError(f"unknown gate type {op}")


def defining_sequence(m: BDD, cs: list[Constraint], depth: int) -> list[dict[str, Val]]:
    """delta: for each time, the least values that the constraints ask for."""
    seq: list[dict[str, Val]] = [dict() for _ in range(depth + 1)]
    for t, u, e, g in cs:
        v = (m.conj(g, e), m.conj(g, m.neg(e)))
        seq[t][u] = join(m, seq[t].get(u, XV), v)
    return seq


def ste(c: Circuit, m: BDD, antecedent: list[Constraint], consequent: list[Constraint]) -> Result:
    """Check the assertion antecedent ==> consequent on the circuit c."""
    depth = max([t for t, *_ in antecedent + consequent], default=0)       # @line L1
    da = defining_sequence(m, antecedent, depth)
    dc = defining_sequence(m, consequent, depth)
    traj: list[dict[str, Val]] = []
    for t in range(depth + 1):                                            # @line L2
        tau: dict[str, Val] = {}
        for u in list(c.inputs) + [s for s, _ in c.latches] + [g for g, _, _ in c.gates]:
            tau[u] = da[t].get(u, XV)                                     # @line L3
        if t > 0:
            for s, nxt in c.latches:                                      # @line L4
                tau[s] = join(m, tau[s], traj[t - 1][nxt])
        for g, op, fanins in c.gates:                                     # @line L5
            tau[g] = join(m, tau[g], gate_value(m, op, [tau[f] for f in fanins]))
        traj.append(tau)
    af = FALSE
    for tau in traj:                                                      # @line L6
        for one, zero in tau.values():
            af = m.disj(af, m.conj(one, zero))
    ok = TRUE
    for t in range(depth + 1):                                            # @line L7
        for u, v in dc[t].items():
            ok = m.conj(ok, leq(m, v, traj[t][u]))
    residual = m.neg(m.disj(ok, af))                                      # @line L8
    return Result(residual == FALSE, residual, af, traj)


def is_(t: int, node: str, e: int, guard: int = TRUE) -> Constraint:
    """The constraint "if guard then node is e at time t"."""
    return (t, node, e, guard)


def counterexample(m: BDD, r: Result) -> Optional[dict[int, int]]:
    """One assignment of the symbolic variables where the assertion fails."""
    return m.sat_one(r.residual)
test_symbolic_trajectory_evaluation.py 215 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/symbolic-trajectory-evaluation/. The authors are listed in prov/NEAHJQ.jsonl.

import itertools
import random

from bdd import FALSE, TRUE, BDD
from symbolic_trajectory_evaluation import Circuit, counterexample, gate_value, is_, leq, ste

OPS = ("BUF", "NOT", "AND", "OR", "NAND", "NOR", "XOR", "XNOR")
X, ZERO, ONE, TOP = (FALSE, FALSE), (FALSE, TRUE), (TRUE, FALSE), (TRUE, TRUE)
LATTICE = (X, ZERO, ONE, TOP)


def boolean(op, xs):
    if op == "BUF":
        return xs[0]
    if op == "NOT":
        return 1 - xs[0]
    if op in ("AND", "NAND"):
        return int(all(xs)) ^ (op == "NAND")
    if op in ("OR", "NOR"):
        return int(any(xs)) ^ (op == "NOR")
    return (sum(xs) % 2) ^ (op == "XNOR")


def below(a, b):
    return (not a[0] or b[0]) and (not a[1] or b[1])


def pipeline(second="XOR"):
    """The circuit of the page: r1 <- a AND b, r2 <- r1 op c, and an unrelated toggle q."""
    return Circuit(
        inputs=("a", "b", "c"),
        latches=(("r1", "g1"), ("r2", "g2"), ("q", "nq")),
        gates=(("g1", "AND", ("a", "b")), ("g2", second, ("r1", "c")), ("nq", "NOT", ("q",))),
    )


def page_assertion(m):
    x, y, z = m.var(0), m.var(1), m.var(2)
    a = [is_(0, "a", x), is_(0, "b", y), is_(1, "c", z)]
    c = [is_(2, "r2", m.xor(m.conj(x, y), z))]
    return a, c


def test_gate_tables_are_monotone_and_exact():
    m = BDD()
    for op in OPS:
        n = 1 if op in ("BUF", "NOT") else 2
        for args in itertools.product(LATTICE, repeat=n):
            out = gate_value(m, op, list(args))
            for bigger in itertools.product(LATTICE, repeat=n):
                if all(below(a, b) for a, b in zip(args, bigger)):
                    assert below(out, gate_value(m, op, list(bigger)))
            if TOP in args:
                continue
            # On 0, 1 and X the table is Kleene's: binary exactly when all completions agree.
            comps = [[0, 1] if a == X else [int(a == ONE)] for a in args]
            vals = {boolean(op, list(xs)) for xs in itertools.product(*comps)}
            want = X if len(vals) == 2 else (ONE if vals == {1} else ZERO)
            assert out == want


def test_page_example_passes():
    m = BDD()
    a, c = page_assertion(m)
    r = ste(pipeline(), m, a, c)
    assert r.passed and r.antecedent_failure == FALSE
    x, y, z = m.var(0), m.var(1), m.var(2)
    assert r.trajectory[1]["r1"] == (m.conj(x, y), m.neg(m.conj(x, y)))
    assert r.trajectory[2]["c"] == X and r.trajectory[2]["q"] == X
    want = m.xor(m.conj(x, y), z)
    assert r.trajectory[1]["g2"] == (want, m.neg(want))
    assert r.trajectory[2]["r2"] == (want, m.neg(want))
    assert r.trajectory[0]["r1"] == X and r.trajectory[1]["g1"] == X


def test_page_example_bug_is_found():
    m = BDD()
    a, c = page_assertion(m)
    r = ste(pipeline("OR"), m, a, c)
    assert not r.passed
    x, y, z = m.var(0), m.var(1), m.var(2)
    assert r.residual == m.conj(m.conj(x, y), z)
    assert counterexample(m, r) == {0: 1, 1: 1, 2: 1}


def test_x_is_too_weak_without_a_variable():
    # z = a OR NOT a is 1 in every run, but with a left at X the check fails.
    c = Circuit(("a",), (), (("na", "NOT", ("a",)), ("z", "OR", ("a", "na"))))
    m = BDD()
    assert not ste(c, m, [], [is_(0, "z", TRUE)]).passed
    assert ste(c, m, [is_(0, "a", m.var(0))], [is_(0, "z", TRUE)]).passed


def test_antecedent_failure_is_vacuous():
    c = Circuit(("a",), (), (("z", "BUF", ("a",)),))
    m = BDD()
    x, y = m.var(0), m.var(1)
    r = ste(c, m, [is_(0, "a", x), is_(0, "a", y)], [is_(0, "z", FALSE)])
    assert r.antecedent_failure == m.xor(x, y)
    assert r.residual == m.conj(x, y)


# ---------------------------------------------------------------- brute force

def runs(c, depth):
    """Every binary run of length depth + 1: all initial latch values and all inputs."""
    nl, ni = len(c.latches), len(c.inputs)
    for bits in itertools.product((0, 1), repeat=nl + ni * (depth + 1)):
        state = dict(zip([s for s, _ in c.latches], bits[:nl]))
        out = []
        for t in range(depth + 1):
            val = dict(state)
            val.update(zip(c.inputs, bits[nl + t * ni: nl + (t + 1) * ni]))
            for g, op, fi in c.gates:
                val[g] = boolean(op, [val[f] for f in fi])
            out.append(val)
            state = {s: val[n] for s, n in c.latches}
        yield out


def satisfies(m, cs, run, phi):
    return all(not m.evaluate(g, phi) or run[t][u] == m.evaluate(e, phi) for t, u, e, g in cs)


def random_expr(m, rng, nv):
    k = rng.randrange(5)
    if k == 0:
        return rng.choice((FALSE, TRUE))
    v = m.var(rng.randrange(nv))
    if k == 1:
        return v
    if k == 2:
        return m.neg(v)
    w = m.var(rng.randrange(nv))
    return m.xor(v, w) if k == 3 else m.conj(v, w)


def random_case(rng):
    ni, nl = rng.randint(1, 2), rng.randint(0, 2)
    inputs = tuple(f"i{j}" for j in range(ni))
    lat = [f"s{j}" for j in range(nl)]
    nodes = list(inputs) + lat
    gates = []
    for j in range(rng.randint(1, 5)):
        op = rng.choice(OPS)
        ar = 1 if op in ("BUF", "NOT") else 2
        gates.append((f"g{j}", op, tuple(rng.choice(nodes) for _ in range(ar))))
        nodes.append(f"g{j}")
    c = Circuit(inputs, tuple((s, rng.choice(nodes)) for s in lat), tuple(gates))
    depth = rng.randint(0, 2)
    while nl + ni * (depth + 1) > 8:
        depth -= 1
    return c, nodes, depth


def test_random_soundness_against_all_runs():
    rng = random.Random(5150)
    nv = 2
    checked = 0
    for _ in range(500):
        c, nodes, depth = random_case(rng)
        m = BDD()
        guard = lambda: TRUE if rng.random() < 0.6 else random_expr(m, rng, nv)  # noqa: E731
        ant = [is_(rng.randint(0, depth), rng.choice(nodes), random_expr(m, rng, nv), guard())
               for _ in range(rng.randint(0, 4))]
        con = [is_(rng.randint(0, depth), rng.choice(nodes), random_expr(m, rng, nv), guard())
               for _ in range(rng.randint(1, 2))]
        r = ste(c, m, ant, con)
        all_runs = list(runs(c, depth))
        for bits in itertools.product((0, 1), repeat=nv):
            phi = dict(enumerate(bits))
            good = [run for run in all_runs if satisfies(m, ant, run, phi)]
            if m.evaluate(r.antecedent_failure, phi):
                assert not good  # TOP means that no run meets the antecedent
            for run in good:
                # The key lemma: the defining trajectory lies below every run that meets A.
                for t, tau in enumerate(r.trajectory):
                    for u, (one, zero) in tau.items():
                        if m.evaluate(one, phi):
                            assert run[t][u] == 1
                        if m.evaluate(zero, phi):
                            assert run[t][u] == 0
                if not m.evaluate(r.residual, phi):
                    assert satisfies(m, con, run, phi)  # soundness
                checked += 1
    assert checked > 1000


def test_complete_when_antecedent_fixes_all_inputs_and_state():
    # With every input and initial latch value fixed, the trajectory is binary,
    # so a failure is a real counterexample.
    rng = random.Random(77)
    for _ in range(300):
        c, nodes, depth = random_case(rng)
        m = BDD()
        ant = [is_(0, s, random_expr(m, rng, 2)) for s, _ in c.latches]
        ant += [is_(t, i, random_expr(m, rng, 2)) for t in range(depth + 1) for i in c.inputs]
        con = [is_(rng.randint(0, depth), rng.choice(nodes), random_expr(m, rng, 2))]
        r = ste(c, m, ant, con)
        assert r.antecedent_failure == FALSE
        for bits in itertools.product((0, 1), repeat=2):
            phi = dict(enumerate(bits))
            good = [run for run in runs(c, depth) if satisfies(m, ant, run, phi)]
            assert len(good) == 1
            assert bool(m.evaluate(r.residual, phi)) == (not satisfies(m, con, good[0], phi))


def test_leq_on_constants():
    m = BDD()
    for a in LATTICE:
        for b in LATTICE:
            assert leq(m, a, b) == (TRUE if below(a, b) else FALSE)

History

Bryant (1991) showed that ternary simulation, with X for unknown values and a monotone circuit model, verifies circuits soundly, and he used it for switch-level designs. Seger and Bryant (1995) built symbolic trajectory evaluation on top of it. They defined the lattice of states, trajectory formulas with the next-time operator, and the defining sequence and trajectory, and they proved that the one-step check is exact for the ternary model. The method went into Seger's Voss system and then into Forte at Intel, where it was used on memory arrays and arithmetic datapaths. Hazelhurst and Seger (1995) added a small theorem prover to join STE runs. Yang and Seger extended the method to assertion graphs as generalized STE.

References

  1. C.-J. H. Seger and R. E. Bryant, Formal verification by symbolic evaluation of partially-ordered trajectories, Formal Methods in System Design 6(2), 147 to 189, 1995, the lattice of ternary states, the monotone excitation function, trajectory formulas, the defining sequence and the defining trajectory, and the theorem that an assertion holds exactly when the defining sequence of the consequent lies below the defining trajectory of the antecedent
  2. R. E. Bryant, A methodology for hardware verification based on logic simulation, Journal of the ACM 38(2), 299 to 328, 1991, ternary simulation with X as a sound abstraction of binary behavior, and the monotonicity of the ternary circuit model
  3. S. Hazelhurst and C.-J. H. Seger, A simple theorem prover based on symbolic trajectory evaluation and BDDs, IEEE Transactions on Computer-Aided Design 14(4), 413 to 422, 1995, inference rules that join STE results, such as conjunction and sequential composition of assertions
  4. R. E. Bryant, Graph-based algorithms for Boolean function manipulation, IEEE Transactions on Computers C-35(8), 677 to 691, 1986, the reduced ordered BDD and the cost O(|f| |g|) of Apply

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example