Algorithm Search⌘K

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)
Properties
deterministicofflineiterative

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.

  1. LCM(P)
  2. 1remove unreachable blocks, give the entry no predecessor, and split every critical edge
  3. 2for each node n: USE[n] <- the expression n computes; KILL[n] <- the expressions with an operand defined at n
  4. 3ANT.out[n] = ∩ ANT.in[s] over successors s (∅ at a ret); ANT.in[n] = USE[n] ∪ (ANT.out[n] \ KILL[n])
  5. 4AV.in[n] = ∩ AV.out[p] over predecessors p (∅ at the entry); AV.out[n] = (ANT.in[n] ∪ AV.in[n]) \ KILL[n]
  6. 5EARLIEST[n] <- ANT.in[n] \ AV.in[n]
  7. 6POST.in[n] = ∩ POST.out[p] (∅ at the entry); POST.out[n] = (EARLIEST[n] ∪ POST.in[n]) \ USE[n]
  8. 7LATEST[n] <- (EARLIEST[n] ∪ POST.in[n]) ∩ (USE[n] ∪ not ∩ (EARLIEST[s] ∪ POST.in[s]) over successors s)
  9. 8USED.out[n] = ∪ USED.in[s]; USED.in[n] = (USE[n] ∪ USED.out[n]) \ LATEST[n]
  10. 9for each node n and each e in LATEST[n] ∩ USED.out[n]: insert t_e = e before n
  11. 10for each node n that is x = e
  12. 11if e is not in LATEST[n], or e is in USED.out[n], then replace it by x = t_e
  13. 12return 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. e∈ANT.in[n]e \in \mathrm{ANT.in}[n] says that every path from nn computes ee 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 ee is computed at every down-safe point. EARLIEST (line L5) keeps the down-safe points where ee 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. e∈POST.in[n]e \in \mathrm{POST.in}[n] says that on every path to nn an earliest point came before, with no use of ee since then. LATEST (line L7) is the last such node: it uses ee, or one of its successors cannot take the computation.
  • USED (line L8) is a liveness analysis for the temporary. If a latest point computes ee and no later node reads the temporary, line L11 keeps x = e and 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 a=2a = 2, b=3b = 3, n=3n = 3 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 = e reads 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 ee. Every safe and correct placement must compute ee inside each segment, because the earliest point has a path from the entry on which ee 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 ss for the first node of the entry block. A path is a finite sequence of nodes along edges, and a complete path goes from ss to a ret node. A path can visit a node more than once, so we count positions on a path.

Fix one expression e=aopbe = a \mathbin{op} b. The bit vectors treat each expression on its own, so this is no loss. Comp(n)\mathrm{Comp}(n) says that node nn computes ee, and Transp(n)\mathrm{Transp}(n) says that nn does not define aa or bb. A node computes before it defines, so a = a + b computes ee 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 BB, and its predecessors are the terminators of the blocks before BB. A block before BB 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 ∩\cap start at the full set and give the greatest solution. This is the meaning of each one, for ee:

  • ANT(n)\mathrm{ANT}(n) (line L3, the value of ANT.in): every path from nn to a ret node has a position mm with Comp(m)\mathrm{Comp}(m) and every node before it, from nn on, transparent. We say nn is down-safe.
  • AV.in(n)\mathrm{AV.in}(n) (line L4): every path from ss to nn has a position zz before nn with ANT\mathrm{ANT} at zz and the nodes from zz to the predecessor of nn transparent. It is false at ss.
  • EARLIEST(n)=ANT(n)∧¬AV.in(n)\mathrm{EARLIEST}(n) = \mathrm{ANT}(n) \wedge \neg \mathrm{AV.in}(n) (line L5).
  • DELAY(n)=EARLIEST(n)∨POST.in(n)\mathrm{DELAY}(n) = \mathrm{EARLIEST}(n) \vee \mathrm{POST.in}(n) (line L6): every path from ss to nn has a position zz with EARLIEST\mathrm{EARLIEST} at zz and no Comp\mathrm{Comp} node from zz to the predecessor of nn.
  • LATEST(n)\mathrm{LATEST}(n) (line L7): DELAY(n)\mathrm{DELAY}(n), and Comp(n)\mathrm{Comp}(n) or some successor of nn is not DELAY\mathrm{DELAY}. At a ret node this is DELAY(n)∧Comp(n)\mathrm{DELAY}(n) \wedge \mathrm{Comp}(n).
  • USED.out(n)\mathrm{USED.out}(n) (line L8, the least solution): some path from a successor of nn reaches a Comp\mathrm{Comp} node mm, and no node on it, mm included, is LATEST\mathrm{LATEST}.
  • nn is up-safe if every path from ss to nn has a position cc with Comp(c)\mathrm{Comp}(c) and the nodes from cc to the predecessor of nn, cc included, transparent. A node is safe if it is down-safe or up-safe.

2. Placements

A placement is a set II of nodes. Its program computes t = e just before each node of II, into a new name tt, and replaces each original x = e by x = t. A placement is admissible if every node of II is safe, and if on every path from ss to a Comp\mathrm{Comp} node mm there is a position ww of a node of II such that the nodes from ww to the predecessor of mm are transparent. We say that tt is valid at mm.

The LCM program is the program of the placement

ILCM={ n:LATEST(n)∧(USED.out(n)∨Comp(n)) }.I_{\mathrm{LCM}} = \{\, n : \mathrm{LATEST}(n) \wedge (\mathrm{USED.out}(n) \vee \mathrm{Comp}(n)) \,\}.

Line L9 inserts at LATEST∧USED.out\mathrm{LATEST} \wedge \mathrm{USED.out}. At a node with LATEST∧Comp∧¬USED.out\mathrm{LATEST} \wedge \mathrm{Comp} \wedge \neg\mathrm{USED.out}, line L11 keeps x = e, which is the same as t = e; x = t with a dead tt. On every path both programs evaluate ee equally often and write the same values into the old names.

The placement of busy code motion (BCM) is IBCM={ n:EARLIEST(n) }I_{\mathrm{BCM}} = \{\, n : \mathrm{EARLIEST}(n) \,\}.

3. Admissible placements keep the outcome

Theorem A. Let II be admissible. On each input, if the old program returns vv, the new program returns vv. 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 mm. There tt is valid at mm along the path of the run. The last t = e before mm is at or after the position ww that validity gives. So it ran with the operand values that ee has at mm, and tt holds the value of ee. That t = e did not trap, so x = e would not trap either.

Now say an inserted t = e before node nn traps, and the old run has not stopped yet. If nn is up-safe, the path of the run has a position cc before nn with Comp(c)\mathrm{Comp}(c) and transparent nodes from cc on. The old run computed ee at cc with the same operand values. That would have trapped, and the run would have stopped. So nn is down-safe. The old run goes on from nn in the same state. If it traps before it reaches a ret, both runs trap. Otherwise its path from nn reaches a ret node, so by down-safety it reaches a Comp\mathrm{Comp} node first, through transparent nodes, and ee traps there with the same operands. □\square

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 n1…nkn_1 \ldots n_k from ss with ANT(nk)\mathrm{ANT}(n_k), there is a j≤kj \le k with EARLIEST(nj)\mathrm{EARLIEST}(n_j) and nj…nk−1n_j \ldots n_{k-1} transparent.

Proof. Take the least jj with ANT(nj)\mathrm{ANT}(n_j) and nj…nk−1n_j \ldots n_{k-1} transparent; j=kj = k is a candidate. If AV.in(nj)\mathrm{AV.in}(n_j), then j>1j > 1 and the path n1…njn_1 \ldots n_j has a z<jz < j with ANT(nz)\mathrm{ANT}(n_z) and nz…nj−1n_z \ldots n_{j-1} transparent. Then zz is a smaller candidate. □\square

Lemma 2. If ANT(nj)\mathrm{ANT}(n_j), nj…nk−1n_j \ldots n_{k-1} are transparent and none of them computes ee, then ANT(nl)\mathrm{ANT}(n_l) for j≤l≤kj \le l \le k.

Proof. Any path from nln_l to a ret node, with nj…nl−1n_j \ldots n_{l-1} in front, is a path from njn_j. Its first Comp\mathrm{Comp} node is at or after nln_l, and the nodes before it are transparent. □\square

Lemma 3. If DELAY(n)\mathrm{DELAY}(n), then ANT(n)\mathrm{ANT}(n).

Proof. Every node reaches a ret. Take a path from ss to nn and its position zz from the meaning of DELAY. Continue the path from nn to a ret node. Down-safety at zz and the absence of Comp\mathrm{Comp} from zz to the predecessor of nn give that nz…n_z \ldots up to the predecessor of nn are transparent. Lemma 2 gives ANT(n)\mathrm{ANT}(n). □\square

Theorem B. IBCMI_{\mathrm{BCM}} and ILCMI_{\mathrm{LCM}} are admissible.

Proof. Safety: EARLIEST⊆ANT\mathrm{EARLIEST} \subseteq \mathrm{ANT}, and LATEST⊆DELAY⊆ANT\mathrm{LATEST} \subseteq \mathrm{DELAY} \subseteq \mathrm{ANT} by Lemma 3.

Validity for BCM: if Comp(m)\mathrm{Comp}(m) then ANT(m)\mathrm{ANT}(m), and Lemma 1 gives the position.

Validity for LCM: take a path n1…nkn_1 \ldots n_k with Comp(nk)\mathrm{Comp}(n_k). Lemma 1 gives jj with EARLIEST(nj)\mathrm{EARLIEST}(n_j) and nj…nk−1n_j \ldots n_{k-1} transparent. Walk from l=jl = j. DELAY(nl)\mathrm{DELAY}(n_l) holds at l=jl = j. If nln_l is not LATEST\mathrm{LATEST}, it does not compute ee and all its successors are DELAY\mathrm{DELAY}, so DELAY(nl+1)\mathrm{DELAY}(n_{l+1}). At l=kl = k, Comp(nk)\mathrm{Comp}(n_k) makes nkn_k LATEST\mathrm{LATEST}. So [j,k][j, k] has a LATEST\mathrm{LATEST} position. Let ii be the largest. If i=ki = k, then nk∈ILCMn_k \in I_{\mathrm{LCM}}. If i<ki < k, no node ni+1…nkn_{i+1} \ldots n_k is LATEST\mathrm{LATEST}, so USED.out(ni)\mathrm{USED.out}(n_i) by the path ni+1…nkn_{i+1} \ldots n_k, and ni∈ILCMn_i \in I_{\mathrm{LCM}}. In both cases the nodes from nin_i to nk−1n_{k-1} are transparent. □\square

5. Computational optimality

Fix a complete path P=n1…nrP = n_1 \ldots n_r. For each EARLIEST\mathrm{EARLIEST} position jj on PP, let m(j)m(j) be the first position ≥j\ge j with Comp\mathrm{Comp}. It exists, since ANT(nj)\mathrm{ANT}(n_j) and PP ends at a ret, and nj…nm(j)−1n_j \ldots n_{m(j)-1} are transparent. Call [j,m(j)][j, m(j)] the segment of jj.

Lemma 4. No node at a position in (j,m(j)](j, m(j)] is EARLIEST\mathrm{EARLIEST}, so the segments on PP are disjoint.

Proof. Let j<l≤m(j)j < l \le m(j). By Lemma 2, every node from njn_j to nln_l is down-safe. We show AV.in(nl)\mathrm{AV.in}(n_l). AV.out(nl−1)\mathrm{AV.out}(n_{l-1}) holds, because nl−1n_{l-1} is down-safe and transparent. If nln_l has another predecessor qq, then by (P) qq is a terminator with the one successor nln_l. Since nln_l is down-safe and qq is transparent and computes nothing, qq is down-safe, so AV.out(q)\mathrm{AV.out}(q). So all predecessors give AV.out\mathrm{AV.out}, and AV.in(nl)\mathrm{AV.in}(n_l). □\square

Lemma 5. Every admissible placement II has a node at some position of each segment.

Proof. Say no node of II is at a position in [j,m(j)][j, m(j)]. If j=1j = 1, validity at nm(j)n_{m(j)} along n1…nm(j)n_1 \ldots n_{m(j)} fails at once. Otherwise ¬AV.in(nj)\neg \mathrm{AV.in}(n_j) gives a path qq from ss to a predecessor of njn_j with no position zz that has ANT\mathrm{ANT} and transparent nodes from zz to the end of qq. On the path q nj…nm(j)q\, n_j \ldots n_{m(j)}, validity gives a position ww of a node of II with transparent nodes from ww on. The node at ww is not one of nj…nm(j)n_j \ldots n_{m(j)}, so ww is on qq. If the node at ww is down-safe, ww is a forbidden zz. If it is up-safe, the part of qq before ww has a Comp\mathrm{Comp} position cc with transparent nodes from cc on, and cc is a forbidden zz, since Comp\mathrm{Comp} implies ANT\mathrm{ANT}. □\square

Lemma 6. On PP, every position of ILCMI_{\mathrm{LCM}} lies in a segment, and each segment holds at most one of them.

Proof. Let ii be a position of ILCMI_{\mathrm{LCM}}. Then DELAY(ni)\mathrm{DELAY}(n_i), so there is a position j≤ij \le i with EARLIEST\mathrm{EARLIEST} and no Comp\mathrm{Comp} from njn_j to ni−1n_{i-1}. Take the largest such jj, and call it j(i)j(i). As in the proof of Lemma 3, down-safety at njn_j makes the nodes from njn_j to ni−1n_{i-1} transparent. None of them computes ee, so i≤m(j)i \le m(j) and ii is in the segment of jj.

Now let i<i′i < i' be positions of ILCMI_{\mathrm{LCM}} with j(i′)≤ij(i') \le i. Then no Comp\mathrm{Comp} is in nj(i′)…ni′−1n_{j(i')} \ldots n_{i'-1}, so nin_i does not compute ee, and nin_i is LATEST\mathrm{LATEST} because a successor is not DELAY\mathrm{DELAY}. If nin_i has two successors, (P) says that each has nin_i as its only predecessor, so each is DELAY\mathrm{DELAY} through POST.in\mathrm{POST.in}. So nin_i has the one successor ni+1n_{i+1}. We show DELAY(nl)\mathrm{DELAY}(n_l) for i<l≤i′i < l \le i'. Take any path qq from ss to nln_l, and add nl+1…ni′n_{l+1} \ldots n_{i'}. The meaning of DELAY(ni′)\mathrm{DELAY}(n_{i'}) gives an EARLIEST\mathrm{EARLIEST} position with no Comp\mathrm{Comp} up to ni′−1n_{i'-1}. It is not in nl+1…ni′n_{l+1} \ldots n_{i'}, since such a position on PP would be larger than j(i′)j(i') and allowed. So it is on qq, and it shows DELAY(nl)\mathrm{DELAY}(n_l). With l=i+1l = i + 1, nin_i is not LATEST\mathrm{LATEST}, which is false. So j(i′)>ij(i') > i, and the map i↦j(i)i \mapsto j(i) is one to one. □\square

Theorem C. For every admissible placement II and every complete path PP, BCM and LCM evaluate ee equally often on PP, and no more often than II.

Proof. The program of a placement evaluates ee exactly at the positions of its nodes on PP. BCM has one position for each segment. By Lemmas 4 and 5, II has at least that many. By Lemma 6, LCM has at most that many, and by Lemma 5, applied to ILCMI_{\mathrm{LCM}}, at least that many. □\square

The original program is the admissible placement that inserts just before each Comp\mathrm{Comp} node, so LCM never evaluates ee more often on a path than the original program does.

6. Lifetime optimality

The lifetime of a placement II is the set of nodes nn after which tt is live: some path from a successor of nn reaches a Comp\mathrm{Comp} node mm with no node of II on it, mm included. A placement is computationally optimal if it is admissible and evaluates ee as often as LCM on every complete path.

Lemma 7. Let II be computationally optimal and PP a complete path. Then II has exactly one position in each segment of PP and none outside the segments, and in each segment its position is at or before the position of ILCMI_{\mathrm{LCM}}.

Proof. The count on PP 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 II and for ILCMI_{\mathrm{LCM}}. Let xx and yy be the positions of ILCMI_{\mathrm{LCM}} and II in the segment [j,m(j)][j, m(j)], and say y>xy > x. Then x<m(j)x < m(j), so nxn_x does not compute ee, and as in Lemma 6 its one successor nx+1n_{x+1} is not DELAY\mathrm{DELAY}. So a path qq from ss to nx+1n_{x+1} has no EARLIEST\mathrm{EARLIEST} position with no Comp\mathrm{Comp} from it to the predecessor of nx+1n_{x+1}. Let QQ be qq followed by nx+2…nrn_{x+2} \ldots n_r, a complete path. A segment of QQ that contains a position of nx+1…nm(j)n_{x+1} \ldots n_{m(j)} starts at an EARLIEST\mathrm{EARLIEST} position. By Lemma 4 on PP, that position is not in nx+1…nm(j)n_{x+1} \ldots n_{m(j)}, so it is on qq before nx+1n_{x+1}, and the segment has no Comp\mathrm{Comp} from it to the end of qq. The choice of qq forbids this. So no segment of QQ contains these positions, and by the first claim on QQ no node of II is at them. But nyn_y is one of them and is in II. □\square

Theorem D. If II is computationally optimal, the lifetime of ILCMI_{\mathrm{LCM}} is a subset of the lifetime of II.

Proof. Let nn be in the lifetime of ILCMI_{\mathrm{LCM}}, by a path π\pi from a successor of nn to a Comp\mathrm{Comp} node mm with no node of ILCMI_{\mathrm{LCM}}. Put a path from ss to nn in front and a path from mm to a ret node behind, to get a complete path PP. Say a node of II is at a position yy of π\pi. By Lemma 7, yy is in a segment [j,m(j)][j, m(j)], and the position xx of ILCMI_{\mathrm{LCM}} in that segment is at or after yy. It is not on π\pi, so xx is after mm. Then mm is a Comp\mathrm{Comp} position with j≤y≤m<x≤m(j)j \le y \le m < x \le m(j), which is before the first Comp\mathrm{Comp} position m(j)m(j) of the segment. This is false. So π\pi has no node of II, and nn is in the lifetime of II. □\square

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 nn be the number of nodes and mm the number of expressions. Each node has at most two successors, so a pass of any of the four iterative analyses costs O(nm)O(n m) bit operations, which is O(n⌈m/w⌉)O(n \lceil m / w \rceil) word operations on a machine with ww-bit words. A round-robin pass in a good order reaches the fixed point after a number of passes bounded by d+2d + 2, by the Kam and Ullman bound, where dd is the loop-connectedness depth, the most back edges on a simple path. This is at most n+1n + 1. So the worst case is O(n2m)O(n^2 m) and the usual case is close to O(nm)O(n m). The sets take Θ(nm)\Theta(n m) bits. Working on basic blocks instead of single instructions, with local summary sets for each block, divides nn 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 / b is partially redundant at B3, but B2 -> B3 is 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 0
    

    The computation cannot go into B2, because the path to B4 does not divide, and b can be 0 there. The start of B3 is too late. Only a new block on the edge can take it, and LCM puts pre.0 = a / b there.

  • Loops that may not run. In a while loop whose test comes first, a / b in 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 a do-while loop 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 + b uses ee 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 = t need 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.

lazy_code_motion.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example