Algorithmcore
Lazy code motion
Also called Knoop-Ruthing-Steffen algorithm.
Solves PRE with unidirectional bit-vector analyses, placing each computation as late as possible to keep register pressure low.
- Time
- O(n^2 m) worst
- Space
- Θ(n m) extra
- Where
- m = the number of distinct expressions; n = the number of nodes of the flow graph (one per instruction and terminator)
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Lazy code motion (LCM) is an algorithm for partial redundancy elimination by Knoop, Rüthing and Steffen. It finds the places where an expression can be computed so that no path computes it more often than before, and it picks the latest of these places, so the temporary that holds the value lives as short a time as possible. It uses four simple bit-vector dataflow analyses, each in one direction, where the first PRE method of Morel and Renvoise needed one bidirectional system. It needs the critical edges of the flow graph split.
In plain words
Look at one expression, such as a * b. One branch computes it and the code after the join computes it again, while the other branch does not compute it.
First find the places where the value will surely be needed later on every path, before a or b changes. Putting the computation there cannot add work to any path. Among these places, take the first ones that are not already covered by a computation above. Putting the computation there removes as many computations as can be removed.
Then push each computation down, as long as it still covers the same uses and no path gets an extra copy. Stop at the last place where it can go. At that place, store the value in a new temporary, and let every old computation read the temporary. A late computation keeps the temporary alive briefly, so it needs fewer registers.
The problem
The input is a procedure of the toy IR with const, copy and op instructions and any control flow. An expression is the text a op b of an op instruction, so a + b and b + a are different expressions. The output is a program that gives the same result or trap on every input that ends, and in which every path from the entry to a ret evaluates each expression at most as often as before. Among all such programs that only compute at safe places, LCM wants one with the fewest evaluations on every path at once, and among those, one with the shortest life for each temporary.
The algorithm
The algorithm works on a graph with one node for each instruction and one for each terminator. A node computes an expression if it is x = e, and it kills every expression with an operand that it defines. All sets are bit vectors with one bit per expression.
LCM(P)- 1
remove unreachable blocks, give the entry no predecessor, and split every critical edge - 2
for each node n: USE[n] <- the expression n computes; KILL[n] <- the expressions with an operand defined at n - 3
ANT.out[n] = ∩ ANT.in[s] over successors s (∅ at a ret); ANT.in[n] = USE[n] ∪ (ANT.out[n] \ KILL[n]) - 4
AV.in[n] = ∩ AV.out[p] over predecessors p (∅ at the entry); AV.out[n] = (ANT.in[n] ∪ AV.in[n]) \ KILL[n] - 5
EARLIEST[n] <- ANT.in[n] \ AV.in[n] - 6
POST.in[n] = ∩ POST.out[p] (∅ at the entry); POST.out[n] = (EARLIEST[n] ∪ POST.in[n]) \ USE[n] - 7
LATEST[n] <- (EARLIEST[n] ∪ POST.in[n]) ∩ (USE[n] ∪ not ∩ (EARLIEST[s] ∪ POST.in[s]) over successors s) - 8
USED.out[n] = ∪ USED.in[s]; USED.in[n] = (USE[n] ∪ USED.out[n]) \ LATEST[n] - 9
for each node n and each e in LATEST[n] ∩ USED.out[n]: insert t_e = e before n - 10
for each node n that is x = e - 11
if e is not in LATEST[n], or e is in USED.out[n], then replace it by x = t_e - 12
return P
Each equation of lines L3, L4, L6 and L8 is solved by iteration to a fixed point. The intersections start from the full set and the union starts from the empty set.
- ANT (line L3) is the anticipated or very busy analysis. says that every path from computes before an operand changes. Such a node is down-safe, and a computation there adds no work to any path.
- AV (line L4) is availability under the guess that is computed at every down-safe point. EARLIEST (line L5) keeps the down-safe points where is not yet available. Inserting there and replacing every old computation is busy code motion, which is already computationally optimal.
- POST (line L6) moves the computation down. says that on every path to an earliest point came before, with no use of since then. LATEST (line L7) is the last such node: it uses , or one of its successors cannot take the computation.
- USED (line L8) is a liveness analysis for the temporary. If a latest point computes and no later node reads the temporary, line L11 keeps
x = eand no temporary is made.
Example
The parameters are a, b and n.
B0:
i = 0
br n B1 B2
B1:
x = a * b
jump B3
B2:
a = a + 1
jump B3
B3:
i = i + 1
y = a * b
c = i < n
br c B3 B4
B4:
z = a * b
ret z
The edge from B3 to itself is critical, so line L1 adds a block B3_B3 that only jumps to B3. The analyses give these points.
| expression | EARLIEST | LATEST | inserted at |
|---|---|---|---|
a * b |
start of B1; end of B2, after a = a + 1 |
the same | the same |
i + 1 |
end of B0, after i = 0; B3_B3 |
i = i + 1 in B3 |
nowhere |
i < n |
y = a * b in B3 |
c = i < n in B3 |
nowhere |
a + 1 |
a = a + 1 in B2 |
the same | nowhere |
The expression a * b is not anticipated in B0, because B2 changes a before any use. So the two earliest points are in the branches. In B3, a * b is available from both branches and from the back edge, so the computation leaves the loop. The result is:
B1:
pre.0 = a * b
x = pre.0
jump B3
B2:
a = a + 1
pre.0 = a * b
jump B3
B3:
i = i + 1
y = pre.0
c = i < n
br c B3_B3 B4
B3_B3:
jump B3
B4:
z = pre.0
ret z
On the input , , the loop runs three times, and the operations run drop from 11 to 7, all from a * b.
Busy code motion evaluates every expression as often as LCM on every path, but it makes three more temporaries. It computes i + 1 at the end of B0 and on the back edge, so pre.2 lives from B0 through B1 or B2 into B3. It also sends a + 1 through a temporary and computes i < n one instruction early. LCM leaves these three computations at their old places, where no temporary is needed.
Correctness
The proof file has the full proof. It fixes one expression and reads each analysis as a statement about all paths, which is exact for these bit-vector problems by the MOP and MFP coincidence theorem.
- Safety. Every insertion is at a down-safe node. If it traps, the old program, which goes on from the same state, either traps on the way or reaches a computation of the same expression with the same operands, which traps too. A replaced
x = ereads a temporary that was computed from the same operand values without a trap. So on every input on which the old program ends, the new program returns the same value or also traps. - Computational optimality. On a path from the entry to a
ret, each earliest point starts a segment that ends at the next computation of . Every safe and correct placement must compute inside each segment, because the earliest point has a path from the entry on which is not available. The segments are disjoint, so no placement does better than one computation per segment. LCM has exactly one computation in each segment. - Lifetime optimality. A placement with the same counts as LCM has exactly one computation in each segment, and it is never after the LCM point. So wherever the LCM temporary is live, the other temporary is live too.
The proof uses the split edges in three lemmas. After the split, a node with two predecessors has predecessors with one successor each. So the end of a branching block never needs a computation that only one of its successors wants.
Proof: Lazy code motion is safe, computationally optimal and lifetime optimalfull
Setting. The program has const, copy and op instructions only. After line L1 it has these properties. Every block is reachable from the entry block, and the entry block has no predecessor. No edge goes from a block with two successors to a block with two predecessors. We also assume that every block can reach a ret. The proof works on the node graph: one node for each instruction and one for each terminator, with an edge from each node to the next one in its block and from a terminator node to the first node of each successor block. Write for the first node of the entry block. A path is a finite sequence of nodes along edges, and a complete path goes from to a ret node. A path can visit a node more than once, so we count positions on a path.
Fix one expression . The bit vectors treat each expression on its own, so this is no loss. says that node computes , and says that does not define or . A node computes before it defines, so a = a + b computes and is not transparent.
The node graph has this property, which is the only place where split edges matter:
(P) If a node has two or more predecessors, each of them is a terminator node with one successor. A terminator node defines nothing and computes nothing.
A node inside a block has one predecessor. So a node with two predecessors is the first node of a block , and its predecessors are the terminators of the blocks before . A block before with two successors would give a critical edge.
1. What the equations mean
All six analyses are bit-vector problems with distributive transfer functions, so the round-robin iteration gives the meet over all paths, by the MOP and MFP coincidence theorem. The analyses that meet with start at the full set and give the greatest solution. This is the meaning of each one, for :
- (line L3, the value of ANT.in): every path from to a
retnode has a position with and every node before it, from on, transparent. We say is down-safe. - (line L4): every path from to has a position before with at and the nodes from to the predecessor of transparent. It is false at .
- (line L5).
- (line L6): every path from to has a position with at and no node from to the predecessor of .
- (line L7): , and or some successor of is not . At a
retnode this is . - (line L8, the least solution): some path from a successor of reaches a node , and no node on it, included, is .
- is up-safe if every path from to has a position with and the nodes from to the predecessor of , included, transparent. A node is safe if it is down-safe or up-safe.
2. Placements
A placement is a set of nodes. Its program computes t = e just before each node of , into a new name , and replaces each original x = e by x = t. A placement is admissible if every node of is safe, and if on every path from to a node there is a position of a node of such that the nodes from to the predecessor of are transparent. We say that is valid at .
The LCM program is the program of the placement
Line L9 inserts at . At a node with , line L11 keeps x = e, which is the same as t = e; x = t with a dead . On every path both programs evaluate equally often and write the same values into the old names.
The placement of busy code motion (BCM) is .
3. Admissible placements keep the outcome
Theorem A. Let be admissible. On each input, if the old program returns , the new program returns . If the old program traps, the new program traps.
Proof. Run both programs on the same input, and use fuel without limit. They take the same branches and hold the same values in the old names, as long as the new program does not trap at an inserted t = e. The induction step for an old instruction is clear, except at a replaced x = e at a node . There is valid at along the path of the run. The last t = e before is at or after the position that validity gives. So it ran with the operand values that has at , and holds the value of . That t = e did not trap, so x = e would not trap either.
Now say an inserted t = e before node traps, and the old run has not stopped yet. If is up-safe, the path of the run has a position before with and transparent nodes from on. The old run computed at with the same operand values. That would have trapped, and the run would have stopped. So is down-safe. The old run goes on from in the same state. If it traps before it reaches a ret, both runs trap. Otherwise its path from reaches a ret node, so by down-safety it reaches a node first, through transparent nodes, and traps there with the same operands.
The proof needs the old run to end. A run that never ends can pass a down-safe node and then loop forever away from the computation, and the new run then traps. The tests use programs that stop.
4. The two placements are admissible
Lemma 1. On a path from with , there is a with and transparent.
Proof. Take the least with and transparent; is a candidate. If , then and the path has a with and transparent. Then is a smaller candidate.
Lemma 2. If , are transparent and none of them computes , then for .
Proof. Any path from to a ret node, with in front, is a path from . Its first node is at or after , and the nodes before it are transparent.
Lemma 3. If , then .
Proof. Every node reaches a ret. Take a path from to and its position from the meaning of DELAY. Continue the path from to a ret node. Down-safety at and the absence of from to the predecessor of give that up to the predecessor of are transparent. Lemma 2 gives .
Theorem B. and are admissible.
Proof. Safety: , and by Lemma 3.
Validity for BCM: if then , and Lemma 1 gives the position.
Validity for LCM: take a path with . Lemma 1 gives with and transparent. Walk from . holds at . If is not , it does not compute and all its successors are , so . At , makes . So has a position. Let be the largest. If , then . If , no node is , so by the path , and . In both cases the nodes from to are transparent.
5. Computational optimality
Fix a complete path . For each position on , let be the first position with . It exists, since and ends at a ret, and are transparent. Call the segment of .
Lemma 4. No node at a position in is , so the segments on are disjoint.
Proof. Let . By Lemma 2, every node from to is down-safe. We show . holds, because is down-safe and transparent. If has another predecessor , then by (P) is a terminator with the one successor . Since is down-safe and is transparent and computes nothing, is down-safe, so . So all predecessors give , and .
Lemma 5. Every admissible placement has a node at some position of each segment.
Proof. Say no node of is at a position in . If , validity at along fails at once. Otherwise gives a path from to a predecessor of with no position that has and transparent nodes from to the end of . On the path , validity gives a position of a node of with transparent nodes from on. The node at is not one of , so is on . If the node at is down-safe, is a forbidden . If it is up-safe, the part of before has a position with transparent nodes from on, and is a forbidden , since implies .
Lemma 6. On , every position of lies in a segment, and each segment holds at most one of them.
Proof. Let be a position of . Then , so there is a position with and no from to . Take the largest such , and call it . As in the proof of Lemma 3, down-safety at makes the nodes from to transparent. None of them computes , so and is in the segment of .
Now let be positions of with . Then no is in , so does not compute , and is because a successor is not . If has two successors, (P) says that each has as its only predecessor, so each is through . So has the one successor . We show for . Take any path from to , and add . The meaning of gives an position with no up to . It is not in , since such a position on would be larger than and allowed. So it is on , and it shows . With , is not , which is false. So , and the map is one to one.
Theorem C. For every admissible placement and every complete path , BCM and LCM evaluate equally often on , and no more often than .
Proof. The program of a placement evaluates exactly at the positions of its nodes on . BCM has one position for each segment. By Lemmas 4 and 5, has at least that many. By Lemma 6, LCM has at most that many, and by Lemma 5, applied to , at least that many.
The original program is the admissible placement that inserts just before each node, so LCM never evaluates more often on a path than the original program does.
6. Lifetime optimality
The lifetime of a placement is the set of nodes after which is live: some path from a successor of reaches a node with no node of on it, included. A placement is computationally optimal if it is admissible and evaluates as often as LCM on every complete path.
Lemma 7. Let be computationally optimal and a complete path. Then has exactly one position in each segment of and none outside the segments, and in each segment its position is at or before the position of .
Proof. The count on equals the number of segments, each segment holds at least one position (Lemma 5), and the segments are disjoint (Lemma 4). This gives the first claim, for and for . Let and be the positions of and in the segment , and say . Then , so does not compute , and as in Lemma 6 its one successor is not . So a path from to has no position with no from it to the predecessor of . Let be followed by , a complete path. A segment of that contains a position of starts at an position. By Lemma 4 on , that position is not in , so it is on before , and the segment has no from it to the end of . The choice of forbids this. So no segment of contains these positions, and by the first claim on no node of is at them. But is one of them and is in .
Theorem D. If is computationally optimal, the lifetime of is a subset of the lifetime of .
Proof. Let be in the lifetime of , by a path from a successor of to a node with no node of . Put a path from to in front and a path from to a ret node behind, to get a complete path . Say a node of is at a position of . By Lemma 7, is in a segment , and the position of in that segment is at or after . It is not on , so is after . Then is a position with , which is before the first position of the segment. This is false. So has no node of , and is in the lifetime of .
7. Why the critical edges must be split
Property (P) is used in Lemmas 4, 6 and 7. Without it the optimum can be out of reach. In the program of the page's pitfall, with a branch B2: br d B3 B4 and a partial redundancy at the join B3, the only node where a placement could evaluate a / b once on the path through B1 and never on the path to B4 is the edge B2 -> B3 itself. The block B2 is not down-safe, because the path to B4 does not compute a / b, and the start of B3 is too late. A new block on the edge gives the node that the proof needs.
Complexity
Let be the number of nodes and the number of expressions. Each node has at most two successors, so a pass of any of the four iterative analyses costs bit operations, which is word operations on a machine with -bit words. A round-robin pass in a good order reaches the fixed point after a number of passes bounded by , by the Kam and Ullman bound, where is the loop-connectedness depth, the most back edges on a simple path. This is at most . So the worst case is and the usual case is close to . The sets take bits. Working on basic blocks instead of single instructions, with local summary sets for each block, divides by the block length.
Properties
- Safe. It never inserts a computation on a path that would not compute the expression later with the same operands.
- Computationally optimal. No safe placement evaluates any expression fewer times on any path.
- Lifetime optimal. Among the computationally optimal placements, its temporaries are live at the fewest points, for each expression on its own.
- Unidirectional. Each analysis goes only forward or only backward, so standard bit-vector solvers work.
- Lexical. It moves the text
a op b. It does not see that two names hold the same value, so copies or SSA renaming can hide redundancy. - Never more evaluations. The old program is one of the placements, so no path evaluates an expression more often than before.
Variants and improvements
- Block level. The textbook form computes the sets for whole basic blocks, with local summaries for the upward-exposed and downward-exposed uses, and inserts at the start or end of a block.
- SSA form. SSAPRE gets the same placement on SSA form, one expression at a time, with sparse graphs instead of bit vectors.
- Value-based PRE. Running PRE on the classes of global value numbering instead of on lexical expressions finds redundancy that renaming hides.
- Speculation. With profile data, a compiler can give up safety on cold paths and insert computations that cannot trap where they pay off on hot paths.
- Partial dead code. Knoop, Rüthing and Steffen used the same delay idea in the other direction, to sink assignments that are dead on some paths.
When to use it
Use LCM as the global redundancy pass of a compiler that works on a flow graph without SSA, or with SSA names mapped back to lexical expressions. It removes common subexpressions and moves loop-invariant code in one pass, and it does not lengthen live ranges the way busy hoisting does. On SSA form, SSAPRE is often the simpler fit. If most redundancy is between different names with equal values, run global value numbering first.
Pitfalls
-
Critical edges. In this program
a / bis partially redundant atB3, butB2 -> B3is a critical edge.B0: br c B1 B2 B1: x = a / b jump B3 B2: br d B3 B4 B3: y = a / b ret y B4: ret 0The computation cannot go into
B2, because the path toB4does not divide, andbcan be 0 there. The start ofB3is too late. Only a new block on the edge can take it, and LCM putspre.0 = a / bthere. -
Loops that may not run. In a
whileloop whose test comes first,a / bin the body is not down-safe at the loop entry, because the loop can exit at once. LCM leaves it in the loop. Turning the loop into a test followed by ado-whileloop makes the computation down-safe in the guarded block. -
Runs that never end. Safety looks at paths that reach a
ret. If a run passes an insertion and then loops forever, the new program can trap where the old one only ran forever. -
An operand defined by the same node.
a = a + buses and kills it. The insertion goes before the node, and the expression is not available after it. -
Optimal per expression only. Lifetime optimality holds for each temporary alone. Many temporaries can still raise the register pressure, and the copies
x = tneed copy propagation or coalescing afterwards.
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/lazy-code-motion/. The authors are listed in prov/AQQH48.jsonl.
"""Lazy code motion (Knoop, Ruthing and Steffen) on the toy IR.
lcm(prog) takes a program with const, copy and op instructions only. It
removes unreachable blocks, gives the entry no predecessor, and splits every
critical edge with a new block that only jumps. Then it works on a graph with
one node for each instruction and one node for each terminator. An
expression is the lexical triple (op, a, b) of an op instruction. Each
expression e gets a new temporary t_e. The program computes t_e = e at the
latest safe points, and an original x = e becomes x = t_e unless it is the
only use of a value computed at that point.
Sets of expressions are Python ints used as bit vectors. analyses(prog)
returns all the sets, so the tests and the page can look at them.
"""
import toyir
# ------------------------------------------------------------------- graph
def normalize(prog):
"""A copy of prog without unreachable blocks, with an entry that has no
predecessor, and with every critical edge split. An edge A -> B is
critical if A has two successors and B has two predecessors. The new
block on the edge only jumps to B."""
for blk in prog.blocks.values():
for ins in blk.instrs:
if ins[0] not in ("const", "copy", "op"):
raise ValueError("lcm handles const, copy and op only: %r" % (ins,))
reach = {prog.entry}
stack = [prog.entry]
while stack:
b = stack.pop()
for s in toyir.succs(prog, b):
if s not in reach:
reach.add(s)
stack.append(s)
taken = set(prog.blocks)
def fresh(base):
name = base
while name in taken:
name += "_"
taken.add(name)
return name
blocks = {}
if any(prog.entry in toyir.succs(prog, b) for b in reach):
blocks[fresh("start")] = toyir.Block([], ("jump", prog.entry))
for label, blk in prog.blocks.items():
if label in reach:
blocks[label] = toyir.Block(list(blk.instrs), blk.term)
p = toyir.Program(list(prog.params), blocks)
npred = {b: len(ps) for b, ps in toyir.preds(p).items()}
out = {}
for label, blk in p.blocks.items():
out[label] = blk
t = blk.term
if t[0] == "br" and t[2] != t[3]:
targets = []
for s in (t[2], t[3]):
if npred[s] > 1:
mid = fresh(label + "_" + s)
out[mid] = toyir.Block([], ("jump", s))
targets.append(mid)
else:
targets.append(s)
blk.term = ("br", t[1], targets[0], targets[1])
return toyir.Program(list(prog.params), out)
class Graph:
"""The node graph of a program. Node (b, i) is instruction i of block b,
and node (b, len(instrs)) is the terminator of b."""
def __init__(self, prog):
self.prog = prog
self.nodes = []
self.succ = {}
for b, blk in prog.blocks.items():
k = len(blk.instrs)
for i in range(k + 1):
self.nodes.append((b, i))
self.succ[(b, i)] = [(b, i + 1)] if i < k else [(s, 0) for s in toyir.succs(prog, b)]
self.pred = {n: [] for n in self.nodes}
for n in self.nodes:
for s in self.succ[n]:
self.pred[s].append(n)
def instr(self, n):
blk = self.prog.blocks[n[0]]
return blk.instrs[n[1]] if n[1] < len(blk.instrs) else None
def expression(ins):
"""The expression (op, a, b) that an instruction computes, or None."""
if ins is not None and ins[0] == "op":
return (ins[2], ins[3], ins[4])
return None
# --------------------------------------------------------------- analyses
def analyses(prog):
"""All the sets of lazy code motion for a normalized program. Returns a
dict with the graph, the list of expressions, and a dict node -> bit set
for each of use, kill, ant_in, ant_out, av_in, av_out, earliest,
post_in, post_out, latest, used_in and used_out."""
g = Graph(prog)
nodes, succ, pred = g.nodes, g.succ, g.pred
exprs = []
index = {}
for n in nodes:
e = expression(g.instr(n))
if e is not None and e not in index:
index[e] = len(exprs)
exprs.append(e)
full = (1 << len(exprs)) - 1
reads = {}
for e, i in index.items():
for a in e[1:]:
if isinstance(a, str):
reads[a] = reads.get(a, 0) | (1 << i)
use, kill = {}, {}
for n in nodes: # @line L2
ins = g.instr(n)
e = expression(ins)
use[n] = 0 if e is None else 1 << index[e]
kill[n] = 0 if ins is None else reads.get(ins[1], 0)
# Anticipated (down-safe): on every path to the exit, e is computed
# before an operand changes.
ant_in = {n: full for n in nodes}
ant_out = {}
changed = True
while changed: # @line L3
changed = False
for n in reversed(nodes):
out = full if succ[n] else 0
for s in succ[n]:
out &= ant_in[s]
ant_out[n] = out
new = use[n] | (out & ~kill[n])
if new != ant_in[n]:
ant_in[n] = new
changed = True
# Available if e were computed at every earliest point.
av_out = {n: full for n in nodes}
av_in = {}
changed = True
while changed: # @line L4
changed = False
for n in nodes:
inn = full if pred[n] else 0
for p in pred[n]:
inn &= av_out[p]
av_in[n] = inn
new = (ant_in[n] | inn) & ~kill[n]
if new != av_out[n]:
av_out[n] = new
changed = True
earliest = {n: ant_in[n] & ~av_in[n] for n in nodes} # @line L5
post_out = {n: full for n in nodes}
post_in = {}
changed = True
while changed: # @line L6
changed = False
for n in nodes:
inn = full if pred[n] else 0
for p in pred[n]:
inn &= post_out[p]
post_in[n] = inn
new = (earliest[n] | inn) & ~use[n]
if new != post_out[n]:
post_out[n] = new
changed = True
latest = {}
for n in nodes: # @line L7
nxt = full
for s in succ[n]:
nxt &= earliest[s] | post_in[s]
latest[n] = (earliest[n] | post_in[n]) & (use[n] | (full & ~nxt))
used_in = {n: 0 for n in nodes}
used_out = {}
changed = True
while changed: # @line L8
changed = False
for n in reversed(nodes):
out = 0
for s in succ[n]:
out |= used_in[s]
used_out[n] = out
new = (use[n] | out) & ~latest[n]
if new != used_in[n]:
used_in[n] = new
changed = True
return {
"graph": g, "exprs": exprs, "use": use, "kill": kill,
"ant_in": ant_in, "ant_out": ant_out, "av_in": av_in, "av_out": av_out,
"earliest": earliest, "post_in": post_in, "post_out": post_out,
"latest": latest, "used_in": used_in, "used_out": used_out,
}
# -------------------------------------------------------------- transform
def names_of(prog):
out = set(prog.params)
for blk in prog.blocks.values():
for ins in blk.instrs:
out.add(ins[1])
out.update(toyir.uses(ins))
out.update(toyir.term_uses(blk.term))
return out
def rewrite(prog, exprs, insert, replace):
"""Build the new program. insert[n] and replace[n] are bit sets: insert
t_e = e before node n for each e in insert[n], and turn the instruction
x = e at n into x = t_e if e is in replace[n]."""
taken = names_of(prog)
temp = []
for i in range(len(exprs)):
name = "pre.%d" % i
while name in taken:
name += "_"
taken.add(name)
temp.append(name)
blocks = {}
for b, blk in prog.blocks.items():
instrs = []
for i in range(len(blk.instrs) + 1):
n = (b, i)
for k, e in enumerate(exprs):
if insert[n] >> k & 1:
instrs.append(("op", temp[k], e[0], e[1], e[2]))
if i < len(blk.instrs):
ins = blk.instrs[i]
e = expression(ins)
if e is not None and replace[n] >> exprs.index(e) & 1:
instrs.append(("copy", ins[1], temp[exprs.index(e)]))
else:
instrs.append(ins)
blocks[b] = toyir.Block(instrs, blk.term)
return toyir.Program(list(prog.params), blocks)
def lcm(prog):
"""Lazy code motion. Returns the new program. Its blocks are the blocks
of normalize(prog), with the same terminators."""
p = normalize(prog) # @line L1
a = analyses(p)
nodes = a["graph"].nodes
insert = {n: a["latest"][n] & a["used_out"][n] for n in nodes} # @line L9
replace = {}
for n in nodes: # @line L10
u = a["use"][n]
replace[n] = u & (~a["latest"][n] | a["used_out"][n]) # @line L11
return rewrite(p, a["exprs"], insert, replace) # @line L12
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_lazy_code_motion.py 370 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lazy-code-motion/. The authors are listed in prov/AQQH48.jsonl.
import random
from collections import Counter
import toyir
import lazy_code_motion as L
PAGE_BEFORE = """# params: a, b, n
B0:
i = 0
br n B1 B2
B1:
x = a * b
jump B3
B2:
a = a + 1
jump B3
B3:
i = i + 1
y = a * b
c = i < n
br c B3 B4
B4:
z = a * b
ret z
"""
PAGE_AFTER = """# params: a, b, n
B0:
i = 0
br n B1 B2
B1:
pre.0 = a * b
x = pre.0
jump B3
B2:
a = a + 1
pre.0 = a * b
jump B3
B3:
i = i + 1
y = pre.0
c = i < n
br c B3_B3 B4
B3_B3:
jump B3
B4:
z = pre.0
ret z
"""
PAGE_BUSY = """# params: a, b, n
B0:
i = 0
pre.2 = i + 1
br n B1 B2
B1:
pre.0 = a * b
x = pre.0
jump B3
B2:
pre.1 = a + 1
a = pre.1
pre.0 = a * b
jump B3
B3:
i = pre.2
pre.3 = i < n
y = pre.0
c = pre.3
br c B3_B3 B4
B3_B3:
pre.2 = i + 1
jump B3
B4:
z = pre.0
ret z
"""
FUEL = 100000
def busy(prog):
"""Busy code motion: insert at the earliest points and replace every
original computation."""
p = L.normalize(prog)
a = L.analyses(p)
return L.rewrite(p, a["exprs"], a["earliest"], a["use"])
def counts(prog, path):
c = Counter()
for b in path:
for ins in prog.blocks[b].instrs:
e = L.expression(ins)
if e is not None:
c[e] += 1
return c
VARS = ("x0", "x1", "x2")
def dense_instr(rng):
r = rng.random()
if r < 0.2:
x = rng.choice(VARS)
return ("op", x, "+", x, 1)
if r < 0.3:
return ("copy", rng.choice(VARS), rng.choice(VARS))
x = rng.choice(VARS + ("y0", "y1"))
return ("op", x, rng.choice(("+", "/")), rng.choice(VARS), rng.choice(VARS + (2,)))
def dense(rng, nblocks, acyclic, most=3):
"""A random program over few names and two operators, so the same
expression is often computed on several paths. Division by a variable
can trap. The control flow and the loop counters come from
toyir.random_program."""
prog = toyir.random_program(rng, 3, nblocks, acyclic)
for blk in prog.blocks.values():
new = []
for ins in blk.instrs:
if ins[0] in ("op", "copy") and ins[1] in VARS:
for _ in range(rng.randint(1, most)):
new.append(dense_instr(rng))
else:
new.append(ins)
blk.instrs = new
return prog
def programs(seed, n):
rng = random.Random(seed)
for k in range(n):
acyclic = k % 2 == 0
if k % 3 == 0:
yield toyir.random_program(rng, rng.randint(2, 4), rng.randint(2, 7), acyclic)
else:
yield dense(rng, rng.randint(2, 7), acyclic)
ARGS = [(0, 0), (1, 0), (0, 1), (2, 3), (-2, 2), (3, -1), (2, 2), (-1, -1)]
def node_paths(prog):
out = []
for path in toyir.paths(prog):
ns = []
for b in path:
ns += [(b, i) for i in range(len(prog.blocks[b].instrs) + 1)]
out.append(ns)
return out
def up_safe(g, comp, killn):
"""Up-safe: on every path from the entry, e was computed and no operand
changed since."""
up_in = {n: True for n in g.nodes}
up_out = {n: True for n in g.nodes}
changed = True
while changed:
changed = False
for n in g.nodes:
inn = bool(g.pred[n]) and all(up_out[p] for p in g.pred[n])
out = (inn or n in comp) and n not in killn
if (inn, out) != (up_in[n], up_out[n]):
up_in[n], up_out[n] = inn, out
changed = True
return up_in
def admissible(g, comp, killn, ins):
"""True if t = e is valid at every original computation of e when it
is computed before each node of ins."""
vout = {n: True for n in g.nodes}
before = {}
changed = True
while changed:
changed = False
for n in g.nodes:
inn = bool(g.pred[n]) and all(vout[p] for p in g.pred[n])
before[n] = inn or n in ins
out = before[n] and n not in killn
if out != vout[n]:
vout[n] = out
changed = True
return all(before[n] for n in comp)
def lifetime(g, comp, ins):
"""The nodes after which t is live."""
live_before = {n: False for n in g.nodes}
live_out = {n: False for n in g.nodes}
changed = True
while changed:
changed = False
for n in reversed(g.nodes):
out = any(live_before[s] for s in g.succ[n])
before = n not in ins and (n in comp or out)
if (out, before) != (live_out[n], live_before[n]):
live_out[n], live_before[n] = out, before
changed = True
return frozenset(n for n in g.nodes if live_out[n])
def safe_placements(prog, a, k, limit):
"""Every admissible placement of expression k at safe nodes, as pairs
(set of nodes, evaluations per path). None if there are too many safe
nodes."""
g = a["graph"]
bit = 1 << k
comp = {n for n in g.nodes if a["use"][n] & bit}
killn = {n for n in g.nodes if a["kill"][n] & bit}
up = up_safe(g, comp, killn)
safe = [n for n in g.nodes if a["ant_in"][n] & bit or up[n]]
if len(safe) > limit:
return None
paths = node_paths(prog)
out = []
for mask in range(1 << len(safe)):
ins = {safe[j] for j in range(len(safe)) if mask >> j & 1}
if admissible(g, comp, killn, ins):
out.append((ins, tuple(sum(n in ins for n in p) for p in paths)))
return comp, out
# ------------------------------------------------------------------- tests
def test_page_example():
p = toyir.parse(PAGE_BEFORE)
q = L.lcm(p)
assert toyir.show(q) == PAGE_AFTER
assert toyir.show(busy(p)) == PAGE_BUSY
for args in [(2, 3, 1), (2, 3, 4), (0, 0, 0), (5, -1, 2)]:
assert toyir.run(q, args) == toyir.run(p, args)
# One trip through the loop on the path through B1: a * b runs 3 times
# before and once after.
path = ["B0", "B1", "B3", "B4"]
e = ("*", "a", "b")
assert counts(p, path)[e] == 3 and counts(q, path)[e] == 1
def test_same_outcome_on_random_programs():
for prog in programs(1, 400):
q = L.lcm(prog)
b = busy(prog)
for args in ARGS:
want = toyir.run(prog, args, FUEL)
assert want != ("fuel",)
assert toyir.run(q, args, FUEL) == want
assert toyir.run(b, args, FUEL) == want
def test_never_more_evaluations_on_any_path():
better = 0
for prog in programs(2, 400):
if not toyir.is_acyclic(prog):
continue
p = L.normalize(prog)
q = L.lcm(prog)
b = busy(prog)
assert list(q.blocks) == list(p.blocks)
for path in toyir.paths(p):
old, new, bcm = counts(p, path), counts(q, path), counts(b, path)
for e in old:
assert new[e] <= old[e]
assert new[e] == bcm[e]
better += new[e] < old[e]
assert set(new) <= set(old)
assert better > 50
def test_computationally_and_lifetime_optimal():
rng = random.Random(3)
checked = optimal_others = 0
for _ in range(250):
prog = L.normalize(dense(rng, rng.randint(2, 4), True, most=2))
a = L.analyses(prog)
q = L.rewrite(prog, a["exprs"],
{n: a["latest"][n] & a["used_out"][n] for n in a["graph"].nodes},
{n: a["use"][n] & (~a["latest"][n] | a["used_out"][n]) for n in a["graph"].nodes})
assert toyir.show(q) == toyir.show(L.lcm(prog))
paths = node_paths(prog)
for k, e in enumerate(a["exprs"]):
bit = 1 << k
got = safe_placements(prog, a, k, 10)
if got is None:
continue
comp, places = got
mine = {n for n in a["graph"].nodes
if a["latest"][n] & bit and (a["used_out"][n] | a["use"][n]) & bit}
vec = tuple(sum(n in mine for n in p) for p in paths)
# The placement model gives the counts of the real program.
assert vec == tuple(counts(q, toyir.paths(prog)[i])[e] for i in range(len(paths)))
assert any(ins == mine for ins, _ in places)
life = lifetime(a["graph"], comp, mine)
for ins, v in places:
assert all(x <= y for x, y in zip(vec, v))
if v == vec:
assert life <= lifetime(a["graph"], comp, ins)
optimal_others += ins != mine
checked += 1
assert checked > 300 and optimal_others > 50
CRITICAL = """# params: a, b, c, d
B0:
br c B1 B2
B1:
x = a / b
jump B3
B2:
br d B3 B4
B3:
y = a / b
ret y
B4:
ret 0
"""
def test_critical_edge_gets_the_insertion():
p = toyir.parse(CRITICAL)
q = L.lcm(p)
assert q.blocks["B2_B3"].instrs == [("op", "pre.0", "/", "a", "b")]
assert q.blocks["B2"].instrs == [] and q.blocks["B0"].instrs == []
e = ("/", "a", "b")
assert counts(q, ["B0", "B1", "B3"])[e] == 1
# b = 0 on the path to B4: no division runs there.
assert toyir.run(p, (1, 0, 0, 0)) == toyir.run(q, (1, 0, 0, 0)) == ("ret", 0)
def test_without_split_no_safe_placement_removes_the_redundancy():
p = toyir.parse(CRITICAL)
a = L.analyses(p) # the graph of p itself, with the critical edge
comp, places = safe_placements(p, a, 0, 12)
paths = toyir.paths(p)
old = tuple(counts(p, path)[("/", "a", "b")] for path in paths)
for _, v in places:
assert v == old or any(x > y for x, y in zip(v, old))
ZERO_TRIP = """# params: a, b, n
B0:
i = 0
jump B1
B1:
c = i < n
br c B2 B3
B2:
x = a / b
i = i + 1
jump B1
B3:
ret i
"""
def test_no_hoisting_out_of_a_loop_that_may_not_run():
p = toyir.parse(ZERO_TRIP)
q = L.lcm(p)
for b, blk in q.blocks.items():
for ins in blk.instrs:
if L.expression(ins) == ("/", "a", "b"):
assert b == "B2"
assert toyir.run(q, (1, 0, 0)) == ("ret", 0)
assert toyir.run(q, (1, 0, 2)) == ("trap",)
History
Morel and Renvoise introduced partial redundancy elimination in 1979, with a bidirectional system of equations that was hard to solve and could move computations higher than needed. Knoop, Rüthing and Steffen presented lazy code motion at PLDI 1992. They split the problem into busy code motion, which is computationally optimal, and a delay step, which makes it lifetime optimal, and they showed that unidirectional analyses suffice. The full proofs appeared in TOPLAS in 1994. The second edition of the Dragon book presents the block-level form with anticipated, available, postponable and used expressions, and Chow and colleagues carried the same results to SSA form with SSAPRE in 1997.
References
- Jens Knoop, Oliver Rüthing and Bernhard Steffen, Lazy code motion, Proceedings of the ACM SIGPLAN 1992 Conference on Programming Language Design and Implementation (PLDI 1992), the whole paper (down-safety and earliestness, the delay and isolation analyses, and the claims of computational and lifetime optimality)
- Jens Knoop, Oliver Rüthing and Bernhard Steffen, Optimal code motion: theory and practice, ACM Transactions on Programming Languages and Systems 16(4), 1994, 1117-1155, the whole paper (the full proofs of safety, computational optimality and lifetime optimality, and busy code motion as the first step)
- Etienne Morel and Claude Renvoise, Global optimization by suppression of partial redundancies, Communications of the ACM 22(2), 1979, 96-103, the whole paper (the first formulation of partial redundancy elimination, with a bidirectional system of equations)
- Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers: Principles, Techniques, and Tools, 2nd edition, Addison-Wesley, 2006, Section 9.5 (Partial-Redundancy Elimination, the lazy code motion algorithm with anticipated, available, postponable and used expressions)
- Keith D. Cooper and Linda Torczon, Engineering a Compiler, 3rd edition, Morgan Kaufmann, 2022, Section 10.3.1 (Lazy Code Motion)
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 AQQH48 Edit this page History Report an error Markdown