Algorithmintro
Copy propagation
Also called copy folding.
Replaces uses of x after a copy x = y by y while neither changes, so that the copy can be removed as dead code.
- Time
- O(R b n c + c b n v) worst
- Space
- O(b (c + v) + n) extra
- Where
- R = the number of rounds; b = the number of blocks; c = the number of copies; n = the number of instructions and terminators; v = the number of names
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Copy propagation replaces a use of a name x by y when the copy x = y is the last write to x on every path to the use and y has not changed since. The fact that it needs is available copies, a forward dataflow problem with intersection as the meet, much like available expressions. The pass does not make the program faster by itself. It removes the reasons to keep the copy, and the copy then dies and goes away, as in dead code elimination. Copies come from common subexpression elimination, local value numbering, inlining and the translation out of static single assignment form, so this pass runs often.
In plain words
After x = y, the two names hold the same number. A later line that reads x can read y instead, as long as nothing wrote to x or to y in between. If every reader of x now reads y, nobody needs x, and the line x = y can be deleted. The hard part is "nothing wrote in between". The program can reach the reader along different roads, and the copy must be the latest news on every road. A write through a pointer can also change a name without naming it, so the pass must be careful with names whose address the program takes.
The problem
The input is a program of the toy IR of three-address code: a control flow graph of blocks with no phi-functions. The output is a program that has the same outcome on every input, the same return value, the same trap or no end, and that has fewer copies. A copy is an instruction x = y with y a name other than x. A copy of a constant, x = 5, is a constant, and spreading it is constant propagation, a different problem.
A pair is available at a point if on every path from the entry to there is a copy x = y, and after the last such copy on the path no instruction writes x or y. Then at the two names have the same value in every run, and a use of x at can read y.
The algorithm
S is a set of pairs. A name is address-taken if the program has an instruction p = &x for it. A store or a call can change such a name through a pointer, so it removes the pairs that mention one.
COPY-PROPAGATION(P)- 1
repeat - 2
IN <- AVAILABLE-COPIES(P) - 3
count <- 0 - 4
for each block B of P do - 5
S <- IN[B] - 6
for each instruction I of B, in order, and then the terminator of B do - 7
for each operand u of I that is a name do - 8
while S holds a copy (u, y) do u <- y - 9
if some operand changed then replace them in I; count <- count + 1 - 10
S <- TRANSFER(I, S) - 11
until count = 0 - 12
delete every copy x = y whose x is dead after it, and every x = x, until none is left - 13
return P AVAILABLE-COPIES(P)- 14
C <- the set of copies (x, y) in P, with y a name other than x - 15
OUT[B] <- C for every block B - 16
repeat, visiting the reachable blocks in reverse postorder, until no OUT[B] changes - 17
IN[B] <- empty if B is the entry, else the intersection of OUT[p] over the predecessors p - 18
OUT[B] <- TRANSFER over the instructions of B, from IN[B] TRANSFER(I, S)- 19
if I is a store or a call then remove the copies that mention an address-taken name - 20
if I defines x then remove every copy (x, .) and (., x) - 21
if I is x = y with y a name other than x then add (x, y) - 22
return S
Lines L14 to L18 solve the dataflow analysis problem of available copies. It is a must problem, so OUT starts at the full set and only shrinks, and the meet at a join is intersection. The entry starts from the empty set: on entry no copy has run. A block that the entry does not reach keeps an empty IN, so that nothing is rewritten in code that never runs.
Line L8 follows chains. After b = a; c = b, a use of c becomes a use of a. The sets that the algorithm builds have at most one pair for each destination and no cycle, so the chain ends. Line L10 updates S with the rewritten instruction, so a copy c = b that became c = a adds the pair .
Line L1 repeats the rounds, because one round does not find everything. In the example below, a copy is killed on one path in the first round, and only its rewritten form survives that path in the next round. Line L12 uses live variable analysis and never deletes a copy to an address-taken name, since a load through a pointer can read it.
Example
The parameters are a and n.
entry:
b = a
c = b
br n left right
left:
d = c + 1
b = 7
jump join
right:
d = c * 2
jump join
join:
e = c + b
e = e + d
ret e
Round 1. The available sets on entry are for left and right. In entry, c = b becomes c = a. In left and right, c follows the chain , so d = c + 1 becomes d = a + 1 and d = c * 2 becomes d = a * 2. At join the set is empty: b = 7 in left removes both and , because each mentions b.
Round 2. Now entry holds c = a. The write b = 7 does not mention c or a, so is available at join on both paths, and e = c + b becomes e = a + b. The use of b at join stays, because on the path through left it is 7.
Round 3 changes nothing. Then c = a is dead and line L12 deletes it. b = a stays, because join reads b on the path through right.
entry:
b = a
br n left right
left:
d = a + 1
b = 7
jump join
right:
d = a * 2
jump join
join:
e = a + b
e = e + d
ret e
For both programs return 18 when and 20 when , and the new one executes one instruction less on every run.
Correctness
The full proof is in the proof file. It has four steps.
- TRANSFER is sound. If every pair of S holds before an instruction, every pair of TRANSFER(I, S) holds after it. A write to a name removes every pair that mentions it. A store or a call can only change names that are address-taken, through a pointer that
p = &xmade, and line L19 removes those pairs. - The analysis is sound. The OUT sets only shrink, so the loop of line L16 stops, at a solution of the equations of lines L17 and L18. By induction on the steps of a run, every pair available at a point holds whenever the run is there: the entry starts from the empty set, and along an edge IN is a subset of the OUT of the predecessor that the run came from.
- A round keeps every state. Each replaced operand follows pairs that hold, so it has the same value. So the rewritten instruction reads the same values, writes the same value, and traps on the same zero divisor. The old and the new program go through the same states, step by step.
- Line L12 keeps the outcome. A deleted copy writes a name that no later instruction reads before it is written again, and that no pointer can reach. The two programs agree on every live name and on memory, and so they have the same outcome.
Each round is correct on its own, so the result is correct for any number of rounds. The implementation stops after at most rounds.
Proof: Copy propagation keeps the outcome of every runfull
Setting. is a program of the toy IR with no phi-functions. A point is a position just before an instruction or a terminator of a block. A state is the environment of the running frame, the memory (the heap and the variables of all frames), and the position. We assume, as for the test programs of the toy IR, that no run of reads a name before it is defined. is the set of address-taken names, the names of the instructions p = &x. A pair stands for the copy x = y, with a name other than . We say that a pair holds in a state when and are both defined there and have the same value.
The outcome of a run is its return value, a trap, or no end. The theorem is: and the program that COPY-PROPAGATION returns have the same outcome on every input. It follows from three lemmas, one for the analysis, one for the rewrite of one round, and one for the removal of dead copies, because the algorithm is a sequence of rounds and one removal.
Lemma 1: the transfer function is sound
Claim. Let be an instruction, a set of pairs, and a state in which every pair of holds. If runs from without a trap and reaches the state , then every pair of holds in .
Proof. Take a pair of the result. Either it was in and survived lines L19 and L20, or line L21 added it.
- It survived. Then and held the same value in . The instruction writes its destination , if it has one, and line L20 removed every pair that mentions , so and . A store writes one memory cell. In the toy IR a pointer is made by
alloc, which gives a heap cell, or byp = &z, which gives the variable of the frame that ran it, with . So a store changes no name outside . A call runs its function in a new frame, and that function changes the names of our frame only through pointers, which again point to names in or to heap cells. Line L19 removed the pairs that mention a name of when is a store or a call, so in that case. In each case changes neither nor , and the pair still holds in . - Line L21 added it. Then is
x = y. The run read , so is defined, and wrote that value to . The pair holds in .
Lemma 2: the available copies hold
The fixed point. The sets OUT start at the full set of the copies in . TRANSFER only adds pairs of , and it is monotone: gives , because removing the pairs that mention a name and adding one fixed pair both keep inclusion. Intersection is monotone too. By induction on the visits, every new value of OUT[B] is a subset of the one before, so the sets only shrink, and since is finite the loop of line L16 stops. In the last pass no OUT changes, so every IN in that pass was computed from the final OUT sets. So for every reachable block the final sets satisfy
where applies TRANSFER to the instructions of in order. A block that the entry does not reach keeps .
For a point inside a block , let be the set that TRANSFER gives from IN[B] over the instructions of before .
Claim. In every run of and at every point that the run reaches, every pair of holds.
Proof. By induction on the number of steps of the run. At the first point the set is , and there is nothing to show. Inside a block, a step from to the next point runs one instruction , and . Lemma 1 gives the claim at . A step from the end of a block to the start of a successor goes along an edge, so is a predecessor of , and both blocks are reachable. The set at the end of is , and every pair of it holds by induction. If is the entry, its set is empty. Otherwise , and every pair of holds. The step does not change the state.
The sets have no cycle. Call a set proper if no name is the destination of two of its pairs and the map of its pairs has no cycle. The empty set is proper, and a subset of a proper set is proper. TRANSFER keeps a set proper: line L21 adds only after line L20 has removed every pair and every pair , so is the destination of one pair, and no pair leads back to . Visit the reachable blocks in reverse postorder. Each block other than the entry has a predecessor that comes earlier in this order, its parent in the depth-first search. By induction its final OUT is proper, so the intersection IN[B] is proper. So every set that the rewrite uses is proper, and the loop of line L8 stops after at most as many steps as there are pairs.
Lemma 3: one round keeps the outcome
Let be the program after one round, lines L2 to L10. The round keeps every instruction in its place and only changes operands.
Claim. For every input, the runs of and go through the same states, step for step, until both end in the same way.
Proof. Inside a block , the round starts from and sets , where is the rewritten instruction . We show by induction on the steps that both runs are in the same state, and that every pair of holds in that state when the runs are before instruction .
At the start of a block both runs are in the same state, which is a state of a run of . By Lemma 2 every pair of holds. Before instruction , every operand that line L8 replaces is followed along pairs of . Each of them holds, so and have the same value. So reads the same operand values as . It does the same thing: it writes the same value to the same destination, stores the same value to the same cell, calls the same function with the same arguments, or traps on the same zero divisor or bad shift count. A terminator with a replaced operand takes the same branch or returns the same value. So the two states after the step are equal. By Lemma 1, applied to the run of that executes , every pair of holds after it.
So the runs never differ, and they have the same outcome. Also reads only names that hold the value of a defined name, so again reads no undefined name, and the next round may use the same lemmas.
Lemma 4: removing dead copies keeps the outcome
One pass of line L12 deletes some instructions x = y from a program and gives . A deleted copy has , and it is x = x or is not in the set of names live after it. The set comes from the liveness of at the end of each block, and inside a block it is updated backward over the kept instructions only:
is enough at the block ends. Let be the liveness of . Going backward through a block, at every point : it holds at the end, where both sets are equal, a kept instruction applies the same rule to both sets, and a deleted x = y, which has or , gives . So for every edge from to , .
Claim. Run and on the same input, and match the points of with the points of , skipping the deleted copies. At matched points the memory is the same, the call stack is the same, and the environments agree on every name of .
Proof. At the start the two environments are equal. A deleted copy runs in only. It cannot trap, because is defined. A deleted x = x changes nothing. Any other deleted copy changes only , which is neither in nor in . In both cases the claim still holds after it. A kept instruction reads names of , which agree, so in both programs it traps in the same way or writes the same value to the same name or cell. After it the names of agree, because they were in and did not change, and got the same value in both. The names of and the memory change in the same way in both, also inside a called function, which is not changed and gets the same arguments and the same memory. A terminator reads names of at the block end, so it takes the same branch or returns the same value, and on an edge only shrinks, by the inclusion above. So the runs trap together, return the same value, or both never end.
Line L12. It repeats such passes until a pass deletes nothing. Each pass deletes at least one instruction or ends the loop, so there are at most passes for copies, and the outcome does not change.
The theorem
COPY-PROPAGATION runs some number of rounds, then line L12. By Lemma 3 every round keeps the outcome and keeps the property that no name is read before it is defined. By Lemma 4 line L12 keeps the outcome. So the result has the same outcome as on every input. The argument does not depend on how many rounds run, so stopping after a fixed number of rounds is also safe.
The cost does not grow. A round changes no instruction into a more costly one, and line L12 only deletes copies. So on every input the new program executes at most as many instructions and terminators as .
Complexity
One pass of the analysis applies TRANSFER to each of the instructions, at cost with sets of the copies. In reverse postorder the must problem needs at most passes, and on a reducible graph only the loop connectedness plus two, where the loop connectedness is the largest number of back edges on a path without repeats (see the Kam and Ullman bound). A round is then , and the rewrite adds . Each pass of line L12 solves liveness in , and it deletes at least one copy, so there are at most passes. With bit vectors of bits the set operations are times faster. The space is the IN and OUT sets of every block, , and the program. In practice is two or three.
Properties
- It never costs more. A round replaces only operands, and line L12 only deletes copies, so every run executes at most as many instructions as before.
- It needs a cleanup. Without line L12, or a dead code pass after it, copy propagation saves nothing: it only moves uses from
xtoy. - It can lengthen live ranges. After the rewrite,
yis live up to the last former use ofx, soyand other names can now interfere in register allocation. - It is conservative. A path that cannot run in practice still kills a pair, and every store kills every pair with an address-taken name.
Variants and improvements
- Local copy propagation. Inside one basic block, start from the empty set and apply lines L6 to L10. No dataflow analysis is needed.
- On SSA form. In static single assignment form each name has one definition and is never written again. So after
x = y, every use ofxcan ready, and the copy is deleted, with no analysis at all. Copies in phi-functions need more care, see the pitfalls. - With def-use chains. Reaching definitions and def-use chains can drive the same rewrite: a use of
xis rewritten if the copyx = yis the only definition ofxthat reaches it and no path from the copy to the use writesy. The second condition is the available-copies fact. - With constants and values. Sparse conditional constant propagation handles copies of constants, and global value numbering finds names that are equal by other means than a copy.
- Coalescing. A register allocator removes copies in a different way: it gives
xandythe same register when they do not interfere, which is the register coalescing problem.
When to use it
Run copy propagation after any pass that leaves copies, such as common subexpression elimination, value numbering, inlining or out-of-SSA translation, and follow it by dead code elimination. On SSA form, use the trivial rule above. In a compiler with alias information, use it in TRANSFER in place of the address-taken test, so that a store kills only the pairs whose names it can reach.
Pitfalls
- A store through a pointer. In
p = &x; y = x; *p = 5; z = y, the store changesx. Rewritingz = yasz = xgives 5, not the old value. The pair must die at the store, which line L19 does becausexis address-taken. - A kill on one path. After
b = a, the pair is not available at a join if one incoming path writesb. Using "some path has the copy" gives a wrong value on the other path. - Writes to the source. After
y = a, a latera = a + 1inside a loop kills . Forgetting the kill of on line L20 keeps a stale pair. - The wrong direction. The rule replaces a use of
xbyy, the source. Replacing uses ofybyxis wrong whenxis written again. - Phi-functions after propagation on SSA. Propagating copies into phi operands can make the live ranges of the phi results overlap. A naive translation out of SSA then loses a value, the lost copy problem.
- Deleting copies to address-taken names. A load through a pointer is a use that liveness on names does not see. Such copies stay.
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/copy-propagation/. The authors are listed in prov/3N51WA.jsonl.
"""Copy propagation on the toy IR, for programs that are not in SSA form.
available_copies(prog) solves the forward must problem of available copies
and returns the sets on entry to each block. propagate(prog) replaces each
use of a name u by y when the copy u = y is available at the use, following
chains of copies, and returns (new program, number of uses replaced).
remove_dead_copies(prog) deletes the copies whose destination is dead.
copy_propagation(prog) repeats propagate until a round changes nothing, then
removes dead copies. Programs with phi-functions are rejected: in SSA form
every copy can be propagated without any analysis.
"""
import toyir
def _check(prog):
for blk in prog.blocks.values():
for ins in blk.instrs:
if ins[0] == "phi":
raise ValueError("copy propagation here works on programs without phi-functions")
def address_taken(prog):
"""The names whose address is taken by an addr instruction. A store or a
call may change them, and a load or a call may read them."""
return {ins[2] for blk in prog.blocks.values() for ins in blk.instrs if ins[0] == "addr"}
def _is_copy(ins):
return ins[0] == "copy" and isinstance(ins[2], str) and ins[2] != ins[1]
def transfer(ins, s, taken):
"""The available copies after ins, given the set s before it."""
if ins[0] in ("store", "call") and taken: # @line L19
s = {(x, y) for (x, y) in s if x not in taken and y not in taken}
d = toyir.defs(ins)
if d is not None: # @line L20
s = {(x, y) for (x, y) in s if x != d and y != d}
if _is_copy(ins): # @line L21
s = s | {(ins[1], ins[2])}
return s # @line L22
def _rpo(prog):
seen = {prog.entry}
post = []
stack = [(prog.entry, iter(toyir.succs(prog, prog.entry)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
post.append(v)
stack.pop()
elif w not in seen:
seen.add(w)
stack.append((w, iter(toyir.succs(prog, w))))
return post[::-1]
def available_copies(prog):
_check(prog)
taken = address_taken(prog)
universe = set()
for blk in prog.blocks.values(): # @line L14
for ins in blk.instrs:
if _is_copy(ins):
universe.add((ins[1], ins[2]))
pred = toyir.preds(prog)
order = _rpo(prog)
out = {b: set(universe) for b in prog.blocks} # @line L15
# A block that the entry does not reach never runs: no copy needs to be
# available there, and its OUT stays at the top value, the full set.
inn = {b: set() for b in prog.blocks}
changed = True
while changed: # @line L16
changed = False
for b in order:
if b == prog.entry: # @line L17
s = set()
else:
s = set(universe)
for p in pred[b]:
s &= out[p]
inn[b] = s
for ins in prog.blocks[b].instrs: # @line L18
s = transfer(ins, s, taken)
if s != out[b]:
out[b] = s
changed = True
return inn
def _resolve(a, s):
"""Follow the available copies from name a. The available copies at a
point never form a cycle, so this ends."""
if not isinstance(a, str):
return a
src = dict(s)
while a in src: # @line L8
a = src[a]
return a
def _rewrite(ins, s):
k = ins[0]
r = lambda a: _resolve(a, s)
if k == "copy":
return ("copy", ins[1], r(ins[2]))
if k == "op":
return ("op", ins[1], ins[2], r(ins[3]), r(ins[4]))
if k == "load":
return ("load", ins[1], r(ins[2]))
if k == "store":
return ("store", r(ins[1]), r(ins[2]))
if k == "call":
return ("call", ins[1], ins[2], [r(a) for a in ins[3]])
return ins
def _rewrite_term(t, s):
if t[0] == "br":
return ("br", _resolve(t[1], s), t[2], t[3])
if t[0] == "ret":
return ("ret", _resolve(t[1], s))
return t
def propagate(prog):
"""One round: analyse, then rewrite every use. Returns (program, count)."""
inn = available_copies(prog) # @line L2
taken = address_taken(prog)
blocks = {}
count = 0 # @line L3
for b, blk in prog.blocks.items(): # @line L4
s = inn[b] # @line L5
new = []
for ins in blk.instrs: # @line L6
ins2 = _rewrite(ins, s) # @line L7
if ins2 != ins: # @line L9
count += 1
new.append(ins2)
s = transfer(ins2, s, taken) # @line L10
term = _rewrite_term(blk.term, s)
if term != blk.term:
count += 1
blocks[b] = toyir.Block(new, term)
return toyir.Program(list(prog.params), blocks), count
def live_out(prog):
"""Live variable analysis: the names live at the end of each block."""
uses, defs = {}, {}
for b, blk in prog.blocks.items():
u, d = set(), set()
for ins in blk.instrs:
for a in toyir.uses(ins):
if a not in d:
u.add(a)
x = toyir.defs(ins)
if x is not None:
d.add(x)
for a in toyir.term_uses(blk.term):
if a not in d:
u.add(a)
uses[b], defs[b] = u, d
lin = {b: set() for b in prog.blocks}
lout = {b: set() for b in prog.blocks}
changed = True
while changed:
changed = False
for b in reversed(list(prog.blocks)):
o = set()
for w in toyir.succs(prog, b):
o |= lin[w]
i = uses[b] | (o - defs[b])
if o != lout[b] or i != lin[b]:
lout[b], lin[b] = o, i
changed = True
return lout
def remove_dead_copies(prog):
"""Delete the copies x = y with x dead after them, and x = x, until none
is left. Copies to an address-taken name are kept, because a load or a
call may read them through a pointer."""
_check(prog)
taken = address_taken(prog)
blocks = {b: toyir.Block(list(blk.instrs), blk.term) for b, blk in prog.blocks.items()}
prog = toyir.Program(list(prog.params), blocks)
while True:
lout = live_out(prog)
removed = 0
for b, blk in prog.blocks.items():
live = set(lout[b]) | set(toyir.term_uses(blk.term))
keep = []
for ins in reversed(blk.instrs):
x = toyir.defs(ins)
dead_copy = ins[0] == "copy" and x not in taken and (x not in live or ins[2] == x)
if dead_copy:
removed += 1
continue
keep.append(ins)
if x is not None:
live.discard(x)
live |= set(toyir.uses(ins))
blk.instrs = keep[::-1]
if not removed:
return prog
def copy_propagation(prog, max_rounds=None):
"""Propagate until a round changes nothing (at most max_rounds rounds,
by default one more than the number of instructions), then remove the
dead copies. Returns (program, number of rounds)."""
if max_rounds is None:
max_rounds = 1 + sum(len(blk.instrs) + 1 for blk in prog.blocks.values())
rounds = 0
while rounds < max_rounds: # @line L1
prog, count = propagate(prog)
rounds += 1
if count == 0: # @line L11
break
prog = remove_dead_copies(prog) # @line L12
return prog, rounds # @line L13
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_copy_propagation.py 233 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/copy-propagation/. The authors are listed in prov/3N51WA.jsonl.
import random
import toyir
from copy_propagation import (
available_copies,
copy_propagation,
propagate,
remove_dead_copies,
)
PAGE = """
# params: a, n
entry:
b = a
c = b
br n left right
left:
d = c + 1
b = 7
jump join
right:
d = c * 2
jump join
join:
e = c + b
e = e + d
ret e
"""
PAGE_AFTER = """
# params: a, n
entry:
b = a
br n left right
left:
d = a + 1
b = 7
jump join
right:
d = a * 2
jump join
join:
e = a + b
e = e + d
ret e
"""
# y = a is killed inside the loop by a = a + 1, so the use of y in the
# loop must stay.
LOOP = """
# params: a
entry:
y = a
i = 0
s = 0
jump h
h:
t = i < 3
br t body done
body:
z = y + i
s = s + z
a = a + 1
i = i + 1
jump h
done:
r = s + a
ret r
"""
ADDRESS = """
# params: x
entry:
p = &x
y = x
*p = 5
z = y + 0
ret z
"""
CALL = """
# params: x
entry:
p = &x
y = x
w = call f(p)
z = y + w
ret z
"""
# f stores 100 through its pointer argument and returns 1.
FUNC_F = toyir.parse("# params: q\nentry:\n *q = 100\n ret 1\n")
def steps(prog, args, funcs=None, limit=4096):
"""The number of instructions and terminators a run executes, found as
the smallest fuel for which toyir.run does not run out."""
if toyir.run(prog, args, fuel=limit, funcs=funcs) == ("fuel",):
return None
lo, hi = 0, limit
while lo < hi:
mid = (lo + hi) // 2
if toyir.run(prog, args, fuel=mid, funcs=funcs) == ("fuel",):
lo = mid + 1
else:
hi = mid
return lo
def add_copies(rng, prog, nvars):
"""Insert copies x_i = x_j at random places, so that chains of copies and
copies killed on some paths appear."""
xs = ["x%d" % i for i in range(nvars)]
for label, blk in prog.blocks.items():
out = []
# In the entry, wait until every x_i has a value.
defined = set(prog.params) if label == prog.entry else set(xs)
for ins in blk.instrs:
if defined >= set(xs) and rng.random() < 0.5:
out.append(("copy", rng.choice(xs), rng.choice(xs)))
out.append(ins)
defined.add(toyir.defs(ins))
blk.instrs = out
return prog
def test_page_example():
p = toyir.parse(PAGE)
q, rounds = copy_propagation(p)
assert toyir.show(q) == toyir.show(toyir.parse(PAGE_AFTER))
assert rounds == 3
for a in range(-5, 6):
for n in (0, 1):
assert toyir.run(p, [a, n]) == toyir.run(q, [a, n])
def test_page_available_sets():
inn = available_copies(toyir.parse(PAGE))
assert inn["left"] == {("b", "a"), ("c", "b")}
assert inn["join"] == set()
# After the first round c = b has become c = a, which survives b = 7.
p1, _ = propagate(toyir.parse(PAGE))
assert available_copies(p1)["join"] == {("c", "a")}
def test_copy_killed_in_loop():
p = toyir.parse(LOOP)
q, _ = copy_propagation(p)
assert ("op", "z", "+", "y", "i") in q.blocks["body"].instrs
for a in range(-4, 5):
assert toyir.run(p, [a]) == toyir.run(q, [a]) == ("ret", 3 * a + 3 + 3 + a)
def test_store_through_pointer_kills_copy():
p = toyir.parse(ADDRESS)
q, _ = copy_propagation(p)
assert ("op", "z", "+", "y", 0) in q.blocks["entry"].instrs
assert toyir.run(q, [9]) == toyir.run(p, [9]) == ("ret", 9)
def test_call_kills_copy_of_address_taken_name():
p = toyir.parse(CALL)
q, _ = copy_propagation(p)
assert ("op", "z", "+", "y", "w") in q.blocks["entry"].instrs
assert toyir.run(q, [9], funcs={"f": FUNC_F}) == ("ret", 10)
def test_stores_and_calls_are_kept():
src = """
# params: x
entry:
p = alloc
y = x
*p = y
w = call f(p)
u = *p
r = u + w
ret r
"""
p = toyir.parse(src)
q, _ = copy_propagation(p)
kinds = [ins[0] for ins in q.blocks["entry"].instrs]
assert kinds == ["alloc", "store", "call", "load", "op"]
assert q.blocks["entry"].instrs[1] == ("store", "p", "x")
for x in range(-3, 4):
assert toyir.run(p, [x], funcs={"f": FUNC_F}) == toyir.run(q, [x], funcs={"f": FUNC_F}) == ("ret", 101)
def test_division_keeps_its_trap():
src = "# params: a, b\nentry:\n c = b\n q = a / c\n ret q\n"
p = toyir.parse(src)
q, _ = copy_propagation(p)
assert q.blocks["entry"].instrs == [("op", "q", "/", "a", "b")]
assert toyir.run(q, [5, 0]) == ("trap",)
assert toyir.run(q, [-7, 2]) == ("ret", -3)
def test_phi_is_rejected():
p = toyir.parse("entry:\n jump b\nb:\n x = phi [entry: 1]\n ret x\n")
try:
copy_propagation(p)
except ValueError:
return
raise AssertionError("expected ValueError")
def test_random_programs():
rng = random.Random(1115)
better = 0
traps = 0
max_rounds = 0
for trial in range(220):
nvars = 5
p = toyir.random_program(rng, nvars, rng.randint(4, 8), acyclic=trial % 2 == 0)
add_copies(rng, p, nvars)
q, rounds = copy_propagation(p)
max_rounds = max(max_rounds, rounds)
# The dead copies are gone: a second removal finds nothing.
assert toyir.show(remove_dead_copies(q)) == toyir.show(q)
for _ in range(6):
args = [rng.randint(-5, 5), rng.randint(-5, 5)]
out = toyir.run(p, args)
assert out == toyir.run(q, args)
traps += out == ("trap",)
s1, s2 = steps(p, args), steps(q, args)
assert s2 <= s1
better += s2 < s1
assert better > 600
assert traps > 20
assert max_rounds <= 6
History
Copy propagation is one of the classical global optimizations of the optimizing compilers of the 1960s and 1970s. Kildall gave in 1973 the iterative algorithm and lattice framework that solves problems such as available copies. The dragon book presents copy propagation with the sets of available copies and an intersection at joins, and Muchnick gives the local and global forms and the place of the pass among the early optimizations. In SSA-based compilers the pass is mostly a side effect of SSA construction and of value numbering.
References
- Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Section 9.1.5 (Copy Propagation) and Section 9.2 (Introduction to Data-Flow Analysis)
- Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Section 12.5 (Copy Propagation), the local form and the global form with the sets of available copies
- Gary A. Kildall, A unified approach to global program optimization, Proceedings of the 1st ACM SIGACT-SIGPLAN Symposium on Principles of Programming Languages (POPL), 1973, 194-206, the iterative algorithm for a dataflow problem with a meet operation, used here with intersection for the available copies
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 3N51WA Edit this page History Report an error Markdown