Algorithm Search⌘K

Algorithmcore

Worklist dataflow algorithm

Also called Kildall's algorithm, iterative dataflow algorithm.

Solves dataflow equations by keeping a worklist of nodes whose input changed and applying their transfer functions until nothing changes.

Time
O((n + m)(h + 1)) worst · averageΘ(n + m) best
Space
Θ(n) extra
Where
h = the height of the lattice; m = the number of edges; n = the number of blocks
Properties
deterministiciterative

The worklist dataflow algorithm solves the equations of a monotone dataflow framework. Every node of the graph gets the value ⊤\top, the start nodes get the boundary value ι\iota, and a queue holds the nodes whose output may still change. The algorithm takes a node from the queue, applies its transfer function, meets the result into the input of each successor, and puts back every successor whose input went down. When the queue is empty, the values are the maximal fixed-point solution (MFP), the greatest solution of the equations. It is safe, because MFP is below the meet-over-all-paths solution, and it equals that solution in a distributive dataflow framework where every node is reachable. With nn nodes, mm edges and a lattice of height hh, it applies at most n(h+1)n(h + 1) transfer functions and m(h+1)m(h + 1) meets. The same code solves reaching definitions, live variables, available expressions, very busy expressions and constant propagation; only the lattice, the functions and the direction change.

In plain words

Picture the blocks of a program, each with a note that says what is known there. At first every note holds the most hopeful claim, except at the place where the analysis starts, which gets the honest starting fact. Every block goes on a to-do list. Take a block off the list, work out what holds when control leaves it, and hand that to the blocks that come next. Each of them combines the new fact with its note. If its note gets weaker, it goes back on the list, because what it hands on may change too. A note can only get weaker, and only a few times, so the list runs empty. Then every note agrees with its neighbors, and the notes are the most precise answer that such local agreement allows.

The problem

The input is an instance of a monotone framework, in the meet convention used by Kildall, Kam and Ullman, and the dragon book:

  • a directed graph G=(V,E)G = (V, E) with nn nodes and mm edges, and a set SS of start nodes;
  • a meet semilattice (L,⊓)(L, \sqcap) with top element ⊤\top, where x⊑yx \sqsubseteq y means x⊓y=xx \sqcap y = x, and of finite height hh: no strictly descending chain has more than hh steps;
  • a boundary value ι∈L\iota \in L;
  • a monotone transfer function fv:L→Lf_v : L \to L for each node vv.

Let init(s)=ιinit(s) = \iota if s∈Ss \in S and init(s)=⊤init(s) = \top otherwise. The output is the greatest assignment ININ with

IN[s]=init(s)⊓⊓(v,s)∈Efv(IN[v])for every node s,IN[s] = init(s) \sqcap \mathop{\large\sqcap}_{(v, s) \in E} f_v(IN[v]) \quad \text{for every node } s,

the maximal fixed-point solution. For a forward problem, GG is the control flow graph, SS holds the entry block, and IN[s]IN[s] is the fact at the start of block ss. For a backward problem, GG is the reverse CFG, SS holds the blocks that end in ret, and IN[s]IN[s] is the fact at the end of block ss. The facts on the other side of each block are fs(IN[s])f_s(IN[s]).

problem graph start nodes meet ⊤\top ι\iota
reaching definitions CFG entry ∪\cup ∅\emptyset ∅\emptyset
live variables reverse CFG ret blocks ∪\cup ∅\emptyset ∅\emptyset
available expressions CFG entry ∩\cap all expressions ∅\emptyset
very busy expressions reverse CFG ret blocks ∩\cap all expressions ∅\emptyset
constant propagation CFG entry per variable, in a flat lattice no value yet, for every variable parameters not constant

May problems use union and must problems use intersection. In a must problem ⊤\top is the set of all items, so the boundary value ∅\emptyset is the bottom element and not ⊤\top.

The algorithm

ININ only goes down during the run, so line L8 can meet the new output into the old value instead of recomputing the meet over all predecessors. A flag per node records whether it is in the queue, so the test of line L11 costs O(1)O(1). The queue starts with every node, in reverse postorder from the start nodes (see depth-first orders), so on the acyclic parts of the graph a node usually runs after all its predecessors.

  1. WORKLIST(V, succ, S, ι, ⊤, ⊓, f)
  2. 1for each node v in V do IN[v] ← ⊤
  3. 2for each start node s in S do IN[s] ← ι
  4. 3W ← a queue that holds every node of V once, in reverse postorder
  5. 4while W is not empty do
  6. 5v ← remove the first node of W
  7. 6out ← f_v(IN[v])
  8. 7for each successor s of v do
  9. 8new ← IN[s] ⊓ out
  10. 9if new ≠ IN[s] then
  11. 10IN[s] ← new
  12. 11if s is not in W then append s to W
  13. return IN

A backward problem calls the same procedure with the predecessor lists as succsucc and the ret blocks as SS. Nothing else changes.

Example

The running example of dataflow analysis has the parameters n and x:

entry:
  i = 0
  s = 0
  jump head
head:
  t = i < n
  br t body done
body:
  a = x * 2
  u = i & 1
  br u odd next
odd:
  s = s + a
  jump next
next:
  i = i + 1
  jump head
done:
  ret s

Take live variables, a backward problem. The reverse CFG has done as its only start node, and the queue starts with its reverse postorder done, head, next, odd, body, entry. IN[v]IN[v] is the set live at the end of vv, and line L6 gives the set live at its start, which goes to the predecessors of vv in the CFG.

step node out (live at its start) IN changed at queue after the step
1 done s head head, next, odd, body, entry
2 head i, n, s entry, next next, odd, body, entry
3 next i, n, s body, odd odd, body, entry
4 odd a, i, n, s body body, entry
5 body i, n, s, x head entry, head
6 entry n none head
7 head i, n, s, x entry, next entry, next
8 entry n, x none next
9 next i, n, s, x body, odd body, odd
10 body i, n, s, x none odd
11 odd a, i, n, s, x none empty

The first pass misses x in most blocks, because x is read only in body and that read reaches head, next and odd only around the loop. Step 5 lowers IN[head]IN[\text{head}] when head has already left the queue, so head goes back in, and its new output then reaches entry and next again. The run applies 11 transfer functions, does 13 unions and changes an ININ value 11 times; no value changes more than 3 times. With n=6n = 6 blocks, m=7m = 7 edges and h=7h = 7 variables, the bounds are 48 transfer functions and 56 meets. On the same program, reaching definitions also takes 11 transfer functions and 13 meets, available expressions and very busy expressions take 6 and 7 (each block runs once), and constant propagation takes 14 and 17, with h=14h = 14.

Correctness

The full proof is in the proof file. Its steps:

  1. Values only go down. Line L8 gives new=IN[s]⊓out⊑IN[s]new = IN[s] \sqcap out \sqsubseteq IN[s], so every change at line L10 is a strict step down.
  2. Termination and counts. By step 1 each IN[s]IN[s] changes at most hh times. A node enters the queue once at line L3 and once more at most after each change, so it is removed at most h+1h + 1 times.
  3. Nothing safe is lost. For every assignment XX with X⊑F(X)X \sqsubseteq F(X), where FF is the right side of the equations, X⊑INX \sqsubseteq IN holds at all times. It holds after line L2, and line L10 keeps it because X[s]⊑fv(X[v])⊑fv(IN[v])X[s] \sqsubseteq f_v(X[v]) \sqsubseteq f_v(IN[v]) by monotonicity.
  4. The end is a fixed point. A node that is not in the queue has sent its current output to all its successors, and a change of its own value puts it back. So at the end IN[s]⊑fv(IN[v])IN[s] \sqsubseteq f_v(IN[v]) for every edge, and IN⊑F(IN)IN \sqsubseteq F(IN). Every node runs at least once, and every value at the end is the meet of init(s)init(s) and of outputs computed from higher values, so also F(IN)⊑INF(IN) \sqsubseteq IN.
  5. It is the MFP. By steps 3 and 4 the result is a fixed point above every fixed point. The order of the queue does not matter for the result.
  6. Safety and precision. Induction on path length gives MFP⊑MOP\mathrm{MFP} \sqsubseteq \mathrm{MOP} for every monotone framework. If every function is distributive and every node is reachable from SS, then MOP⊑F(MOP)\mathrm{MOP} \sqsubseteq F(\mathrm{MOP}), so step 3 gives MOP⊑MFP\mathrm{MOP} \sqsubseteq \mathrm{MFP} and the two are equal. Gen-kill functions x↦g∪(x−k)x \mapsto g \cup (x - k) are distributive over ∪\cup and over ∩\cap, so this covers the four bit-vector problems.
Proof: The worklist dataflow algorithm terminates and computes the maximal fixed pointfull

Setting. (L,⊓)(L, \sqcap) is a meet semilattice: ⊓\sqcap is idempotent, commutative and associative. x⊑yx \sqsubseteq y means x⊓y=xx \sqcap y = x; this is a partial order in which x⊓yx \sqcap y is the greatest lower bound of xx and yy, and ⊓\sqcap is monotone in each argument. ⊤\top is the identity of ⊓\sqcap, so x⊑⊤x \sqsubseteq \top for all xx. The height hh is finite: every chain x0⊐x1⊐⋯⊐xkx_0 \sqsupset x_1 \sqsupset \cdots \sqsupset x_k has k≤hk \le h. G=(V,E)G = (V, E) is a directed graph with nn nodes and mm edges, S⊆VS \subseteq V is the set of start nodes, ι∈L\iota \in L is the boundary value, and each fv:L→Lf_v : L \to L is monotone: x⊑yx \sqsubseteq y implies fv(x)⊑fv(y)f_v(x) \sqsubseteq f_v(y). Let init(s)=ιinit(s) = \iota for s∈Ss \in S and init(s)=⊤init(s) = \top otherwise. An assignment XX gives each node a value, and X⊑YX \sqsubseteq Y means X[v]⊑Y[v]X[v] \sqsubseteq Y[v] for all vv. Define

F(X)[s]=init(s)⊓⊓(v,s)∈Efv(X[v]),F(X)[s] = init(s) \sqcap \mathop{\large\sqcap}_{(v, s) \in E} f_v(X[v]),

where the empty meet is ⊤\top. The maximal fixed-point solution (MFP) is the greatest XX with X=F(X)X = F(X). FF is monotone, because each fvf_v and the meet are.

We use the lines L1 to L11 of the pseudocode. An iteration is one pass through lines L5 to L11. Line L3 puts every node into WW exactly once. We write c(s)c(s) for the number of times line L10 changes IN[s]IN[s], and C=∑sc(s)C = \sum_s c(s).

Lemma 1 (values go down). After line L2, IN[s]=init(s)IN[s] = init(s) for every ss. Every execution of lines L8 to L10 for an edge (v,s)(v, s) leaves IN[s]IN[s] equal to its old value met with outout, and if line L10 runs, the new value is strictly below the old one.

Proof. Line L1 sets every value to ⊤\top and line L2 sets the start nodes to ι\iota, which is initinit. Line L8 computes new=IN[s]⊓outnew = IN[s] \sqcap out. If new=IN[s]new = IN[s], nothing changes and IN[s]=IN[s]⊓outIN[s] = IN[s] \sqcap out already. Otherwise line L10 stores newnew, and new=IN[s]⊓out⊑IN[s]new = IN[s] \sqcap out \sqsubseteq IN[s] with new≠IN[s]new \ne IN[s]. □\square

Lemma 2 (the queue). WW never holds a node twice. A node is added to WW only at line L3 or at line L11, and line L11 adds ss only right after line L10 has changed IN[s]IN[s].

Proof. Line L3 adds each node once, and line L11 adds ss only if it is not in WW. The rest is read off the code. □\square

Theorem 1 (termination and counts). Each IN[s]IN[s] changes at most hh times. The loop of line L4 runs at most n+C≤n(h+1)n + C \le n(h + 1) times, so line L6 applies at most n(h+1)n(h + 1) transfer functions, and line L8 computes at most m(h+1)m(h + 1) meets. In particular the algorithm terminates.

Proof. By Lemma 1 the values taken by IN[s]IN[s] form a strictly descending chain init(s)⊐⋯init(s) \sqsupset \cdots with c(s)c(s) steps, so c(s)≤hc(s) \le h. By Lemma 2, ss is added to WW at most 1+c(s)1 + c(s) times, and each iteration removes one node at line L5, so ss is removed at most 1+c(s)≤h+11 + c(s) \le h + 1 times. Summing over the nodes, there are at most n+C≤n+nhn + C \le n + n h iterations, each with one transfer function at line L6. An iteration that removes vv runs line L8 once per outgoing edge of vv, so the number of meets is at most ∑v(1+c(v)) outdeg(v)≤(h+1)∑voutdeg(v)=(h+1)m\sum_v (1 + c(v))\, outdeg(v) \le (h + 1) \sum_v outdeg(v) = (h + 1) m. Each iteration is finite, and there are finitely many, so the run ends. □\square

Lemma 3 (no safe value is lost). Let XX be any assignment with X⊑F(X)X \sqsubseteq F(X). Then X⊑INX \sqsubseteq IN holds after line L2 and after every later step.

Proof. After line L2, X[s]⊑F(X)[s]⊑init(s)=IN[s]X[s] \sqsubseteq F(X)[s] \sqsubseteq init(s) = IN[s], because a meet is below each of its terms. Values change only at line L10, for an edge (v,s)(v, s), with new=IN[s]⊓outnew = IN[s] \sqcap out and out=fv(IN0[v])out = f_v(IN_0[v]), where IN0[v]IN_0[v] is the value of IN[v]IN[v] when line L6 ran in this iteration. By the claim at that time, X[v]⊑IN0[v]X[v] \sqsubseteq IN_0[v], so by monotonicity

X[s]⊑F(X)[s]⊑fv(X[v])⊑fv(IN0[v])=out.X[s] \sqsubseteq F(X)[s] \sqsubseteq f_v(X[v]) \sqsubseteq f_v(IN_0[v]) = out.

By the claim before the change, X[s]⊑IN[s]X[s] \sqsubseteq IN[s]. So X[s]X[s] is a lower bound of IN[s]IN[s] and outout, hence X[s]⊑newX[s] \sqsubseteq new. □\square

Lemma 4 (the end is below FF). Let RR be the value of ININ when the algorithm stops. Then R⊑F(R)R \sqsubseteq F(R).

Proof. We show that the following claim P holds before every iteration and after the last one: for every node u∉Wu \notin W and every edge (u,s)(u, s), IN[s]⊑fu(IN[u])IN[s] \sqsubseteq f_u(IN[u]).

Before the first iteration W=VW = V, so P holds trivially. Assume P before an iteration that removes vv, and look at the state after it.

  • The node vv. For each successor ss, after line L8 and line L10, IN[s]=IN[s]⊓out⊑outIN[s] = IN[s] \sqcap out \sqsubseteq out by Lemma 1, and later steps of this iteration only lower IN[s]IN[s]. If IN[v]IN[v] did not change in this iteration, then out=fv(IN[v])out = f_v(IN[v]), and P holds for vv. If IN[v]IN[v] changed, which happens only through a self-loop (v,v)(v, v), then line L11 added vv back, since line L5 had removed it, so v∈Wv \in W and P says nothing about vv.
  • Another node u∉Wu \notin W. Nodes leave WW only at line L5, so uu was not in WW before the iteration either, and P held for uu. If IN[u]IN[u] had changed in this iteration, line L11 would have put uu into WW, or uu would have been there already, so IN[u]IN[u] did not change. The values IN[s]IN[s] of the successors of uu can only have gone down by Lemma 1, so IN[s]⊑fu(IN[u])IN[s] \sqsubseteq f_u(IN[u]) still holds.

When the algorithm stops, WW is empty, so P gives R[s]⊑fu(R[u])R[s] \sqsubseteq f_u(R[u]) for every edge (u,s)(u, s). By Lemma 1, R[s]⊑init(s)R[s] \sqsubseteq init(s). So R[s]R[s] is a lower bound of all terms of F(R)[s]F(R)[s], and R[s]⊑F(R)[s]R[s] \sqsubseteq F(R)[s]. □\square

Lemma 5 (the end is above FF). F(R)⊑RF(R) \sqsubseteq R.

Proof. By Lemma 1 and induction over the run, R[s]=init(s)⊓o1⊓⋯⊓okR[s] = init(s) \sqcap o_1 \sqcap \cdots \sqcap o_k, where o1,…,oko_1, \ldots, o_k are all the values outout used at line L8 for edges into ss. Each ojo_j belongs to an edge (vj,s)(v_j, s) and equals fvj(IN0[vj])f_{v_j}(IN_0[v_j]) for a value IN0[vj]IN_0[v_j] that IN[vj]IN[v_j] had during the run. By Lemma 1, IN0[vj]⊒R[vj]IN_0[v_j] \sqsupseteq R[v_j], so oj⊒fvj(R[vj])o_j \sqsupseteq f_{v_j}(R[v_j]) by monotonicity. Every node is removed from WW at least once, because it is in WW after line L3 and the run stops only when WW is empty, so every edge (v,s)(v, s) is among the (vj,s)(v_j, s). Since the meet is monotone in each argument and idempotent,

R[s]⊒init(s)⊓⊓jfvj(R[vj])=init(s)⊓⊓(v,s)∈Efv(R[v])=F(R)[s].□R[s] \sqsupseteq init(s) \sqcap \mathop{\large\sqcap}_j f_{v_j}(R[v_j]) = init(s) \sqcap \mathop{\large\sqcap}_{(v, s) \in E} f_v(R[v]) = F(R)[s]. \qquad \square

Theorem 2 (correctness). RR is the maximal fixed-point solution. It is also the greatest assignment XX with X⊑F(X)X \sqsubseteq F(X). In particular the MFP exists, and the result does not depend on the order of the queue in line L3.

Proof. By Lemmas 4 and 5 and antisymmetry, R=F(R)R = F(R), so RR is a fixed point. If XX is any fixed point, or any assignment with X⊑F(X)X \sqsubseteq F(X), then Lemma 3 at the end of the run gives X⊑RX \sqsubseteq R. So RR is the greatest fixed point, and also the greatest such XX. Greatest elements are unique, so every order of the queue gives the same RR. □\square

Meet over all paths. A path π=v0,v1,…,vk\pi = v_0, v_1, \ldots, v_k in GG with v0∈Sv_0 \in S is a path to vkv_k; its function is fπ=fvk−1∘⋯∘fv0f_\pi = f_{v_{k-1}} \circ \cdots \circ f_{v_0}, the functions of the nodes before vkv_k, and the identity if k=0k = 0. Let PsP_s be the set of paths to ss. The meet-over-all-paths solution is MOP[s]=⊓π∈Psfπ(ι)\mathrm{MOP}[s] = \mathop{\large\sqcap}_{\pi \in P_s} f_\pi(\iota), which is ⊤\top if PsP_s is empty. PsP_s can be infinite, so we first show that this meet exists.

Lemma 6 (meets of arbitrary sets). Every nonempty set A⊆LA \subseteq L has a greatest lower bound ⊓A\mathop{\large\sqcap} A, and it is the meet of at most h+1h + 1 members of AA.

Proof. Pick a0∈Aa_0 \in A and set g0=a0g_0 = a_0. While some a∈Aa \in A has gi⊓a≠gig_i \sqcap a \ne g_i, pick such an ai+1a_{i+1} and set gi+1=gi⊓ai+1g_{i+1} = g_i \sqcap a_{i+1}, which is strictly below gig_i. The chain g0⊐g1⊐⋯g_0 \sqsupset g_1 \sqsupset \cdots has at most hh steps, so it stops at some gkg_k, k≤hk \le h, with gk⊑ag_k \sqsubseteq a for all a∈Aa \in A. Any lower bound bb of AA is below a0,…,aka_0, \ldots, a_k, hence below their meet gkg_k. So gkg_k is the greatest lower bound. □\square

Theorem 3 (MFP is below MOP). For every monotone framework and every node ss, R[s]⊑MOP[s]R[s] \sqsubseteq \mathrm{MOP}[s]. So every fact of the result holds along every path, and the result is safe whenever each fvf_v safely describes its node.

Proof. We show R[vk]⊑fπ(ι)R[v_k] \sqsubseteq f_\pi(\iota) for every path π=v0,…,vk\pi = v_0, \ldots, v_k with v0∈Sv_0 \in S, by induction on kk. If k=0k = 0, v0∈Sv_0 \in S and R[v0]=F(R)[v0]⊑init(v0)=ι=fπ(ι)R[v_0] = F(R)[v_0] \sqsubseteq init(v_0) = \iota = f_\pi(\iota). If k>0k > 0, let π′\pi' be π\pi without its last node, a path to vk−1v_{k-1}, so fπ=fvk−1∘fπ′f_\pi = f_{v_{k-1}} \circ f_{\pi'}. By Theorem 2, the induction hypothesis and monotonicity,

R[vk]=F(R)[vk]⊑fvk−1(R[vk−1])⊑fvk−1(fπ′(ι))=fπ(ι).R[v_k] = F(R)[v_k] \sqsubseteq f_{v_{k-1}}(R[v_{k-1}]) \sqsubseteq f_{v_{k-1}}(f_{\pi'}(\iota)) = f_\pi(\iota).

So R[s]R[s] is a lower bound of all fπ(ι)f_\pi(\iota) with π∈Ps\pi \in P_s, and R[s]⊑MOP[s]R[s] \sqsubseteq \mathrm{MOP}[s]; if PsP_s is empty this holds because MOP[s]=⊤\mathrm{MOP}[s] = \top. □\square

Theorem 4 (MFP equals MOP for distributive frameworks). Suppose every fvf_v is distributive, fv(x⊓y)=fv(x)⊓fv(y)f_v(x \sqcap y) = f_v(x) \sqcap f_v(y) for all x,yx, y, and every node is reachable from SS. Then R=MOPR = \mathrm{MOP}.

Proof. A distributive ff is monotone: if x⊑yx \sqsubseteq y, then x=x⊓yx = x \sqcap y, so f(x)=f(x)⊓f(y)⊑f(y)f(x) = f(x) \sqcap f(y) \sqsubseteq f(y). It also distributes over every nonempty set AA: by Lemma 6, ⊓A=a0⊓⋯⊓ak\mathop{\large\sqcap} A = a_0 \sqcap \cdots \sqcap a_k for some members, so f(⊓A)=f(a0)⊓⋯⊓f(ak)⊒⊓f(A)f(\mathop{\large\sqcap} A) = f(a_0) \sqcap \cdots \sqcap f(a_k) \sqsupseteq \mathop{\large\sqcap} f(A), and f(⊓A)⊑f(a)f(\mathop{\large\sqcap} A) \sqsubseteq f(a) for every a∈Aa \in A by monotonicity, so f(⊓A)=⊓f(A)f(\mathop{\large\sqcap} A) = \mathop{\large\sqcap} f(A).

Let M=MOPM = \mathrm{MOP}. We show M⊑F(M)M \sqsubseteq F(M). Fix a node ss. If s∈Ss \in S, the path of length zero gives the term ι\iota, so M[s]⊑ι=init(s)M[s] \sqsubseteq \iota = init(s); otherwise init(s)=⊤init(s) = \top. For an edge (v,s)(v, s), the set PvP_v is nonempty because vv is reachable, so

fv(M[v])=fv(⊓π∈Pvfπ(ι))=⊓π∈Pvfv(fπ(ι)).f_v(M[v]) = f_v\Big(\mathop{\large\sqcap}_{\pi \in P_v} f_\pi(\iota)\Big) = \mathop{\large\sqcap}_{\pi \in P_v} f_v(f_\pi(\iota)).

Each fv(fπ(ι))f_v(f_\pi(\iota)) is fπs(ι)f_{\pi s}(\iota) for the path π\pi followed by ss, which is in PsP_s, so it is above M[s]M[s]. Hence M[s]⊑fv(M[v])M[s] \sqsubseteq f_v(M[v]). So M[s]M[s] is below every term of F(M)[s]F(M)[s], and M⊑F(M)M \sqsubseteq F(M). Lemma 3, applied at the end of the run, gives M⊑RM \sqsubseteq R, and Theorem 3 gives R⊑MR \sqsubseteq M. □\square

Reachability is needed. If vv is not reachable, M[v]=⊤M[v] = \top, and fv(⊤)f_v(\top) can be below ⊤\top. In reaching definitions, an unreachable block with a self-loop and a definition dd has MOP=∅\mathrm{MOP} = \emptyset, but {d}\{d\} is in its MFP.

Lemma 7 (gen-kill functions are distributive). On the subsets of a finite set UU, let f(x)=g∪(x−k)f(x) = g \cup (x - k). Then f(x∪y)=f(x)∪f(y)f(x \cup y) = f(x) \cup f(y) and f(x∩y)=f(x)∩f(y)f(x \cap y) = f(x) \cap f(y). The composition of two such functions is again of this form.

Proof. Set difference distributes over union and intersection: (x∪y)−k=(x−k)∪(y−k)(x \cup y) - k = (x - k) \cup (y - k) and (x∩y)−k=(x−k)∩(y−k)(x \cap y) - k = (x - k) \cap (y - k). So f(x∪y)=g∪(x−k)∪(y−k)=f(x)∪f(y)f(x \cup y) = g \cup (x - k) \cup (y - k) = f(x) \cup f(y), and f(x∩y)=g∪((x−k)∩(y−k))=(g∪(x−k))∩(g∪(y−k))=f(x)∩f(y)f(x \cap y) = g \cup ((x - k) \cap (y - k)) = (g \cup (x - k)) \cap (g \cup (y - k)) = f(x) \cap f(y), because union distributes over intersection. For the composition, with f1=(g1,k1)f_1 = (g_1, k_1) applied first,

f2(f1(x))=g2∪((g1∪(x−k1))−k2)=(g2∪(g1−k2))∪(x−(k1∪k2)),f_2(f_1(x)) = g_2 \cup ((g_1 \cup (x - k_1)) - k_2) = (g_2 \cup (g_1 - k_2)) \cup (x - (k_1 \cup k_2)),

which has gen set g2∪(g1−k2)g_2 \cup (g_1 - k_2) and kill set k1∪k2k_1 \cup k_2. □\square

So the block functions of reaching definitions, live variables, available expressions and very busy expressions, which are compositions of the gen-kill functions of their instructions, are distributive for both meets. In the lattice of subsets of UU under ∪\cup or ∩\cap, the height is ∣U∣|U|. By Theorems 2 and 4, the algorithm computes the MOP solution of these four problems on every CFG where every block is reachable from the entry (forward problems) or reaches a ret block (backward problems, on the reverse CFG).

Theorem 5 (best case). If GG is acyclic and line L3 orders the nodes so that every edge goes from an earlier node to a later one, then line L11 never adds a node, and the run applies exactly nn transfer functions and mm meets.

Proof. Suppose line L11 adds a node, and look at the first time it does, while vv is processed, for an edge (v,s)(v, s). Up to then no node was added, so WW holds exactly the nodes after vv in the initial order. The edge (v,s)(v, s) puts ss after vv, so s∈Ws \in W, and line L11 does not add it, a contradiction. So each node is removed exactly once, line L6 runs nn times, and line L8 runs once per edge. □\square

Complexity

A transfer function or a meet counts as one lattice operation. The proved bounds:

  • Transfer functions. Each removal of a node from the queue applies one function. A node is removed at most once more than its value changes, so there are at most n+C≤n(h+1)n + C \le n(h + 1) of them, where C≤nhC \le n h is the total number of changes.
  • Meets. Each removal of vv does one meet per outgoing edge, so there are at most ∑v(h+1) outdeg(v)=m(h+1)\sum_v (h + 1)\, outdeg(v) = m(h + 1) meets.
  • Total. O((n+m)(h+1))O((n + m)(h + 1)) lattice operations, plus O(1)O(1) queue work per operation. The extra space is one value per node, the queue and the flags, Θ(n)\Theta(n) values.
  • Best case. If the graph is acyclic and the queue starts in a topological order, such as reverse postorder from the start nodes when every node is reachable, no node is ever appended again: exactly nn transfer functions and mm meets.
  • Bit vectors. For a gen-kill problem over UU items, h=∣U∣h = |U| and one operation costs O(∣U∣/w)O(|U| / w) word operations on a ww-bit word RAM, so the worst case is O((n+m)∣U∣2/w)O((n + m)|U|^2 / w). For constant propagation over vv variables, h=2vh = 2v.

The bound is a worst case allowed by the height, and it is rarely reached. The table below is measured, not proved: it comes from 300 random looping programs of the toy IR (seed 31337), with 3 to 8 blocks and 25.6 instructions on average (at most 43), solved with a queue in reverse postorder.

analysis transfer functions per block, average per block, worst most changes of one value largest hh meets per edge, worst
reaching definitions 1.36 2.12 6 35 2.33
live variables 1.32 2.25 4 14 2.11
available expressions 1.11 1.67 4 24 1.78
very busy expressions 1.16 1.71 3 24 1.67
constant propagation 2.04 3.50 7 28 3.67

The bound allows h+1h + 1 transfer functions per block, up to 36 here, and the worst run used 3.5. For rapid frameworks such as the bit-vector problems, the Kam-Ullman iteration bound shows that the number of round-robin sweeps depends on the loops of the graph and not on hh.

Properties

  • Order-free result. Any initial order of the queue, and a stack or a priority queue in place of the FIFO queue, gives the same MFP. Only the amount of work depends on the order.
  • Deterministic. For a fixed order the run, its counts and its result are fixed.
  • Non-recursive. One loop and a queue; no recursion.
  • Generic. The algorithm needs only ⊤\top, ι\iota, the meet, an equality test and the transfer functions. The lattice can be sets, bit vectors, maps from variables to constants, or any other domain of finite height.
  • No safe partial answer. Values move down only, so a run stopped early can leave values that are too high, which is unsafe.

Variants and improvements

  • Round-robin iteration. Sweep over all nodes in reverse postorder until a whole sweep changes nothing. For rapid frameworks, which include the four bit-vector problems, d+2d + 2 sweeps suffice, where dd is the largest number of back edges on an acyclic path (Kam-Ullman iteration bound). It is simpler, but it revisits nodes whose inputs did not change.
  • Priority by order. Keep the worklist sorted by reverse postorder number and always take the earliest node. This follows the flow of the program more closely than a FIFO queue, and the result is the same.
  • Recompute the input. Store OUT[v]=fv(IN[v])OUT[v] = f_v(IN[v]) and recompute IN[s]IN[s] as the meet over all predecessors when ss is taken from the queue, as in the dragon book. This gives the same result, but a node with kk predecessors costs kk meets per visit.
  • Bit-vector parallelism. For gen-kill problems, store each set as a bit vector, so one machine word handles ww items at once.
  • Elimination methods. Elimination dataflow methods solve the equations by the loop structure of a reducible flow graph, instead of by iteration.
  • Sparse analysis. On static single assignment form, facts about a variable can travel along def-use edges instead of through every block. Sparse conditional constant propagation runs one worklist of CFG edges and one of SSA edges.
  • Deltas. For a union meet, send only the items that are new since the last visit, as in semi-naive evaluation of Datalog.
  • Infinite height. For lattices such as intervals, the run may not end. Abstract interpretation adds a widening operator at loop heads to force termination, in the join convention where values go up from ⊥\bot.
  • Interprocedural problems. The IFDS framework runs a worklist over path edges of an exploded supergraph.

When to use it

Use it for any intraprocedural dataflow problem with monotone transfer functions and a lattice of finite height. It is the standard solver in compilers and static analyzers: it needs no structure of the graph, works for irreducible control flow, and does little work on typical programs. If the lattice has infinite height, add widening. If the program is in SSA form and the facts are per variable, a sparse solver is often faster.

Pitfalls

  • Setting the boundary to ⊤\top. The boundary value ι\iota describes the start of the program (or the point after ret) and is usually not ⊤\top. In available expressions, ι=∅\iota = \emptyset but ⊤\top is the set of all expressions; starting the entry at ⊤\top claims that every expression is available on entry. In the may problems ⊤=ι=∅\top = \iota = \emptyset, which hides the difference.
  • Running a backward problem on the CFG. A backward problem needs the reverse CFG, with the ret blocks as start nodes and the queue order taken from the reverse CFG. Its ININ values are the facts at the ends of the blocks.
  • Starting a must problem at the empty set. The other nodes must start at ⊤\top, the set of all items. Starting at ∅\emptyset still ends at a fixed point, but often a smaller one: an expression computed before a loop is lost at the loop head, because the back edge brings ∅\emptyset.
  • A queue that does not hold every node at the start. If line L3 puts only the start nodes in the queue, a node whose input never changes is never processed, so its own facts, such as its definitions in reaching definitions, never reach its successors. Line L3 must queue every node once.
  • Unreachable nodes. Nodes that the start nodes do not reach get values from the equations alone, which can differ from MOP. For example, an unreachable block that loops to itself keeps its own definitions in reaching definitions. MFP = MOP needs every node to be reachable.
  • Non-monotone functions. If a transfer function is not monotone, the equations may have no solution. This algorithm still stops, because line L8 only lowers values, but its result is then not a solution, and a solver that recomputes inputs can loop forever. With one item dd, union as the meet and a self-loop with the function X↦{d}−XX \mapsto \{d\} - X, this algorithm returns {d}\{d\}, which does not satisfy X={d}−XX = \{d\} - X.
  • Self-loops. Line L5 must clear the queue flag of vv before the loop of line L7, so that a self-loop that lowers IN[v]IN[v] puts vv back.

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.

toyir.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.

A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:

    ("const", x, k)          x = k
    ("copy", x, a)           x = y
    ("op", x, op, a, b)      x = a op b
    ("phi", x, {pred: a})    x = phi [pred: a, ...]
    ("addr", p, x)           p = &x
    ("load", x, p)           x = *p
    ("store", p, a)          *p = a
    ("alloc", p)             p = alloc
    ("call", x, f, args)     x = call f(a, b)   (args is a list)

Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""

from dataclasses import dataclass, field
import re

OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")


@dataclass
class Block:
    instrs: list = field(default_factory=list)
    term: tuple = ("ret", 0)


@dataclass
class Program:
    params: list
    blocks: dict

    @property
    def entry(self):
        return next(iter(self.blocks))


class UndefinedName(Exception):
    """A name was read before any definition."""


# ---------------------------------------------------------------- text form

_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"


def _operand(tok):
    if re.fullmatch(_INT, tok):
        return int(tok)
    if re.fullmatch(_NAME, tok):
        return tok
    raise ValueError("bad operand: %r" % tok)


def _name(tok):
    if not re.fullmatch(_NAME, tok):
        raise ValueError("bad name: %r" % tok)
    return tok


def _parse_instr(line):
    toks = line.split()
    if toks[0] == "jump" and len(toks) == 2:
        return "term", ("jump", _name(toks[1]))
    if toks[0] == "br" and len(toks) == 4:
        return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
    if toks[0] == "ret" and len(toks) == 2:
        return "term", ("ret", _operand(toks[1]))
    lhs, eq, rhs = line.partition("=")
    if not eq:
        raise ValueError("bad line: %r" % line)
    lhs, rhs = lhs.strip(), rhs.strip()
    if lhs.startswith("*"):
        return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
    x = _name(lhs)
    if rhs.startswith("phi"):
        body = rhs[3:].strip()
        if not (body.startswith("[") and body.endswith("]")):
            raise ValueError("bad phi: %r" % line)
        args = {}
        inner = body[1:-1].strip()
        if inner:
            for part in inner.split(","):
                pred, colon, a = part.partition(":")
                if not colon:
                    raise ValueError("bad phi: %r" % line)
                args[_name(pred.strip())] = _operand(a.strip())
        return "instr", ("phi", x, args)
    if rhs.startswith("call "):
        m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
        if not m:
            raise ValueError("bad call: %r" % line)
        inner = m.group(2).strip()
        args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
        return "instr", ("call", x, m.group(1), args)
    if rhs == "alloc":
        return "instr", ("alloc", x)
    if rhs.startswith("&"):
        return "instr", ("addr", x, _name(rhs[1:].strip()))
    if rhs.startswith("*"):
        return "instr", ("load", x, _name(rhs[1:].strip()))
    parts = rhs.split()
    if len(parts) == 1:
        a = _operand(parts[0])
        if isinstance(a, int):
            return "instr", ("const", x, a)
        return "instr", ("copy", x, a)
    if len(parts) == 3 and parts[1] in OPS:
        return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
    raise ValueError("bad instruction: %r" % line)


def parse(text):
    """Parse the text form. A line "# params: a, b" gives the parameters;
    without it, the parameters are the names that are read and never
    defined, in the order of their first use."""
    params = None
    blocks = {}
    cur = None
    for raw in text.splitlines():
        line = raw.strip()
        if not line:
            continue
        if line.startswith("#"):
            m = re.fullmatch(r"#\s*params:(.*)", line)
            if m:
                inner = m.group(1).strip()
                params = [_name(p.strip()) for p in inner.split(",")] if inner else []
            continue
        if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
            label = line[:-1]
            if label in blocks:
                raise ValueError("duplicate label: %r" % label)
            cur = label
            blocks[label] = Block([], None)
            continue
        if cur is None:
            raise ValueError("instruction outside a block: %r" % line)
        if blocks[cur].term is not None:
            raise ValueError("instruction after the terminator in %r" % cur)
        kind, item = _parse_instr(line)
        if kind == "term":
            blocks[cur].term = item
        else:
            blocks[cur].instrs.append(item)
    for label, b in blocks.items():
        if b.term is None:
            raise ValueError("block %r has no terminator" % label)
    if not blocks:
        raise ValueError("empty program")
    prog = Program([], blocks)
    if params is None:
        params = _free_names(prog)
    prog.params = params
    return prog


def _free_names(prog):
    defined = set()
    for b in prog.blocks.values():
        for ins in b.instrs:
            d = defs(ins)
            if d is not None:
                defined.add(d)
    out = []
    for b in prog.blocks.values():
        for ins in b.instrs:
            for a in uses(ins):
                if a not in defined and a not in out:
                    out.append(a)
        for a in term_uses(b.term):
            if a not in defined and a not in out:
                out.append(a)
    return out


def _show_instr(ins):
    k = ins[0]
    if k == "const":
        return "%s = %d" % (ins[1], ins[2])
    if k == "copy":
        return "%s = %s" % (ins[1], ins[2])
    if k == "op":
        return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
    if k == "phi":
        return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
    if k == "addr":
        return "%s = &%s" % (ins[1], ins[2])
    if k == "load":
        return "%s = *%s" % (ins[1], ins[2])
    if k == "store":
        return "*%s = %s" % (ins[1], ins[2])
    if k == "alloc":
        return "%s = alloc" % ins[1]
    if k == "call":
        return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
    raise ValueError("bad instruction: %r" % (ins,))


def _show_term(t):
    if t[0] == "jump":
        return "jump %s" % t[1]
    if t[0] == "br":
        return "br %s %s %s" % (t[1], t[2], t[3])
    if t[0] == "ret":
        return "ret %s" % (t[1],)
    raise ValueError("bad terminator: %r" % (t,))


def show(prog):
    lines = ["# params: " + ", ".join(prog.params)]
    for label, b in prog.blocks.items():
        lines.append(label + ":")
        for ins in b.instrs:
            lines.append("  " + _show_instr(ins))
        lines.append("  " + _show_term(b.term))
    return "\n".join(lines) + "\n"


# ---------------------------------------------------------- names and graph


def defs(ins):
    """The name an instruction defines, or None for a store."""
    return None if ins[0] == "store" else ins[1]


def uses(ins):
    """The names an instruction reads, in order (phi operands included)."""
    k = ins[0]
    if k == "const" or k == "alloc" or k == "addr":
        ops = []
    elif k == "copy":
        ops = [ins[2]]
    elif k == "op":
        ops = [ins[3], ins[4]]
    elif k == "phi":
        ops = list(ins[2].values())
    elif k == "load":
        ops = [ins[2]]
    elif k == "store":
        ops = [ins[1], ins[2]]
    elif k == "call":
        ops = list(ins[3])
    else:
        raise ValueError("bad instruction: %r" % (ins,))
    return [a for a in ops if isinstance(a, str)]


def term_uses(t):
    if t[0] == "br" or t[0] == "ret":
        return [t[1]] if isinstance(t[1], str) else []
    return []


def succs(prog, label):
    """Successor labels of a block, without repeats, in terminator order."""
    t = prog.blocks[label].term
    if t[0] == "jump":
        return [t[1]]
    if t[0] == "br":
        return [t[2]] if t[2] == t[3] else [t[2], t[3]]
    return []


def edges(prog):
    return [(a, b) for a in prog.blocks for b in succs(prog, a)]


def preds(prog):
    """Dict from label to the list of predecessor labels, in block order."""
    out = {label: [] for label in prog.blocks}
    for a, b in edges(prog):
        out[b].append(a)
    return out


def is_acyclic(prog):
    color = {label: 0 for label in prog.blocks}
    for root in prog.blocks:
        if color[root]:
            continue
        color[root] = 1
        stack = [(root, iter(succs(prog, root)))]
        while stack:
            v, it = stack[-1]
            w = next(it, None)
            if w is None:
                color[v] = 2
                stack.pop()
            elif color[w] == 1:
                return False
            elif color[w] == 0:
                color[w] = 1
                stack.append((w, iter(succs(prog, w))))
    return True


def paths(prog):
    """Every path from the entry to a ret block, as a list of labels.
    The CFG must be acyclic."""
    if not is_acyclic(prog):
        raise ValueError("paths needs an acyclic CFG")
    out = []

    def walk(path):
        last = path[-1]
        s = succs(prog, last)
        if not s:
            out.append(list(path))
        for w in s:
            path.append(w)
            walk(path)
            path.pop()

    walk([prog.entry])
    return out


# ------------------------------------------------------------------ running


class _Trap(Exception):
    pass


class _Fuel(Exception):
    pass


def _binop(op, a, b):
    if not isinstance(a, int) or not isinstance(b, int):
        raise TypeError("arithmetic on a pointer")
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op == "*":
        return a * b
    if op == "/" or op == "%":
        if b == 0:
            raise _Trap()
        q = abs(a) // abs(b)
        if (a < 0) != (b < 0):
            q = -q
        return q if op == "/" else a - b * q
    if op == "&":
        return a & b
    if op == "|":
        return a | b
    if op == "^":
        return a ^ b
    if op == "<<" or op == ">>":
        if b < 0 or b > 63:
            raise _Trap()
        return a << b if op == "<<" else a >> b
    if op == "<":
        return int(a < b)
    if op == "<=":
        return int(a <= b)
    if op == "==":
        return int(a == b)
    if op == "!=":
        return int(a != b)
    raise ValueError("bad operator: %r" % op)


class _Frame:
    """One activation: its program, its variables and its position."""

    def __init__(self, prog, args, fid):
        if len(args) != len(prog.params):
            raise ValueError("expected %d arguments" % len(prog.params))
        self.prog = prog
        self.env = dict(zip(prog.params, args))
        self.fid = fid
        self.label = prog.entry
        self.prev = None
        self.pc = 0  # 0 means: the phis of the block have not run yet
        self.dest = None  # the name that receives the value of a pending call

    def val(self, a):
        if isinstance(a, int):
            return a
        if a not in self.env:
            raise UndefinedName(a)
        return self.env[a]


def _run(prog, args, fuel, funcs):
    """Run with an explicit stack of frames, so deep recursion in the toy
    program does not use Python recursion."""
    heap = {}
    envs = {}
    stack = []
    fr = _Frame(prog, args, 0)
    envs[0] = fr.env
    nframes = 1

    def tick():
        nonlocal fuel
        if fuel <= 0:
            raise _Fuel()
        fuel -= 1

    while True:
        block = fr.prog.blocks[fr.label]
        instrs = block.instrs
        if fr.pc == 0:
            # Phis at the top of the block read all operands first, then assign.
            incoming = []
            i = 0
            while i < len(instrs) and instrs[i][0] == "phi":
                tick()
                ins = instrs[i]
                if fr.prev not in ins[2]:
                    raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
                incoming.append((ins[1], fr.val(ins[2][fr.prev])))
                i += 1
            for x, v in incoming:
                fr.env[x] = v
            fr.pc = i if i > 0 else -1
        start = fr.pc if fr.pc > 0 else 0
        called = False
        env = fr.env
        for j in range(start, len(instrs)):
            ins = instrs[j]
            tick()
            k = ins[0]
            if k == "const":
                env[ins[1]] = ins[2]
            elif k == "copy":
                env[ins[1]] = fr.val(ins[2])
            elif k == "op":
                env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
            elif k == "addr":
                env[ins[1]] = ("var", fr.fid, ins[2])
            elif k == "alloc":
                cell = ("heap", len(heap))
                heap[cell] = None
                env[ins[1]] = cell
            elif k == "load":
                p = fr.val(ins[2])
                if p[0] == "var":
                    if p[2] not in envs[p[1]]:
                        raise UndefinedName(p[2])
                    env[ins[1]] = envs[p[1]][p[2]]
                else:
                    if heap[p] is None:
                        raise UndefinedName(repr(p))
                    env[ins[1]] = heap[p]
            elif k == "store":
                p = fr.val(ins[1])
                if p[0] == "var":
                    envs[p[1]][p[2]] = fr.val(ins[2])
                else:
                    heap[p] = fr.val(ins[2])
            elif k == "call":
                if funcs is None or ins[2] not in funcs:
                    raise ValueError("unknown function %r" % ins[2])
                vals = [fr.val(a) for a in ins[3]]
                fr.pc = j + 1
                fr.dest = ins[1]
                stack.append(fr)
                fr = _Frame(funcs[ins[2]], vals, nframes)
                envs[nframes] = fr.env
                nframes += 1
                called = True
                break
            elif k == "phi":
                raise ValueError("phi after a non-phi instruction")
            else:
                raise ValueError("bad instruction: %r" % (ins,))
        if called:
            continue
        tick()
        t = block.term
        if t[0] == "jump" or t[0] == "br":
            if t[0] == "jump":
                nxt = t[1]
            else:
                nxt = t[2] if fr.val(t[1]) != 0 else t[3]
            fr.prev, fr.label, fr.pc = fr.label, nxt, 0
            continue
        v = fr.val(t[1])
        if not stack:
            return ("ret", v), fuel
        fr = stack.pop()
        fr.env[fr.dest] = v


def run(prog, args, fuel=10000, funcs=None):
    """Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
    Each instruction, phi and terminator uses one unit of fuel. funcs is an
    optional dict from function name to Program, used by call; deep
    recursion in the toy program is fine, because the frames are kept on an
    explicit stack."""
    try:
        out, _ = _run(prog, list(args), fuel, funcs)
        return out
    except _Trap:
        return ("trap",)
    except _Fuel:
        return ("fuel",)


# ------------------------------------------------------------ random programs

_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")


def random_program(rng, nvars, nblocks, acyclic):
    """A random program with blocks B0 .. B(nblocks-1) and variables
    x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
    others, so no run reads an undefined name. A division by a variable can
    trap. Every block is reachable from
    B0 and B0 has no predecessor. With acyclic=False, each loop has its own
    counter c that is set to 0 in B0 and never reset, and the back edge is
    taken only while c < m and c < 4, where m is the first parameter. So the
    whole run takes each back edge at most 3 times."""
    nvars = max(nvars, 1)
    nblocks = max(nblocks, 1)
    xs = ["x%d" % i for i in range(nvars)]
    params = xs[:2]
    labels = ["B%d" % i for i in range(nblocks)]

    def operand():
        if rng.random() < 0.25:
            return rng.randint(-3, 9)
        return rng.choice(xs)

    def instr():
        x = rng.choice(xs)
        r = rng.random()
        if r < 0.15:
            return ("const", x, rng.randint(-5, 9))
        if r < 0.25:
            return ("copy", x, rng.choice(xs))
        if r < 0.3:
            # A division by a variable may trap.
            return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
        if r < 0.4:
            op = rng.choice(_CONST_RIGHT)
            k = rng.randint(1, 5)
            return ("op", x, op, rng.choice(xs), k)
        return ("op", x, rng.choice(_SAFE), operand(), operand())

    blocks = {}
    has_pred = [False] * nblocks
    has_pred[0] = True
    for i in range(nblocks):
        instrs = [instr() for _ in range(rng.randint(1, 3))]
        if i == 0:
            instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
        if i == nblocks - 1:
            term = ("ret", rng.choice(xs))
        elif has_pred[i + 1] and rng.random() < 0.2:
            term = ("ret", rng.choice(xs))
        else:
            first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
            if rng.random() < 0.5:
                term = ("jump", labels[first])
                has_pred[first] = True
            else:
                second = rng.randrange(i + 1, nblocks)
                if second == first:
                    term = ("jump", labels[first])
                else:
                    term = ("br", rng.choice(xs), labels[first], labels[second])
                    has_pred[second] = True
                has_pred[first] = True
        blocks[labels[i]] = Block(instrs, term)

    if not acyclic and nblocks > 1:
        nloops = rng.randint(1, max(1, nblocks // 3))
        for k in range(nloops):
            latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
            if not latches:
                break
            t = rng.choice(latches)
            h = labels[rng.randint(1, labels.index(t))]
            c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
            blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
            out = blocks[t].term[1]
            blocks[t].instrs += [
                ("op", c, "+", c, 1),
                ("op", w1, "<", c, m),
                ("op", w2, "<", c, 4),
                ("op", w, "&", w1, w2),
            ]
            blocks[t].term = ("br", w, h, out)
    return Program(list(params), blocks)
worklist_dataflow_algorithm.py 328 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/worklist-dataflow-algorithm/. The authors are listed in prov/5353DC.jsonl.
"""The worklist dataflow algorithm (Kildall 1973) on the toy IR.

The lattice uses the meet convention of Kildall and the dragon book: top is
the identity of meet and the start value, and the result is the maximal
fixed point (MFP). A backward problem runs the same solver on the reverse
CFG, with the ret blocks as start nodes.

Five analyses are given: reaching definitions, live variables, available
expressions and very busy expressions (gen-kill problems on frozensets),
and constant propagation (a flat lattice per variable, not distributive).
"""

from collections import deque

from toyir import defs, preds, succs, term_uses, uses

TOP = "top"  # constant propagation: no value seen yet
NAC = "nac"  # constant propagation: not a constant (bottom)


def worklist(nodes, succ, starts, boundary, top, meet, transfer, order=None):
    """Solve IN[s] = (boundary if s is a start else top) meet the meet over
    the edges (n, s) of transfer(n, IN[n]), for the greatest solution.

    nodes: the nodes; succ: dict node -> list of successors in the direction
    of the analysis; starts: the start nodes. Returns (IN, stats), where
    stats counts transfer applications, meets and changes of IN."""
    order = list(nodes) if order is None else list(order)
    inn = {n: top for n in nodes}  # @line L1
    for s in starts:
        inn[s] = boundary  # @line L2
    work = deque(order)  # @line L3
    queued = set(order)
    stats = {"transfers": 0, "meets": 0, "changes": 0}
    changes = {n: 0 for n in nodes}
    while work:  # @line L4
        n = work.popleft()  # @line L5
        queued.discard(n)
        out = transfer(n, inn[n])  # @line L6
        stats["transfers"] += 1
        for s in succ[n]:  # @line L7
            new = meet(inn[s], out)  # @line L8
            stats["meets"] += 1
            if new != inn[s]:  # @line L9
                inn[s] = new  # @line L10
                changes[s] += 1
                stats["changes"] += 1
                if s not in queued:  # @line L11
                    work.append(s)
                    queued.add(s)
    stats["max_changes"] = max(changes.values(), default=0)
    return inn, stats


def reverse_postorder(nodes, succ, starts):
    """Nodes in reverse postorder of a DFS from the starts; nodes that the
    starts do not reach come last, in their given order."""
    seen, post = set(), []
    for root in starts:
        if root in seen:
            continue
        seen.add(root)
        stack = [(root, iter(succ[root]))]
        while stack:
            v, it = stack[-1]
            w = next(it, None)
            if w is None:
                post.append(v)
                stack.pop()
            elif w not in seen:
                seen.add(w)
                stack.append((w, iter(succ[w])))
    order = post[::-1]
    return order + [n for n in nodes if n not in seen]


def graph(prog, forward):
    """The CFG in the direction of the analysis: (nodes, succ, starts)."""
    nodes = list(prog.blocks)
    if forward:
        return nodes, {n: succs(prog, n) for n in nodes}, [prog.entry]
    p = preds(prog)
    exits = [n for n in nodes if prog.blocks[n].term[0] == "ret"]
    return nodes, {n: p[n] for n in nodes}, exits


def solve(prog, an):
    """Run the worklist algorithm for the analysis an. Returns (IN, OUT,
    stats) in CFG terms: IN[L] holds at the start of block L, OUT[L] at its
    end, for forward and backward problems alike."""
    nodes, succ, starts = graph(prog, an.forward)
    order = reverse_postorder(nodes, succ, starts)
    before, stats = worklist(nodes, succ, starts, an.boundary, an.top, an.meet, an.transfer, order)
    after = {n: an.transfer(n, before[n]) for n in nodes}
    if an.forward:
        return before, after, stats
    return after, before, stats


# ------------------------------------------------------------ gen-kill problems


def compose(first, second):
    """The gen-kill pair of second after first: gen2 | (gen1 - kill2),
    kill1 | kill2."""
    g1, k1 = first
    g2, k2 = second
    return g2 | (g1 - k2), k1 | k2


class GenKill:
    """A gen-kill problem. step(label, i, ins) gives the gen-kill pair of
    one instruction (ins is None for the terminator); the block pair is the
    composition in the direction of the analysis."""

    def __init__(self, prog, forward, must, universe, step, boundary=frozenset()):
        self.prog = prog
        self.forward = forward
        self.must = must
        self.universe = frozenset(universe)
        self.top = self.universe if must else frozenset()
        self.boundary = frozenset(boundary)
        self.height = len(self.universe)
        self.step = step
        self.block = {}
        for label, b in prog.blocks.items():
            items = [(i, ins) for i, ins in enumerate(b.instrs)] + [(len(b.instrs), None)]
            if not forward:
                items.reverse()
            pair = (frozenset(), frozenset())
            for i, ins in items:
                g, k = step(label, i, ins)
                pair = compose(pair, (frozenset(g), frozenset(k)))
            self.block[label] = pair

    def meet(self, a, b):
        return a & b if self.must else a | b

    def transfer(self, label, x):
        g, k = self.block[label]
        return g | (x - k)

    def leq(self, a, b):
        return self.meet(a, b) == a


def _check(prog):
    for b in prog.blocks.values():
        for ins in b.instrs:
            if ins[0] not in ("const", "copy", "op"):
                raise ValueError("these analyses take const, copy and op only")


def names(prog):
    out = list(prog.params)
    for b in prog.blocks.values():
        for ins in b.instrs:
            for a in uses(ins) + [defs(ins)]:
                if a not in out:
                    out.append(a)
        for a in term_uses(b.term):
            if a not in out:
                out.append(a)
    return out


def expressions(prog):
    """The expressions (op, a, b) of the program, in program order."""
    out = []
    for b in prog.blocks.values():
        for ins in b.instrs:
            if ins[0] == "op" and ins[2:] not in out:
                out.append(ins[2:])
    return out


def reaching_definitions(prog):
    """Forward, may. A definition is the pair (label, index)."""
    _check(prog)
    sites = [(lab, i) for lab, b in prog.blocks.items() for i in range(len(b.instrs))]
    by_var = {}
    for lab, i in sites:
        by_var.setdefault(defs(prog.blocks[lab].instrs[i]), set()).add((lab, i))

    def step(label, i, ins):
        if ins is None:
            return set(), set()
        return {(label, i)}, by_var[defs(ins)] - {(label, i)}

    return GenKill(prog, True, False, sites, step)


def live_variables(prog):
    """Backward, may. A fact is a variable name."""
    _check(prog)

    def step(label, i, ins):
        if ins is None:
            return set(term_uses(prog.blocks[label].term)), set()
        return set(uses(ins)), {defs(ins)}

    return GenKill(prog, False, False, names(prog), step)


def _killed(exprs, x):
    return {e for e in exprs if x in (e[1], e[2])}


def available_expressions(prog):
    """Forward, must. A fact is an expression (op, a, b)."""
    _check(prog)
    exprs = expressions(prog)

    def step(label, i, ins):
        if ins is None:
            return set(), set()
        kill = _killed(exprs, defs(ins))
        gen = {ins[2:]} - kill if ins[0] == "op" else set()
        return gen, kill

    return GenKill(prog, True, True, exprs, step)


def very_busy_expressions(prog):
    """Backward, must. A fact is an expression (op, a, b)."""
    _check(prog)
    exprs = expressions(prog)

    def step(label, i, ins):
        if ins is None:
            return set(), set()
        kill = _killed(exprs, defs(ins))
        gen = {ins[2:]} if ins[0] == "op" else set()
        return gen, kill

    return GenKill(prog, False, True, exprs, step)


# --------------------------------------------------------- constant propagation


def flat_meet(a, b):
    if a == TOP:
        return b
    if b == TOP or a == b:
        return a
    return NAC


def fold(op, a, b):
    """The abstract value of a op b on the flat lattice."""
    if a == NAC or b == NAC:
        return NAC
    if a == TOP or b == TOP:
        return TOP
    if op in ("/", "%") and b == 0:
        return NAC  # the program traps here; NAC is a safe answer
    if op in ("<<", ">>") and not 0 <= b <= 63:
        return NAC
    if op in ("/", "%"):
        q = abs(a) // abs(b)
        if (a < 0) != (b < 0):
            q = -q
        return q if op == "/" else a - b * q
    table = {
        "+": lambda: a + b, "-": lambda: a - b, "*": lambda: a * b,
        "&": lambda: a & b, "|": lambda: a | b, "^": lambda: a ^ b,
        "<<": lambda: a << b, ">>": lambda: a >> b,
        "<": lambda: int(a < b), "<=": lambda: int(a <= b),
        "==": lambda: int(a == b), "!=": lambda: int(a != b),
    }
    return table[op]()


class ConstantPropagation:
    """Forward. A value is a tuple with one flat-lattice entry per name.
    Parameters start as NAC, the other names as TOP (not yet defined)."""

    forward = True

    def __init__(self, prog):
        _check(prog)
        self.prog = prog
        self.vars = names(prog)
        self.index = {x: i for i, x in enumerate(self.vars)}
        self.top = tuple(TOP for _ in self.vars)
        self.boundary = tuple(NAC if x in prog.params else TOP for x in self.vars)
        self.height = 2 * len(self.vars)

    def meet(self, a, b):
        return tuple(flat_meet(x, y) for x, y in zip(a, b))

    def leq(self, a, b):
        return self.meet(a, b) == a

    def value(self, env, a):
        return a if isinstance(a, int) else env[self.index[a]]

    def step(self, env, ins):
        env = list(env)
        k, x = ins[0], ins[1]
        if k == "const":
            env[self.index[x]] = ins[2]
        elif k == "copy":
            env[self.index[x]] = self.value(env, ins[2])
        else:
            env[self.index[x]] = fold(ins[2], self.value(env, ins[3]), self.value(env, ins[4]))
        return tuple(env)

    def transfer(self, label, env):
        for ins in self.prog.blocks[label].instrs:
            env = self.step(env, ins)
        return env


def constant_propagation(prog):
    return ConstantPropagation(prog)


ANALYSES = {
    "reaching-definitions": reaching_definitions,
    "live-variables": live_variables,
    "available-expressions": available_expressions,
    "very-busy-expressions": very_busy_expressions,
    "constant-propagation": constant_propagation,
}
test_worklist_dataflow_algorithm.py 411 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/worklist-dataflow-algorithm/. The authors are listed in prov/5353DC.jsonl.

import random

import toyir
from toyir import defs, parse, paths, preds, random_program, succs, term_uses, uses
from worklist_dataflow_algorithm import (
    ANALYSES,
    NAC,
    TOP,
    available_expressions,
    constant_propagation,
    live_variables,
    reaching_definitions,
    solve,
    very_busy_expressions,
)

EX = """
# params: n, x
entry:
  i = 0
  s = 0
  jump head
head:
  t = i < n
  br t body done
body:
  a = x * 2
  u = i & 1
  br u odd next
odd:
  s = s + a
  jump next
next:
  i = i + 1
  jump head
done:
  ret s
"""

DIAMOND = """
# params: c
entry:
  br c left right
left:
  x = 2
  y = 3
  jump join
right:
  x = 3
  y = 2
  jump join
join:
  z = x + y
  ret z
"""

GENKILL = ["reaching-definitions", "live-variables", "available-expressions", "very-busy-expressions"]


def exits(prog):
    return [n for n in prog.blocks if prog.blocks[n].term[0] == "ret"]


# ------------------------------------------------------------ reference: MOP


def mop(prog, an, inclusive=False):
    """Meet over all paths by enumeration on an acyclic CFG, in CFG terms
    (IN for a forward problem, OUT for a backward one). With inclusive=True
    the paths also run through the block itself (OUT for a forward problem,
    IN for a backward one)."""
    res = {n: an.top for n in prog.blocks}
    j = 1 if inclusive else 0
    for p in paths(prog):
        for k in range(len(p)):
            if an.forward:
                head, rest = p[k], p[:k + j]
            else:
                head, rest = p[k], list(reversed(p[k + 1 - j:]))
            v = an.boundary
            for b in rest:
                v = an.transfer(b, v)
            res[head] = an.meet(res[head], v)
    return res


def walk_facts(prog, labels, kind, exprs):
    """The fact of one path, by the meaning of the problem, without gen and
    kill sets. labels are the blocks, in program order, that the path runs
    through after (forward) or before (backward) the point."""
    events = []
    for b in labels:
        blk = prog.blocks[b]
        for i, ins in enumerate(blk.instrs):
            events += [("use", a) for a in uses(ins)]
            if ins[0] == "op":
                events.append(("eval", ins[2:]))
            events.append(("def", defs(ins), (b, i)))
        events += [("use", a) for a in term_uses(blk.term)]
    if kind == "reaching-definitions":
        last = {}
        for e in events:
            if e[0] == "def":
                last[e[1]] = e[2]
        return frozenset(last.values())
    if kind == "available-expressions":
        avail = set()
        for e in events:
            if e[0] == "eval":
                avail.add(e[1])
            elif e[0] == "def":
                avail = {f for f in avail if e[1] not in (f[1], f[2])}
        return frozenset(avail)
    if kind == "live-variables":
        live, written = set(), set()
        for e in events:
            if e[0] == "use" and e[1] not in written:
                live.add(e[1])
            elif e[0] == "def":
                written.add(e[1])
        return frozenset(live)
    busy, dead = set(), set()
    for e in events:
        if e[0] == "eval" and e[1] not in dead:
            busy.add(e[1])
        elif e[0] == "def":
            dead |= {f for f in exprs if e[1] in (f[1], f[2]) and f not in busy}
    return frozenset(busy)


def by_meaning(prog, kind):
    an = ANALYSES[kind](prog)
    exprs = an.universe
    res = {n: an.top for n in prog.blocks}
    for p in paths(prog):
        for k in range(len(p)):
            labels = p[:k] if an.forward else p[k + 1:]
            res[p[k]] = an.meet(res[p[k]], walk_facts(prog, labels, kind, exprs))
    return res


# ------------------------------------------------- reference: round robin


def round_robin(prog, an):
    """Kleene iteration from top over all blocks until nothing changes."""
    nodes = list(prog.blocks)
    p = preds(prog)
    ins = {n: an.top for n in nodes}
    changed = True
    while changed:
        changed = False
        for n in nodes:
            if an.forward:
                v = an.boundary if n == prog.entry else an.top
                for q in p[n]:
                    v = an.meet(v, an.transfer(q, ins[q]))
            else:
                v = an.boundary if prog.blocks[n].term[0] == "ret" else an.top
                for q in succs(prog, n):
                    v = an.meet(v, an.transfer(q, ins[q]))
            if v != ins[n]:
                ins[n] = v
                changed = True
    return ins


def check_fixed_point(prog, an, IN, OUT):
    p = preds(prog)
    for n in prog.blocks:
        if an.forward:
            v = an.boundary if n == prog.entry else an.top
            for q in p[n]:
                v = an.meet(v, OUT[q])
            assert IN[n] == v and OUT[n] == an.transfer(n, IN[n])
        else:
            v = an.boundary if prog.blocks[n].term[0] == "ret" else an.top
            for q in succs(prog, n):
                v = an.meet(v, IN[q])
            assert OUT[n] == v and IN[n] == an.transfer(n, OUT[n])


# --------------------------------------------- reference: concrete runs


def trace(prog, args, fuel=2000):
    """Run prog and record events: ("enter", L, env), ("use", x),
    ("eval", e) and ("def", x, (L, i)). Returns (events, outcome)."""
    env = dict(zip(prog.params, args))
    events = []
    label = prog.entry
    try:
        while True:
            events.append(("enter", label, dict(env)))
            blk = prog.blocks[label]
            for i, ins in enumerate(blk.instrs):
                fuel -= 1
                if fuel < 0:
                    return events, "fuel"
                events += [("use", a) for a in uses(ins)]
                def val(a):
                    return a if isinstance(a, int) else env[a]

                if ins[0] == "const":
                    env[ins[1]] = ins[2]
                elif ins[0] == "copy":
                    env[ins[1]] = val(ins[2])
                else:
                    events.append(("eval", ins[2:]))
                    env[ins[1]] = toyir._binop(ins[2], val(ins[3]), val(ins[4]))
                events.append(("def", ins[1], (label, i)))
            events += [("use", a) for a in term_uses(blk.term)]
            t = blk.term
            if t[0] == "ret":
                return events, "ret"
            if t[0] == "jump":
                label = t[1]
            else:
                c = t[1] if isinstance(t[1], int) else env[t[1]]
                label = t[2] if c != 0 else t[3]
    except toyir._Trap:
        return events, "trap"


def check_runs(prog, results, rng):
    IN = {k: results[k][0] for k in results}
    cp = constant_propagation(prog)
    for _ in range(12):
        args = [rng.randint(-5, 9) for _ in prog.params]
        events, outcome = trace(prog, args)
        last, avail = {}, set()
        for e in events:
            if e[0] == "enter":
                assert set(last.values()) <= IN["reaching-definitions"][e[1]]
                assert IN["available-expressions"][e[1]] <= avail
                for x, v in zip(cp.vars, IN["constant-propagation"][e[1]]):
                    if v == TOP:
                        assert x not in e[2]
                    elif v != NAC:
                        assert e[2].get(x, v) == v
            elif e[0] == "eval":
                avail.add(e[1])
            elif e[0] == "def":
                last[e[1]] = e[2]
                avail = {f for f in avail if e[1] not in (f[1], f[2])}
        live, busy = set(), set()
        exprs = ANALYSES["very-busy-expressions"](prog).universe
        for e in reversed(events):
            if e[0] == "enter":
                assert live <= IN["live-variables"][e[1]]
                if outcome == "ret":
                    assert IN["very-busy-expressions"][e[1]] <= busy
            elif e[0] == "use":
                live.add(e[1])
            elif e[0] == "eval":
                busy.add(e[1])
            elif e[0] == "def":
                live.discard(e[1])
                busy -= {f for f in exprs if e[1] in (f[1], f[2])}


# --------------------------------------------------------------- the tests


def show_set(v):
    out = []
    for e in v:
        if isinstance(e, str):
            out.append(e)
        elif isinstance(e[1], int):
            out.append("%s%d" % e)
        else:
            out.append("%s %s %s" % (e[1], e[0], e[2]))
    return sorted(out)


def test_running_example() -> None:
    prog = parse(EX)
    IN, OUT, st = solve(prog, live_variables(prog))
    assert show_set(IN["entry"]) == ["n", "x"]
    assert show_set(OUT["body"]) == ["a", "i", "n", "s", "x"]
    assert show_set(IN["done"]) == ["s"]
    assert st == {"transfers": 11, "meets": 13, "changes": 11, "max_changes": 3}
    IN, OUT, st = solve(prog, reaching_definitions(prog))
    assert show_set(IN["head"]) == ["body0", "body1", "entry0", "entry1", "head0", "next0", "odd0"]
    assert show_set(OUT["next"]) == ["body0", "body1", "entry1", "head0", "next0", "odd0"]
    assert st["transfers"] == 11
    IN, OUT, st = solve(prog, available_expressions(prog))
    assert show_set(IN["head"]) == []
    assert show_set(IN["next"]) == ["i & 1", "i < n", "x * 2"]
    assert show_set(IN["done"]) == ["i < n"]
    assert st["transfers"] == 6
    IN, OUT, st = solve(prog, very_busy_expressions(prog))
    assert show_set(IN["body"]) == ["i & 1", "i + 1", "x * 2"]
    assert show_set(OUT["entry"]) == ["i < n"]
    assert show_set(OUT["head"]) == []
    assert st["transfers"] == 6


def test_constant_propagation_is_not_distributive() -> None:
    prog = parse(DIAMOND)
    an = constant_propagation(prog)
    IN, OUT, _ = solve(prog, an)
    z = an.index["z"]
    assert IN["join"][an.index["x"]] == NAC
    assert OUT["join"][z] == NAC
    assert mop(prog, an, inclusive=True)["join"][z] == 5
    left, right = OUT["left"], OUT["right"]
    assert an.transfer("join", left)[z] == 5 and an.transfer("join", right)[z] == 5
    assert an.meet(an.transfer("join", left), an.transfer("join", right))[z] == 5
    assert an.transfer("join", an.meet(left, right))[z] == NAC


def test_genkill_composition_and_distributivity() -> None:
    rng = random.Random(7)
    for _ in range(40):
        prog = random_program(rng, 4, rng.randint(2, 7), acyclic=rng.random() < 0.5)
        for kind in GENKILL:
            an = ANALYSES[kind](prog)
            universe = sorted(an.universe, key=repr)
            for label, b in prog.blocks.items():
                x = frozenset(e for e in universe if rng.random() < 0.5)
                y = frozenset(e for e in universe if rng.random() < 0.5)
                items = [(i, ins) for i, ins in enumerate(b.instrs)] + [(len(b.instrs), None)]
                if not an.forward:
                    items.reverse()
                v = x
                for i, ins in items:
                    g, k = an.step(label, i, ins)
                    v = frozenset(g) | (v - frozenset(k))
                assert an.transfer(label, x) == v
                assert an.transfer(label, an.meet(x, y)) == an.meet(an.transfer(label, x), an.transfer(label, y))


def acyclic_cases(seed, count):
    """MFP against MOP on random acyclic programs. Gen-kill problems must
    agree exactly; constant propagation must be below MOP. Returns the
    number of blocks where constant propagation is strictly below MOP."""
    rng = random.Random(seed)
    strict = 0
    for _ in range(count):
        prog = random_program(rng, 4, rng.randint(2, 8), acyclic=True)
        for kind in GENKILL:
            an = ANALYSES[kind](prog)
            IN, OUT, _ = solve(prog, an)
            mfp, mfp2 = (IN, OUT) if an.forward else (OUT, IN)
            assert mfp == mop(prog, an)
            assert mfp2 == mop(prog, an, inclusive=True)
            assert mfp == by_meaning(prog, kind)
        an = constant_propagation(prog)
        IN, OUT, _ = solve(prog, an)
        m, m2 = mop(prog, an), mop(prog, an, inclusive=True)
        for n in prog.blocks:
            assert an.leq(IN[n], m[n]) and an.leq(OUT[n], m2[n])
            strict += OUT[n] != m2[n]
    return strict


def test_acyclic_mfp_equals_mop() -> None:
    # 400 programs; constant propagation is strictly below MOP at 19 blocks.
    assert acyclic_cases(2024, 400) == 19


def test_constant_propagation_below_mop_on_diamonds() -> None:
    rng = random.Random(99)
    strict = 0
    for _ in range(100):
        a, b = rng.randint(0, 4), rng.randint(0, 4)
        text = DIAMOND.replace("x = 2", "x = A").replace("y = 3", "y = B")
        text = text.replace("x = 3", "x = B").replace("y = 2", "y = A")
        prog = parse(text.replace("A", str(a)).replace("B", str(b)))
        an = constant_propagation(prog)
        IN, OUT, _ = solve(prog, an)
        mo = mop(prog, an, inclusive=True)["join"]
        assert an.leq(OUT["join"], mo)
        assert mo[an.index["z"]] == a + b
        strict += OUT["join"] != mo
        assert (OUT["join"][an.index["z"]] == NAC) == (a != b)
        assert (OUT["join"] != mo) == (a != b)
    assert strict == 85


def test_cyclic_fixed_point_bounds_and_runs() -> None:
    rng = random.Random(31337)
    for _ in range(300):
        prog = random_program(rng, 4, rng.randint(3, 8), acyclic=False)
        nblocks = len(prog.blocks)
        nedges = len(toyir.edges(prog))
        results = {}
        for kind, mk in ANALYSES.items():
            an = mk(prog)
            IN, OUT, st = solve(prog, an)
            check_fixed_point(prog, an, IN, OUT)
            assert round_robin(prog, an) == (IN if an.forward else OUT)
            assert st["max_changes"] <= an.height
            assert st["transfers"] <= nblocks + st["changes"]
            assert st["meets"] <= (an.height + 1) * nedges
            results[kind] = (IN, OUT)
        check_runs(prog, results, rng)


def test_exits_and_boundary() -> None:
    prog = parse(EX)
    assert exits(prog) == ["done"]
    an = available_expressions(prog)
    assert an.boundary == frozenset() and an.top == an.universe
    IN, _, _ = solve(prog, an)
    assert IN["entry"] == frozenset()

History

Kildall (1973) described one iterative algorithm for a whole family of global optimization problems, parameterized by a lattice and the functions of the nodes. It starts from the top element and lowers values until they are stable, and Kildall showed that it gives the meet over all paths when the functions are distributive. Kam and Ullman (1976) studied round-robin iteration in depth-first order and bounded the number of sweeps for the bit-vector problems. Kam and Ullman (1977) defined monotone frameworks, proved that Kildall's algorithm computes the maximal fixed point, which is below the meet over all paths and can differ from it, and showed that no algorithm computes the meet over all paths for every monotone framework. Textbooks give both the round-robin and the worklist forms (Aho, Lam, Sethi and Ullman; Cooper and Torczon; Nielson, Nielson and Hankin, who use the join convention and least fixed points).

References

  1. Gary A. Kildall, A unified approach to global program optimization, Proceedings of the 1st ACM SIGACT-SIGPLAN Symposium on Principles of Programming Languages (POPL 1973), 194-206, the whole paper (the iterative algorithm from the top element, and its result for distributive functions)
  2. John B. Kam and Jeffrey D. Ullman, Monotone data flow analysis frameworks, Acta Informatica 7(3), 1977, 305-317, the whole paper (the maximal fixed point of a monotone framework, the proof that Kildall's algorithm computes it, and the proof that it is below the meet over all paths)
  3. John B. Kam and Jeffrey D. Ullman, Global data flow analysis and iterative algorithms, Journal of the ACM 23(1), 1976, 158-171, the whole paper (the analysis of round-robin iteration in depth-first order, which covers the bit-vector problems)
  4. Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Pearson Addison-Wesley, 2007, Section 9.3.3 (The Iterative Algorithm for General Frameworks), Section 9.3.4 (Meaning of a Data-Flow Solution) and Section 9.6.7 (Speed of Convergence of Iterative Data-Flow Algorithms)
  5. Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 9 (Data-Flow Analysis), Section 9.2 (Iterative Data-Flow Analysis)
  6. Flemming Nielson, Hanne Riis Nielson and Chris Hankin, Principles of Program Analysis, Springer, 1999, Section 2.4 (Equation Solving, the worklist algorithm for the MFP solution), in the join convention where the same solution is the least one

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.average
  • a full proof of time.best
  • 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
  • History with a source
  • a scene preset for the example