Algorithm Search⌘K

Algorithmcore

T1-T2 reduction

Also called Hecht-Ullman transformations.

Tests reducibility by removing self-loops and merging nodes with a single predecessor; the graph is reducible if one node remains.

Time
O(n^2 + m) worstΘ(n + m) best
Space
Θ(n + m) extra
Where
m = the number of edges; n = the number of vertices
Properties
deterministicofflineiterative

The T1-T2 reduction tests whether a control flow graph is a reducible flow graph. It uses two rules, the Hecht-Ullman transformations. T1 deletes a self-loop. T2 takes a node other than the entry that has exactly one predecessor and merges it into that predecessor. Apply the rules until neither applies. The graph is reducible if and only if one node is left, and the order of the steps does not change the answer. With a worklist the test takes O(n2+m)O(n^2 + m) time. The list of steps also tells in which order the regions of the graph collapse, which is what elimination data-flow methods use.

In plain words

Think of the flow graph as a map of rooms joined by one-way doors. Two moves are allowed. If a door leads from a room back into the same room, remove it. If a room other than the entrance can be entered from only one other room, knock down the wall between them, so they become one room; its doors out now leave from the bigger room. Keep making moves until none is possible. If only the entrance room is left, every loop in the program had one way in, and the graph is reducible. If several rooms are left, each of them can be entered from two or more places, and some loop has more than one way in. It does not matter which move you make first. You always end with the same answer.

The problem

Input. A flow graph G=(N,E,r)G = (N, E, r): a directed graph with nn vertices, mm edges and an entry vertex rr. Vertices that rr does not reach are ignored, and parallel edges count as one edge.

Output. The limit graph, which is the graph left when neither T1 nor T2 applies, and the list of steps. GG is reducible exactly when the limit graph has one vertex.

The rules. T1 deletes an edge (v,v)(v, v). T2 applies to a vertex v≠rv \ne r whose only predecessor is uu. It deletes vv and the edge (u,v)(u, v), and it replaces each edge (v,w)(v, w) by (u,w)(u, w). An edge (v,u)(v, u) becomes a self-loop on uu, which a later T1 removes. Reducibility itself is defined on the reducible flow graph page: the graph without its back edges, the edges (t,h)(t, h) where hh dominates tt, has no cycle.

The algorithm

A worklist WW holds the vertices that may need a step. A vertex whose sets change goes back on the list.

  1. T1-T2-REDUCE(G, r)
  2. 1keep the vertices that r reaches; succ[v], pred[v] <- sets of successors and predecessors
  3. 2W <- all kept vertices
  4. 3while W is not empty do
  5. 4v <- pop(W); if v was merged before, skip it
  6. 5if v is in succ[v] then
  7. 6T1: remove v from succ[v] and from pred[v]
  8. 7if v != r and pred[v] = {u} for one vertex u then
  9. 8T2: remove v from succ[u]
  10. 9for each w in succ[v] do
  11. 10replace v by u in pred[w]; add w to succ[u]
  12. 11delete v; push u and every w in succ[v] on W
  13. 12return the remaining graph; G is reducible if it has one vertex

Line L6 runs before line L7, so a vertex with a self-loop gets the loop removed and can then be merged in the same visit. Line L11 pushes exactly the vertices whose sets changed: uu lost an edge and gained others, and each moved successor ww has a new predecessor set, which may now have one element. A T1 changes only the sets of vv, and line L7 tests vv again at once.

In the implementation, the sets are Python sets, the steps are returned as tuples ("T1", v) and ("T2", v, u), and cfg_is_reducible runs the test on the blocks of a toy IR program.

Example

Take the nested loops of the natural loop page:

B0:
  i = 0
  s = 0
  jump B1
B1:
  t = i < n
  br t B2 B6
B2:
  j = 0
  jump B3
B3:
  u = j < i
  br u B4 B5
B4:
  s = s + j
  j = j + 1
  jump B3
B5:
  i = i + 1
  jump B1
B6:
  ret s

The edges are B0→B1B0 \to B1, B1→B2B1 \to B2, B1→B6B1 \to B6, B2→B3B2 \to B3, B3→B4B3 \to B4, B3→B5B3 \to B5, B4→B3B4 \to B3, B5→B1B5 \to B1. The worklist starts with B0 to B6 and pops the smallest first.

step rule what happens edges after the step
1 T2 B2 has only B1 before it; merge B2 into B1 B1→B3B1 \to B3 replaces B1→B2→B3B1 \to B2 \to B3
2 T2 B4 has only B3; merge B4 into B3 B4→B3B4 \to B3 becomes the self-loop B3→B3B3 \to B3
3 T1 remove B3→B3B3 \to B3 now B3 has only B1 before it
4 T2 merge B3 into B1 B1→B5B1 \to B5, B1→B6B1 \to B6
5 T2 B5 has only B1; merge B5 into B1 B5→B1B5 \to B1 becomes the self-loop B1→B1B1 \to B1
6 T1 remove B1→B1B1 \to B1 now B1 has only B0 before it
7 T2 merge B1 into B0 B0→B6B0 \to B6
8 T2 merge B6 into B0 no edges

One vertex is left, so the graph is reducible. The inner loop {B3,B4}\{B3, B4\} collapsed in steps 2 and 3, and the outer loop in steps 4 to 6. Each T1 marks the moment a whole loop has become one node.

Now take the smallest irreducible graph from the reducible flow graph page: r→Ar \to A, r→Br \to B, A→BA \to B, B→AB \to A, A→CA \to C, B→CB \to C. There is no self-loop, rr is the entry, and AA, BB and CC have two predecessors each. No step applies, and the limit graph is the whole graph with 4 vertices. The cycle A→B→AA \to B \to A can be entered at both AA and BB.

Correctness

The proof file proves the whole claim. Its steps:

  1. T1 changes nothing that matters. A self-loop lies on no path and is always a back edge, so dominance and the graph without back edges stay the same.
  2. T2 keeps reducibility in both directions. When vv merges into uu, the dominance relation among the other vertices does not change, and (v,w)(v, w) is a back edge exactly when (u,w)(u, w) is one. The edge (u,v)(u, v) is never a back edge. So the graph without back edges after the step is the graph before it with the edge (u,v)(u, v) contracted, and one has a cycle if and only if the other does.
  3. A reducible graph always allows a step. If the graph is reducible, has at least two vertices and has no self-loop, some vertex other than rr has one predecessor. Take the first vertex vv after rr in a topological order of the graph without back edges. Either rr is its only predecessor, or the vertices that vv dominates form a smaller reducible flow graph with root vv, and induction finds the vertex inside it.
  4. The theorem. From 1 to 3: GG is reducible if and only if every maximal sequence of steps ends in one vertex, if and only if some sequence does. So the order does not matter.
  5. The worklist. Each vertex that may allow a step is on WW, so when WW is empty no step applies, and the algorithm has made a maximal sequence.

Hecht and Ullman proved more: the limit graph is the same, up to names, for every order of the steps. The proof file cites this and does not prove it; the test does not need it.

Proof: T1 and T2 reduce a flow graph to one vertex exactly when it is reducible, and the worklist finds a maximal sequencefull

Setting. A flow graph is G=(N,E,r)G = (N, E, r), where EE is a set of ordered pairs (self-loops are allowed, parallel edges are not) and rr reaches every vertex. Line L1 of the algorithm keeps only the vertices that rr reaches, and an edge from a vertex that rr does not reach lies on no path from rr, so this changes neither the dominators nor the answer; from here on every vertex is reachable. xx dominates yy, written x dom yx \,\mathrm{dom}\, y, if every path from rr to yy contains xx. An edge (t,h)(t, h) is a back edge if h dom th \,\mathrm{dom}\, t, BB is the set of back edges, and H=(N,E∖B)H = (N, E \setminus B). GG is reducible if HH has no cycle; call this condition (C). This is the definition on the page of the reducible flow graph.

T1 deletes a self-loop (v,v)(v, v). T2 applies to a vertex v≠rv \ne r whose set of predecessors is {u}\{u\} for one vertex uu. It deletes vv and the edge (u,v)(u, v) and replaces each edge (v,w)(v, w) by (u,w)(u, w); an edge that is already there is not added again. Since v≠rv \ne r is reachable and uu is its only predecessor, u≠vu \ne v, so vv has no self-loop. An edge (v,u)(v, u) becomes the self-loop (u,u)(u, u). Let φ(v)=u\varphi(v) = u and φ(x)=x\varphi(x) = x for x≠vx \ne v. Then the new graph is G′=(N′,E′,r)G' = (N', E', r) with N′=N∖{v}N' = N \setminus \{v\} and E′={(φ(a),φ(b)):(a,b)∈E, (a,b)≠(u,v)}E' = \{(\varphi(a), \varphi(b)) : (a, b) \in E,\ (a, b) \ne (u, v)\}, because the only edge into vv is (u,v)(u, v).

Two facts are used many times. A walk from rr to yy that avoids a vertex xx contains a path from rr to yy that avoids xx. Dominance is antisymmetric: if x dom yx \,\mathrm{dom}\, y and y dom xy \,\mathrm{dom}\, x, then x=yx = y. Indeed, let x≠yx \ne y and take a path PP from rr to xx. It contains yy, and yy is not its last vertex, so the part of PP up to yy is a path from rr to yy that does not contain xx, because xx appears on PP only at the end. So xx does not dominate yy.

Lemma 1 (T1 keeps everything). T1 does not change reachability, dominance or HH.

Proof. A self-loop is on no path, since a path does not repeat a vertex. So the paths from rr are the same, and reachability and dominance are the same. The self-loop (v,v)(v, v) is a back edge because v dom vv \,\mathrm{dom}\, v, so it is not in HH, and the other back edges stay back edges. □\square

Lemma 2 (paths through a T2 step). Let T2 merge vv into uu.

(a) Every vertex of G′G' is reachable from rr.

(b) For x,y≠vx, y \ne v: x dom yx \,\mathrm{dom}\, y in GG if and only if x dom yx \,\mathrm{dom}\, y in G′G'.

(c) For b≠vb \ne v: b dom vb \,\mathrm{dom}\, v in GG if and only if b dom ub \,\mathrm{dom}\, u in GG.

(d) (u,v)(u, v) is not a back edge of GG.

Proof. Every occurrence of vv on a walk from rr comes right after an occurrence of uu, because v≠rv \ne r and uu is its only predecessor.

Down. Map a walk PP of GG from rr by φ\varphi and drop each step u→vu \to v, which becomes u→uu \to u. A step v→wv \to w becomes u→wu \to w, which is in E′E'. The result is a walk of G′G' from rr with the vertex set φ(V(P))\varphi(V(P)). If v∈V(P)v \in V(P), then also u∈V(P)u \in V(P), so V(P)∖{v}V(P) \setminus \{v\} is that vertex set in all cases.

Up. An edge (a,b)∈E′(a, b) \in E' is the image of some edge (a′,b′)∈E(a', b') \in E other than (u,v)(u, v). Then b′≠vb' \ne v, so b′=bb' = b, and a′=aa' = a, or a=ua = u and a′=va' = v. Replace the step a→ba \to b by a→ba \to b in the first case and by u→v→bu \to v \to b in the second. A walk of G′G' from rr becomes a walk of GG from rr whose vertex set is the old vertex set, perhaps with vv added.

(a) follows from the down map, applied to a path from rr to y≠vy \ne v.

(b) If a path of G′G' from rr to yy avoids xx, its lift is a walk of GG from rr to yy that avoids xx, since the only new vertex is v≠xv \ne x. If a path PP of GG from rr to yy avoids xx, its image has the vertex set V(P)∖{v}V(P) \setminus \{v\}, which does not contain xx. So "some path avoids xx" is true in GG exactly when it is true in G′G'.

(c) Each path from rr to vv ends with the step u→vu \to v, so its part up to uu is a path from rr to uu. If every path to uu contains bb, so does every path to vv. If a path to uu avoids bb, then adding the step u→vu \to v gives a path to vv that avoids bb, because b≠vb \ne v and the path to uu does not contain vv (it would contain uu before it).

(d) u dom vu \,\mathrm{dom}\, v, since every path to vv passes through uu. If also v dom uv \,\mathrm{dom}\, u, then u=vu = v by antisymmetry, which is false. So vv does not dominate uu, and (u,v)(u, v) is not a back edge. □\square

Lemma 3 (T2 keeps (C)). If T2 turns GG into G′G', then GG satisfies (C) if and only if G′G' does.

Proof. First, an edge (a,b)≠(u,v)(a, b) \ne (u, v) of GG is a back edge of GG exactly when its image (φ(a),φ(b))(\varphi(a), \varphi(b)) is a back edge of G′G'. If a,b≠va, b \ne v this is Lemma 2(b). The case b=vb = v does not occur. If a=va = v and b≠vb \ne v, then (v,b)(v, b) is a back edge iff b dom vb \,\mathrm{dom}\, v in GG, iff b dom ub \,\mathrm{dom}\, u in GG by Lemma 2(c), iff b dom ub \,\mathrm{dom}\, u in G′G' by Lemma 2(b), iff (u,b)(u, b) is a back edge of G′G'. Two edges with the same image, (u,w)(u, w) and (v,w)(v, w), are therefore both back edges or both not.

So the edges of H′H' are the images of the edges of HH other than (u,v)(u, v), and (u,v)(u, v) is an edge of HH by Lemma 2(d). In other words, H′H' is HH with the edge (u,v)(u, v) contracted, where (u,v)(u, v) is the only edge of HH into vv.

A graph has a cycle exactly when it has a closed walk with at least one edge. Let CC be a cycle of HH. If CC avoids vv, it is a cycle of H′H'. Otherwise CC contains the steps u→v→wu \to v \to w, and replacing them by u→wu \to w gives a closed walk of H′H' with at least one edge; if CC is u→v→uu \to v \to u, the result is the self-loop (u,u)(u, u). Conversely, a closed walk of H′H' with at least one edge lifts as in the proof of Lemma 2, by putting u→vu \to v before every step that comes from an edge (v,w)(v, w), to a closed walk of HH with at least one edge. □\square

Lemma 4 (progress). If GG satisfies (C), has at least 2 vertices and has no self-loop, then some vertex w≠rw \ne r has exactly one predecessor.

Proof. By strong induction on ∣N∣|N|. Every edge (a,r)(a, r) is a back edge, because rr dominates every vertex. The edges of a depth-first search tree from rr are not back edges: for a tree edge (x,y)(x, y), the tree path from rr to xx does not contain yy, so yy does not dominate xx. So HH contains a spanning tree from rr, every vertex x≠rx \ne r has a predecessor in HH, and rr has none. HH is acyclic by (C), so it has a topological order, and rr comes first because it is the only vertex without a predecessor in HH and all others are reachable from it in HH. Let vv be the second vertex in this order. Its predecessors in HH come before it, so they are {r}\{r\}. Every other predecessor pp of vv in GG is the tail of a back edge (p,v)(p, v), so v dom pv \,\mathrm{dom}\, p, and p≠vp \ne v because there is no self-loop. The edge (r,v)(r, v) is not a back edge, since vv does not dominate rr.

Case 1. vv has no predecessor other than rr. Then w=vw = v works.

Case 2. Some predecessor p≠rp \ne r has v dom pv \,\mathrm{dom}\, p. Let D={x:v dom x}D = \{x : v \,\mathrm{dom}\, x\}. Then v,p∈Dv, p \in D, r∉Dr \notin D, so 2≤∣D∣<∣N∣2 \le |D| < |N|.

(i) Every edge into D∖{v}D \setminus \{v\} starts in DD. Let (a,x)∈E(a, x) \in E with x∈Dx \in D, x≠vx \ne v. If a∉Da \notin D, a path from rr to aa that avoids vv, followed by the step to xx, is a path to xx that avoids vv; this contradicts x∈Dx \in D.

(ii) vv reaches every vertex of DD inside DD. Take a path from rr to x∈Dx \in D and its part SS after the last vv. A vertex yy of SS is in DD: if a path QQ from rr to yy avoided vv, then QQ followed by the rest of SS would be a walk to xx that avoids vv.

So GD=(D,E∩(D×D),v)G_D = (D, E \cap (D \times D), v) is a flow graph with root vv, fewer vertices than GG, at least 2 vertices and no self-loop.

(iii) GDG_D satisfies (C). Let x,y∈Dx, y \in D with y dom xy \,\mathrm{dom}\, x in GG. We show y dom xy \,\mathrm{dom}\, x in GDG_D. If y=vy = v this holds, because vv is the root of GDG_D. Let y≠vy \ne v. Take a path from rr to vv and cut it at its first vv; call this part QQ. QQ does not contain yy: otherwise its part up to yy would avoid vv, and v dom yv \,\mathrm{dom}\, y would fail. So if a path of GDG_D from vv to xx avoided yy, then QQ followed by it would be a walk of GG from rr to xx that avoids yy, which is false. Hence every back edge of GG inside DD is a back edge of GDG_D, and the graph HDH_D of GDG_D is a subgraph of HH. A subgraph of an acyclic graph is acyclic.

By induction, some w∈Dw \in D, w≠vw \ne v, has exactly one predecessor in GDG_D. By (i), all predecessors of ww in GG lie in DD, so ww has exactly one predecessor in GG, and w≠rw \ne r because r∉Dr \notin D. □\square

Theorem 1 (the T1-T2 characterization). A sequence of T1 and T2 steps is maximal if neither applies to its last graph. Every sequence is finite, because each step removes an edge or a vertex. For a flow graph GG, these are equivalent:

  1. GG is reducible.
  2. Every maximal sequence of T1 and T2 steps ends in a graph with one vertex.
  3. Some maximal sequence ends in a graph with one vertex.

Proof. (1) ⇒ (2): by Lemmas 1 and 3, every graph of the sequence satisfies (C) and is a flow graph. The last graph has no self-loop, since T1 does not apply, and no vertex w≠rw \ne r with exactly one predecessor, since T2 does not apply. By Lemma 4 it has one vertex. (2) ⇒ (3): a maximal sequence exists, since any sequence can be extended until it stops. (3) ⇒ (1): the last graph has one vertex and no self-loop, so it has no edge and satisfies (C). Lemmas 1 and 3 hold in both directions, so going back along the sequence, every graph satisfies (C), and so does GG. □\square

So the verdict does not depend on the order of the steps. Hecht and Ullman (1972) proved more: the last graph of a maximal sequence is the same, up to the names of the vertices, for every order. This file does not prove that stronger claim, and the algorithm does not need it.

Lemma 5 (the worklist finds a maximal sequence). Each T1 in line L6 and each T2 in lines L8 to L11 is a step on the current graph, and when line L3 finds WW empty, neither T1 nor T2 applies to any vertex.

Proof. Lines L5 and L7 test exactly the conditions of T1 and T2 on the current sets, and lines L8 to L11 update succsucc and predpred as T2 says, with sets, so a repeated edge is stored once. Whether T1 or T2 applies to a vertex xx depends only on succ[x]succ[x], pred[x]pred[x] and whether x=rx = r. Invariant: each vertex to which T1 or T2 applies is in WW when line L3 tests it. At the start every vertex is in WW. When vv is popped, line L6 removes a self-loop if there is one, and then line L7 tests T2 on the new sets of vv. If T2 is not done, then neither step applies to vv any more, and no other set has changed. If T2 is done, vv is gone. The sets that change are succ[u]succ[u], the sets pred[w]pred[w] for w∈succ[v]w \in succ[v], and pred[u]pred[u] when u∈succ[v]u \in succ[v]; line L11 pushes uu and every such ww. A T1 changes only the sets of vv. So the invariant holds after each iteration, and when WW is empty no step applies. □\square

Termination and cost. Let nn and mm be the numbers of vertices and edges. There are at most n−1n - 1 T2 steps, because each removes a vertex and the root is never removed, and at most m+n−1m + n - 1 T1 steps, because a self-loop is either an edge of the input or made by a T2 step from an edge (v,u)(v, u), at most one per T2. Line L2 pushes nn vertices and each T2 pushes 1+∣succ[v]∣≤n1 + |succ[v]| \le n vertices, so there are at most n+(n−1)nn + (n - 1) n pushes, and the loop runs O(n2)O(n^2) times. Line L1 takes O(n+m)O(n + m) steps. Each T2 step does O(1+∣succ[v]∣)=O(n)O(1 + |succ[v]|) = O(n) set operations. With a hash table per set, each set operation takes expected constant time, and the total is O(n2+m)O(n^2 + m) expected; with an n×nn \times n bit table for edge membership and lists for iteration the same bound holds in the worst case. The space is O(n+m)O(n + m) for the sets.

What is proved and what is measured. Theorem 1, Lemma 5 and the bound O(n2+m)O(n^2 + m) are proved here. The uniqueness of the limit graph is cited from Hecht and Ullman. The tests check, on seeded random graphs, that the result agrees with the definition of reducibility computed by brute force, and that a naive applier that picks T1 and T2 steps in random orders always reaches the same verdict; these are measurements and do not replace the proof.

Complexity

Proved. Line L1 takes O(n+m)O(n + m) time. Each T2 removes a vertex, so there are at most n−1n - 1 of them, and each pushes at most nn vertices, so the loop runs O(n2)O(n^2) times. Each T2 does O(n)O(n) set operations, one per moved successor. The total is O(n2+m)O(n^2 + m), in expectation with hash sets and in the worst case with an n×nn \times n bit table for edge membership. The extra space is Θ(n+m)\Theta(n + m) for the sets. On a star, where rr points to every other vertex, each vertex is merged with no successors to move, and the time is Θ(n+m)\Theta(n + m).

Measured, not proved. In the tests, 1,500 seeded random digraphs with 1 to 8 vertices give the same verdict as the definition computed by brute force, and on 400 graphs a naive applier that picks steps in random orders always reaches the verdict of the worklist. A chain of 20,000 vertices with edges in both directions takes a few hundredths of a second in Python on a laptop.

Properties

  • Deterministic. The step list depends on the order of the worklist; the verdict does not.
  • Non-recursive. The search of line L1 and the main loop use explicit lists.
  • Order-independent. Any order of T1 and T2 steps gives the same answer, by the theorem of the proof file.
  • A parse of the graph. On a reducible graph the steps form a hierarchy of regions: each T2 attaches a region to its single entry, and each T1 closes a loop.
  • Offline. The whole graph is needed; after an edge change the test runs again.

Variants and improvements

  • Tarjan's test. Tarjan (1974) tests reducibility in almost linear time with one depth-first search and disjoint set forests, which keep track of the vertices that have been collapsed together.
  • Test with one search. Run one depth-first search, compute dominators, for example with the Cooper-Harvey-Kennedy algorithm, and check that each retreating edge goes to a dominator of its source. This is form 5 on the reducible flow graph page.
  • Intervals. Allen and Cocke's interval analysis collapses a whole single-entry region at a time, instead of one node. A graph is reducible exactly when the sequence of interval graphs ends in one node.
  • Elimination data-flow analysis. The step list orders the work of elimination methods: at a T2 step the transfer function of vv is composed into uu, and at a T1 step the effect of the loop is closed. Then the results are spread back in reverse order.
  • Node splitting. When the reduction gets stuck, copy a vertex with kk predecessors into kk vertices, one per predecessor. Each copy then allows a T2 step. Repeating this makes any flow graph reducible, but the graph can grow very large.

When to use it

Use it when you need a simple and clearly correct reducibility test for the control flow graphs of single procedures, which are small, or when you also need the order in which the regions collapse. For large graphs, use Tarjan's test or a single search with dominators. If you need the loops themselves, compute natural loops or a loop nesting forest instead.

Pitfalls

  • Unreachable vertices. An edge from a vertex that rr does not reach still counts as a predecessor, so T2 cannot fire and a reducible graph looks irreducible. Delete unreachable vertices first, as line L1 does.
  • Parallel edges. A branch br c L L gives two edges to L. Counted twice, they block T2 on L. Keep the edges as sets.
  • The self-loop as a predecessor. A vertex with a self-loop has itself as a predecessor. Do T1 before testing T2, or the test fails on every loop header.
  • Merging the entry. T2 must never merge rr, even if rr has exactly one predecessor, for example the latch of a loop that starts at the entry. Merging it would remove the entry of the graph.
  • A worklist that forgets vertices. After a T2, both uu and the moved successors must go back on the list. If they do not, the loop can stop while a step still applies, and the answer is 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.

t1_t2_reduction.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/t1-t2-reduction/. The authors are listed in prov/VPKTQX.jsonl.
"""The T1-T2 reduction of Hecht and Ullman.

t1_t2_reduce(n, edges, root) applies T1 (delete a self-loop) and T2 (merge a
vertex other than the root that has exactly one predecessor into that
predecessor) until neither applies. It returns (left, left_edges, steps):
the vertices and edges of the limit graph and the list of steps taken, each
("T1", v) or ("T2", v, u) for "v merged into u". Only the vertices that the
root reaches take part. The graph is reducible exactly when one vertex is
left; is_reducible says so, and cfg_is_reducible does it for a toy IR
program.
"""

import toyir


def t1_t2_reduce(n, edges, root):
    if n < 1 or not 0 <= root < n:
        raise ValueError("a flow graph needs n >= 1 vertices and a root in range")
    out = [[] for _ in range(n)]
    for a, b in edges:
        if not (0 <= a < n and 0 <= b < n):
            raise ValueError("edge endpoint out of range")
        out[a].append(b)

    # Keep the vertices that root reaches, with successor and predecessor sets.
    seen = [False] * n  # @line L1
    seen[root] = True
    stack = [root]
    while stack:
        v = stack.pop()
        for w in out[v]:
            if not seen[w]:
                seen[w] = True
                stack.append(w)
    succ = {v: set() for v in range(n) if seen[v]}
    pred = {v: set() for v in succ}
    for a, b in edges:
        if seen[a]:
            succ[a].add(b)
            pred[b].add(a)

    steps = []
    work = sorted(succ, reverse=True)  # @line L2
    while work:  # @line L3
        v = work.pop()  # @line L4
        if v not in succ:
            continue
        if v in succ[v]:  # @line L5
            succ[v].discard(v)  # @line L6
            pred[v].discard(v)
            steps.append(("T1", v))
        if v != root and len(pred[v]) == 1:  # @line L7
            (u,) = pred[v]
            moved = succ[v]
            succ[u].discard(v)  # @line L8
            for w in moved:  # @line L9
                pred[w].discard(v)  # @line L10
                pred[w].add(u)
                succ[u].add(w)
            del succ[v], pred[v]  # @line L11
            steps.append(("T2", v, u))
            work.append(u)
            work.extend(moved)
    left = sorted(succ)  # @line L12
    left_edges = sorted((a, b) for a in succ for b in succ[a])
    return left, left_edges, steps


def is_reducible(n, edges, root):
    """True if T1 and T2 reduce the part that root reaches to one vertex."""
    return len(t1_t2_reduce(n, edges, root)[0]) == 1


def cfg_is_reducible(prog):
    """Reducibility of the control flow graph of a toy IR program."""
    labels = list(prog.blocks)
    index = {lab: i for i, lab in enumerate(labels)}
    edges = [(index[a], index[b]) for a, b in toyir.edges(prog)]
    return is_reducible(len(labels), edges, 0)
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_t1_t2_reduction.py 282 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/t1-t2-reduction/. The authors are listed in prov/VPKTQX.jsonl.

import random

import pytest

import toyir
from t1_t2_reduction import cfg_is_reducible, is_reducible, t1_t2_reduce

NESTED = """
B0:
  i = 0
  s = 0
  jump B1
B1:
  t = i < n
  br t B2 B6
B2:
  j = 0
  jump B3
B3:
  u = j < i
  br u B4 B5
B4:
  s = s + j
  j = j + 1
  jump B3
B5:
  i = i + 1
  jump B1
B6:
  ret s
"""

STUCK = """
r:
  br p A B
A:
  x = x + 1
  br q B C
B:
  x = x * 2
  br q A C
C:
  ret x
"""

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


def graph(prog):
    labels = list(prog.blocks)
    index = {lab: i for i, lab in enumerate(labels)}
    return labels, [(index[a], index[b]) for a, b in toyir.edges(prog)]


def reach(n, succ, root, banned):
    """The vertices that root reaches without passing through banned."""
    if banned == root:
        return set()
    seen = {root}
    stack = [root]
    while stack:
        v = stack.pop()
        for w in succ[v]:
            if w != banned and w not in seen:
                seen.add(w)
                stack.append(w)
    return seen


def brute_reducible(n, edges, root):
    """Reducibility by the definition: compute the dominators by deleting
    each vertex in turn, drop the back edges (t, h) with h dominating t, and
    check that what is left has no cycle."""
    succ = [[] for _ in range(n)]
    for a, b in edges:
        succ[a].append(b)
    full = reach(n, succ, root, -1)
    dom = {v: {v} for v in full}
    for d in full:
        r = reach(n, succ, root, d)
        for v in full:
            if v not in r:
                dom[v].add(d)
    fwd = {v: set() for v in full}
    for a, b in edges:
        if a in full and b not in dom[a]:
            fwd[a].add(b)
    indeg = {v: 0 for v in full}
    for a in fwd:
        for b in fwd[a]:
            indeg[b] += 1
    queue = [v for v in full if indeg[v] == 0]
    count = 0
    while queue:
        v = queue.pop()
        count += 1
        for w in fwd[v]:
            indeg[w] -= 1
            if indeg[w] == 0:
                queue.append(w)
    return count == len(full)


def naive_reduce(n, edges, root, rng):
    """Apply T1 and T2 in a random order until neither applies. Returns the
    number of vertices left."""
    succ = [[] for _ in range(n)]
    for a, b in edges:
        succ[a].append(b)
    full = reach(n, succ, root, -1)
    s = {v: set() for v in full}
    for a, b in edges:
        if a in full:
            s[a].add(b)
    while True:
        moves = []
        for v in s:
            if v in s[v]:
                moves.append(("T1", v))
            preds = [u for u in s if v in s[u]]
            if v != root and len(preds) == 1 and preds[0] != v:
                moves.append(("T2", v, preds[0]))
        if not moves:
            return len(s)
        move = rng.choice(moves)
        if move[0] == "T1":
            s[move[1]].discard(move[1])
        else:
            v, u = move[1], move[2]
            s[u].discard(v)
            s[u] |= s[v]
            del s[v]


def random_graph(rng):
    n = rng.randint(1, 8)
    m = rng.randint(n, 3 * n)
    return n, [(rng.randrange(n), rng.randrange(n)) for _ in range(m)]


def test_nested_loops_reduce_to_one_node():
    labels, edges = graph(toyir.parse(NESTED))
    left, left_edges, steps = t1_t2_reduce(len(labels), edges, 0)
    assert left == [0] and left_edges == []
    named = [(s[0],) + tuple(labels[x] for x in s[1:]) for s in steps]
    assert named == [
        ("T2", "B2", "B1"),
        ("T2", "B4", "B3"),
        ("T1", "B3"),
        ("T2", "B3", "B1"),
        ("T2", "B5", "B1"),
        ("T1", "B1"),
        ("T2", "B1", "B0"),
        ("T2", "B6", "B0"),
    ]


def test_smallest_irreducible_graph_is_stuck():
    prog = toyir.parse(STUCK)
    labels, edges = graph(prog)
    left, left_edges, steps = t1_t2_reduce(len(labels), edges, 0)
    assert steps == []
    assert left == [0, 1, 2, 3]
    assert left_edges == [(0, 1), (0, 2), (1, 2), (1, 3), (2, 1), (2, 3)]
    assert not cfg_is_reducible(prog)
    assert not brute_reducible(len(labels), edges, 0)


def test_odd_sum_program():
    prog = toyir.parse(ODD_SUM)
    assert cfg_is_reducible(prog)
    assert toyir.run(prog, [6]) == ("ret", 9)


def test_small_cases():
    assert t1_t2_reduce(1, [], 0) == ([0], [], [])
    assert t1_t2_reduce(1, [(0, 0)], 0) == ([0], [], [("T1", 0)])
    # Parallel edges count as one edge.
    assert t1_t2_reduce(2, [(0, 1), (0, 1)], 0) == ([0], [], [("T2", 1, 0)])
    # A cycle through the root is reducible.
    assert is_reducible(3, [(0, 1), (1, 2), (2, 0)], 0)
    # The root keeps its in-edges until a T1 removes them.
    assert t1_t2_reduce(2, [(0, 1), (1, 0)], 0) == ([0], [], [("T2", 1, 0), ("T1", 0)])


def test_unreachable_part_is_ignored():
    # 3, 4 and 5 form an irreducible pattern that the root 0 does not reach.
    edges = [(0, 1), (1, 2), (3, 4), (3, 5), (4, 5), (5, 4), (4, 1)]
    left, left_edges, _ = t1_t2_reduce(6, edges, 0)
    assert left == [0] and left_edges == []
    # With root 3 the same graph is irreducible.
    assert not is_reducible(6, edges, 3)


def test_bad_input():
    with pytest.raises(ValueError):
        t1_t2_reduce(0, [], 0)
    with pytest.raises(ValueError):
        t1_t2_reduce(2, [], 2)
    with pytest.raises(ValueError):
        t1_t2_reduce(2, [(0, 2)], 0)


def test_random_graphs_match_the_definition():
    rng = random.Random(53)
    seen = [0, 0]
    for _ in range(1500):
        n, edges = random_graph(rng)
        root = rng.randrange(n)
        want = brute_reducible(n, edges, root)
        assert is_reducible(n, edges, root) == want
        seen[want] += 1
    assert min(seen) > 100


def test_every_order_gives_the_same_answer():
    rng = random.Random(59)
    for _ in range(400):
        n, edges = random_graph(rng)
        want = is_reducible(n, edges, 0)
        for _ in range(4):
            assert (naive_reduce(n, edges, 0, rng) == 1) == want


def test_limit_graph_is_stuck_and_counts_match():
    rng = random.Random(61)
    for _ in range(800):
        n, edges = random_graph(rng)
        left, left_edges, steps = t1_t2_reduce(n, edges, 0)
        succ = [[] for _ in range(n)]
        for a, b in edges:
            succ[a].append(b)
        size = len(reach(n, succ, 0, -1))
        assert sum(1 for s in steps if s[0] == "T2") == size - len(left)
        assert 0 in left
        assert all(a != b for a, b in left_edges)
        for v in left:
            if v != 0:
                assert sum(1 for a, b in left_edges if b == v) >= 2


def test_random_toy_programs():
    rng = random.Random(67)
    seen = [0, 0]
    for _ in range(300):
        prog = toyir.random_program(rng, 3, rng.randint(2, 9), rng.random() < 0.3)
        labels, edges = graph(prog)
        want = brute_reducible(len(labels), edges, 0)
        assert cfg_is_reducible(prog) == want
        seen[want] += 1
    assert seen[1] > 100


def test_long_graphs():
    n = 20000
    chain = [(i, i + 1) for i in range(n - 1)]
    assert is_reducible(n, chain + [(i + 1, i) for i in range(n - 1)], 0)
    assert is_reducible(n, chain + [(n - 1, 0)], 0)
    # Two entries into one long cycle: irreducible.
    assert not is_reducible(n, chain + [(n - 1, 1), (0, n // 2)], 0)

History

Hecht and Ullman introduced the transformations T1 and T2 in 1972 and defined a flow graph to be reducible when they reduce it to one node; they also proved that the limit graph does not depend on the order of the steps. Their 1974 paper in the Journal of the ACM gave further equivalent forms, among them the forbidden (∗)(*) subgraph. In the same year Tarjan gave an almost-linear test. The rules became the standard way to explain reducibility in textbooks, and the order of collapse that they define is the basis of T1-T2 elimination methods for data-flow analysis.

References

  1. Matthew S. Hecht and Jeffrey D. Ullman, Flow graph reducibility, SIAM Journal on Computing 1(2) (1972), 188-202, the transformations T1 and T2, the definition of reducibility as reduction to one node, and the uniqueness of the limit graph
  2. Matthew S. Hecht and Jeffrey D. Ullman, Characterizations of reducible flow graphs, Journal of the ACM 21(3), 1974, the equivalent forms of reducibility, among them the forbidden (*) subgraph and the uniqueness of the acyclic graph of forward edges
  3. Robert Endre Tarjan, Testing flow graph reducibility, Journal of Computer and System Sciences 9(3), 1974, pages 355-365, the almost-linear test for reducibility with depth-first search and disjoint set union
  4. Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Section 9.6.4 (back edges and reducibility) and Section 9.7 (region-based analysis)
  5. Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Chapter 7 (Control-Flow Analysis), reducibility and the analyses that collapse regions of a flow graph

About this page

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

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