Algorithmcore
Worklist dataflow algorithm
Also called Kildall's algorithm, iterative dataflow algorithm.
Solves dataflow equations by keeping a worklist of nodes whose input changed and applying their transfer functions until nothing changes.
- Solves
- Reaching definitions, Live variable analysis, Available expressions, Very busy expressions, Constant propagation
- Time
- O((n + m)(h + 1)) worst · averageΘ(n + m) best
- Space
- Θ(n) extra
- Where
- h = the height of the lattice; m = the number of edges; n = the number of blocks
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
The worklist dataflow algorithm solves the equations of a monotone dataflow framework. Every node of the graph gets the value , the start nodes get the boundary value , and a queue holds the nodes whose output may still change. The algorithm takes a node from the queue, applies its transfer function, meets the result into the input of each successor, and puts back every successor whose input went down. When the queue is empty, the values are the maximal fixed-point solution (MFP), the greatest solution of the equations. It is safe, because MFP is below the meet-over-all-paths solution, and it equals that solution in a distributive dataflow framework where every node is reachable. With nodes, edges and a lattice of height , it applies at most transfer functions and meets. The same code solves reaching definitions, live variables, available expressions, very busy expressions and constant propagation; only the lattice, the functions and the direction change.
In plain words
Picture the blocks of a program, each with a note that says what is known there. At first every note holds the most hopeful claim, except at the place where the analysis starts, which gets the honest starting fact. Every block goes on a to-do list. Take a block off the list, work out what holds when control leaves it, and hand that to the blocks that come next. Each of them combines the new fact with its note. If its note gets weaker, it goes back on the list, because what it hands on may change too. A note can only get weaker, and only a few times, so the list runs empty. Then every note agrees with its neighbors, and the notes are the most precise answer that such local agreement allows.
The problem
The input is an instance of a monotone framework, in the meet convention used by Kildall, Kam and Ullman, and the dragon book:
- a directed graph with nodes and edges, and a set of start nodes;
- a meet semilattice with top element , where means , and of finite height : no strictly descending chain has more than steps;
- a boundary value ;
- a monotone transfer function for each node .
Let if and otherwise. The output is the greatest assignment with
the maximal fixed-point solution. For a forward problem, is the control flow graph, holds the entry block, and is the fact at the start of block . For a backward problem, is the reverse CFG, holds the blocks that end in ret, and is the fact at the end of block . The facts on the other side of each block are .
| problem | graph | start nodes | meet | ||
|---|---|---|---|---|---|
| reaching definitions | CFG | entry | |||
| live variables | reverse CFG | ret blocks |
|||
| available expressions | CFG | entry | all expressions | ||
| very busy expressions | reverse CFG | ret blocks |
all expressions | ||
| constant propagation | CFG | entry | per variable, in a flat lattice | no value yet, for every variable | parameters not constant |
May problems use union and must problems use intersection. In a must problem is the set of all items, so the boundary value is the bottom element and not .
The algorithm
only goes down during the run, so line L8 can meet the new output into the old value instead of recomputing the meet over all predecessors. A flag per node records whether it is in the queue, so the test of line L11 costs . The queue starts with every node, in reverse postorder from the start nodes (see depth-first orders), so on the acyclic parts of the graph a node usually runs after all its predecessors.
WORKLIST(V, succ, S, ι, ⊤, ⊓, f)- 1
for each node v in V do IN[v] ← ⊤ - 2
for each start node s in S do IN[s] ← ι - 3
W ← a queue that holds every node of V once, in reverse postorder - 4
while W is not empty do - 5
v ← remove the first node of W - 6
out ← f_v(IN[v]) - 7
for each successor s of v do - 8
new ← IN[s] ⊓ out - 9
if new ≠ IN[s] then - 10
IN[s] ← new - 11
if s is not in W then append s to W return IN
A backward problem calls the same procedure with the predecessor lists as and the ret blocks as . Nothing else changes.
Example
The running example of dataflow analysis has the parameters n and x:
entry:
i = 0
s = 0
jump head
head:
t = i < n
br t body done
body:
a = x * 2
u = i & 1
br u odd next
odd:
s = s + a
jump next
next:
i = i + 1
jump head
done:
ret s
Take live variables, a backward problem. The reverse CFG has done as its only start node, and the queue starts with its reverse postorder done, head, next, odd, body, entry. is the set live at the end of , and line L6 gives the set live at its start, which goes to the predecessors of in the CFG.
| step | node | out (live at its start) | IN changed at | queue after the step |
|---|---|---|---|---|
| 1 | done | s | head | head, next, odd, body, entry |
| 2 | head | i, n, s | entry, next | next, odd, body, entry |
| 3 | next | i, n, s | body, odd | odd, body, entry |
| 4 | odd | a, i, n, s | body | body, entry |
| 5 | body | i, n, s, x | head | entry, head |
| 6 | entry | n | none | head |
| 7 | head | i, n, s, x | entry, next | entry, next |
| 8 | entry | n, x | none | next |
| 9 | next | i, n, s, x | body, odd | body, odd |
| 10 | body | i, n, s, x | none | odd |
| 11 | odd | a, i, n, s, x | none | empty |
The first pass misses x in most blocks, because x is read only in body and that read reaches head, next and odd only around the loop. Step 5 lowers when head has already left the queue, so head goes back in, and its new output then reaches entry and next again. The run applies 11 transfer functions, does 13 unions and changes an value 11 times; no value changes more than 3 times. With blocks, edges and variables, the bounds are 48 transfer functions and 56 meets. On the same program, reaching definitions also takes 11 transfer functions and 13 meets, available expressions and very busy expressions take 6 and 7 (each block runs once), and constant propagation takes 14 and 17, with .
Correctness
The full proof is in the proof file. Its steps:
- Values only go down. Line L8 gives , so every change at line L10 is a strict step down.
- Termination and counts. By step 1 each changes at most times. A node enters the queue once at line L3 and once more at most after each change, so it is removed at most times.
- Nothing safe is lost. For every assignment with , where is the right side of the equations, holds at all times. It holds after line L2, and line L10 keeps it because by monotonicity.
- The end is a fixed point. A node that is not in the queue has sent its current output to all its successors, and a change of its own value puts it back. So at the end for every edge, and . Every node runs at least once, and every value at the end is the meet of and of outputs computed from higher values, so also .
- It is the MFP. By steps 3 and 4 the result is a fixed point above every fixed point. The order of the queue does not matter for the result.
- Safety and precision. Induction on path length gives for every monotone framework. If every function is distributive and every node is reachable from , then , so step 3 gives and the two are equal. Gen-kill functions are distributive over and over , so this covers the four bit-vector problems.
Proof: The worklist dataflow algorithm terminates and computes the maximal fixed pointfull
Setting. is a meet semilattice: is idempotent, commutative and associative. means ; this is a partial order in which is the greatest lower bound of and , and is monotone in each argument. is the identity of , so for all . The height is finite: every chain has . is a directed graph with nodes and edges, is the set of start nodes, is the boundary value, and each is monotone: implies . Let for and otherwise. An assignment gives each node a value, and means for all . Define
where the empty meet is . The maximal fixed-point solution (MFP) is the greatest with . is monotone, because each and the meet are.
We use the lines L1 to L11 of the pseudocode. An iteration is one pass through lines L5 to L11. Line L3 puts every node into exactly once. We write for the number of times line L10 changes , and .
Lemma 1 (values go down). After line L2, for every . Every execution of lines L8 to L10 for an edge leaves equal to its old value met with , and if line L10 runs, the new value is strictly below the old one.
Proof. Line L1 sets every value to and line L2 sets the start nodes to , which is . Line L8 computes . If , nothing changes and already. Otherwise line L10 stores , and with .
Lemma 2 (the queue). never holds a node twice. A node is added to only at line L3 or at line L11, and line L11 adds only right after line L10 has changed .
Proof. Line L3 adds each node once, and line L11 adds only if it is not in . The rest is read off the code.
Theorem 1 (termination and counts). Each changes at most times. The loop of line L4 runs at most times, so line L6 applies at most transfer functions, and line L8 computes at most meets. In particular the algorithm terminates.
Proof. By Lemma 1 the values taken by form a strictly descending chain with steps, so . By Lemma 2, is added to at most times, and each iteration removes one node at line L5, so is removed at most times. Summing over the nodes, there are at most iterations, each with one transfer function at line L6. An iteration that removes runs line L8 once per outgoing edge of , so the number of meets is at most . Each iteration is finite, and there are finitely many, so the run ends.
Lemma 3 (no safe value is lost). Let be any assignment with . Then holds after line L2 and after every later step.
Proof. After line L2, , because a meet is below each of its terms. Values change only at line L10, for an edge , with and , where is the value of when line L6 ran in this iteration. By the claim at that time, , so by monotonicity
By the claim before the change, . So is a lower bound of and , hence .
Lemma 4 (the end is below ). Let be the value of when the algorithm stops. Then .
Proof. We show that the following claim P holds before every iteration and after the last one: for every node and every edge , .
Before the first iteration , so P holds trivially. Assume P before an iteration that removes , and look at the state after it.
- The node . For each successor , after line L8 and line L10, by Lemma 1, and later steps of this iteration only lower . If did not change in this iteration, then , and P holds for . If changed, which happens only through a self-loop , then line L11 added back, since line L5 had removed it, so and P says nothing about .
- Another node . Nodes leave only at line L5, so was not in before the iteration either, and P held for . If had changed in this iteration, line L11 would have put into , or would have been there already, so did not change. The values of the successors of can only have gone down by Lemma 1, so still holds.
When the algorithm stops, is empty, so P gives for every edge . By Lemma 1, . So is a lower bound of all terms of , and .
Lemma 5 (the end is above ). .
Proof. By Lemma 1 and induction over the run, , where are all the values used at line L8 for edges into . Each belongs to an edge and equals for a value that had during the run. By Lemma 1, , so by monotonicity. Every node is removed from at least once, because it is in after line L3 and the run stops only when is empty, so every edge is among the . Since the meet is monotone in each argument and idempotent,
Theorem 2 (correctness). is the maximal fixed-point solution. It is also the greatest assignment with . In particular the MFP exists, and the result does not depend on the order of the queue in line L3.
Proof. By Lemmas 4 and 5 and antisymmetry, , so is a fixed point. If is any fixed point, or any assignment with , then Lemma 3 at the end of the run gives . So is the greatest fixed point, and also the greatest such . Greatest elements are unique, so every order of the queue gives the same .
Meet over all paths. A path in with is a path to ; its function is , the functions of the nodes before , and the identity if . Let be the set of paths to . The meet-over-all-paths solution is , which is if is empty. can be infinite, so we first show that this meet exists.
Lemma 6 (meets of arbitrary sets). Every nonempty set has a greatest lower bound , and it is the meet of at most members of .
Proof. Pick and set . While some has , pick such an and set , which is strictly below . The chain has at most steps, so it stops at some , , with for all . Any lower bound of is below , hence below their meet . So is the greatest lower bound.
Theorem 3 (MFP is below MOP). For every monotone framework and every node , . So every fact of the result holds along every path, and the result is safe whenever each safely describes its node.
Proof. We show for every path with , by induction on . If , and . If , let be without its last node, a path to , so . By Theorem 2, the induction hypothesis and monotonicity,
So is a lower bound of all with , and ; if is empty this holds because .
Theorem 4 (MFP equals MOP for distributive frameworks). Suppose every is distributive, for all , and every node is reachable from . Then .
Proof. A distributive is monotone: if , then , so . It also distributes over every nonempty set : by Lemma 6, for some members, so , and for every by monotonicity, so .
Let . We show . Fix a node . If , the path of length zero gives the term , so ; otherwise . For an edge , the set is nonempty because is reachable, so
Each is for the path followed by , which is in , so it is above . Hence . So is below every term of , and . Lemma 3, applied at the end of the run, gives , and Theorem 3 gives .
Reachability is needed. If is not reachable, , and can be below . In reaching definitions, an unreachable block with a self-loop and a definition has , but is in its MFP.
Lemma 7 (gen-kill functions are distributive). On the subsets of a finite set , let . Then and . The composition of two such functions is again of this form.
Proof. Set difference distributes over union and intersection: and . So , and , because union distributes over intersection. For the composition, with applied first,
which has gen set and kill set .
So the block functions of reaching definitions, live variables, available expressions and very busy expressions, which are compositions of the gen-kill functions of their instructions, are distributive for both meets. In the lattice of subsets of under or , the height is . By Theorems 2 and 4, the algorithm computes the MOP solution of these four problems on every CFG where every block is reachable from the entry (forward problems) or reaches a ret block (backward problems, on the reverse CFG).
Theorem 5 (best case). If is acyclic and line L3 orders the nodes so that every edge goes from an earlier node to a later one, then line L11 never adds a node, and the run applies exactly transfer functions and meets.
Proof. Suppose line L11 adds a node, and look at the first time it does, while is processed, for an edge . Up to then no node was added, so holds exactly the nodes after in the initial order. The edge puts after , so , and line L11 does not add it, a contradiction. So each node is removed exactly once, line L6 runs times, and line L8 runs once per edge.
Complexity
A transfer function or a meet counts as one lattice operation. The proved bounds:
- Transfer functions. Each removal of a node from the queue applies one function. A node is removed at most once more than its value changes, so there are at most of them, where is the total number of changes.
- Meets. Each removal of does one meet per outgoing edge, so there are at most meets.
- Total. lattice operations, plus queue work per operation. The extra space is one value per node, the queue and the flags, values.
- Best case. If the graph is acyclic and the queue starts in a topological order, such as reverse postorder from the start nodes when every node is reachable, no node is ever appended again: exactly transfer functions and meets.
- Bit vectors. For a gen-kill problem over items, and one operation costs word operations on a -bit word RAM, so the worst case is . For constant propagation over variables, .
The bound is a worst case allowed by the height, and it is rarely reached. The table below is measured, not proved: it comes from 300 random looping programs of the toy IR (seed 31337), with 3 to 8 blocks and 25.6 instructions on average (at most 43), solved with a queue in reverse postorder.
| analysis | transfer functions per block, average | per block, worst | most changes of one value | largest | meets per edge, worst |
|---|---|---|---|---|---|
| reaching definitions | 1.36 | 2.12 | 6 | 35 | 2.33 |
| live variables | 1.32 | 2.25 | 4 | 14 | 2.11 |
| available expressions | 1.11 | 1.67 | 4 | 24 | 1.78 |
| very busy expressions | 1.16 | 1.71 | 3 | 24 | 1.67 |
| constant propagation | 2.04 | 3.50 | 7 | 28 | 3.67 |
The bound allows transfer functions per block, up to 36 here, and the worst run used 3.5. For rapid frameworks such as the bit-vector problems, the Kam-Ullman iteration bound shows that the number of round-robin sweeps depends on the loops of the graph and not on .
Properties
- Order-free result. Any initial order of the queue, and a stack or a priority queue in place of the FIFO queue, gives the same MFP. Only the amount of work depends on the order.
- Deterministic. For a fixed order the run, its counts and its result are fixed.
- Non-recursive. One loop and a queue; no recursion.
- Generic. The algorithm needs only , , the meet, an equality test and the transfer functions. The lattice can be sets, bit vectors, maps from variables to constants, or any other domain of finite height.
- No safe partial answer. Values move down only, so a run stopped early can leave values that are too high, which is unsafe.
Variants and improvements
- Round-robin iteration. Sweep over all nodes in reverse postorder until a whole sweep changes nothing. For rapid frameworks, which include the four bit-vector problems, sweeps suffice, where is the largest number of back edges on an acyclic path (Kam-Ullman iteration bound). It is simpler, but it revisits nodes whose inputs did not change.
- Priority by order. Keep the worklist sorted by reverse postorder number and always take the earliest node. This follows the flow of the program more closely than a FIFO queue, and the result is the same.
- Recompute the input. Store and recompute as the meet over all predecessors when is taken from the queue, as in the dragon book. This gives the same result, but a node with predecessors costs meets per visit.
- Bit-vector parallelism. For gen-kill problems, store each set as a bit vector, so one machine word handles items at once.
- Elimination methods. Elimination dataflow methods solve the equations by the loop structure of a reducible flow graph, instead of by iteration.
- Sparse analysis. On static single assignment form, facts about a variable can travel along def-use edges instead of through every block. Sparse conditional constant propagation runs one worklist of CFG edges and one of SSA edges.
- Deltas. For a union meet, send only the items that are new since the last visit, as in semi-naive evaluation of Datalog.
- Infinite height. For lattices such as intervals, the run may not end. Abstract interpretation adds a widening operator at loop heads to force termination, in the join convention where values go up from .
- Interprocedural problems. The IFDS framework runs a worklist over path edges of an exploded supergraph.
When to use it
Use it for any intraprocedural dataflow problem with monotone transfer functions and a lattice of finite height. It is the standard solver in compilers and static analyzers: it needs no structure of the graph, works for irreducible control flow, and does little work on typical programs. If the lattice has infinite height, add widening. If the program is in SSA form and the facts are per variable, a sparse solver is often faster.
Pitfalls
- Setting the boundary to . The boundary value describes the start of the program (or the point after
ret) and is usually not . In available expressions, but is the set of all expressions; starting the entry at claims that every expression is available on entry. In the may problems , which hides the difference. - Running a backward problem on the CFG. A backward problem needs the reverse CFG, with the
retblocks as start nodes and the queue order taken from the reverse CFG. Its values are the facts at the ends of the blocks. - Starting a must problem at the empty set. The other nodes must start at , the set of all items. Starting at still ends at a fixed point, but often a smaller one: an expression computed before a loop is lost at the loop head, because the back edge brings .
- A queue that does not hold every node at the start. If line L3 puts only the start nodes in the queue, a node whose input never changes is never processed, so its own facts, such as its definitions in reaching definitions, never reach its successors. Line L3 must queue every node once.
- Unreachable nodes. Nodes that the start nodes do not reach get values from the equations alone, which can differ from MOP. For example, an unreachable block that loops to itself keeps its own definitions in reaching definitions. MFP = MOP needs every node to be reachable.
- Non-monotone functions. If a transfer function is not monotone, the equations may have no solution. This algorithm still stops, because line L8 only lowers values, but its result is then not a solution, and a solver that recomputes inputs can loop forever. With one item , union as the meet and a self-loop with the function , this algorithm returns , which does not satisfy .
- Self-loops. Line L5 must clear the queue flag of before the loop of line L7, so that a self-loop that lowers puts back.
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
# 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)
worklist_dataflow_algorithm.py 328 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/worklist-dataflow-algorithm/. The authors are listed in prov/5353DC.jsonl.
"""The worklist dataflow algorithm (Kildall 1973) on the toy IR.
The lattice uses the meet convention of Kildall and the dragon book: top is
the identity of meet and the start value, and the result is the maximal
fixed point (MFP). A backward problem runs the same solver on the reverse
CFG, with the ret blocks as start nodes.
Five analyses are given: reaching definitions, live variables, available
expressions and very busy expressions (gen-kill problems on frozensets),
and constant propagation (a flat lattice per variable, not distributive).
"""
from collections import deque
from toyir import defs, preds, succs, term_uses, uses
TOP = "top" # constant propagation: no value seen yet
NAC = "nac" # constant propagation: not a constant (bottom)
def worklist(nodes, succ, starts, boundary, top, meet, transfer, order=None):
"""Solve IN[s] = (boundary if s is a start else top) meet the meet over
the edges (n, s) of transfer(n, IN[n]), for the greatest solution.
nodes: the nodes; succ: dict node -> list of successors in the direction
of the analysis; starts: the start nodes. Returns (IN, stats), where
stats counts transfer applications, meets and changes of IN."""
order = list(nodes) if order is None else list(order)
inn = {n: top for n in nodes} # @line L1
for s in starts:
inn[s] = boundary # @line L2
work = deque(order) # @line L3
queued = set(order)
stats = {"transfers": 0, "meets": 0, "changes": 0}
changes = {n: 0 for n in nodes}
while work: # @line L4
n = work.popleft() # @line L5
queued.discard(n)
out = transfer(n, inn[n]) # @line L6
stats["transfers"] += 1
for s in succ[n]: # @line L7
new = meet(inn[s], out) # @line L8
stats["meets"] += 1
if new != inn[s]: # @line L9
inn[s] = new # @line L10
changes[s] += 1
stats["changes"] += 1
if s not in queued: # @line L11
work.append(s)
queued.add(s)
stats["max_changes"] = max(changes.values(), default=0)
return inn, stats
def reverse_postorder(nodes, succ, starts):
"""Nodes in reverse postorder of a DFS from the starts; nodes that the
starts do not reach come last, in their given order."""
seen, post = set(), []
for root in starts:
if root in seen:
continue
seen.add(root)
stack = [(root, iter(succ[root]))]
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(succ[w])))
order = post[::-1]
return order + [n for n in nodes if n not in seen]
def graph(prog, forward):
"""The CFG in the direction of the analysis: (nodes, succ, starts)."""
nodes = list(prog.blocks)
if forward:
return nodes, {n: succs(prog, n) for n in nodes}, [prog.entry]
p = preds(prog)
exits = [n for n in nodes if prog.blocks[n].term[0] == "ret"]
return nodes, {n: p[n] for n in nodes}, exits
def solve(prog, an):
"""Run the worklist algorithm for the analysis an. Returns (IN, OUT,
stats) in CFG terms: IN[L] holds at the start of block L, OUT[L] at its
end, for forward and backward problems alike."""
nodes, succ, starts = graph(prog, an.forward)
order = reverse_postorder(nodes, succ, starts)
before, stats = worklist(nodes, succ, starts, an.boundary, an.top, an.meet, an.transfer, order)
after = {n: an.transfer(n, before[n]) for n in nodes}
if an.forward:
return before, after, stats
return after, before, stats
# ------------------------------------------------------------ gen-kill problems
def compose(first, second):
"""The gen-kill pair of second after first: gen2 | (gen1 - kill2),
kill1 | kill2."""
g1, k1 = first
g2, k2 = second
return g2 | (g1 - k2), k1 | k2
class GenKill:
"""A gen-kill problem. step(label, i, ins) gives the gen-kill pair of
one instruction (ins is None for the terminator); the block pair is the
composition in the direction of the analysis."""
def __init__(self, prog, forward, must, universe, step, boundary=frozenset()):
self.prog = prog
self.forward = forward
self.must = must
self.universe = frozenset(universe)
self.top = self.universe if must else frozenset()
self.boundary = frozenset(boundary)
self.height = len(self.universe)
self.step = step
self.block = {}
for label, b in prog.blocks.items():
items = [(i, ins) for i, ins in enumerate(b.instrs)] + [(len(b.instrs), None)]
if not forward:
items.reverse()
pair = (frozenset(), frozenset())
for i, ins in items:
g, k = step(label, i, ins)
pair = compose(pair, (frozenset(g), frozenset(k)))
self.block[label] = pair
def meet(self, a, b):
return a & b if self.must else a | b
def transfer(self, label, x):
g, k = self.block[label]
return g | (x - k)
def leq(self, a, b):
return self.meet(a, b) == a
def _check(prog):
for b in prog.blocks.values():
for ins in b.instrs:
if ins[0] not in ("const", "copy", "op"):
raise ValueError("these analyses take const, copy and op only")
def names(prog):
out = list(prog.params)
for b in prog.blocks.values():
for ins in b.instrs:
for a in uses(ins) + [defs(ins)]:
if a not in out:
out.append(a)
for a in term_uses(b.term):
if a not in out:
out.append(a)
return out
def expressions(prog):
"""The expressions (op, a, b) of the program, in program order."""
out = []
for b in prog.blocks.values():
for ins in b.instrs:
if ins[0] == "op" and ins[2:] not in out:
out.append(ins[2:])
return out
def reaching_definitions(prog):
"""Forward, may. A definition is the pair (label, index)."""
_check(prog)
sites = [(lab, i) for lab, b in prog.blocks.items() for i in range(len(b.instrs))]
by_var = {}
for lab, i in sites:
by_var.setdefault(defs(prog.blocks[lab].instrs[i]), set()).add((lab, i))
def step(label, i, ins):
if ins is None:
return set(), set()
return {(label, i)}, by_var[defs(ins)] - {(label, i)}
return GenKill(prog, True, False, sites, step)
def live_variables(prog):
"""Backward, may. A fact is a variable name."""
_check(prog)
def step(label, i, ins):
if ins is None:
return set(term_uses(prog.blocks[label].term)), set()
return set(uses(ins)), {defs(ins)}
return GenKill(prog, False, False, names(prog), step)
def _killed(exprs, x):
return {e for e in exprs if x in (e[1], e[2])}
def available_expressions(prog):
"""Forward, must. A fact is an expression (op, a, b)."""
_check(prog)
exprs = expressions(prog)
def step(label, i, ins):
if ins is None:
return set(), set()
kill = _killed(exprs, defs(ins))
gen = {ins[2:]} - kill if ins[0] == "op" else set()
return gen, kill
return GenKill(prog, True, True, exprs, step)
def very_busy_expressions(prog):
"""Backward, must. A fact is an expression (op, a, b)."""
_check(prog)
exprs = expressions(prog)
def step(label, i, ins):
if ins is None:
return set(), set()
kill = _killed(exprs, defs(ins))
gen = {ins[2:]} if ins[0] == "op" else set()
return gen, kill
return GenKill(prog, False, True, exprs, step)
# --------------------------------------------------------- constant propagation
def flat_meet(a, b):
if a == TOP:
return b
if b == TOP or a == b:
return a
return NAC
def fold(op, a, b):
"""The abstract value of a op b on the flat lattice."""
if a == NAC or b == NAC:
return NAC
if a == TOP or b == TOP:
return TOP
if op in ("/", "%") and b == 0:
return NAC # the program traps here; NAC is a safe answer
if op in ("<<", ">>") and not 0 <= b <= 63:
return NAC
if op in ("/", "%"):
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return q if op == "/" else a - b * q
table = {
"+": lambda: a + b, "-": lambda: a - b, "*": lambda: a * b,
"&": lambda: a & b, "|": lambda: a | b, "^": lambda: a ^ b,
"<<": lambda: a << b, ">>": lambda: a >> b,
"<": lambda: int(a < b), "<=": lambda: int(a <= b),
"==": lambda: int(a == b), "!=": lambda: int(a != b),
}
return table[op]()
class ConstantPropagation:
"""Forward. A value is a tuple with one flat-lattice entry per name.
Parameters start as NAC, the other names as TOP (not yet defined)."""
forward = True
def __init__(self, prog):
_check(prog)
self.prog = prog
self.vars = names(prog)
self.index = {x: i for i, x in enumerate(self.vars)}
self.top = tuple(TOP for _ in self.vars)
self.boundary = tuple(NAC if x in prog.params else TOP for x in self.vars)
self.height = 2 * len(self.vars)
def meet(self, a, b):
return tuple(flat_meet(x, y) for x, y in zip(a, b))
def leq(self, a, b):
return self.meet(a, b) == a
def value(self, env, a):
return a if isinstance(a, int) else env[self.index[a]]
def step(self, env, ins):
env = list(env)
k, x = ins[0], ins[1]
if k == "const":
env[self.index[x]] = ins[2]
elif k == "copy":
env[self.index[x]] = self.value(env, ins[2])
else:
env[self.index[x]] = fold(ins[2], self.value(env, ins[3]), self.value(env, ins[4]))
return tuple(env)
def transfer(self, label, env):
for ins in self.prog.blocks[label].instrs:
env = self.step(env, ins)
return env
def constant_propagation(prog):
return ConstantPropagation(prog)
ANALYSES = {
"reaching-definitions": reaching_definitions,
"live-variables": live_variables,
"available-expressions": available_expressions,
"very-busy-expressions": very_busy_expressions,
"constant-propagation": constant_propagation,
}
test_worklist_dataflow_algorithm.py 411 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/worklist-dataflow-algorithm/. The authors are listed in prov/5353DC.jsonl.
import random
import toyir
from toyir import defs, parse, paths, preds, random_program, succs, term_uses, uses
from worklist_dataflow_algorithm import (
ANALYSES,
NAC,
TOP,
available_expressions,
constant_propagation,
live_variables,
reaching_definitions,
solve,
very_busy_expressions,
)
EX = """
# params: n, x
entry:
i = 0
s = 0
jump head
head:
t = i < n
br t body done
body:
a = x * 2
u = i & 1
br u odd next
odd:
s = s + a
jump next
next:
i = i + 1
jump head
done:
ret s
"""
DIAMOND = """
# params: c
entry:
br c left right
left:
x = 2
y = 3
jump join
right:
x = 3
y = 2
jump join
join:
z = x + y
ret z
"""
GENKILL = ["reaching-definitions", "live-variables", "available-expressions", "very-busy-expressions"]
def exits(prog):
return [n for n in prog.blocks if prog.blocks[n].term[0] == "ret"]
# ------------------------------------------------------------ reference: MOP
def mop(prog, an, inclusive=False):
"""Meet over all paths by enumeration on an acyclic CFG, in CFG terms
(IN for a forward problem, OUT for a backward one). With inclusive=True
the paths also run through the block itself (OUT for a forward problem,
IN for a backward one)."""
res = {n: an.top for n in prog.blocks}
j = 1 if inclusive else 0
for p in paths(prog):
for k in range(len(p)):
if an.forward:
head, rest = p[k], p[:k + j]
else:
head, rest = p[k], list(reversed(p[k + 1 - j:]))
v = an.boundary
for b in rest:
v = an.transfer(b, v)
res[head] = an.meet(res[head], v)
return res
def walk_facts(prog, labels, kind, exprs):
"""The fact of one path, by the meaning of the problem, without gen and
kill sets. labels are the blocks, in program order, that the path runs
through after (forward) or before (backward) the point."""
events = []
for b in labels:
blk = prog.blocks[b]
for i, ins in enumerate(blk.instrs):
events += [("use", a) for a in uses(ins)]
if ins[0] == "op":
events.append(("eval", ins[2:]))
events.append(("def", defs(ins), (b, i)))
events += [("use", a) for a in term_uses(blk.term)]
if kind == "reaching-definitions":
last = {}
for e in events:
if e[0] == "def":
last[e[1]] = e[2]
return frozenset(last.values())
if kind == "available-expressions":
avail = set()
for e in events:
if e[0] == "eval":
avail.add(e[1])
elif e[0] == "def":
avail = {f for f in avail if e[1] not in (f[1], f[2])}
return frozenset(avail)
if kind == "live-variables":
live, written = set(), set()
for e in events:
if e[0] == "use" and e[1] not in written:
live.add(e[1])
elif e[0] == "def":
written.add(e[1])
return frozenset(live)
busy, dead = set(), set()
for e in events:
if e[0] == "eval" and e[1] not in dead:
busy.add(e[1])
elif e[0] == "def":
dead |= {f for f in exprs if e[1] in (f[1], f[2]) and f not in busy}
return frozenset(busy)
def by_meaning(prog, kind):
an = ANALYSES[kind](prog)
exprs = an.universe
res = {n: an.top for n in prog.blocks}
for p in paths(prog):
for k in range(len(p)):
labels = p[:k] if an.forward else p[k + 1:]
res[p[k]] = an.meet(res[p[k]], walk_facts(prog, labels, kind, exprs))
return res
# ------------------------------------------------- reference: round robin
def round_robin(prog, an):
"""Kleene iteration from top over all blocks until nothing changes."""
nodes = list(prog.blocks)
p = preds(prog)
ins = {n: an.top for n in nodes}
changed = True
while changed:
changed = False
for n in nodes:
if an.forward:
v = an.boundary if n == prog.entry else an.top
for q in p[n]:
v = an.meet(v, an.transfer(q, ins[q]))
else:
v = an.boundary if prog.blocks[n].term[0] == "ret" else an.top
for q in succs(prog, n):
v = an.meet(v, an.transfer(q, ins[q]))
if v != ins[n]:
ins[n] = v
changed = True
return ins
def check_fixed_point(prog, an, IN, OUT):
p = preds(prog)
for n in prog.blocks:
if an.forward:
v = an.boundary if n == prog.entry else an.top
for q in p[n]:
v = an.meet(v, OUT[q])
assert IN[n] == v and OUT[n] == an.transfer(n, IN[n])
else:
v = an.boundary if prog.blocks[n].term[0] == "ret" else an.top
for q in succs(prog, n):
v = an.meet(v, IN[q])
assert OUT[n] == v and IN[n] == an.transfer(n, OUT[n])
# --------------------------------------------- reference: concrete runs
def trace(prog, args, fuel=2000):
"""Run prog and record events: ("enter", L, env), ("use", x),
("eval", e) and ("def", x, (L, i)). Returns (events, outcome)."""
env = dict(zip(prog.params, args))
events = []
label = prog.entry
try:
while True:
events.append(("enter", label, dict(env)))
blk = prog.blocks[label]
for i, ins in enumerate(blk.instrs):
fuel -= 1
if fuel < 0:
return events, "fuel"
events += [("use", a) for a in uses(ins)]
def val(a):
return a if isinstance(a, int) else env[a]
if ins[0] == "const":
env[ins[1]] = ins[2]
elif ins[0] == "copy":
env[ins[1]] = val(ins[2])
else:
events.append(("eval", ins[2:]))
env[ins[1]] = toyir._binop(ins[2], val(ins[3]), val(ins[4]))
events.append(("def", ins[1], (label, i)))
events += [("use", a) for a in term_uses(blk.term)]
t = blk.term
if t[0] == "ret":
return events, "ret"
if t[0] == "jump":
label = t[1]
else:
c = t[1] if isinstance(t[1], int) else env[t[1]]
label = t[2] if c != 0 else t[3]
except toyir._Trap:
return events, "trap"
def check_runs(prog, results, rng):
IN = {k: results[k][0] for k in results}
cp = constant_propagation(prog)
for _ in range(12):
args = [rng.randint(-5, 9) for _ in prog.params]
events, outcome = trace(prog, args)
last, avail = {}, set()
for e in events:
if e[0] == "enter":
assert set(last.values()) <= IN["reaching-definitions"][e[1]]
assert IN["available-expressions"][e[1]] <= avail
for x, v in zip(cp.vars, IN["constant-propagation"][e[1]]):
if v == TOP:
assert x not in e[2]
elif v != NAC:
assert e[2].get(x, v) == v
elif e[0] == "eval":
avail.add(e[1])
elif e[0] == "def":
last[e[1]] = e[2]
avail = {f for f in avail if e[1] not in (f[1], f[2])}
live, busy = set(), set()
exprs = ANALYSES["very-busy-expressions"](prog).universe
for e in reversed(events):
if e[0] == "enter":
assert live <= IN["live-variables"][e[1]]
if outcome == "ret":
assert IN["very-busy-expressions"][e[1]] <= busy
elif e[0] == "use":
live.add(e[1])
elif e[0] == "eval":
busy.add(e[1])
elif e[0] == "def":
live.discard(e[1])
busy -= {f for f in exprs if e[1] in (f[1], f[2])}
# --------------------------------------------------------------- the tests
def show_set(v):
out = []
for e in v:
if isinstance(e, str):
out.append(e)
elif isinstance(e[1], int):
out.append("%s%d" % e)
else:
out.append("%s %s %s" % (e[1], e[0], e[2]))
return sorted(out)
def test_running_example() -> None:
prog = parse(EX)
IN, OUT, st = solve(prog, live_variables(prog))
assert show_set(IN["entry"]) == ["n", "x"]
assert show_set(OUT["body"]) == ["a", "i", "n", "s", "x"]
assert show_set(IN["done"]) == ["s"]
assert st == {"transfers": 11, "meets": 13, "changes": 11, "max_changes": 3}
IN, OUT, st = solve(prog, reaching_definitions(prog))
assert show_set(IN["head"]) == ["body0", "body1", "entry0", "entry1", "head0", "next0", "odd0"]
assert show_set(OUT["next"]) == ["body0", "body1", "entry1", "head0", "next0", "odd0"]
assert st["transfers"] == 11
IN, OUT, st = solve(prog, available_expressions(prog))
assert show_set(IN["head"]) == []
assert show_set(IN["next"]) == ["i & 1", "i < n", "x * 2"]
assert show_set(IN["done"]) == ["i < n"]
assert st["transfers"] == 6
IN, OUT, st = solve(prog, very_busy_expressions(prog))
assert show_set(IN["body"]) == ["i & 1", "i + 1", "x * 2"]
assert show_set(OUT["entry"]) == ["i < n"]
assert show_set(OUT["head"]) == []
assert st["transfers"] == 6
def test_constant_propagation_is_not_distributive() -> None:
prog = parse(DIAMOND)
an = constant_propagation(prog)
IN, OUT, _ = solve(prog, an)
z = an.index["z"]
assert IN["join"][an.index["x"]] == NAC
assert OUT["join"][z] == NAC
assert mop(prog, an, inclusive=True)["join"][z] == 5
left, right = OUT["left"], OUT["right"]
assert an.transfer("join", left)[z] == 5 and an.transfer("join", right)[z] == 5
assert an.meet(an.transfer("join", left), an.transfer("join", right))[z] == 5
assert an.transfer("join", an.meet(left, right))[z] == NAC
def test_genkill_composition_and_distributivity() -> None:
rng = random.Random(7)
for _ in range(40):
prog = random_program(rng, 4, rng.randint(2, 7), acyclic=rng.random() < 0.5)
for kind in GENKILL:
an = ANALYSES[kind](prog)
universe = sorted(an.universe, key=repr)
for label, b in prog.blocks.items():
x = frozenset(e for e in universe if rng.random() < 0.5)
y = frozenset(e for e in universe if rng.random() < 0.5)
items = [(i, ins) for i, ins in enumerate(b.instrs)] + [(len(b.instrs), None)]
if not an.forward:
items.reverse()
v = x
for i, ins in items:
g, k = an.step(label, i, ins)
v = frozenset(g) | (v - frozenset(k))
assert an.transfer(label, x) == v
assert an.transfer(label, an.meet(x, y)) == an.meet(an.transfer(label, x), an.transfer(label, y))
def acyclic_cases(seed, count):
"""MFP against MOP on random acyclic programs. Gen-kill problems must
agree exactly; constant propagation must be below MOP. Returns the
number of blocks where constant propagation is strictly below MOP."""
rng = random.Random(seed)
strict = 0
for _ in range(count):
prog = random_program(rng, 4, rng.randint(2, 8), acyclic=True)
for kind in GENKILL:
an = ANALYSES[kind](prog)
IN, OUT, _ = solve(prog, an)
mfp, mfp2 = (IN, OUT) if an.forward else (OUT, IN)
assert mfp == mop(prog, an)
assert mfp2 == mop(prog, an, inclusive=True)
assert mfp == by_meaning(prog, kind)
an = constant_propagation(prog)
IN, OUT, _ = solve(prog, an)
m, m2 = mop(prog, an), mop(prog, an, inclusive=True)
for n in prog.blocks:
assert an.leq(IN[n], m[n]) and an.leq(OUT[n], m2[n])
strict += OUT[n] != m2[n]
return strict
def test_acyclic_mfp_equals_mop() -> None:
# 400 programs; constant propagation is strictly below MOP at 19 blocks.
assert acyclic_cases(2024, 400) == 19
def test_constant_propagation_below_mop_on_diamonds() -> None:
rng = random.Random(99)
strict = 0
for _ in range(100):
a, b = rng.randint(0, 4), rng.randint(0, 4)
text = DIAMOND.replace("x = 2", "x = A").replace("y = 3", "y = B")
text = text.replace("x = 3", "x = B").replace("y = 2", "y = A")
prog = parse(text.replace("A", str(a)).replace("B", str(b)))
an = constant_propagation(prog)
IN, OUT, _ = solve(prog, an)
mo = mop(prog, an, inclusive=True)["join"]
assert an.leq(OUT["join"], mo)
assert mo[an.index["z"]] == a + b
strict += OUT["join"] != mo
assert (OUT["join"][an.index["z"]] == NAC) == (a != b)
assert (OUT["join"] != mo) == (a != b)
assert strict == 85
def test_cyclic_fixed_point_bounds_and_runs() -> None:
rng = random.Random(31337)
for _ in range(300):
prog = random_program(rng, 4, rng.randint(3, 8), acyclic=False)
nblocks = len(prog.blocks)
nedges = len(toyir.edges(prog))
results = {}
for kind, mk in ANALYSES.items():
an = mk(prog)
IN, OUT, st = solve(prog, an)
check_fixed_point(prog, an, IN, OUT)
assert round_robin(prog, an) == (IN if an.forward else OUT)
assert st["max_changes"] <= an.height
assert st["transfers"] <= nblocks + st["changes"]
assert st["meets"] <= (an.height + 1) * nedges
results[kind] = (IN, OUT)
check_runs(prog, results, rng)
def test_exits_and_boundary() -> None:
prog = parse(EX)
assert exits(prog) == ["done"]
an = available_expressions(prog)
assert an.boundary == frozenset() and an.top == an.universe
IN, _, _ = solve(prog, an)
assert IN["entry"] == frozenset()
History
Kildall (1973) described one iterative algorithm for a whole family of global optimization problems, parameterized by a lattice and the functions of the nodes. It starts from the top element and lowers values until they are stable, and Kildall showed that it gives the meet over all paths when the functions are distributive. Kam and Ullman (1976) studied round-robin iteration in depth-first order and bounded the number of sweeps for the bit-vector problems. Kam and Ullman (1977) defined monotone frameworks, proved that Kildall's algorithm computes the maximal fixed point, which is below the meet over all paths and can differ from it, and showed that no algorithm computes the meet over all paths for every monotone framework. Textbooks give both the round-robin and the worklist forms (Aho, Lam, Sethi and Ullman; Cooper and Torczon; Nielson, Nielson and Hankin, who use the join convention and least fixed points).
References
- 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 whole paper (the iterative algorithm from the top element, and its result for distributive functions)
- John B. Kam and Jeffrey D. Ullman, Monotone data flow analysis frameworks, Acta Informatica 7(3), 1977, 305-317, the whole paper (the maximal fixed point of a monotone framework, the proof that Kildall's algorithm computes it, and the proof that it is below the meet over all paths)
- John B. Kam and Jeffrey D. Ullman, Global data flow analysis and iterative algorithms, Journal of the ACM 23(1), 1976, 158-171, the whole paper (the analysis of round-robin iteration in depth-first order, which covers the bit-vector problems)
- Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Pearson Addison-Wesley, 2007, Section 9.3.3 (The Iterative Algorithm for General Frameworks), Section 9.3.4 (Meaning of a Data-Flow Solution) and Section 9.6.7 (Speed of Convergence of Iterative Data-Flow Algorithms)
- Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 9 (Data-Flow Analysis), Section 9.2 (Iterative Data-Flow Analysis)
- Flemming Nielson, Hanne Riis Nielson and Chris Hankin, Principles of Program Analysis, Springer, 1999, Section 2.4 (Equation Solving, the worklist algorithm for the MFP solution), in the join convention where the same solution is the least one
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 5353DC Edit this page History Report an error Markdown