Algorithmcore
Cytron SSA construction
Also called Cytron et al. SSA construction.
Builds minimal SSA form by placing phi-functions at the iterated dominance frontiers of each variable's definitions and renaming over the dominator tree.
- Solves
- SSA construction
- Time
- O(I + V (n + m + D)) worst · averageΘ(I + n + m + D) best
- Space
- O(I + V m + D) extra
- Where
- D = the total size of the dominance frontiers; I = the number of instructions; V = the number of variables; m = the number of edges; n = the number of blocks
- Model
- Word RAM
- Properties
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
The Cytron SSA construction is the standard way to build static single assignment form. It works in two passes over a control flow graph whose dominator tree and dominance frontiers are known. The first pass decides where phi-functions go: for each variable, at the iterated dominance frontier of the blocks that assign it. The second pass walks the dominator tree from the root and gives every definition a new name, with one stack of names per variable, so that each use gets the name of the nearest definition above it. Cytron, Ferrante, Rosen, Wegman and Zadeck published it in 1991 and proved that it places the fewest phi-functions that any correct placement needs. Almost every textbook teaches it.
In plain words
First decide where merges are needed. A variable assigned in some block can meet other values of itself only at the edge of the region that block controls, so put a merge there. A merge is itself an assignment, so repeat from each new merge until nothing changes. Then walk the blocks from the top of the dominator tree down. Keep, for each variable, a stack of the names in force. A new assignment gets a fresh name, which goes on the stack. A read takes the name on top. At the end of each block, fill in the merges of the next blocks with the names in force. After a block and everything below it in the tree are done, pop the names it pushed, so its siblings see the old ones.
The problem
The input is a procedure in three-address code with no phi-functions, and its control flow graph . Every block is reachable and the entry has no predecessors. The output is the same procedure in minimal, strict SSA form, as defined on the SSA construction page: a phi-function for each variable exactly at the blocks of the iterated join set , where is the set of blocks that assign plus , each definition with a new name, and each use renamed so that it reads the same value as before.
The algorithm needs the immediate dominators and the dominance frontiers. The implementation computes the first with the Cooper-Harvey-Kennedy iteration and the second with the walk described on the dominance frontier computation page.
The algorithm
CYTRON-SSA(G, r, idom, DF)// Part 1: where the phi-functions go- 1
for each variable v do Sites[v] <- {r} - 2
for each block b and each instruction in b that assigns v do add b to Sites[v] - 3
for each variable v do - 4
W <- Sites[v] - 5
while W is not empty do remove a block x from W - 6
for each y in DF[x] do - 7
if y has no phi-function for v then put "v = phi" at the top of y - 8
if y was never in W then add y to W // Part 2: renaming- 9
for each parameter p do push p on Stack[p] RENAME(r)- 10
RENAME(b) for each phi-function "v = phi" at the top of b do- 11
replace v by a new name v.k; push v.k on Stack[v] - 12
for each other instruction "v = ... u ..." of b, in order do replace each use u by Top(u)- 13
replace v by a new name v.k; push v.k on Stack[v] replace each use u in the terminator of b by Top(u)- 14
for each successor s of b do - 15
for each phi-function for v in s do set its operand for the edge (b, s) to Top(v) - 16
for each child c of b in the dominator tree do RENAME(c) - 17
pop every name that b pushed in lines L11 and L13
Top(v) is the name on top of the stack of . If the stack is empty, is a local variable read on a path where it has no value yet. Then Top(v) returns v.0, and the implementation puts v.0 = 0 at the top of the entry block. This keeps the result strict: every name has a definition that dominates all its uses. The parameters keep their own names for their values on entry.
Lines L1 and L2 put in every site set, because the entry holds each variable's first value. Lines L4 to L8 are the worklist that computes ; the test in line L7 puts at most one phi-function for in each block, and the test in line L8 puts each block on the list at most once. Line L12 reads the uses before line L13 pushes the new name, so i = i + 1 reads the old name of i. Lines L14 and L15 run after the whole block, so a phi operand gets the name in force at the end of the predecessor.
The phi-functions of a block are read in parallel, as one copy on the edge. Line L15 takes all their operands from the state at the end of , not from the other phi-functions of , so the order in which the phi-functions are written does not matter.
Example
The program from the control flow graph page 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
Part 1. The frontiers are , , and the others are empty. The sites are i: {B1, B5}, s: {B1, B4}, t1: {B1, B2}, t2: {B1, B3} and n: {B1}. For s, the worklist takes B4 and puts a phi-function at B5, takes B5 and puts one at B2, and takes B2, whose frontier B2 already has one. For i, t1 and t2 it puts one at B2. So B2 gets four phi-functions and B5 gets one.
Part 2. The dominator tree is B1 → B2 → {B3, B6}, B3 → {B4, B5}. The walk visits B1, B2, B3, B4, B5 and B6.
- B1 pushes
i.1ands.1. At the edge to B2, the stacks oft1andt2are empty, so those operands becomet1.0andt2.0. - B2 pushes the phi names
i.2,s.2,t1.1,t2.1, thent1.2fort1 = i < n, which readsi.2. - B3 pushes
t2.2. At the edge to B5, the operand ofsbecomess.2. - B4 pushes
s.3fors = s + i, which readss.2andi.2. At the edge to B5, the operand becomess.3. B4 popss.3. - B5 pushes the phi name
s.4andi.3. At the edge to B2, the operands becomei.3,s.4,t1.2andt2.2. B5 pops its names. - B3 pops
t2.2. B6 returnss.2, the name on top of the stack ofsafter B2.
The result is:
# params: n
B1:
t1.0 = 0
t2.0 = 0
i.1 = 0
s.1 = 0
jump B2
B2:
i.2 = phi [B1: i.1, B5: i.3]
s.2 = phi [B1: s.1, B5: s.4]
t1.1 = phi [B1: t1.0, B5: t1.2]
t2.1 = phi [B1: t2.0, B5: t2.2]
t1.2 = i.2 < n
br t1.2 B3 B6
B3:
t2.2 = i.2 % 2
br t2.2 B4 B5
B4:
s.3 = s.2 + i.2
jump B5
B5:
s.4 = phi [B3: s.2, B4: s.3]
i.3 = i.2 + 1
jump B2
B6:
ret s.2
On it returns 9, and on it returns 25, the same as the input. The phi-functions for t1 and t2 are minimal but dead. Pruned SSA form would leave them out.
Correctness
The proof file gives the full proof in two parts.
Placement. A phi-function for is needed at when two definitions of reach along paths that meet first at ; this set, closed under the new phi-functions, is . The proof shows . One direction: if , a path from that stays in the region dominates and a path from that avoids meet first at . The other direction: follow a path from a definition to and track the deepest definition block that dominates the current node. It changes only at blocks of , so if is not one of them, both paths into come from definitions that strictly dominate , and one of the two paths then avoids a node that dominates , which is impossible.
Renaming. For each point of the program, let be the nearest definition of , phi-functions included, that dominates . Along any path, crossing an edge into a block with no phi-function for does not change , because a change would put the block in the dominance frontier of a definition block. So in every run, the last definition of executed before is . The stacks hold exactly the definitions on the dominator tree path above , so Top(v) is . Hence every use reads the value it read before, every name is defined once, and every definition dominates its uses. The same argument shows that two versions of one variable are never live at the same point, so the output is conventional SSA.
Proof: Phi-functions at the iterated dominance frontier give minimal SSA form, and renaming over the dominator tree is correctfull
Setting. is the control flow graph of the input program. Every block is reachable from , and has no predecessors (the toy IR gives the entry no predecessors; a compiler can add an empty entry block). means that every path from to contains , and is the strict version. The dominators of are the ancestors of in the dominator tree, included, so they form a chain. A path is a sequence of blocks joined by edges, and it is non-empty if it has at least one edge.
Fix a variable . Let be the set of blocks that assign , plus . The block counts as a definition because it holds the value of on entry: the parameter itself, or the name when is not a parameter.
Lemma 1. If and , then .
Proof. A path from to that avoids , followed by the edge , is a path from to that avoids , since .
Part 1. The placement is minimal
Join sets. if there are two non-empty paths from to and from to with in , such that is the only node the two paths share. (So occurs in each path only at the end, except that may start at .)
What minimal means. After the construction, the definitions of are the blocks of and the blocks that get a phi-function for . If two of them reach a block along paths that meet first at , a use at the top of would have two reaching definitions, so needs a phi-function. So a valid placement is a set with . is monotone and is finite, so the least such set exists. It is , the limit of , : by induction each lies in every valid , and the limit is valid. Minimal SSA form places phi-functions for exactly at . We show that this set is , the set that lines L3 to L8 compute.
Lemma 2. If , then .
Proof. Let : there is an edge with and not . As has no predecessors, .
The first path. Take a path from to . It contains . Keep the part after the last , so we get a path from to in which occurs only at the start. Every node on it is dominated by : a path from to that avoids , followed by the rest of this path to , would avoid and contradict . Add the edge , and cut the path at the first after the start. The result is a non-empty path from to , and every node of except the last is dominated by .
The second path. Take a path from to and cut it at the first . If , choose it to avoid , which is possible because does not dominate . The result is non-empty, because . No node of before is dominated by : the part of from to avoids (if , because occurs only at the end).
So the only node the two paths share is , and they start at and , which differ. Hence .
Lemma 3. For every set with , .
Proof. Let . By the definition of as a limit, . For each node , let be the deepest dominator of that is in , with itself allowed. It exists, since dominates every node.
Claim. If and , then . Let , so and . If did not strictly dominate , then , which is false. So , and is or a node below . As , , so by Lemma 1 , and is or a node above . So .
Now let through and , with . Let be the last node of that is in . It exists, as . The nodes are not in , so the claim gives . So . If does not strictly dominate , then and we are done. In the same way, with the last node of in , either or .
Suppose and . Both are on the dominator chain of , so one dominates the other; say . They are not equal: they are nodes of and other than . So does not dominate , and some path from to avoids . Follow it with the part of from to . The nodes of other than are not on , and , so the whole path avoids . This contradicts .
Lemma 4. .
Proof. Let . Then , and . So contains and is closed, and is the least such set, so . The other inclusion holds because is monotone.
Theorem 1. . So lines L3 to L8 place a phi-function for at exactly the blocks where minimal SSA form needs one.
Proof. () By induction on the sequence , , each . Every with in has , by Lemma 2 and monotonicity, and because strictly dominates every other node and has no predecessors. So , and if , then .
() Let . By Lemmas 3 and 4, . So is a valid placement, and the least one, , lies inside it.
Lines L4 to L8 compute by the standard worklist, which returns the limit of the sequence (this is Lemma 4 of the dominance frontier computation proof). The flag has_phi puts at most one phi-function for in each block.
Part 2. Renaming is correct
Fix again. After line L8, the definition points of are: the entry definition at the top of , each phi-function for at the top of a block of , and each instruction that assigns . A point is a position between two instructions of a block, or the end of a block (after the last instruction, before the terminator). A definition point in block dominates a point in block if , or and comes before . For each point , the definition points that dominate it form a chain: those in strict dominators of , ordered by depth in the tree and then by position, followed by those above in . The entry definition is always in it. Let be the last one, the nearest dominating definition.
Lemma 5. Let be an edge and let have no phi-function for . Then .
Proof. Let , in block . Then , and . If did not strictly dominate , then (by Lemma 4, ), and would have a phi-function. So , and dominates the top of .
Every definition point that dominates the top of lies in a block with , because has no definition point at its top. By Lemma 1, , so the point also dominates the end of . So the chain for the top of is part of the chain for the end of , and it contains , the last element of the larger chain. Hence is its last element too.
Theorem 2 (the dynamic meaning). Along every path from , and so in every run, at every point , the last definition point of that was passed is . Phi-functions count as passed when their block is entered.
Proof. Let be the last definition point passed before ; it exists because the entry definition runs first. Right after , the nearest dominating definition is itself. Between and , the run executes no definition point of . Moving inside a block past instructions that do not define does not change . Moving along an edge into a block that has no phi-function for does not change , by Lemma 5. A block with a phi-function for cannot be entered in this stretch, because the phi-function would be executed. So .
Theorem 3 (the walk). Lines L9 to L17 give each use of at a point the name of . For a phi operand of in block that belongs to the edge , the use is at the end of , and the walk gives it the name of .
Proof. Invariant: when the walk is at a point of block , the stack of holds the names of the definition points of that dominate , in chain order, except that the entry definition of a variable that is not a parameter is left implicit. This holds at the top of : line L9 pushes each parameter, and the stacks of the other variables are empty. Lines L11 and L13 push a name exactly when the walk passes a definition point, which then dominates the following points of . When the walk enters a child of in the tree, at line L16, the points of above the end all dominate the top of , and no other definition points do except those in the strict dominators of , which are already on the stack below them. Line L17 pops what pushed, so the stacks are restored when the walk goes back up. So the top of the stack is , or the stack is empty and is the entry definition , which the function top returns.
Lines L12 and L13 read the top before they push the new definition, so an instruction like x = x + 1 reads the old name. Lines L14 and L15 run after all instructions of , so they fill the operand of the edge with .
Corollary (correctness of the output). Take a run of the input program that never reads a variable before it has a value. In the matching run of the output, each instruction reads, at each use, the name of the last definition of that variable that was executed, by Theorems 2 and 3, and that name holds the value the input program would read. The branches go the same way, so the two runs follow the same blocks and return the same value. A phi operand is read only on a path where the input program does not read , because is never the last definition before a real use in such a run. Every use names the definition at , which dominates , so the output is strict. Each name has one definition point, so each use has exactly one reaching definition.
Corollary (the output is conventional). At any point , the only version of that is live is the one defined at . If is live at , there is a path from to a use of with no definition of on it. If that path had any definition point of , the last one before the use would be of the use, which is the definition of , so the use would not see from . So the path has no definition point of , and by Theorem 2, applied to a run through along that path, is the definition of . So the versions of one variable never interfere, and mapping each back to and deleting the phi-functions, as strip_versions does, keeps the meaning.
Running time. Lines L1 and L2 read each instruction once. For one variable, the worklist of lines L4 to L8 takes each block of once and reads its frontier once, which costs , with the total size of the frontiers. Over variables this is , and the sum of over all variables is at most the number of instructions plus . The walk visits each block once, each instruction once and each phi operand once, so it takes time linear in the size of the output, which is for instructions and edges.
Complexity
Let be the number of instructions, the number of variables, and the numbers of blocks and edges, and the total size of the dominance frontiers.
- Dominance. The immediate dominators take time with the simple version of Lengauer-Tarjan, or with its sophisticated version, or a few passes of the Cooper-Harvey-Kennedy iteration in practice. The frontiers take .
- Placement. For one variable, the worklist takes each block of once and reads its frontier once, which is . Over all variables this is .
- Renaming. Each instruction, each phi-function and each phi operand is handled once. The output has at most phi-functions per block, so this is .
The total after the dominator tree is . can be , and the output itself can have phi-functions, as the nested repeat-until loops on the dominance frontier page show. Cytron et al. found both to grow about linearly on real programs. The extra space is the frontiers, the stacks and the output.
Properties
- Minimal. It places phi-functions at exactly for each variable, on any control flow graph, reducible or not.
- Not pruned. It can place dead phi-functions, such as those for
t1andt2in the example. - Strict and conventional. With the entry definitions, every definition dominates its uses, and the versions of one variable never interfere. So, before any optimization, out-of-SSA translation can just drop the version numbers.
- Needs the whole graph. The graph must be complete before the dominator tree can be built.
- Recursive. RENAME recurses on the dominator tree. A deep tree needs an explicit stack in production code.
Variants and improvements
- Pruned SSA. Compute liveness first and skip a phi-function for at if is not live on entry to . See pruned SSA form.
- Semi-pruned SSA. Briggs, Cooper, Harvey and Simpson (1998) skip the variables that are never live across a block boundary. It needs no full liveness pass and removes most of the dead phi-functions.
- Linear-time placement. Sreedhar and Gao (1995) compute on the DJ-graph in per variable, without the frontiers.
- On-demand construction. Braun et al. (2013) build SSA form during translation from the syntax tree, with no dominance information.
- Copy folding during renaming. For a copy
x = y, push the name ofyon the stack ofxand drop the copy. This saves a pass, but the output is then no longer conventional, and out-of-SSA translation must handle the lost copy and swap problems.
When to use it
Use it when the whole control flow graph is available and the dominator tree is needed anyway, which is the case in most optimizing compilers. It is the reference method: it is easy to prove correct and it gives the minimal placement on any graph. If the graph is not built yet, or the compiler wants to avoid the dominance passes, Braun's method is simpler. If the frontiers may be large, use DJ-graphs for the placement.
Pitfalls
- Missing entry definitions. A variable read on some path before it is assigned has no name on that path. Without
v.0at the entry, the phi operand is empty and the result is not strict. - Reading phi-functions one by one. All phi-functions of a block take their operands from the end of the predecessor. Filling an operand with the name of another phi-function of the same block is wrong.
- Popping too early or too late. The names pushed by a block must stay on the stacks while its dominator subtree is renamed and must be gone before its siblings are. Popping at the end of the block body, before the children, gives the children wrong names.
- Edges into the entry. If the entry has a predecessor, it may need phi-functions, and the first entry has no incoming edge to choose an operand. Add a new empty entry block first.
- Unreachable blocks. They have no immediate dominator. Delete them first.
- Assuming the output is pruned. It is minimal, not pruned. Later passes must expect dead phi-functions, or the compiler must prune.
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/cytron-ssa-construction/. The authors are listed in prov/BVFDF2.jsonl.
"""Minimal SSA form by the method of Cytron, Ferrante, Rosen, Wegman and
Zadeck: phi-functions at the iterated dominance frontier of the blocks that
assign each variable, then renaming by a walk of the dominator tree.
The input is a toy IR program without phi-functions, whose names contain no
dot. The output names the k-th definition of v as v.k. A parameter keeps its
own name for its value on entry. A variable that some path reads before any
assignment gets the name v.0, defined by v.0 = 0 at the top of the entry, so
the result is strict: every definition dominates its uses.
"""
import toyir
from toyir import Block, Program
# ------------------------------------------------- dominators and frontiers
def _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])))
return out
def immediate_dominators(succ, root):
"""The Cooper-Harvey-Kennedy iteration. idom[root] is None, and only the
nodes that root reaches are keys."""
order = _postorder(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, root, idom):
"""The walk of Cooper, Harvey and Kennedy from each predecessor."""
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
# ------------------------------------------------------------- construction
def variables(prog):
"""The parameters, then the assigned names, in order of first appearance."""
out = list(prog.params)
for b in prog.blocks.values():
for ins in b.instrs:
x = toyir.defs(ins)
if x is not None and x not in out:
out.append(x)
return out
def place_phis(prog, idom=None, df=None):
"""Dict from block to the variables that get a phi-function there."""
succ = {label: toyir.succs(prog, label) for label in prog.blocks}
root = prog.entry
if idom is None:
idom = immediate_dominators(succ, root)
if df is None:
df = dominance_frontiers(succ, root, idom)
sites = {v: {root} for v in variables(prog)} # @line L1
for label in idom:
for ins in prog.blocks[label].instrs:
x = toyir.defs(ins)
if x is not None:
sites[x].add(label) # @line L2
phis = {label: [] for label in idom}
for v, s in sites.items(): # @line L3
has_phi = set()
work = list(s) # @line L4
queued = set(s)
while work: # @line L5
x = work.pop()
for y in df[x]: # @line L6
if y not in has_phi:
has_phi.add(y)
phis[y].append(v) # @line L7
if y not in queued:
queued.add(y)
work.append(y) # @line L8
return phis
def cytron_ssa(prog):
"""Return a new program in minimal, strict SSA form with the same behaviour."""
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)
succ = {label: toyir.succs(prog, label) for label in prog.blocks}
root = prog.entry
idom = immediate_dominators(succ, root)
df = dominance_frontiers(succ, root, idom)
phis = place_phis(prog, idom, df)
children = {v: [] for v in idom}
for v in idom:
if idom[v] is not None:
children[idom[v]].append(v)
params = set(prog.params)
counter = {v: 0 for v in variables(prog)}
stacks = {v: [] for v in counter}
undefined = [] # the variables that need v.0 = 0 at the entry
def top(v):
if stacks[v]:
return stacks[v][-1]
name = v + ".0"
if name not in undefined:
undefined.append(name)
return name
def fresh(v):
counter[v] += 1
name = "%s.%d" % (v, counter[v])
stacks[v].append(name)
return name
def operand(a):
return top(a) if isinstance(a, str) else a
for p in prog.params:
stacks[p].append(p) # @line L9
# The blocks of the result, filled in during the walk. The phi-functions
# are created first, with no operands, and get one operand per edge.
new_phis = {label: [("phi", None, {}) for _ in phis[label]] for label in idom}
out = {label: None for label in prog.blocks if label in idom}
def rename(b): # @line L10
pushed = []
block_phis = []
for v, (_, _, args) in zip(phis[b], new_phis[b]):
block_phis.append(("phi", fresh(v), args)) # @line L11
pushed.append(v)
new_phis[b] = block_phis
instrs = []
for ins in prog.blocks[b].instrs:
k = ins[0]
if k == "const":
ins2 = ("const", None, ins[2])
elif k == "copy":
ins2 = ("copy", None, operand(ins[2])) # @line L12
elif k == "op":
ins2 = ("op", None, ins[2], operand(ins[3]), operand(ins[4]))
else:
raise ValueError("unsupported instruction: %r" % (ins,))
name = fresh(ins[1]) # @line L13
pushed.append(ins[1])
instrs.append(ins2[:1] + (name,) + ins2[2:])
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]: # @line L14
for v, (_, _, args) in zip(phis[s], new_phis[s]):
args[b] = top(v) # @line L15
out[b] = (instrs, t)
for c in children[b]: # @line L16
rename(c)
for v in pushed: # @line L17
stacks[v].pop()
rename(root)
preds = {label: [] for label in out}
for a in out:
for s in succ[a]:
preds[s].append(a)
blocks = {}
for label, (instrs, t) in out.items():
# Write the operands of each phi-function in predecessor order.
head = [("phi", x, {p: args[p] for p in preds[label]}) for _, x, args in new_phis[label]]
if label == root:
head = [("const", name, 0) for name in undefined] + head
blocks[label] = Block(head + instrs, t)
return Program(list(prog.params), blocks)
def strip_versions(prog):
"""Out of SSA for the output of cytron_ssa: drop the phi-functions and
map each name v.k back to v. This is correct because the construction
keeps the program conventional: 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_cytron_ssa_construction.py 332 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cytron-ssa-construction/. The authors are listed in prov/BVFDF2.jsonl.
import random
import toyir
from toyir import Block, Program
from cytron_ssa_construction import cytron_ssa, place_phis, strip_versions, variables
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:
t1.0 = 0
t2.0 = 0
i.1 = 0
s.1 = 0
jump B2
B2:
i.2 = phi [B1: i.1, B5: i.3]
s.2 = phi [B1: s.1, B5: s.4]
t1.1 = phi [B1: t1.0, B5: t1.2]
t2.1 = phi [B1: t2.0, B5: t2.2]
t1.2 = i.2 < n
br t1.2 B3 B6
B3:
t2.2 = i.2 % 2
br t2.2 B4 B5
B4:
s.3 = s.2 + i.2
jump B5
B5:
s.4 = phi [B3: s.2, B4: s.3]
i.3 = i.2 + 1
jump B2
B6:
ret s.2
"""
# ------------------------------------------------------------ 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 def_sites(prog):
sites = {v: {prog.entry} for v in variables(prog)}
for label, b in prog.blocks.items():
for ins in b.instrs:
sites[ins[1]].add(label)
return sites
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 _paths_into(succ, x):
"""All non-empty paths from x that end at their first repeated node or
earlier, as (end, set of nodes before the end). A path may end at x."""
out = []
def walk(v, seen):
for w in succ[v]:
out.append((w, frozenset(seen)))
if w not in seen:
seen.add(w)
walk(w, seen)
seen.remove(w)
walk(x, {x})
return out
def brute_join(succ, s):
"""J(S): nodes y with two non-empty paths from two different nodes of S
that end at y and share no node but y."""
ends = {x: {} for x in s}
for x in s:
for y, before in _paths_into(succ, x):
if y in before and y != x:
continue # the path passed y before its end
ends[x].setdefault(y, set()).add(before - {y})
out = set()
xs = sorted(s)
for i, a in enumerate(xs):
for b in xs[i + 1:]:
for y in set(ends[a]) & set(ends[b]):
if any(not (p & q) for p in ends[a][y] for q in ends[b][y]):
out.add(y)
return out
def brute_iterated_join(succ, s):
cur = set()
while True:
nxt = brute_join(succ, set(s) | cur)
if nxt == cur:
return cur
cur = nxt
def trace(prog, args, skip=(), fuel=2000):
"""Run prog and record, for each executed non-phi instruction and
terminator, the values of its operands. Instructions that define a name
in skip are not recorded."""
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])
k = 0
for ins in b.instrs:
if ins[0] == "phi":
continue
ops = [a if isinstance(a, int) else env[a] for a in toyir.uses(ins) + [x for x in ins[2:] if isinstance(x, int)]]
if ins[1] not in skip:
out.append((label, k, tuple(ops)))
k += 1
if ins[0] == "const":
env[ins[1]] = ins[2]
elif ins[0] == "copy":
env[ins[1]] = ops[0]
else:
a = env[ins[3]] if isinstance(ins[3], str) else ins[3]
c = env[ins[4]] if isinstance(ins[4], str) else ins[4]
try:
env[ins[1]] = toyir._binop(ins[2], a, c)
except toyir._Trap:
out.append(("trap",))
return out
t = b.term
if t[0] == "ret":
out.append((label, "ret", env[t[1]] if isinstance(t[1], str) else t[1]))
return out
if t[0] == "jump":
prev, label = label, t[1]
else:
c = env[t[1]] if isinstance(t[1], str) else t[1]
out.append((label, "br", c))
prev, label = label, (t[2] if c != 0 else t[3])
out.append(("fuel",))
return out
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 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 = cytron_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_phis_at_iterated_frontier():
for _, prog in programs(1, 300):
succ = graph(prog)
df = brute_frontiers(succ, prog.entry)
phis = place_phis(prog)
for v, s in def_sites(prog).items():
want = brute_idf(df, s)
got = {b for b, vs in phis.items() if v in vs}
assert got == want
assert all(phis[b].count(v) <= 1 for b in phis)
def test_iterated_frontier_is_the_join_set():
# Minimality: a phi-function goes exactly where two definitions converge.
for _, prog in programs(2, 150, nvars=4, nblocks=6):
succ = graph(prog)
df = brute_frontiers(succ, prog.entry)
for v, s in def_sites(prog).items():
j = brute_join(succ, s)
assert brute_idf(df, s) == j
assert brute_iterated_join(succ, s) == j
def test_ssa_is_single_assignment_and_strict():
for _, prog in programs(3, 300):
check_ssa(cytron_ssa(prog))
def test_every_use_reads_the_original_value():
for rng, prog in programs(4, 300):
ssa = cytron_ssa(prog)
skip = {ins[1] for ins in ssa.blocks[ssa.entry].instrs if ins[1].endswith(".0")}
for _ in range(4):
args = [rng.randint(-3, 6), rng.randint(-3, 6)]
assert trace(ssa, args, skip) == trace(prog, args)
def test_round_trip_outputs():
for rng, prog in programs(5, 400):
ssa = cytron_ssa(prog)
back = strip_versions(ssa)
for _ in range(5):
args = [rng.randint(-4, 8), rng.randint(-4, 8)]
want = toyir.run(prog, args)
assert toyir.run(ssa, args) == want
assert toyir.run(back, args) == want
def test_quadratic_family():
for n in range(1, 10):
blocks = {"E": Block([], ("jump", "h1"))}
for i in range(1, n + 1):
blocks["h%d" % i] = Block([], ("jump", "h%d" % (i + 1) if i < n else "l%d" % n))
for i in range(n, 0, -1):
nxt = "l%d" % (i - 1) if i > 1 else "X"
blocks["l%d" % i] = Block([("const", "v%d" % i, i)], ("br", "c", "h%d" % i, nxt))
blocks["X"] = Block([], ("ret", 0))
prog = Program(["c"], blocks)
phis = place_phis(prog)
assert sum(len(vs) for vs in phis.values()) == n * (n + 1) // 2
check_ssa(cytron_ssa(prog))
assert toyir.run(cytron_ssa(prog), [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:
cytron_ssa(prog)
except ValueError:
return
assert False
History
Rosen, Wegman and Zadeck introduced phi-functions for global value numbering in 1988. Cytron, Ferrante, Rosen, Wegman and Zadeck gave the efficient construction through dominance frontiers at POPL 1989, and the full version with proofs and the control dependence graph in TOPLAS in 1991. The method made SSA form practical, and research and production compilers took it up; GCC, for example, places its phi-functions with dominance frontiers. Briggs et al. (1998) made it cheaper with semi-pruned SSA, and Sreedhar and Gao (1995) gave a linear-time placement.
References
- 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 placement of phi-functions with a worklist over the dominance frontiers, the renaming pass with one stack per variable over the dominator tree, the proofs that the result is minimal and correct, and the cost analysis
- Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 19 (Static Single-Assignment Form), inserting phi-functions and renaming the variables
- Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 9 (Data-Flow Analysis), the section on static single-assignment form, with the placement of phi-functions and the renaming
- Fabrice Rastello and Florent Bouchez Tichadou (editors), SSA-based Compiler Design, Springer, 2022, Chapter 3 (Standard Construction and Destruction Algorithms), phi-function insertion and variable renaming
- Preston Briggs, Keith D. Cooper, Timothy J. Harvey and L. Taylor Simpson, Practical improvements to the construction and destruction of static single assignment form, Software: Practice and Experience 28(8), 1998, pages 859-881, semi-pruned SSA form as a cheaper input to the same algorithm
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 BVFDF2 Edit this page History Report an error Markdown