Algorithm Search⌘K

Data structurecore

Program dependence graph

Also called PDG.

A graph of the statements of a procedure with edges for data and control dependences, used for slicing, vectorization and scheduling.

Time
O(m + c) control-edgesO(n (n + m) r) data-edgesO(n + c + d) slice
Space
O(n + m + c + d) total
Where
c = the number of control dependence edges; d = the number of flow dependence edges; m = the number of CFG edges; n = the number of instructions; r = the number of definitions
Origin
Jeanne Ferrante, Karl J. Ottenstein, Joe D. Warren, 1987

A program dependence graph (PDG) has one node for each instruction of a procedure and two kinds of edges. A data edge goes from an instruction that defines a variable to an instruction that may read that value. A control edge goes from a branch to an instruction whose execution the branch decides. The control flow graph fixes one order for the instructions; the PDG keeps only the order that the meaning of the program needs. So two instructions with no path between them in the PDG can be reordered or run in parallel, and the instructions that can affect a given one are its ancestors. Ferrante, Ottenstein and Warren (1987) built the control edges from post-dominance, and the PDG is the basis of program slicing, aggressive dead code elimination and dependence-based vectorization.

In plain words

A recipe is written as a list of steps, but many steps do not need the step before them. You can chop the onions while the water boils. The PDG draws only the real needs. An arrow from step A to step B means B uses something A made, or B happens only if a test in A came out a certain way. Any order that follows the arrows cooks the same dish. To find every step that can change the taste of the sauce, follow the arrows backward from the sauce.

The abstract type

The PDG of a procedure is a directed graph with these parts:

  • Nodes. One node for each instruction, with the terminator of each block counted as an instruction, and one node ENTRY that stands for the start of the procedure and the definitions of the parameters.
  • Control edges (x,y,ℓ)(x, y, \ell): instruction yy is control dependent on the branch xx through the edge of xx to the block ℓ\ell. The label ℓ\ell is the outcome of the branch that makes yy run. Instructions that run on every run of the procedure depend on ENTRY.
  • Data edges (d,u,v)(d, u, v): the definition of variable vv at dd reaches the instruction uu, which reads vv. These are the flow (true) dependences of data dependence. Anti and output dependences are added when the PDG is used to reorder memory operations, as described under Variants.

It supports these operations:

  • BUILD(procedure): make the graph.
  • CONTROL-PARENTS(yy) and DATA-PARENTS(yy): the edges into yy.
  • CHILDREN(xx): the edges out of xx.
  • SLICE(yy): all nodes from which yy is reachable, the backward slice of yy.

Representation

Each node has two lists of incoming edges and two lists of outgoing edges, one of each for control and for data. An instruction node is a pair (block, index), where the index equal to the number of instructions in the block names the terminator. The block-level control dependences are kept as well: every instruction of a block has the same control parents, so the per-instruction control edges are the block edges copied to each instruction.

Ferrante, Ottenstein and Warren add region nodes. All instructions that have the same set of control parents with the same labels hang below one region node, and the region node carries the control edges. This saves space when many instructions share their conditions, and it gives a tree of regions that a code generator can walk to put the instructions back into a control flow graph.

Operations

  1. BUILD(P) ▷ P: a procedure with blocks, an entry block, ret terminators
  2. 1G ← the CFG of P, with a node START, a node EXIT,
  3. an edge START → entry, an edge START → EXIT, and an edge to EXIT from every ret block
  4. 2ipdom ← immediate post-dominators of G ▷ dominators of the reverse of G, rooted at EXIT
  5. 3for each edge a → b of G with b ≠ ipdom(a) do
  6. 4y ← b
  7. 5while y ≠ ipdom(a) do
  8. 6src ← ENTRY if a = START, else the terminator of a
  9. 7for each instruction i of block y: add control edge (src, i, b)
  10. 8y ← ipdom(y)
  11. 9IN ← reaching definitions of P, with the parameters defined at ENTRY
  12. 10for each block B do
  13. 11cur ← IN[B], grouped by variable
  14. 12for each instruction u of B, in order, terminator last do
  15. 13for each variable v that u reads, each d in cur[v]: add data edge (d, u, v)
  16. 14if u defines v then cur[v] ← {u}
  17. SLICE(y)
  18. 15S ← {y}; stack ← [y]
  19. 16while stack is not empty do
  20. 17z ← pop(stack)
  21. 18for each control or data edge (x, z, ·) into z with x ∉ S: add x to S, push x
  22. 19return S

Control edges (L1 to L8). Line L1 builds the augmented CFG of control dependence. The edge START → EXIT makes the blocks that run on every run depend on START, which the PDG shows as ENTRY. Line L2 computes the post-dominator tree, for example with the Cooper-Harvey-Kennedy iteration on the transpose graph. Lines L3 to L8 are the walk of Ferrante, Ottenstein and Warren: for each edge a→ba \to b, the blocks that depend on aa through it are the blocks on the post-dominator tree path from bb up to ipdom(a)\mathrm{ipdom}(a), with ipdom(a)\mathrm{ipdom}(a) left out. A block whose terminator is jump has one successor, which is its immediate post-dominator, so only the terminators br get children. A block can depend on its own terminator when it is a loop test.

Data edges (L9 to L14). Line L9 solves reaching definitions, a forward gen-kill problem. Lines L10 to L14 then walk each block once. The set cur[v]\mathit{cur}[v] holds the definitions of vv that reach the current point. A definition inside the block replaces it, so a use after a definition in the same block gets one edge. These edges are the def-use chains of the procedure.

Slicing (L15 to L19). A backward slice is plain reachability over the reversed edges. It is the method of PDG slicing, and its result is a set of instructions that can affect yy.

Example

Take the toy IR program that adds the odd numbers below the parameter 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

The PDG has 13 nodes: ENTRY and 12 instructions. The block-level control dependences, worked out on the control dependence page, are B1, B2 and B6 on START, B2, B3 and B5 on the branch of B2 with label B3, and B4 on the branch of B3 with label B4. Copied to the instructions, they give 14 control edges:

from to label
ENTRY i = 0, s = 0, jump B2 (B1), t1 = i < n, br t1 B3 B6 (B2), ret s (B6) B1
br t1 B3 B6 t1 = i < n, br t1 B3 B6 (B2), t2 = i % 2, br t2 B4 B5 (B3), i = i + 1, jump B2 (B5) B3
br t2 B4 B5 s = s + i, jump B5 (B4) B4

The 15 data edges are:

definition uses reached
i = 0 and i = i + 1 t1 = i < n, t2 = i % 2, s = s + i, i = i + 1 (8 edges)
s = 0 and s = s + i s = s + i, ret s (4 edges)
ENTRY (parameter n) t1 = i < n
t1 = i < n br t1 B3 B6
t2 = i % 2 br t2 B4 B5

The slice of ret s holds ENTRY and every instruction except the three jumps: the jumps define nothing and decide nothing. The slice of i = i + 1 is ENTRY, i = 0, i = i + 1, t1 = i < n and br t1 B3 B6, so the computation of s and the parity test do not affect i. The loop test br t1 B3 B6\texttt{br t1 B3 B6} is its own control parent, which is how the PDG shows that it runs again on each trip.

Correctness

The PDG is correct when its control edges are exactly the control dependences of Ferrante, Ottenstein and Warren, copied to the instructions, and its data edges are exactly the pairs (definition, use) joined by a path with no other definition of the same variable. The proof in proofs/correctness.md shows both. For the control edges it shows that the walk at an edge a→ba \to b visits exactly the nodes that bb post-dominates and that do not strictly post-dominate aa. For the data edges it shows that the least solution of the reaching definitions equations holds exactly the definitions with such a definition-clear path, and that the scan of lines L10 to L14 adds the same pairs at instruction level. The tests compare the control edges with a brute-force search over the paths of the definition on random graphs, and the data edges with a search over instruction positions on random programs.

Proof: BUILD gives exactly the control dependences and the flow dependencesfull

We use the notation of the page. GG is the augmented CFG of line L1, xx is EXIT, and every node of GG reaches xx. Post-dominance and ipdom\mathrm{ipdom} are taken in GG. The facts about the post-dominator tree that we use are those of the post-dominance page: the post-dominators of a node vv are exactly the ancestors of vv in the tree, with vv itself, and the strict post-dominators of v≠xv \ne x are ipdom(v)\mathrm{ipdom}(v) and its ancestors.

Part 1: the control edges

Definition. Block YY is control dependent on block XX through the edge X→SX \to S if Y  pdom  SY \;\mathrm{pdom}\; S and YY does not strictly post-dominate XX. The control dependence page proves that this edge form is equivalent to the path form of Ferrante, Ottenstein and Warren.

Lemma 1. For every edge a→ba \to b of GG, ipdom(a)\mathrm{ipdom}(a) post-dominates bb.

Proof. The node aa has a successor, so a≠xa \ne x and ipdom(a)\mathrm{ipdom}(a) exists. Let QQ be a path from bb to xx. Then aa followed by QQ is a path from aa to xx, so it contains ipdom(a)\mathrm{ipdom}(a). Since ipdom(a)≠a\mathrm{ipdom}(a) \ne a, the node is on QQ. □\square

Lemma 2. For an edge a→ba \to b, the set D(a,b)={Y:Y  pdom  b and Y does not strictly post-dominate a}D(a, b) = \{Y : Y \;\mathrm{pdom}\; b \text{ and } Y \text{ does not strictly post-dominate } a\} is the set of nodes on the tree path from bb up to ipdom(a)\mathrm{ipdom}(a), with ipdom(a)\mathrm{ipdom}(a) left out. In particular it is empty when b=ipdom(a)b = \mathrm{ipdom}(a).

Proof. Y  pdom  bY \;\mathrm{pdom}\; b holds iff YY is bb or an ancestor of bb. YY strictly post-dominates aa iff YY is ipdom(a)\mathrm{ipdom}(a) or an ancestor of it. By Lemma 1, ipdom(a)\mathrm{ipdom}(a) is bb or an ancestor of bb. So the ancestors of bb (with bb) fall into two parts: those strictly below ipdom(a)\mathrm{ipdom}(a) on the path from bb, and ipdom(a)\mathrm{ipdom}(a) with its ancestors. The first part is D(a,b)D(a, b). □\square

Claim 1. Lines L3 to L8 add the control edge (src(a),i,b)(\mathit{src}(a), i, b) for an instruction ii of block YY exactly when YY is control dependent on aa through a→ba \to b, where src(a)\mathit{src}(a) is ENTRY if aa is START and the terminator of aa otherwise.

Proof. If b=ipdom(a)b = \mathrm{ipdom}(a), line L3 skips the edge, and D(a,b)D(a, b) is empty by Lemma 2. Otherwise the loop of lines L5 to L8 starts at bb and moves to the parent in the tree until it meets ipdom(a)\mathrm{ipdom}(a). It meets it, because ipdom(a)\mathrm{ipdom}(a) is an ancestor of bb by Lemma 1, and each step moves one level up. So the loop body runs for exactly the nodes of D(a,b)D(a, b), and line L7 adds the edges for all instructions of each of them. The node EXIT is never in D(a,b)D(a, b) for a≠xa \ne x, since it strictly post-dominates every other node, so line L7 always finds a real block. □\square

Every instruction of a block runs exactly when the block runs, so giving all of them the control parents of the block is the instruction-level form of the same relation.

Part 2: the data edges

A position is an instruction of a block, the terminator included. A definition dd of vv at a position, or of a parameter vv at ENTRY, reaches a position uu if there is a path in the CFG from just after dd to uu on which no position before uu defines vv. For ENTRY, the path starts at the first position of the entry block. The specification is: (d,u,v)(d, u, v) is a data edge iff uu reads vv and the definition dd of vv reaches uu.

The equations. For a block BB, let gen(B)\mathrm{gen}(B) be the last definition in BB of each variable that BB defines, and kill(B)\mathrm{kill}(B) the set of variables that BB defines. The code computes, by round-robin iteration from IN=∅\mathrm{IN} = \emptyset and OUT(B)=gen(B)\mathrm{OUT}(B) = \mathrm{gen}(B),

IN(B)=bnd(B)∪⋃P→BOUT(P),OUT(B)=gen(B)∪{(d,v)∈IN(B):v∉kill(B)},\mathrm{IN}(B) = \mathit{bnd}(B) \cup \bigcup_{P \to B} \mathrm{OUT}(P), \qquad \mathrm{OUT}(B) = \mathrm{gen}(B) \cup \{(d, v) \in \mathrm{IN}(B) : v \notin \mathrm{kill}(B)\},

where bnd(B)\mathit{bnd}(B) is the set of parameter definitions at ENTRY if BB is the entry block and empty otherwise.

Lemma 3. The iteration stops, and then (d,v)∈IN(B)(d, v) \in \mathrm{IN}(B) iff the definition dd of vv reaches the first position of BB.

Proof. The right-hand sides are monotone in the sets, the sets only grow from their start values, and they are subsets of a finite set of pairs, so the iteration stops. Let R(B)R(B) be the set of pairs (d,v)(d, v) such that dd reaches the first position of BB.

(R⊆INR \subseteq \mathrm{IN}.) Take (d,v)∈R(B)(d, v) \in R(B) with a witness path, and use induction on the number of blocks that the path enters after dd. If dd is a parameter and the path is empty, BB is the entry and (d,v)∈bnd(B)(d, v) \in \mathit{bnd}(B). If dd is in block PP and the next block is BB, then dd is the last definition of vv in PP, because the path after dd to the end of PP has no definition of vv, so (d,v)∈gen(P)⊆OUT(P)⊆IN(B)(d, v) \in \mathrm{gen}(P) \subseteq \mathrm{OUT}(P) \subseteq \mathrm{IN}(B). Otherwise the path enters a block PP before BB and crosses all of it without defining vv. By induction (d,v)∈IN(P)(d, v) \in \mathrm{IN}(P), and v∉kill(P)v \notin \mathrm{kill}(P), so (d,v)∈OUT(P)⊆IN(B)(d, v) \in \mathrm{OUT}(P) \subseteq \mathrm{IN}(B). These inclusions hold at the fixpoint because it satisfies the equations.

(IN⊆R\mathrm{IN} \subseteq R.) Every value that the iteration produces is in RR, by induction on the steps. The start values are empty or are gen(B)\mathrm{gen}(B), and a pair (d,v)(d, v) of gen(P)\mathrm{gen}(P) reaches the start of every successor of PP. A pair that enters IN(B)\mathrm{IN}(B) comes from bnd(B)\mathit{bnd}(B), which is in R(B)R(B), or from some OUT(P)\mathrm{OUT}(P) with P→BP \to B. A pair of OUT(P)\mathrm{OUT}(P) is in gen(P)\mathrm{gen}(P), or it is in IN(P)⊆R(P)\mathrm{IN}(P) \subseteq R(P) with v∉kill(P)v \notin \mathrm{kill}(P), so its witness path extends through PP and the edge P→BP \to B without a new definition of vv. □\square

Claim 2. Lines L10 to L14 add (d,u,v)(d, u, v) iff uu reads vv and dd reaches uu.

Proof. Fix a block BB. The invariant of the loop of line L12 is: before position uu, the set cur[v]\mathit{cur}[v] is the set of definitions of vv that reach uu. Before the first position this is Lemma 3, because line L11 groups IN(B)\mathrm{IN}(B). If position uu does not define vv, a definition reaches the next position iff it reaches uu, since the path can be extended by one step and no new definition of vv is crossed. If uu defines vv, the only definition of vv that reaches the next position is uu itself, because every path from an earlier definition passes uu. Line L14 sets cur[v]={u}\mathit{cur}[v] = \{u\}, which keeps the invariant. Line L13 runs before line L14, so a use of vv in an instruction that also defines vv, such as i = i + 1, gets the definitions that reach it from before. The loop adds exactly the triples of the claim at each position. □\square

Claims 1 and 2 together say that the graph built by BUILD has exactly the control edges and the flow dependence edges of its definition. SLICE returns the nodes from which yy is reachable along these edges, by the usual argument for a graph search: every node it adds has a path to yy, and every node with a path to yy is added when the last edge of its path is examined. □\square

Complexity

The model is the word RAM, and the unit step is one operation on a hash set or list with one element. Let nn be the number of instructions, mm the number of CFG edges, cc the number of control edges and dd the number of data edges.

  • Post-dominators. The Cooper-Harvey-Kennedy iteration is fast in practice, and the Lengauer-Tarjan algorithm takes O(mα(m,n))O(m \alpha(m, n)) time.
  • Control edges. Each step of the walk adds at least one new edge, so lines L3 to L8 take O(m+c)O(m + c). The number cc can be Θ(n2)\Theta(n^2): the control dependence page has a chain with back edges where kk blocks give k(k+1)/2k(k+1)/2 dependences. Region nodes reduce the stored edges in common cases, but not in the worst case.
  • Data edges. With rr definitions, each round of the reaching definitions iteration costs O((n+m)r)O((n + m) r), and a round-robin iteration needs at most n+1n + 1 rounds, so the worst case is O(n(n+m)r)O(n (n + m) r). Visiting the blocks in reverse postorder needs only a few rounds on usual code. The scan of lines L10 to L14 costs O(n+d)O(n + d) beyond that. The number dd can also be quadratic: kk definitions of one variable that all reach kk uses give k2k^2 edges.
  • Space. O(n+m+c+d)O(n + m + c + d).
  • Queries. With adjacency lists, CONTROL-PARENTS and DATA-PARENTS cost O(1)O(1) per edge returned, and SLICE costs O(n+c+d)O(n + c + d).

Variants

  • Region nodes. As in the original paper, an extra node per set of equal control conditions.
  • System dependence graph. Horwitz, Reps and Binkley (1990) join one PDG per procedure with call, parameter-in and parameter-out edges, plus summary edges, so that slicing across calls can respect calling context. See system dependence graph slicing.
  • All data dependences. For reordering, the data edges must include anti dependences (a read before a write) and output dependences (two writes), and the dependences through memory, which need alias information. Loop-carried dependences with distance and direction vectors are the input of loop vectorization and parallelization.
  • SSA-based PDG. On static single assignment form, each use has one reaching definition, so data edges are the SSA def-use edges and reaching definitions is not needed. The sea of nodes carries this idea further and drops the blocks.
  • Weak control dependence. Some tools use the weak form of Podgurski and Clarke, so that code after a loop depends on the loop test, which keeps non-termination in slices.

When to use it

Use a PDG when the question is "what can affect this" or "what can move": slicing for debugging and program understanding, dead code removal that starts from the outputs and keeps only what they need, finding statements that can run in parallel, and vectorization, where cycles of dependences inside a loop decide which statements can be vectorized. For plain forward data flow analyses a CFG is simpler, and for most scalar optimizations SSA with def-use chains gives the data edges at lower cost.

Pitfalls

  • Forgetting the edge START → EXIT. Without it, blocks that always run have no control parent, and a slice of them misses the dependence on the procedure being called at all.
  • Several returns or no return. The post-dominator tree needs one exit, so add EXIT with an edge from each return. A loop that never exits leaves blocks that do not reach EXIT, and the walk then has no immediate post-dominator for them. Add a fake exit edge first.
  • Flow edges are not enough to reorder. Two writes to the same variable have no flow edge between them, but they cannot be swapped. Add anti and output edges before reordering.
  • Jumps disappear from slices. A slice is a set of instructions, not a program. To run a slice, the jumps and the block structure must be rebuilt, for example from the region tree.
  • Memory. Data edges through loads and stores depend on alias analysis. An edge left out makes a slice or a reordering wrong.

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.

program_dependence_graph.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/program-dependence-graph/. The authors are listed in prov/AK2XM4.jsonl.
"""The program dependence graph of a toy IR procedure.

Control dependence follows Ferrante, Ottenstein and Warren (1987): the CFG
gets a node START with edges to the entry block and to a node EXIT, and an
edge from every ret block to EXIT. For each edge (a, b) where b is not the
immediate post-dominator of a, the walk from b up the post-dominator tree to
ipdom(a), not included, gives the nodes that are control dependent on a
through the edge (a, b). Data dependence is flow dependence: an edge from a
definition to each use that it reaches, found by reaching definitions.

A PDG node is ("ENTRY",) for START and the parameters, or (label, i): the
instruction i of the block, where i = len(instrs) is the terminator.
"""

import toyir

START = "START"
EXIT = "EXIT"
ENTRY = ("ENTRY",)


def idoms(nodes, succ, root):
    """Immediate dominators by the Cooper-Harvey-Kennedy iteration.

    nodes: all nodes; succ: dict node -> list of nodes; root: the start.
    Returns a dict from each node that root reaches to its immediate
    dominator; root maps to itself.
    """
    po, seen, stack = {}, {root}, [(root, iter(succ[root]))]
    while stack:
        v, it = stack[-1]
        w = next(it, None)
        if w is None:
            po[v] = len(po)
            stack.pop()
        elif w not in seen:
            seen.add(w)
            stack.append((w, iter(succ[w])))
    pred = {v: [] for v in nodes}
    for v in nodes:
        for w in succ[v]:
            pred[w].append(v)
    order = sorted(po, key=lambda v: -po[v])
    dom = {root: root}

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

    changed = True
    while changed:
        changed = False
        for b in order[1:]:
            ps = [p for p in pred[b] if p in dom]
            new = ps[0]
            for p in ps[1:]:
                new = intersect(p, new)
            if dom.get(b) != new:
                dom[b] = new
                changed = True
    return dom


def augmented_cfg(prog):
    """The CFG with START and EXIT, as (nodes, succ). The edge START -> EXIT
    makes the blocks that run on every run control dependent on START."""
    nodes = [START] + list(prog.blocks) + [EXIT]
    succ = {START: [prog.entry, EXIT], EXIT: []}
    for label in prog.blocks:
        s = toyir.succs(prog, label)
        succ[label] = s if s else [EXIT]
    return nodes, succ


def post_dominator_tree(nodes, succ, exit_node):
    """ipdom as a dict: dominators of the reversed graph, rooted at the exit."""
    rsucc = {v: [] for v in nodes}
    for v in nodes:
        for w in succ[v]:
            rsucc[w].append(v)
    return idoms(nodes, rsucc, exit_node)


def control_dependences(nodes, succ, exit_node):
    """The set of triples (x, y, s): y is control dependent on x through the
    edge x -> s. Every node must reach exit_node."""
    ipdom = post_dominator_tree(nodes, succ, exit_node)
    out = set()
    for a in nodes:
        for b in succ[a]:
            if b == ipdom.get(a):
                continue
            runner = b
            while runner != ipdom[a]:
                out.add((a, runner, b))
                runner = ipdom[runner]
    return out


def block_control_dependences(prog):
    nodes, succ = augmented_cfg(prog)
    return control_dependences(nodes, succ, EXIT)


def reaching_definitions(prog):
    """IN sets per block: sets of (node, var). The parameters are defined at
    ENTRY."""
    gen, kill_vars = {}, {}
    for label, b in prog.blocks.items():
        last = {}
        for i, ins in enumerate(b.instrs):
            d = toyir.defs(ins)
            if d is not None:
                last[d] = (label, i)
        gen[label] = {(n, v) for v, n in last.items()}
        kill_vars[label] = set(last)
    preds = toyir.preds(prog)
    inn = {label: set() for label in prog.blocks}
    out = {label: set(gen[label]) for label in prog.blocks}
    boundary = {(ENTRY, p) for p in prog.params}
    changed = True
    while changed:
        changed = False
        for label in prog.blocks:
            s = set(boundary) if label == prog.entry else set()
            for p in preds[label]:
                s |= out[p]
            inn[label] = s
            o = gen[label] | {(n, v) for (n, v) in s if v not in kill_vars[label]}
            if o != out[label]:
                out[label] = o
                changed = True
    return inn


def data_dependences(prog):
    """The set of triples (d, u, v): the definition of v at node d reaches the
    node u, which reads v."""
    inn = reaching_definitions(prog)  # @line L9
    out = set()
    for label, b in prog.blocks.items():  # @line L10
        cur = {}
        for n, v in inn[label]:  # @line L11
            cur.setdefault(v, set()).add(n)
        items = list(b.instrs) + [b.term]
        for i, ins in enumerate(items):  # @line L12
            used = toyir.term_uses(ins) if i == len(b.instrs) else toyir.uses(ins)
            for v in used:
                for d in cur.get(v, ()):
                    out.add((d, (label, i), v))  # @line L13
            if i < len(b.instrs):
                d = toyir.defs(ins)
                if d is not None:
                    cur[d] = {(label, i)}  # @line L14
    return out


class PDG:
    """The nodes and the two kinds of edges.

    block_cd: set of (x, y, s): block y is control dependent on x through the
    CFG edge x -> s; x may be START.
    control: set of (x, y, s): node y is control dependent on the branch
    node x, through the CFG edge to block s; x is ENTRY for START.
    data: set of (d, u, v), flow dependences.
    """

    def __init__(self, prog):
        self.prog = prog
        self.nodes = [ENTRY]
        for label, b in prog.blocks.items():
            self.nodes += [(label, i) for i in range(len(b.instrs) + 1)]
        nodes, succ = augmented_cfg(prog)  # @line L1
        ipdom = post_dominator_tree(nodes, succ, EXIT)  # @line L2
        self.block_cd, self.control = set(), set()
        for a in nodes:
            for b in succ[a]:  # @line L3
                if b == ipdom.get(a):
                    continue
                y = b  # @line L4
                while y != ipdom[a]:  # @line L5
                    src = ENTRY if a == START else (a, len(prog.blocks[a].instrs))  # @line L6
                    self.block_cd.add((a, y, b))
                    for i in range(len(prog.blocks[y].instrs) + 1):
                        self.control.add((src, (y, i), b))  # @line L7
                    y = ipdom[y]  # @line L8
        self.data = data_dependences(prog)

    def control_parents(self, node):
        return {(x, s) for x, y, s in self.control if y == node}

    def data_parents(self, node):
        return {(d, v) for d, u, v in self.data if u == node}

    def slice(self, node):
        """The backward slice: every node from which node is reachable."""
        into = {}
        for x, y, _ in self.control:
            into.setdefault(y, []).append(x)
        for d, u, _ in self.data:
            into.setdefault(u, []).append(d)
        seen, stack = {node}, [node]  # @line L15
        while stack:  # @line L16
            z = stack.pop()  # @line L17
            for x in into.get(z, ()):  # @line L18
                if x not in seen:
                    seen.add(x)
                    stack.append(x)
        return seen  # @line L19
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_program_dependence_graph.py 249 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/program-dependence-graph/. The authors are listed in prov/AK2XM4.jsonl.

import random

import toyir
from program_dependence_graph import (
    ENTRY,
    EXIT,
    PDG,
    START,
    augmented_cfg,
    block_control_dependences,
    control_dependences,
    data_dependences,
)

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
"""


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


def reaches(succ, a, b, banned):
    """Does a reach b without passing through banned?"""
    if a == banned:
        return False
    seen, stack = {a}, [a]
    while stack:
        v = stack.pop()
        if v == b:
            return True
        for w in succ[v]:
            if w != banned and w not in seen:
                seen.add(w)
                stack.append(w)
    return False


def pdom(succ, exit_node, y, z):
    """y post-dominates z: every path from z to the exit contains y."""
    return y == z or not reaches(succ, z, exit_node, y)


def cd_by_paths(nodes, succ, exit_node):
    """Control dependence by the path definition of Ferrante, Ottenstein and
    Warren: y is control dependent on x through the edge x -> s if a path
    x, s, ..., y exists on which y post-dominates every node after x, and y
    does not strictly post-dominate x. The paths are enumerated."""
    pd = {(y, z): pdom(succ, exit_node, y, z) for y in nodes for z in nodes}
    out = set()
    for x in nodes:
        for s in succ[x]:
            for y in nodes:
                if y != x and pd[(y, x)]:
                    continue  # y strictly post-dominates x

                def walk(z, seen):
                    if not pd[(y, z)]:
                        return False
                    if z == y:
                        return True
                    for w in succ[z]:
                        if w not in seen and walk(w, seen | {w}):
                            return True
                    return False

                if walk(s, {s}):
                    out.add((x, y, s))
    return out


def dd_by_paths(prog):
    """Flow dependences by search over instruction positions: the definition
    of v at d reaches the use u if some path from just after d to u has no
    other definition of v."""
    pos = {}
    for label, b in prog.blocks.items():
        pos[label] = list(b.instrs) + [b.term]

    def after(node):
        label, i = node
        if i < len(pos[label]) - 1:
            return [(label, i + 1)]
        return [(s, 0) for s in toyir.succs(prog, label)]

    def reads(node):
        label, i = node
        ins = pos[label][i]
        return toyir.term_uses(ins) if i == len(pos[label]) - 1 else toyir.uses(ins)

    def writes(node):
        label, i = node
        if i == len(pos[label]) - 1:
            return None
        return toyir.defs(pos[label][i])

    defs = [(ENTRY, p, [(prog.entry, 0)]) for p in prog.params]
    for label in prog.blocks:
        for i in range(len(pos[label]) - 1):
            v = writes((label, i))
            if v is not None:
                defs.append(((label, i), v, after((label, i))))
    out = set()
    for d, v, starts in defs:
        seen, stack = set(starts), list(starts)
        while stack:
            n = stack.pop()
            if v in reads(n):
                out.add((d, n, v))
            if writes(n) == v:
                continue
            for w in after(n):
                if w not in seen:
                    seen.add(w)
                    stack.append(w)
    return out


def random_cfg(rng, n):
    """A random digraph on 0 .. n-1 with entry 0, exit n-1 and a START node
    as in the PDG, kept only if every node is reachable and reaches the exit."""
    while True:
        succ = {v: [] for v in range(n)}
        for v in range(n - 1):
            k = rng.randint(1, 2)
            succ[v] = sorted(set(rng.randrange(n) for _ in range(k)))
        nodes = list(range(n)) + [START]
        succ[START] = [0, n - 1]
        ok = all(reaches(succ, START, v, None) and reaches(succ, v, n - 1, None) for v in range(n))
        if ok:
            return nodes, succ


# ------------------------------------------------------------ the page example


def test_page_example_control():
    prog = toyir.parse(ODD_SUM)
    cd = {(x, y) for x, y, s in block_control_dependences(prog)}
    assert cd == {
        (START, "B1"), (START, "B2"), (START, "B6"),
        ("B2", "B2"), ("B2", "B3"), ("B2", "B5"),
        ("B3", "B4"),
    }
    labelled = {(x, y, s) for x, y, s in block_control_dependences(prog) if x == "B3"}
    assert labelled == {("B3", "B4", "B4")}


def test_page_example_data():
    prog = toyir.parse(ODD_SUM)
    dd = data_dependences(prog)
    names = {}
    for label, b in prog.blocks.items():
        for i, ins in enumerate(b.instrs):
            names[(label, i)] = toyir._show_instr(ins)
        names[(label, len(b.instrs))] = toyir._show_term(b.term)
    names[ENTRY] = "ENTRY"
    got = {(names[d], names[u], v) for d, u, v in dd}
    assert got == {
        ("i = 0", "t1 = i < n", "i"),
        ("i = 0", "t2 = i % 2", "i"),
        ("i = 0", "s = s + i", "i"),
        ("i = 0", "i = i + 1", "i"),
        ("i = i + 1", "t1 = i < n", "i"),
        ("i = i + 1", "t2 = i % 2", "i"),
        ("i = i + 1", "s = s + i", "i"),
        ("i = i + 1", "i = i + 1", "i"),
        ("ENTRY", "t1 = i < n", "n"),
        ("t1 = i < n", "br t1 B3 B6", "t1"),
        ("t2 = i % 2", "br t2 B4 B5", "t2"),
        ("s = 0", "s = s + i", "s"),
        ("s = 0", "ret s", "s"),
        ("s = s + i", "s = s + i", "s"),
        ("s = s + i", "ret s", "s"),
    }


def test_pdg_nodes_and_edges():
    prog = toyir.parse(ODD_SUM)
    g = PDG(prog)
    assert len(g.nodes) == 1 + 3 + 2 + 2 + 2 + 2 + 1
    # s = s + i is the first instruction of B4, which depends on the branch of B3.
    assert g.control_parents(("B4", 0)) == {(("B3", 1), "B4")}
    assert g.control_parents(("B6", 0)) == {(ENTRY, "B1")}
    assert g.control_parents(("B2", 1)) == {(ENTRY, "B1"), (("B2", 1), "B3")}
    assert g.data_parents(("B4", 0)) == {(("B1", 1), "s"), (("B4", 0), "s"), (("B1", 0), "i"), (("B5", 0), "i")}


def test_slices():
    prog = toyir.parse(ODD_SUM)
    g = PDG(prog)
    everything = set(g.nodes)
    jumps = {("B1", 2), ("B4", 1), ("B5", 1)}
    assert g.slice(("B6", 0)) == everything - jumps
    assert g.slice(("B5", 0)) == {ENTRY, ("B1", 0), ("B5", 0), ("B2", 0), ("B2", 1)}


def test_diamond():
    prog = toyir.parse("B0:\n  br a B1 B2\nB1:\n  x = 1\n  jump B3\nB2:\n  x = 2\n  jump B3\nB3:\n  ret x\n")
    cd = block_control_dependences(prog)
    assert cd == {(START, "B0", "B0"), (START, "B3", "B0"), ("B0", "B1", "B1"), ("B0", "B2", "B2")}


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


def test_control_dependence_random_cfgs():
    rng = random.Random(20261115)
    for _ in range(400):
        n = rng.randint(2, 7)
        nodes, succ = random_cfg(rng, n)
        assert control_dependences(nodes, succ, n - 1) == cd_by_paths(nodes, succ, n - 1)


def test_control_dependence_random_programs():
    rng = random.Random(7)
    for k in range(300):
        prog = toyir.random_program(rng, rng.randint(2, 4), rng.randint(1, 8), acyclic=(k % 2 == 0))
        nodes, succ = augmented_cfg(prog)
        expected = cd_by_paths(nodes, succ, EXIT)
        assert block_control_dependences(prog) == expected
        assert PDG(prog).block_cd == expected


def test_data_dependence_random_programs():
    rng = random.Random(11)
    for k in range(300):
        prog = toyir.random_program(rng, rng.randint(2, 5), rng.randint(1, 8), acyclic=(k % 3 == 0))
        assert data_dependences(prog) == dd_by_paths(prog)

History

Ferrante, Ottenstein and Warren (1987) defined the PDG as a common graph for control and data dependence, computed control dependence from the post-dominator tree, and showed its use for vectorization, code motion and node splitting. Horwitz, Reps and Binkley (1990) built the system dependence graph for slicing across procedures. Cytron et al. (1991) showed that control dependences are the reverse dominance frontiers, with the same algorithm that places phi-functions in SSA form. Later graph IRs, such as the sea of nodes of Click and Paleczny (1995), keep explicit dependence edges and drop the fixed order of a CFG in the same spirit.

References

  1. Jeanne Ferrante, Karl J. Ottenstein and Joe D. Warren, The program dependence graph and its use in optimization, ACM Transactions on Programming Languages and Systems 9(3), 1987, pages 319-349, the definition of the PDG, control dependence from the post-dominator tree, region nodes, and the uses for vectorization and code motion
  2. 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 section on the control dependence graph
  3. Susan Horwitz, Thomas Reps and David Binkley, Interprocedural slicing using dependence graphs, ACM Transactions on Programming Languages and Systems 12(1), 1990, pages 26-60, the system dependence graph, a PDG per procedure joined by call and parameter edges, and slicing by reachability
  4. Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, the chapter on dependence analysis and dependence graphs, the section on program dependence graphs
  5. James Stanier and Des Watson, Intermediate representations in imperative compilers, a survey, ACM Computing Surveys 45(3), 2013, the sections on graph-based intermediate representations and the PDG family

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.control-edges
  • a full proof of time.data-edges
  • a full proof of time.slice
  • a full proof of space.total
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)
WritingW4 complete
  • a review of the text: no review record reviews/AK2XM4/text.yaml