Data structureintro
Def-use chains
Also called use-def chains, du-chains, ud-chains.
Links each definition of a variable to the uses it can reach and each use to the definitions that can reach it.
- Evidence
- Full proofCode in 1 languages
Def-use chains record, for a program in three-address code, which definitions of a variable can supply the value that each use reads. A du-chain links a definition to all the uses it can reach; a ud-chain, or use-def chain, links a use to all the definitions that can reach it. Both are the same set of pairs, read in two directions. A definition of reaches a use of if some path in the control flow graph leads from to the use without another definition of . The chains are built from the answer of reaching definitions, and optimizations then follow them instead of scanning the whole program: copy propagation, dead code elimination, constant propagation, induction variable analysis and the webs of register allocation. They can be large: definitions that meet at one join and reach uses give links, which is one reason for static single assignment form.
In plain words
A program sets variables in some places and reads them in others. When a line reads a variable, the compiler wants to know which earlier lines could have set the value it gets. It looks at every way the program can run to that line and keeps the lines that set the variable last before it. A ud-chain is that list for one reading line. A du-chain goes the other way: for one line that sets a variable, the list of lines that can read the value it wrote. With these lists, a compiler can see that a value is never read, so its line can go, or that only one line can set a value, so that value is known. It follows the lists instead of reading the whole program again.
The abstract type
The structure stores a relation between two kinds of sites. A definition site is instruction of block when it writes the name ; a parameter is the site , written on the way into the program. A use site is instruction of block when it reads , and , the number of instructions of , means the terminator. The operations are:
chains(P): build the structure for program .du(d): the uses that definition reaches.ud(u): the definitions that reach use .
The law: if and only if if and only if reaches . Here of reaches if some path from the point just after to passes no other definition of ; the instruction at may itself define , since it reads first. A phi operand that comes from the predecessor counts as a use at the end of . The relation is about paths, not about runs: a path that no input can take still counts, so the chains may contain pairs that never happen, but they miss no pair that does happen in a run that writes variables only by name.
Representation
Two maps hold the relation: du from each definition site to the sorted list of its uses, and ud from each use site to the sorted list of its definitions. Every definition site is a key of du, even with no uses, and every use site is a key of ud, even with no definitions. A compiler keeps the lists on the instructions themselves, as pointers, so that it can go from an instruction to its uses in constant time per link.
To build the maps, the code first solves reaching definitions per block. holds the last definition in of each name, and holds the names that defines. and are the definitions that reach the start and the end of . Compilers store these sets as bit vectors with one bit per definition site; the Python code uses sets of site tuples.
Operations
BUILD-CHAINS(P)- 1
for each block b: GEN[b] <- the last definition in b of each name; KILL[b] <- the names b defines - 2
OUT[b] <- GEN[b] for every block b - 3
repeat - 4
for each block b in reverse postorder do - 5
IN[b] <- the union of OUT[p] over the predecessors p of b, plus the parameters if b is the entry - 6
OUT[b] <- GEN[b] ∪ {d in IN[b] : the name of d is not in KILL[b]} - 7
until no OUT set changed in the pass - 8
for each block b do - 9
live[x] <- the definitions of x in IN[b], for every name x - 10
for each instruction s of b in order, then the terminator do - 11
link every d in live[x] with the use (s, x), for each name x that s reads - 12
if s defines x then live[x] <- {s} - 13
return du and ud
Lines L1 to L7 are the round-robin solution of reaching definitions. Lines L8 to L12 walk each block once: is always the set of definitions of that reach the current instruction, so a read of is linked to exactly those. Line L11 reads before line L12 writes, so i = i + 1 links its read of i to the earlier definitions, not to itself. A phi is the exception to line L11: its operand from predecessor is linked to the definitions of that name in , because the value is chosen on the edge from .
du(d) and ud(u) are lookups in the two maps. The function reaching returns , and the number of passes.
Example
The odd-sum program of the control flow graph page, with the parameter n:
B1:
i = 0
s = 0
jump B2
B2:
t1 = i < n
br t1 B3 B6
B3:
t2 = i % 2
br t2 B4 B5
B4:
s = s + i
jump B5
B5:
i = i + 1
jump B2
B6:
ret s
Reaching definitions in reverse postorder B1, B2, B6, B3, B4, B5 settle in 2 passes, and a third pass changes nothing. Since starts at , i = i + 1 reaches the loop header B2 along already in the first pass. s = s + i in B4 gets there only in the second pass, after the first pass has carried it into . The chains, as du-chains:
| definition | uses it reaches |
|---|---|
n (parameter) |
t1 = i < n in B2 |
i = 0 in B1 |
the reads of i in B2, B3, B4 and B5 |
i = i + 1 in B5 |
the reads of i in B2, B3, B4 and B5 |
s = 0 in B1 |
s = s + i in B4, ret s in B6 |
s = s + i in B4 |
s = s + i in B4, ret s in B6 |
t1 in B2 |
br t1 in B2 |
t2 in B3 |
br t2 in B3 |
There are 15 links. Read as ud-chains, the use of s in ret s has two definitions, s = 0 and s = s + i, so s is not a constant there. The definition s = s + i reaches its own read through the loop. Each ti has one definition and one use, so a compiler could fold the comparison into the branch. The program returns 9 for .
Correctness
The proof file shows three things. First, the sets "definitions that reach the start of " and "definitions that reach the end of " are the least solution of the equations of lines L5 and L6: they solve them, by cutting a path at its last entry into , and every solution contains them, by induction on the length of the path. Second, the iteration starts below this least solution, stays below it and only grows, so it stops, and when a pass changes nothing it has reached the least solution; at most passes are needed, for blocks and definition sites. Third, during the scan of a block, is always the set of definitions of that reach the current instruction, because the only way into instruction is through instruction . So each use is linked to exactly the definitions that reach it. The proof covers names only. A store through a pointer writes a variable without naming it, and the chains do not see it.
Proof: The reaching-definitions iteration and the block scan build exactly the def-use chainsfull
Setting. A program has blocks with instructions and one terminator each, and an entry block. A point is for , where is the number of instructions of : for it is instruction of , and is the terminator. The point graph has the edges for and for every successor of . Add a start point with the single edge . A definition site is a point that defines a name , written ; a parameter is the site , placed at . The point after is , or for a parameter. A phi instruction at a point defines its name there, like any other instruction.
Definition. A path of points is clear for if no point of except possibly its last one defines . The definition of reaches a point if some path clear for goes from the point after to , with itself allowed to define . It reaches the end of a block if it reaches ; the terminator defines nothing. The chains are the pairs for a use of such that:
- where point is not a phi and reads , and reaches ; or
- where point is a phi whose operand for the predecessor is , and reaches the end of .
The function returns , the uses with a chain, and , the definitions with a chain. So and are the same relation read in two directions, and it is enough to show that the set of pairs is right.
Block summaries. For a block , holds, for each name defined in , the site of its last definition in , and is the set of names defined in . is the set of parameter sites. Let be the set of definitions that reach and the set that reach the end of . Write for the name that defines.
Lemma 1 (the equations). and satisfy
and every other solution has and for all . So they are the least solution.
Proof. They are a solution. The points with an edge into are the ends of the predecessors of , and if is the entry. A path clear for from the point after to either has length 0, which happens only for a parameter and , or its last but one point is the end of a predecessor , and the part up to it is a path clear for that ends at a point defining nothing. This gives , and the converse direction is the same argument read backwards. For , a path clear for to from the point after either starts inside , after , and then no later point of defines , so ; or it passes through , its part up to shows , and then the whole block is passed without a definition of , so . Conversely each such gives such a path. (A path that starts inside and later passes falls under the second case; the first case uses its last visit to .)
They are the least solution. Let be a solution. We show by induction on the number of points of the path that if a path clear for goes from the point after to then , and if it goes to then . For : the path has length 0 and , or its part up to the end of a predecessor is shorter, so . For : look at the last time the path is at . If there is none, the path lies in after , and . Otherwise the part up to that point is shorter, so , and the rest crosses without a definition of , so and .
Lemma 2 (the iteration). Lines L2 to L7 stop, and when they stop, and . The number of passes is at most , where is the number of blocks and the number of definition sites.
Proof. Let be the map that takes the sets to new and sets by the equations. It is monotone: larger sets give larger sets and then larger sets. Two invariants hold at all times.
(i) for all . At the start , and , because the last definition of in reaches the end of along the rest of . An update computes and from sets that lie below , and is a fixed point of the equations, so by monotonicity the new sets lie below it too.
(ii) The sets never shrink. The first value of is , and every later value is . After that, each new value of is computed from sets that are at least as large as at the previous update of , so by monotonicity it is at least the previous value.
A pass that sets adds at least one site to some set, and by (i) the sets are bounded by the finite sets, which have at most elements in total. So at most passes change something, and the loop stops after at most one more pass. In the last pass no set changed, so each was computed from the final sets, and each final equals the right side of its equation. So the final sets are a solution, by (i) they lie below the least solution, and by Lemma 1 they are the least solution.
Lemma 3 (the block scan). In lines L8 to L12, just before point is handled, is the set of definitions of that reach , for every name .
Proof. By induction on . For , line L9 sets from by Lemma 2. For : the only edge into comes from . A path clear for to is either the path of length 0 from the point after , or a path clear for to followed by one step, and then must not define , because it is not the last point. So if point defines , the set for at is , and otherwise it is the set at . Line L12 makes exactly this change, and does it after the uses of point have been read.
Theorem. chains returns exactly the chains of the definition.
Proof. For a use at a point that is not a phi, including a terminator, line L11 links it to , which by Lemma 3 is the set of definitions that reach the point. For a phi operand from the predecessor , the code links the use to the definitions of in , the definitions that reach the end of . These are the two cases of the definition. Each pair is added to both and .
Cost. Let be the number of edges of the control flow graph, the number of instructions and the number of chains. With bit vectors of bits, one pass costs word operations on a machine with -bit words, and by Lemma 2 there are at most passes. The scan costs set operations plus the cost of reading the sets. The bound on the passes is crude. Kam and Ullman showed that for problems of this kind, round-robin iteration in reverse postorder needs at most passes, where is the loop connectedness of the graph; that result is cited, not proved here.
What is proved and what is measured. Lemmas 1 to 3 and the theorem are proved here, for the chains of the definition above. They say nothing about stores through pointers: a store *p = a writes a variable without naming it, so a program that takes the address of a name can read a value that no chain explains. The tests compare the result with a graph search from each definition over the point graph, with the union over all paths of acyclic programs, and with random walks on programs with loops. The pass counts in the tests are measurements.
Complexity
Let be the number of blocks, the number of edges, the number of instructions, the number of definition sites, the number of use sites and the number of links.
| part | time | space |
|---|---|---|
| GEN and KILL (line L1) | words as bit vectors | |
| one pass of lines L4 to L6 | word operations | |
| the scan (lines L8 to L12) | set operations plus reading the IN sets | |
| the chains | , with |
Proved. At most passes, in the proof file. The number of links can be quadratic: blocks that each set x and jump to one join block, followed by reads of x and ret x, give links, because each of the uses is reached by all definitions. In SSA form the join gets one phi with operands and the count is : links into the phi and out of it.
Cited, not proved. For bit-vector problems such as reaching definitions, round-robin iteration in reverse postorder needs at most the loop connectedness plus 2 passes (Kam-Ullman bound). Structured programs have small loop connectedness, so a few passes are usual.
Measured, not proved. Over 3,000 seeded random toy programs with loops and up to 9 blocks, the iteration took 1 pass on 46 programs, 2 on 2,571, 3 on 363 and 4 on 20. On one random program with 400 blocks it took 13 passes and built 19,451 links; on one with 1,600 blocks, 12 passes and 348,930 links, which shows how fast the chains grow on large functions.
Variants
- Static single assignment form. Rename each definition so that every name has one, and put phi-functions at joins. Then the ud-chain of each use has exactly one element, the du-chain of a name is its list of uses, and the size is linear in the program. Most modern compilers keep this form instead of chains.
- Webs. A web is a maximal set of du-chains of one name that share uses. Each web becomes one live range in Chaitin-style register allocation, and different webs of the same name can get different registers.
- Data dependence edges. In a program dependence graph, the data edges are the def-use chains, next to the control dependence edges.
- Only one direction. Some passes need only ud-chains, for example constant propagation, which asks "what can this use see". Others need only du-chains, for example dead code elimination, which asks "is this value read".
- Pointers and calls. With pointer analysis, a store
*p = abecomes a possible definition of each variable thatpmay point to. Such a definition does not kill the earlier ones, because the store may write somewhere else. - Sparse analyses. Constant propagation and similar analyses can run over the chains instead of over the blocks, so that they only visit places where a value can flow. Sparse conditional constant propagation does this on SSA form.
When to use it
Use def-use chains when an analysis or optimization asks again and again which definitions a use can see, or which uses a definition feeds, and the program is not in SSA form: in a simple compiler, in a debugger or program analysis tool that works on the original variables, or in a register allocator that builds webs. For a full optimizing compiler, SSA form gives the same information in linear size and is easier to keep up to date when the code changes.
Pitfalls
- Phi operands. A phi operand from predecessor is a use at the end of , not at the top of the join block. Treating it as a use at the join links it to definitions that come in on other edges.
- Pointers. If a variable's address is taken, a store through a pointer can change it, and chains built from names alone miss that definition. Either treat such stores as possible definitions or leave address-taken variables out.
- Uninitialized variables. A ud-chain lists the definitions that reach a use, but it does not say whether some path reaches the use with no definition at all. Add a dummy definition of every name at the entry to find such paths.
- Unreachable code. A definition in a block that the entry does not reach still has paths to later uses, and the iteration counts it. Delete unreachable blocks first if this matters.
- Size. The number of links can grow with the square of the number of definitions of a name. Large generated functions can make the chains much bigger than the code.
- Stale chains. A transformation that moves, copies or deletes an instruction changes the chains. Rebuild them or update them, or the next pass works on wrong facts.
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/def-use-chains/. The authors are listed in prov/XZ8C52.jsonl.
"""Def-use and use-def chains for a toy IR program.
A definition site is a tuple (label, i, x): instruction i of block label
defines the name x. A parameter x is the site (entry, -1, x): it is defined
on the way into the program, before the first instruction of the entry
block. A use site is (label, i, x): instruction i of block label reads x,
where i = len(instrs) stands for the terminator.
chains(prog) returns (du, ud). du maps every definition site to the sorted
list of use sites it reaches, and ud maps every use site to the sorted list
of definition sites that reach it. A definition d of x reaches a use u of x
if some path in the control flow graph goes from just after d to u and
does not define x again on the way. A phi operand that comes from the
predecessor p is used at the end of p. A store *p = a defines no name, so
names whose address is taken get incomplete chains (see the page).
reaching(prog) returns the sets IN and OUT of reaching definitions per
block, found by round-robin iteration in reverse postorder.
"""
import toyir
def _order(prog):
"""The labels in reverse postorder from the entry, then the labels that
the entry does not reach, in program order."""
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))))
rest = [lab for lab in prog.blocks if lab not in seen]
return post[::-1] + rest
def reaching(prog):
"""Return (IN, OUT, passes): dicts from label to a frozenset of
definition sites, and the number of passes of the iteration."""
entry = prog.entry
preds = toyir.preds(prog)
gen = {}
kill = {}
for lab, block in prog.blocks.items(): # @line L1
last = {}
for i, ins in enumerate(block.instrs):
x = toyir.defs(ins)
if x is not None:
last[x] = (lab, i, x)
gen[lab] = frozenset(last.values())
kill[lab] = frozenset(last)
params = frozenset((entry, -1, x) for x in prog.params)
out = {lab: gen[lab] for lab in prog.blocks} # @line L2
into = {}
order = _order(prog)
passes = 0
changed = True
while changed: # @line L3
changed = False
passes += 1
for lab in order: # @line L4
s = set(params) if lab == entry else set() # @line L5
for p in preds[lab]:
s |= out[p]
into[lab] = frozenset(s)
new = gen[lab] | frozenset(d for d in s if d[2] not in kill[lab]) # @line L6
if new != out[lab]:
out[lab] = new
changed = True # @line L7
return into, out, passes
def chains(prog):
into, out, _ = reaching(prog)
preds = toyir.preds(prog)
du = {}
ud = {}
for x in prog.params:
du[(prog.entry, -1, x)] = set()
for lab, block in prog.blocks.items():
for i, ins in enumerate(block.instrs):
x = toyir.defs(ins)
if x is not None:
du[(lab, i, x)] = set()
def link(defs, use):
ud.setdefault(use, set()).update(defs)
for d in defs:
du[d].add(use)
for lab, block in prog.blocks.items(): # @line L8
live = {}
for d in into[lab]: # @line L9
live.setdefault(d[2], set()).add(d)
n = len(block.instrs)
for i in range(n + 1): # @line L10
if i == n:
for x in toyir.term_uses(block.term):
link(live.get(x, ()), (lab, i, x))
break
ins = block.instrs[i]
if ins[0] == "phi":
for p, a in ins[2].items():
if p not in preds[lab]:
raise ValueError("phi in %s names %r, which is not a predecessor" % (lab, p))
if isinstance(a, str):
link([d for d in out[p] if d[2] == a], (lab, i, a))
else:
for x in toyir.uses(ins):
link(live.get(x, ()), (lab, i, x)) # @line L11
x = toyir.defs(ins)
if x is not None:
live[x] = {(lab, i, x)} # @line L12
du = {d: sorted(us) for d, us in du.items()} # @line L13
ud = {u: sorted(ds) for u, ds in ud.items()}
return du, ud
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_def_use_chains.py 289 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/def-use-chains/. The authors are listed in prov/XZ8C52.jsonl.
import random
import pytest
import toyir
from def_use_chains import chains, reaching
ODD_SUM = """
B1:
i = 0
s = 0
jump B2
B2:
t1 = i < n
br t1 B3 B6
B3:
t2 = i % 2
br t2 B4 B5
B4:
s = s + i
jump B5
B5:
i = i + 1
jump B2
B6:
ret s
"""
PHI = """
B0:
br c B1 B2
B1:
x1 = 1
jump B3
B2:
x2 = 2
jump B3
B3:
x3 = phi [B1: x1, B2: x2]
y = x3 + c
ret y
"""
def brute_chains(prog):
"""The chains by the definition, one graph search per definition over
the graph of program points. Point (lab, i) is instruction i of block
lab, and (lab, len(instrs)) is its terminator. A phi operand from p is
a use at the end of p."""
du = {}
starts = {}
for x in prog.params:
starts[(prog.entry, -1, x)] = (prog.entry, 0)
for lab, block in prog.blocks.items():
for i, ins in enumerate(block.instrs):
x = toyir.defs(ins)
if x is not None:
starts[(lab, i, x)] = (lab, i + 1)
for d, start in starts.items():
x = d[2]
found = set()
seen = {start}
stack = [start]
while stack:
lab, i = stack.pop()
block = prog.blocks[lab]
if i < len(block.instrs):
ins = block.instrs[i]
if ins[0] != "phi" and x in toyir.uses(ins):
found.add((lab, i, x))
if toyir.defs(ins) == x:
continue
nxt = [(lab, i + 1)]
else:
if x in toyir.term_uses(block.term):
found.add((lab, i, x))
nxt = []
for s in toyir.succs(prog, lab):
for k, ins in enumerate(prog.blocks[s].instrs):
if ins[0] == "phi" and ins[2].get(lab) == x:
found.add((s, k, x))
nxt.append((s, 0))
for q in nxt:
if q not in seen:
seen.add(q)
stack.append(q)
du[d] = sorted(found)
return du
def path_pairs(prog, path):
"""The (definition, use) pairs that one run along the block path shows:
each use is linked to the last definition of its name before it."""
last = {x: (prog.entry, -1, x) for x in prog.params}
pairs = set()
prev = None
for lab in path:
block = prog.blocks[lab]
incoming = []
for i, ins in enumerate(block.instrs):
if ins[0] == "phi":
a = ins[2].get(prev)
if isinstance(a, str) and a in last:
pairs.add((last[a], (lab, i, a)))
incoming.append((ins[1], (lab, i, ins[1])))
continue
for x, site in incoming:
last[x] = site
incoming = []
for x in toyir.uses(ins):
if x in last:
pairs.add((last[x], (lab, i, x)))
x = toyir.defs(ins)
if x is not None:
last[x] = (lab, i, x)
for x, site in incoming:
last[x] = site
for x in toyir.term_uses(block.term):
if x in last:
pairs.add((last[x], (lab, len(block.instrs), x)))
prev = lab
return pairs
def as_pairs(du):
return {(d, u) for d, us in du.items() for u in us}
def all_uses(prog):
out = set()
for lab, block in prog.blocks.items():
for i, ins in enumerate(block.instrs):
names = ins[2].values() if ins[0] == "phi" else toyir.uses(ins)
for x in names:
if isinstance(x, str):
out.add((lab, i, x))
for x in toyir.term_uses(block.term):
out.add((lab, len(block.instrs), x))
return out
def test_odd_sum_chains():
prog = toyir.parse(ODD_SUM)
du, ud = chains(prog)
assert du[("B1", 0, "i")] == [("B2", 0, "i"), ("B3", 0, "i"), ("B4", 0, "i"), ("B5", 0, "i")]
assert du[("B5", 0, "i")] == du[("B1", 0, "i")]
assert du[("B1", 1, "s")] == [("B4", 0, "s"), ("B6", 0, "s")]
assert du[("B4", 0, "s")] == [("B4", 0, "s"), ("B6", 0, "s")]
assert du[("B1", -1, "n")] == [("B2", 0, "n")]
assert ud[("B6", 0, "s")] == [("B1", 1, "s"), ("B4", 0, "s")]
assert ud[("B2", 1, "t1")] == [("B2", 0, "t1")]
assert sum(len(us) for us in du.values()) == 15
assert reaching(prog)[2] == 3
assert toyir.run(prog, [6]) == ("ret", 9)
def test_phi_operands_are_used_at_the_predecessor():
prog = toyir.parse(PHI)
du, ud = chains(prog)
assert du[("B1", 0, "x1")] == [("B3", 0, "x1")]
assert du[("B2", 0, "x2")] == [("B3", 0, "x2")]
assert ud[("B3", 1, "x3")] == [("B3", 0, "x3")]
assert du == brute_chains(prog)
with pytest.raises(ValueError):
chains(toyir.parse("A:\n x = phi [Z: 1]\n ret x\n"))
def test_du_and_ud_are_inverse():
rng = random.Random(71)
for _ in range(200):
prog = toyir.random_program(rng, 4, rng.randint(1, 8), rng.random() < 0.5)
du, ud = chains(prog)
assert as_pairs(du) == {(d, u) for u, ds in ud.items() for d in ds}
assert set(ud) == all_uses(prog)
def test_undefined_and_unreachable():
prog = toyir.parse("""
# params: a
A:
br a B C
B:
y = 1
jump C
C:
z = y + a
ret z
D:
y = 7
jump C
""")
du, ud = chains(prog)
# On the path A, C no definition of y comes first; the chain lists only B.
# D is unreachable, but a path from its definition to the use exists.
assert ud[("C", 0, "y")] == [("B", 0, "y"), ("D", 0, "y")]
assert ud[("C", 0, "a")] == [("A", -1, "a")]
assert du == brute_chains(prog)
def test_loop_back_to_the_entry():
prog = toyir.parse("""
# params: n
E:
t = n < 3
n = n + 1
br t E X
X:
ret n
""")
du, ud = chains(prog)
assert ud[("E", 0, "n")] == [("E", -1, "n"), ("E", 1, "n")]
assert ud[("X", 0, "n")] == [("E", 1, "n")]
assert du == brute_chains(prog)
def test_random_programs_match_the_definition():
rng = random.Random(73)
for _ in range(300):
prog = toyir.random_program(rng, 4, rng.randint(1, 8), rng.random() < 0.4)
du, _ = chains(prog)
assert du == brute_chains(prog)
def test_acyclic_programs_match_all_paths():
rng = random.Random(79)
for _ in range(300):
prog = toyir.random_program(rng, 4, rng.randint(1, 8), True)
du, _ = chains(prog)
seen = set()
for path in toyir.paths(prog):
seen |= path_pairs(prog, path)
assert as_pairs(du) == seen
def test_random_walks_stay_inside_the_chains():
rng = random.Random(83)
for _ in range(300):
prog = toyir.random_program(rng, 4, rng.randint(2, 8), False)
pairs = as_pairs(chains(prog)[0])
for _ in range(5):
path = [prog.entry]
while toyir.succs(prog, path[-1]) and len(path) < 40:
path.append(rng.choice(toyir.succs(prog, path[-1])))
assert path_pairs(prog, path) <= pairs
def test_passes_bound_on_reducible_programs():
# Reaching definitions in reverse postorder: random programs are
# reducible, so their loop connectedness is small.
rng = random.Random(89)
worst = 0
for _ in range(300):
prog = toyir.random_program(rng, 4, rng.randint(1, 9), False)
worst = max(worst, reaching(prog)[2])
assert 2 <= worst <= 4
def join_program(k):
lines = ["T1:"]
for i in range(1, k + 1):
lines.append("T%d:" % i if i > 1 else "")
nxt = "T%d" % (i + 1) if i < k else "D%d" % i
lines.append(" br c D%d %s" % (i, nxt))
for i in range(1, k + 1):
lines += ["D%d:" % i, " x = %d" % i, " jump J"]
lines.append("J:")
for j in range(k):
lines.append(" y%d = x + %d" % (j, j))
lines.append(" ret x")
return toyir.parse("\n".join(line for line in lines if line))
def test_k_definitions_and_k_uses_give_k_squared_chains():
for k in (2, 5, 20):
prog = join_program(k)
du, _ = chains(prog)
links = sum(len(us) for d, us in du.items() if d[2] == "x")
assert links == k * (k + 1)
assert du == brute_chains(prog)
def test_bigger_program():
rng = random.Random(97)
prog = toyir.random_program(rng, 6, 60, False)
du, _ = chains(prog)
assert du == brute_chains(prog)
History
Reaching definitions was among the first global data-flow problems that optimizing compilers solved, in the work of Allen and Cocke at IBM in the late 1960s and 1970s, and the chains were the usual way to keep its answer per use. Kennedy's paper of 1978 described use-definition chains and many optimizations built on them. Textbooks of the 1980s and 1990s, among them the dragon book and Muchnick, presented du-chains, ud-chains and webs as the standard tools of global optimization. Static single assignment form, from Cytron, Ferrante, Rosen, Wegman and Zadeck (1991), made each ud-chain a single definition and replaced explicit chains in most compilers.
References
- Ken Kennedy, Use-definition chains with applications, Computer Languages 3(3), 1978, pages 163-179, use-definition chains, how to compute them from reaching definitions, and their use in program optimization
- Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Section 9.2.4 (reaching definitions, with gen and kill sets per block and the iterative solution)
- Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Chapter 8 (Data-Flow Analysis), the section on du-chains, ud-chains and webs
- Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 9 (Data-Flow Analysis), iterative data-flow analysis and static single-assignment form
Where this leads
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 | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag XZ8C52 Edit this page History Report an error Markdown