Algorithm Search⌘K

Algorithmcore

Dominance frontier computation

Also called Cytron dominance frontier algorithm.

Computes all dominance frontiers in time linear in their total size by a bottom-up walk of the dominator tree.

Time
Θ(n + m + D) worst · average · best
Space
Θ(n + D) extra
Where
D = the total size of all dominance frontiers; m = the number of edges; n = the number of reachable nodes
Properties
deterministicofflineiterative

Dominance frontier computation finds the dominance frontier of every node of a flow graph, given its dominator tree. The method of Cytron, Ferrante, Rosen, Wegman and Zadeck (1991) visits the tree bottom up. The frontier of a node is made from the edges that leave it directly, plus the frontiers of its children that also escape the node itself. The cost is linear in the size of the graph plus the total size of the frontiers, which is the size of the output. Cooper, Harvey and Kennedy later gave a shorter method that walks up the tree from the predecessors of each join node. This page covers both. The frontiers tell Cytron SSA construction where to put phi-functions.

In plain words

A block "owns" every block it dominates: control cannot get there without passing through it. The frontier of a block is the set of blocks just outside its land, the first blocks that can also be reached by a road that skips it. To find them all, start from the deepest blocks of the dominator tree. Each block looks at its own outgoing edges and keeps the targets it does not own. Then it looks at what its children reported, and keeps the blocks it does not own either. A parent never has to look below its children, because they already did that work. The other method starts at each meeting point and climbs the tree from each incoming edge, marking every block it passes, until it reaches the block that owns the meeting point.

The problem

The input is a flow graph G=(N,E,r)G = (N, E, r) with root rr and the immediate dominator idom(y)\mathrm{idom}(y) of each node y≠ry \ne r that rr reaches. Nodes that rr does not reach are ignored. The output is, for each reachable node xx,

DF(x)={ y:∃ (p,y)∈E, xdom⁡p, not xsdom⁡y }.DF(x) = \{\, y : \exists\, (p, y) \in E,\ x \operatorname{dom} p,\ \text{not } x \operatorname{sdom} y \,\}.

Often the next step is the iterated frontier DF+(S)DF^+(S) of a set SS of blocks, which is where the phi-functions for one variable go.

The two methods rest on two forms of the definition, both proved on the dominance frontier page and in the proof file. The bottom-up form is

DF(x)={y∈succ(x):idom(y)≠x}  ∪⋃idom(z)=x{y∈DF(z):idom(y)≠x}.DF(x) = \{y \in \mathrm{succ}(x) : \mathrm{idom}(y) \ne x\} \;\cup \bigcup_{\mathrm{idom}(z) = x} \{y \in DF(z) : \mathrm{idom}(y) \ne x\}.

Cytron et al. call the first part DFlocal(x)DF_{\text{local}}(x) and the parts that come from the children DFup(z)DF_{\text{up}}(z). The edge form says that y∈DF(x)y \in DF(x) if and only if xx lies on the tree path from some predecessor pp of yy up to idom(y)\mathrm{idom}(y), with idom(y)\mathrm{idom}(y) itself excluded.

The algorithm

  1. DOMINANCE-FRONTIERS(G, r, idom)
  2. 1for each node x, in a postorder of the dominator tree do
  3. 2DF[x] <- empty set
  4. 3for each successor y of x do
  5. 4if idom(y) != x then add y to DF[x]
  6. 5for each child z of x in the dominator tree do
  7. 6for each y in DF[z] do
  8. 7if idom(y) != x then add y to DF[x]
  9. 8return DF
  10. DOMINANCE-FRONTIERS-WALK(G, r, idom)
  11. 9for each node y with two or more predecessors, and for y = r do
  12. 10for each predecessor p of y do
  13. 11runner <- p
  14. 12while runner != idom(y) and y is not in DF[runner] do
  15. 13add y to DF[runner]
  16. 14runner <- idom(runner)

The first routine is Cytron's. The postorder of line L1 makes sure that the children of xx are finished before xx, so line L6 reads their final frontiers. Line L4 adds DFlocal(x)DF_{\text{local}}(x) and line L7 adds DFupDF_{\text{up}} of each child. The test in both lines is the same: a node whose immediate dominator is xx is strictly dominated by xx, and every other candidate is not.

The second routine is the walk of Cooper, Harvey and Kennedy. A node with one predecessor pp has idom(y)=p\mathrm{idom}(y) = p, so its walk would be empty, and line L9 skips it. The root is the one exception: it can have a single predecessor through a back edge, and nothing strictly dominates it, so idom(r)\mathrm{idom}(r) is None and the walk goes all the way up. The second test of line L12 is an early stop. If yy is already in DF[runner]DF[\text{runner}], an earlier walk for the same yy passed here and went on up to idom(y)\mathrm{idom}(y), so the rest of the path is done.

In the implementation, the immediate dominators come from the Cooper-Harvey-Kennedy iteration, with idom[root] = None. The routine program_frontiers runs the first method on the blocks of a toy IR program, and iterated_dominance_frontier computes DF+(S)DF^+(S) with a worklist.

Example

Take the program from the control flow graph page that adds the odd numbers below nn. Its edges are B1 → B2, B2 → B3, B2 → B6, B3 → B4, B3 → B5, B4 → B5 and B5 → B2. The dominator tree has B1 → B2, B2 → B3, B2 → B6, B3 → B4 and B3 → B5. A postorder of the tree is B4, B5, B3, B6, B2, B1.

step x local part (L3, L4) from children (L5 to L7) DF[x]
1 B4 B5: idom is B3, keep none {B5}
2 B5 B2: idom is B1, keep none {B2}
3 B3 B4, B5: idom is B3, drop B5 from B4: idom is B3, drop. B2 from B5: keep {B2}
4 B6 no successors none ∅
5 B2 B3, B6: idom is B2, drop B2 from B3: idom is B1, keep {B2}
6 B1 B2: idom is B1, drop B2 from B2: idom is B1, drop ∅

Step 3 shows why the test matters. B4 reports B5, but B3 dominates B5, so for B3 that is not a frontier node. Step 5 shows a node in its own frontier: the back edge B5 → B2 escapes the land of B2 by entering B2 itself, which B2 does not strictly dominate.

The walk gives the same sets. The join nodes are B2, with predecessors B1 and B5, and B5, with predecessors B3 and B4. For B2, the walk from B1 stops at once, since B1 = idom(B2). The walk from B5 adds B2 to the frontiers of B5, B3 and B2, and stops at B1. For B5, the walk from B3 stops at once, and the walk from B4 adds B5 to DF[B4]DF[B4] and stops at B3.

The variable s is assigned in B1 and B4. The worklist for DF+({B1,B4})DF^+(\{B1, B4\}) takes B4 and finds B5, then takes B5 and finds B2, then takes B2 and finds B2 again. The result is {B2, B5}, the two blocks that get a phi-function for s.

Correctness

The proof file proves four facts. First, for an edge (p,y)(p, y) with y≠ry \ne r, idom(y)\mathrm{idom}(y) dominates pp: a path to pp that avoids it, plus the edge, would reach yy without it. So the nodes that dominate pp form a chain that contains idom(y)\mathrm{idom}(y), and the ones that do not strictly dominate yy are those below idom(y)\mathrm{idom}(y). This gives the edge form. Second, splitting the walk from pp at xx gives the bottom-up form: either p=xp = x, which is the local part, or the walk passes the child zz of xx first, which puts yy in DF(z)DF(z). Third, the postorder of line L1 makes the bottom-up form an induction, so the first routine is correct, and the walk adds yy to exactly the nodes of the edge form, so the second one is correct too. The early stop skips only nodes that already hold yy. Fourth, the worklist for DF+(S)DF^+(S) returns the least set that contains DF(S)DF(S) and is closed under DFDF.

Proof: Both passes compute the dominance frontiers, and the worklist computes the iterated frontierfull

Setting. GG is a directed graph with root rr, and RR is the set of nodes that rr reaches. Only nodes of RR and edges between them take part: an edge from a node outside RR lies on no path from rr and changes no dominance relation, and the code never looks at such nodes. xdom⁡yx \operatorname{dom} y means that every path from rr to yy contains xx, and xsdom⁡yx \operatorname{sdom} y means xdom⁡yx \operatorname{dom} y and x≠yx \ne y. The input idom\mathrm{idom} is correct: idom(r)\mathrm{idom}(r) is None, and for y≠ry \ne r, idom(y)\mathrm{idom}(y) is the strict dominator of yy that every other strict dominator of yy dominates. (The Cooper-Harvey-Kennedy page proves this for the routine used.) TT is the dominator tree, with parent idom\mathrm{idom}. We use one standard fact: the dominators of yy are exactly the ancestors of yy in TT, yy included. So the dominators of yy form a chain, and xsdom⁡yx \operatorname{sdom} y if and only if xx is a proper ancestor of yy.

The target is DF(x)={y:∃(p,y)∈E, xdom⁡p, not xsdom⁡y}DF(x) = \{y : \exists (p, y) \in E,\ x \operatorname{dom} p,\ \text{not } x \operatorname{sdom} y\}. For an edge (p,y)(p, y), let W(p,y)W(p, y) be the set of nodes on the tree path from pp up to, but not including, idom(y)\mathrm{idom}(y). If y=ry = r, the path goes up to rr and includes it.

Lemma 1. Let (p,y)∈E(p, y) \in E with p,y∈Rp, y \in R and y≠ry \ne r. Then idom(y)dom⁡p\mathrm{idom}(y) \operatorname{dom} p.

Proof. Let d=idom(y)d = \mathrm{idom}(y), so d≠yd \ne y. Suppose some path PP from rr to pp avoids dd. Then PP followed by the edge (p,y)(p, y) is a path from rr to yy. Its nodes are those of PP and yy, and none of them is dd. This contradicts ddom⁡yd \operatorname{dom} y. □\square

So idom(y)\mathrm{idom}(y) is an ancestor of pp in TT, and W(p,y)W(p, y) is a well defined part of the path from pp to the root.

Lemma 2 (the edge form). y∈DF(x)y \in DF(x) if and only if x∈W(p,y)x \in W(p, y) for some edge (p,y)(p, y).

Proof. Fix an edge (p,y)(p, y). The nodes xx with xdom⁡px \operatorname{dom} p are the ancestors of pp, which form the path AA from pp up to rr.

If y=ry = r, no node strictly dominates yy, since a strict dominator of rr would have to lie on the empty path from rr to rr. So xdom⁡px \operatorname{dom} p and not xsdom⁡yx \operatorname{sdom} y holds for all x∈A=W(p,y)x \in A = W(p, y).

If y≠ry \ne r, let d=idom(y)d = \mathrm{idom}(y). By Lemma 1, d∈Ad \in A. Take x∈Ax \in A. Both xx and dd are on the chain AA, so one is an ancestor of the other. The strict dominators of yy are the ancestors of dd, dd included. So xsdom⁡yx \operatorname{sdom} y if and only if xx is dd or above dd. Hence the x∈Ax \in A with not xsdom⁡yx \operatorname{sdom} y are exactly the nodes of AA below dd, which is W(p,y)W(p, y).

Taking the union over all edges into yy gives the claim. □\square

Lemma 3 (the bottom-up split). For every node xx,

DF(x)={y∈succ(x):idom(y)≠x}  ∪⋃z:idom(z)=x{y∈DF(z):idom(y)≠x}.DF(x) = \{y \in \mathrm{succ}(x) : \mathrm{idom}(y) \ne x\} \;\cup \bigcup_{z : \mathrm{idom}(z) = x} \{y \in DF(z) : \mathrm{idom}(y) \ne x\}.

(For y=ry = r the test idom(y)≠x\mathrm{idom}(y) \ne x is true, since idom(r)\mathrm{idom}(r) is None.)

Proof. (⊆\subseteq) Let y∈DF(x)y \in DF(x). By Lemma 2 there is an edge (p,y)(p, y) with x∈W(p,y)x \in W(p, y). Then x≠idom(y)x \ne \mathrm{idom}(y), because W(p,y)W(p, y) excludes idom(y)\mathrm{idom}(y).

  • If x=px = p, then yy is a successor of xx with idom(y)≠x\mathrm{idom}(y) \ne x, so yy is in the first set.
  • If x≠px \ne p, then xx is a proper ancestor of pp. Let zz be the child of xx on the tree path from xx down to pp. The node zz is between pp and xx, so it is below xx, and xx is below idom(y)\mathrm{idom}(y) (or y=ry = r). So z∈W(p,y)z \in W(p, y), and by Lemma 2, y∈DF(z)y \in DF(z). With idom(y)≠x\mathrm{idom}(y) \ne x, yy is in the second set.

(⊇\supseteq) Let yy be a successor of xx with idom(y)≠x\mathrm{idom}(y) \ne x. If y=ry = r, then x∈W(x,y)x \in W(x, y) since that path runs from xx to the root. Otherwise, by Lemma 1 with p=xp = x, idom(y)\mathrm{idom}(y) is an ancestor of xx, and it is not xx. So x∈W(x,y)x \in W(x, y) and y∈DF(x)y \in DF(x) by Lemma 2.

Let zz be a child of xx and y∈DF(z)y \in DF(z) with idom(y)≠x\mathrm{idom}(y) \ne x. By Lemma 2 there is an edge (p,y)(p, y) with z∈W(p,y)z \in W(p, y). If y=ry = r, the path from pp to the root contains zz and so contains its parent xx, and x∈W(p,y)x \in W(p, y). Otherwise idom(y)\mathrm{idom}(y) is a proper ancestor of zz, so it is xx or above xx. It is not xx, so it is above xx, and xx lies on the path from zz up to idom(y)\mathrm{idom}(y) with idom(y)\mathrm{idom}(y) excluded. Hence x∈W(p,y)x \in W(p, y) and y∈DF(x)y \in DF(x). □\square

Theorem 1 (the bottom-up pass, lines L1 to L8). When line L8 returns, DF[x]=DF(x)DF[x] = DF(x) for every x∈Rx \in R.

Proof. Line L1 visits the nodes in a postorder of TT, so every child zz of xx is finished before xx starts. By induction on this order, DF[z]=DF(z)DF[z] = DF(z) for each child when xx is visited. Lines L3 and L4 add the first set of Lemma 3, and lines L5 to L7 add the second set, reading the finished DF[z]DF[z]. Nothing else is added. By Lemma 3 the result is DF(x)DF(x). Every node of RR is in TT and is visited once. □\square

Theorem 2 (the walk, lines L9 to L14). When the walk ends, DF[x]=DF(x)DF[x] = DF(x) for every x∈Rx \in R.

Proof. First take the walk without the early stop, that is, with the test y not in DF[runner] removed from line L12. For the edge (p,y)(p, y), lines L11 to L14 start at pp and move to the parent until they reach idom(y)\mathrm{idom}(y), or until they pass the root when y=ry = r (then idom(y)\mathrm{idom}(y) is None, and the parent of the root is None too). By Lemma 1 the walk does reach idom(y)\mathrm{idom}(y), so it stops, and the nodes it adds yy to are exactly W(p,y)W(p, y). Line L9 skips a node y≠ry \ne r with one predecessor pp. For such a node every path from rr to yy ends with the edge (p,y)(p, y), so pdom⁡yp \operatorname{dom} y, and the strict dominators of yy are pp and the dominators of pp, which makes idom(y)=p\mathrm{idom}(y) = p and W(p,y)=∅W(p, y) = \emptyset. So skipping it loses nothing. By Lemma 2, the union over all edges is DFDF.

Now the early stop. The walks for one node yy run one after the other, before the walks for any other node. Claim: whenever y∈DF[u]y \in DF[u] during the walks for yy, every node on the tree path from uu up to idom(y)\mathrm{idom}(y), with idom(y)\mathrm{idom}(y) excluded, also has yy in its set. This holds before the first walk for yy, when no set holds yy. A walk adds yy to a sequence of nodes u1,u2,…,uku_1, u_2, \ldots, u_k going up the tree. It stops either at idom(y)\mathrm{idom}(y), so the claim holds for all uiu_i, or at a node uk+1u_{k+1} that already holds yy, and then the claim for uk+1u_{k+1} gives the rest of the path. So the early stop only skips nodes that already hold yy, and the sets at the end are the same as without it. □\square

Lemma 4 (the iterated frontier). Let LL be the limit of DF1=DF(S)DF_1 = DF(S), DFi+1=DF(S∪DFi)DF_{i+1} = DF(S \cup DF_i). The worklist routine returns LL.

Proof. Each DFi⊆DFi+1DF_i \subseteq DF_{i+1}, by induction: DF1=DF(S)⊆DF(S∪DF1)DF_1 = DF(S) \subseteq DF(S \cup DF_1), and if DFi−1⊆DFiDF_{i-1} \subseteq DF_i then DF(S∪DFi−1)⊆DF(S∪DFi)DF(S \cup DF_{i-1}) \subseteq DF(S \cup DF_i). The sets lie in the finite set NN, so the sequence stops at some LL with L=DF(S∪L)L = DF(S \cup L).

Let WW be the returned set. Every node put on the work list is in S∪WS \cup W, and is put there once.

(W⊆LW \subseteq L) A node yy enters WW as a member of DF(x)DF(x) for a node xx taken from the list. By induction on the order of the steps, x∈S∪Lx \in S \cup L, so y∈DF(S∪L)=Ly \in DF(S \cup L) = L. A node that enters the list is then in S∪LS \cup L, which keeps the induction going.

(L⊆WL \subseteq W) At the end the list is empty, so every node of S∪WS \cup W was taken from it and its frontier was added to WW. So DF(S∪W)⊆WDF(S \cup W) \subseteq W. Then DF1=DF(S)⊆WDF_1 = DF(S) \subseteq W, and if DFi⊆WDF_i \subseteq W then DFi+1=DF(S∪DFi)⊆DF(S∪W)⊆WDF_{i+1} = DF(S \cup DF_i) \subseteq DF(S \cup W) \subseteq W. So L⊆WL \subseteq W. □\square

Running time. Let n=∣R∣n = |R|, mm the number of edges inside RR, and D=∑x∣DF(x)∣D = \sum_x |DF(x)|. In the bottom-up pass, each node is visited once (L1, L2), each edge is looked at once (L3, L4), and each element of DF(z)DF(z) is looked at once, at the parent of zz (L6, L7). With a set that tests and adds in O(1)O(1), for example a marker array stamped with xx, the time is Θ(n+m+D)\Theta(n + m + D). In the walk, each pass through line L13 adds a new pair (runner,y)(\text{runner}, y), because of the early stop, so there are at most DD such passes. Each predecessor pp of yy costs O(1)O(1) more for the test that ends its walk. So the time is O(n+m+D)O(n + m + D). The worklist for DF+(S)DF^+(S) takes each node at most once and reads its frontier once, so it takes O(n+D)O(n + D) time.

Complexity

Let nn be the number of reachable nodes, mm the number of edges and D=∑x∣DF(x)∣D = \sum_x |DF(x)|.

  • The bottom-up pass. Each node is visited once, each edge is tested once at line L4, and each element of DF(z)DF(z) is tested once, at the parent of zz. With a set that tests and adds in constant time, the time is Θ(n+m+D)\Theta(n + m + D).
  • The walk. Because of the early stop, every pass through line L13 adds a new pair, so there are at most DD of them. Each predecessor costs O(1)O(1) more to stop its walk. The time is O(n+m+D)O(n + m + D). Without the early stop, two walks for the same yy can climb the same part of the tree, and the cost grows with the in-degree of yy times its number of frontier entries.
  • Space. The frontiers take Θ(D)\Theta(D) and the tree takes Θ(n)\Theta(n).

DD itself can be Θ(n2)\Theta(n^2). For kk nested repeat-until loops the graph has 2k+12k + 1 nodes and 3k3k edges, and D=k(k+1)D = k(k + 1); the dominance frontier page works this out. On real programs Cytron et al. found DD to grow about linearly with nn. Sreedhar and Gao avoid the quadratic case: their DJ-graph method finds DF+(S)DF^+(S) in O(n+m)O(n + m) time for each set SS, without computing DD.

Properties

  • Output sensitive. The time is linear in the input plus the output, so neither method can be beaten by more than a constant factor when all frontiers are wanted.
  • Needs only the tree and the edges. Both methods read the immediate dominators and the successor or predecessor lists, nothing else.
  • Works on any flow graph. Reducible or not, with or without edges into the root.
  • Local to join nodes. Only nodes with two or more predecessors (and the root) appear in a frontier, so the walk does no work for the other nodes.

Variants and improvements

  • Post-dominance frontiers. Run the same code on the reverse graph, with the post-dominator tree. The result gives control dependence: yy is control dependent on xx if xx is in the post-dominance frontier of yy.
  • Iterated frontiers on demand. Placing phi-functions needs only DF+(S)DF^+(S) for one set at a time. Sreedhar and Gao's DJ-graphs, and the merge sets of chapter 4 of the SSA book, compute it directly in linear time per set.
  • Bit vectors. For small graphs, each DF[x]DF[x] can be a bit vector, and line L7 becomes a masked union.
  • No frontiers at all. Braun SSA construction builds SSA form with no dominance information.

When to use it

Use the walk when the dominator tree comes from the Cooper-Harvey-Kennedy or Lengauer-Tarjan algorithm and the frontiers are needed for many variables. It is the shortest code and is easy to get right. Use the bottom-up pass when the tree is already walked in postorder for other reasons. If the graph is large and has deep nests of loops, so that DD may grow quadratically, compute DF+DF^+ per variable instead.

Pitfalls

  • Edges into the root. If the root has a predecessor, it is in some frontiers. Treat idom(r)\mathrm{idom}(r) as None, and do not skip the root in line L9 just because it has one predecessor. The toy IR avoids the case by giving the entry no predecessors.
  • Unreachable blocks. A block that the root does not reach has no immediate dominator. Delete it or skip it, and skip its edges.
  • Strict versus plain dominance. A node can be in its own frontier. Testing "xx dominates yy" in place of "xx strictly dominates yy" loses the loop headers, and the loops then get no phi-functions.
  • Stale frontiers. Splitting an edge or deleting a block changes the frontiers. Recompute them, or update them with care, after the graph changes.
  • Parallel edges. If a block has two edges to yy, the walk runs twice from it. The early stop makes this harmless.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

dominance_frontier_computation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dominance-frontier-computation/. The authors are listed in prov/VKF111.jsonl.
"""Dominance frontiers of a flow graph.

dominance_frontiers is the bottom-up pass of Cytron, Ferrante, Rosen, Wegman
and Zadeck over the dominator tree (lines L1 to L8 of the page).
dominance_frontiers_walk is the walk of Cooper, Harvey and Kennedy from each
predecessor of a node up to its immediate dominator (lines L9 to L14).

A graph is a dict from node to its list of successors, and a root. Only the
nodes that the root reaches take part. The immediate dominators come from the
iterative algorithm of Cooper, Harvey and Kennedy; idom[root] is None.
"""

import toyir


def program_graph(prog):
    """The successor lists and the entry of a toy IR program."""
    return {label: toyir.succs(prog, label) for label in prog.blocks}, prog.entry


def postorder(succ, root):
    """The nodes that root reaches, in postorder of an iterative DFS."""
    seen = {root}
    out = []
    stack = [(root, iter(succ[root]))]
    while stack:
        v, it = stack[-1]
        w = next(it, None)
        if w is None:
            stack.pop()
            out.append(v)
        elif w not in seen:
            seen.add(w)
            stack.append((w, iter(succ[w])))
    return out


def immediate_dominators(succ, root):
    """Dict from each node that root reaches to its immediate dominator."""
    order = postorder(succ, root)
    po = {v: i for i, v in enumerate(order)}
    pred = {v: [] for v in order}
    for v in order:
        for w in succ[v]:
            pred[w].append(v)
    doms = {root: root}

    def intersect(a, b):
        while a != b:
            while po[a] < po[b]:
                a = doms[a]
            while po[b] < po[a]:
                b = doms[b]
        return a

    changed = True
    while changed:
        changed = False
        for b in reversed(order):
            if b == root:
                continue
            new = None
            for p in pred[b]:
                if p in doms:
                    new = p if new is None else intersect(p, new)
            if doms.get(b) != new:
                doms[b] = new
                changed = True
    idom = dict(doms)
    idom[root] = None
    return idom


def tree_children(idom):
    children = {v: [] for v in idom}
    for v, d in idom.items():
        if d is not None:
            children[d].append(v)
    return children


def _tree_postorder(children, root):
    out = []
    stack = [(root, False)]
    while stack:
        v, done = stack.pop()
        if done:
            out.append(v)
        else:
            stack.append((v, True))
            for c in children[v]:
                stack.append((c, False))
    return out


def dominance_frontiers(succ, root, idom=None):
    """Cytron's bottom-up pass. Returns a dict from node to its frontier."""
    if idom is None:
        idom = immediate_dominators(succ, root)
    children = tree_children(idom)
    df = {}
    for x in _tree_postorder(children, root):  # @line L1
        s = set()  # @line L2
        for y in succ[x]:  # @line L3
            if idom[y] != x:  # @line L4
                s.add(y)
        for z in children[x]:  # @line L5
            for y in df[z]:  # @line L6
                if idom[y] != x:  # @line L7
                    s.add(y)
        df[x] = s
    return df  # @line L8


def dominance_frontiers_walk(succ, root, idom=None):
    """The walk of Cooper, Harvey and Kennedy, with the early stop."""
    if idom is None:
        idom = immediate_dominators(succ, root)
    pred = {v: [] for v in idom}
    for v in idom:
        for w in succ[v]:
            pred[w].append(v)
    df = {v: set() for v in idom}
    for y in idom:  # @line L9
        if len(pred[y]) < 2 and y != root:
            continue
        for p in pred[y]:  # @line L10
            runner = p  # @line L11
            while runner != idom[y] and y not in df[runner]:  # @line L12
                df[runner].add(y)  # @line L13
                runner = idom[runner]  # @line L14
    return df


def iterated_dominance_frontier(df, nodes):
    """DF+ of a set of nodes, by a worklist over the frontiers."""
    result = set()
    seen = set(nodes)
    work = list(nodes)
    while work:
        x = work.pop()
        for y in df[x]:
            if y not in result:
                result.add(y)
                if y not in seen:
                    seen.add(y)
                    work.append(y)
    return result


def program_frontiers(prog):
    """The dominance frontiers of the blocks of a toy IR program."""
    succ, root = program_graph(prog)
    return dominance_frontiers(succ, root)
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.

A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:

    ("const", x, k)          x = k
    ("copy", x, a)           x = y
    ("op", x, op, a, b)      x = a op b
    ("phi", x, {pred: a})    x = phi [pred: a, ...]
    ("addr", p, x)           p = &x
    ("load", x, p)           x = *p
    ("store", p, a)          *p = a
    ("alloc", p)             p = alloc
    ("call", x, f, args)     x = call f(a, b)   (args is a list)

Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""

from dataclasses import dataclass, field
import re

OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")


@dataclass
class Block:
    instrs: list = field(default_factory=list)
    term: tuple = ("ret", 0)


@dataclass
class Program:
    params: list
    blocks: dict

    @property
    def entry(self):
        return next(iter(self.blocks))


class UndefinedName(Exception):
    """A name was read before any definition."""


# ---------------------------------------------------------------- text form

_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"


def _operand(tok):
    if re.fullmatch(_INT, tok):
        return int(tok)
    if re.fullmatch(_NAME, tok):
        return tok
    raise ValueError("bad operand: %r" % tok)


def _name(tok):
    if not re.fullmatch(_NAME, tok):
        raise ValueError("bad name: %r" % tok)
    return tok


def _parse_instr(line):
    toks = line.split()
    if toks[0] == "jump" and len(toks) == 2:
        return "term", ("jump", _name(toks[1]))
    if toks[0] == "br" and len(toks) == 4:
        return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
    if toks[0] == "ret" and len(toks) == 2:
        return "term", ("ret", _operand(toks[1]))
    lhs, eq, rhs = line.partition("=")
    if not eq:
        raise ValueError("bad line: %r" % line)
    lhs, rhs = lhs.strip(), rhs.strip()
    if lhs.startswith("*"):
        return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
    x = _name(lhs)
    if rhs.startswith("phi"):
        body = rhs[3:].strip()
        if not (body.startswith("[") and body.endswith("]")):
            raise ValueError("bad phi: %r" % line)
        args = {}
        inner = body[1:-1].strip()
        if inner:
            for part in inner.split(","):
                pred, colon, a = part.partition(":")
                if not colon:
                    raise ValueError("bad phi: %r" % line)
                args[_name(pred.strip())] = _operand(a.strip())
        return "instr", ("phi", x, args)
    if rhs.startswith("call "):
        m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
        if not m:
            raise ValueError("bad call: %r" % line)
        inner = m.group(2).strip()
        args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
        return "instr", ("call", x, m.group(1), args)
    if rhs == "alloc":
        return "instr", ("alloc", x)
    if rhs.startswith("&"):
        return "instr", ("addr", x, _name(rhs[1:].strip()))
    if rhs.startswith("*"):
        return "instr", ("load", x, _name(rhs[1:].strip()))
    parts = rhs.split()
    if len(parts) == 1:
        a = _operand(parts[0])
        if isinstance(a, int):
            return "instr", ("const", x, a)
        return "instr", ("copy", x, a)
    if len(parts) == 3 and parts[1] in OPS:
        return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
    raise ValueError("bad instruction: %r" % line)


def parse(text):
    """Parse the text form. A line "# params: a, b" gives the parameters;
    without it, the parameters are the names that are read and never
    defined, in the order of their first use."""
    params = None
    blocks = {}
    cur = None
    for raw in text.splitlines():
        line = raw.strip()
        if not line:
            continue
        if line.startswith("#"):
            m = re.fullmatch(r"#\s*params:(.*)", line)
            if m:
                inner = m.group(1).strip()
                params = [_name(p.strip()) for p in inner.split(",")] if inner else []
            continue
        if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
            label = line[:-1]
            if label in blocks:
                raise ValueError("duplicate label: %r" % label)
            cur = label
            blocks[label] = Block([], None)
            continue
        if cur is None:
            raise ValueError("instruction outside a block: %r" % line)
        if blocks[cur].term is not None:
            raise ValueError("instruction after the terminator in %r" % cur)
        kind, item = _parse_instr(line)
        if kind == "term":
            blocks[cur].term = item
        else:
            blocks[cur].instrs.append(item)
    for label, b in blocks.items():
        if b.term is None:
            raise ValueError("block %r has no terminator" % label)
    if not blocks:
        raise ValueError("empty program")
    prog = Program([], blocks)
    if params is None:
        params = _free_names(prog)
    prog.params = params
    return prog


def _free_names(prog):
    defined = set()
    for b in prog.blocks.values():
        for ins in b.instrs:
            d = defs(ins)
            if d is not None:
                defined.add(d)
    out = []
    for b in prog.blocks.values():
        for ins in b.instrs:
            for a in uses(ins):
                if a not in defined and a not in out:
                    out.append(a)
        for a in term_uses(b.term):
            if a not in defined and a not in out:
                out.append(a)
    return out


def _show_instr(ins):
    k = ins[0]
    if k == "const":
        return "%s = %d" % (ins[1], ins[2])
    if k == "copy":
        return "%s = %s" % (ins[1], ins[2])
    if k == "op":
        return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
    if k == "phi":
        return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
    if k == "addr":
        return "%s = &%s" % (ins[1], ins[2])
    if k == "load":
        return "%s = *%s" % (ins[1], ins[2])
    if k == "store":
        return "*%s = %s" % (ins[1], ins[2])
    if k == "alloc":
        return "%s = alloc" % ins[1]
    if k == "call":
        return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
    raise ValueError("bad instruction: %r" % (ins,))


def _show_term(t):
    if t[0] == "jump":
        return "jump %s" % t[1]
    if t[0] == "br":
        return "br %s %s %s" % (t[1], t[2], t[3])
    if t[0] == "ret":
        return "ret %s" % (t[1],)
    raise ValueError("bad terminator: %r" % (t,))


def show(prog):
    lines = ["# params: " + ", ".join(prog.params)]
    for label, b in prog.blocks.items():
        lines.append(label + ":")
        for ins in b.instrs:
            lines.append("  " + _show_instr(ins))
        lines.append("  " + _show_term(b.term))
    return "\n".join(lines) + "\n"


# ---------------------------------------------------------- names and graph


def defs(ins):
    """The name an instruction defines, or None for a store."""
    return None if ins[0] == "store" else ins[1]


def uses(ins):
    """The names an instruction reads, in order (phi operands included)."""
    k = ins[0]
    if k == "const" or k == "alloc" or k == "addr":
        ops = []
    elif k == "copy":
        ops = [ins[2]]
    elif k == "op":
        ops = [ins[3], ins[4]]
    elif k == "phi":
        ops = list(ins[2].values())
    elif k == "load":
        ops = [ins[2]]
    elif k == "store":
        ops = [ins[1], ins[2]]
    elif k == "call":
        ops = list(ins[3])
    else:
        raise ValueError("bad instruction: %r" % (ins,))
    return [a for a in ops if isinstance(a, str)]


def term_uses(t):
    if t[0] == "br" or t[0] == "ret":
        return [t[1]] if isinstance(t[1], str) else []
    return []


def succs(prog, label):
    """Successor labels of a block, without repeats, in terminator order."""
    t = prog.blocks[label].term
    if t[0] == "jump":
        return [t[1]]
    if t[0] == "br":
        return [t[2]] if t[2] == t[3] else [t[2], t[3]]
    return []


def edges(prog):
    return [(a, b) for a in prog.blocks for b in succs(prog, a)]


def preds(prog):
    """Dict from label to the list of predecessor labels, in block order."""
    out = {label: [] for label in prog.blocks}
    for a, b in edges(prog):
        out[b].append(a)
    return out


def is_acyclic(prog):
    color = {label: 0 for label in prog.blocks}
    for root in prog.blocks:
        if color[root]:
            continue
        color[root] = 1
        stack = [(root, iter(succs(prog, root)))]
        while stack:
            v, it = stack[-1]
            w = next(it, None)
            if w is None:
                color[v] = 2
                stack.pop()
            elif color[w] == 1:
                return False
            elif color[w] == 0:
                color[w] = 1
                stack.append((w, iter(succs(prog, w))))
    return True


def paths(prog):
    """Every path from the entry to a ret block, as a list of labels.
    The CFG must be acyclic."""
    if not is_acyclic(prog):
        raise ValueError("paths needs an acyclic CFG")
    out = []

    def walk(path):
        last = path[-1]
        s = succs(prog, last)
        if not s:
            out.append(list(path))
        for w in s:
            path.append(w)
            walk(path)
            path.pop()

    walk([prog.entry])
    return out


# ------------------------------------------------------------------ running


class _Trap(Exception):
    pass


class _Fuel(Exception):
    pass


def _binop(op, a, b):
    if not isinstance(a, int) or not isinstance(b, int):
        raise TypeError("arithmetic on a pointer")
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op == "*":
        return a * b
    if op == "/" or op == "%":
        if b == 0:
            raise _Trap()
        q = abs(a) // abs(b)
        if (a < 0) != (b < 0):
            q = -q
        return q if op == "/" else a - b * q
    if op == "&":
        return a & b
    if op == "|":
        return a | b
    if op == "^":
        return a ^ b
    if op == "<<" or op == ">>":
        if b < 0 or b > 63:
            raise _Trap()
        return a << b if op == "<<" else a >> b
    if op == "<":
        return int(a < b)
    if op == "<=":
        return int(a <= b)
    if op == "==":
        return int(a == b)
    if op == "!=":
        return int(a != b)
    raise ValueError("bad operator: %r" % op)


class _Frame:
    """One activation: its program, its variables and its position."""

    def __init__(self, prog, args, fid):
        if len(args) != len(prog.params):
            raise ValueError("expected %d arguments" % len(prog.params))
        self.prog = prog
        self.env = dict(zip(prog.params, args))
        self.fid = fid
        self.label = prog.entry
        self.prev = None
        self.pc = 0  # 0 means: the phis of the block have not run yet
        self.dest = None  # the name that receives the value of a pending call

    def val(self, a):
        if isinstance(a, int):
            return a
        if a not in self.env:
            raise UndefinedName(a)
        return self.env[a]


def _run(prog, args, fuel, funcs):
    """Run with an explicit stack of frames, so deep recursion in the toy
    program does not use Python recursion."""
    heap = {}
    envs = {}
    stack = []
    fr = _Frame(prog, args, 0)
    envs[0] = fr.env
    nframes = 1

    def tick():
        nonlocal fuel
        if fuel <= 0:
            raise _Fuel()
        fuel -= 1

    while True:
        block = fr.prog.blocks[fr.label]
        instrs = block.instrs
        if fr.pc == 0:
            # Phis at the top of the block read all operands first, then assign.
            incoming = []
            i = 0
            while i < len(instrs) and instrs[i][0] == "phi":
                tick()
                ins = instrs[i]
                if fr.prev not in ins[2]:
                    raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
                incoming.append((ins[1], fr.val(ins[2][fr.prev])))
                i += 1
            for x, v in incoming:
                fr.env[x] = v
            fr.pc = i if i > 0 else -1
        start = fr.pc if fr.pc > 0 else 0
        called = False
        env = fr.env
        for j in range(start, len(instrs)):
            ins = instrs[j]
            tick()
            k = ins[0]
            if k == "const":
                env[ins[1]] = ins[2]
            elif k == "copy":
                env[ins[1]] = fr.val(ins[2])
            elif k == "op":
                env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
            elif k == "addr":
                env[ins[1]] = ("var", fr.fid, ins[2])
            elif k == "alloc":
                cell = ("heap", len(heap))
                heap[cell] = None
                env[ins[1]] = cell
            elif k == "load":
                p = fr.val(ins[2])
                if p[0] == "var":
                    if p[2] not in envs[p[1]]:
                        raise UndefinedName(p[2])
                    env[ins[1]] = envs[p[1]][p[2]]
                else:
                    if heap[p] is None:
                        raise UndefinedName(repr(p))
                    env[ins[1]] = heap[p]
            elif k == "store":
                p = fr.val(ins[1])
                if p[0] == "var":
                    envs[p[1]][p[2]] = fr.val(ins[2])
                else:
                    heap[p] = fr.val(ins[2])
            elif k == "call":
                if funcs is None or ins[2] not in funcs:
                    raise ValueError("unknown function %r" % ins[2])
                vals = [fr.val(a) for a in ins[3]]
                fr.pc = j + 1
                fr.dest = ins[1]
                stack.append(fr)
                fr = _Frame(funcs[ins[2]], vals, nframes)
                envs[nframes] = fr.env
                nframes += 1
                called = True
                break
            elif k == "phi":
                raise ValueError("phi after a non-phi instruction")
            else:
                raise ValueError("bad instruction: %r" % (ins,))
        if called:
            continue
        tick()
        t = block.term
        if t[0] == "jump" or t[0] == "br":
            if t[0] == "jump":
                nxt = t[1]
            else:
                nxt = t[2] if fr.val(t[1]) != 0 else t[3]
            fr.prev, fr.label, fr.pc = fr.label, nxt, 0
            continue
        v = fr.val(t[1])
        if not stack:
            return ("ret", v), fuel
        fr = stack.pop()
        fr.env[fr.dest] = v


def run(prog, args, fuel=10000, funcs=None):
    """Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
    Each instruction, phi and terminator uses one unit of fuel. funcs is an
    optional dict from function name to Program, used by call; deep
    recursion in the toy program is fine, because the frames are kept on an
    explicit stack."""
    try:
        out, _ = _run(prog, list(args), fuel, funcs)
        return out
    except _Trap:
        return ("trap",)
    except _Fuel:
        return ("fuel",)


# ------------------------------------------------------------ random programs

_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")


def random_program(rng, nvars, nblocks, acyclic):
    """A random program with blocks B0 .. B(nblocks-1) and variables
    x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
    others, so no run reads an undefined name. A division by a variable can
    trap. Every block is reachable from
    B0 and B0 has no predecessor. With acyclic=False, each loop has its own
    counter c that is set to 0 in B0 and never reset, and the back edge is
    taken only while c < m and c < 4, where m is the first parameter. So the
    whole run takes each back edge at most 3 times."""
    nvars = max(nvars, 1)
    nblocks = max(nblocks, 1)
    xs = ["x%d" % i for i in range(nvars)]
    params = xs[:2]
    labels = ["B%d" % i for i in range(nblocks)]

    def operand():
        if rng.random() < 0.25:
            return rng.randint(-3, 9)
        return rng.choice(xs)

    def instr():
        x = rng.choice(xs)
        r = rng.random()
        if r < 0.15:
            return ("const", x, rng.randint(-5, 9))
        if r < 0.25:
            return ("copy", x, rng.choice(xs))
        if r < 0.3:
            # A division by a variable may trap.
            return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
        if r < 0.4:
            op = rng.choice(_CONST_RIGHT)
            k = rng.randint(1, 5)
            return ("op", x, op, rng.choice(xs), k)
        return ("op", x, rng.choice(_SAFE), operand(), operand())

    blocks = {}
    has_pred = [False] * nblocks
    has_pred[0] = True
    for i in range(nblocks):
        instrs = [instr() for _ in range(rng.randint(1, 3))]
        if i == 0:
            instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
        if i == nblocks - 1:
            term = ("ret", rng.choice(xs))
        elif has_pred[i + 1] and rng.random() < 0.2:
            term = ("ret", rng.choice(xs))
        else:
            first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
            if rng.random() < 0.5:
                term = ("jump", labels[first])
                has_pred[first] = True
            else:
                second = rng.randrange(i + 1, nblocks)
                if second == first:
                    term = ("jump", labels[first])
                else:
                    term = ("br", rng.choice(xs), labels[first], labels[second])
                    has_pred[second] = True
                has_pred[first] = True
        blocks[labels[i]] = Block(instrs, term)

    if not acyclic and nblocks > 1:
        nloops = rng.randint(1, max(1, nblocks // 3))
        for k in range(nloops):
            latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
            if not latches:
                break
            t = rng.choice(latches)
            h = labels[rng.randint(1, labels.index(t))]
            c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
            blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
            out = blocks[t].term[1]
            blocks[t].instrs += [
                ("op", c, "+", c, 1),
                ("op", w1, "<", c, m),
                ("op", w2, "<", c, 4),
                ("op", w, "&", w1, w2),
            ]
            blocks[t].term = ("br", w, h, out)
    return Program(list(params), blocks)
test_dominance_frontier_computation.py 209 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dominance-frontier-computation/. The authors are listed in prov/VKF111.jsonl.

import random

import toyir
from dominance_frontier_computation import (
    dominance_frontiers,
    dominance_frontiers_walk,
    immediate_dominators,
    iterated_dominance_frontier,
    program_frontiers,
    program_graph,
)

ODD_SUM = """
# params: n
B1:
  i = 0
  s = 0
  jump B2
B2:
  t1 = i < n
  br t1 B3 B6
B3:
  t2 = i % 2
  br t2 B4 B5
B4:
  s = s + i
  jump B5
B5:
  i = i + 1
  jump B2
B6:
  ret s
"""


# ------------------------------------------------------------ brute force


def _reach(succ, root, removed=None):
    if root == removed:
        return set()
    seen = {root}
    stack = [root]
    while stack:
        v = stack.pop()
        for w in succ[v]:
            if w != removed and w not in seen:
                seen.add(w)
                stack.append(w)
    return seen


def brute_dominators(succ, root):
    """D[v] = the set of dominators of v: d dominates v if removing d cuts v off."""
    nodes = _reach(succ, root)
    dom = {v: set() for v in nodes}
    for d in nodes:
        left = _reach(succ, root, d)
        for v in nodes:
            if v not in left:
                dom[v].add(d)
    return dom


def brute_frontiers(succ, root):
    """DF by the definition: x dom p for an edge (p, y), and not x sdom y."""
    dom = brute_dominators(succ, root)
    df = {v: set() for v in dom}
    for p in dom:
        for y in succ[p]:
            for x in dom[p]:
                if not (x in dom[y] and x != y):
                    df[x].add(y)
    return df


def brute_idf(df, s):
    """DF+ as the limit of DF_1 = DF(S), DF_(i+1) = DF(S + DF_i)."""
    cur = set()
    while True:
        nxt = set()
        for x in set(s) | cur:
            nxt |= df[x]
        if nxt == cur:
            return cur
        cur = nxt


def random_graph(rng, n):
    succ = {v: [] for v in range(n)}
    for _ in range(rng.randint(0, 3 * n)):
        a, b = rng.randrange(n), rng.randrange(n)
        if b not in succ[a]:
            succ[a].append(b)
    for v in range(1, n):
        if rng.random() < 0.8:
            a = rng.randrange(v)
            if v not in succ[a]:
                succ[a].append(v)
    return succ


def ladder(n):
    """n nested repeat-until loops: headers h, latches l, exit e."""
    succ = {}
    for i in range(1, n + 1):
        succ["h%d" % i] = ["h%d" % (i + 1)] if i < n else ["l%d" % n]
        succ["l%d" % i] = ["h%d" % i] + (["l%d" % (i - 1)] if i > 1 else ["e"])
    succ["e"] = []
    return succ


# ------------------------------------------------------------------ tests


def test_page_example():
    succ, root = program_graph(toyir.parse(ODD_SUM))
    want = {"B1": set(), "B2": {"B2"}, "B3": {"B2"}, "B4": {"B5"}, "B5": {"B2"}, "B6": set()}
    assert dominance_frontiers(succ, root) == want
    assert dominance_frontiers_walk(succ, root) == want
    df = dominance_frontiers(succ, root)
    assert iterated_dominance_frontier(df, {"B1", "B4"}) == {"B2", "B5"}
    assert iterated_dominance_frontier(df, {"B1", "B5"}) == {"B2"}


def test_idom_matches_brute_force():
    rng = random.Random(1)
    for _ in range(300):
        succ = random_graph(rng, rng.randint(1, 9))
        idom = immediate_dominators(succ, 0)
        dom = brute_dominators(succ, 0)
        assert set(idom) == set(dom)
        for v, d in idom.items():
            if v == 0:
                assert d is None
            else:
                # the immediate dominator is the strict dominator with the most dominators
                strict = dom[v] - {v}
                assert d == max(strict, key=lambda u: len(dom[u]))


def test_random_graphs():
    rng = random.Random(2)
    for _ in range(600):
        succ = random_graph(rng, rng.randint(1, 10))
        want = brute_frontiers(succ, 0)
        assert dominance_frontiers(succ, 0) == want
        assert dominance_frontiers_walk(succ, 0) == want


def test_random_programs():
    rng = random.Random(3)
    for k in range(300):
        prog = toyir.random_program(rng, 6, 8, acyclic=(k % 3 == 0))
        succ, root = program_graph(prog)
        want = brute_frontiers(succ, root)
        assert program_frontiers(prog) == want
        assert dominance_frontiers_walk(succ, root) == want


def test_iterated_frontier():
    rng = random.Random(4)
    for _ in range(400):
        n = rng.randint(1, 10)
        succ = random_graph(rng, n)
        df = dominance_frontiers(succ, 0)
        nodes = list(df)
        s = set(rng.sample(nodes, rng.randint(1, len(nodes))))
        got = iterated_dominance_frontier(df, s)
        assert got == brute_idf(df, s)
        # DF+ is closed: DF(S + DF+) is inside DF+
        closed = set()
        for x in s | got:
            closed |= df[x]
        assert closed <= got


def test_quadratic_family():
    for n in range(1, 12):
        succ = ladder(n)
        df = dominance_frontiers(succ, "h1")
        assert df == dominance_frontiers_walk(succ, "h1")
        assert len(df) == 2 * n + 1
        assert sum(len(x) for x in succ.values()) == 3 * n
        assert sum(len(x) for x in df.values()) == n * (n + 1)
        for i in range(1, n + 1):
            want = {"h%d" % j for j in range(1, i + 1)}
            assert df["h%d" % i] == want and df["l%d" % i] == want
        phis = sum(len(iterated_dominance_frontier(df, {"h1", "l%d" % i})) for i in range(1, n + 1))
        assert phis == n * (n + 1) // 2


def test_entry_with_predecessors():
    # The back edge 2 -> 0 enters the root, which has one predecessor.
    succ = {0: [1], 1: [2], 2: [0]}
    want = {0: {0}, 1: {0}, 2: {0}}
    assert brute_frontiers(succ, 0) == want
    assert dominance_frontiers(succ, 0) == want
    assert dominance_frontiers_walk(succ, 0) == want


def test_unreachable_nodes_are_ignored():
    succ = {0: [1], 1: [], 2: [1]}
    df = dominance_frontiers(succ, 0)
    assert df == {0: set(), 1: set()}
    assert dominance_frontiers_walk(succ, 0) == df

History

Cytron, Ferrante, Rosen, Wegman and Zadeck defined the dominance frontier and gave the bottom-up algorithm in their POPL 1989 paper on computing SSA form, and in full in the 1991 TOPLAS paper, which also used the reverse graph for control dependence. Sreedhar and Gao (1995) showed that the iterated frontier can be found in linear time with DJ-graphs. Cooper, Harvey and Kennedy published the walk from the predecessors with their simple iterative dominator algorithm, at Rice University in 2001, and it became a common choice in textbooks and compilers.

References

  1. Ron Cytron, Jeanne Ferrante, Barry K. Rosen, Mark N. Wegman and F. Kenneth Zadeck, Efficiently computing static single assignment form and the control dependence graph, ACM Transactions on Programming Languages and Systems 13(4), 1991, pages 451-490, the definition of DF_local and DF_up, the lemmas that give DF from them, the bottom-up algorithm over the dominator tree, and its cost in the size of the frontiers
  2. Keith D. Cooper, Timothy J. Harvey and Ken Kennedy, A simple, fast dominance algorithm, technical report, Department of Computer Science, Rice University, the dominance frontier algorithm that walks from each predecessor of a join node up to its immediate dominator
  3. Vugranam C. Sreedhar and Guang R. Gao, A linear time algorithm for placing phi-nodes, Proceedings of the 22nd ACM Symposium on Principles of Programming Languages (POPL), 1995, pages 62-73, DJ-graphs, and the iterated dominance frontier in linear time without computing the frontiers
  4. Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 19 (Static Single-Assignment Form), the computation of the dominance frontier by DF_local and DF_up
  5. Fabrice Rastello and Florent Bouchez Tichadou (editors), SSA-based Compiler Design, Springer, 2022, Chapter 3 (Standard Construction and Destruction Algorithms), the computation of dominance frontiers; Chapter 4 (Advanced Construction Algorithms for SSA), DJ-graphs and merge sets

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • 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