Algorithmadvanced
Braun SSA construction algorithm
Also called simple and efficient SSA construction.
Builds SSA form directly from an AST or CFG by local value numbering and on-demand lookup in predecessors, with no dominance frontiers.
- Solves
- SSA construction
- Time
- O(I + (B + E) V + B^2 V^2) worst · averageΘ(I + B + E) best
- Space
- O(I + (B + E) V) extra
- Where
- B = the number of blocks; E = the number of edges; I = the number of instructions; V = the number of variables
- Model
- Word RAM
- Properties
- deterministiconlinerecursive
- Evidence
- Proof sketchCode in 1 languages
The Braun SSA construction builds static single assignment form while the compiler translates a program into its intermediate representation, with no dominator tree and no dominance frontiers. Inside a block, it keeps the current value of each variable, as local value numbering does. When a block reads a variable that it has not assigned, the algorithm asks the predecessors, and puts a phi-function at the block if there are several. A phi-function that merges only one value is removed at once. Braun, Buchwald, Hack, Leißa, Mallon and Zwinkau published it in 2013. They proved that the result is pruned, and minimal on reducible control flow graphs. A short extra pass makes it minimal on all graphs.
In plain words
Translate the program block by block. In each block, remember the latest value of each variable. When the block reads a variable it did not set, look backward. With one predecessor, ask that block. With several, create a merge here first, so that a loop that leads back here stops at this merge, and then ask each predecessor. If all the answers are the same value, the merge is useless: delete it and use that value. A block whose incoming edges are not all known yet, such as a loop header before its loop body exists, gets a placeholder merge. Its inputs are filled in when the last edge arrives. The result has merges only where some later read needs one.
The problem
The input is a procedure without phi-functions, given block by block in an order where each block comes after at least one of its predecessors, as a translator from an abstract syntax tree produces it. A block is filled when all its instructions are translated. It is sealed when no more predecessors will be added. The output is a strict SSA form of the procedure with the same behaviour, as defined on the SSA construction page.
The implementation takes a whole control flow graph and replays this process: it fills the blocks in reverse postorder and seals each block as soon as all its predecessors are filled.
The algorithm
WRITE-VARIABLE(v, b, value)- 1
currentDef[v][b] <- value READ-VARIABLE(v, b)- 2
if currentDef[v] has an entry for b then return currentDef[v][b] - 3
return READ-VARIABLE-RECURSIVE(v, b) READ-VARIABLE-RECURSIVE(v, b)- 4
if b is not sealed then val <- new phi at b; incompletePhis[b][v] <- val - 5
else if b has one predecessor p then val <- READ-VARIABLE(v, p) - 6
else val <- new phi at b; WRITE-VARIABLE(v, b, val) - 7
val <- ADD-PHI-OPERANDS(v, val) - 8
WRITE-VARIABLE(v, b, val); return val ADD-PHI-OPERANDS(v, phi)- 9
for each predecessor p of phi.block do append READ-VARIABLE(v, p) to phi - 10
return TRY-REMOVE-TRIVIAL-PHI(phi) TRY-REMOVE-TRIVIAL-PHI(phi)- 11
same <- none; for each operand op of phi do if op = same or op = phi then continueif same != none then return phi // two values: not trivialsame <- op- 12
if same = none then same <- undefined // start block, or unreachable - 13
replace every use of phi by same and delete phi - 14
for each phi-function u that used phi do TRY-REMOVE-TRIVIAL-PHI(u) return sameSEAL-BLOCK(b)- 15
for each (v, phi) in incompletePhis[b] do ADD-PHI-OPERANDS(v, phi) mark b sealedBUILD(G)- 16
for each block b in reverse postorder do if all predecessors of b are filled then SEAL-BLOCK(b)fill b: for each read of v, use READ-VARIABLE(v, b);for each assignment to v, WRITE-VARIABLE(v, b, new name)- 17
for each successor s of b whose predecessors are all filled do SEAL-BLOCK(s) REMOVE-REDUNDANT-PHIS(set of phi-functions) // optional, Section 3.2- 18
for each SCC S of the graph "phi -> its phi operands", operands first do if |S| = 1 then continue- 19
outer <- operands of S that are not in S; inner <- members of S with no outer operand - 20
if |outer| = 1 then replace every member of S by the single outer value - 21
else if |outer| > 1 then REMOVE-REDUNDANT-PHIS(inner)
Lines L1 to L3 are local value numbering. If the block has no value for the variable, line L5 or L6 looks backward. Line L6 records the new phi-function as the block's value before line L7 reads the predecessors. A lookup that comes around a loop back to this block then finds the phi-function and stops. Without this step a loop would make the lookup recurse forever.
Lines L11 to L14 remove a trivial phi-function: one whose operands are only itself and one other value. Removing it can make the phi-functions that used it trivial, so line L14 checks them again. If a phi-function has no operand other than itself, it is in the start block or in unreachable code, and its value is undefined. The implementation gives such a variable the name v.0 and defines v.0 = 0 at the top of the entry, so that the result stays strict.
Line L4 handles a block whose predecessors are not all known. It creates an empty phi-function and waits. Line L15 completes it when the block is sealed. Sealing needs all predecessors to be filled, because a lookup there reads their final values. A loop header is sealed after the jump back from the loop body is added.
Lines L18 to L21 are the pass of Section 3.2 of the paper. Each phi-function in a set that takes values only from and from one outside value is equal to . Irreducible control flow can leave such sets, and the trivial test alone does not see them.
Example
Take the program from the control flow graph page that adds the odd numbers below :
# params: n
B1:
i = 0
s = 0
jump B2
B2:
t1 = i < n
br t1 B3 B6
B3:
t2 = i % 2
br t2 B4 B5
B4:
s = s + i
jump B5
B5:
i = i + 1
jump B2
B6:
ret s
The reverse postorder is B1, B2, B6, B3, B4, B5.
- B1 has no predecessors, so it is sealed. Filling it records
i.1ands.1. B2 cannot be sealed: B5 is not filled. - B2 reads
iandn. B2 is not sealed, so both get empty phi-functions,i.2andn.1. It definest1.1 = i.2 < n.1. B3 and B6 have only B2 as predecessor, so they are sealed. - B6 reads
s. It has one predecessor, so the lookup goes to B2, which has no value forsand is not sealed. B2 gets an empty phi-functions.2, and B6 returnss.2. - B3 reads
i. The lookup goes to B2 and findsi.2. It definest2.1. - B4 reads
sandi, through B3, and findss.2andi.2. It definess.3. B5 now has both predecessors filled, so it is sealed. - B5 reads
i. It is sealed and has two predecessors, so it gets the phi-functioni.3, whose operands arei.2from B3 andi.2from B4. That is one value, soi.3is trivial and is replaced byi.2. B5 definesi.4 = i.2 + 1. B2 now has both predecessors filled, so it is sealed. - Sealing B2 completes its three empty phi-functions.
i.2getsi.1from B1 andi.4from B5: it stays.n.1getsnfrom B1, and from B5 a new phi-functionn.2in B5 whose operands are bothn.1. Son.2is trivial and becomesn.1, and thenn.1has the operandsnand itself, so it is trivial too and becomesn.s.2getss.1from B1, and from B5 a new phi-functions.4with the operandss.2from B3 ands.3from B4. Both stay.
The result is:
# params: n
B1:
i.1 = 0
s.1 = 0
jump B2
B2:
i.2 = phi [B1: i.1, B5: i.4]
s.2 = phi [B1: s.1, B5: s.4]
t1.1 = i.2 < n
br t1.1 B3 B6
B3:
t2.1 = i.2 % 2
br t2.1 B4 B5
B4:
s.3 = s.2 + i.2
jump B5
B5:
s.4 = phi [B3: s.2, B4: s.3]
i.4 = i.2 + 1
jump B2
B6:
ret s.2
The gaps in the version numbers are the removed phi-functions. The three phi-functions that are left are exactly those of pruned SSA form. The Cytron construction also puts dead phi-functions for t1 and t2 at B2. Here, no block ever asks for t1 or t2 at B2, so those phi-functions are never created.
Irreducible flow. In this program, B2 and B3 form a loop with two entries from B1:
# params: c, d
B1:
x = 1
br c B3 B2
B2:
br d B3 B4
B3:
y = x + 1
br y B2 B4
B4:
ret x
Only B1 assigns x, so minimal SSA has no phi-function for it. The basic algorithm builds x.3 = phi [B1: x.1, B3: x.2] at B2 and x.2 = phi [B1: x.1, B2: x.3] at B3. Neither one is trivial, because each one has two operands other than itself: x.1 and the other phi-function. Together they only pass x.1 around. The SCC pass finds the set with the single outside value x.1, and replaces both by x.1. Then the phi-function for x at B4 becomes trivial, and the same happens for the parameter d.
Correctness
The full proof is in the proof file. It has four parts.
- Values. The builder attaches a name of to the points where a lookup happens. At the top of a block, the name is either the block's phi-function or a name that every predecessor has at its end. A removed phi-function forwards to a value equal to all its operands. Induction over the steps of a run shows that every name holds the current value of its variable, so the output reads the same values and takes the same branches as the input.
- Strictness. Walk any path backward from a use. The name stays attached until the path reaches its definition, so the definition dominates the use.
- No dead phi-function. Every lookup is caused by a real read, through a chain of blocks without an assignment to the variable. So every phi-function sits at a block where its variable is live.
- Minimal on reducible graphs. This is Theorem 1 of Braun et al. Suppose a phi-function is not needed and not trivial. It must have an operand that is also a phi-function that is not needed, in a block that does not dominate it. Following these operands gives a cycle. On a reducible graph the loop entry dominates the rest of the cycle, which is a contradiction.
Proof: Correctness of the Braun SSA constructionfull
We prove that the construction in impl/python/braun_ssa_construction.py terminates, that its output is in strict SSA form, and that the output computes the same values as the input on every run. We also prove that every phi-function it keeps lies at a block where its variable is live, and that no trivial phi-function is left. Minimality on reducible graphs is the theorem of Braun et al. (CC 2013, Section 4); we give their argument in outline at the end.
Setting
The input is a program without phi-functions. Its control flow graph has entry , has no predecessors, and every block is reachable from . A point is a position between two instructions of a block, or the top or the end of a block. For a run of and a variable , is the value of at the current step. If has no value yet, any value counts as correct for it.
The builder fills the blocks in reverse postorder. It seals a block when all its predecessors are filled, and at the end it seals the rest. Every block is then filled and sealed.
The output names are of three kinds: the fresh name of each instruction, the name of each phi-function the builder creates, and the entry names (the parameters and the names , which v.0 = 0 defines at the top of ). A removed phi-function forwards to the value that replaced it. Write for the end of the forwarding chain of after the builder stops. The output writes wherever the builder recorded .
Facts that hold during the run of the builder
Fact 1. Every call read_variable(v, p) made from inside read_variable_recursive or add_phi_operands has filled.
Proof. Such a call is either the single-predecessor case or the operand read of a phi-function. In both cases is a predecessor of a block that is sealed at that moment: the single-predecessor case is only taken for a sealed , add_phi_operands runs either from seal_block or for a sealed in read_variable_recursive. A block is sealed only when all its predecessors are filled.
So a recursive lookup never enters the block that is being filled, because that block is not yet filled. The first call of a lookup is either at the block being filled, at the current point, or (Fact 1) at the end of a filled block.
Fact 2. At most one phi-function for is ever created in a block .
Proof. A phi-function for at is created only in read_variable_recursive(v, b), which runs only when current_def has no entry for , and which sets that entry before it returns (line L8) and, in the sealed case, before it recurses (line L6). The entry is never deleted.
Fact 3 (termination). Every lookup ends.
Proof. A call read_variable_recursive(v, b) either creates a phi-function and records it in current_def[(v, b)] before it reads any predecessor, or follows the single predecessor. After the first case, a lookup of at stops at once. By Fact 2 this case happens at most once per pair . A chain of single-predecessor steps cannot run forever: it would follow a cycle in which every block has one predecessor, and no block of such a cycle is reachable from . Each removal of a phi-function deletes one of finitely many phi-functions, so the recursive rechecks also end.
Names attached to points
The builder attaches names to points. We call a triple a claim: " is the name of at point ". The claims are these.
- (C1) Definitions. When block is filled and the instruction at point assigns with the fresh name , the claim holds for each point after in up to the next assignment of in , or up to the end of .
- (C2) Values on entry. When
read_variable_recursive(v, b)records the value (lines L4 to L8), the claim holds for the top of and for each point of before the first assignment of in . For the builder also records each parameter as the name of at the top of . - (C3) Phi operands. When a phi-function for at gets the operand for the edge , the claim holds.
A use of at point of block reads read_variable(v, b). By Fact 1 and the order of filling, this returns either the name of the last assignment of before in (a claim C1 at ) or the value recorded for (a claim C2 at ). A phi operand for the edge is the value of read_variable(v, p) for a filled , which is a claim C1 or C2 at the end of ; C3 records it. So every name the output reads is the first part of a claim at the point where it is read.
In the output, every claim becomes . We call these the output claims.
Lemma 1 (entry claims). Let be an output claim made by C2. Then exactly one of these holds:
- is the name of a phi-function for at that the output keeps;
- , and is an output claim for every predecessor of ;
- , and is a parameter or .
Proof. Look at the case of read_variable_recursive(v, b) that recorded the value.
- Single predecessor . The recorded value is
read_variable(v, p), a claim at the end of . Its image under is . This is case 2. - A phi-function was created (unsealed block, or sealed block with several predecessors, or with none). Every phi-function becomes complete: an incomplete one gets its operands when is sealed, and every block is sealed. If the output keeps , then and we are in case 1. Otherwise was replaced. A replacement by
try_remove_trivial_phihappens when every operand of is itself or one value , and then forwards to . A replacement by the SCC pass happens when lies in a set of phi-functions whose operands lie in the set or equal one value , and then every member forwards to . In both cases every operand of has the same image under as , which is . If , the operand claims C3 give case 2. If , has no operands and is replaced by : case 3. - The parameter claims at are case 3.
Since the output keeps at most one phi-function for at (Fact 2), case 1 says that is that phi-function.
Single assignment and strictness
Every output name has exactly one definition: fresh names and phi names are new each time, and the entry names are defined once at the top of .
Theorem 1 (strict). If the output reads at point , the definition of dominates .
Proof. There is an output claim . Suppose a path from the top of to avoids the definition of . Walk backward from and carry the claim.
- Inside a block, a claim C1 at comes from an assignment of with name earlier in the same block, and passes it before unless starts later than it, which it does not, because starts at and enters the block at its top. So every claim we meet inside a block on is a claim C2, which holds from the top of the block.
- At the top of a block , Lemma 1 applies. Case 1 puts the definition of at the top of , on , which is excluded. Case 2 gives the claim at the end of the predecessor that came from, so we can go on. For a claim at the end of a block that is a claim C1, the assignment is in that block and , which passed the whole block, passed it; so it is a claim C2 again.
- At the top of , case 3 applies, and is defined at the top of , on .
Each case either contradicts the choice of or moves the claim to an earlier point of . Since is finite, we reach a contradiction.
The same walk shows that every phi-function has one operand per predecessor in the output: the builder gives it one per predecessor when it is completed.
Same values on every run
Theorem 2. Run and the output on the same arguments. They follow the same path through the blocks, and at every step, for every output claim with the current point, the output holds in .
Proof. By induction on the number of steps. Assume the statement at a step, and look at the next one.
- Top of . The claims there are case 3 of Lemma 1. A parameter holds its argument. is a claim only for a that has no value yet in , and any value is correct for it.
- An instruction at in block . Its operands are names with claims at , so by the hypothesis they hold the values that reads. The instruction computes the same value, and, for a branch, takes the same edge. If it assigns with fresh name , the claims at the next point for are claims C1 with name , and now holds the new value of . For any other variable , a claim at is the same claim as at (C1 and C2 run over a range of points), and its name is a name of , which this step does not write.
- An edge from to . Take a claim . If comes from a C1 claim, it is not at the top of a block. So Lemma 1 applies. In case 1, is the phi-function for at . It receives the value of its operand for , which has a claim at the end of . All phi-functions of read their operands before any of them is written, so that value is at the end of , which is at the top of . In case 2, is a claim, so held at the end of , and the edge writes only the phi-functions of . A phi-function of for another variable has a different name, and is not the phi-function of for because case 1 and case 2 exclude each other. So still holds .
Every name the output reads has a claim at that point, so every read in the output gets the value that the matching read in gets, and both programs make the same steps.
The output has no copies in place of the input's copies (the builder keeps each copy as an instruction), so two names of the same variable are never live at once, and dropping the version numbers gives back a program equivalent to . This is the function strip_versions.
Every phi-function is at a live block
Theorem 3. If the builder creates a phi-function for at , then is live on entry to in .
Proof. Call a lookup read_variable(v, c) justified if some path from the point where it asks for (the current point of during filling, or the end of otherwise) reaches a use of with no assignment of in between. A lookup made for an operand of an instruction or a terminator is justified by that use. A recursive lookup at a predecessor of comes from read_variable_recursive(v, c), which runs only when has no assignment of before the point asked for. If the lookup at was justified, the path from the end of into and then on to the use is free of assignments of , so the lookup at is justified. An operand lookup for an incomplete phi-function at , made when is sealed, is justified in the same way, because the lookup that created the incomplete phi-function was. By induction every lookup is justified. A phi-function for at is created by read_variable_recursive(v, b), for a point of with no assignment of before it, so the justifying path starts at the top of .
No trivial phi-function is left
Theorem 4. In the output, every phi-function has at least two different operands other than itself.
Proof. A phi-function is tested by try_remove_trivial_phi when its last operand is in (line L10). Its operands can change later only when one of them is replaced. The builder keeps, for every value, the set of phi-functions that use it, and when a phi-function is replaced, its users move to the new value and are tested again (line L14). The SCC pass replaces through the same routine. So every phi-function that is left was tested with its final operands, and the test keeps exactly those with two different operands other than itself.
Minimality on reducible graphs (outline)
Braun et al. (CC 2013, Section 4, Theorem 1) prove: an SSA program with a reducible control flow graph and no trivial phi-function is in minimal SSA form, that is, every phi-function for sits at a block where two paths from two different assignments of first meet. Their argument, in outline:
- (Lemma 2 of the paper.) If a phi-function at block has two distinct operands and , other than , defined in blocks and , then and do not both dominate . Otherwise one of them, say , dominates the other, and the path from through to the predecessor where reads has another definition of between a definition and its use.
- (Lemma 3 of the paper.) If is unnecessary but not trivial, then it has an operand that is itself an unnecessary phi-function whose block does not dominate the block of .
- (Theorem 1.) Follow such operands from an unnecessary phi-function. The chain must repeat, so the phi-functions form a cycle, which lies on a cycle of the control flow graph. In a reducible graph, that cycle has an entry block that dominates all its blocks, and the phi-function in that block dominates the one before it in the chain, against step 2.
By Theorem 4, the builder's output has no trivial phi-function, so on a reducible graph it is minimal. With Theorem 3, every phi-function it keeps for lies in , the iterated join set of the assignments of , at a block where is live. On irreducible graphs, a cycle of phi-functions can pass a single value around without being trivial, and the SCC pass of Section 3.2 of the paper (minimize_sccs=True) removes such cycles.
Running time
Filling the blocks touches each instruction once. Each pair is looked up recursively at most once, so there are phi-functions and operand reads, where and are the numbers of blocks and edges. This gives before the removal of trivial phi-functions. Each removal retests the users of the removed phi-function; Braun et al. bound these tests by in total, and the SCC pass by .
Complexity
Let be the number of instructions, the number of variables, the number of blocks and the number of edges.
- Lookups. Each pair (variable, block) is looked up recursively at most once, because the answer is stored in
currentDef. So there are phi-functions and operand reads. Braun et al. show that the basic algorithm runs in in the worst case, and that this matches a lower bound: some programs need phi-functions with operands for each variable. - Trivial phi-functions. Each removal rechecks the users. With a cache of two witness operands per phi-function, Braun et al. bound all checks by .
- SCC pass. , because each recursive step works on a strictly smaller set of phi-functions.
In practice, the paper's LLVM implementation of the marker variant was as fast as LLVM's tuned Cytron implementation: compiling SPEC CINT2000 executed 0.28% fewer instructions in total. The best case is a program where no variable is read outside the block that assigns it: then .
Properties
- Pruned. It never creates a phi-function that no read asks for, so no phi-function is dead.
- Minimal on reducible graphs. With all trivial phi-functions removed, the placement is the minimal one. On irreducible graphs it may keep extra cycles of phi-functions, unless the SCC pass runs.
- No dominance information. It needs only the predecessors of each block.
- Incremental. It works while the graph is still being built, block by block, as long as the translator says when a block is sealed.
- Strict. Every definition dominates its uses.
- Recursive. The lookup recurses along chains of predecessors, as deep as the longest such chain. Production code may need an explicit stack.
Variants and improvements
- On-the-fly optimizations. Section 3.1 of the paper runs local optimizations during construction: constant folding, arithmetic simplification, common subexpression elimination with the value numbers, and copy propagation, which records
y's value as the value ofxforx = y. These can remove phi-functions and even branches. With copy propagation, the output is no longer conventional SSA, and out-of-SSA translation must handle the lost copy and swap problems. - Fewer temporary phi-functions. The marker variant only marks a block during the lookup and creates a phi-function there only if the lookup comes back to it or finds two different values. The SCC variant runs Tarjan's algorithm during the lookup and creates only needed phi-functions (Section 3.3).
- Simpler recheck. If the IR keeps no list of users, recheck the one remaining operand instead of the users. The paper notes that this gives minimal SSA in most cases, but not all.
- SSA reconstruction. After a transformation adds new definitions of a value, such as live range splitting, the same lookup finds the right definition for each use and places the missing phi-functions (Section 5.1).
- Continuation-passing style. Instead of phi-functions, the same lookup adds parameters to local functions and arguments to the calls that reach them; see the SSA-CPS correspondence.
- Earlier work. Aycock and Horspool (2000) put a phi-function for every variable in every block and then removed the redundant ones, which is also minimal on reducible graphs. Braun et al. describe their SCC pass as a generalization of those local simplifications.
When to use it
Use it in a front end or a JIT compiler that builds SSA form straight from the syntax tree or the bytecode, with no non-SSA form in between. It needs no dominator tree, no frontiers and no liveness, and it gives pruned SSA without a separate dead-code pass. The paper's authors used variants of it in the libFirm compiler library. When the compiler already has a complete graph, its dominator tree, and needs minimal SSA on irreducible code without an extra pass, the Cytron construction is the standard choice.
Pitfalls
- Sealing too early. A sealed block reads its predecessors at once. If one of them is not filled, the lookup misses its later assignments and gives a wrong value. Seal a block only when all its predecessors are filled.
- Forgetting to seal. An incomplete phi-function in a block that is never sealed has no operands. Seal every block at the end.
- Recording the phi-function too late. Line L6 must record the phi-function before line L7 reads the predecessors. Otherwise a loop makes the lookup recurse forever.
- Checking a half-built phi-function. The removal of one phi-function rechecks its users. If a user is still collecting its operands, the test sees only some of them and can remove it by mistake. Check a phi-function only after its last operand is in.
- Stale references. After a phi-function is replaced, every place that stored it, including
currentDef, must see the new value. Use a list of users, or a forwarding map that is resolved on every read. - Expecting minimal SSA on irreducible graphs. Without the SCC pass, cycles of phi-functions that carry one value can remain.
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/braun-ssa-construction/. The authors are listed in prov/T846M5.jsonl.
"""SSA construction by the method of Braun, Buchwald, Hack, Leissa, Mallon
and Zwinkau (2013): local value numbering in each block, a lookup in the
predecessors when a block reads a variable it has not assigned, and removal
of trivial phi-functions as soon as they appear. No dominance information is
used.
The input is a toy IR program without phi-functions, whose names contain no
dot. The blocks are filled in reverse postorder, and a block is sealed as soon
as all its predecessors are filled. A copy x = y stays an instruction; it is
not folded into the value of y.
The output names the k-th value of v as v.k; the numbers have gaps where a
phi-function was removed. A parameter keeps its own name. A read with no
reaching definition gets v.0, defined by v.0 = 0 at the top of the entry.
"""
import toyir
from toyir import Block, Program
class _Phi:
def __init__(self, name, block, var):
self.name = name
self.block = block
self.var = var
self.ops = {} # predecessor -> value name
self.complete = False
class BraunBuilder:
"""The state of one construction. Values are names; a removed
phi-function forwards to the value that replaced it."""
def __init__(self, prog):
for b in prog.blocks.values():
for ins in b.instrs:
if ins[0] == "phi":
raise ValueError("the input already has phi-functions")
x = toyir.defs(ins)
if x is not None and "." in x:
raise ValueError("names must not contain a dot: %r" % x)
self.prog = prog
self.preds = toyir.preds(prog)
self.current_def = {} # (variable, block) -> value name
self.incomplete = {label: {} for label in prog.blocks}
self.sealed = set()
self.filled = set()
self.phis = {} # name -> _Phi, only the phi-functions still alive
self.users = {} # name -> set of phi names that use it
self.forward = {} # name of a removed phi -> the value that replaced it
self.counter = {}
self.undefined = []
self.trivial_checks = 0
# -------------------------------------------------------------- values
def resolve(self, a):
if not isinstance(a, str):
return a
path = []
while a in self.forward:
path.append(a)
a = self.forward[a]
for p in path:
self.forward[p] = a
return a
def fresh(self, v):
self.counter[v] = self.counter.get(v, 0) + 1
return "%s.%d" % (v, self.counter[v])
def undef(self, v):
name = v + ".0"
if name not in self.undefined:
self.undefined.append(name)
return name
def new_phi(self, block, v):
phi = _Phi(self.fresh(v), block, v)
self.phis[phi.name] = phi
return phi.name
# ---------------------------------------------- Algorithms 1, 2, 3, 4
def write_variable(self, v, block, value):
self.current_def[(v, block)] = value # @line L1
def read_variable(self, v, block):
if (v, block) in self.current_def:
return self.resolve(self.current_def[(v, block)]) # @line L2
return self.read_variable_recursive(v, block) # @line L3
def read_variable_recursive(self, v, block):
if block not in self.sealed:
val = self.new_phi(block, v) # @line L4
self.incomplete[block][v] = val
elif len(self.preds[block]) == 1:
val = self.read_variable(v, self.preds[block][0]) # @line L5
else:
val = self.new_phi(block, v) # @line L6
self.write_variable(v, block, val)
val = self.add_phi_operands(v, val) # @line L7
self.write_variable(v, block, val) # @line L8
return val
def add_phi_operands(self, v, name):
phi = self.phis[name]
for p in self.preds[phi.block]:
op = self.read_variable(v, p) # @line L9
phi.ops[p] = op
self.users.setdefault(op, set()).add(name)
phi.complete = True
return self.try_remove_trivial_phi(name) # @line L10
def try_remove_trivial_phi(self, name):
phi = self.phis.get(name)
if phi is None or not phi.complete:
# Removed already, or its operands are still being collected; it
# is checked when the last operand is in.
return self.resolve(name)
self.trivial_checks += 1
same = None
for op in phi.ops.values():
op = self.resolve(op)
if op == same or op == name:
continue # @line L11
if same is not None:
return name # it merges two values: not trivial
same = op
if same is None:
same = self.undef(phi.var) # @line L12
self.replace(name, same) # @line L13
return same
def replace(self, name, value):
"""Reroute every use of the phi-function name to value, delete the
phi-function, then recheck the phi-functions that used it."""
users = self.users.pop(name, set()) - {name}
del self.phis[name]
self.forward[name] = value
if isinstance(value, str):
self.users.setdefault(value, set()).update(users)
for u in users:
self.try_remove_trivial_phi(u) # @line L14
def seal_block(self, block):
for v, name in list(self.incomplete[block].items()):
self.add_phi_operands(v, name) # @line L15
self.incomplete[block] = {}
self.sealed.add(block)
# ------------------------------------------------------ the CFG walk
def fill_block(self, label):
out = []
for ins in self.prog.blocks[label].instrs:
k = ins[0]
if k == "const":
ins2 = ("const", None, ins[2])
elif k == "copy":
ins2 = ("copy", None, self.operand(ins[2], label))
elif k == "op":
ins2 = ("op", None, ins[2], self.operand(ins[3], label), self.operand(ins[4], label))
else:
raise ValueError("unsupported instruction: %r" % (ins,))
name = self.fresh(ins[1])
self.write_variable(ins[1], label, name)
out.append(ins2[:1] + (name,) + ins2[2:])
t = self.prog.blocks[label].term
if t[0] == "br":
t = ("br", self.operand(t[1], label), t[2], t[3])
elif t[0] == "ret":
t = ("ret", self.operand(t[1], label))
self.filled.add(label)
return out, t
def operand(self, a, label):
return self.read_variable(a, label) if isinstance(a, str) else a
def maybe_seal(self, label):
if label not in self.sealed and all(p in self.filled for p in self.preds[label]):
self.seal_block(label)
def build(self, minimize_sccs=False):
prog = self.prog
root = prog.entry
if self.preds[root]:
raise ValueError("the entry block must have no predecessors")
succ = {label: toyir.succs(prog, label) for label in prog.blocks}
order = _reverse_postorder(succ, root)
reach = set(order) # unreachable blocks are dropped
self.preds = {b: [p for p in ps if p in reach] for b, ps in self.preds.items()}
for p in prog.params:
self.write_variable(p, root, p)
bodies = {}
for label in order: # @line L16
self.maybe_seal(label)
bodies[label] = self.fill_block(label)
for s in succ[label]:
self.maybe_seal(s) # @line L17
for label in order:
self.maybe_seal(label)
if minimize_sccs:
remove_redundant_phis(self, list(self.phis))
return self.assemble(bodies)
def assemble(self, bodies):
r = self.resolve
by_block = {label: [] for label in bodies}
for phi in self.phis.values():
by_block[phi.block].append(phi)
blocks = {}
for label in self.prog.blocks:
if label not in bodies:
continue # unreachable from the entry
head = []
for phi in sorted(by_block[label], key=lambda q: _version_key(q.name)):
head.append(("phi", phi.name, {p: r(phi.ops[p]) for p in self.preds[label]}))
instrs, t = bodies[label]
body = []
for ins in instrs:
if ins[0] == "const":
body.append(ins)
elif ins[0] == "copy":
body.append(("copy", ins[1], r(ins[2])))
else:
body.append(("op", ins[1], ins[2], r(ins[3]), r(ins[4])))
if t[0] == "br":
t = ("br", r(t[1]), t[2], t[3])
elif t[0] == "ret":
t = ("ret", r(t[1]))
if label == self.prog.entry:
head = [("const", name, 0) for name in self.undefined] + head
blocks[label] = Block(head + body, t)
return Program(list(self.prog.params), blocks)
# ------------------------------------------------- Algorithm 5 (Section 3.2)
def remove_redundant_phis(builder, names):
"""Replace every strongly connected set of phi-functions that has only
one value coming in from outside by that value."""
names = [n for n in names if n in builder.phis]
for scc in _phi_sccs(builder, names): # @line L18
_process_scc(builder, scc)
def _process_scc(builder, scc):
scc = [n for n in scc if n in builder.phis]
if len(scc) <= 1:
return # a single phi-function is handled by the trivial test
members = set(scc)
inner, outer = [], set()
for n in scc:
is_inner = True
for op in builder.phis[n].ops.values():
op = builder.resolve(op)
if op not in members:
outer.add(op) # @line L19
is_inner = False
if is_inner:
inner.append(n)
if len(outer) == 1:
value = outer.pop()
for n in scc:
if n in builder.phis:
builder.replace(n, value) # @line L20
elif len(outer) > 1:
remove_redundant_phis(builder, inner) # @line L21
def _phi_sccs(builder, names):
"""Tarjan's algorithm on the graph phi -> operand phi, restricted to
names. A component comes out after every component it reads from, so the
operands are simplified first."""
allowed = set(names)
index, low, on_stack, stack, out = {}, {}, set(), [], []
counter = [0]
def edges(n):
return [o for o in (builder.resolve(x) for x in builder.phis[n].ops.values()) if o in allowed]
for start in names:
if start in index:
continue
index[start] = low[start] = counter[0]
counter[0] += 1
stack.append(start)
on_stack.add(start)
work = [(start, iter(edges(start)))]
while work:
v, it = work[-1]
w = next(it, None)
if w is None:
work.pop()
if work:
low[work[-1][0]] = min(low[work[-1][0]], low[v])
if low[v] == index[v]:
comp = []
while True:
x = stack.pop()
on_stack.discard(x)
comp.append(x)
if x == v:
break
out.append(comp)
elif w not in index:
index[w] = low[w] = counter[0]
counter[0] += 1
stack.append(w)
on_stack.add(w)
work.append((w, iter(edges(w))))
elif w in on_stack:
low[v] = min(low[v], index[w])
return out
# ------------------------------------------------------------------ helpers
def _reverse_postorder(succ, root):
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])))
out.reverse()
return out
def _version_key(name):
base, _, k = name.rpartition(".")
return (base, int(k))
def braun_ssa(prog, minimize_sccs=False):
"""Return a new program in SSA form with the same behaviour. With
minimize_sccs, run the Section 3.2 pass that removes redundant cycles of
phi-functions, which irreducible control flow can leave."""
return BraunBuilder(prog).build(minimize_sccs)
def strip_versions(prog):
"""Out of SSA for the output of braun_ssa: drop the phi-functions and map
each name v.k back to v. This is correct because copies are not folded,
so no two versions of one variable are live at the same point."""
def base(a):
return a.split(".")[0] if isinstance(a, str) else a
blocks = {}
for label, b in prog.blocks.items():
instrs = []
for ins in b.instrs:
if ins[0] == "phi":
continue
if ins[0] == "const":
instrs.append(("const", base(ins[1]), ins[2]))
elif ins[0] == "copy":
instrs.append(("copy", base(ins[1]), base(ins[2])))
else:
instrs.append(("op", base(ins[1]), ins[2], base(ins[3]), base(ins[4])))
t = b.term
if t[0] == "br":
t = ("br", base(t[1]), t[2], t[3])
elif t[0] == "ret":
t = ("ret", base(t[1]))
blocks[label] = Block(instrs, t)
return Program(list(prog.params), blocks)
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_braun_ssa_construction.py 393 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/braun-ssa-construction/. The authors are listed in prov/T846M5.jsonl.
import random
import toyir
from braun_ssa_construction import braun_ssa, strip_versions
ODD_SUM = """
# params: n
B1:
i = 0
s = 0
jump B2
B2:
t1 = i < n
br t1 B3 B6
B3:
t2 = i % 2
br t2 B4 B5
B4:
s = s + i
jump B5
B5:
i = i + 1
jump B2
B6:
ret s
"""
ODD_SUM_SSA = """# params: n
B1:
i.1 = 0
s.1 = 0
jump B2
B2:
i.2 = phi [B1: i.1, B5: i.4]
s.2 = phi [B1: s.1, B5: s.4]
t1.1 = i.2 < n
br t1.1 B3 B6
B3:
t2.1 = i.2 % 2
br t2.1 B4 B5
B4:
s.3 = s.2 + i.2
jump B5
B5:
s.4 = phi [B3: s.2, B4: s.3]
i.4 = i.2 + 1
jump B2
B6:
ret s.2
"""
# Two loops that enter each other: B2 and B3 form a cycle with two entries.
IRREDUCIBLE = """
# params: c, d
B1:
x = 1
br c B3 B2
B2:
br d B3 B4
B3:
y = x + 1
br y B2 B4
B4:
ret x
"""
# ------------------------------------------------------------ brute force
def graph(prog):
return {label: toyir.succs(prog, label) for label in prog.blocks}
def _reach(succ, root, removed=None):
if root == removed:
return set()
seen = {root}
stack = [root]
while stack:
v = stack.pop()
for w in succ[v]:
if w != removed and w not in seen:
seen.add(w)
stack.append(w)
return seen
def brute_dominators(succ, root):
nodes = _reach(succ, root)
dom = {v: set() for v in nodes}
for d in nodes:
left = _reach(succ, root, d)
for v in nodes:
if v not in left:
dom[v].add(d)
return dom
def brute_frontiers(succ, root):
dom = brute_dominators(succ, root)
df = {v: set() for v in dom}
for p in dom:
for y in succ[p]:
for x in dom[p]:
if not (x in dom[y] and x != y):
df[x].add(y)
return df
def brute_idf(df, s):
cur = set()
while True:
nxt = set()
for x in set(s) | cur:
nxt |= df[x]
if nxt == cur:
return cur
cur = nxt
def brute_live_in(prog, v, start):
"""Is v read on some path from the top of start before any assignment?"""
seen = set()
stack = [start]
while stack:
b = stack.pop()
if b in seen:
continue
seen.add(b)
blk = prog.blocks[b]
killed = False
for ins in blk.instrs:
if v in toyir.uses(ins):
return True
if ins[1] == v:
killed = True
break
if killed:
continue
if v in toyir.term_uses(blk.term):
return True
stack.extend(toyir.succs(prog, b))
return False
def pruned_minimal_phis(prog):
"""The phi-functions of pruned minimal SSA: v at y when y is in the
iterated dominance frontier of the blocks that assign v and v is live on
entry to y."""
succ = graph(prog)
df = brute_frontiers(succ, prog.entry)
sites = {}
for v in prog.params:
sites[v] = {prog.entry}
for label, b in prog.blocks.items():
for ins in b.instrs:
sites.setdefault(ins[1], {prog.entry}).add(label)
out = set()
for v, s in sites.items():
for y in brute_idf(df, s):
if brute_live_in(prog, v, y):
out.add((y, v))
return out
def reducible(prog):
"""Hecht and Ullman's T1 and T2: remove self-loops, and merge a node
with a single predecessor into it. The graph is reducible exactly when
this ends in one node."""
succ = {v: set(ws) for v, ws in graph(prog).items()}
changed = True
while changed:
changed = False
for v in succ:
succ[v].discard(v)
pred = {v: set() for v in succ}
for v, ws in succ.items():
for w in ws:
pred[w].add(v)
for w in list(succ):
if w != prog.entry and len(pred[w]) == 1:
(p,) = pred[w]
succ[p] |= succ[w]
succ[p].discard(w)
del succ[w]
changed = True
break
return len(succ) == 1
def phi_set(ssa):
return {(label, ins[1].rpartition(".")[0]) for label, b in ssa.blocks.items() for ins in b.instrs if ins[0] == "phi"}
def check_ssa(ssa):
"""Single assignment, one operand per incoming edge, and strictness."""
succ = graph(ssa)
pred = toyir.preds(ssa)
dom = brute_dominators(succ, ssa.entry)
where = {p: (ssa.entry, -1) for p in ssa.params}
for label, b in ssa.blocks.items():
for k, ins in enumerate(b.instrs):
assert ins[1] not in where, "two definitions of %s" % ins[1]
where[ins[1]] = (label, k)
def dominates(d, block, pos):
b, k = d
return (b in dom[block] and b != block) or (b == block and k < pos)
for label, b in ssa.blocks.items():
seen_other = False
for k, ins in enumerate(b.instrs):
if ins[0] == "phi":
assert not seen_other
assert set(ins[2]) == set(pred[label])
for p, a in ins[2].items():
if isinstance(a, str):
assert dominates(where[a], p, len(ssa.blocks[p].instrs))
else:
seen_other = True
for a in toyir.uses(ins):
assert dominates(where[a], label, k)
for a in toyir.term_uses(b.term):
assert dominates(where[a], label, len(b.instrs))
def check_pruned_and_no_trivial(ssa):
"""Every phi-function transitively feeds a non-phi use, and none of them
merges only itself and one other value."""
phis = {ins[1]: ins for b in ssa.blocks.values() for ins in b.instrs if ins[0] == "phi"}
useful, work = set(), []
for b in ssa.blocks.values():
for ins in b.instrs:
if ins[0] != "phi":
work += toyir.uses(ins)
work += toyir.term_uses(b.term)
while work:
a = work.pop()
if a not in useful:
useful.add(a)
if a in phis:
work += [x for x in phis[a][2].values() if isinstance(x, str)]
for x, ins in phis.items():
assert x in useful, "dead phi %s" % x
others = set(ins[2].values()) - {x}
assert len(others) >= 2, "trivial phi %s" % x
def trace(prog, args, fuel=2000):
"""The operand values of every executed non-phi instruction and
terminator, in order."""
env = dict(zip(prog.params, args))
label, prev, out = prog.entry, None, []
while fuel > 0:
fuel -= 1
b = prog.blocks[label]
phis = [ins for ins in b.instrs if ins[0] == "phi"]
env.update([(ins[1], env[ins[2][prev]]) for ins in phis])
for ins in b.instrs:
if ins[0] == "phi":
continue
if ins[0] == "const" and ins[1].endswith(".0"):
env[ins[1]] = ins[2]
continue
if ins[0] == "const":
vals = [ins[2]]
elif ins[0] == "copy":
vals = [env[ins[2]]]
else:
vals = [ins[2]] + [env[a] if isinstance(a, str) else a for a in ins[3:]]
out.append((label, tuple(vals)))
if ins[0] == "const":
env[ins[1]] = ins[2]
elif ins[0] == "copy":
env[ins[1]] = vals[0]
else:
try:
env[ins[1]] = toyir._binop(ins[2], vals[1], vals[2])
except toyir._Trap:
out.append(("trap",))
return out
t = b.term
if t[0] == "jump":
prev, label = label, t[1]
continue
c = env[t[1]] if isinstance(t[1], str) else t[1]
out.append((label, t[0], c))
if t[0] == "ret":
return out
prev, label = label, (t[2] if c != 0 else t[3])
out.append(("fuel",))
return out
def programs(seed, count, nvars=6, nblocks=8):
rng = random.Random(seed)
for k in range(count):
yield rng, toyir.random_program(rng, nvars, nblocks, acyclic=(k % 3 == 0))
# ------------------------------------------------------------------ tests
def test_page_example():
prog = toyir.parse(ODD_SUM)
ssa = braun_ssa(prog)
assert toyir.show(ssa) == ODD_SUM_SSA
for n in range(-2, 12):
assert toyir.run(ssa, [n]) == toyir.run(prog, [n])
def test_reducible_gives_pruned_minimal_ssa():
# Braun et al., Section 4: pruned always, minimal on reducible graphs.
seen = 0
for _, prog in programs(1, 400):
if reducible(prog):
seen += 1
assert phi_set(braun_ssa(prog)) == pruned_minimal_phis(prog)
assert seen > 100
def test_scc_pass_gives_pruned_minimal_ssa_on_any_graph():
irreducible = 0
for _, prog in programs(2, 400):
irreducible += not reducible(prog)
assert phi_set(braun_ssa(prog, minimize_sccs=True)) == pruned_minimal_phis(prog)
assert irreducible > 10
def test_irreducible_example():
prog = toyir.parse(IRREDUCIBLE)
assert not reducible(prog)
plain = braun_ssa(prog)
assert phi_set(plain) == {("B2", "x"), ("B3", "x"), ("B4", "x"), ("B2", "d"), ("B3", "d")}
assert phi_set(braun_ssa(prog, minimize_sccs=True)) == set() == pruned_minimal_phis(prog)
for c in (0, 1):
for d in (0, 1):
assert toyir.run(plain, [c, d]) == toyir.run(prog, [c, d])
def test_pruned_and_no_trivial_phis():
for _, prog in programs(3, 300):
for flag in (False, True):
check_pruned_and_no_trivial(braun_ssa(prog, flag))
def test_ssa_is_single_assignment_and_strict():
for _, prog in programs(4, 300):
check_ssa(braun_ssa(prog))
check_ssa(braun_ssa(prog, minimize_sccs=True))
def test_every_use_reads_the_original_value():
for rng, prog in programs(5, 300):
ssa = braun_ssa(prog)
for _ in range(4):
args = [rng.randint(-3, 6), rng.randint(-3, 6)]
assert trace(ssa, args) == trace(prog, args)
def test_round_trip_outputs():
for rng, prog in programs(6, 300):
a = braun_ssa(prog)
b = braun_ssa(prog, minimize_sccs=True)
for _ in range(4):
args = [rng.randint(-4, 8), rng.randint(-4, 8)]
want = toyir.run(prog, args)
assert toyir.run(a, args) == want
assert toyir.run(b, args) == want
assert toyir.run(strip_versions(a), args) == want
assert toyir.run(strip_versions(b), args) == want
def test_read_before_write_gets_entry_definition():
prog = toyir.parse("# params: c\nB1:\n br c B2 B3\nB2:\n x = 4\n jump B3\nB3:\n ret x\n")
ssa = braun_ssa(prog)
assert ssa.blocks["B1"].instrs[0] == ("const", "x.0", 0)
check_ssa(ssa)
assert toyir.run(ssa, [1]) == ("ret", 4)
assert toyir.run(ssa, [0]) == ("ret", 0)
def test_rejects_phi_input():
prog = toyir.parse("B1:\n jump B2\nB2:\n x = phi [B1: 1]\n ret x\n")
try:
braun_ssa(prog)
except ValueError:
return
assert False
History
Aycock and Horspool (2000) built SSA form by placing phi-functions everywhere and removing those that are not needed, and showed that this is minimal on reducible graphs. Braun, Buchwald, Hack, Leißa, Mallon and Zwinkau presented the on-demand construction at Compiler Construction 2013. Their compiler library libFirm had long used a variant of it. They proved that it gives pruned SSA, and minimal SSA on reducible graphs, gave the SCC pass for irreducible graphs, and compared an LLVM implementation with LLVM's Cytron-based construction. Section 5.1 of the paper applies the same lookup to SSA reconstruction, which Chapter 5 of the SSA book by Rastello and Bouchez Tichadou (2022) treats in full.
References
- Matthias Braun, Sebastian Buchwald, Sebastian Hack, Roland Leißa, Christoph Mallon and Andreas Zwinkau, Simple and efficient construction of static single assignment form, Compiler Construction (CC 2013), LNCS 7791, pages 102-122, Section 2 (local value numbering, Algorithm 1; global value numbering and trivial phi-functions, Algorithms 2 and 3; incomplete CFGs and sealing, Algorithm 4), Section 3.2 (redundant SCCs of phi-functions, Lemma 1, Algorithm 5), Section 4 (pruned SSA, Theorem 1 on minimality for reducible graphs, Section 4.1 on time), Section 6 (evaluation in LLVM and libFirm)
- John Aycock and Nigel Horspool, Simple generation of static single-assignment form, Compiler Construction (CC 2000), LNCS 1781, phi-functions for every variable in every block, then removal of the redundant ones; minimal on reducible graphs
- 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, pages 451-490, the definition of minimal SSA form through converging paths, used by Braun et al. in Section 4
- Fabrice Rastello and Florent Bouchez Tichadou (editors), SSA-based Compiler Design, Springer, 2022, Chapter 5 (SSA Reconstruction), on-demand lookup of reaching definitions after a transformation adds definitions
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 T846M5 Edit this page History Report an error Markdown