Algorithm Search⌘K

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.

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
Properties
deterministicofflineiterative

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 GG with vertices 0,…,n−10, \ldots, n - 1 and mm edges, given as a list of pairs (a,b)(a, b) meaning a→ba \to b, and a start vertex rr. Self-loops and parallel edges are allowed. A vertex xx dominates vv if every path from rr to vv contains xx; D(v)D(v) is the set of dominators of vv. The immediate dominator idom(v)\mathrm{idom}(v) of v≠rv \ne r is the strict dominator of vv that every other strict dominator of vv dominates. The output is idom(v)\mathrm{idom}(v) for every vertex v≠rv \ne r that rr reaches, and nothing (here −1-1) for rr and for the unreachable vertices.

The algorithm numbers the reachable vertices in postorder of a depth-first search from rr, so po(r)po(r) is the largest number, and visits them in reverse postorder, from the largest number down. An edge (u,v)(u, v) is retreating if po(v)≥po(u)po(v) \ge po(u), that is, if vv does not come after uu in the visit order. Every other edge goes forward in that order.

The algorithm

The array domsdoms holds the guesses. A vertex is defined once it has a guess. Following domsdoms from a defined vertex yy gives a path y,doms[y],doms[doms[y]],…y, doms[y], doms[doms[y]], \ldots that ends at rr; call its vertices the chain of yy. The proof file shows that doms[y]doms[y] always has a larger postorder number than yy, so the defined vertices form a tree rooted at rr, and the chain of yy is the set of its ancestors in this tree. The intended result is that the chain of yy is exactly D(y)D(y).

  1. CHK-DOMINATORS(G, r)
  2. 1number the vertices that r reaches in postorder of a DFS from r: po[v]
  3. 2for all vertices b do doms[b] <- Undefined
  4. 3doms[r] <- r
  5. 4changed <- true
  6. 5while changed do
  7. 6changed <- false
  8. 7for each vertex b != r that r reaches, in reverse postorder do
  9. 8new_idom <- the first predecessor p of b with doms[p] != Undefined
  10. 9for each other predecessor p of b do
  11. 10if doms[p] != Undefined then new_idom <- INTERSECT(p, new_idom)
  12. 11if doms[b] != new_idom then
  13. 12doms[b] <- new_idom; changed <- true
  14. 13return doms
  15. INTERSECT(b1, b2)
  16. 14finger1 <- b1; finger2 <- b2
  17. 15while finger1 != finger2 do
  18. 16while po[finger1] < po[finger2] do finger1 <- doms[finger1]
  19. 17while po[finger2] < po[finger1] do finger2 <- doms[finger2]
  20. 18return finger1

Line L8 always finds a predecessor: the parent of bb in the DFS tree comes before bb 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 b1b_1 and b2b_2, 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 bb equal to {b}\{b\} plus that intersection. This is the classic set equation D(b)={b}∪⋂pD(p)D(b) = \{b\} \cup \bigcap_{p} D(p), 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 rr 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 r,a,b,c,d,er, a, b, c, d, e, start rr, and the edges

r→a,  r→b,  a→c,  b→d,  b→e,  c→d,  d→c,  d→e,  e→d.r \to a,\; r \to b,\; a \to c,\; b \to d,\; b \to e,\; c \to d,\; d \to c,\; d \to e,\; e \to d.

The cycle c→d→cc \to d \to c can be entered at cc (from aa) and at dd (from bb), so no vertex of the cycle dominates the other, and the graph is not reducible. Every vertex other than rr has idom=r\mathrm{idom} = r: cc is reached by r,a,cr, a, c and by r,b,d,cr, b, d, c, and dd by r,b,dr, b, d and by r,a,c,dr, a, c, d.

With successors tried in the order listed, the DFS from rr goes r,a,c,d,er, a, c, d, e, backs up, and then visits bb. The postorder is e,d,c,a,b,re, d, c, a, b, r with po=0,…,5po = 0, \ldots, 5, and the reverse postorder is r,b,a,c,d,er, b, a, c, d, e. The retreating edges are d→cd \to c and e→de \to d.

pass vertex defined predecessors INTERSECT steps domsdoms
1 bb rr none rr
1 aa rr none rr
1 cc aa (dd is not yet defined) none aa
1 dd b,cb, c c→a→rc \to a \to r, then b→rb \to r rr
1 ee b,db, d d→rd \to r, then b→rb \to r rr
2 cc a,da, d d→rd \to r, then a→ra \to r rr (changed)
3 all no change

After pass 1, the guess for cc is wrong: when cc was visited, its predecessor dd had no guess yet, because the edge d→cd \to c is retreating. Pass 2 sees dd and moves cc up to rr. Pass 3 changes nothing, so the algorithm stops after 3 passes with idom(v)=r\mathrm{idom}(v) = r for all v≠rv \ne r. Here the largest number of retreating edges on a simple path from rr is d=2d = 2, on the path r,b,e,d,cr, b, e, d, c, and the proved bound is d+2=4d + 2 = 4 passes.

On the reducible control flow graph of the odd-sum program on the control flow graph page, with edges B1→B2B1 \to B2, B2→B3B2 \to B3, B2→B6B2 \to B6, B3→B4B3 \to B4, B3→B5B3 \to B5, B4→B5B4 \to B5, B5→B2B5 \to B2, pass 1 already gives the answer B2↦B1B2 \mapsto B1, B3↦B2B3 \mapsto B2, B6↦B2B6 \mapsto B2, B4↦B3B4 \mapsto B3, B5↦B3B5 \mapsto B3, 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 idom=[−,0,1,2,2,4,2,3,7]idom = [-, 0, 1, 2, 2, 4, 2, 3, 7].

Correctness

The full proof is in the proof file. Its steps:

  1. The guesses form a tree. When bb gets a guess, the guess is on the chain of the DFS parent of bb, so it is a proper DFS ancestor of bb with a larger postorder number. Hence every chain climbs strictly in postorder and ends at rr, and a new guess for bb is never inside the subtree of bb.
  2. INTERSECT. A finger never passes the nearest common ancestor cc of b1b_1 and b2b_2: a finger at cc 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 cc.
  3. Soundness. At all times D(y)⊆chain(y)D(y) \subseteq chain(y) for every defined yy. A strict dominator of bb dominates every predecessor of bb, and a change at bb also keeps the property for the vertices below bb in the tree, because they are DFS descendants of bb.
  4. Fixed point. When a pass changes nothing, chain(b)={b}∪⋂pchain(p)chain(b) = \{b\} \cup \bigcap_p chain(p) for all b≠rb \ne r. Walking along a path from rr that avoids a vertex xx shows that xx is in no chain on the path, so chain(y)⊆D(y)chain(y) \subseteq D(y). With step 3, chain(y)=D(y)chain(y) = D(y), and then doms[y]=idom(y)doms[y] = \mathrm{idom}(y).
  5. Termination. The chains are always subsets of the sets of the plain set iteration run in the same order, and after pass kk those sets are inside the vertex set of every path from rr with at most k−1k - 1 retreating edges. So after pass d+1d + 1 every chain equals DD, and pass d+2d + 2 changes nothing.
Proof: The Cooper-Harvey-Kennedy algorithm computes the immediate dominators in at most d + 2 passesfull

Setting. GG is a directed graph with start vertex rr. Let RR be the set of vertices that rr reaches. A vertex outside RR 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 RR lies on no path from rr, so it changes no dominator. From here on, all vertices are in RR and "predecessor" means a predecessor in RR. TT is the DFS tree of line L1, popo its postorder numbering, and the visit order of line L7 is decreasing popo. D(v)D(v) is the set of dominators of vv. The DFS tree is used only through these facts: a proper TT-ancestor of vv has a larger popo than vv, and the tree path from rr to vv contains exactly the TT-ancestors of vv.

For a defined vertex yy, chain(y)chain(y) is the set of vertices on y,doms[y],doms[doms[y]],…y, doms[y], doms[doms[y]], \ldots. Lemma 1 shows this sequence reaches rr, where it stops, since doms[r]=rdoms[r] = r.

Lemma 0 (the dominator equation). For b≠rb \ne r, D(b)={b}∪⋂pD(p)D(b) = \{b\} \cup \bigcap_{p} D(p), the intersection over the predecessors pp of bb. Also D(r)={r}D(r) = \{r\}.

Proof. Let x∈D(b)x \in D(b) with x≠bx \ne b, and let pp be a predecessor. If x=px = p then x∈D(p)x \in D(p). Otherwise a path from rr to pp that avoids xx, followed by the edge (p,b)(p, b), would avoid xx, so x∈D(p)x \in D(p). Conversely, let x≠bx \ne b be in every D(p)D(p). A path from rr to bb has at least one edge, since b≠rb \ne r, so its last but one vertex is a predecessor pp, and the part up to pp contains xx. The vertex rr is a path from rr to rr by itself, so D(r)={r}D(r) = \{r\}. □\square

Lemma 1 (the guesses form a tree). At all times: every defined y≠ry \ne r has doms[y]doms[y] defined and a proper TT-ancestor of yy, and chain(y)chain(y) is a set of TT-ancestors of yy. A vertex that is defined stays defined.

Proof. At the start only rr is defined. Line L12 never writes Undefined. Assume the claim before an update of bb in line L12. In pass 1 every vertex visited before bb was given a value when it was visited, by induction along the visit order, and the DFS parent qq of bb comes before bb because po(q)>po(b)po(q) > po(b). So qq is defined, line L8 finds a predecessor, and the defined predecessors include qq. Lemma 2 below, applied to the current tree, shows that the value cc that lines L8 to L10 compute is a vertex of chain(q)chain(q), and by the claim chain(q)chain(q) consists of TT-ancestors of qq. So cc is defined and a proper TT-ancestor of bb. After the update, chain(b)={b}∪chain(c)chain(b) = \{b\} \cup chain(c); the old chain of cc does not contain bb, because it consists of TT-ancestors of cc, and bb is not one of them, so it is not changed by the update. For another vertex yy, either b∉chain(y)b \notin chain(y) and nothing changes, or chain(y)chain(y) is the part from yy up to just below bb, which is unchanged, together with the new chain(b)chain(b). Since b∈chain(y)b \in chain(y), bb is a TT-ancestor of yy, and the new chain(b)chain(b) consists of TT-ancestors of bb, so of yy. □\square

So following domsdoms strictly raises popo until it reaches rr: the defined vertices form a tree with root rr and parent array domsdoms, and chain(y)chain(y) is the set of ancestors of yy in that tree. The vertex of chain(y)chain(y) with the smallest popo is yy, so the chain determines yy.

Lemma 2 (INTERSECT). In a tree with root rr whose parent array is domsdoms and in which every parent has a larger popo than its child, INTERSECT(b1,b2)(b_1, b_2) stops and returns the nearest common ancestor cc of b1b_1 and b2b_2. Moreover chain(c)=chain(b1)∩chain(b2)chain(c) = chain(b_1) \cap chain(b_2).

Proof. The common ancestors of b1b_1 and b2b_2 are chain(b1)∩chain(b2)chain(b_1) \cap chain(b_2). They form the path from cc up to rr, which gives the second claim. We show that finger1finger_1 is always a descendant of cc (possibly cc), and the same for finger2finger_2. This holds at the start. Line L16 moves finger1finger_1 only when po(finger1)<po(finger2)po(finger_1) < po(finger_2). If finger1=cfinger_1 = c, then finger2finger_2 is a descendant of cc, so po(finger2)≤po(c)=po(finger1)po(finger_2) \le po(c) = po(finger_1), and there is no move. So finger1finger_1 is a proper descendant of cc, and its parent is still a descendant of cc. Line L17 is the same. Each move raises the popo of one finger, so the inner loops stop. In an outer iteration with finger1≠finger2finger_1 \ne finger_2 the numbers differ, since popo 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 ff, which is an ancestor of b1b_1 and of b2b_2 and a descendant of cc. Every common ancestor is an ancestor of cc, so f=cf = c. □\square

The nearest common ancestor is associative, so lines L8 to L10 compute the nearest common ancestor cc of all defined predecessors pp of bb, and chain(c)=⋂pchain(p)chain(c) = \bigcap_p chain(p). By Lemma 1, the update of line L12, or the decision not to update, gives

chain′(b)={b}∪⋂p definedchain(p).(∗)chain'(b) = \{b\} \cup \bigcap_{p \text{ defined}} chain(p). \qquad (\ast)

Lemma 3 (soundness). At all times, D(y)⊆chain(y)D(y) \subseteq chain(y) for every defined yy.

Proof. At the start, D(r)={r}=chain(r)D(r) = \{r\} = chain(r). Assume the claim before an update of bb.

At bb. Let x∈D(b)x \in D(b) with x≠bx \ne b. By Lemma 0, x∈D(p)⊆chain(p)x \in D(p) \subseteq chain(p) for every defined predecessor pp, so x∈chain′(b)x \in chain'(b) by (∗)(\ast). And b∈chain′(b)b \in chain'(b).

Below bb. Let y≠by \ne b have b∈chain(y)b \in chain(y), and let x∈D(y)x \in D(y). The new chain of yy is the old part from yy to bb together with chain′(b)chain'(b). If xx is in the old part, we are done. Otherwise x∈chain(y)x \in chain(y) by the claim, and xx is above bb in the old chain, so it is in the old chain(doms[b])chain(doms[b]) and is a proper TT-ancestor of bb by Lemma 1. Also bb is a TT-ancestor of yy. Then xx dominates bb: if a path from rr to bb avoided xx, it could be continued by the tree path from bb to yy, which contains only TT-descendants of bb and so not xx, and this would be a path to yy that avoids xx. So x∈D(b)⊆chain′(b)x \in D(b) \subseteq chain'(b) by the case above.

The chains of all other vertices do not change. □\square

Theorem 1 (partial correctness). If the loop of line L5 stops, then doms[y]=idom(y)doms[y] = \mathrm{idom}(y) for every y≠ry \ne r.

Proof. If R={r}R = \{r\}, there is nothing to show. Otherwise pass 1 sets a value for every vertex, which changes domsdoms, 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 (∗)(\ast), at its end, chain(b)={b}∪⋂pchain(p)chain(b) = \{b\} \cup \bigcap_p chain(p) over all predecessors, for all b≠rb \ne r, and chain(r)={r}chain(r) = \{r\}.

Let x∈chain(y)x \in chain(y) and suppose x∉D(y)x \notin D(y). Then there is a path r=v0,v1,…,vk=yr = v_0, v_1, \ldots, v_k = y that avoids xx, and x≠rx \ne r. We show x∉chain(vi)x \notin chain(v_i) for all ii. For v0=rv_0 = r the chain is {r}\{r\}. If x∉chain(vi)x \notin chain(v_i) and vi+1≠rv_{i+1} \ne r, then xx is not in the intersection over the predecessors of vi+1v_{i+1}, which include viv_i, and x≠vi+1x \ne v_{i+1}, so x∉chain(vi+1)x \notin chain(v_{i+1}). If vi+1=rv_{i+1} = r, its chain is {r}\{r\}. So x∉chain(y)x \notin chain(y), a contradiction. Hence chain(y)⊆D(y)chain(y) \subseteq D(y), and with Lemma 3, chain(y)=D(y)chain(y) = D(y).

Now chain(doms[y])=D(y)∖{y}chain(doms[y]) = D(y) \setminus \{y\}, so doms[y]doms[y] is a strict dominator of yy, and every strict dominator of yy lies in chain(doms[y])=D(doms[y])chain(doms[y]) = D(doms[y]), that is, it dominates doms[y]doms[y]. This is the definition of idom(y)\mathrm{idom}(y). □\square

The set iteration. To bound the passes we compare with the set version SS of the same loop. Let S(r)={r}S(r) = \{r\} and S(v)=RS(v) = R for v≠rv \ne r at the start, and let SS visit the vertices in the same order as CHK, one pass at a time, doing S(b)←{b}∪⋂pS(p)S(b) \leftarrow \{b\} \cup \bigcap_p S(p) 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 SS is still RR. So intersecting over all S(p)S(p) is the same as intersecting over the defined pp, since RR changes no intersection.

  • (S1) SS only shrinks. Each value is the same monotone function of the current SS, the current SS is at most the earlier one by induction, and the first values are RR.
  • (S2) D⊆SD \subseteq S. By induction with Lemma 0: {b}∪⋂pS(p)⊇{b}∪⋂pD(p)=D(b)\{b\} \cup \bigcap_p S(p) \supseteq \{b\} \cup \bigcap_p D(p) = D(b).

Lemma 4. At all times, if b∈S(y)b \in S(y), then S(b)⊆S(y)S(b) \subseteq S(y).

Proof. At the start, S(y)=RS(y) = R for y≠ry \ne r, and S(r)={r}S(r) = \{r\}. Consider an update at zz that gives S′(z)S'(z). Take b∈S′(y)b \in S'(y). If y≠zy \ne z and b≠zb \ne z, nothing involved has changed. If y=b=zy = b = z, the claim is trivial. If y=z≠by = z \ne b, then b∈S(p)b \in S(p) for every predecessor pp of zz, so S(b)⊆S(p)S(b) \subseteq S(p) for every pp, and S′(b)=S(b)⊆⋂pS(p)⊆S′(z)S'(b) = S(b) \subseteq \bigcap_p S(p) \subseteq S'(z). If y≠z=by \ne z = b, then z∈S(y)z \in S(y) gives S(z)⊆S(y)S(z) \subseteq S(y), and S′(z)⊆S(z)S'(z) \subseteq S(z) by (S1), so S′(z)⊆S′(y)S'(z) \subseteq S'(y). □\square

Lemma 5. At all times, chain(y)⊆S(y)chain(y) \subseteq S(y) for every defined yy.

Proof. At the start both are {r}\{r\} at rr. At an update of bb: by (∗)(\ast) and the remark on Undefined vertices, chain′(b)={b}∪⋂p definedchain(p)⊆{b}∪⋂pS(p)=S′(b)chain'(b) = \{b\} \cup \bigcap_{p \text{ defined}} chain(p) \subseteq \{b\} \cup \bigcap_p S(p) = S'(b). For y≠by \ne b with b∈chain(y)b \in chain(y): the new chain of yy is the old part from yy to bb, which is in chain(y)⊆S(y)chain(y) \subseteq S(y), together with chain′(b)⊆S′(b)⊆S(b)chain'(b) \subseteq S'(b) \subseteq S(b). Since b∈chain(y)⊆S(y)b \in chain(y) \subseteq S(y), Lemma 4 gives S(b)⊆S(y)S(b) \subseteq S(y). And S′(y)=S(y)S'(y) = S(y). The other chains do not change. □\square

Lemma 6 (paths). For a path PP from rr, let ret(P)ret(P) be the number of its edges (u,v)(u, v) that are retreating, that is, po(v)≥po(u)po(v) \ge po(u). If pass k≥1k \ge 1 has finished, then S(v)⊆S(v) \subseteq the vertex set of PP for every path PP from rr to vv with ret(P)≤k−1ret(P) \le k - 1.

Proof. Let P=v0,…,vjP = v_0, \ldots, v_j with v0=rv_0 = r, and let $k_i = 1 + $ the number of retreating edges among the first ii edges. We show: by the end of pass kik_i, S(vi)⊆{v0,…,vi}S(v_i) \subseteq \{v_0, \ldots, v_i\}, and by (S1) it stays so. For i=0i = 0, S(r)={r}S(r) = \{r\} at all times. For the step, let e=(vi,vi+1)e = (v_i, v_{i+1}); if vi+1=rv_{i+1} = r there is nothing to show. If ee is not retreating, vi+1v_{i+1} comes after viv_i in the visit order, so in pass ki+1=kik_{i+1} = k_i it is visited after viv_i was visited (or, for vi=rv_i = r, at a time when S(r)={r}S(r) = \{r\}). So when vi+1v_{i+1} is visited, S(vi)⊆{v0,…,vi}S(v_i) \subseteq \{v_0, \ldots, v_i\}, and the new S(vi+1)⊆{vi+1}∪S(vi)⊆{v0,…,vi+1}S(v_{i+1}) \subseteq \{v_{i+1}\} \cup S(v_i) \subseteq \{v_0, \ldots, v_{i+1}\}. If ee is retreating, ki+1=ki+1k_{i+1} = k_i + 1, and in pass ki+1k_i + 1 the vertex vi+1v_{i+1} is visited after pass kik_i has ended, so the same argument applies. □\square

Theorem 2 (termination). Let dd be the largest ret(P)ret(P) over the simple paths PP from rr. The loop of line L5 stops after at most d+2d + 2 passes.

Proof. A vertex xx dominates vv if and only if xx is on every simple path from rr to vv, since every path from rr to vv contains a simple one, with a subset of its vertices, obtained by cutting out cycles. If pass d+1d + 1 runs, then after it Lemma 6 gives S(v)⊆S(v) \subseteq the vertex set of each simple path from rr to vv, so S(v)⊆D(v)S(v) \subseteq D(v), and S=DS = D by (S2). By Lemmas 3 and 5, D⊆chain⊆S=DD \subseteq chain \subseteq S = D, so every chain is DD. In pass d+2d + 2, by (∗)(\ast) and Lemma 0, each visit computes chain′(b)={b}∪⋂pD(p)=D(b)=chain(b)chain'(b) = \{b\} \cup \bigcap_p D(p) = D(b) = chain(b), 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 d+2d + 2 or earlier. A simple path has at most ∣R∣−1|R| - 1 edges, so d+2≤∣R∣+1d + 2 \le |R| + 1. □\square

Corollary (reducible graphs). Call an edge (t,h)(t, h) a back edge if hh dominates tt, and call GG reducible if GG without its back edges has no cycle. If GG is reducible, the loop stops after at most 2 passes.

Proof. First, every retreating edge (u,v)(u, v) is a back edge. For u=vu = v this is clear. Otherwise, in a DFS an edge (u,v)(u, v) with po(v)>po(u)po(v) > po(u) goes to a TT-ancestor vv of uu, because tree edges, forward edges and cross edges all go to a smaller popo. A tree edge (x,y)(x, y) is never a back edge, since the tree path from rr to xx avoids its proper descendant yy. So if (u,v)(u, v) were not a back edge, the tree path from vv to uu and the edge (u,v)(u, v) would form a cycle without back edges.

Next, let PP be a path from rr to vv with a retreating edge (t,h)(t, h). Then hh dominates tt, so hh appears in PP before tt; cutting out the part of PP from that earlier hh to the hh after tt gives a shorter path from rr to vv, made of edges of PP, with a subset of its vertices. Repeating this gives a path with no retreating edge. So D(v)D(v) is the intersection of the vertex sets of the paths from rr to vv with ret=0ret = 0, and by Lemma 6 with k=1k = 1, S=DS = D after pass 1. As in Theorem 2, every chain is DD after pass 1, and pass 2 changes nothing. □\square

The proof of Lemma 6 shows more: on a reducible graph, S(b)=D(b)S(b) = D(b) already at the moment bb 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 Θ(n+m)\Theta(n + m). 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 popo each time, so it makes at most 2∣R∣2|R| moves. A pass costs O(n+mn)O(n + m n), and with Theorem 2 the total is O(n+m+(d+2)(n+mn))O(n + m + (d + 2)(n + m n)), which is O((d+2) n(n+m))O((d + 2)\, n (n + m)). On a reducible graph a chain has at most h+1h + 1 vertices in every pass, where hh is the height of the dominator tree, so a pass costs O(n+mh)O(n + m h).

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 Θ(n+m)\Theta(n + m) 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 2n2n. A pass costs O(n+mn)O(n + m n). The number of passes is at most d+2d + 2, where dd is the largest number of retreating edges on a simple path from rr 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 rr. Since d≤n−1d \le n - 1, the total is O((d+2) n(n+m))O((d + 2)\, n (n + m)), which is O(n2(n+m))O(n^2 (n + m)) in the worst case. On a reducible graph every retreating edge (t,h)(t, h) is a back edge, so hh comes before tt on any path from rr to tt, and a simple path from rr cannot use the edge. So d=0d = 0, there are at most 2 passes, and the time is O(n(n+m))O(n (n + m)). Georgiadis, Tarjan and Werneck give graph families on which the iterative algorithm is slow. The extra space is Θ(n+m)\Theta(n + m) for the predecessor lists and Θ(n)\Theta(n) for popo and domsdoms.

Stated in the paper, not proved here. The technical report quotes a bound of d(G)+3d(G) + 3 passes from the work of Kam and Ullman. The proof file proves d+2d + 2 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 3n3n edges, the largest pass count was 5, the count never exceeded d+2d + 2, and it reached d+2d + 2 on some graphs; no reducible graph needed more than 2 passes.

graph passes time per pass
reducible at most 2 O(n+m⋅h)O(n + m \cdot h), hh the height of the dominator tree
general at most d+2d + 2 O(n+m⋅n)O(n + m \cdot n)
a tree, a path, a star 2 Θ(n+m)\Theta(n + m)

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 domsdoms 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 domsdoms is not in general a valid starting point.
  • Guesses are never too high. A guess can be too deep, as for cc 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 D(v)D(v) for each vertex, as a bit vector, and repeats D(b)←{b}∪⋂pD(p)D(b) \leftarrow \{b\} \cup \bigcap_p D(p) until no set changes. Its passes obey the same bound, but it costs Θ(n)\Theta(n) bits per vertex and Θ(n)\Theta(n) 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 domsdoms 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 rr.
  • 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 doms[r]=rdoms[r] = r. Without line L3 the root is Undefined, line L8 finds nothing for the children of rr, and INTERSECT has no stopping point.
  • Unreachable predecessors. A predecessor that rr 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 cc in the example. Keep the test on changed unless 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.

cooper_harvey_kennedy_dominance.pyI0RawGitHub
# 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 D(v)D(v) 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

  1. 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
  2. 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
  3. 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)
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example