Algorithm Search⌘K

Algorithmadvanced

Superblock scheduling

Also called superblock formation.

Forms traces with one entry by tail duplication and schedules each as a block, with no compensation code at side entries.

Time
O(m (s N + n^2)) worst
Space
O(s N + n^2) extra
Where
N = the number of names; m = the number of superblocks; n = the number of items of one superblock; s = the number of instructions and terminators of the program after formation
Properties
deterministicofflineiterative
Origin
Wen mei W. Hwu, Scott A. Mahlke, Pohua P. Chang, 1993

Superblock scheduling is a global instruction scheduling method. A superblock is a trace, a likely path through several basic blocks, that control can enter only at its head and can leave at many side exits. The method makes superblocks by tail duplication: when another path joins a trace in the middle, the part of the trace from that point to its end is copied, and the other path goes to the copy. Then each superblock is scheduled as one block. It differs from trace scheduling in where it pays for side entrances. Trace scheduling keeps them and puts compensation code on them after scheduling. Superblock scheduling removes them before scheduling, so it needs no compensation code at entrances and, with the motion rules of this page, none at exits either. The IMPACT group (Hwu et al. 1993) introduced it.

In plain words

A program usually takes the same way through its branches. This method finds that usual way and makes sure that nothing can jump into the middle of it. Where some other path did jump in, the method gives that path its own copy of the rest of the way. Now the usual way is one straight line that can only be left early, never entered late. The scheduler packs that line tightly for a wide machine, and it moves an instruction past an early exit only when the exit does not need the instruction and the instruction cannot fail. So no repair code is needed. The price is the copied code, which makes the program larger.

The problem

The input is a program in the toy IR of these pages: a control flow graph with no cycle whose blocks hold const, copy and op instructions and end with jump, br or ret, and an edge profile, a count for each edge. A run ends with ret v or with a trap (a division or remainder by 0, or a shift by an amount outside 0 to 63). The machine is the one of trace scheduling: at most 2 items per cycle, at most one multiply-unit operation (*, /, %, latency 3) and at most one branch (latency 1). Other operations have latency 1.

The output is a program that has the same outcome as the input on every input, the same returned value or a trap, and whose blocks are list schedules of superblocks. Loops are not handled here. A real compiler forms superblocks inside a loop body, often after unrolling, or uses software pipelining.

The algorithm

  1. SUPERBLOCK-SCHEDULE(P, freq)
  2. 1done <- empty; S <- empty list
  3. 2while some block of P is not in done do
  4. 3T = b1 .. bk <- the seed of highest count, grown along edges that are most likely at both ends, never into or backward past the entry
  5. 4j <- the least i >= 2 such that bi has a predecessor other than b(i-1); if there is none, go to L7
  6. 5for i <- j to k do make a copy ci of bi whose edges to a block bm with m >= j go to cm
  7. 6for i <- j to k do send each edge from a predecessor p != b(i-1) of bi to ci
  8. 7append T to S; add b1 .. bk to done
  9. 8for each superblock T in S do
  10. 9live <- the live-in sets of the current P
  11. 10D <- the dependence DAG of the items of T: data edges, and an edge from each item to the end item
  12. 11add an edge from each side exit B to each later branch, and to each later operation that may trap or writes a name of live(off(B))
  13. 12add an edge to each side exit B from each earlier operation that may trap or writes a name of live(off(B))
  14. 13t <- a list schedule of D by height; order the items by (t, original position)
  15. 14emit the items in that order, starting a new block after each side exit; the first piece keeps the label b1
  16. 15return P

Formation (lines L1 to L7). Line L3 picks a trace among the blocks not yet in a superblock, as in trace scheduling. The seed is the block of highest count, the larger of the sums of its incoming and its outgoing edge counts. The trace grows forward from its last block aa to the successor bb of the largest edge count, but only if aa is also the predecessor of bb with the largest count and bb is not done. It grows backward in the same way. It never takes the entry block except as its head. Chang and Hwu (1988) describe this growth with a best successor and a best predecessor. Line L4 finds the first side entrance, the first block after the head with a second predecessor. Lines L5 and L6 copy the tail bj,…,bkb_j, \dots, b_k. A copy cic_i keeps the instructions of bib_i. Its edges into the tail go to the copies, so the copies never become new side entrances. Every side edge into bib_i moves to cic_i. After this, the trace edge from bi−1b_{i-1} is the only edge into bib_i, and TT is a superblock. The copies are new blocks that are not done, so later rounds put them in superblocks of their own.

Items (line L10). In the original order, the items of a superblock b1,…,bkb_1, \dots, b_k are: the instructions of each block, called operations; a side exit item for each br of bib_i, i<ki < k, whose other target off(B)\mathrm{off}(B) leaves the superblock; and the end item, the terminator of bkb_k. A jump from bib_i to bi+1b_{i+1} gives no item.

Dependences (lines L10 to L12). The data edges are the true, anti and output dependences of data dependence: a true dependence waits for the latency of the writer, an output dependence waits 1 cycle, and an anti dependence waits 0 cycles. Line L11 keeps the side exits in order, and lets an operation from below a side exit move above it only if the operation cannot trap and its result is dead on the exit. Such a motion is safe speculation. Line L12 is the rule that replaces compensation code: an operation from above a side exit moves below it only under the same two conditions. Then a run that leaves at the exit does not need the operation, and it is correct that the operation did not run. Trace scheduling lets such an operation move and puts a copy on the exit edge instead.

Emission (line L14). The scheduled items run in the order of (t,original position)(t, \text{original position}), so items with a delay 0 between them can share a cycle. A new block starts after each side exit and ends with the old br on the same condition, to the next piece and to the old exit target. The other labels of the superblock disappear: by tail duplication, nothing else jumps to them.

Example

Take the program of the trace scheduling page, with parameters a and b, and the profile 90 for B0→B1B_0 \to B_1 and B1→B3B_1 \to B_3, and 10 for B0→B2B_0 \to B_2 and B2→B3B_2 \to B_3:

B0:
  c = b < 5
  s = a - b
  br c B1 B2
B1:
  y = a / b
  jump B3
B2:
  y = a - 1
  jump B3
B3:
  w = b + 1
  v = w * w
  z = y + v
  r = z + s
  ret r

Formation. Line L3 picks B0B_0, the block of highest count, and grows it to B0,B1,B3B_0, B_1, B_3. The block B3B_3 has a second predecessor, B2B_2, so line L4 gives j=3j = 3. Lines L5 and L6 make the copy B3.1 of B3B_3 and send the edge B2→B3B_2 \to B_3 to it. The second round picks B2B_2 and grows it to B2B_2, B3.1, which has no side entrance. The formed program has the two superblocks below, and four more instructions than the input.

round trace first side entrance copies edge counts after the round
1 B0,B1,B3B_0, B_1, B_3 B3B_3, from B2B_2 B3.1 B1→B3B_1 \to B_3: 90, B2→B_2 \to B3.1: 10
2 B2B_2, B3.1 none none unchanged

Scheduling the first superblock. Line L9 gives live(B2)={a,b,s}\mathrm{live}(B_2) = \{a, b, s\}. The items, with their units, latencies, heights and cycles, are:

index item unit latency height cycle
0 c = b < 5 alu 1 7 0
1 s = a - b alu 1 6 1
2 side exit, off B2B_2 br 1 6 1
3 y = a / b mul 3 6 2
4 w = b + 1 alu 1 7 0
5 v = w * w mul 3 6 3
6 z = y + v alu 1 3 6
7 r = z + s alu 1 2 7
8 ret r br 1 1 8

Line L11 adds the edge from the exit to y = a / b, since a division by b can trap. It adds no edge to w, v, z or r: they cannot trap and their names are dead at B2B_2. Line L12 adds the edge from s = a - b to the exit, since s is live at B2B_2. The list scheduler gives:

cycle ready, by height issued
0 c, w, s c, w
1 s, exit, v (all of height 6) s, exit
2 y, v y (one multiply unit)
3 v v
4, 5 none none
6 z z
7 r r
8 ret r ret r

The length is 8+1=98 + 1 = 9 cycles. The optimum for this DAG is 8: v and s at cycle 1, the exit and y at cycle 2, z at 5. The list scheduler breaks the tie at cycle 1 by original position and fills the cycle with s and the exit, so the two multiplies start one cycle later. Trace scheduling reaches 8 cycles on the same path with this list scheduler, because it moves s below the exit and puts a copy of s on the exit edge. Line L12 forbids that motion here. Block by block, the same path takes 2+3+7=122 + 3 + 7 = 12 cycles.

The second superblock. B2B_2, B3.1 is one block of six items. Its list schedule puts y and w at cycle 0, v at 1, z at 4, r at 5 and ret r at 6, a length of 7, which is optimal. The output is:

B0:
  c = b < 5
  w = b + 1
  s = a - b
  br c B0.1 B2
B0.1:
  y = a / b
  v = w * w
  z = y + v
  r = z + s
  ret r
B2:
  y = a - 1
  w = b + 1
  v = w * w
  z = y + v
  r = z + s
  ret r

The operation w = b + 1 moved above the exit by speculation. It also runs on the rare path, where its value is computed again in B2. No other code was added: the output has 12 instructions, the same as the formed program, while the trace scheduling output has 10. On (a,b)=(1,7)(a, b) = (1, 7) both the input and the output take the rare path and return 58. On (4,2)(4, 2) both return 13, and on (4,0)(4, 0) both trap.

Correctness

Theorem. On every input, the output of SUPERBLOCK-SCHEDULE returns the same value as the input program, or traps exactly when the input program traps. Formation stops, and scheduling adds no instruction.

The full proof is in the proof file. For formation, each block of the new program maps to a block of the old one with the same instructions and the same targets after the map, so the two programs run in step. After the copies, the only edge into bib_i, i≥2i \ge 2, is from bi−1b_{i-1}, and later rounds keep this. Formation stops because the number of paths from the blocks not yet done drops by at least 1 in each round, although the copies are new blocks. For scheduling, the edges keep the order of any two items that read or write the same name, and the order of the exits. An operation that crosses an exit in either direction cannot trap and writes only a name that is dead on the exit (lines L11 and L12). So a run that leaves at an exit sees the same values of the live names as before, a run that reaches the end item sees the same values of all names, and a trap happens in both runs or in neither. An induction over the blocks in reverse topological order finishes the proof.

Proof: Superblock formation and superblock scheduling keep the meaning of the program and stopfull

We prove three things about SUPERBLOCK-SCHEDULE. Tail duplication (lines L4 to L6) keeps the outcome of every run and gives each trace one entry. The formation loop (lines L2 to L7) stops. Scheduling one superblock (lines L9 to L14) keeps the outcome of every run, and adds no instruction. The rules of code motion of lines L11 and L12 are exactly what the scheduling proof needs.

Setup

The program PP has an acyclic control flow graph and only const, copy and op instructions. Every value is an integer. A run ends with ret v or with a trap (a division or remainder by 0, or a shift by an amount outside 0 to 63). As the graph is acyclic, every run is finite. The outcome of a run is its returned value or the trap. live(L)\mathrm{live}(L) is the set of names that some path from the start of block LL reads before it writes them, the least solution of the usual backward equations, which line L9 computes in one pass in reverse topological order.

An operation uu may trap if it is a division or remainder whose right operand is not a nonzero constant, or a shift whose amount is not a constant from 0 to 63. Every operation that traps on some run may trap.

Part 1. Tail duplication

Line L3 gives a trace T=b1,…,bkT = b_1, \dots, b_k, a path of blocks that are in no superblock yet. If some bib_i with i≥2i \ge 2 has a predecessor other than bi−1b_{i-1} (a side entrance), let jj be the least such ii (line L4). Line L5 makes a new block cic_i for each i≥ji \ge j with the instructions of bib_i, and the terminator of bib_i in which every target bmb_m with m≥jm \ge j is replaced by cmc_m. Line L6 replaces, in the terminator of every predecessor p≠bi−1p \ne b_{i-1} of bib_i with i≥ji \ge j, the target bib_i by cic_i. Call the result P′P', and let hh map each cic_i to bib_i and every other label to itself.

Lemma 1. For every block LL of P′P', the block h(L)h(L) of PP has the same instructions, and its terminator is the terminator of LL with hh applied to each target. So PP and P′P' have the same outcome on every input.

Proof. For a copy cic_i this is the construction of line L5. For any other block, line L6 only renames a target bib_i to cic_i, and h(ci)=bih(c_i) = b_i. Now run PP and P′P' on the same input. By induction on the number of blocks run, after each block the runs are at labels L′L' and h(L′)h(L') with the same state: the two blocks run the same instructions on the same state, so they trap together or reach the same state, and the terminators read the same name and take the targets in the same position, which hh maps one to the other. The entry is not a copy, so both runs start at the same label. □\square

Lemma 2. In P′P', for every i≥2i \ge 2, the only predecessor of bib_i is bi−1b_{i-1}.

Proof. For i<ji < j, by the choice of jj, bib_i had no other predecessor, and lines L5 and L6 add no edge into bib_i: a copy only targets copies and blocks outside the tail. For i≥ji \ge j, line L6 moved every edge from a predecessor other than bi−1b_{i-1} to cic_i, and a copy never targets bib_i. The edge from bi−1b_{i-1} to bib_i is not renamed, since line L6 renames the target bib_i only in predecessors other than bi−1b_{i-1}, and renames a target bm≠bib_m \ne b_i of bi−1b_{i-1} only to cmc_m. □\square

Lemma 3. Once TT is a superblock, it stays one: in every later program of the loop, bib_i for i≥2i \ge 2 has the one predecessor bi−1b_{i-1}.

Proof. A later step of line L6 renames only targets that are blocks of the later trace, which are in no superblock yet, so it never removes or adds an edge into bib_i. A later step of line L5 copies a block tt that is in no superblock. If tt had an edge to bib_i with i≥2i \ge 2, then t=bi−1t = b_{i-1} by induction, but bi−1b_{i-1} is in a superblock. So the copies add no edge into bib_i. □\square

Lemma 4. The formation loop stops. For a program QQ and the set done\mathrm{done} of blocks in superblocks, let p(c)=1p(c) = 1 if cc is done or has no successor, and otherwise p(c)=∑sp(s)p(c) = \sum_s p(s) over the successors ss of cc. Let Φ=∑c not donep(c)\Phi = \sum_{c \text{ not done}} p(c). Each step of the loop makes Φ\Phi smaller by at least 1, so the loop stops after at most Φ\Phi steps of the input.

Proof. Write pp before the step and p′p' after it, when the blocks of TT are done. We show p′(c)≤p(h(c))p'(c) \le p(h(c)) for every block cc of P′P' that is not done after the step, by induction in reverse topological order of P′P'. If cc has no successor, both are 1. Otherwise h(c)h(c) was not done before the step (copies are made only of blocks that were not done), and by Lemma 1 the successors of cc map one to one under hh to the successors of h(c)h(c). A successor that is done after the step has p′=1≤pp' = 1 \le p, and any other successor ss has p′(s)≤p(h(s))p'(s) \le p(h(s)) by induction. So p′(c)≤p(h(c))p'(c) \le p(h(c)).

The blocks not done after the step are the old blocks not done, minus b1,…,bkb_1, \dots, b_k, plus the copies cj,…,ckc_j, \dots, c_k. So

Φ′≤(Φ−∑i=1kp(bi))+∑i=jkp(bi)=Φ−∑i<jp(bi)≤Φ−p(b1)≤Φ−1,\Phi' \le \Big(\Phi - \sum_{i=1}^{k} p(b_i)\Big) + \sum_{i=j}^{k} p(b_i) = \Phi - \sum_{i < j} p(b_i) \le \Phi - p(b_1) \le \Phi - 1,

since j≥2j \ge 2 and p≥1p \ge 1. Without a side entrance there are no copies, and the bound is the same. □\square

So formation stops, keeps the outcome of every run (Lemma 1), keeps the graph acyclic (a copy cic_i only has edges to copies of later trace blocks and to blocks after bib_i, and an edge renamed by line L6 goes to a copy whose original came after its source), and gives superblocks that cover all blocks, each with a single entry at its head (Lemmas 2 and 3). The entry block is never bib_i with i≥2i \ge 2, because line L3 does not grow a trace into the entry or backward past it.

Part 2. Scheduling one superblock

Fix a superblock b1,…,bkb_1, \dots, b_k of the current program PP. Its items I0,…,In−1I_0, \dots, I_{n-1} are, in index order: the instructions of each block, called operations; for i<ki < k, a branch BB when bib_i ends with a br to two labels, one of them bi+1b_{i+1} and the other its exit target off(B)\mathrm{off}(B); and the end item, the terminator of bkb_k. A branch or the end item reads its condition or its returned name. Two items u<vu < v conflict if one of them writes a name that the other reads or writes.

By Lemmas 2 and 3, off(B)\mathrm{off}(B) is not a block bmb_m of the superblock: m≤im \le i would close a cycle, m=i+1m = i + 1 is the trace target, and m>i+1m > i + 1 would give bmb_m a second predecessor.

Say that an operation uu stays at a branch BB if uu may trap or uu writes a name of live(off(B))\mathrm{live}(\mathrm{off}(B)). The DAG DD has these edges u→vu \to v, all with u<vu < v and a delay δ≥0\delta \ge 0:

  • (E1) data: from the last writer of xx before vv to each reader vv of xx, delay the latency of the writer; from the last writer of xx before vv to a writer vv of xx, delay 1; from each reader of xx after the last writer of xx before vv to a writer vv of xx, delay 0;
  • (E2) from a branch BB to each later branch, to the end item, and to each later operation that stays at BB (line L11);
  • (E3) from each operation that stays at BB to each later branch BB (line L12);
  • (E4) from each item to the end item.

Line L13 gives each item a cycle tvt_v with tv≥tu+δ(u,v)t_v \ge t_u + \delta(u, v) for each edge. The order π\pi sorts the items by (tv,v)(t_v, v), and u≺vu \prec v means that uu is before vv in π\pi. Line L14 cuts π\pi after each branch: the first piece takes the label b1b_1, the other pieces get new labels, a piece that ends at a branch BB ends with br on the same condition to the next piece and to off(B)\mathrm{off}(B), in the positions of the old targets, and the last piece ends with the end item. The blocks b2,…,bkb_2, \dots, b_k are removed. All other blocks stay as they are. Call the result P′P'.

Lemma 5. Order. (a) Each edge u→vu \to v of DD has u≺vu \prec v. (b) If u<vu < v conflict, then u≺vu \prec v.

Proof. (a) u<vu < v and tv≥tu+δ(u,v)≥tut_v \ge t_u + \delta(u, v) \ge t_u, so (tu,u)<(tv,v)(t_u, u) < (t_v, v). (b) By (a) it is enough to find a path from uu to vv in DD. Let xx be the name of the conflict. The writers of xx form a path in index order by the output edges of (E1). If uu writes and vv reads, the last writer ww of xx before vv has u≤wu \le w, and the path is u→⋯→w→vu \to \dots \to w \to v. If uu reads and vv writes, the first writer ww of xx after uu has w≤vw \le v, uu reads xx after the last writer before ww, so (E1) has u→wu \to w, and the path goes on along the writers to vv. If both write, the writers path joins them. □\square

Lemma 6. Shape. (a) The branches and the end item are in index order in π\pi, and the end item is last. (b) If an operation vv and a branch BB are in a different order in π\pi than in index order, then vv does not stay at BB: it cannot trap, and it writes no name of live(off(B))\mathrm{live}(\mathrm{off}(B)).

Proof. (a) is (E2) and (E4) with Lemma 5(a). (b) If v>Bv > B and vv stayed at BB, (E2) would give B≺vB \prec v. If v<Bv < B and vv stayed at BB, (E3) would give v≺Bv \prec B. □\square

So an operation moves above a branch only by speculation that is safe, and below a branch only when it is not needed on the exit and cannot trap. This is why no copy is needed.

The two runs. Run PP and P′P' from the label b1b_1, with states σ\sigma and σ′\sigma' that agree on live(b1)\mathrm{live}(b_1). PP runs the items in index order until a branch leaves or the end item. P′P' runs the items in the order π\pi until a branch leaves or the end item. Call XX the items that P′P' runs, a prefix of π\pi.

For an item uu and a name xx that it reads, let rw(u,x)\mathrm{rw}(u, x) be the last writer of xx among I0,…,Iu−1I_0, \dots, I_{u-1}, or "none". The ideal value val(u)\mathrm{val}(u) of an operation is its result when all operations run in index order as straight-line code from σ\sigma, with a special value ⊥\bot for an operation that traps or reads ⊥\bot. PP computes exactly the ideal values for the items it runs.

Lemma 7. The same values. Every item of XX reads the ideal values of its operands, and every operation of XX that does not trap computes its ideal value.

Proof. By induction along XX. Let u∈Xu \in X read xx. If w=rw(u,x)w = \mathrm{rw}(u, x) exists, then w≺uw \prec u by Lemma 5(b), so w∈Xw \in X before uu, since XX is a prefix of π\pi. Any other writer w′w' of xx in XX has w′<ww' < w, and then w′≺ww' \prec w, or w′>uw' > u, and then u≺w′u \prec w', by Lemma 5(b). So the last writer of xx before uu in XX is ww, and uu reads val(w)\mathrm{val}(w) by induction (ww did not trap, or the run would have stopped). If rw(u,x)\mathrm{rw}(u, x) is none, every writer of xx in XX comes after uu, so uu reads σ′(x)\sigma'(x). The trace path reads xx at uu with no write before it, so x∈live(b1)x \in \mathrm{live}(b_1) and σ′(x)=σ(x)\sigma'(x) = \sigma(x). □\square

Lemma 8. One superblock. Exactly one of these holds.

  1. Both runs trap.
  2. Both leave at the same branch BB to off(B)\mathrm{off}(B), with states that agree on live(off(B))\mathrm{live}(\mathrm{off}(B)).
  3. Both reach the end item. If it is ret a, both return the same value. Otherwise both go to the same successor of bkb_k, with states that agree on its live set.

Proof. PP leaves at a branch B∗B^* without a trap. Before B∗B^* in π\pi, P′P' meets: branches below B∗B^*, which are in index order (Lemma 6(a)) and read the same values as in PP (Lemma 7), so they stay on the superblock; operations below B∗B^* that are before B∗B^* in π\pi, which ran in PP without a trap and get the same operands; and operations above B∗B^* that are before B∗B^* in π\pi, which cannot trap by Lemma 6(b). So P′P' reaches B∗B^*, reads the same condition, and leaves to off(B∗)\mathrm{off}(B^*). Take x∈live(off(B∗))x \in \mathrm{live}(\mathrm{off}(B^*)). PP ran the writers of xx among the items below B∗B^*. P′P' ran the same writers: by Lemma 6(b), no operation that crossed B∗B^* writes xx. Their order is the same by Lemma 5(b), so the last writer is the same, and it computed the same value by Lemma 7. If there is no such writer, both states keep the value at b1b_1, and x∈live(b1)x \in \mathrm{live}(b_1) because the path through B∗B^* to off(B∗)\mathrm{off}(B^*) reads xx first. This is case 2.

PP reaches the end item without a trap. The same argument with the end item for B∗B^*. By Lemma 6(a), XX is all of π\pi, so both runs ran all items, with the same last writer of each name. The end item reads the same value. If it is ret, both return it. Otherwise both take the same target with states that agree on every name, and in particular on its live set. This is case 3.

PP traps at an operation oo. Then oo may trap. Suppose that P′P' does not trap. Then it leaves at a branch BB or reaches the end item. The branches before BB in π\pi stayed on the superblock in P′P' with the ideal values, so they stay in PP too, and BB leaves (or is the end) in PP too. As PP trapped first, o<Bo < B. Since oo may trap, it stays at BB, so (E3), or (E4) for the end item, gives o≺Bo \prec B, and o∈Xo \in X. By Lemma 7, oo got its ideal operands in P′P', the values with which it traps in PP. So P′P' traps, a contradiction. In the first two cases, P′P' ran only operations that do not trap. So this is case 1, and in cases 2 and 3 P′P' does not trap either. □\square

Theorem 9. PP and P′P' have the same outcome on every input, and P′P' has exactly as many instructions as PP.

Proof. The labels of P′P' are the labels of PP other than b2,…,bkb_2, \dots, b_k, plus the new pieces, which only pieces of the same superblock reach. By Lemma 2 and Lemma 3, the only edge into bib_i, i≥2i \ge 2, is from bi−1b_{i-1}, so no other block of PP refers to a removed label. We show, for each label LL of PP other than b2,…,bkb_2, \dots, b_k, that runs of PP and P′P' from LL with states that agree on live(L)\mathrm{live}(L) have the same outcome, by induction on LL in reverse topological order of PP. If L≠b1L \ne b_1, both have the same block at LL: they trap together, return the same value, or go to the same successor with states that agree on its live set, and that successor is not bib_i with i≥2i \ge 2 (it would be bi−1b_{i-1}, which is not LL) and comes later. If L=b1L = b_1, Lemma 8 applies; in case 2, off(B)\mathrm{off}(B) is not in the superblock and comes after b1b_1, and in case 3 the successor of bkb_k comes after b1b_1. The entry of PP is b1b_1 or not in the superblock, so it stays the entry. Line L14 puts every operation in exactly one piece, so no instruction is added or removed. □\square

Lemma 10. The rest of the loop. P′P' is acyclic, has only const, copy and op instructions, and every other superblock is still a path with a single entry in P′P'.

Proof. The pieces form a chain, and the edges out of the chain go to the exit targets and to the successors of bkb_k, which come after bkb_k or after some bib_i in PP; a cycle through the chain would give a cycle in PP. The instructions are the old ones. Scheduling changes only the blocks of this superblock and keeps the exit targets, so the edges into the blocks of other superblocks are the same as before. □\square

Summary

Formation keeps the outcome (Lemma 1), stops (Lemma 4), and gives superblocks with one entry each (Lemmas 2 and 3). Each scheduling step keeps the outcome and the instruction count (Theorem 9) and keeps the other superblocks valid (Lemma 10). So SUPERBLOCK-SCHEDULE stops, its output has the same outcome as its input on every input, and all its new instructions come from tail duplication, none from scheduling. ■\blacksquare

Complexity

Let nn be the number of items of one superblock, ss the number of instructions and terminators of the program after formation, NN the number of names and mm the number of superblocks.

  • Lines L3 to L7. The counts, the growth and the copies look at each edge and each instruction a constant number of times: O(s)O(s) per round.
  • Line L9. One backward pass in reverse topological order solves the liveness equations of an acyclic graph, with sets of at most NN names: O(sN)O(s N).
  • Lines L10 to L12. The DAG has O(n2)O(n^2) edges, and each one is made in O(1)O(1): O(n2)O(n^2).
  • Line L13. Heights in one pass over the edges, then a list schedule with a ready queue: O(n2+nlog⁡n)O(n^2 + n \log n), as the number of cycles is at most the sum of the latencies, O(n)O(n). The Python code scans all items for each choice, which is O(n3)O(n^3).
  • Line L14. O(n)O(n) for the pieces and O(s)O(s) for the rebuild.

So the run costs O(m(sN+n2))O(m (s N + n^2)) time and O(sN+n2)O(s N + n^2) space. Tail duplication can make ss exponential in the number of blocks of the input, since a tail copied in one round can be copied again in later rounds. Real compilers limit the length of a superblock and the amount of copied code.

Properties

  • Correct for every input. The profile only chooses the superblocks. A bad profile makes the code slower, never wrong.
  • No compensation code. All new instructions come from tail duplication, before scheduling. Scheduling only reorders.
  • Simpler than trace scheduling. There are no entrances in a superblock, so the scheduler needs no entrance items, no entrance copies and no rejoin blocks. The copies also make a superblock a better target for classic optimizations, since no other path reaches its middle.
  • The optimum is never worse than block by block. The best schedule of a superblock is at most the sum of the best schedules of its blocks. The list scheduler is a heuristic, so this holds for the optimum, not for every list schedule.
  • Less freedom at exits. An operation whose result is live on an exit cannot move below it, so some schedules of trace scheduling are not possible, as for s in the example.
  • Code growth. Each side entrance copies the whole tail after it, also code that is not on the hot path.

Variants and improvements

  • Superblock optimizations (Hwu et al. 1993). Since a superblock has one entry, the compiler can unroll superblock loops, rename registers and expand accumulators and induction variables inside it before scheduling, to remove dependences.
  • Speculation with hardware help. With instructions that do not trap, such as non-trapping loads, the scheduler can also move operations that may trap above an exit. The IMPACT papers compare such scheduling models (Chang et al. 1991).
  • Hyperblocks (Mahlke et al. 1992). If-conversion turns several paths into one block with one entry and predicated instructions, so that a rare path no longer cuts the hot one.
  • Better traces. Path profiles give the real hot paths instead of a chain of locally likely edges. A tracing JIT records a hot path at run time and compiles it as a superblock-like trace with one entry and many exits.
  • Loops. The superblock stops at a back edge. Loop unrolling gives longer superblocks, and software pipelining overlaps iterations instead.

When to use it

Use it for a wide in-order machine, such as a VLIW or EPIC processor, on code with small blocks and branches that a profile can predict, when a simple scheduler matters more than code size. It suits compilers that run classic optimizations on the hot path too, since a superblock is easier to optimize than a trace with entrances. Prefer trace scheduling when code size is tight, or when moving an operation below an exit matters. On an out-of-order processor the gain is smaller. For loops with many iterations, use iterative modulo scheduling.

Pitfalls

  • Moving the trace edge to the copy. If line L6 sends every edge into bib_i to cic_i, the edge from bi−1b_{i-1} also goes to the copy, and bib_i is no longer reached from the trace. Move only the edges from predecessors p≠bi−1p \ne b_{i-1}.
  • Copies that point back into the tail. If line L5 keeps the targets of bib_i in cic_i, the copy jumps to bi+1b_{i+1}, which gets a new side entrance from cic_i. The copy edges into bmb_m, m≥jm \ge j, must go to cmc_m.
  • Starting the copy at the last side entrance. If line L4 takes the greatest such ii, the earlier side entrances stay in the superblock. Take the least ii, so that the copied tail covers all of them.
  • Moving a live write below an exit. If line L12 is left out, as in a trace scheduler that relies on copies, an operation can move below an exit whose path reads its result, and the rare path reads an old value. In the example, s would move below the exit and the run on (1,7)(1, 7) would read s before any write. Keep line L12, or add compensation code.
  • Speculating an operation that can trap. If line L11 adds edges only for live names, a division from below an exit can move above it, and a run that leaves at that exit with a divisor of 0 traps where the input did not. Line L11 must also add the edge for every operation that may trap.
  • Stale live sets. If line L9 runs once on the input, the copies have no live sets and the exit targets of later superblocks have the wrong ones. Compute live-in sets on the current program.

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.

superblock_scheduling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/superblock-scheduling/. The authors are listed in prov/WWP2JP.jsonl.
"""Superblock formation by tail duplication and superblock scheduling, on
the toy IR.

superblock_schedule(prog, freq) takes a toy IR program with an acyclic
control flow graph and only const, copy and op instructions, and an edge
profile freq (a dict from an edge (a, b) to a count).

Formation. While some block is in no superblock, pick a trace among those
blocks (the block of highest count, grown along edges that are the most
likely way out of one end and the most likely way into the other end). If
some block b_j, j >= 2, of the trace has a predecessor other than b_(j-1),
copy the tail b_j .. b_k and send every such side edge to the copy. Then
the trace has one entry, at its head: it is a superblock. The copies are new
blocks and later get superblocks of their own.

Scheduling. Each superblock is list scheduled as one block. Its only side
paths are side exits, so no compensation code is needed if an operation
moves above a side exit only when it cannot trap and its result is dead on
the exit, and moves below a side exit only under the same two conditions.

The machine: each cycle issues at most `width` items, at most cap[u] of
unit u. A multiply, divide or remainder uses "mul" (latency 3), a branch or
the last terminator "br" (latency 1), and the other operations "alu"
(latency 1). The scheduled superblock runs its items in the order (cycle,
original position), so a dependence with delay 0 lets two items share a
cycle.

Cost: with s instructions and terminators, N names, n items in a
superblock and m superblocks, O(m (s N + n^2)) time besides the Python
list scheduler, which is O(n^3) per superblock. Tail duplication can make s
grow exponentially in the number of blocks in the worst case.
"""

import toyir

MACHINE = {"width": 2, "cap": {"mul": 1, "br": 1}}
LATENCY = {"alu": 1, "mul": 3, "br": 1}


class Item:
    """One item of a superblock: an operation ("op"), a side exit ("br")
    or the terminator of the last block ("end")."""

    def __init__(self, kind, blk, ins=None, term=None, off=None):
        self.kind = kind
        self.blk = blk
        self.ins = ins
        self.term = term
        self.off = off
        if kind == "op":
            self.uses = toyir.uses(ins)
            self.defs = toyir.defs(ins)
        else:
            self.uses = toyir.term_uses(term)
            self.defs = None

    def unit(self):
        if self.kind != "op":
            return "br"
        if self.ins[0] == "op" and self.ins[2] in ("*", "/", "%"):
            return "mul"
        return "alu"

    def latency(self):
        return LATENCY[self.unit()]


def can_trap(ins):
    if ins[0] in ("const", "copy"):
        return False
    if ins[0] != "op":
        return True
    op, b = ins[2], ins[4]
    if op in ("/", "%"):
        return not (isinstance(b, int) and b != 0)
    if op in ("<<", ">>"):
        return not (isinstance(b, int) and 0 <= b <= 63)
    return False


def check_input(prog):
    if not toyir.is_acyclic(prog):
        raise ValueError("superblock scheduling here needs an acyclic CFG")
    for b in prog.blocks.values():
        for ins in b.instrs:
            if ins[0] not in ("const", "copy", "op"):
                raise ValueError("only const, copy and op instructions: %r" % (ins,))


def topological_order(prog):
    order, seen = [], set()
    for root in prog.blocks:
        if root in seen:
            continue
        seen.add(root)
        stack = [(root, iter(toyir.succs(prog, root)))]
        while stack:
            v, it = stack[-1]
            w = next(it, None)
            if w is None:
                order.append(v)
                stack.pop()
            elif w not in seen:
                seen.add(w)
                stack.append((w, iter(toyir.succs(prog, w))))
    order.reverse()
    return order


def liveness(prog):
    """live_in[label]: the names that some path from the start of the block
    reads before it writes them. One backward pass in reverse topological
    order, which is exact on an acyclic graph."""
    live_in = {}
    for lab in reversed(topological_order(prog)):
        b = prog.blocks[lab]
        live = set()
        for s in toyir.succs(prog, lab):
            live |= live_in[s]
        live |= set(toyir.term_uses(b.term))
        for ins in reversed(b.instrs):
            live.discard(toyir.defs(ins))
            live |= set(toyir.uses(ins))
        live_in[lab] = live
    return live_in


# ---------------------------------------------------------------- profiles


def profile(prog, inputs):
    """Edge counts from runs of prog on the inputs (a run that traps
    counts the edges it took before the trap)."""
    freq = {e: 0 for e in toyir.edges(prog)}
    for args in inputs:
        env = dict(zip(prog.params, args))
        lab = prog.entry
        try:
            while True:
                b = prog.blocks[lab]
                for ins in b.instrs:
                    env[ins[1]] = _value(ins, env)
                t = b.term
                if t[0] == "ret":
                    break
                if t[0] == "jump":
                    nxt = t[1]
                else:
                    nxt = t[2] if _operand(t[1], env) != 0 else t[3]
                freq[(lab, nxt)] += 1
                lab = nxt
        except toyir._Trap:
            pass
    return freq


def _operand(a, env):
    return a if isinstance(a, int) else env[a]


def _value(ins, env):
    if ins[0] == "const":
        return ins[2]
    if ins[0] == "copy":
        return _operand(ins[2], env)
    return toyir._binop(ins[2], _operand(ins[3], env), _operand(ins[4], env))


def static_profile(prog):
    """A guess without runs: the entry runs once and each br splits evenly."""
    bf = {lab: 0.0 for lab in prog.blocks}
    bf[prog.entry] = 1.0
    freq = {}
    for lab in topological_order(prog):
        ss = toyir.succs(prog, lab)
        for s in ss:
            freq[(lab, s)] = bf[lab] / len(ss)
            bf[s] += freq[(lab, s)]
    return freq


# ---------------------------------------------------------------- formation


def pick_trace(prog, freq, done):
    """The seed is the block outside every superblock with the highest
    count. The trace grows from its last block a to the most likely
    successor b, and from its first block b to the most likely predecessor
    a, only while a is also the most likely predecessor of b (or b the most
    likely successor of a) and the new block is in no superblock. The entry
    block is always the head of its trace."""
    pr = toyir.preds(prog)
    rank = {lab: i for i, lab in enumerate(prog.blocks)}
    inn = {lab: 0 for lab in prog.blocks}
    out = {lab: 0 for lab in prog.blocks}
    for a, b in toyir.edges(prog):
        out[a] += freq.get((a, b), 0)
        inn[b] += freq.get((a, b), 0)

    def count(lab):
        return max(inn[lab], out[lab])

    def best_succ(a):
        return max(toyir.succs(prog, a), key=lambda b: (freq.get((a, b), 0), -rank[b]), default=None)

    def best_pred(b):
        return max(pr[b], key=lambda a: (freq.get((a, b), 0), -rank[a]), default=None)

    seed = max((lab for lab in prog.blocks if lab not in done), key=lambda lab: (count(lab), -rank[lab]))
    trace = [seed]
    while True:
        b = best_succ(trace[-1])
        if b is None or b in done or b in trace or b == prog.entry or best_pred(b) != trace[-1]:
            break
        trace.append(b)
    while trace[0] != prog.entry:
        a = best_pred(trace[0])
        if a is None or a in done or a in trace or best_succ(a) != trace[0]:
            break
        trace.insert(0, a)
    return trace


def _fresh(taken, base):
    k = 1
    while "%s.%d" % (base, k) in taken:
        k += 1
    lab = "%s.%d" % (base, k)
    taken.add(lab)
    return lab


def _retarget(term, old, new):
    if term[0] == "jump":
        return ("jump", new) if term[1] == old else term
    if term[0] == "br":
        return ("br", term[1], new if term[2] == old else term[2], new if term[3] == old else term[3])
    return term


def tail_duplicate(prog, trace, freq):
    """Copy the trace from its first side entrance to its end and send the
    side entrances to the copy. Returns (new program, new edge counts)."""
    pr = toyir.preds(prog)
    k = len(trace)
    side = [i for i in range(1, k) if any(p != trace[i - 1] for p in pr[trace[i]])]  # @line L4
    if not side:
        return prog, dict(freq)
    j = side[0]
    taken = set(prog.blocks)
    copy_of = {trace[i]: _fresh(taken, trace[i]) for i in range(j, k)}
    blocks = {lab: toyir.Block(list(b.instrs), b.term) for lab, b in prog.blocks.items()}
    for i in range(j, k):  # @line L5
        lab = trace[i]
        term = prog.blocks[lab].term
        # A copy is never the trace predecessor of a tail block, so every
        # edge from a copy into the tail goes to the copy of the target.
        for s in toyir.succs(prog, lab):
            if s in copy_of:
                term = _retarget(term, s, copy_of[s])
        blocks[copy_of[lab]] = toyir.Block(list(prog.blocks[lab].instrs), term)
    for i in range(j, k):
        lab = trace[i]
        for p in pr[lab]:
            if p != trace[i - 1]:
                blocks[p].term = _retarget(blocks[p].term, lab, copy_of[lab])  # @line L6
    new = toyir.Program(list(prog.params), blocks)
    return new, _split_counts(prog, new, trace, j, copy_of, freq)


def _split_counts(prog, new, trace, j, copy_of, freq):
    """Edge counts for the program after tail duplication. The out-counts
    of a tail block are split between it and its copy in the ratio of the
    flow that now enters the copy to the flow that entered the block."""
    orig = {c: lab for lab, c in copy_of.items()}
    pr_old = toyir.preds(prog)
    pr_new = toyir.preds(new)
    ratio = {}

    def weight(a, b):
        a0, b0 = orig.get(a, a), orig.get(b, b)
        w = freq.get((a0, b0), 0)
        if a0 in ratio:
            w = w * ratio[a0] if a in orig else w * (1 - ratio[a0])
        return w

    for i in range(j, len(trace)):
        lab = trace[i]
        total = sum(freq.get((p, lab), 0) for p in pr_old[lab])
        inflow = sum(weight(p, copy_of[lab]) for p in pr_new[copy_of[lab]])
        ratio[lab] = min(1, inflow / total) if total else 0
    return {(a, b): weight(a, b) for a, b in toyir.edges(new)}


def form_superblocks(prog, freq):
    """Returns (program, list of superblocks, edge counts). Each
    superblock is a path of blocks whose only entry is its head."""
    done = set()  # @line L1
    superblocks = []
    while any(lab not in done for lab in prog.blocks):  # @line L2
        trace = pick_trace(prog, freq, done)  # @line L3
        prog, freq = tail_duplicate(prog, trace, freq)
        superblocks.append(trace)  # @line L7
        done |= set(trace)
    return prog, superblocks, freq


# ---------------------------------------------------------------- scheduling


def superblock_items(prog, sb):
    """The items of the superblock in their original order."""
    items = []
    for i, lab in enumerate(sb):
        b = prog.blocks[lab]
        for ins in b.instrs:
            items.append(Item("op", i, ins=ins))
        t = b.term
        if i == len(sb) - 1:
            items.append(Item("end", i, term=t))
        elif t[0] == "br" and t[2] != t[3]:
            off = t[3] if t[2] == sb[i + 1] else t[2]
            items.append(Item("br", i, term=t, off=off))
    return items


def _stays(it, live):
    """An operation must stay on its side of a side exit if it can trap or
    if it writes a name that is live on the exit."""
    return can_trap(it.ins) or it.defs in live


def build_dag(items, live_in):
    """Edges (u, v) -> delay, all with u < v."""
    edges = {}

    def add(u, v, d):
        edges[(u, v)] = max(edges.get((u, v), d), d)

    last_def = {}
    readers = {}
    for v, it in enumerate(items):
        for x in it.uses:
            if x in last_def:
                add(last_def[x], v, items[last_def[x]].latency())
        x = it.defs
        if x is not None:
            if x in last_def:
                add(last_def[x], v, 1)
            for r in readers.get(x, []):
                add(r, v, 0)
        for y in it.uses:
            readers.setdefault(y, []).append(v)
        if x is not None:
            last_def[x] = v
            readers[x] = []
    for b, it in enumerate(items):
        if it.kind != "br":
            continue
        live = live_in[it.off]
        for v in range(b + 1, len(items)):  # @line L11
            w = items[v]
            if w.kind != "op" or _stays(w, live):
                add(b, v, 0)
        for u in range(b):  # @line L12
            w = items[u]
            if w.kind == "op" and _stays(w, live):
                add(u, b, 0)
    end = len(items) - 1
    for u in range(end):
        add(u, end, 0)
    return edges


def heights(items, edges):
    h = [it.latency() for it in items]
    succ = {}
    for (u, v), d in edges.items():
        succ.setdefault(u, []).append((v, d))
    for u in range(len(items) - 1, -1, -1):
        for v, d in succ.get(u, []):
            h[u] = max(h[u], d + h[v])
    return h


def fits(it, used, machine):
    u = it.unit()
    return len(used) < machine["width"] and used.count(u) < machine["cap"].get(u, machine["width"])


def list_schedule(items, edges, machine=MACHINE):
    """Cycle by cycle, start the ready item of greatest height that fits,
    until no ready item fits; then go to the next cycle."""
    n = len(items)
    preds = [[] for _ in range(n)]
    for (u, v), d in edges.items():
        preds[v].append((u, d))
    h = heights(items, edges)
    t = {}
    cyc = 0
    while len(t) < n:
        used = []
        while True:
            ready = [v for v in range(n) if v not in t and all(u in t and t[u] + d <= cyc for u, d in preds[v])]
            ok = [v for v in ready if fits(items[v], used, machine)]
            if not ok:
                break
            v = max(ok, key=lambda v: (h[v], -v))
            t[v] = cyc
            used.append(items[v].unit())
        cyc += 1
    return t


def length(items, t):
    return max(t[v] + items[v].latency() for v in range(len(items)))


def schedule_superblock(prog, sb, machine=MACHINE):
    """Schedule one superblock. Returns (new program, labels of its
    pieces, (items, t))."""
    live_in = liveness(prog)  # @line L9
    items = superblock_items(prog, sb)
    edges = build_dag(items, live_in)  # @line L10
    t = list_schedule(items, edges, machine)  # @line L13
    order = sorted(range(len(items)), key=lambda v: (t[v], v))
    taken = set(prog.blocks)
    head = sb[0]
    pieces = {}
    cur, body = head, []
    for v in order:  # @line L14
        it = items[v]
        if it.kind == "op":
            body.append(it.ins)
        elif it.kind == "br":
            nxt = _fresh(taken, head)
            c = it.term
            term = ("br", c[1], it.off, nxt) if c[2] == it.off else ("br", c[1], nxt, it.off)
            pieces[cur] = toyir.Block(body, term)
            cur, body = nxt, []
        else:
            pieces[cur] = toyir.Block(body, it.term)
    blocks = {}
    for lab, b in prog.blocks.items():
        if lab == head:
            blocks.update(pieces)
        elif lab not in sb:
            blocks[lab] = b
    return toyir.Program(list(prog.params), blocks), list(pieces), (items, t)


def superblock_schedule(prog, freq=None, machine=MACHINE):
    """Form superblocks, then schedule each one. Returns (new program,
    list of superblocks, list of (items, t) for each superblock)."""
    check_input(prog)
    if freq is None:
        freq = static_profile(prog)
    prog, superblocks, _ = form_superblocks(prog, freq)
    log = []
    for sb in superblocks:  # @line L8
        prog, _, sched = schedule_superblock(prog, sb, machine)
        log.append(sched)
    return prog, superblocks, log  # @line L15
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_superblock_scheduling.py 248 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/superblock-scheduling/. The authors are listed in prov/WWP2JP.jsonl.
import random

import pytest

import toyir
import superblock_scheduling as sbs

EXAMPLE = """# params: a, b
B0:
  c = b < 5
  s = a - b
  br c B1 B2
B1:
  y = a / b
  jump B3
B2:
  y = a - 1
  jump B3
B3:
  w = b + 1
  v = w * w
  z = y + v
  r = z + s
  ret r
"""
EXAMPLE_FREQ = {("B0", "B1"): 90, ("B0", "B2"): 10, ("B1", "B3"): 90, ("B2", "B3"): 10}


def same_meaning(p, q, inputs):
    return all(toyir.run(p, a) == toyir.run(q, a) for a in inputs)


def grid():
    return [[a, b] for a in range(-6, 7) for b in range(-6, 8)]


def ninstrs(prog):
    return sum(len(b.instrs) for b in prog.blocks.values())


def legal(items, edges, t, machine):
    for (u, v), d in edges.items():
        if u in t and v in t and t[v] < t[u] + d:
            return False
    by_cycle = {}
    for v in t:
        by_cycle.setdefault(t[v], []).append(items[v].unit())
    for units in by_cycle.values():
        if len(units) > machine["width"]:
            return False
        for u, m in machine["cap"].items():
            if units.count(u) > m:
                return False
    return True


def brute_optimum(items, edges, machine):
    """Try every start cycle for every item, in index order (a topological
    order), and keep the shortest legal schedule."""
    n = len(items)
    horizon = sum(it.latency() for it in items) + 1
    preds = [[] for _ in range(n)]
    for (u, v), d in edges.items():
        preds[v].append((u, d))
    best = [horizon + 10]

    def rec(j, t):
        if j == n:
            assert legal(items, edges, t, machine)
            best[0] = min(best[0], sbs.length(items, t))
            return
        lo = max([t[u] + d for u, d in preds[j]], default=0)
        for c in range(lo, horizon):
            if c + items[j].latency() >= best[0]:
                break
            t[j] = c
            if legal(items, {}, t, machine):
                rec(j + 1, t)
            del t[j]

    rec(0, {})
    return best[0]


def test_example_formation():
    p = toyir.parse(EXAMPLE)
    f, superblocks, freq = sbs.form_superblocks(p, EXAMPLE_FREQ)
    assert superblocks == [["B0", "B1", "B3"], ["B2", "B3.1"]]
    assert f.blocks["B2"].term == ("jump", "B3.1")
    assert f.blocks["B3.1"].instrs == f.blocks["B3"].instrs
    assert toyir.preds(f)["B3"] == ["B1"]
    assert freq[("B2", "B3.1")] == 10 and freq[("B1", "B3")] == 90
    assert same_meaning(p, f, grid())


def test_example_schedule():
    p = toyir.parse(EXAMPLE)
    q, superblocks, log = sbs.superblock_schedule(p, EXAMPLE_FREQ)
    items, t = log[0]
    got = {it.ins[1]: t[v] for v, it in enumerate(items) if it.kind == "op"}
    assert got == {"c": 0, "s": 1, "y": 2, "w": 0, "v": 3, "z": 6, "r": 7}
    assert [(it.kind, t[v]) for v, it in enumerate(items) if it.kind != "op"] == [("br", 1), ("end", 8)]
    assert sbs.length(items, t) == 9
    f, _, _ = sbs.form_superblocks(p, EXAMPLE_FREQ)
    live = sbs.liveness(f)
    assert live["B2"] == {"a", "b", "s"}
    assert brute_optimum(items, sbs.build_dag(items, live), sbs.MACHINE) == 8
    assert list(q.blocks) == ["B0", "B0.1", "B2"]
    assert q.blocks["B0"].instrs == [("op", "c", "<", "b", 5), ("op", "w", "+", "b", 1), ("op", "s", "-", "a", "b")]
    assert q.blocks["B0"].term == ("br", "c", "B0.1", "B2")
    assert sbs.length(*log[1]) == 7
    assert ninstrs(q) == ninstrs(f)
    assert same_meaning(p, q, grid())
    assert toyir.run(q, [1, 7]) == ("ret", 58)
    assert toyir.run(q, [4, 2]) == ("ret", 13)
    assert toyir.run(q, [4, 0]) == ("trap",)


def test_formation_on_random_programs():
    rng = random.Random(11)
    for _ in range(150):
        p = toyir.random_program(rng, rng.randint(2, 6), rng.randint(1, 8), True)
        freq = {e: rng.randint(0, 9) for e in toyir.edges(p)}
        f, superblocks, _ = sbs.form_superblocks(p, freq)
        assert toyir.is_acyclic(f)
        assert f.entry == p.entry and any(sb[0] == p.entry for sb in superblocks)
        assert sorted(lab for sb in superblocks for lab in sb) == sorted(f.blocks)
        pr = toyir.preds(f)
        for sb in superblocks:
            for i in range(1, len(sb)):
                assert pr[sb[i]] == [sb[i - 1]]
                assert sb[i] in toyir.succs(f, sb[i - 1])
        inputs = [[rng.randint(-6, 9), rng.randint(-6, 9)] for _ in range(20)]
        assert same_meaning(p, f, inputs)


def test_meaning_random_programs():
    rng = random.Random(12)
    for _ in range(120):
        p = toyir.random_program(rng, rng.randint(2, 6), rng.randint(1, 8), True)
        freq = {e: rng.randint(0, 9) for e in toyir.edges(p)}
        q, _, _ = sbs.superblock_schedule(p, freq)
        assert toyir.is_acyclic(q)
        f, _, _ = sbs.form_superblocks(p, freq)
        assert ninstrs(q) == ninstrs(f)
        inputs = [[rng.randint(-6, 9), rng.randint(-6, 9)] for _ in range(25)]
        assert same_meaning(p, q, inputs)


def test_meaning_with_profiles():
    rng = random.Random(13)
    for _ in range(35):
        p = toyir.random_program(rng, rng.randint(2, 6), rng.randint(2, 8), True)
        inputs = [[rng.randint(-6, 9), rng.randint(-6, 9)] for _ in range(25)]
        for freq in (sbs.profile(p, inputs), sbs.static_profile(p), None):
            q, _, _ = sbs.superblock_schedule(p, freq)
            assert same_meaning(p, q, inputs)


def potential(prog, done):
    memo = {}

    def paths(lab):
        if lab not in memo:
            s = toyir.succs(prog, lab)
            memo[lab] = 1 if lab in done or not s else sum(paths(x) for x in s)
        return memo[lab]

    return sum(paths(lab) for lab in prog.blocks if lab not in done)


def test_formation_stops():
    rng = random.Random(14)
    for _ in range(200):
        prog = toyir.random_program(rng, 3, rng.randint(2, 9), True)
        freq = {e: rng.randint(0, 9) for e in toyir.edges(prog)}
        done = set()
        phi = potential(prog, done)
        while any(lab not in done for lab in prog.blocks):
            trace = sbs.pick_trace(prog, freq, done)
            prog, freq = sbs.tail_duplicate(prog, trace, freq)
            done |= set(trace)
            nphi = potential(prog, done)
            assert nphi < phi
            phi = nphi


def test_motion_rules():
    rng = random.Random(15)
    seen = {"above": 0, "below": 0}
    for _ in range(120):
        p = toyir.random_program(rng, rng.randint(2, 6), rng.randint(2, 8), True)
        freq = {e: rng.randint(0, 9) for e in toyir.edges(p)}
        prog, superblocks, _ = sbs.form_superblocks(p, freq)
        for sb in superblocks:
            live = sbs.liveness(prog)
            new, _, (items, t) = sbs.schedule_superblock(prog, sb)
            pos = {v: k for k, v in enumerate(sorted(range(len(items)), key=lambda v: (t[v], v)))}
            for b, it in enumerate(items):
                if it.kind != "br":
                    continue
                for v, w in enumerate(items):
                    if w.kind != "op":
                        assert (v < b) == (pos[v] < pos[b])
                        continue
                    if (v < b) != (pos[v] < pos[b]):
                        assert not sbs.can_trap(w.ins) and w.defs not in live[it.off]
                        seen["above" if v > b else "below"] += 1
            prog = new
    assert min(seen.values()) > 20


def test_schedules_against_brute_force():
    rng = random.Random(16)
    checked = 0
    while checked < 60:
        p = toyir.random_program(rng, 3, rng.randint(2, 4), True)
        freq = {e: rng.randint(0, 9) for e in toyir.edges(p)}
        f, superblocks, _ = sbs.form_superblocks(p, freq)
        sb = superblocks[0]
        live = sbs.liveness(f)
        items = sbs.superblock_items(f, sb)
        if len(items) > 9:
            continue
        edges = sbs.build_dag(items, live)
        assert all(u < v for u, v in edges)
        t = sbs.list_schedule(items, edges)
        assert legal(items, edges, t, sbs.MACHINE)
        best = brute_optimum(items, edges, sbs.MACHINE)
        assert sbs.length(items, t) >= best
        local = 0
        for lab in sb:
            one = sbs.superblock_items(f, [lab])
            local += brute_optimum(one, sbs.build_dag(one, live), sbs.MACHINE)
        assert best <= local
        checked += 1


def test_input_checks():
    with pytest.raises(ValueError):
        sbs.superblock_schedule(toyir.parse("B0:\n  x = 1\n  br x B1 B0\nB1:\n  ret x\n"))
    with pytest.raises(ValueError):
        sbs.superblock_schedule(toyir.parse("# params: p\nB0:\n  x = *p\n  ret x\n"))
    one = toyir.parse("# params: a\nB0:\n  x = a + 1\n  ret x\n")
    q, superblocks, _ = sbs.superblock_schedule(one)
    assert superblocks == [["B0"]] and toyir.run(q, [4]) == ("ret", 5)

History

Fisher introduced trace scheduling in 1981, with a bookkeeping phase that copies operations onto the side entrances and exits of a trace. Chang and Hwu (1988) studied trace selection for C programs in the IMPACT compiler at the University of Illinois. In 1991 Chang, Mahlke, Chen, Warter and Hwu used superblocks in the IMPACT-I C compiler to measure scheduling models, issue rates and load latencies for multiple-issue processors. Hwu and eleven coauthors gave the full account in 1993: trace selection, tail duplication, a set of optimizations on superblocks, and superblock scheduling, with large speedups on a 4-issue processor. Mahlke and others extended the idea to hyperblocks with predication in 1992. The idea of a region with one entry and many exits reappeared in dynamic optimizers and tracing JIT compilers.

References

  1. Wen-mei W. Hwu, Scott A. Mahlke, William Y. Chen, Pohua P. Chang, Nancy J. Warter, Roger A. Bringmann, Roland G. Ouellette, Richard E. Hank, Tokuzo Kiyohara, Grant E. Haab, John G. Holm and Daniel M. Lavery, The superblock, an effective technique for VLIW and superscalar compilation, The Journal of Supercomputing 7(1-2), 1993, 229-248, the definition of a superblock as a trace with one entry and one or more exits, its formation by trace selection and tail duplication, the superblock optimizations, and superblock scheduling
  2. Pohua P. Chang, Scott A. Mahlke, William Y. Chen, Nancy J. Warter and Wen-mei W. Hwu, IMPACT, an architectural framework for multiple-instruction-issue processors, Proceedings of the 18th Annual International Symposium on Computer Architecture, 1991, 266-275, the experiments on the code scheduling model, the issue rate, the load latency and the limits of the function units for code from the IMPACT-I C compiler
  3. Pohua P. Chang and Wen-mei W. Hwu, Trace selection for compiling large C application programs to microcode, Proceedings of the 21st Annual Workshop on Microprogramming and Microarchitecture, 1988, 21-29, Section 4 on trace selection by node weights and arc weights from a seed with the best successor and the best predecessor
  4. Scott A. Mahlke, David C. Lin, William Y. Chen, Richard E. Hank and Roger A. Bringmann, Effective compiler support for predicated execution using the hyperblock, Proceedings of the 25th Annual International Symposium on Microarchitecture, 1992, 45-54, the hyperblock, a block with one entry formed from several paths by if-conversion and predication, as an extension of the superblock

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.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
  • a scene preset for the example