Algorithmcore
Sparse conditional constant propagation
Also called SCCP, Wegman-Zadeck algorithm.
Propagates constants over SSA edges and executable flow edges together, so it ignores branches that constants prove dead.
- Solves
- Constant propagation
- Time
- O(n + m + s d) worst · averageΘ(n + s) best
- Space
- Θ(n + m + s) extra
- Where
- d = the largest number of predecessors of a block; m = the number of CFG edges; n = the number of instructions in SSA form; s = the number of SSA edges
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
Sparse conditional constant propagation (SCCP) solves the constant propagation problem on a program in static single assignment form. It keeps two worklists. One holds edges of the control flow graph that may run. The other holds SSA edges, from the one definition of a name to a use of it. The algorithm starts with every name at , "no value seen yet", and only the entry reachable. It looks at an instruction only after some executable edge reaches its block. A branch whose condition is a known constant makes only one of its edges executable. So a constant can prove a branch dead, and the dead branch then cannot spoil other constants. The result is the greatest fixed point of one combined system for values and reachability. It is at least as strong as simple constant propagation and dead branch elimination run one after the other in any order and as often as you like, and it can be strictly stronger when the program has a loop. Each SSA edge goes through the worklist at most twice, so the work is close to linear in the size of the SSA form.
In plain words
Assume at first that every variable is a constant whose value is not known yet, and that no code runs except the first block. Then follow the program forward. When a block becomes reachable, work out its instructions. When a value becomes known, tell every instruction that reads it. When a branch tests a known value, mark only the side it will take as reachable. A variable only gets less hopeful over time: unknown, then one constant, then "not a constant". So the work ends soon. Code that never becomes reachable is never looked at, and its assignments cannot spoil the constants in the code that does run.
The problem
The input is a program in strict SSA form: every name has one definition, which dominates its uses. The output gives every name a value in the flat constant lattice, and marks the CFG edges and blocks that may run. The analysis uses the meet convention of Kildall: is the start value and the result is a greatest fixed point. Flipping the order gives the join convention of Cousot, with as the start value and a least fixed point; the result is the same.
| item | choice |
|---|---|
| direction | forward, along SSA edges and CFG edges |
| may or must | must: a constant holds on every run that reaches the definition |
| domain | for each SSA name, a value in ; for each CFG edge, executable or not |
| order | , constants pairwise incomparable; for edges, fewer executable edges is higher |
| meet | , for , is the identity |
| and | : no value seen yet; : not a constant |
| boundary | parameters are ; the pseudo edge into the entry is executable |
| initial value | every other name is ; every other edge is not executable |
| transfer functions | monotone; not distributive, as for constant propagation |
| height | 2 per name, 1 per edge |
Lattice and transfer functions. A state is a pair of values and executable edges, ordered by "higher values and fewer edges". An instruction gets : any operand gives , else any operand gives , else the operation runs, and an operation that would trap, such as division by zero, gives . A phi-function in block gets the meet of over the operands whose edge is in . A call gives . A branch br a L1 L2 allows both edges if , only the edge picked by if (nonzero picks L1), and none if .
Equations. The combined map recomputes every value from and , gives to the names of blocks that no edge in reaches, and makes the pseudo edge plus the edges that the terminators of reached blocks allow. is monotone, so by the Knaster-Tarski theorem it has a greatest fixed point. SCCP computes it.
MOP and soundness. The meet-over-all-paths solution is the ideal answer, and as for every constant propagation it is not computable in general. The fixed point found here is sound for real runs: every block a run enters is reachable in the result, every edge it takes is executable, and every value it assigns to a name with a constant result is that constant. The proof file has the details.
Precision. Simple constant propagation is the same analysis with every edge executable, which is the maximal fixed point of the usual framework. SCCP is never below it, and the example below shows a case where it is strictly above it and also above any mix of it with dead branch elimination.
Cost. The cost is for SSA instructions, CFG edges, SSA edges and at most predecessors per block. See the section on complexity.
The algorithm
The analysis needs the SSA form, a list of the uses of each name, and a flag per CFG edge. Both worklists are queues. A CFG edge is put on FlowWL at most once; a set of edges seen before checks that.
SCCP(P) P is in strict SSA form- 1
for each parameter p do V[p] ← ⊥; for each other name x do V[x] ← ⊤ - 2
Exec ← ∅; Visited ← ∅ - 3
FlowWL ← [(start, entry)]; SSAWL ← [] - 4
while FlowWL or SSAWL is not empty do - 5
if FlowWL is not empty then - 6
(p, b) ← remove the first edge of FlowWL - 7
add (p, b) to Exec; VISIT every phi of b - 8
if b ∉ Visited then add b to Visited; VISIT every other instruction of b, then its terminator - 9
else (x, u) ← remove the first SSA edge of SSAWL - 10
if the block of u is in Visited then VISIT(u) VISIT(u), for an instruction or terminator u of block b- 11
if u is x = phi[p1: a1, ...] then new ← ⊓ of V[ai] over the i with (pi, b) ∈ Exec - 12
if u is x = a op c then new ← fold(op, V[a], V[c]) (x = k gives k, a copy gives V[a], a call gives ⊥) - 13
if new ≠ V[x] then V[x] ← new; append (x, w) to SSAWL for each use w of x - 14
if u is br a L1 L2 then: if V[a] = ⊥ then PUSH (b, L1) and (b, L2); if V[a] = c then PUSH the edge that c picks - 15
if u is jump L then PUSH (b, L) return V, Exec, Visited
PUSH appends an edge to FlowWL unless it was appended before. A use at line L13 is a use site: if one instruction reads twice, as in y = x + x, there is one SSA edge, not two.
After the analysis, a rewrite applies the result. Every name with a constant value gets the definition x = c, and every use of it reads c. A branch whose condition is a constant becomes a jump. Blocks outside go away, and so do the phi operands of edges outside . Lemma 6 of the proof shows that no name in a reachable block keeps , so the rewrite never meets a branch with no allowed edge.
Example
This loop sets i = 1, and the only other store to i is in a branch that runs when i is not 1. The parameter is n.
entry:
i = 1
k = 0
jump head
head:
c = i == 1
br c same other
same:
jump latch
other:
i = 2
jump latch
latch:
k = k + 1
t = k < n
br t head exit
exit:
ret i
In pruned SSA form, head gets i.2 = phi [entry: i.1, latch: i.4] and k.2 = phi [entry: k.1, latch: k.3], and latch gets i.4 = phi [same: i.2, other: i.3], where i.3 = 2 is in other. The run:
| step | item taken | what changes | edges pushed |
|---|---|---|---|
| 1 | flow (start, entry) | i.1 = 1, k.1 = 0 | (entry, head) |
| 2 | flow (entry, head) | phis over the one executable edge: i.2 = 1, k.2 = 0; then c.1 = 1 | (head, same) only, since c.1 is the constant 1 |
| 3 | flow (head, same) | nothing | (same, latch) |
| 4 | flow (same, latch) | i.4 = 1 (only the edge from same is executable), k.3 = 1, t.1 = ⊥ |
(latch, head) and (latch, exit) |
| 5 | flow (latch, head) | i.2 stays 1, since 1 ⊓ 1 = 1; k.2 = 0 ⊓ 1 = ⊥ | none |
| 6 | flow (latch, exit) | the ret reads i.4 |
none |
| 7 to 20 | 14 SSA edges | only k.3 changes, from 1 to ⊥ | none |
The edge (head, other) never becomes executable, so i.3 stays and other is never visited. The result has i.2 = i.4 = 1 and c.1 = 1. The rewrite drops other, turns the branch in head into jump same, and ends with ret 1. The run takes 6 flow items and 14 SSA items, and it does 29 visits.
Simple constant propagation counts every edge. It gets i.4 = i.2 ⊓ 2 = ⊥ around the loop, so i.2 = 1 ⊓ ⊥ = ⊥ and c.1 = ⊥. Dead branch elimination needs a literal condition, so it does nothing. Running the two passes again changes nothing, in either order. The value 1 holds on every run, but only an analysis that assumes the branch is dead while it studies the loop can prove it. In a program without loops this gap closes: there the two passes, repeated until nothing changes, reach the same result as SCCP.
Correctness
The full proof is in the proof file. Its steps:
- Φ is monotone. A phi meets fewer operands when fewer edges are executable, is monotone, and a higher condition allows fewer edges. So the greatest fixed point exists.
- Values only go down. Each visit recomputes a value from inputs that only went down, with more executable edges. So every change at line L13 is a strict step down.
- Termination and the bound. The flat lattice has height 2, so a name changes at most twice and each SSA edge enters SSAWL at most twice. Each CFG edge enters FlowWL at most once.
- Nothing above G is lost. The values stay above and stays inside 's edges, because each step is one application of a monotone map to a state above .
- The end is a fixed point. Each input change of an instruction leads to a new visit of it: a new reachable block visits all its instructions, a new edge visits the phis, and a changed operand queues the SSA edge. So at the end every value and every edge agrees with . Steps 4 and 5 give the result .
- Soundness. By induction along a run: the run stays in executable edges, and each value it assigns is described by the value of its name.
- At least as strong as CP and DBE in any order. Every program that a sequence of these passes produces describes a state with , and is the join of all such states.
Proof: Sparse conditional constant propagation computes the greatest fixed point of the combined systemfull
Setting. is a program in strict SSA form: every name has exactly one definition , in block , and that definition dominates every use of (for a phi operand, the use is at the end of the predecessor). The entry block has no predecessor. is the flat lattice for every integer ; its height is 2. , and give the concrete values that a lattice value describes. is a pseudo edge. A state is a pair : maps every name to , and is a set of CFG edges together with . is the set of blocks with some . States are ordered by
A higher state knows more: higher values and fewer edges. The states form a finite complete lattice, with top .
For an instruction in block , is its abstract value: for a phi, the meet of over the operands with (the empty meet is ); for , the constant ; for a copy of , ; for , , where any operand gives , else any gives , else the operation runs and a trap gives ; for a call, . An int operand has the value . is the set of successors that the terminator of may take: both targets of br a L1 L2 when , none when , and only L1 (if ) or only L2 (if ) when ; the target of a jump; none for ret. The combined map is with
- for each parameter ; if , and otherwise;
- .
We use the lines L1 to L15 of the pseudocode.
Lemma 1 (Φ is monotone). If then .
Proof. From we get . Take a name . If , the right side gives , which is above anything. Otherwise is in both sets. A phi meets fewer operands under than under , and each operand value is higher in , so its value under is higher. is monotone in each operand: going up from to to gives , then a constant or , then . So . For the edges, is antitone: a higher condition value allows fewer targets ( allows two, one, none). With this gives .
By the Knaster-Tarski theorem, has a greatest fixed point , and is the join of all states with .
Lemma 2 (values only go down). Every assignment to at line L13 replaces the old value by a value strictly below it.
Proof. Only the visits of write . Line L13 writes only when the new value differs from the old one. Use induction over time. The first write replaces , and any other value is below . For a later write, compare the current visit of with the visit that made the previous write. By the induction hypothesis no value went up in between, and only grows. Since is monotone in and antitone in (Lemma 1), the new value is below or equal to the old one, and it differs, so it is strictly below.
Lemma 3 (termination and the bounds). Each name changes at most twice. Each SSA edge is put on SSAWL at most twice and taken off at most twice. Each CFG edge is put on FlowWL at most once. So the main loop runs at most times, where is the number of CFG edges and the number of SSA edges.
Proof. By Lemma 2 the values of form a strictly falling chain in , which has height 2, so there are at most two changes. Line L13 puts on SSAWL once per change of . FlowWL takes an edge only if it was never put there before. Each turn of the loop at line L4 removes one item from one list.
Lemma 4 (the state stays above ). At all times for every and .
Proof. Induction over time. At line L1 the parameters get and every other name gets ; is empty. Every edge on FlowWL is in : is in ; any other edge was put there by the visit of the terminator of a block , with for the values of that moment. Those values are above , and is antitone, so and 's edge set, which is . So line L7 keeps . A write at line L13 stores for a block in ; by Lemma 1 this is above .
Lemma 5 (the final state is a fixed point). When both lists are empty, and .
Proof. A block enters exactly when the first edge into it is taken at line L7, so . Take an instruction in a block . Its value under depends on at its operands and, for a phi, on the edges into in . Each of these inputs changes only at a moment that leads to a new visit of : when enters , line L8 visits every instruction of ; when an edge into joins , line L7 visits every phi of ; when an operand changes, line L13 puts on SSAWL, and since from then on, line L10 visits when that item comes off. So the last visit of came after the last change of its inputs, and . A name whose block is not in is never visited, so it keeps , as asks. The same argument for the terminator of shows that its last visit saw the final value of its condition, so every edge of was put on FlowWL and is now in . Conversely, each edge in other than was put there for values above the final ones, and is antitone, so it is in for the final . So is exactly the edge set of .
Theorem 1 (correctness). SCCP terminates and returns , the greatest fixed point of .
Proof. Lemma 3 gives termination. By Lemma 5 the result is a fixed point, so it is below the greatest fixed point . By Lemma 4 it is above .
Lemma 6 (nothing reachable stays ⊤). In , every name defined in a block of has a value below . The same holds for the greatest fixed point of any CP pass below, whose blocks are all reachable.
Proof. Order the blocks of by the first time SCCP takes an edge into them, and the instructions of a block by position. Use induction on this order. A phi in has an operand along the first edge that SCCP took. was reached before , so and is not dominated by ; the definition of the operand dominates the end of , so it lies in a block reached before (or is a parameter or an int). By induction its value is below , and a meet with it stays below . Any other instruction reads names defined earlier in or in blocks that strictly dominate , which are reached before ; operands below give a value below .
So in the result of SCCP, the condition of every reachable branch is a constant or , and the rewrite never meets a .
Theorem 2 (soundness). Let a run of on any arguments assign the value to a name . Then . Every block the run enters is in , and every edge it takes is in .
Proof. Induction on the steps of the run. The run starts at the entry along , and the parameters have . When the run executes in a block , the induction hypothesis says and the edge it came by is in . Every operand that reads holds the value assigned at the last run of , because has only one definition, and by hypothesis that value is in . For a phi, the run reads the operand of the edge it came by; , so and . For : if both operand values are constants, they are the run's values and computes the same result (if the operation traps, the run stops there). Otherwise some operand value is (it is not , since is empty), and gives . At a branch on with run value : if both edges are in ; if then and the edge that picks is in .
So the rewrite is safe: it replaces a name by a constant only where every run computes that constant, and it removes only blocks and edges that no run reaches.
Theorem 3 (at least as strong as any order of CP and DBE). A CP pass runs simple constant propagation on the current program, counting every remaining edge, and replaces each name with a constant value by that constant (both its definition and its uses; a branch keeps its form with a literal condition). A DBE pass turns each branch on a literal into a jump, then removes the blocks that the entry no longer reaches and the phi operands of the removed edges. Let be the program after any finite sequence of such passes, applied to . Then every block of is still in , and every name that defines as a constant has .
Proof. Describe a program by the state : is plus the edges of (each one is an edge of ); if defines as the constant , if is not in , and otherwise. The claim says . Since is the join of all post-fixed points, it is enough to show for every in the sequence. Two facts hold by induction along the sequence. (a) Every block of is reachable in : has no unreachable block, CP removes no edge, and DBE removes the blocks it cuts off. So is the block set of . (b) The known constants only grow: a CP pass keeps every constant definition, because each one is a fixed point of its own equation; and DBE removes a constant definition only together with its block.
Edges. Take a block of . If its terminator in is a branch, both edges are in , and is a subset of them. If it is a jump made by DBE from a branch on , then DBE saw a literal , which CP wrote because then defined as ; by (b) still, so is the one target of the jump. Other jumps and returns are as in . So has no edge outside .
Values. If is or is a parameter, there is nothing to show. If is not in , then and gives as well. Otherwise defines as , and a CP pass on an earlier program found the value for as the greatest fixed point of simple constant propagation on , with . In that fixed point every operand of that reaches by an edge of had a value below (Lemma 6 applied to ), so it was a constant (an operand with value would make give , and a phi with a operand gives ). That CP pass made each of those operands a constant definition, so by (b) gives each of them the same constant. Now reads the same constants, over a subset of the phi operands; it is , or for an empty meet. Either way it is above .
Proposition 4 (without loops the gap closes). If the CFG of has no cycle, every sequence of CP and DBE passes that runs until neither pass changes the program ends with .
Proof. At the end, CP finds no new constant, so on the blocks of the values are the greatest fixed point of simple constant propagation over , with for the rest; and DBE finds no literal branch, so each remaining branch has a condition of value (Lemma 6 rules out ). Then : the edges agree because a branch on allows both targets, and the values agree because they solve the same equations. Now show that an acyclic has only one fixed point of . Take the blocks in a topological order. Whether a block is in depends only on the terminators and the values of earlier blocks; the value of a name depends only on names defined earlier in the same block, in dominating blocks, or at the ends of predecessors, all of which come earlier in the order. So the fixed point equations fix every component one after the other, and .
With a loop the equations can have several fixed points, and the passes can stop at a lower one. The example on the page is such a case: simple constant propagation sees i = 2 flow around the loop, so it never makes the branch literal, while SCCP never takes the edge into the block that sets i = 2.
Complexity
- Worklist items. At most flow items and SSA items.
- Visits. Each instruction is visited once when its block first becomes reachable. A phi is visited again for each new executable edge into its block and for each SSA item that reaches it. A visit of an ordinary instruction costs ; a visit of a phi costs , because it meets its operands again. So all visits cost . Wegman and Zadeck (Section 5.4) show how to do all the recomputations of one expression in time proportional to its size, which gives .
- Space. The values, the use lists, the edge flags and the two lists: .
- Best case. Building the use lists reads the whole program, , even when a constant branch at the entry makes most of the program unreachable.
- SSA form. The SSA form can be larger than the program. The number of phi-functions can grow quadratically in the worst case, so and are sizes of the SSA form, not of the source program.
The table below is measured, not proved. For each number of blocks , it averages 50 random looping programs of the toy IR with 6 variables, made with the seed and put in pruned SSA form.
| blocks | SSA instructions | SSA edges | CFG edges | SSA items taken | flow items taken | visits | most pushes of one SSA edge |
|---|---|---|---|---|---|---|---|
| 8 | 34.6 | 46.1 | 10.2 | 50.4 | 9.3 | 93.0 | 2 |
| 16 | 74.0 | 111.4 | 22.2 | 113.9 | 16.2 | 192.8 | 2 |
| 32 | 153.1 | 253.0 | 46.0 | 268.9 | 29.5 | 429.4 | 2 |
| 64 | 376.9 | 694.5 | 96.1 | 775.1 | 57.3 | 1197.4 | 2 |
The SSA items stay close to , well below the bound , and the flow items stay below because some edges never become executable.
Properties
- Optimistic. It starts from and assumes the best until the program proves otherwise. This is why it can find constants that flow around a loop. A pessimistic method starts from and must stop at a lower fixed point.
- Order-free result. The result is the greatest fixed point of , so any order of the two lists gives the same values and edges. Only the amount of work changes.
- Sparse. Values travel along SSA edges, from definition to use, and not through every block in between. The dense versions keep one value per variable per block, which costs a factor of the number of variables more.
- Deterministic and iterative. For a fixed input and fixed queues the run is fixed. It uses no recursion.
- Strictly stronger than the parts. On the example, no sequence of constant propagation and dead branch elimination finds
i = 1, but SCCP does.
Variants and improvements
- Sparse simple constant propagation. Treat every edge as executable. This finds the same constants as Kildall's dense method, faster. Wegman and Zadeck call it SSC and credit it to Reif and Lewis.
- Dense conditional constant propagation. Keep the executable flags but run on the CFG with one value per variable per block. Wegman and Zadeck call it CC, a variant of an algorithm of Wegbreit. It finds the same constants as SCCP, more slowly.
- Combined analyses. Click and Cooper studied this pattern in general: two optimistic analyses solved as one system can beat any sequence of the two separate passes. SCCP is the classic case. The same idea combines constant propagation with global value numbering.
- Richer lattices. The flat lattice can be replaced by any lattice of finite height, such as known bits or small sets of values. A lattice of infinite height, such as ranges, needs a way to force the values down fast enough.
- Branch facts. On the edge where
x == 5is true,xis 5. Wegman and Zadeck describe inserting assignments on such edges so that the analysis can use the fact. - Across procedures. Wegman and Zadeck also give an interprocedural version. See interprocedural constant propagation, and the IDE framework for a version that summarizes procedures.
When to use it
Use SCCP in a compiler that already has SSA form. It is cheap, it folds constants and removes dead branches in one pass, and its result then feeds dead code elimination, because the definitions it turns into constants often have no uses left. Production compilers built on SSA form, such as LLVM and GCC, include a pass of this kind. If the program is not in SSA form and you need only a quick result, constant folding inside each block, or the dense worklist algorithm, may be enough.
Pitfalls
- Visiting unreachable code. Line L10 must skip a use whose block is not in . If it does not, the values from dead code spoil the phis, and the algorithm is no stronger than simple constant propagation.
- Phis must ignore dead edges. Line L11 meets only the operands of executable edges. Meeting all operands loses the whole benefit.
- Starting pessimistic. If every name starts at , or if a phi waits until all its operands are known, constants that flow around a loop are lost. Wegman and Zadeck point out that many older sparse methods worked this way.
- Names read before they are defined. If a reachable instruction reads a name that has no definition on some path, its value can stay , and a branch on it then makes no edge executable. Code that does run would then be marked dead. Give such names an explicit definition first; the implementation here adds
v.0 = 0at the entry. - Folding a trap.
x = 7 / 0must give , not a value, and the instruction must stay in the program, because it traps when it runs. - One SSA edge per use site. If
y = x + xadds two SSA edges forx, each change ofxqueuesytwice, and the bound of two items per SSA edge no longer holds in that form. - Def-use chains without SSA. Running the same sparse method on def-use chains of a program that is not in SSA form loses precision, because one use can then see several definitions that SSA would have merged by a phi in the right place.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-conditional-constant-propagation/. The authors are listed in prov/WNK50T.jsonl.
"""Sparse conditional constant propagation (Wegman and Zadeck) on the toy IR.
The analysis runs on SSA form. to_ssa builds pruned SSA form by the method
of Cytron et al.: phi-functions at the iterated dominance frontier of the
blocks that assign a variable, kept only where the variable is live, then
renaming by a walk of the dominator tree. The k-th definition of v is named
v.k, and a parameter keeps its own name for its value on entry.
The lattice is flat, in the meet convention: TOP (no value seen yet) is the
start value, an int is a constant, BOT means "not a constant". sccp keeps
two worklists, one of CFG edges and one of SSA edges, and evaluates an
instruction only when its block is reachable through executable edges.
rewrite applies the result: it folds constants, turns a branch on a known
condition into a jump, and drops the blocks that no executable edge reaches.
"""
from collections import Counter, deque
import toyir
from toyir import Block, Program
TOP = "top" # no value seen yet
BOT = "bot" # not a constant
def is_const(v):
return isinstance(v, int)
def meet(a, b):
if a == TOP:
return b
if b == TOP or a == b:
return a
return BOT
def fold(op, a, b):
"""The abstract value of a op b. Any TOP operand gives TOP, else any BOT
operand gives BOT, else the operation runs; an operation that traps
gives BOT, because the instruction must stay in the program."""
if a == TOP or b == TOP:
return TOP
if a == BOT or b == BOT:
return BOT
try:
return toyir._binop(op, a, b)
except toyir._Trap:
return BOT
# ------------------------------------------------------------ SSA construction
def _reachable_order(succ, root):
"""Postorder of the blocks that root reaches."""
seen = {root}
out = []
stack = [(root, iter(succ[root]))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
stack.pop()
out.append(v)
elif w not in seen:
seen.add(w)
stack.append((w, iter(succ[w])))
return out
def immediate_dominators(succ, root):
"""Cooper, Harvey and Kennedy. Only the blocks that root reaches are keys."""
order = _reachable_order(succ, root)
po = {v: i for i, v in enumerate(order)}
pred = {v: [] for v in order}
for v in order:
for w in succ[v]:
pred[w].append(v)
doms = {root: root}
def intersect(a, b):
while a != b:
while po[a] < po[b]:
a = doms[a]
while po[b] < po[a]:
b = doms[b]
return a
changed = True
while changed:
changed = False
for b in reversed(order):
if b == root:
continue
new = None
for p in pred[b]:
if p in doms:
new = p if new is None else intersect(p, new)
if doms.get(b) != new:
doms[b] = new
changed = True
idom = dict(doms)
idom[root] = None
return idom
def dominance_frontiers(succ, idom):
pred = {v: [] for v in idom}
for v in idom:
for w in succ[v]:
pred[w].append(v)
df = {v: set() for v in idom}
for y in idom:
for p in pred[y]:
runner = p
while runner != idom[y] and y not in df[runner]:
df[runner].add(y)
runner = idom[runner]
return df
def live_in(prog, labels, succ):
"""The variables that are live on entry to each block (backward round robin)."""
gen, kill = {}, {}
for b in labels:
g, k = set(), set()
for ins in prog.blocks[b].instrs:
g |= {a for a in toyir.uses(ins) if a not in k}
k.add(ins[1])
g |= {a for a in toyir.term_uses(prog.blocks[b].term) if a not in k}
gen[b], kill[b] = g, k
live = {b: set() for b in labels}
changed = True
while changed:
changed = False
for b in reversed(labels):
out = set()
for s in succ[b]:
out |= live[s]
new = gen[b] | (out - kill[b])
if new != live[b]:
live[b] = new
changed = True
return live
def to_ssa(prog):
"""Pruned SSA form with the same runs. The unreachable blocks are dropped.
A name that some path reads before any definition gets v.0 = 0 at the top
of the entry, so the result is strict."""
succ = {b: toyir.succs(prog, b) for b in prog.blocks}
root = prog.entry
for b in prog.blocks.values():
for ins in b.instrs:
if ins[0] not in ("const", "copy", "op", "call"):
raise ValueError("unsupported instruction: %r" % (ins,))
if "." in ins[1]:
raise ValueError("names must not contain a dot: %r" % ins[1])
idom = immediate_dominators(succ, root)
labels = [b for b in prog.blocks if b in idom]
if any(root in succ[b] for b in labels):
raise ValueError("the entry must have no predecessor")
df = dominance_frontiers(succ, idom)
live = live_in(prog, labels, succ)
sites = {}
for p in prog.params:
sites.setdefault(p, {root})
for b in labels:
for ins in prog.blocks[b].instrs:
sites.setdefault(ins[1], set()).add(b)
phis = {b: [] for b in labels}
for v, s in sites.items():
has_phi, work = set(), list(s)
while work:
x = work.pop()
for y in df[x]:
if y not in has_phi and v in live[y]:
has_phi.add(y)
phis[y].append(v)
work.append(y)
children = {b: [] for b in labels}
for b in labels:
if idom[b] is not None:
children[idom[b]].append(b)
counter = Counter()
stacks = {v: [] for v in sites}
for p in prog.params:
stacks[p].append(p)
undefined = []
def top(v):
if stacks.get(v):
return stacks[v][-1]
name = v + ".0"
if name not in undefined:
undefined.append(name)
return name
def operand(a):
return top(a) if isinstance(a, str) else a
def fresh(v):
counter[v] += 1
name = "%s.%d" % (v, counter[v])
stacks[v].append(name)
return name
phi_args = {b: [{} for _ in phis[b]] for b in labels}
phi_names = {b: [] for b in labels}
out = {}
def rename(b):
pushed = []
for v in phis[b]:
phi_names[b].append(fresh(v))
pushed.append(v)
instrs = []
for ins in prog.blocks[b].instrs:
if ins[0] == "const":
new = ("const", None, ins[2])
elif ins[0] == "copy":
new = ("copy", None, operand(ins[2]))
elif ins[0] == "op":
new = ("op", None, ins[2], operand(ins[3]), operand(ins[4]))
else:
new = ("call", None, ins[2], [operand(a) for a in ins[3]])
instrs.append(new[:1] + (fresh(ins[1]),) + new[2:])
pushed.append(ins[1])
t = prog.blocks[b].term
if t[0] == "br":
t = ("br", operand(t[1]), t[2], t[3])
elif t[0] == "ret":
t = ("ret", operand(t[1]))
for s in succ[b]:
for v, args in zip(phis[s], phi_args[s]):
args[b] = top(v)
out[b] = (instrs, t)
for c in children[b]:
rename(c)
for v in pushed:
stacks[v].pop()
rename(root)
preds = {b: [p for p in labels if b in succ[p]] for b in labels}
blocks = {}
for b in labels:
instrs, t = out[b]
head = [("phi", x, {p: args[p] for p in preds[b]}) for x, args in zip(phi_names[b], phi_args[b])]
if b == root:
head = [("const", name, 0) for name in undefined] + head
blocks[b] = Block(head + instrs, t)
return Program(list(prog.params), blocks)
# ------------------------------------------------------------------- SCCP
def sccp(prog):
"""Analyse a program in SSA form. Returns (value, executable, visited,
stats): the lattice value of every name, the executable CFG edges (the
pseudo edge (None, entry) included), the reachable blocks, and counters.
stats["ssa_pushes"] counts how often each SSA edge (name, use site) was
put on the SSA worklist; stats["changes"] counts how often each value
went down."""
blocks = prog.blocks
uses_of = {}
value = {p: BOT for p in prog.params} # @line L1
for b, blk in blocks.items():
for i, ins in enumerate(blk.instrs):
if ins[1] in value:
raise ValueError("not in SSA form: %r has two definitions" % ins[1])
value[ins[1]] = TOP # @line L1
for a in set(toyir.uses(ins)): # one SSA edge per (name, use site)
uses_of.setdefault(a, []).append((b, i))
for a in toyir.term_uses(blk.term):
uses_of.setdefault(a, []).append((b, None))
executable, visited, pushed = set(), set(), set() # @line L2
flow = deque([(None, prog.entry)]) # @line L3
pushed.add((None, prog.entry))
ssa = deque()
stats = {"ssa_pushes": Counter(), "changes": Counter(), "flow_pops": 0, "ssa_pops": 0, "evals": 0}
def val(a):
return a if isinstance(a, int) else value[a]
def add_edge(e):
if e not in pushed:
pushed.add(e)
flow.append(e)
def evaluate(b, i):
stats["evals"] += 1
if i is None:
t = blocks[b].term
if t[0] == "jump":
add_edge((b, t[1])) # @line L15
elif t[0] == "br":
c = val(t[1])
if c == BOT:
add_edge((b, t[2])) # @line L14
add_edge((b, t[3]))
elif c != TOP:
add_edge((b, t[2] if c != 0 else t[3])) # @line L14
return
ins = blocks[b].instrs[i]
k, x = ins[0], ins[1]
if k == "phi":
new = TOP
for p, a in ins[2].items():
if (p, b) in executable:
new = meet(new, val(a)) # @line L11
elif k == "const":
new = ins[2]
elif k == "copy":
new = val(ins[2])
elif k == "op":
new = fold(ins[2], val(ins[3]), val(ins[4])) # @line L12
else:
new = BOT # a call: nothing is known about its result
if new != value[x]: # @line L13
value[x] = new
stats["changes"][x] += 1
for s in uses_of.get(x, ()):
stats["ssa_pushes"][(x, s)] += 1
ssa.append((x, s))
while flow or ssa: # @line L4
if flow: # @line L5
e = flow.popleft() # @line L6
stats["flow_pops"] += 1
p, b = e
executable.add(e) # @line L7
first = b not in visited
visited.add(b)
for i, ins in enumerate(blocks[b].instrs):
if ins[0] == "phi" or first: # @line L7
evaluate(b, i) # @line L8
if first:
evaluate(b, None) # @line L8
else:
x, (b, i) = ssa.popleft() # @line L9
stats["ssa_pops"] += 1
if b in visited:
evaluate(b, i) # @line L10
return value, executable, visited, stats
def rewrite(prog, value, executable, visited):
"""Apply an SCCP result: names with a constant value become constants, a
branch on a constant becomes a jump, unreachable blocks and the phi
operands of non-executable edges go away."""
def opnd(a):
if isinstance(a, str) and is_const(value[a]):
return value[a]
return a
blocks = {}
for b, blk in prog.blocks.items():
if b not in visited:
continue
phis, folded, rest = [], [], []
for ins in blk.instrs:
k, x = ins[0], ins[1]
if k != "call" and is_const(value[x]):
(folded if k == "phi" else rest).append(("const", x, value[x]))
elif k == "phi":
phis.append(("phi", x, {p: opnd(a) for p, a in ins[2].items() if (p, b) in executable}))
elif k == "copy":
rest.append(("copy", x, opnd(ins[2])))
elif k == "op":
rest.append(("op", x, ins[2], opnd(ins[3]), opnd(ins[4])))
else:
rest.append(("call", x, ins[2], [opnd(a) for a in ins[3]]))
t = blk.term
if t[0] == "br":
c = opnd(t[1])
if is_const(c):
t = ("jump", t[2] if c != 0 else t[3])
else:
t = ("br", c, t[2], t[3])
elif t[0] == "ret":
t = ("ret", opnd(t[1]))
blocks[b] = Block(phis + folded + rest, t)
return Program(list(prog.params), blocks)
def sparse_conditional_constant_propagation(prog):
"""SSA construction, analysis and rewrite in one call. Returns the
optimised SSA program and the lattice value of every SSA name."""
ssa = to_ssa(prog)
value, executable, visited, _ = sccp(ssa)
return rewrite(ssa, value, executable, visited), value
toyir.py 602 lines
# 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)
test_sparse_conditional_constant_propagation.py 446 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-conditional-constant-propagation/. The authors are listed in prov/WNK50T.jsonl.
import random
import toyir
from toyir import Block, Program, edges, parse, random_program, run, show, succs
from sparse_conditional_constant_propagation import (
BOT,
TOP,
fold,
is_const,
meet,
rewrite,
sccp,
sparse_conditional_constant_propagation,
to_ssa,
)
# The example of the page: the branch that sets i = 2 never runs, but only
# a method that ignores it while it looks at the loop can see that.
LOOP = """
# params: n
entry:
i = 1
k = 0
jump head
head:
c = i == 1
br c same other
same:
jump latch
other:
i = 2
jump latch
latch:
k = k + 1
t = k < n
br t head exit
exit:
ret i
"""
# A branch on a constant: simple constant propagation alone gives y = BOT.
KNOWN = """
# params: a
entry:
x = 1
c = x == 1
br c then else
then:
y = 2
jump join
else:
y = a
jump join
join:
z = y + 1
ret z
"""
# ------------------------------------------------ shared abstract semantics
def evaluate(ins, V, live):
"""The value of one instruction under the values V, where a phi reads
only the operands of the predecessors p with live(p) true."""
k = ins[0]
def val(a):
return a if isinstance(a, int) else V[a]
if k == "phi":
new = TOP
for p, a in ins[2].items():
if live(p):
new = meet(new, val(a))
return new
if k == "const":
return ins[2]
if k == "copy":
return val(ins[2])
if k == "op":
return fold(ins[2], val(ins[3]), val(ins[4]))
return BOT
def allowed(prog, b, V):
"""The successors that the terminator of b may take under V."""
t = prog.blocks[b].term
if t[0] == "br":
c = t[1] if isinstance(t[1], int) else V[t[1]]
if c == TOP:
return []
if c != BOT:
return [t[2] if c != 0 else t[3]]
return succs(prog, b)
def initial(prog):
V = {p: BOT for p in prog.params}
for blk in prog.blocks.values():
for ins in blk.instrs:
V[ins[1]] = TOP
return V
def naive_gfp(prog):
"""Iterate the combined map Phi(V, E) from (all TOP, no edge) until it
stops: E grows by the edges the terminators allow, V goes down."""
V = initial(prog)
E = {(None, prog.entry)}
while True:
R = {b for _, b in E}
newE = {(None, prog.entry)} | {(b, s) for b in R for s in allowed(prog, b, V)}
newV = dict(V)
for b, blk in prog.blocks.items():
for ins in blk.instrs:
newV[ins[1]] = evaluate(ins, V, lambda p, b=b: (p, b) in E) if b in R else TOP
if newV == V and newE == E:
return V, E
V, E = newV, newE
# --------------------------------------- simple constant propagation and DBE
def cp_values(prog):
"""Simple constant propagation on SSA form: every edge counts."""
V = initial(prog)
changed = True
while changed:
changed = False
for blk in prog.blocks.values():
for ins in blk.instrs:
new = evaluate(ins, V, lambda p: True)
if new != V[ins[1]]:
V[ins[1]] = new
changed = True
return V
def cp_pass(prog):
"""Replace every name with a constant value by the constant. A branch
keeps its form, with a literal condition."""
V = cp_values(prog)
def opnd(a):
return V[a] if isinstance(a, str) and is_const(V[a]) else a
blocks = {}
for b, blk in prog.blocks.items():
phis, folded, rest = [], [], []
for ins in blk.instrs:
k, x = ins[0], ins[1]
if is_const(V[x]):
(folded if k == "phi" else rest).append(("const", x, V[x]))
elif k == "phi":
phis.append(("phi", x, {p: opnd(a) for p, a in ins[2].items()}))
elif k == "copy":
rest.append(("copy", x, opnd(ins[2])))
else:
rest.append(("op", x, ins[2], opnd(ins[3]), opnd(ins[4])))
t = blk.term
if t[0] in ("br", "ret"):
t = (t[0], opnd(t[1])) + t[2:]
blocks[b] = Block(phis + folded + rest, t)
return Program(list(prog.params), blocks)
def dbe_pass(prog):
"""Dead branch elimination: a branch on a literal becomes a jump, then
the blocks that the entry no longer reaches and their phi operands go."""
terms = {}
for b, blk in prog.blocks.items():
t = blk.term
if t[0] == "br" and isinstance(t[1], int):
t = ("jump", t[2] if t[1] != 0 else t[3])
terms[b] = t
tmp = Program(list(prog.params), {b: Block([], terms[b]) for b in prog.blocks})
seen, stack = {prog.entry}, [prog.entry]
while stack:
for s in succs(tmp, stack.pop()):
if s not in seen:
seen.add(s)
stack.append(s)
live_edges = {e for e in edges(tmp) if e[0] in seen}
blocks = {}
for b, blk in prog.blocks.items():
if b not in seen:
continue
instrs = []
for ins in blk.instrs:
if ins[0] == "phi":
ins = ("phi", ins[1], {p: a for p, a in ins[2].items() if (p, b) in live_edges})
instrs.append(ins)
blocks[b] = Block(instrs, terms[b])
return Program(list(prog.params), blocks)
def cp_dbe_fixpoint(prog, order):
"""Apply the passes in the given order (a string over "C" and "D", then
repeated) until neither pass changes the program."""
passes = {"C": cp_pass, "D": dbe_pass}
quiet = set()
i = 0
while len(quiet) < 2:
name = order[i % len(order)]
new = passes[name](prog)
if show(new) == show(prog):
quiet.add(name)
else:
quiet = set()
prog = new
i += 1
return prog
# ---------------------------------------------------------- concrete runs
def trace(prog, args, fuel=5000):
"""Run an SSA program. Returns (outcome, assignments, blocks, edges)."""
env = dict(zip(prog.params, args))
assigned, blocks, taken = [], set(), set()
label, prev = prog.entry, None
try:
while fuel > 0:
blocks.add(label)
taken.add((prev, label))
blk = prog.blocks[label]
incoming = []
for ins in blk.instrs:
fuel -= 1
def val(a):
return a if isinstance(a, int) else env[a]
if ins[0] == "phi":
incoming.append((ins[1], val(ins[2][prev])))
continue
for x, v in incoming:
env[x] = v
assigned.append((x, v))
incoming = []
if ins[0] == "const":
v = ins[2]
elif ins[0] == "copy":
v = val(ins[2])
else:
v = toyir._binop(ins[2], val(ins[3]), val(ins[4]))
env[ins[1]] = v
assigned.append((ins[1], v))
for x, v in incoming:
env[x] = v
assigned.append((x, v))
t = blk.term
if t[0] == "ret":
return ("ret", t[1] if isinstance(t[1], int) else env[t[1]]), assigned, blocks, taken
prev = label
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]
return ("fuel",), assigned, blocks, taken
except toyir._Trap:
return ("trap",), assigned, blocks, taken
def arg_list(rng):
fixed = [(0, 0), (1, 0), (0, 1), (2, 3), (3, -1), (5, 5)]
return fixed + [(rng.randint(-6, 6), rng.randint(-6, 6)) for _ in range(4)]
# ------------------------------------------------------------------ checks
def check_fixed_point(prog, value, executable, visited):
"""(value, executable) is a fixed point of the combined map."""
entry_edge = (None, prog.entry)
assert {b for _, b in executable} == visited
want = {entry_edge} | {(b, s) for b in visited for s in allowed(prog, b, value)}
assert executable == want
for b, blk in prog.blocks.items():
for ins in blk.instrs:
if b in visited:
assert value[ins[1]] == evaluate(ins, value, lambda p, b=b: (p, b) in executable)
assert value[ins[1]] != TOP # strict SSA: nothing reachable stays TOP
else:
assert value[ins[1]] == TOP
def check_bounds(prog, value, executable, stats):
nedges = len(edges(prog)) + 1
assert stats["flow_pops"] == len(executable) <= nedges
assert all(c <= 2 for c in stats["changes"].values())
assert all(c <= 2 for c in stats["ssa_pushes"].values())
ssa_edges = 0
for blk in prog.blocks.values():
ssa_edges += sum(len(set(toyir.uses(ins))) for ins in blk.instrs) + len(toyir.term_uses(blk.term))
assert stats["ssa_pops"] == sum(stats["ssa_pushes"].values()) <= 2 * ssa_edges
def check_sound(ssa, value, executable, visited, args):
out, assigned, blocks, taken = trace(ssa, args)
for x, v in assigned:
assert value[x] == BOT or value[x] == v, (x, value[x], v)
assert blocks <= visited
assert taken <= executable
return out
def compare_with_cp_dbe(ssa, value, visited):
"""SCCP knows at least what any order of CP and DBE steps knows.
Returns True when SCCP knows strictly more."""
win = False
for order in ("CD", "DC", "CCD", "DDC"):
res = cp_dbe_fixpoint(ssa, order)
assert visited <= set(res.blocks)
known = {}
for blk in res.blocks.values():
for ins in blk.instrs:
if ins[0] == "const":
known[ins[1]] = ins[2]
for x, k in known.items():
assert value[x] == TOP or value[x] == k
sccp_known = {x for x, v in value.items() if v != BOT}
defined = {ins[1] for blk in res.blocks.values() for ins in blk.instrs}
if visited < set(res.blocks) or (sccp_known & defined) - set(known):
win = True
return win, res
# -------------------------------------------------------------------- tests
def test_loop_example() -> None:
prog = parse(LOOP)
ssa = to_ssa(prog)
value, executable, visited, stats = sccp(ssa)
check_fixed_point(ssa, value, executable, visited)
assert "other" not in visited
head_phi = [ins for ins in ssa.blocks["head"].instrs if ins[0] == "phi" and ins[1].startswith("i.")]
assert len(head_phi) == 1 and value[head_phi[0][1]] == 1
assert ssa.blocks["exit"].term[0] == "ret" and value[ssa.blocks["exit"].term[1]] == 1
new, _ = sparse_conditional_constant_propagation(prog)
assert "other" not in new.blocks and new.blocks["exit"].term == ("ret", 1)
for n in range(-2, 6):
assert run(prog, [n]) == run(new, [n]) == ("ret", 1)
# Simple CP and DBE, in any order, keep i as BOT: SCCP wins.
win, res = compare_with_cp_dbe(ssa, value, visited)
assert win and "other" in res.blocks
cp = cp_values(ssa)
assert cp[head_phi[0][1]] == BOT
def test_known_branch() -> None:
prog = parse(KNOWN)
ssa = to_ssa(prog)
value, executable, visited, _ = sccp(ssa)
assert visited == {"entry", "then", "join"}
z = ssa.blocks["join"].term[1]
assert value[z] == 3
cp = cp_values(ssa)
assert cp[z] == BOT # simple CP alone meets 2 with a
win, res = compare_with_cp_dbe(ssa, value, visited)
assert not win # here CP then DBE then CP reaches the same result
assert res.blocks["join"].term == ("ret", 3)
def test_lattice_and_fold() -> None:
assert meet(TOP, 4) == 4 and meet(4, 4) == 4 and meet(4, 5) == BOT
assert meet(BOT, TOP) == BOT
assert fold("+", TOP, BOT) == TOP and fold("*", BOT, 0) == BOT
assert fold("/", 7, 0) == BOT and fold("<<", 1, 64) == BOT
assert fold("/", -7, 2) == -3 and fold("%", -7, 2) == -1
def random_cases(seed, count, acyclic):
rng = random.Random(seed)
for _ in range(count):
prog = random_program(rng, 6, 8, acyclic)
yield rng, prog
def test_random_programs() -> None:
wins = 0
total = 0
for acyclic in (True, False):
for rng, prog in random_cases(11 if acyclic else 12, 150, acyclic):
ssa = to_ssa(prog)
value, executable, visited, stats = sccp(ssa)
check_fixed_point(ssa, value, executable, visited)
check_bounds(ssa, value, executable, stats)
assert naive_gfp(ssa) == (value, executable)
new = rewrite(ssa, value, executable, visited)
win, res = compare_with_cp_dbe(ssa, value, visited)
# Without loops the combined map has one fixed point, so the
# passes reach the SCCP result; a strict win needs a loop.
assert not (acyclic and win)
wins += win
total += 1
for args in arg_list(rng):
want = run(prog, list(args))
assert want[0] != "fuel"
assert run(ssa, list(args)) == want
assert run(new, list(args)) == want
assert run(res, list(args)) == want
assert check_sound(ssa, value, executable, visited, args) == want
assert wins >= 5, wins
def test_strict_wins_with_constant_branches() -> None:
"""Programs whose branches test constants: SCCP is never worse than any
CP and DBE order, and it is strictly better on some of them."""
rng = random.Random(21)
wins = 0
for _ in range(120):
prog = random_program(rng, 6, 8, False)
for blk in prog.blocks.values():
t = blk.term
if t[0] == "br" and t[1] in ("x0", "x1") and rng.random() < 0.7:
blk.term = ("br", rng.choice(["x2", "x3", "x4", "x5"]), t[2], t[3])
ssa = to_ssa(prog)
value, executable, visited, stats = sccp(ssa)
check_bounds(ssa, value, executable, stats)
win, res = compare_with_cp_dbe(ssa, value, visited)
wins += win
for args in arg_list(rng)[:4]:
want = run(prog, list(args))
assert run(res, list(args)) == want
assert check_sound(ssa, value, executable, visited, args) == want
assert wins >= 3, wins
def test_ssa_form() -> None:
rng = random.Random(5)
for _ in range(60):
prog = random_program(rng, 5, 7, False)
ssa = to_ssa(prog)
names = [ins[1] for blk in ssa.blocks.values() for ins in blk.instrs]
assert len(names) == len(set(names))
assert all("." in x for x in names)
assert set(ssa.blocks) == set(prog.blocks)
History
Kildall (1973) gave an early general iterative method for constant propagation. Wegbreit (1975) gave a dense algorithm that also tracks which branches may run. Reif and Lewis gave a sparse method for simple constants. Wegman and Zadeck (POPL 1985; TOPLAS 1991) put the four methods side by side: simple, sparse simple, conditional, and their new sparse conditional algorithm. They proved that it is conservative and that it finds at least the constants of the dense conditional method, and they noted that each SSA edge is examined at most twice. The SSA form it runs on was made practical by Cytron, Ferrante, Rosen, Wegman and Zadeck (1991). Click and Cooper (1995) studied why combined analyses such as this one can beat their parts.
References
- Mark N. Wegman and F. Kenneth Zadeck, Constant propagation with conditional branches, ACM Transactions on Programming Languages and Systems 13(2), 1991, 181-210, Section 3 (the four algorithms SC, SSC, CC and SCC), Section 3.4 and 3.4.1 (the algorithm and its cost, each SSA edge examined at most twice), Section 4 (conservative and at least as strong as CC), Section 5.1 (optimistic and pessimistic algorithms)
- Mark N. Wegman and F. Kenneth Zadeck, Constant propagation with conditional branches, Proceedings of the 12th ACM Symposium on Principles of Programming Languages (POPL 1985), 291-299, the whole paper (the first version)
- Ben Wegbreit, Property extraction in well-founded property sets, IEEE Transactions on Software Engineering SE-1(3), 1975, 270-285, Algorithm 3.1, the dense conditional algorithm that Wegman and Zadeck call CC
- Ron Cytron, Jeanne Ferrante, Barry K. Rosen, Mark N. Wegman and F. Kenneth Zadeck, Efficiently computing static single assignment form and the control dependence graph, ACM Transactions on Programming Languages and Systems 13(4), 1991, 451-490, the whole paper (the SSA construction that the implementation uses)
- Cliff Click and Keith D. Cooper, Combining analyses, combining optimizations, ACM Transactions on Programming Languages and Systems 17(2), 1995, 181-196, the whole paper (combining two analyses into one optimistic analysis, with constant propagation and unreachable code as the main case)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag WNK50T Edit this page History Report an error Markdown