Algorithmadvanced
Trace scheduling
Also called Fisher trace scheduling.
Schedules a likely path through several blocks as one block and adds compensation code where other paths enter or leave it.
- Solves
- Instruction scheduling
- 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 traces; n = the number of items of one trace; s = the number of instructions and terminators of the largest program during the run
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Joseph A. Fisher, 1981
Trace scheduling is a global instruction scheduling method. It picks a trace, a path through several basic blocks that a profile says is likely, and schedules the whole trace as if it were one block. So an instruction can move above a branch or below the point where another path joins, which a block-by-block scheduler cannot do. The other paths must still compute the same values. When an instruction moves below a side exit (a branch that leaves the trace), a copy goes on the edge that leaves. When an instruction moves above a side entrance (a point where another path joins the trace), a copy goes on the edge that joins. These copies are the compensation code. Fisher (1981) introduced the method to compact horizontal microcode. It became the main scheduler of the first commercial VLIW compilers.
In plain words
A program often takes the same way through its branches. Trace scheduling finds that usual way, treats it as one long straight line of code, and packs the instructions of that line tightly, so that a wide machine can run several of them in each cycle. Packing moves some instructions past the branches. Then a run that leaves the usual way at a branch could miss an instruction that it needs, and a run that comes in from the side could miss one that moved up past its entry point. So the method puts a copy of each such instruction on the side path. The usual way gets faster, and the rare ways get a little slower and a little longer. The method then packs the next most usual way, until all code is done.
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). The machine issues 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 traces. Loops are not handled here: real compilers unroll a loop and schedule traces inside its body, or use software pipelining.
The algorithm
TRACE-SCHEDULE(P, freq)- 1
while some block of P is not scheduled do - 2
T <- the seed of highest count, grown along edges that are most likely at both ends, never backward past the entry - 3
live <- the live-in sets of P - 4
D <- the dependence DAG of the items of T: data edges, branches in order, the end item last - 5
add an edge from each branch B to each later operation that may trap or whose result is in live(off(B)) - 6
add an edge from each item to each later entrance, and from each entrance to each later branch - 7
S <- a list schedule of D by height; order the items by (cycle, original position) - 8
for each branch B of T do - 9
C <- the operations from above B that S puts after B - 10
put copies of C, in the order of S, in a new block on the off-trace edge of B - 11
for each entrance J of T into a block b do - 12
C <- the operations from below J that S puts before J - 13
put copies of C, in the order of S, in a new block that takes the label b and jumps to the code after J - 14
replace T by S cut after each branch and at each entrance; mark the pieces scheduled; update freq - 15
return P
Trace selection (line L2). The seed is the block not yet scheduled with the highest count, the larger of the sums of its incoming and its outgoing edge counts. The trace grows forward from its last block to the successor of the largest edge count, but only if is also the predecessor of with the largest count, and is not yet scheduled. It grows backward in the same way, and it stops at the entry block, so that the entry stays the head of its trace. This is the mutual most likely rule. Chang and Hwu (1988) describe this growth from a seed with a best successor and a best predecessor.
Items (line L4). In the original order, the items of the trace are: an entrance for each , , that has a predecessor other than ; the instructions of each block; a branch item for each br of , , whose other target is off the trace; and the end item, the terminator of . An entrance takes no issue slot.
Dependences (lines L4 to L6). The data edges are the usual 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, so the two items can issue in the same cycle with the reader first. The branches keep their order, and every item comes before the end item. Line L5 lets an operation move above a branch only if it cannot trap and its result is dead on the off-trace edge. Such a motion is speculation: the operation runs also on runs that leave, and does nothing visible there. Line L6 keeps every item that is above an entrance above it, and keeps the order of entrances and branches. An operation may still move above an entrance.
Compensation (lines L8 to L13). An operation from above a branch that the schedule puts after does not run on a run that leaves at . So lines L9 and L10 put a copy of it on that edge. An operation from below an entrance that the schedule puts before does not run on a run that comes in at . So lines L12 and L13 put a copy of it on the side edges: the new block takes the label of , which all side edges already use, and it jumps to the code after . The trace edge from goes straight to that code.
Cutting (line L14). The schedule becomes blocks: a new block starts after each branch and at each entrance. The first piece keeps the label . The compensation blocks are not scheduled yet, so later traces schedule them with their neighbors.
Example
Take this program with parameters a and b, and the profile 90 for and , and 10 for and :
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
Line L2 picks , the block of highest count, and grows it to the trace . Line L3 gives . The items, with their units, latencies and heights, are:
| index | item | unit | latency | height |
|---|---|---|---|---|
| 0 | c = b < 5 |
alu | 1 | 7 |
| 1 | s = a - b |
alu | 1 | 3 |
| 2 | branch, off | br | 1 | 6 |
| 3 | y = a / b |
mul | 3 | 6 |
| 4 | entrance into | none | 0 | 1 |
| 5 | w = b + 1 |
alu | 1 | 7 |
| 6 | v = w * w |
mul | 3 | 6 |
| 7 | z = y + v |
alu | 1 | 3 |
| 8 | r = z + s |
alu | 1 | 2 |
| 9 | ret r |
br | 1 | 1 |
Line L5 adds the edge from the branch 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 . Line L6 keeps items 0 to 3 above the entrance. The list scheduler gives:
| cycle | ready, by height | issued |
|---|---|---|
| 0 | c, w, s |
c, w |
| 1 | branch, v, s, then y once the branch issues |
branch, y |
| 2 | v, s, then the entrance |
v, s, entrance |
| 3, 4 | none | none |
| 5 | z |
z |
| 6 | r |
r |
| 7 | ret r |
ret r |
The length is cycles. This is optimal. The two multiply-unit operations y and v cannot start at cycle 0, because y waits for the branch and v waits for w, and they cannot share cycle 1. So one of them starts at 2 or later, z starts at 5 or later, and ret r at 7 or later. Block by block, the best schedules of , and take 2, 3 and 7 cycles, so the same path takes 12.
Two motions need copies. s moved below the branch, so line L10 puts s = a - b on the edge to . w moved above the entrance into (and above the branch, which line L5 allows since w is dead at ), so line L13 makes a block with label that computes w and jumps to the code after the entrance. y = a / b stays below the branch. The second trace is the exit block, and the entrance block, which have no side entrance and become one block. The output is:
B0:
c = b < 5
w = b + 1
br c B0.1 B0.2
B0.1:
y = a / b
s = a - b
jump B0.3
B0.3:
v = w * w
z = y + v
r = z + s
ret r
B0.2:
s = a - b
y = a - 1
w = b + 1
jump B0.3
On both programs take the rare path and return 58. On both return 13, and on both trap. Without the copy of s in B0.2, the run on would read s before any write. The copy of w in B0.2 is correct but not needed here: the only side entrance comes after B0, which has already computed w. Removing such copies is the subject of Freudenberger, Gross and Lowney (1994).
Correctness
Theorem. On every input, the output of TRACE-SCHEDULE returns the same value as the input program, or traps exactly when the input program traps. The loop of line L1 stops.
The full proof is in the proof file. It goes one trace at a time. The dependence edges make the schedule keep the order of any two items that read or write the same name, and keep the branches and entrances in their original order. So from the head or from an entrance, the new code runs the same items as the old code with the same last writer for every read, up to the point where a run leaves. At a side exit, an operation from below that ran early cannot trap and wrote only a name that is dead there (line L5), and an operation from above that did not run yet is in the exit block (line L10). So both runs leave with the same values of the live names. The same holds at the end of the trace, and a trap happens in both runs or in neither. An induction over the blocks in reverse topological order finishes the step. For termination, the number of paths from the blocks not yet scheduled to the first scheduled block or ret drops by at least 1 with each trace, although the compensation blocks are new blocks.
Proof: Trace scheduling with compensation code keeps the meaning of the program and stopsfull
We prove that one step of TRACE-SCHEDULE (lines L2 to L14: pick a trace, schedule it, add compensation code, cut it into blocks) gives a program with the same outcome as the input on every input. Then we prove that the loop of line L1 stops on an acyclic control flow graph. The rules of code motion in lines L4 to L6 are exactly what the proof needs: each rule appears in one lemma.
Setup
The program has an acyclic control flow graph and only const, copy and op instructions. Every value is an integer. A run of 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. is the set of names that some path from the start of block reads before it writes them. It is the least solution of the usual backward equations, which line L3 computes.
The trace and its items. The trace is a path of the graph. The entry block of is never for , because line L2 never grows a trace backward from the entry. Its items are, in this index order:
- for each with that has a predecessor other than : an entrance ;
- the instructions of , which we call operations;
- for , if ends with a
brto two labels: a branch . One target is , and the other is its off-trace target ; - for : the end item, the terminator of .
A branch or the end item reads its condition or its returned name. We say that two items conflict if one of them writes a name that the other reads or writes.
The DAG. has these edges with and a delay :
- (E1) data: from the last writer of before to each reader of , delay the latency of the writer; from the last writer of before to a writer of , delay 1; from each reader of after the last writer of before to a writer of , delay 0;
- (E2) from a branch to each later branch and to the end item; and from to each later operation that can trap or whose result is in (line L5);
- (E3) from each item before an entrance to , and from to each later branch and to the end item (line L6);
- (E4) from each item to the end item.
The schedule. Line L7 gives each item a cycle with for each edge. The order sorts the items by . We write when comes before in .
The output . Walk and cut it after each branch, at each entrance and after the end item. The pieces become blocks. The first piece keeps the label . A piece that ends with a branch ends with br to the next piece and to the exit target of : that is if is empty, and otherwise a new exit block with copies of the operations of
in the order , and then jump off(B) (lines L8 to L10). A piece that ends at an entrance jumps to the next piece. The label goes to a new entrance block with copies of the operations of
in the order , and then a jump to the piece after . If is empty, the piece after takes the label itself (lines L11 to L13). The last piece ends with the terminator of . All other blocks of stay as they are.
Lemma 1. Order
(a) Each edge of has . (b) If conflict, then .
Proof. (a) and , so .
(b) By (a) it is enough to find a path from to in . Let be the name of the conflict and let be the writers of . Consecutive writers are joined by output edges of (E1), so the writers form a path in index order. If writes and reads, the last writer before has , and the path goes . If reads and writes, the first writer after has , is a reader after the last writer before , so (E1) has , and the path goes on along the writers to . If both write, the writers path joins them.
Lemma 2. Shape of the order
(a) The branches and the end item are in index order in .
(b) For an entrance : every item has , and every branch or end item has . So the items all have .
(c) For a branch and an entrance : every has .
(d) For a branch : every operation with cannot trap, and its result is not in .
Proof. (a) is (E2) with Lemma 1. (b) is (E3) with Lemma 1; for the last sentence, an operation would have . (c) If , then by (b), but means . (d) If could trap or wrote a name of , (E2) would give the edge and so .
The run through one region
Fix an entrance point : either for the head , or is the index of an entrance . Its label is or . Both labels exist in . Let be restricted to the items with index above .
What does from . It runs the items in index order. An entrance does nothing. A branch either goes on along the trace or leaves to .
What does from . For it runs the pieces from the first one, that is in order. For an entrance it first runs the copies of in the order , then the pieces after . By Lemma 2(b), the items after in are the items above that are not in . So in both cases runs in order, until a branch leaves the trace. Then it runs the copies of in the order and jumps to . By Lemma 2(c), has only items above . If no branch leaves, it ends with the end item. Call the items that runs in this region, in the order it runs them, the sequence .
Ideal values. For an item and a name that reads, let be the last writer of among the items , or "the entrance" if there is none. Run the operations above in index order as straight-line code from a state , with a trapping operation giving the special value , and with for any operation that reads . This gives each operation its ideal value . The run of from computes exactly these values for the items it runs, because it runs them in index order.
Lemma 3. The same writers
If is in and reads , then the last item before in that writes is , or there is none if is the entrance.
Proof. First, for two items in that conflict, is before in . If both are in or both in , this is Lemma 1(b), as both parts follow . If and is in the part of that runs, then , which is against Lemma 1(b). If runs in and , then is before in anyway.
Next, is in before . If runs in the part of , then by Lemma 1(b), and , so runs before . If , then . Either and ran in , or and .
Last, take any other writer of in . If , it is before by the first step. No writer lies strictly between and in index order. If , it conflicts with and so is after . So is the last writer before . If is the entrance, every writer of in is above , so after .
Lemma 4. The same values
Let and agree on . Run from with , and from with . Then every item in reads the same values as in the ideal run from , and every operation in that does not trap computes .
Proof. By induction along . Take and a name that it reads. If , then by Lemma 3, reads the value that computed in , which is by induction. ( did not trap, or the run would have stopped.) If is the entrance, reads . The trace path from to the block of reads at with no write before, so and . In both cases reads the ideal value.
Lemma 5. One region
Under the hypothesis of Lemma 4, exactly one of these holds.
- Both runs trap in the region.
- Both leave at the same branch to , with states that agree on .
- Both reach the end item. If it is
ret a, both return the same value. Otherwise both go to the same successor of , with states that agree on its live set.
Proof. There are three cases for the run of .
leaves at a branch without a trap. The items of that meets before are of three kinds. Branches: by Lemma 2(a) they are the branches below in index order. They read the ideal values by Lemma 4, the same as in , so they stay on the trace. Operations below : ran them without a trap, and they compute the same values. Operations above that are before in : they cannot trap, by Lemma 2(d). So reaches , leaves the trace, and runs , whose operations are below and do not trap. The items that ran are all the items and the set of operations. Take . By Lemma 2(d), no item of writes . The writers of in run in index order (Lemma 3, first step), so the last one is the same as in , and it computed the same value. If none of them writes , then and both states keep the entry value. This is case 2.
reaches the end item without a trap. The same argument with the end item. By (E4), is empty. The end item reads the same value. This is case 3.
traps at an operation , and every branch below stays on the trace. Suppose that does not trap in the region. Then it leaves at a branch or reaches the end item, and as above it ran every item from to (or to the end). The branches below stayed on the trace in with the ideal values, so they also do so in . left in , so it would leave in too. As trapped first, . So ran , with the ideal values of its operands by Lemma 4, and these are the values with which traps in . So traps, which is a contradiction. This is case 1.
Theorem 6. One step keeps the meaning
On every input, and have the same outcome.
Proof. Call a label of kept if it is not on the trace, or it is , or it is a with an entrance. Every kept label is a label of . We show, for every kept label , that runs of and from with states that agree on have the same outcome. We use induction on in reverse topological order of .
If is not on the trace, has the same block at . Both runs compute the same values on the live names, trap together, and go to the same successor with states that agree on . is kept: if with , then is a predecessor other than , so has an entrance. comes after in the topological order, so the induction applies.
If is or an entrance label , Lemma 5 applies. In case 1 both trap, and in case 3 with ret both return the same value. In case 2, for a branch of with is either off the trace, or it is some . In the second case , because would close a cycle and is the trace target. Then is a predecessor of other than , so has an entrance and is kept. comes after , so after , and the induction applies. Case 3 with a jump or a branch is the same.
The entry of is kept, because it is or off the trace, and it stays the entry of . Both runs start there with the same arguments.
Lemma 7. The new program can go through the loop again
has only const, copy and op instructions, and its graph is acyclic.
Proof. The copies are copies of operations. For the graph, give each block of a key, and compare the keys first by the topological rank of a block of , then by a number. Let be the cut items in (branches, entrances and the end item). By Lemma 2(a) and 2(b) they are in index order. Let be the block of that holds , where . The keys are:
- a block not on the trace: (its rank, 0);
- the piece that ends at : ;
- the exit block of a branch of : ;
- the entrance block of : .
Every edge of goes to a larger key. From a piece to the next piece: the block does not go down, and the number goes up. From the piece of a branch of to its exit block: . From an exit block of , or from the piece of a branch of , to : comes after in , and its key has that block or a later one. From an entrance block to the piece after : that piece has a block at least and a number at least 0. From a block off the trace to or : it comes before in . From the last piece to a successor of : the successor comes after . So there is no cycle.
Theorem 8. The loop stops
For a program with a set of scheduled blocks, let if is done or has no successor, and otherwise over the successors of . So counts the paths from that stop at the first done block or at a ret. Let
is a positive integer while some block is not done, and each step makes it smaller by at least 1. So the loop of line L1 stops after at most steps of the input.
Proof. Write before the step and after. The step removes from the blocks that are not done, marks the pieces done, and adds exit blocks and entrance blocks.
Old blocks do not grow. For a block off the trace, the edges into the trace now go to (a done piece, ) or to the label (a done piece, , or an entrance block whose only successor is done, so ). Each of these has . By induction in reverse topological order, .
The exit blocks. An exit block of has the one successor , so its is . Each path from leaves the trace at a first place: at a branch to , or at the end of . So , where counts the paths that leave at the end ( if returns). So the exit blocks add at most .
The entrance blocks. There are at most , and each has .
The removed blocks. They had .
So .
Summary
Each step keeps the outcome (Theorem 6), keeps the input form (Lemma 7), and lowers (Theorem 8). So TRACE-SCHEDULE stops, and its output has the same outcome as its input on every input. The bound counts paths, so it can be exponential in the number of blocks. This proof does not bound the code growth any better.
Complexity
Let be the number of items of one trace, the number of instructions and terminators of the program, the number of names and the number of traces.
- Line L2. The counts and the growth look at each edge a constant number of times: .
- Line L3. One backward pass in reverse topological order solves the liveness equations of an acyclic graph, with sets of at most names: . The Python code repeats the pass until nothing changes, which can take more passes.
- Lines L4 to L6. The DAG has edges. Each data edge, each branch edge and each entrance edge is made in : .
- Line L7. Heights in one pass over the edges, then a list schedule with a ready queue: , as the number of cycles is at most the sum of the latencies, . The Python code scans all items for each choice, which is .
- Lines L8 to L14. Each branch and each entrance copies at most operations: , and the rebuild is .
So one trace costs , and the run costs time and space. Here is the size of the largest program during the run. The termination proof bounds by the number of paths, which can be exponential in the number of blocks, and the copies can make grow in the same way. In practice compilers limit the length of a trace and the motions that need copies.
Properties
- Correct for every input. The profile only chooses the traces. A bad profile makes the code slower, never wrong.
- The optimum is never worse than block by block. The best schedule of the whole trace is at most the sum of the best schedules of its blocks, because the block schedules placed one after the other are a legal schedule of the trace. In the example, 8 cycles against 12. The list scheduler is a heuristic, so this holds for the optimum, not for every list schedule.
- Slower rare paths. A run that leaves at a side exit runs the exit block, and a run that comes in at a side entrance runs the entrance block. Their cost goes on the rare paths.
- Code growth. Every motion past a side exit or entrance makes a copy, and copies are scheduled again in later traces, where they can be copied again.
- Speculation without hardware help. Only operations that cannot trap move above a branch. With loads and stores this needs memory dependence analysis, or hardware with non-trapping loads.
Variants and improvements
- Superblock scheduling (Hwu et al. 1993) removes the side entrances first by tail duplication. Then only side exits need care, and the bookkeeping is much simpler, at the cost of more code.
- Avoidance and suppression of compensation code (Freudenberger, Gross and Lowney 1994). The scheduler can refuse a motion that needs a copy when the gain is small, or drop a copy whose value the side path already has, as with
win the example. - Better traces. Chang and Hwu (1988) compare selection by block counts and by edge counts, and stop a trace when an edge is not likely enough. Path profiles give the real hot paths instead of a chain of locally likely edges.
- Loops. The trace stops at a back edge. Unrolling the loop with loop unrolling first gives longer traces. For loops with many iterations, software pipelining overlaps the iterations instead.
- Percolation scheduling (Nicolau) moves operations one edge at a time by a small set of local transformations, each of which keeps the meaning, instead of scheduling a whole trace at once. Muchnick (Section 17.6) describes it.
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. There the machine does not reorder instructions, and a block alone has too little parallel work. Prefer superblock scheduling when simple bookkeeping matters more than code size. On an out-of-order processor, the hardware already looks past branches, and the gain is smaller. For loops, use iterative modulo scheduling. Without a profile, the static guess of even branch splits gives traces that can slow down the paths that matter.
Pitfalls
- Speculating an operation that can trap. If line L5 adds edges only for live names, a division can move above the branch that tests its divisor, and a run that leaves at that branch traps where the input did not. Line L5 must also add the edge for every operation that may trap.
- Speculating a write to a live name. If line L5 ignores , an operation from below the branch can overwrite a name that the off-trace path still reads. Use the live-in set of the off-trace target, computed by line L3 on the current program.
- Missing exit copies. If line L9 collects only the operations of the block of , an operation from an earlier block that moved below is lost on the exit. In the example, dropping the copy of
smakes the rare path read an undefined name. Take every operation from above , in any block of the trace. - Moving an operation below an entrance. If line L6 does not add the edges into the entrance, an operation from above the entrance can move below it, and then it also runs on the side path, where it did not run before. Keep every earlier item above the entrance.
- Entrance copies on the wrong edge. If line L13 gives the label to the piece after the entrance and puts the copies elsewhere, the side edges skip the copies. The new block must take the label , which the side edges use, and the trace edge from must go past it.
- Growing a trace backward past the entry. If line L2 puts the entry block in the middle of a trace, the entry gets an entrance and its label moves to a new block. Stop the backward growth at the entry.
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.
# 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)
trace_scheduling.py 432 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trace-scheduling/. The authors are listed in prov/5GWXK6.jsonl.
"""Trace scheduling after Fisher, on the toy IR.
trace_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). While some block is not
scheduled, it
1. picks a trace: the unscheduled block of highest count, grown forward and
backward along edges that are the most likely way out of one end and the
most likely way into the other end;
2. builds the dependence DAG of the items of the trace (its operations, its
side exits and its side entrances) and list schedules it as one block;
3. puts copies of the operations that moved below a side exit on the
off-trace edge of that exit, and copies of the operations that moved
above a side entrance on the edges that enter there;
4. cuts the scheduled trace into blocks and marks them scheduled.
The compensation blocks are new unscheduled blocks, so later traces
schedule them too.
The machine: each cycle issues at most `width` items, at most cap[u] of
unit u. The unit of a multiply, divide or remainder is "mul" (latency 3),
of a branch or of the last terminator "br" (latency 1), and of the other
operations "alu" (latency 1). An entrance is a mark that takes no slot.
The scheduled trace runs its items in the order (cycle, original
position), so a dependence with delay 0 lets two items share a cycle.
Code motion rules. An operation may move below a side exit; it is copied
onto the off-trace edge. An operation may move above a side exit only if it
cannot trap and its result is dead on the off-trace edge. No operation moves
below a side entrance: entrances and branches keep their order. An
operation may move above a side entrance; it is copied onto the side edges.
"""
import toyir
MACHINE = {"width": 2, "cap": {"mul": 1, "br": 1}}
LATENCY = {"alu": 1, "mul": 3, "br": 1, "join": 0}
class Item:
"""One item of a trace: an operation ("op"), a side exit ("br"), a
side entrance ("join") or the terminator of the last block ("end")."""
def __init__(self, kind, blk, ins=None, term=None, label=None, off=None):
self.kind = kind
self.blk = blk
self.ins = ins
self.term = term
self.label = label
self.off = off
if kind == "op":
self.uses = toyir.uses(ins)
self.defs = toyir.defs(ins)
elif kind in ("br", "end"):
self.uses = toyir.term_uses(term)
self.defs = None
else:
self.uses = []
self.defs = None
def unit(self):
if self.kind in ("br", "end"):
return "br"
if self.kind == "join":
return "join"
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("trace 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 liveness(prog):
"""live_in[label]: the names read before any write on some path."""
live_in = {lab: set() for lab in prog.blocks}
changed = True
while changed:
changed = False
for lab in reversed(list(prog.blocks)):
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))
if live != live_in[lab]:
live_in[lab] = live
changed = True
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."""
order = []
seen = set()
def visit(lab):
seen.add(lab)
for s in toyir.succs(prog, lab):
if s not in seen:
visit(s)
order.append(lab)
visit(prog.entry)
order.reverse()
bf = {lab: 0.0 for lab in prog.blocks}
bf[prog.entry] = 1.0
freq = {}
for lab in order:
ss = toyir.succs(prog, lab)
for s in ss:
freq[(lab, s)] = bf[lab] / len(ss)
bf[s] += freq[(lab, s)]
return freq
# ---------------------------------------------------------- trace selection
def pick_trace(prog, freq, done):
"""The seed is the unscheduled block 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 not scheduled. The entry block is always the head of
its trace, so the entry label stays the entry."""
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 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
# ------------------------------------------------------------ the DAG
def trace_items(prog, trace):
"""The items of the trace in their original order."""
pr = toyir.preds(prog)
items = []
for i, lab in enumerate(trace):
b = prog.blocks[lab]
if i > 0 and any(p != trace[i - 1] for p in pr[lab]):
items.append(Item("join", i, label=lab))
for ins in b.instrs:
items.append(Item("op", i, ins=ins))
t = b.term
if i == len(trace) - 1:
items.append(Item("end", i, term=t))
elif t[0] == "br" and t[2] != t[3]:
off = t[3] if t[2] == trace[i + 1] else t[2]
items.append(Item("br", i, term=t, off=off))
return items
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": # @line L5
for v in range(b + 1, len(items)):
w = items[v]
if w.kind in ("br", "end"):
add(b, v, 0)
elif w.kind == "op" and (can_trap(w.ins) or w.defs in live_in[it.off]):
add(b, v, 0)
elif it.kind == "join": # @line L6
for u in range(b):
add(u, b, 0)
for v in range(b + 1, len(items)):
if items[v].kind in ("br", "end"):
add(b, v, 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()
if u == "join":
return True
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
if items[v].unit() != "join":
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)))
# ------------------------------------------------------------ one 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 schedule_trace(prog, trace, freq, machine=MACHINE):
"""Schedule one trace. Returns (new program, labels of the scheduled
pieces, new edge counts, (items, t))."""
live_in = liveness(prog) # @line L3
items = trace_items(prog, trace)
edges = build_dag(items, live_in) # @line L4
t = list_schedule(items, edges, machine) # @line L7
order = sorted(range(len(items)), key=lambda v: (t[v], v))
where = {v: k for k, v in enumerate(order)}
taken = set(prog.blocks)
head = trace[0]
pieces = {}
extra = {}
newfreq = {}
cur, body = head, []
for v in order:
it = items[v]
if it.kind == "op":
body.append(it.ins)
elif it.kind == "br": # @line L8
comp = [items[u].ins for u in order[where[v] + 1 :] if items[u].kind == "op" and u < v] # @line L9
nxt = _fresh(taken, head)
w = freq.get((trace[it.blk], it.off), 0)
target = it.off
if comp:
target = _fresh(taken, head) # @line L10
extra[target] = toyir.Block(list(comp), ("jump", it.off))
newfreq[(target, it.off)] = w
c = it.term
term = ("br", c[1], target, nxt) if c[2] == it.off else ("br", c[1], nxt, target)
pieces[cur] = toyir.Block(body, term)
newfreq[(cur, target)] = w
newfreq[(cur, nxt)] = freq.get((trace[it.blk], trace[it.blk + 1]), 0)
cur, body = nxt, []
elif it.kind == "join": # @line L11
comp = [items[u].ins for u in order[: where[v]] if items[u].kind == "op" and u > v] # @line L12
side = sum(freq.get((p, it.label), 0) for p in toyir.preds(prog)[it.label] if p != trace[it.blk - 1])
if comp:
nxt = _fresh(taken, head)
extra[it.label] = toyir.Block(list(comp), ("jump", nxt)) # @line L13
newfreq[(it.label, nxt)] = side
else:
nxt = it.label
pieces[cur] = toyir.Block(body, ("jump", nxt))
newfreq[(cur, nxt)] = freq.get((trace[it.blk - 1], it.label), 0)
cur, body = nxt, []
else:
pieces[cur] = toyir.Block(body, it.term)
last = trace[-1]
for s in toyir.succs(prog, last):
newfreq[(cur, s)] = freq.get((last, s), 0)
blocks = {}
for lab, b in prog.blocks.items(): # @line L14
if lab == head:
blocks.update(pieces)
elif lab in trace:
if lab in extra:
blocks[lab] = extra.pop(lab)
else:
blocks[lab] = b
for s in toyir.succs(prog, lab):
newfreq[(lab, s)] = freq.get((lab, s), 0)
blocks.update(extra)
return toyir.Program(list(prog.params), blocks), set(pieces), newfreq, (items, t)
def trace_schedule(prog, freq=None, machine=MACHINE):
"""Schedule the whole program trace by trace. Returns (new program,
list of (trace, items, t) for each trace)."""
check_input(prog)
if freq is None:
freq = static_profile(prog)
done = set()
log = []
while any(lab not in done for lab in prog.blocks): # @line L1
trace = pick_trace(prog, freq, done) # @line L2
prog, pieces, freq, (items, t) = schedule_trace(prog, trace, freq, machine)
done |= pieces
log.append((trace, items, t))
return prog, log # @line L15
test_trace_scheduling.py 230 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trace-scheduling/. The authors are listed in prov/5GWXK6.jsonl.
import copy
import random
import pytest
import toyir
import trace_scheduling as ts
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 legal(items, edges, t, machine):
for (u, v), d in edges.items():
if t[v] < t[u] + d:
return False
by_cycle = {}
for v in t:
if items[v].unit() != "join":
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], ts.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():
p = toyir.parse(EXAMPLE)
live = ts.liveness(p)
assert live["B2"] == {"a", "b", "s"}
q, log = ts.trace_schedule(p, EXAMPLE_FREQ)
assert [tr for tr, _, _ in log] == [["B0", "B1", "B3"], ["B0.2", "B2", "B3"]]
items, t = log[0][1], log[0][2]
got = {it.ins[1]: t[v] for v, it in enumerate(items) if it.kind == "op"}
assert got == {"c": 0, "w": 0, "s": 2, "y": 1, "v": 2, "z": 5, "r": 6}
assert [(it.kind, t[v]) for v, it in enumerate(items) if it.kind != "op"] == [("br", 1), ("join", 2), ("end", 7)]
assert ts.length(items, t) == 8
assert q.blocks["B0"].instrs == [("op", "c", "<", "b", 5), ("op", "w", "+", "b", 1)]
assert q.blocks["B0"].term == ("br", "c", "B0.1", "B0.2")
assert same_meaning(p, q, grid())
assert toyir.run(q, [1, 7]) == ("ret", 58)
assert toyir.run(q, [4, 0]) == ("trap",)
def test_example_lengths_against_blocks():
p = toyir.parse(EXAMPLE)
live = ts.liveness(p)
local = 0
for lab in ("B0", "B1", "B3"):
items = ts.trace_items(p, [lab])
edges = ts.build_dag(items, live)
t = ts.list_schedule(items, edges)
assert ts.length(items, t) == brute_optimum(items, edges, ts.MACHINE)
local += ts.length(items, t)
assert local == 12
items = ts.trace_items(p, ["B0", "B1", "B3"])
edges = ts.build_dag(items, live)
assert brute_optimum(items, edges, ts.MACHINE) == 8
def test_compensation_is_needed():
p = toyir.parse(EXAMPLE)
q, _ = ts.trace_schedule(p, EXAMPLE_FREQ)
broken = copy.deepcopy(q)
b = broken.blocks["B0.2"]
b.instrs = [ins for ins in b.instrs if ins[1] != "s"]
assert toyir.run(p, [1, 7]) == ("ret", 58)
with pytest.raises(toyir.UndefinedName):
toyir.run(broken, [1, 7])
def test_meaning_random_programs():
rng = random.Random(7)
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, _ = ts.trace_schedule(p, freq)
assert toyir.is_acyclic(q)
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(8)
for _ in range(50):
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 (ts.profile(p, inputs), ts.static_profile(p), None):
q, _ = ts.trace_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_motion_rules_and_termination():
rng = random.Random(9)
seen = {"exit copy": 0, "entrance copy": 0, "speculation": 0}
for _ in range(200):
prog = toyir.random_program(rng, rng.randint(2, 6), rng.randint(2, 8), 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 = ts.pick_trace(prog, freq, done)
live = ts.liveness(prog)
new, pieces, freq, (items, t) = ts.schedule_trace(prog, trace, freq)
pos = {v: k for k, v in enumerate(sorted(range(len(items)), key=lambda v: (t[v], v)))}
for b, it in enumerate(items):
later = range(b + 1, len(items))
if it.kind == "br":
for v in later:
w = items[v]
if w.kind in ("br", "end"):
assert pos[b] < pos[v]
elif w.kind == "op" and pos[v] < pos[b]:
assert not ts.can_trap(w.ins) and w.defs not in live[it.off]
seen["speculation"] += 1
if any(items[u].kind == "op" and pos[u] > pos[b] for u in range(b)):
seen["exit copy"] += 1
if it.kind == "join":
assert all(pos[u] < pos[b] for u in range(b))
assert all(pos[v] > pos[b] for v in later if items[v].kind in ("br", "end"))
if any(items[v].kind == "op" and pos[v] < pos[b] for v in later):
seen["entrance copy"] += 1
prog = new
done |= pieces
nphi = potential(prog, done)
assert nphi < phi
phi = nphi
assert min(seen.values()) > 20
def test_schedules_against_brute_force():
rng = random.Random(10)
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)}
trace = ts.pick_trace(p, freq, set())
live = ts.liveness(p)
items = ts.trace_items(p, trace)
if len(items) > 9:
continue
edges = ts.build_dag(items, live)
assert all(u < v for u, v in edges)
t = ts.list_schedule(items, edges)
assert legal(items, edges, t, ts.MACHINE)
best = brute_optimum(items, edges, ts.MACHINE)
assert ts.length(items, t) >= best
local = 0
for lab in trace:
one = ts.trace_items(p, [lab])
local += brute_optimum(one, ts.build_dag(one, live), ts.MACHINE)
assert best <= local
checked += 1
def test_input_checks():
with pytest.raises(ValueError):
ts.trace_schedule(toyir.parse("B0:\n x = 1\n br x B1 B0\nB1:\n ret x\n"))
with pytest.raises(ValueError):
ts.trace_schedule(toyir.parse("# params: p\nB0:\n x = *p\n ret x\n"))
History
Fisher developed trace scheduling in his 1979 NYU thesis and the 1981 paper to compact horizontal microcode, where one long instruction word controls many units at once. The copies on the side edges came from a separate bookkeeping phase. Ellis built the Bulldog compiler for VLIW machines on trace scheduling in his Yale thesis, published as a book in 1986. Fisher and others then founded Multiflow, whose TRACE machines (Colwell et al. 1988) and compiler (Lowney et al. 1993) were designed around the method. Chang and Hwu (1988) studied trace selection for C programs in the IMPACT compiler, and the same group then gave superblocks (Hwu et al. 1993). Freudenberger, Gross and Lowney (1994) measured how much compensation code the Multiflow compiler made and how to avoid it.
References
- Joseph A. Fisher, Trace scheduling, a technique for global microcode compaction, IEEE Transactions on Computers C-30(7), 1981, 478-490, the selection of traces by expected execution counts, the compaction of a trace as if it were one block, and the bookkeeping phase that copies operations onto the edges that leave or join the trace
- 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 3 on trace selection, local compaction and bookkeeping with patch code at the splits and rejoins of a trace, and Section 4 on selection by node weights and arc weights from a seed with the best successor and the best predecessor
- P. Geoffrey Lowney, Stefan M. Freudenberger, Thomas J. Karzes, W. D. Lichtenstein, Robert P. Nix, John S. O'Donnell and John C. Ruttenberg, The Multiflow trace scheduling compiler, The Journal of Supercomputing 7(1-2), 1993, 51-142, the production trace scheduling compiler of the Multiflow TRACE machines, with its trace picker, its scheduler and its compensation code
- Stefan M. Freudenberger, Thomas R. Gross and P. Geoffrey Lowney, Avoidance and suppression of compensation code in a trace scheduling compiler, ACM Transactions on Programming Languages and Systems 16(4), 1994, 1156-1214, the amount of compensation code in practice, and the methods that avoid code motions that need copies or remove copies that are not needed
- Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Section 17.5 (Trace Scheduling), 569 to 571
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 5GWXK6 Edit this page History Report an error Markdown