Algorithmcore
Cooper-Harvey-Kennedy dominance algorithm
Also called simple fast dominance algorithm, iterative dominator algorithm.
Computes immediate dominators by iterating over the nodes in reverse postorder and intersecting paths in the partial dominator tree.
- Solves
- Dominators problem
- Time
- O((d + 2) n (n + m)) worstΘ(n + m) best
- Space
- Θ(n + m) extra
- Where
- d = the largest number of retreating edges on a simple path from the root (for the depth-first order of line L1); m = the number of edges; n = the number of vertices
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
The Cooper-Harvey-Kennedy algorithm solves the dominators problem on a flow graph, usually a control flow graph. It keeps one number per node, the current guess of its immediate dominator, so the guesses form a tree. In each pass it visits the nodes in reverse postorder and sets the guess of a node to the nearest common ancestor, in that tree, of its predecessors. Two fingers that climb the tree by postorder numbers find this ancestor. It repeats passes until one pass changes nothing. On a reducible flow graph this takes at most two passes. The name "iterative dominator algorithm" also covers older methods, such as the iteration over sets of dominators in the style of Allen and Cocke; this page is the version of Cooper, Harvey and Kennedy (2001) with the intersect step.
In plain words
Every block of a program has guards: blocks that each run must pass through before it gets there. The nearest guard is the immediate dominator. The algorithm keeps one guess per block, a pointer to its nearest guard, so the guesses form a tree. It visits the blocks so that a block usually comes after the blocks that lead into it. For each block, it finds where the paths up the tree from the blocks that lead into it meet. Two fingers climb the tree, always moving the deeper one, until they touch. The meeting point is the new guess. A loop can make a guess wrong at first, so the algorithm sweeps again until a sweep changes nothing. On most real programs, two sweeps are enough.
The problem
The input is a directed graph with vertices and edges, given as a list of pairs meaning , and a start vertex . Self-loops and parallel edges are allowed. A vertex dominates if every path from to contains ; is the set of dominators of . The immediate dominator of is the strict dominator of that every other strict dominator of dominates. The output is for every vertex that reaches, and nothing (here ) for and for the unreachable vertices.
The algorithm numbers the reachable vertices in postorder of a depth-first search from , so is the largest number, and visits them in reverse postorder, from the largest number down. An edge is retreating if , that is, if does not come after in the visit order. Every other edge goes forward in that order.
The algorithm
The array holds the guesses. A vertex is defined once it has a guess. Following from a defined vertex gives a path that ends at ; call its vertices the chain of . The proof file shows that always has a larger postorder number than , so the defined vertices form a tree rooted at , and the chain of is the set of its ancestors in this tree. The intended result is that the chain of is exactly .
CHK-DOMINATORS(G, r)- 1
number the vertices that r reaches in postorder of a DFS from r: po[v] - 2
for all vertices b do doms[b] <- Undefined - 3
doms[r] <- r - 4
changed <- true - 5
while changed do - 6
changed <- false - 7
for each vertex b != r that r reaches, in reverse postorder do - 8
new_idom <- the first predecessor p of b with doms[p] != Undefined - 9
for each other predecessor p of b do - 10
if doms[p] != Undefined then new_idom <- INTERSECT(p, new_idom) - 11
if doms[b] != new_idom then - 12
doms[b] <- new_idom; changed <- true - 13
return doms INTERSECT(b1, b2)- 14
finger1 <- b1; finger2 <- b2 - 15
while finger1 != finger2 do - 16
while po[finger1] < po[finger2] do finger1 <- doms[finger1] - 17
while po[finger2] < po[finger1] do finger2 <- doms[finger2] - 18
return finger1
Line L8 always finds a predecessor: the parent of in the DFS tree comes before in reverse postorder, so it is defined. INTERSECT walks the two fingers up the tree of guesses. The finger with the smaller postorder number is the deeper one in that tree, and it moves up until it is no longer below the other. When they meet, they are at the nearest common ancestor of and , whose chain is the intersection of the two chains. So lines L8 to L10 compute the vertex whose chain is the intersection of the chains of all defined predecessors, and line L12 makes the chain of equal to plus that intersection. This is the classic set equation , with each set stored as a path in one tree instead of as a bit vector.
In the implementation, line L1 is an iterative DFS, the predecessors with $doms[p] = $ Undefined are filtered out before line L8, and the vertices that does not reach never get a postorder number and stay Undefined. The function cfg_idom runs the algorithm on the blocks of a toy IR program and returns a map from each block to its immediate dominator.
Example
Take the flow graph with vertices , start , and the edges
The cycle can be entered at (from ) and at (from ), so no vertex of the cycle dominates the other, and the graph is not reducible. Every vertex other than has : is reached by and by , and by and by .
With successors tried in the order listed, the DFS from goes , backs up, and then visits . The postorder is with , and the reverse postorder is . The retreating edges are and .
| pass | vertex | defined predecessors | INTERSECT steps | |
|---|---|---|---|---|
| 1 | none | |||
| 1 | none | |||
| 1 | ( is not yet defined) | none | ||
| 1 | , then | |||
| 1 | , then | |||
| 2 | , then | (changed) | ||
| 3 | all | no change |
After pass 1, the guess for is wrong: when was visited, its predecessor had no guess yet, because the edge is retreating. Pass 2 sees and moves up to . Pass 3 changes nothing, so the algorithm stops after 3 passes with for all . Here the largest number of retreating edges on a simple path from is , on the path , and the proved bound is passes.
On the reducible control flow graph of the odd-sum program on the control flow graph page, with edges , , , , , , , pass 1 already gives the answer , , , , , and pass 2 confirms it. On the 9-vertex example of the Lengauer-Tarjan algorithm, which is not reducible, the algorithm also stops after 2 passes, with the same .
Correctness
The full proof is in the proof file. Its steps:
- The guesses form a tree. When gets a guess, the guess is on the chain of the DFS parent of , so it is a proper DFS ancestor of with a larger postorder number. Hence every chain climbs strictly in postorder and ends at , and a new guess for is never inside the subtree of .
- INTERSECT. A finger never passes the nearest common ancestor of and : a finger at has a postorder number at least that of the other finger, so it does not move. Each move raises a postorder number, so the loops stop, and they stop at .
- Soundness. At all times for every defined . A strict dominator of dominates every predecessor of , and a change at also keeps the property for the vertices below in the tree, because they are DFS descendants of .
- Fixed point. When a pass changes nothing, for all . Walking along a path from that avoids a vertex shows that is in no chain on the path, so . With step 3, , and then .
- Termination. The chains are always subsets of the sets of the plain set iteration run in the same order, and after pass those sets are inside the vertex set of every path from with at most retreating edges. So after pass every chain equals , and pass changes nothing.
Proof: The Cooper-Harvey-Kennedy algorithm computes the immediate dominators in at most d + 2 passesfull
Setting. is a directed graph with start vertex . Let be the set of vertices that reaches. A vertex outside gets no postorder number in line L1, is never visited in line L7 and stays Undefined, so line L10 skips it as a predecessor. An edge from a vertex outside lies on no path from , so it changes no dominator. From here on, all vertices are in and "predecessor" means a predecessor in . is the DFS tree of line L1, its postorder numbering, and the visit order of line L7 is decreasing . is the set of dominators of . The DFS tree is used only through these facts: a proper -ancestor of has a larger than , and the tree path from to contains exactly the -ancestors of .
For a defined vertex , is the set of vertices on . Lemma 1 shows this sequence reaches , where it stops, since .
Lemma 0 (the dominator equation). For , , the intersection over the predecessors of . Also .
Proof. Let with , and let be a predecessor. If then . Otherwise a path from to that avoids , followed by the edge , would avoid , so . Conversely, let be in every . A path from to has at least one edge, since , so its last but one vertex is a predecessor , and the part up to contains . The vertex is a path from to by itself, so .
Lemma 1 (the guesses form a tree). At all times: every defined has defined and a proper -ancestor of , and is a set of -ancestors of . A vertex that is defined stays defined.
Proof. At the start only is defined. Line L12 never writes Undefined. Assume the claim before an update of in line L12. In pass 1 every vertex visited before was given a value when it was visited, by induction along the visit order, and the DFS parent of comes before because . So is defined, line L8 finds a predecessor, and the defined predecessors include . Lemma 2 below, applied to the current tree, shows that the value that lines L8 to L10 compute is a vertex of , and by the claim consists of -ancestors of . So is defined and a proper -ancestor of . After the update, ; the old chain of does not contain , because it consists of -ancestors of , and is not one of them, so it is not changed by the update. For another vertex , either and nothing changes, or is the part from up to just below , which is unchanged, together with the new . Since , is a -ancestor of , and the new consists of -ancestors of , so of .
So following strictly raises until it reaches : the defined vertices form a tree with root and parent array , and is the set of ancestors of in that tree. The vertex of with the smallest is , so the chain determines .
Lemma 2 (INTERSECT). In a tree with root whose parent array is and in which every parent has a larger than its child, INTERSECT stops and returns the nearest common ancestor of and . Moreover .
Proof. The common ancestors of and are . They form the path from up to , which gives the second claim. We show that is always a descendant of (possibly ), and the same for . This holds at the start. Line L16 moves only when . If , then is a descendant of , so , and there is no move. So is a proper descendant of , and its parent is still a descendant of . Line L17 is the same. Each move raises the of one finger, so the inner loops stop. In an outer iteration with the numbers differ, since is one to one, so one of the inner loops moves; hence the outer loop stops too. At the end both fingers are the same vertex , which is an ancestor of and of and a descendant of . Every common ancestor is an ancestor of , so .
The nearest common ancestor is associative, so lines L8 to L10 compute the nearest common ancestor of all defined predecessors of , and . By Lemma 1, the update of line L12, or the decision not to update, gives
Lemma 3 (soundness). At all times, for every defined .
Proof. At the start, . Assume the claim before an update of .
At . Let with . By Lemma 0, for every defined predecessor , so by . And .
Below . Let have , and let . The new chain of is the old part from to together with . If is in the old part, we are done. Otherwise by the claim, and is above in the old chain, so it is in the old and is a proper -ancestor of by Lemma 1. Also is a -ancestor of . Then dominates : if a path from to avoided , it could be continued by the tree path from to , which contains only -descendants of and so not , and this would be a path to that avoids . So by the case above.
The chains of all other vertices do not change.
Theorem 1 (partial correctness). If the loop of line L5 stops, then for every .
Proof. If , there is nothing to show. Otherwise pass 1 sets a value for every vertex, which changes , so the last pass is pass 2 or later, and in it every vertex and every predecessor is defined. The last pass changes nothing, so by , at its end, over all predecessors, for all , and .
Let and suppose . Then there is a path that avoids , and . We show for all . For the chain is . If and , then is not in the intersection over the predecessors of , which include , and , so . If , its chain is . So , a contradiction. Hence , and with Lemma 3, .
Now , so is a strict dominator of , and every strict dominator of lies in , that is, it dominates . This is the definition of .
The set iteration. To bound the passes we compare with the set version of the same loop. Let and for at the start, and let visit the vertices in the same order as CHK, one pass at a time, doing over all predecessors. We run the two side by side, so each step of one is matched by a step of the other at the same vertex. In pass 1, a vertex is Undefined in CHK exactly when it has not been visited yet, which is exactly when its is still . So intersecting over all is the same as intersecting over the defined , since changes no intersection.
- (S1) only shrinks. Each value is the same monotone function of the current , the current is at most the earlier one by induction, and the first values are .
- (S2) . By induction with Lemma 0: .
Lemma 4. At all times, if , then .
Proof. At the start, for , and . Consider an update at that gives . Take . If and , nothing involved has changed. If , the claim is trivial. If , then for every predecessor of , so for every , and . If , then gives , and by (S1), so .
Lemma 5. At all times, for every defined .
Proof. At the start both are at . At an update of : by and the remark on Undefined vertices, . For with : the new chain of is the old part from to , which is in , together with . Since , Lemma 4 gives . And . The other chains do not change.
Lemma 6 (paths). For a path from , let be the number of its edges that are retreating, that is, . If pass has finished, then the vertex set of for every path from to with .
Proof. Let with , and let $k_i = 1 + $ the number of retreating edges among the first edges. We show: by the end of pass , , and by (S1) it stays so. For , at all times. For the step, let ; if there is nothing to show. If is not retreating, comes after in the visit order, so in pass it is visited after was visited (or, for , at a time when ). So when is visited, , and the new . If is retreating, , and in pass the vertex is visited after pass has ended, so the same argument applies.
Theorem 2 (termination). Let be the largest over the simple paths from . The loop of line L5 stops after at most passes.
Proof. A vertex dominates if and only if is on every simple path from to , since every path from to contains a simple one, with a subset of its vertices, obtained by cutting out cycles. If pass runs, then after it Lemma 6 gives the vertex set of each simple path from to , so , and by (S2). By Lemmas 3 and 5, , so every chain is . In pass , by and Lemma 0, each visit computes , so the new value has the same chain as the old one, so it is the same vertex, and nothing changes. The loop stops after pass or earlier. A simple path has at most edges, so .
Corollary (reducible graphs). Call an edge a back edge if dominates , and call reducible if without its back edges has no cycle. If is reducible, the loop stops after at most 2 passes.
Proof. First, every retreating edge is a back edge. For this is clear. Otherwise, in a DFS an edge with goes to a -ancestor of , because tree edges, forward edges and cross edges all go to a smaller . A tree edge is never a back edge, since the tree path from to avoids its proper descendant . So if were not a back edge, the tree path from to and the edge would form a cycle without back edges.
Next, let be a path from to with a retreating edge . Then dominates , so appears in before ; cutting out the part of from that earlier to the after gives a shorter path from to , made of edges of , with a subset of its vertices. Repeating this gives a path with no retreating edge. So is the intersection of the vertex sets of the paths from to with , and by Lemma 6 with , after pass 1. As in Theorem 2, every chain is after pass 1, and pass 2 changes nothing.
The proof of Lemma 6 shows more: on a reducible graph, already at the moment is first visited, so every guess is final when it is set, and in pass 1 every chain is a path of the final dominator tree.
Cost. Line L1 is . In a pass, line L7 visits each vertex once, lines L8 to L10 look at each edge once, and each call of INTERSECT moves each finger along one chain, raising its each time, so it makes at most moves. A pass costs , and with Theorem 2 the total is , which is . On a reducible graph a chain has at most vertices in every pass, where is the height of the dominator tree, so a pass costs .
What is measured and what is proved. Theorems 1 and 2 and the corollary are proved above. The timings in the paper and the pass counts of the seeded experiment on the page are measurements. The tests check the result against dominators computed by the definition (delete a vertex, test reachability) on random graphs and on toy IR control flow graphs, and check the bounds of Theorem 2 and of the corollary against a brute-force count of retreating edges on simple paths.
Complexity
Proved. Line L1 takes time. In one pass, each vertex is visited once and each edge causes at most one call of INTERSECT; each finger move raises a postorder number along one chain, so a call costs at most the sum of two chain lengths, at most . A pass costs . The number of passes is at most , where is the largest number of retreating edges on a simple path from for the DFS of line L1. It is at most the loop connectedness of Kam and Ullman, which counts retreating edges on all cycle-free paths, not only on those from . Since , the total is , which is in the worst case. On a reducible graph every retreating edge is a back edge, so comes before on any path from to , and a simple path from cannot use the edge. So , there are at most 2 passes, and the time is . Georgiadis, Tarjan and Werneck give graph families on which the iterative algorithm is slow. The extra space is for the predecessor lists and for and .
Stated in the paper, not proved here. The technical report quotes a bound of passes from the work of Kam and Ullman. The proof file proves for this version, counting the final pass that changes nothing.
Measured, not proved. Cooper, Harvey and Kennedy timed their code against Lengauer-Tarjan on a 300 MHz Sun Ultra 10, on the control flow graphs of 169 Fortran routines (the largest with 744 blocks). Their algorithm was about 2.5 times faster on average. On random graphs with 30,000 nodes the two were about equal, and on a straight-line graph with 30,000 nodes theirs took about 0.04 s against about 0.4 s. In a seeded experiment for this page, over 20,000 random digraphs with 1 to 8 vertices and up to edges, the largest pass count was 5, the count never exceeded , and it reached on some graphs; no reducible graph needed more than 2 passes.
| graph | passes | time per pass |
|---|---|---|
| reducible | at most 2 | , the height of the dominator tree |
| general | at most | |
| a tree, a path, a star | 2 |
Properties
- Deterministic. The DFS order depends on the order of the successor lists. The number of passes depends on that order; the result does not.
- Non-recursive. The DFS of line L1 uses an explicit stack, and INTERSECT is two loops, so long paths do not overflow the call stack.
- The tree is the output. The array is the dominator tree as a parent array; no separate sets are kept.
- Offline. The whole graph is needed. After an edge change, the old is not in general a valid starting point.
- Guesses are never too high. A guess can be too deep, as for in the example, but the chain of every vertex always contains all its dominators. On a reducible graph each guess is final as soon as it is first set.
Variants and improvements
- Iteration over sets. The older iterative method keeps the set for each vertex, as a bit vector, and repeats until no set changes. Its passes obey the same bound, but it costs bits per vertex and word operations per edge per pass. The dragon book presents dominators this way.
- Post-dominators. Run the algorithm on the reverse graph from the exit, with a reverse postorder of the reverse graph, to get post-dominance.
- Dominance frontiers. The same report gives a short algorithm for dominance frontiers that walks up the tree from the predecessors of each join point, used to place phi-functions in static single assignment form.
- Semidominators plus nearest common ancestors. A hybrid computes the semidominators of the Lengauer-Tarjan algorithm and then finds each immediate dominator with one nearest common ancestor step in the partly built tree, in one pass and without iteration. Georgiadis, Tarjan and Werneck study it under the name SNCA.
- Lengauer-Tarjan. Near-linear in the worst case, with more code. Use it when the graphs are large or adversarial.
When to use it
Use it for the control flow graphs of single procedures. They are small, and most of them are reducible, so the algorithm runs at most two passes over a graph of a few hundred blocks, and its short code is easy to get right. The same code also gives post-dominators and, with a few more lines, dominance frontiers. For very large graphs or for graphs built to be hard, such as heap graphs or generated code with deep irreducible nesting, prefer a near-linear algorithm such as Lengauer-Tarjan.
Pitfalls
- Comparing the wrong numbers. INTERSECT must compare postorder numbers of the same DFS that gives the visit order. Comparing vertex labels or preorder numbers can make a finger skip the meeting point and climb past .
- Visiting in another order. The proof needs every vertex to be visited after its DFS parent in pass 1, so that line L8 finds a defined predecessor whose chain is made of DFS ancestors. Reverse postorder does this. Plain vertex order does not.
- Forgetting . Without line L3 the root is Undefined, line L8 finds nothing for the children of , and INTERSECT has no stopping point.
- Unreachable predecessors. A predecessor that does not reach has no postorder number and stays Undefined; it must be skipped, not used in INTERSECT.
- Post-dominators with the forward order. On the reverse graph, the reverse postorder must come from a DFS of the reverse graph from the exit. The reverse of a forward postorder is not that order, and the pass bound fails.
- Stopping after a fixed number of passes. On a reducible graph pass 1 already gives the answer, but on an irreducible graph it can be wrong, as for in the example. Keep the test on
changedunless the graph is known to be reducible.
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/cooper-harvey-kennedy-dominance/. The authors are listed in prov/0T0R8F.jsonl.
"""The iterative dominator algorithm of Cooper, Harvey and Kennedy.
chk(n, edges, root) returns (idom, passes): idom[v] is the immediate
dominator of v, or -1 for the root and for the vertices that the root does
not reach; passes is the number of passes of the main loop, the last of
which changes nothing. cfg_idom(prog) applies it to a toy IR program.
"""
import toyir
UNDEFINED = -1
def _postorder(n, succ, root):
"""Iterative DFS from root; returns the vertices in postorder."""
seen = [False] * n
seen[root] = True
post = []
stack = [(root, 0)]
while stack:
v, i = stack[-1]
if i < len(succ[v]):
stack[-1] = (v, i + 1)
w = succ[v][i]
if not seen[w]:
seen[w] = True
stack.append((w, 0))
else:
stack.pop()
post.append(v)
return post
def chk(n, edges, root):
if n < 1 or not 0 <= root < n:
raise ValueError("a flow graph needs n >= 1 vertices and a root in range")
succ = [[] for _ in range(n)]
pred = [[] for _ in range(n)]
for a, b in edges:
if not (0 <= a < n and 0 <= b < n):
raise ValueError("edge endpoint out of range")
succ[a].append(b)
pred[b].append(a)
post = _postorder(n, succ, root) # @line L1
po = [-1] * n
for i, v in enumerate(post):
po[v] = i
rpo = post[::-1]
doms = [UNDEFINED] * n # @line L2
doms[root] = root # @line L3
def intersect(b1, b2):
finger1, finger2 = b1, b2 # @line L14
while finger1 != finger2: # @line L15
while po[finger1] < po[finger2]: # @line L16
finger1 = doms[finger1]
while po[finger2] < po[finger1]: # @line L17
finger2 = doms[finger2]
return finger1 # @line L18
changed = True # @line L4
passes = 0
while changed: # @line L5
passes += 1
changed = False # @line L6
for b in rpo[1:]: # @line L7
ps = [p for p in pred[b] if doms[p] != UNDEFINED]
new_idom = ps[0] # @line L8
for p in ps[1:]: # @line L9
new_idom = intersect(p, new_idom) # @line L10
if doms[b] != new_idom: # @line L11
doms[b] = new_idom # @line L12
changed = True
idom = [UNDEFINED] * n # @line L13
for v in range(n):
if v != root and doms[v] != UNDEFINED:
idom[v] = doms[v]
return idom, passes
def chk_idom(n, edges, root):
"""Immediate dominators only; -1 for the root and unreachable vertices."""
return chk(n, edges, root)[0]
def cfg_idom(prog):
"""Immediate dominators of the blocks of a toy IR program, as a dict from
label to label. The entry and the unreachable blocks map to None."""
labels = list(prog.blocks)
index = {lab: i for i, lab in enumerate(labels)}
edges = [(index[a], index[b]) for a, b in toyir.edges(prog)]
idom = chk_idom(len(labels), edges, 0)
return {lab: (labels[idom[i]] if idom[i] != UNDEFINED else None) for i, lab in enumerate(labels)}
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_cooper_harvey_kennedy_dominance.py 239 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cooper-harvey-kennedy-dominance/. The authors are listed in prov/0T0R8F.jsonl.
import random
import pytest
import toyir
from cooper_harvey_kennedy_dominance import _postorder, cfg_idom, chk, chk_idom
# The irreducible example of the page: r, a, b, c, d, e are 0 .. 5.
PAGE = [(0, 1), (0, 2), (1, 3), (2, 4), (2, 5), (3, 4), (4, 3), (4, 5), (5, 4)]
# The example of the Lengauer-Tarjan page.
LT = [(0, 1), (1, 2), (2, 3), (2, 4), (3, 4), (3, 7), (4, 5), (5, 6), (6, 3), (7, 8), (8, 6)]
ODD_SUM = """
B1:
i = 0
s = 0
jump B2
B2:
t1 = i < n
br t1 B3 B6
B3:
t2 = i % 2
br t2 B4 B5
B4:
s = s + i
jump B5
B5:
i = i + 1
jump B2
B6:
ret s
"""
def reach(n, succ, root, banned):
"""The vertices that root reaches without passing through banned."""
if banned == root:
return set()
seen = {root}
stack = [root]
while stack:
v = stack.pop()
for w in succ[v]:
if w != banned and w not in seen:
seen.add(w)
stack.append(w)
return seen
def brute_dom(n, edges, root):
"""dom[v] = the set of dominators of v, by the definition: d dominates v
if v is reachable and deleting d makes v unreachable (or d = v)."""
succ = [[] for _ in range(n)]
for a, b in edges:
succ[a].append(b)
full = reach(n, succ, root, -1)
dom = {v: {v} for v in full}
for d in full:
r = reach(n, succ, root, d)
for v in full:
if v not in r:
dom[v].add(d)
return dom
def brute_idom(n, edges, root):
dom = brute_dom(n, edges, root)
out = [-1] * n
for v, ds in dom.items():
if v != root:
strict = ds - {v}
out[v] = max(strict, key=lambda x: len(dom[x]))
return out
def max_retreating(n, edges, root):
"""The largest number of retreating edges on a simple path from root, for
the DFS order that chk uses. An edge (u, v) is retreating if v does not
come after u in reverse postorder."""
succ = [[] for _ in range(n)]
for a, b in edges:
succ[a].append(b)
post = _postorder(n, succ, root)
po = [-1] * n
for i, v in enumerate(post):
po[v] = i
best = 0
on_path = [False] * n
stack = [(root, 0, 0)]
on_path[root] = True
while stack:
v, i, k = stack[-1]
best = max(best, k)
if i < len(succ[v]):
stack[-1] = (v, i + 1, k)
w = succ[v][i]
if not on_path[w]:
on_path[w] = True
stack.append((w, 0, k + (1 if po[w] >= po[v] else 0)))
else:
on_path[v] = False
stack.pop()
return best
def is_reducible(n, edges, root):
"""Reachable part only: the graph without its back edges (t, h), where h
dominates t, has no cycle."""
dom = brute_dom(n, edges, root)
keep = [(a, b) for a, b in edges if a in dom and b not in dom[a]]
indeg = [0] * n
for _, b in keep:
indeg[b] += 1
ready = [v for v in dom if indeg[v] == 0]
done = 0
while ready:
v = ready.pop()
done += 1
for a, b in keep:
if a == v:
indeg[b] -= 1
if indeg[b] == 0:
ready.append(b)
return done == len(dom)
def test_page_example() -> None:
idom, passes = chk(6, PAGE, 0)
assert idom == [-1, 0, 0, 0, 0, 0]
assert passes == 3
assert max_retreating(6, PAGE, 0) == 2
assert not is_reducible(6, PAGE, 0)
def test_lengauer_tarjan_example() -> None:
assert chk_idom(9, LT, 0) == [-1, 0, 1, 2, 2, 4, 2, 3, 7]
assert chk_idom(9, LT, 0) == brute_idom(9, LT, 0)
def test_odd_sum_program() -> None:
prog = toyir.parse(ODD_SUM)
assert cfg_idom(prog) == {"B1": None, "B2": "B1", "B3": "B2", "B4": "B3", "B5": "B3", "B6": "B2"}
assert toyir.run(prog, [6]) == ("ret", 9)
def test_single_vertex() -> None:
assert chk(1, [], 0) == ([-1], 1)
assert chk_idom(1, [(0, 0)], 0) == [-1]
def test_star_and_diamond() -> None:
n = 8
edges = [(0, v) for v in range(1, n)] + [(3, 4), (4, 5), (7, 1)]
assert chk_idom(n, edges, 0) == [-1] + [0] * (n - 1)
assert chk_idom(4, [(0, 1), (0, 2), (1, 3), (2, 3)], 0) == [-1, 0, 0, 0]
def test_unreachable_and_other_root() -> None:
edges = [(0, 1), (1, 2), (3, 2), (2, 0)]
assert chk_idom(4, edges, 0) == [-1, 0, 1, -1]
assert chk_idom(4, edges, 3) == [2, 0, 3, -1]
def test_self_loops_and_parallel_edges() -> None:
edges = [(0, 1), (0, 1), (1, 1), (1, 2), (2, 2), (2, 1)]
assert chk_idom(3, edges, 0) == [-1, 0, 1]
def test_long_paths() -> None:
n = 20_000
path = [(i, i + 1) for i in range(n - 1)]
assert chk(n, path, 0) == ([-1] + list(range(n - 1)), 2)
idom = chk_idom(n, path + [(i, 0) for i in range(n)], 0)
assert idom == [-1] + list(range(n - 1))
idom = chk_idom(n, path + [(i, i + 2) for i in range(n - 2)], 0)
assert idom == [-1] + [0] * (n - 1)
# The far end has an edge back to every vertex. The answer is the path,
# but each intersect in pass 2 climbs a long chain.
k = 1500
path = [(i, i + 1) for i in range(k - 1)]
idom = chk_idom(k, path + [(k - 1, i) for i in range(1, k - 1)], 0)
assert idom == [-1] + list(range(k - 1))
def test_bad_input() -> None:
with pytest.raises(ValueError):
chk(0, [], 0)
with pytest.raises(ValueError):
chk(2, [(0, 3)], 0)
with pytest.raises(ValueError):
chk(2, [], 2)
def test_random_against_definition() -> None:
rng = random.Random(41)
for _ in range(1500):
n = rng.randint(1, 10)
m = rng.randint(0, 3 * n)
edges = [(rng.randrange(n), rng.randrange(n)) for _ in range(m)]
root = rng.randrange(n)
assert chk_idom(n, edges, root) == brute_idom(n, edges, root)
def test_pass_bounds() -> None:
# Proved on the page: at most d + 2 passes, where d is the largest number
# of retreating edges on a simple path from the root, and at most 2
# passes on a reducible graph.
rng = random.Random(43)
seen_reducible = seen_irreducible = 0
for _ in range(1500):
n = rng.randint(1, 8)
m = rng.randint(0, 3 * n)
edges = [(rng.randrange(n), rng.randrange(n)) for _ in range(m)]
_, passes = chk(n, edges, 0)
assert 1 <= passes <= max_retreating(n, edges, 0) + 2
if is_reducible(n, edges, 0):
seen_reducible += 1
assert passes <= 2
else:
seen_irreducible += 1
assert seen_reducible > 100 and seen_irreducible > 100
def test_toy_ir_cfgs() -> None:
rng = random.Random(47)
for trial in range(300):
prog = toyir.random_program(rng, 4, 8, acyclic=trial % 3 == 0)
labels = list(prog.blocks)
index = {lab: i for i, lab in enumerate(labels)}
edges = [(index[a], index[b]) for a, b in toyir.edges(prog)]
want = brute_idom(len(labels), edges, 0)
got = cfg_idom(prog)
assert got == {lab: (labels[want[i]] if want[i] != -1 else None) for i, lab in enumerate(labels)}
# Every block is reachable, so only the entry has no idom.
assert [lab for lab in labels if got[lab] is None] == [labels[0]]
History
Prosser introduced dominators in 1959, and Lowry and Medlock used them in 1969 for loop optimization in the FORTRAN H compiler. Allen's 1970 paper on control flow analysis and the 1972 IBM report of Allen and Cocke (RC 3923) treated dominators with the other flow graph facts; Purdom and Moore gave another early method. Computing by iteration over sets became the textbook method, and Kam and Ullman (1976) bounded the number of passes of such iterations by the loop connectedness. Lengauer and Tarjan (1979) gave the near-linear algorithm. Cooper, Harvey and Kennedy, in a Rice University report of 2001, kept the iteration but stored all the sets in one tree and intersected them with the two-finger walk; their timing study made the case that this simple algorithm is fast on real control flow graphs. Georgiadis, Tarjan and Werneck (2006) compared it with several versions of Lengauer-Tarjan on many graph families.
References
- Keith D. Cooper, Timothy J. Harvey and Ken Kennedy, A simple, fast dominance algorithm, technical report, Department of Computer Science, Rice University, the iterative algorithm with the doms array and the intersect routine (Figure 3), the pass bound taken from Kam and Ullman, the timing study against Lengauer-Tarjan, and the dominance frontier algorithm built on the same tree
- Loukas Georgiadis, Robert E. Tarjan and Renato F. Werneck, Finding dominators in practice, Journal of Graph Algorithms and Applications 10(1) (2006), 69-94, the iterative algorithm of Cooper, Harvey and Kennedy among the implementations compared, its O(mn^2) worst-case bound, and the graph families on which it is slow
- Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Section 9.6.1 (dominators, found as a data-flow problem by iteration over sets) and Section 9.6.2 (depth-first ordering)
- Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 9 (Data-Flow Analysis), dominance, the iterative computation and the dominator tree
- Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Chapter 7 (Control-Flow Analysis), the computation of dominators and immediate dominators
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 0T0R8F Edit this page History Report an error Markdown