Algorithmcore
Dominance frontier computation
Also called Cytron dominance frontier algorithm.
Computes all dominance frontiers in time linear in their total size by a bottom-up walk of the dominator tree.
- Time
- Θ(n + m + D) worst · average · best
- Space
- Θ(n + D) extra
- Where
- D = the total size of all dominance frontiers; m = the number of edges; n = the number of reachable nodes
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Dominance frontier computation finds the dominance frontier of every node of a flow graph, given its dominator tree. The method of Cytron, Ferrante, Rosen, Wegman and Zadeck (1991) visits the tree bottom up. The frontier of a node is made from the edges that leave it directly, plus the frontiers of its children that also escape the node itself. The cost is linear in the size of the graph plus the total size of the frontiers, which is the size of the output. Cooper, Harvey and Kennedy later gave a shorter method that walks up the tree from the predecessors of each join node. This page covers both. The frontiers tell Cytron SSA construction where to put phi-functions.
In plain words
A block "owns" every block it dominates: control cannot get there without passing through it. The frontier of a block is the set of blocks just outside its land, the first blocks that can also be reached by a road that skips it. To find them all, start from the deepest blocks of the dominator tree. Each block looks at its own outgoing edges and keeps the targets it does not own. Then it looks at what its children reported, and keeps the blocks it does not own either. A parent never has to look below its children, because they already did that work. The other method starts at each meeting point and climbs the tree from each incoming edge, marking every block it passes, until it reaches the block that owns the meeting point.
The problem
The input is a flow graph with root and the immediate dominator of each node that reaches. Nodes that does not reach are ignored. The output is, for each reachable node ,
Often the next step is the iterated frontier of a set of blocks, which is where the phi-functions for one variable go.
The two methods rest on two forms of the definition, both proved on the dominance frontier page and in the proof file. The bottom-up form is
Cytron et al. call the first part and the parts that come from the children . The edge form says that if and only if lies on the tree path from some predecessor of up to , with itself excluded.
The algorithm
DOMINANCE-FRONTIERS(G, r, idom)- 1
for each node x, in a postorder of the dominator tree do - 2
DF[x] <- empty set - 3
for each successor y of x do - 4
if idom(y) != x then add y to DF[x] - 5
for each child z of x in the dominator tree do - 6
for each y in DF[z] do - 7
if idom(y) != x then add y to DF[x] - 8
return DF DOMINANCE-FRONTIERS-WALK(G, r, idom)- 9
for each node y with two or more predecessors, and for y = r do - 10
for each predecessor p of y do - 11
runner <- p - 12
while runner != idom(y) and y is not in DF[runner] do - 13
add y to DF[runner] - 14
runner <- idom(runner)
The first routine is Cytron's. The postorder of line L1 makes sure that the children of are finished before , so line L6 reads their final frontiers. Line L4 adds and line L7 adds of each child. The test in both lines is the same: a node whose immediate dominator is is strictly dominated by , and every other candidate is not.
The second routine is the walk of Cooper, Harvey and Kennedy. A node with one predecessor has , so its walk would be empty, and line L9 skips it. The root is the one exception: it can have a single predecessor through a back edge, and nothing strictly dominates it, so is None and the walk goes all the way up. The second test of line L12 is an early stop. If is already in , an earlier walk for the same passed here and went on up to , so the rest of the path is done.
In the implementation, the immediate dominators come from the Cooper-Harvey-Kennedy iteration, with idom[root] = None. The routine program_frontiers runs the first method on the blocks of a toy IR program, and iterated_dominance_frontier computes with a worklist.
Example
Take the program from the control flow graph page that adds the odd numbers below . Its edges are B1 → B2, B2 → B3, B2 → B6, B3 → B4, B3 → B5, B4 → B5 and B5 → B2. The dominator tree has B1 → B2, B2 → B3, B2 → B6, B3 → B4 and B3 → B5. A postorder of the tree is B4, B5, B3, B6, B2, B1.
| step | x | local part (L3, L4) | from children (L5 to L7) | DF[x] |
|---|---|---|---|---|
| 1 | B4 | B5: idom is B3, keep | none | {B5} |
| 2 | B5 | B2: idom is B1, keep | none | {B2} |
| 3 | B3 | B4, B5: idom is B3, drop | B5 from B4: idom is B3, drop. B2 from B5: keep | {B2} |
| 4 | B6 | no successors | none | ∅ |
| 5 | B2 | B3, B6: idom is B2, drop | B2 from B3: idom is B1, keep | {B2} |
| 6 | B1 | B2: idom is B1, drop | B2 from B2: idom is B1, drop | ∅ |
Step 3 shows why the test matters. B4 reports B5, but B3 dominates B5, so for B3 that is not a frontier node. Step 5 shows a node in its own frontier: the back edge B5 → B2 escapes the land of B2 by entering B2 itself, which B2 does not strictly dominate.
The walk gives the same sets. The join nodes are B2, with predecessors B1 and B5, and B5, with predecessors B3 and B4. For B2, the walk from B1 stops at once, since B1 = idom(B2). The walk from B5 adds B2 to the frontiers of B5, B3 and B2, and stops at B1. For B5, the walk from B3 stops at once, and the walk from B4 adds B5 to and stops at B3.
The variable s is assigned in B1 and B4. The worklist for takes B4 and finds B5, then takes B5 and finds B2, then takes B2 and finds B2 again. The result is {B2, B5}, the two blocks that get a phi-function for s.
Correctness
The proof file proves four facts. First, for an edge with , dominates : a path to that avoids it, plus the edge, would reach without it. So the nodes that dominate form a chain that contains , and the ones that do not strictly dominate are those below . This gives the edge form. Second, splitting the walk from at gives the bottom-up form: either , which is the local part, or the walk passes the child of first, which puts in . Third, the postorder of line L1 makes the bottom-up form an induction, so the first routine is correct, and the walk adds to exactly the nodes of the edge form, so the second one is correct too. The early stop skips only nodes that already hold . Fourth, the worklist for returns the least set that contains and is closed under .
Proof: Both passes compute the dominance frontiers, and the worklist computes the iterated frontierfull
Setting. is a directed graph with root , and is the set of nodes that reaches. Only nodes of and edges between them take part: an edge from a node outside lies on no path from and changes no dominance relation, and the code never looks at such nodes. means that every path from to contains , and means and . The input is correct: is None, and for , is the strict dominator of that every other strict dominator of dominates. (The Cooper-Harvey-Kennedy page proves this for the routine used.) is the dominator tree, with parent . We use one standard fact: the dominators of are exactly the ancestors of in , included. So the dominators of form a chain, and if and only if is a proper ancestor of .
The target is . For an edge , let be the set of nodes on the tree path from up to, but not including, . If , the path goes up to and includes it.
Lemma 1. Let with and . Then .
Proof. Let , so . Suppose some path from to avoids . Then followed by the edge is a path from to . Its nodes are those of and , and none of them is . This contradicts .
So is an ancestor of in , and is a well defined part of the path from to the root.
Lemma 2 (the edge form). if and only if for some edge .
Proof. Fix an edge . The nodes with are the ancestors of , which form the path from up to .
If , no node strictly dominates , since a strict dominator of would have to lie on the empty path from to . So and not holds for all .
If , let . By Lemma 1, . Take . Both and are on the chain , so one is an ancestor of the other. The strict dominators of are the ancestors of , included. So if and only if is or above . Hence the with not are exactly the nodes of below , which is .
Taking the union over all edges into gives the claim.
Lemma 3 (the bottom-up split). For every node ,
(For the test is true, since is None.)
Proof. () Let . By Lemma 2 there is an edge with . Then , because excludes .
- If , then is a successor of with , so is in the first set.
- If , then is a proper ancestor of . Let be the child of on the tree path from down to . The node is between and , so it is below , and is below (or ). So , and by Lemma 2, . With , is in the second set.
() Let be a successor of with . If , then since that path runs from to the root. Otherwise, by Lemma 1 with , is an ancestor of , and it is not . So and by Lemma 2.
Let be a child of and with . By Lemma 2 there is an edge with . If , the path from to the root contains and so contains its parent , and . Otherwise is a proper ancestor of , so it is or above . It is not , so it is above , and lies on the path from up to with excluded. Hence and .
Theorem 1 (the bottom-up pass, lines L1 to L8). When line L8 returns, for every .
Proof. Line L1 visits the nodes in a postorder of , so every child of is finished before starts. By induction on this order, for each child when is visited. Lines L3 and L4 add the first set of Lemma 3, and lines L5 to L7 add the second set, reading the finished . Nothing else is added. By Lemma 3 the result is . Every node of is in and is visited once.
Theorem 2 (the walk, lines L9 to L14). When the walk ends, for every .
Proof. First take the walk without the early stop, that is, with the test y not in DF[runner] removed from line L12. For the edge , lines L11 to L14 start at and move to the parent until they reach , or until they pass the root when (then is None, and the parent of the root is None too). By Lemma 1 the walk does reach , so it stops, and the nodes it adds to are exactly . Line L9 skips a node with one predecessor . For such a node every path from to ends with the edge , so , and the strict dominators of are and the dominators of , which makes and . So skipping it loses nothing. By Lemma 2, the union over all edges is .
Now the early stop. The walks for one node run one after the other, before the walks for any other node. Claim: whenever during the walks for , every node on the tree path from up to , with excluded, also has in its set. This holds before the first walk for , when no set holds . A walk adds to a sequence of nodes going up the tree. It stops either at , so the claim holds for all , or at a node that already holds , and then the claim for gives the rest of the path. So the early stop only skips nodes that already hold , and the sets at the end are the same as without it.
Lemma 4 (the iterated frontier). Let be the limit of , . The worklist routine returns .
Proof. Each , by induction: , and if then . The sets lie in the finite set , so the sequence stops at some with .
Let be the returned set. Every node put on the work list is in , and is put there once.
() A node enters as a member of for a node taken from the list. By induction on the order of the steps, , so . A node that enters the list is then in , which keeps the induction going.
() At the end the list is empty, so every node of was taken from it and its frontier was added to . So . Then , and if then . So .
Running time. Let , the number of edges inside , and . In the bottom-up pass, each node is visited once (L1, L2), each edge is looked at once (L3, L4), and each element of is looked at once, at the parent of (L6, L7). With a set that tests and adds in , for example a marker array stamped with , the time is . In the walk, each pass through line L13 adds a new pair , because of the early stop, so there are at most such passes. Each predecessor of costs more for the test that ends its walk. So the time is . The worklist for takes each node at most once and reads its frontier once, so it takes time.
Complexity
Let be the number of reachable nodes, the number of edges and .
- The bottom-up pass. Each node is visited once, each edge is tested once at line L4, and each element of is tested once, at the parent of . With a set that tests and adds in constant time, the time is .
- The walk. Because of the early stop, every pass through line L13 adds a new pair, so there are at most of them. Each predecessor costs more to stop its walk. The time is . Without the early stop, two walks for the same can climb the same part of the tree, and the cost grows with the in-degree of times its number of frontier entries.
- Space. The frontiers take and the tree takes .
itself can be . For nested repeat-until loops the graph has nodes and edges, and ; the dominance frontier page works this out. On real programs Cytron et al. found to grow about linearly with . Sreedhar and Gao avoid the quadratic case: their DJ-graph method finds in time for each set , without computing .
Properties
- Output sensitive. The time is linear in the input plus the output, so neither method can be beaten by more than a constant factor when all frontiers are wanted.
- Needs only the tree and the edges. Both methods read the immediate dominators and the successor or predecessor lists, nothing else.
- Works on any flow graph. Reducible or not, with or without edges into the root.
- Local to join nodes. Only nodes with two or more predecessors (and the root) appear in a frontier, so the walk does no work for the other nodes.
Variants and improvements
- Post-dominance frontiers. Run the same code on the reverse graph, with the post-dominator tree. The result gives control dependence: is control dependent on if is in the post-dominance frontier of .
- Iterated frontiers on demand. Placing phi-functions needs only for one set at a time. Sreedhar and Gao's DJ-graphs, and the merge sets of chapter 4 of the SSA book, compute it directly in linear time per set.
- Bit vectors. For small graphs, each can be a bit vector, and line L7 becomes a masked union.
- No frontiers at all. Braun SSA construction builds SSA form with no dominance information.
When to use it
Use the walk when the dominator tree comes from the Cooper-Harvey-Kennedy or Lengauer-Tarjan algorithm and the frontiers are needed for many variables. It is the shortest code and is easy to get right. Use the bottom-up pass when the tree is already walked in postorder for other reasons. If the graph is large and has deep nests of loops, so that may grow quadratically, compute per variable instead.
Pitfalls
- Edges into the root. If the root has a predecessor, it is in some frontiers. Treat as None, and do not skip the root in line L9 just because it has one predecessor. The toy IR avoids the case by giving the entry no predecessors.
- Unreachable blocks. A block that the root does not reach has no immediate dominator. Delete it or skip it, and skip its edges.
- Strict versus plain dominance. A node can be in its own frontier. Testing " dominates " in place of " strictly dominates " loses the loop headers, and the loops then get no phi-functions.
- Stale frontiers. Splitting an edge or deleting a block changes the frontiers. Recompute them, or update them with care, after the graph changes.
- Parallel edges. If a block has two edges to , the walk runs twice from it. The early stop makes this harmless.
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/dominance-frontier-computation/. The authors are listed in prov/VKF111.jsonl.
"""Dominance frontiers of a flow graph.
dominance_frontiers is the bottom-up pass of Cytron, Ferrante, Rosen, Wegman
and Zadeck over the dominator tree (lines L1 to L8 of the page).
dominance_frontiers_walk is the walk of Cooper, Harvey and Kennedy from each
predecessor of a node up to its immediate dominator (lines L9 to L14).
A graph is a dict from node to its list of successors, and a root. Only the
nodes that the root reaches take part. The immediate dominators come from the
iterative algorithm of Cooper, Harvey and Kennedy; idom[root] is None.
"""
import toyir
def program_graph(prog):
"""The successor lists and the entry of a toy IR program."""
return {label: toyir.succs(prog, label) for label in prog.blocks}, prog.entry
def postorder(succ, root):
"""The nodes that root reaches, in postorder of an iterative DFS."""
seen = {root}
out = []
stack = [(root, iter(succ[root]))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
stack.pop()
out.append(v)
elif w not in seen:
seen.add(w)
stack.append((w, iter(succ[w])))
return out
def immediate_dominators(succ, root):
"""Dict from each node that root reaches to its immediate dominator."""
order = postorder(succ, root)
po = {v: i for i, v in enumerate(order)}
pred = {v: [] for v in order}
for v in order:
for w in succ[v]:
pred[w].append(v)
doms = {root: root}
def intersect(a, b):
while a != b:
while po[a] < po[b]:
a = doms[a]
while po[b] < po[a]:
b = doms[b]
return a
changed = True
while changed:
changed = False
for b in reversed(order):
if b == root:
continue
new = None
for p in pred[b]:
if p in doms:
new = p if new is None else intersect(p, new)
if doms.get(b) != new:
doms[b] = new
changed = True
idom = dict(doms)
idom[root] = None
return idom
def tree_children(idom):
children = {v: [] for v in idom}
for v, d in idom.items():
if d is not None:
children[d].append(v)
return children
def _tree_postorder(children, root):
out = []
stack = [(root, False)]
while stack:
v, done = stack.pop()
if done:
out.append(v)
else:
stack.append((v, True))
for c in children[v]:
stack.append((c, False))
return out
def dominance_frontiers(succ, root, idom=None):
"""Cytron's bottom-up pass. Returns a dict from node to its frontier."""
if idom is None:
idom = immediate_dominators(succ, root)
children = tree_children(idom)
df = {}
for x in _tree_postorder(children, root): # @line L1
s = set() # @line L2
for y in succ[x]: # @line L3
if idom[y] != x: # @line L4
s.add(y)
for z in children[x]: # @line L5
for y in df[z]: # @line L6
if idom[y] != x: # @line L7
s.add(y)
df[x] = s
return df # @line L8
def dominance_frontiers_walk(succ, root, idom=None):
"""The walk of Cooper, Harvey and Kennedy, with the early stop."""
if idom is None:
idom = immediate_dominators(succ, root)
pred = {v: [] for v in idom}
for v in idom:
for w in succ[v]:
pred[w].append(v)
df = {v: set() for v in idom}
for y in idom: # @line L9
if len(pred[y]) < 2 and y != root:
continue
for p in pred[y]: # @line L10
runner = p # @line L11
while runner != idom[y] and y not in df[runner]: # @line L12
df[runner].add(y) # @line L13
runner = idom[runner] # @line L14
return df
def iterated_dominance_frontier(df, nodes):
"""DF+ of a set of nodes, by a worklist over the frontiers."""
result = set()
seen = set(nodes)
work = list(nodes)
while work:
x = work.pop()
for y in df[x]:
if y not in result:
result.add(y)
if y not in seen:
seen.add(y)
work.append(y)
return result
def program_frontiers(prog):
"""The dominance frontiers of the blocks of a toy IR program."""
succ, root = program_graph(prog)
return dominance_frontiers(succ, root)
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_dominance_frontier_computation.py 209 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dominance-frontier-computation/. The authors are listed in prov/VKF111.jsonl.
import random
import toyir
from dominance_frontier_computation import (
dominance_frontiers,
dominance_frontiers_walk,
immediate_dominators,
iterated_dominance_frontier,
program_frontiers,
program_graph,
)
ODD_SUM = """
# params: 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
"""
# ------------------------------------------------------------ brute force
def _reach(succ, root, removed=None):
if root == removed:
return set()
seen = {root}
stack = [root]
while stack:
v = stack.pop()
for w in succ[v]:
if w != removed and w not in seen:
seen.add(w)
stack.append(w)
return seen
def brute_dominators(succ, root):
"""D[v] = the set of dominators of v: d dominates v if removing d cuts v off."""
nodes = _reach(succ, root)
dom = {v: set() for v in nodes}
for d in nodes:
left = _reach(succ, root, d)
for v in nodes:
if v not in left:
dom[v].add(d)
return dom
def brute_frontiers(succ, root):
"""DF by the definition: x dom p for an edge (p, y), and not x sdom y."""
dom = brute_dominators(succ, root)
df = {v: set() for v in dom}
for p in dom:
for y in succ[p]:
for x in dom[p]:
if not (x in dom[y] and x != y):
df[x].add(y)
return df
def brute_idf(df, s):
"""DF+ as the limit of DF_1 = DF(S), DF_(i+1) = DF(S + DF_i)."""
cur = set()
while True:
nxt = set()
for x in set(s) | cur:
nxt |= df[x]
if nxt == cur:
return cur
cur = nxt
def random_graph(rng, n):
succ = {v: [] for v in range(n)}
for _ in range(rng.randint(0, 3 * n)):
a, b = rng.randrange(n), rng.randrange(n)
if b not in succ[a]:
succ[a].append(b)
for v in range(1, n):
if rng.random() < 0.8:
a = rng.randrange(v)
if v not in succ[a]:
succ[a].append(v)
return succ
def ladder(n):
"""n nested repeat-until loops: headers h, latches l, exit e."""
succ = {}
for i in range(1, n + 1):
succ["h%d" % i] = ["h%d" % (i + 1)] if i < n else ["l%d" % n]
succ["l%d" % i] = ["h%d" % i] + (["l%d" % (i - 1)] if i > 1 else ["e"])
succ["e"] = []
return succ
# ------------------------------------------------------------------ tests
def test_page_example():
succ, root = program_graph(toyir.parse(ODD_SUM))
want = {"B1": set(), "B2": {"B2"}, "B3": {"B2"}, "B4": {"B5"}, "B5": {"B2"}, "B6": set()}
assert dominance_frontiers(succ, root) == want
assert dominance_frontiers_walk(succ, root) == want
df = dominance_frontiers(succ, root)
assert iterated_dominance_frontier(df, {"B1", "B4"}) == {"B2", "B5"}
assert iterated_dominance_frontier(df, {"B1", "B5"}) == {"B2"}
def test_idom_matches_brute_force():
rng = random.Random(1)
for _ in range(300):
succ = random_graph(rng, rng.randint(1, 9))
idom = immediate_dominators(succ, 0)
dom = brute_dominators(succ, 0)
assert set(idom) == set(dom)
for v, d in idom.items():
if v == 0:
assert d is None
else:
# the immediate dominator is the strict dominator with the most dominators
strict = dom[v] - {v}
assert d == max(strict, key=lambda u: len(dom[u]))
def test_random_graphs():
rng = random.Random(2)
for _ in range(600):
succ = random_graph(rng, rng.randint(1, 10))
want = brute_frontiers(succ, 0)
assert dominance_frontiers(succ, 0) == want
assert dominance_frontiers_walk(succ, 0) == want
def test_random_programs():
rng = random.Random(3)
for k in range(300):
prog = toyir.random_program(rng, 6, 8, acyclic=(k % 3 == 0))
succ, root = program_graph(prog)
want = brute_frontiers(succ, root)
assert program_frontiers(prog) == want
assert dominance_frontiers_walk(succ, root) == want
def test_iterated_frontier():
rng = random.Random(4)
for _ in range(400):
n = rng.randint(1, 10)
succ = random_graph(rng, n)
df = dominance_frontiers(succ, 0)
nodes = list(df)
s = set(rng.sample(nodes, rng.randint(1, len(nodes))))
got = iterated_dominance_frontier(df, s)
assert got == brute_idf(df, s)
# DF+ is closed: DF(S + DF+) is inside DF+
closed = set()
for x in s | got:
closed |= df[x]
assert closed <= got
def test_quadratic_family():
for n in range(1, 12):
succ = ladder(n)
df = dominance_frontiers(succ, "h1")
assert df == dominance_frontiers_walk(succ, "h1")
assert len(df) == 2 * n + 1
assert sum(len(x) for x in succ.values()) == 3 * n
assert sum(len(x) for x in df.values()) == n * (n + 1)
for i in range(1, n + 1):
want = {"h%d" % j for j in range(1, i + 1)}
assert df["h%d" % i] == want and df["l%d" % i] == want
phis = sum(len(iterated_dominance_frontier(df, {"h1", "l%d" % i})) for i in range(1, n + 1))
assert phis == n * (n + 1) // 2
def test_entry_with_predecessors():
# The back edge 2 -> 0 enters the root, which has one predecessor.
succ = {0: [1], 1: [2], 2: [0]}
want = {0: {0}, 1: {0}, 2: {0}}
assert brute_frontiers(succ, 0) == want
assert dominance_frontiers(succ, 0) == want
assert dominance_frontiers_walk(succ, 0) == want
def test_unreachable_nodes_are_ignored():
succ = {0: [1], 1: [], 2: [1]}
df = dominance_frontiers(succ, 0)
assert df == {0: set(), 1: set()}
assert dominance_frontiers_walk(succ, 0) == df
History
Cytron, Ferrante, Rosen, Wegman and Zadeck defined the dominance frontier and gave the bottom-up algorithm in their POPL 1989 paper on computing SSA form, and in full in the 1991 TOPLAS paper, which also used the reverse graph for control dependence. Sreedhar and Gao (1995) showed that the iterated frontier can be found in linear time with DJ-graphs. Cooper, Harvey and Kennedy published the walk from the predecessors with their simple iterative dominator algorithm, at Rice University in 2001, and it became a common choice in textbooks and compilers.
References
- Ron Cytron, Jeanne Ferrante, Barry K. Rosen, Mark N. Wegman and F. Kenneth Zadeck, Efficiently computing static single assignment form and the control dependence graph, ACM Transactions on Programming Languages and Systems 13(4), 1991, pages 451-490, the definition of DF_local and DF_up, the lemmas that give DF from them, the bottom-up algorithm over the dominator tree, and its cost in the size of the frontiers
- Keith D. Cooper, Timothy J. Harvey and Ken Kennedy, A simple, fast dominance algorithm, technical report, Department of Computer Science, Rice University, the dominance frontier algorithm that walks from each predecessor of a join node up to its immediate dominator
- Vugranam C. Sreedhar and Guang R. Gao, A linear time algorithm for placing phi-nodes, Proceedings of the 22nd ACM Symposium on Principles of Programming Languages (POPL), 1995, pages 62-73, DJ-graphs, and the iterated dominance frontier in linear time without computing the frontiers
- Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 19 (Static Single-Assignment Form), the computation of the dominance frontier by DF_local and DF_up
- Fabrice Rastello and Florent Bouchez Tichadou (editors), SSA-based Compiler Design, Springer, 2022, Chapter 3 (Standard Construction and Destruction Algorithms), the computation of dominance frontiers; Chapter 4 (Advanced Construction Algorithms for SSA), DJ-graphs and merge sets
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 VKF111 Edit this page History Report an error Markdown