Algorithmresearch
Linear scan register allocation on SSA form
Also called Wimmer-Franz linear scan.
Runs linear scan directly on SSA form with lifetime intervals and resolves phi-functions after allocation, without leaving SSA first.
- Solves
- Register allocation
- Time
- O(s + b^2 + n^2 b) worst
- Space
- O(s + n b) extra
- Where
- b = the number of blocks; n = the number of names; s = the number of instructions and terminators
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Christian Wimmer, Michael Franz, 2010
Linear scan on SSA form gives registers to the names of a program while it is still in static single assignment form, with the scan of linear scan. It differs from classic linear scan in three ways. Each name gets a lifetime interval with holes, a list of ranges, not one interval from the first to the last point where it is live. The intervals come from one backward pass over the blocks, with no fixed point of liveness, because each name has one definition and the blocks are put in an order where dominators come first and loops are contiguous. The phis stay until after the scan, and then turn into moves at the ends of the predecessors. It differs from SSA-based register allocation in that it does not spill first and color second: it decides spills during the scan, like any linear scan, so it is fast and simple but gives no promise on the number of spills.
In plain words
Put the blocks of the program in a line, so that every block comes after the blocks that must run before it, and every loop sits together. Number every instruction along that line. For each value, write down the stretches of the line where the value must be kept, going from the bottom to the top once. A value can have gaps where it is not needed. Then walk down the line. When a value starts, give it a register that no value holds at any point where the new value is kept. If no register is free, send the value that lasts longest to memory. Last, where paths join and a value has different names on different paths, add copies at the end of each path.
The problem
The input is a program in the toy IR in strict SSA form, with const, copy, op and phi instructions, a reducible control flow graph, and a number of registers. Strict means that each name has one definition and that the definition dominates every use, where a phi operand from the predecessor counts as used at the end of . Reducible means that every cycle enters through a block that dominates the cycle, see reducible flow graph. The output is a program with no phi that uses only the registers , two scratch registers and for spill code and copies, and memory slots mem.x, and that has the same outcome as on every input.
A node is the group of all phis of one block, one other instruction, or one terminator. For a node , is the set of names that defines and is the set of names live just after . MaxLive is the largest . Names and interfere when one of them is in and the other in for some node .
The algorithm
SSA-LINEAR-SCAN(P, k)- 1
P <- P with a start block that loads the parameters, and each edge from a br into a block with phis split - 2
order the blocks so that each block follows its dominators and each loop is contiguous; number the positions - 3
for each block b in reverse order do - 4
live <- union of liveIn(s) over the successors s of b, plus the phi operands that b sends to s - 5
for each x in live do add the range [b.start, b.end) to x - 6
for each item i of b from last to first (terminator, then instructions) do - 7
for its result y: if y in live, cut the first range of y to start at pos(i) and remove y from live; else add [pos(i), pos(i)+1) - 8
for each operand x: add [b.start, pos(i)) to x; add x to live - 9
for each phi y of b: remove y from live (add [b.start, b.start+1) if it is dead); liveIn(b) <- live - 10
if b is a loop header then - 11
for each x in live do add [b.start, end of the last block of the loop) to x - 12
sort the intervals by start - 13
for each interval cur in that order do - 14
move intervals of active that ended out, and those in a hole at start(cur) to inactive - 15
move intervals of inactive that ended out, and those that cover start(cur) to active - 16
busy <- registers of active, and of inactive intervals that intersect cur - 17
if some register is not busy then give cur the lowest one; add cur to active - 18
else s <- the interval in active, whose register no intersecting inactive interval holds, with the largest end - 19
if end(s) > end(cur) then give cur the register of s; spill s - 20
else spill cur - 21
for each edge (Q, B) with B having phis do the parallel copy loc(y) <- loc(a) at the end of Q - 22
sequentialize it with s0 for cycles and s1 for memory to memory moves - 23
return the program with registers and slots, loads into s0/s1 before uses of spilled names and stores after definitions
Here is for a kept name with register and mem.x for a spilled name. A range is half open.
Positions. Line L2 gives each block an even position , where its phis write. Its instructions and its terminator get the next even positions, and , two after the last item, is the start of the next block. An item at position reads its operands at the end of ranges that stop at , and writes its result at the start of a range that begins at . So a name read at and a name written at do not meet there, and the result can take the register of an operand that dies.
The block order. The natural loops are found from the back edges, and each loop is first shrunk to its header. Without back edges the graph is acyclic, so its reverse postorder puts every block after its dominators. Each header is then replaced by the order of its own loop, built the same way. Every edge that goes backward in this order is a back edge. Irreducible graphs are rejected: they have a cycle with two entries and no single header.
Why one pass suffices. In the backward pass, every successor along a forward edge is done before its predecessor, so lines L4 to L9 compute liveness along paths with no back edge. A value can be live around a loop only if it is live at the header, and such a value is defined before the loop and needed in all of it. Line L11 covers the whole loop for it, which is one range because the loop is contiguous. That fills in the rest, and the result is exact liveness without a fixed point.
The scan. An interval is active when it covers the current position and inactive when it is in a hole there but has later ranges. An inactive interval does not hold its register, so another interval that fits in the hole can use it. Line L16 still checks inactive intervals for a later overlap. In strict SSA with this order that check never finds one: an earlier interval in a hole at is not live at the definition of , so the two names do not interfere. Wimmer and Franz use this to skip those tests.
Line L1 is the usual critical edge splitting: the copies for an edge go at the end of , and if ended in br they would also run on its other edge. The start block gives each parameter a definition, which keeps the program strict.
This version never splits an interval: a name lives in one register for its whole life or in its slot. The allocator of Wimmer and Franz splits intervals and uses register hints, see the variants below.
Example
Holes. The program has the parameter p and a join with a phi:
entry:
a = p + 1
br p L R
L:
d = a - p
jump J
R:
b = p * 2
c = b + p
jump J
J:
e = phi [L: d, R: c]
ret e
Line L1 adds start: p = mem.p; jump entry. No edge needs a split block, because L and R end in jump. Line L2 gives the order start, entry, R, L, J. The positions are:
| block | start | items | end |
|---|---|---|---|
| start | 0 | p = mem.p 2, jump 4 |
6 |
| entry | 6 | a = p + 1 8, br 10 |
12 |
| R | 12 | b = p * 2 14, c = b + p 16, jump 18 |
20 |
| L | 20 | d = a - p 22, jump 24 |
26 |
| J | 26 | ret e 28 |
30 |
The backward pass gives these intervals:
| name | ranges | why |
|---|---|---|
| , | dead in R after c = b + p at 16, live into L |
|
| , | dead in R, used in L |
|
phi operand, live to the end of R |
||
phi operand, live to the end of L |
||
The scan with goes:
| cur | start | active | inactive | busy | action |
|---|---|---|---|---|---|
| 2 | none | none | none | ||
| 8 | none | 0 | |||
| 14 | (hole) | 0 | does not meet : | ||
| 16 | none | , (holes) | none | ended, is in a hole: | |
| 22 | none | none | none | , , ended: | |
| 26 | none | none | none |
Nothing is spilled. The phi needs no move, since , and all have . The output is:
start:
r0 = mem.p
jump entry
entry:
r1 = r0 + 1
br r0 L R
R:
r1 = r0 * 2
r0 = r1 + r0
jump J
L:
r0 = r1 - r0
jump J
J:
ret r0
Without holes, the interval of would be and that of would be . At position 14 these two and would overlap, so classic linear scan with two registers would spill. The same happens on the linear scan page, where the program has no join. With the scan spills and , and the output loads them through and . Both outputs return the same values as the input, for example 1 for and 0 for .
Loops. The program sums the squares :
entry:
i0 = 0
a0 = 0
jump head
head:
i1 = phi [entry: i0, body: i2]
a1 = phi [entry: a0, body: a2]
t = i1 < n
br t body done
body:
u = i1 * i1
a2 = a1 + u
i2 = i1 + 1
jump head
done:
ret a1
The order is start, entry, head, body, done, with starts 0, 6, 14, 20 and 30. The loop is head and body, which ends at 30. The intervals are:
| name | ranges | why |
|---|---|---|
live into head, so line L11 covers the whole loop |
||
| phi operand | ||
| phi operand | ||
| , | phi of head, last use in body at 24, used in done |
|
| phi operand on the back edge | ||
| phi operand on the back edge |
When body is done in the backward pass, head is not done yet, so body sees only the phi operands and it sends, not . Line L11 at head adds to , which joins into . MaxLive is 4, at t = i1 < n, where , , and meet.
With nothing is spilled and four registers are used: , , , , , , , and . The loop body has no move, but on the edge from entry the parallel copy , is a swap, and line L22 breaks it with :
entry:
r1 = 0
r2 = 0
s0 = r2
r2 = r1
r1 = s0
jump head
The scan took the lowest free register for and , in name order, without looking at their phi operands. Register hints would give the register of and remove the swap.
With , at (start 16) the active intervals are (end 30), (end 32) and (end 26). The one with the largest end is , and , so is spilled and takes its register . Then , and . The edge copies become mem.a1 = r2; r2 = r1 from entry and mem.a1 = r1 from body. With the scan spills and . All outputs return 0, 0, 1, 5, 14, 30 for , the same as the input.
Correctness
The full proof is in the proof file. Its parts are:
- Order. In each region the graph with loops shrunk to their headers has only forward edges and is acyclic, so its reverse postorder puts dominators first. By induction on the nesting of loops, each loop is contiguous and every backward edge is a back edge.
- Exact intervals. The backward pass computes liveness along paths with no back edge. A shortest path from a block to a use, cut at its first back edge , shows that a name live into a block is either found by the pass or live into a header whose loop holds the block. Such a name is defined before the loop and live in all of it, which is what line L11 adds. So an interval covers a position exactly when its name is live there, and two intervals meet exactly when their names interfere.
- Scan. At each step, active holds the earlier kept intervals that cover the current start, and inactive those in a hole that end later. So busy is exactly the set of registers of earlier kept intervals that meet , and two kept intervals that meet never share a register.
- Optimal when the pressure fits. The start of an interval is the definition of its name, and dominators come first. So the earlier intervals that meet are names live at the definition of , at most MaxLive of them. With MaxLive, nothing is spilled and exactly MaxLive registers are used, by the SSA chordal interference theorem.
- Same outcome. Along a run, every name whose interval covers the position holds its value in its location. A definition writes only its own location, and the parallel copy on an edge writes only the locations of the phis, which no other live name shares.
When is below MaxLive the spill choice is a heuristic. With holes the intervals no longer form an interval graph, so the optimality of the furthest end rule for intervals does not carry over.
Proof: SSA linear scan builds exact intervals without a fixed point and gives a correct programfull
We prove six facts about SSA-LINEAR-SCAN. Lemma 1 is about the block order. Lemmas 2 and 3 show that the one backward pass of lines L3 to L11 gives, for each name, exactly the positions where it is live, with no fixed point. Lemma 4 shows that the scan never gives one register to two intervals that intersect. Lemma 5 shows that with MaxLive nothing is spilled and exactly MaxLive registers are used. Lemma 6 shows that the output has the same outcome as the input.
Setup
The input is in strict SSA form: each name has one definition, and the definition dominates each use, where a phi operand from counts as a use at the end of . The control flow graph is reducible. Line L1 adds a start block that copies each parameter from its slot, and puts an empty block on each edge from a br to a block with phis. Both keep strict SSA form, reducibility and the outcome.
An edge is a back edge if dominates . The loop of a header is the union, over the back edges , of and the blocks that reach without passing through . In a reducible graph, the graph without back edges is acyclic, and two loops with different headers are disjoint or one holds the other: if and with , each would dominate the other.
A node is the group of phis of a block, an instruction or a terminator, as on the SSA chordal interference theorem page. For a node , is the set of names it defines and the names live just after it, where a phi operand stays live until the end of its predecessor. Names interfere when some node has and , and MaxLive is the largest .
Positions follow the order of line L2. A block has the even position , where its phis write; its items get the next even positions; and , two after its last item, is the start of the next block. A name is live at position of an item when it is live just after that item and was live before it or is written by it; it is live at when it is live just after the item. It is live at when it is a phi of or live into , and at when it is live after the phis. A phi operand that sends is live up to . A name that is written and never read gets the single position of its write.
The block order
Lemma 1. Line L2 lists every reachable block once. Each block comes after its strict dominators, the blocks of each loop are contiguous with the header first, and every edge with before is a back edge.
Proof. Look at one call of the region routine, on a loop body with header , or on all blocks with the entry as . Every block of is mapped to , the header of the largest loop inside , other than the loop of , that holds , or itself. The edges of the shrunken graph are the edges of with and .
No such edge is a back edge. A back edge with inside has ; the loops of that hold form a chain and all hold , so and have the same top. So all edges of the shrunken graph come from edges of . It has no cycle: entries into a loop go to its header, and inside a loop the header reaches every block by edges of , so a cycle of shrunken nodes would give a cycle in . Every block of is reachable from inside , so the depth-first search from reaches every shrunken node, and its reverse postorder is a topological order of them, with first.
Each loop node is then replaced by the order of its own loop, built the same way. By induction on the depth of the loops, each loop is contiguous with its header first, and each edge of goes forward in the order. Every edge that goes backward is therefore a back edge.
For dominance, let strictly dominate . If is outside the region of , then dominates the header of that region and comes before it by induction. Otherwise, a path in the shrunken graph from to that misses would lift to a path in from to that misses ; with a path from the entry to , this contradicts dominance (if , use induction inside the loop). So is on every path to in an acyclic graph, and it comes first in any topological order.
The intervals are exact
Let be the set of names live into in the graph , that is, along paths with no back edge, not counting the phis of .
Lemma 2. When line L3 has finished with , the set is . Every range added is made of positions where its name is live.
Proof. By Lemma 1, every edge of goes forward, so is done before in the backward pass, and line L4 unions over those successors and adds the phi operands sent by . For a back edge , is not done yet, and line L4 adds only the phi operands of from , which are live until the end of . This set is the live-out set of in . Lines L5 to L9 then do the standard backward walk through one block: a name live at the end gets the whole block, a definition cuts the range of its name to start at the definition, and a use adds the range from the block start to the use. So is the live-in set of in without the phis of , which is .
Every position put in a range at lines L5 to L9 is live in , hence live in the program. The first range of a name at line L7 is the one from this block, since all ranges added before come from later blocks, so the cut is right. For line L11, take for a header . The definition of dominates , by strictness, and is not a phi of . It is not in either, since no block of the loop other than dominates , and a definition inside after its start could not reach a use before itself without passing through itself. Every block of the loop reaches inside the loop with no definition of , and from the name reaches a use. So is live at every position of the loop, which by Lemma 1 is exactly the range from to the end of the last block of the loop.
Lemma 3. A name is live at a position if and only if its interval covers that position.
Proof. One direction is Lemma 2. For the other, let be live at a position in block . If a use of later in explains it, or is defined at that position, lines L6 to L9 cover it. Otherwise is live into or live at its end, and it is enough to show , or for a header whose loop holds : in the first case lines L4 to L9 of the blocks on the path cover the position, and in the second line L11 does.
Take a shortest path from the start of to a use of with no definition of ; it repeats no block. We use induction on the number of back edges on . With none, . Otherwise, let be the first back edge. The part from to is in , and it does not pass through , because comes later on and repeats no block; also for the same reason. So reaches without passing , and . The rest of , from , has fewer back edges, so by induction , or for a header whose loop holds . In the second case the loop of shares with the loop of , so one holds the other, and it is the loop of that holds the loop of (otherwise would be in the loop of and the two headers would dominate each other). So as well.
So the backward pass computes liveness exactly in one pass. Two intervals then intersect if and only if their names interfere: a shared position is either the write of one name while the other is live after it or written at the same node, or a point where both are live, and by Lemma 3 of the theorem page two names live at one point interfere. Conversely, if and , both intervals cover the position of .
The scan
Lemma 4. Every kept interval gets one register below , and two kept intervals that intersect get different registers.
Proof. We keep this invariant at line L14 for the interval with start : every kept interval handled before is in active if it covers , in inactive if it does not cover but ends after , and dropped if it ends at or before . Lines L14 and L15 restore it from the previous step, since they look again at every interval of both sets.
A dropped interval cannot intersect , which lies at or after . An active interval covers , which also covers. So the registers held by earlier kept intervals that intersect are exactly those in busy at line L16. Line L17 picks a register not in busy. At line L18, two active intervals both cover and so intersect, and by induction they have different registers, so is the only active interval with its register. No inactive interval that intersects holds that register, by the choice of . So after is spilled, no earlier kept interval that intersects shares its register. Later intervals are checked against in their own step.
Lemma 5. If MaxLive , nothing is spilled and exactly registers are used.
Proof. Order the names by the start of their interval, which is the position of their definition. By Lemma 1, a strict dominator comes before in this order, which is all that Lemma 4 of the theorem page needs. So the names that start no later than and intersect it, that is, interfere with it, are all in for the node that defines . There are at most of them, so busy has at most registers and line L17 picks a register below . No spill happens, and at most registers are used. A node with gives names that pairwise interfere (Lemma 3 of the theorem page), so their intervals pairwise intersect and need different registers.
The same argument shows that an inactive interval never intersects , for any . If started before and does not cover , but meets , the two names interfere, so one is live at the definition of the other. The name is not live at , and is not live before . So the registers from inactive intervals at line L16 add nothing, and the choice at line L18 is among all active intervals. Wimmer and Franz use this to skip intersection tests.
When the scan spills, and the choice at lines L18 to L20 is a heuristic. Without lifetime holes the furthest end rule would give the fewest spilled intervals, as on the linear scan page. With holes the intervals no longer form an interval graph, and that optimality is lost.
The same outcome
Lemma 6. On every input, the output has the same outcome as .
Proof. Let be for a kept name with register and mem.x for a spilled one. We show that along a run, at each position, every name whose interval covers the position holds its value in .
An instruction at position that writes reads its operands from their locations, which hold their values by the invariant, through and for slots. It then writes only. Any other name live after the item was live before it too, so its interval covers , as does the interval of . They intersect, so has a different register by Lemma 4, or one of them has a slot, which is named after its name.
At the end of a block whose successor has phis, ends in jump because of line L1. The parallel copy reads the phi operands, which are live up to and so hold their values. Its destinations are the locations of the phis of ; they are different, since the phis of one block all start at and pairwise intersect. A name live into that is not a phi also covers , so it does not share a location with a phi of . The sequential form from line L22 writes the destinations with the values the parallel copy would give and changes nothing else but and , by the same argument as for the SSA-based allocator: a move is emitted only when no pending move reads its destination, and when only cycles are left one destination is saved in , which no pending move reads at that time. So after the copy, every name live into and every phi of holds its value.
Branches and returns read their operands from their locations. So the output takes the same branches and returns the same value as , and it traps in the same place.
Complexity
With names, instructions and terminators, and blocks:
- Block order. Dominators by the iterative method, natural loops from the back edges, and one reverse postorder per loop region take in the worst case and close to in practice.
- Intervals. One backward pass. Each block adds a range for each name live through it, so there are range additions. In the backward pass a new range is always at or before the first range of its name, so with ranges kept in a list from the front each addition is , as in the paper. The Python code merges into a sorted list, which is simpler and slower.
- Scan. Each interval looks at the active and inactive sets, intervals, and an intersection test walks two lists of at most ranges. That is in the worst case. Since the inactive test can be skipped in SSA form, and the active set is at most long, the scan is close to linear in practice.
- Phi removal. One parallel copy per edge into a block with phis, quadratic in the number of phis of that block with the simple scan.
The total is time and space. No interference graph is built and no liveness fixed point is run.
Properties
- One liveness pass. For a reducible graph in SSA form, the intervals are exact after one backward pass. Classic linear scan needs a fixed point of live variable analysis first.
- Holes. A name does not hold its register where it is dead, so another name can use it there. This often saves a register, as in the diamond above.
- Exact when the pressure fits. With MaxLive it uses exactly MaxLive registers and no spill. Classic linear scan has no such promise, because its intervals depend on the block order and can overlap where the names do not interfere.
- No interference graph. The scan needs only the intervals, so it fits a just-in-time compiler, where compile time counts.
- Whole names in this version. A spilled name is in memory everywhere. There is no splitting, so one hot use cannot save a name that lives long.
- Reducible graphs only. The loop rule of line L11 needs one header per loop. Structured source languages rarely give irreducible graphs, and node splitting can make any graph reducible.
Variants and improvements
- Interval splitting (Wimmer and Mössenböck, 2005). When no register is free for the whole of , the allocator gives it a register up to the point where that register is next needed, splits the interval there, and puts the rest back in the list. Spilled parts are split around their uses so that each use has a register. A resolution pass then adds moves on edges where the two sides of a split are in different locations. Wimmer and Franz keep this and put the phi moves into the same pass. See live range splitting.
- Register hints. An interval defined by a move or a phi gets a hint to use the register of its source, which removes the swap of the loop example in most cases.
- Fixed intervals. Registers that an instruction must use, such as the operands of a call, are given as intervals that are already assigned, and other intervals must avoid them.
- Use positions. Real allocators keep for each interval the positions of its uses, and spill the interval whose next use is furthest away instead of the one that ends last.
- SSA-based register allocation. Spill first until the pressure is at most , then color in dominance order with no spill. It gives better spill decisions when is small, at the cost of a separate spill phase.
When to use it
Use it in a JIT compiler or a fast compiler tier that keeps SSA form until code generation, where allocation time matters more than the last bit of code quality. It removes the liveness fixed point and the step that leaves SSA form, and it gives the best number of registers when no spill is needed. For an optimizing compiler where spill code matters most, use SSA-based register allocation or graph coloring. For a program that has already left SSA form, use classic linear scan.
Pitfalls
- A bad block order. The loop rule covers a loop with one range from the header to the end of the last loop block. If a block from outside the loop sits in between, a name gets a range where it is not live, and if a loop block sits outside, a range is missing. Keep each loop contiguous.
- Back edges in the backward pass. The pass cannot see the live-in set of a header from the end of its loop, since the header is done last. Do not try to read it there. Add only the phi operands the latch sends, and let line L11 cover the rest.
- Irreducible graphs. A cycle with two entries has no header, so the one-pass intervals miss liveness around it. Reject such graphs, make them reducible first, or fall back to a liveness fixed point.
- Phi operands. An operand of a phi of is live to the end of the predecessor , not to the start of . Count it in the live-out set of only, not in the live-in set of .
- Copies on a branch edge. A copy for the edge placed before a
brof also runs on the other edge. Split such edges first. - Swaps. Two phi moves that exchange registers form a cycle. Copying them one by one loses a value. Use a scratch register or an exchange instruction.
- Leaving SSA first. If the phis are replaced by copies before the scan, a name has several definitions, the one-pass rule fails, and the MaxLive promise is lost. Allocate first, then remove the phis.
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
# Part of https://algorithm.tamnd.com/ssa-linear-scan/. The authors are listed in prov/SBG2CF.jsonl.
"""Linear scan register allocation on SSA form, after Wimmer and Franz.
allocate(prog, k) takes a toy IR program in strict SSA form with a
reducible control flow graph, with const, copy, op and phi instructions,
and k >= 1 registers. It
1. orders the blocks so that each block comes after its dominators and the
blocks of each loop are contiguous;
2. builds a lifetime interval with holes (a list of ranges) for each name in
one backward pass over the blocks, with no liveness fixed point: a name
live at a loop header gets a range over the whole loop;
3. scans the intervals by start with the sets active and inactive (an
inactive interval is in a hole), and gives each interval a register that
no interval it intersects holds, or spills the interval that ends last;
4. replaces the phis by parallel copies at the ends of the predecessors.
This version never splits an interval: a name is in one register for its
whole life, or in its slot mem.x. It returns (out, reg, spilled), where reg
maps each kept name to its register number. The output uses r0 .. r(k-1),
the scratch registers s0 and s1, and slots, and its parameters are the slots
of the parameters of prog.
Positions: the blocks get the positions in order. A block b starts at an
even position b.start where its phis write, its items (instructions and the
terminator) get the next even positions, and b.end is two after the last
item, which is also the start of the next block. A range [a, e) is half
open. An item at position p reads its operands at the end of a range that
stops at p and writes its result at the start of a range that starts at p.
"""
import toyir
MEM = "mem."
def is_mem(name):
return isinstance(name, str) and name.startswith(MEM)
def _phis(b):
return [ins for ins in b.instrs if ins[0] == "phi"]
def _body(b):
return [ins for ins in b.instrs if ins[0] != "phi"]
# ------------------------------------------------------------ preparation
def _fresh(blocks, base):
label = base
while label in blocks:
label += "_"
return label
def prepare(prog):
"""Add a start block that loads each parameter from its slot, and split
each edge into a block with phis whose source ends in a branch."""
for b in prog.blocks.values():
for ins in b.instrs:
if ins[0] not in ("const", "copy", "op", "phi"):
raise ValueError("only const, copy, op and phi: %r" % (ins,))
for a in [ins[1]] + toyir.uses(ins):
if is_mem(a):
raise ValueError("names that start with %r are reserved" % MEM)
if any(ins[0] == "phi" for ins in prog.blocks[prog.entry].instrs):
raise ValueError("the entry block must not have phis")
blocks = {lab: toyir.Block(list(b.instrs), b.term) for lab, b in prog.blocks.items()}
for lab in list(blocks):
term = blocks[lab].term
if term[0] != "br" or term[2] == term[3]:
continue
for target in (term[2], term[3]):
if not _phis(blocks[target]):
continue
mid = _fresh(blocks, "%s_%s" % (lab, target))
blocks[mid] = toyir.Block([], ("jump", target))
term = (term[0], term[1]) + tuple(mid if t == target else t for t in term[2:])
blocks[target].instrs = [
("phi", ins[1], {(mid if p == lab else p): a for p, a in ins[2].items()}) if ins[0] == "phi" else ins
for ins in blocks[target].instrs
]
blocks[lab].term = term
start = _fresh(blocks, "start")
pro = [("copy", p, MEM + p) for p in prog.params]
out = {start: toyir.Block(pro, ("jump", prog.entry))}
out.update(blocks)
return toyir.Program([MEM + p for p in prog.params], out)
# ------------------------------------------------------------- block order
def dominators(prog):
"""Immediate dominators by the iterative method of Cooper, Harvey and
Kennedy. Unreachable blocks are left out."""
entry = prog.entry
post, seen = [], {entry}
stack = [(entry, iter(toyir.succs(prog, entry)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
post.append(v)
stack.pop()
elif w not in seen:
seen.add(w)
stack.append((w, iter(toyir.succs(prog, w))))
rpo = post[::-1]
index = {v: i for i, v in enumerate(rpo)}
pred = toyir.preds(prog)
idom = {entry: entry}
def meet(a, b):
while a != b:
while index[a] > index[b]:
a = idom[a]
while index[b] > index[a]:
b = idom[b]
return a
changed = True
while changed:
changed = False
for v in rpo[1:]:
ps = [p for p in pred[v] if p in idom]
new = ps[0]
for p in ps[1:]:
new = meet(p, new)
if idom.get(v) != new:
idom[v] = new
changed = True
return idom, rpo
def dominates(idom, a, b):
while b != a and idom[b] != b:
b = idom[b]
return a == b
def loops(prog, idom, reach):
"""The natural loops, as a dict from header to the set of its blocks.
Raises ValueError if the graph is not reducible."""
pred = toyir.preds(prog)
body = {}
for u in reach:
for h in toyir.succs(prog, u):
if dominates(idom, h, u):
blocks = body.setdefault(h, {h})
work = [u]
while work:
v = work.pop()
if v not in blocks:
blocks.add(v)
work.extend(p for p in pred[v] if p in reach)
# Reducible if and only if the graph without the back edges is acyclic.
state = {}
for root in reach:
if root in state:
continue
state[root] = 1
stack = [(root, iter(toyir.succs(prog, root)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
state[v] = 2
stack.pop()
elif w in body and v in body[w]:
continue
elif state.get(w) == 1:
raise ValueError("the control flow graph is not reducible")
elif w not in state:
state[w] = 1
stack.append((w, iter(toyir.succs(prog, w))))
return body
def loop_bodies(prog):
idom, rpo = dominators(prog)
return loops(prog, idom, set(rpo)), rpo
def block_order(prog):
"""A linear order of the reachable blocks in which every block comes
after its dominators and the blocks of each loop are contiguous. Each
loop is first shrunk to its header; the resulting acyclic graph is put
in reverse postorder; then each header is replaced by the order of its
own loop, built the same way."""
body, rpo = loop_bodies(prog)
rank = {v: i for i, v in enumerate(rpo)}
def region(blocks, head):
# top[v] is v, or the header of the largest loop inside this region
# that holds v.
top = {}
for v in blocks:
around = [h for h, hb in body.items() if h != head and h in blocks and v in hb]
top[v] = max(around, key=lambda h: len(body[h])) if around else v
succ = {x: [] for x in set(top.values())}
for v in sorted(blocks, key=rank.get):
for w in toyir.succs(prog, v):
if w in blocks and w != head and top[w] != top[v] and top[w] not in succ[top[v]]:
succ[top[v]].append(top[w])
first = head if head is not None else prog.entry
post, seen = [], {first}
stack = [(first, iter(succ[first]))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
post.append(v)
stack.pop()
elif w not in seen:
seen.add(w)
stack.append((w, iter(succ[w])))
out = []
for x in reversed(post):
out += [x] if x == head or x not in body else region(body[x], x)
return out
return region(set(rpo), None)
# --------------------------------------------------------------- intervals
def _add_range(ranges, a, e):
"""Add [a, e) to a sorted list of disjoint ranges, merging touching ones."""
if a >= e:
return
out = []
for r in ranges:
if r[1] < a or r[0] > e:
out.append(r)
else:
a, e = min(a, r[0]), max(e, r[1])
out.append([a, e])
out.sort()
ranges[:] = out
def build_intervals(prog, order):
"""Number the positions, then build the ranges of each name in one
backward pass over the blocks. Returns (ranges, pos, start, end), where
pos maps (label, j) to the position of item j of the block."""
pos, start, end = {}, {}, {}
p = 0
for lab in order:
start[lab] = p
n = len(_body(prog.blocks[lab])) + 1
for j in range(n):
pos[(lab, j)] = p + 2 + 2 * j
p += 2 * n + 2
end[lab] = p
body, _ = loop_bodies(prog)
last = {}
for h, blocks in body.items():
last[h] = max(blocks, key=order.index)
ranges = {}
live_in = {}
for lab in reversed(order): # @line L3
b = prog.blocks[lab]
live = set()
for s in toyir.succs(prog, lab): # @line L4
live |= live_in.get(s, set())
for ins in _phis(prog.blocks[s]):
a = ins[2][lab]
if isinstance(a, str):
live.add(a)
for x in live: # @line L5
_add_range(ranges.setdefault(x, []), start[lab], end[lab])
items = _body(b)
t = b.term
reads = toyir.term_uses(t)
for x in reads:
_add_range(ranges.setdefault(x, []), start[lab], pos[(lab, len(items))])
live.add(x)
for j in range(len(items) - 1, -1, -1): # @line L6
ins = items[j]
q = pos[(lab, j)]
y = ins[1]
if y in live: # @line L7
r = ranges[y][0]
r[0] = q
live.discard(y)
else:
_add_range(ranges.setdefault(y, []), q, q + 1)
for x in toyir.uses(ins): # @line L8
if not is_mem(x):
_add_range(ranges.setdefault(x, []), start[lab], q)
live.add(x)
for ins in _phis(b): # @line L9
y = ins[1]
if y in live:
live.discard(y)
else:
_add_range(ranges.setdefault(y, []), start[lab], start[lab] + 1)
live_in[lab] = live
# A name live at a loop header is live in the whole loop, which is
# contiguous in the order.
if lab in body: # @line L10
for x in live:
_add_range(ranges[x], start[lab], end[last[lab]]) # @line L11
return ranges, pos, start, end
def covers(ranges, p):
return any(a <= p < e for a, e in ranges)
def intersects(r1, r2):
i = j = 0
while i < len(r1) and j < len(r2):
if r1[i][0] < r2[j][1] and r2[j][0] < r1[i][1]:
return True
if r1[i][1] <= r2[j][1]:
i += 1
else:
j += 1
return False
# ------------------------------------------------------------------- scan
def linear_scan(ranges, k):
"""Scan the intervals by start. Returns (reg, spilled)."""
names = sorted(ranges, key=lambda x: (ranges[x][0][0], x)) # @line L12
reg, spilled = {}, set()
active, inactive = [], []
for cur in names: # @line L13
p = ranges[cur][0][0]
for it in list(active): # @line L14
if ranges[it][-1][1] <= p:
active.remove(it)
elif not covers(ranges[it], p):
active.remove(it)
inactive.append(it)
for it in list(inactive): # @line L15
if ranges[it][-1][1] <= p:
inactive.remove(it)
elif covers(ranges[it], p):
inactive.remove(it)
active.append(it)
blocked = {reg[it] for it in inactive if intersects(ranges[it], ranges[cur])}
busy = {reg[it] for it in active} | blocked # @line L16
free = [r for r in range(k) if r not in busy]
if free:
reg[cur] = free[0] # @line L17
active.append(cur)
continue
cands = [it for it in active if reg[it] not in blocked]
s = max(cands, key=lambda it: (ranges[it][-1][1], ranges[it][0][0], it), default=None) # @line L18
if s is not None and ranges[s][-1][1] > ranges[cur][-1][1]:
reg[cur] = reg.pop(s) # @line L19
spilled.add(s)
active.remove(s)
active.append(cur)
else:
spilled.add(cur) # @line L20
return reg, spilled
# ------------------------------------------------------------ phi removal
def sequentialize(moves):
"""Turn a parallel copy, a list of (dst, src) with distinct dst, into a
list of instructions. A cycle is broken by saving one destination in s0;
a move from memory to memory goes through s1."""
moves = [(d, s) for d, s in moves if d != s]
out = []
def emit(d, s):
if isinstance(s, int):
out.append(("const", d, s))
elif is_mem(d) and is_mem(s):
out.extend([("copy", "s1", s), ("copy", d, "s1")])
else:
out.append(("copy", d, s))
while moves:
srcs = {s for _, s in moves if isinstance(s, str)}
for i, (d, s) in enumerate(moves):
if d not in srcs:
emit(d, s)
moves.pop(i)
break
else:
d = moves[0][0]
out.append(("copy", "s0", d))
moves = [(dd, "s0" if ss == d else ss) for dd, ss in moves]
return out
def _rewrite_body(instrs, loc):
out = []
for ins in instrs:
x = loc(ins[1])
if ins[0] == "const":
out.append(("const", x, ins[2]))
continue
locs = [loc(a) for a in ([ins[2]] if ins[0] == "copy" else [ins[3], ins[4]])]
if ins[0] == "copy":
if locs[0] != x:
if is_mem(locs[0]) and is_mem(x):
out += [("copy", "s0", locs[0]), ("copy", x, "s0")]
else:
out.append(("copy", x, locs[0]))
continue
loaded = {}
for a in locs:
if is_mem(a) and a not in loaded:
loaded[a] = ("s0", "s1")[len(loaded)]
out.append(("copy", loaded[a], a))
a, c = (loaded.get(v, v) for v in locs)
if is_mem(x):
out += [("op", "s0", ins[2], a, c), ("copy", x, "s0")]
else:
out.append(("op", x, ins[2], a, c))
return out
def allocate(prog, k):
if k < 1:
raise ValueError("k must be at least 1")
work = prepare(prog) # @line L1
order = block_order(work) # @line L2
ranges, _, _, _ = build_intervals(work, order)
reg, spilled = linear_scan(ranges, k)
def loc(a):
if not isinstance(a, str) or is_mem(a):
return a
return MEM + a if a in spilled else "r%d" % reg[a]
reached = set(order)
copies = {lab: [] for lab in work.blocks}
for lab in order: # @line L21
for ins in _phis(work.blocks[lab]):
for p, a in ins[2].items():
if p in reached:
copies[p].append((loc(ins[1]), loc(a)))
blocks = {}
for lab in order:
b = work.blocks[lab]
body = _rewrite_body(_body(b), loc)
term = b.term
if copies[lab]:
body += sequentialize(copies[lab]) # @line L22
if term[0] in ("br", "ret"):
a = loc(term[1])
if is_mem(a):
body.append(("copy", "s0", a))
a = "s0"
term = (term[0], a) + term[2:]
blocks[lab] = toyir.Block(body, term)
return toyir.Program(list(work.params), blocks), reg, spilled # @line L23
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_ssa_linear_scan.py 406 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ssa-linear-scan/. The authors are listed in prov/SBG2CF.jsonl.
import random
import pytest
import toyir
from ssa_linear_scan import allocate, block_order, build_intervals, covers, linear_scan, prepare
DIAMOND = """# params: p
entry:
a = p + 1
br p L R
L:
d = a - p
jump J
R:
b = p * 2
c = b + p
jump J
J:
e = phi [L: d, R: c]
ret e
"""
# ------------------------------------------------- SSA construction (Cytron)
def dominator_sets(prog):
"""Dom(v) = {v} + the meet of Dom(p) over the predecessors, by the plain
fixed point."""
labels = list(prog.blocks)
pred = toyir.preds(prog)
dom = {v: set(labels) for v in labels}
dom[prog.entry] = {prog.entry}
changed = True
while changed:
changed = False
for v in labels:
if v == prog.entry:
continue
ps = [dom[p] for p in pred[v]]
new = {v} | (set.intersection(*ps) if ps else set())
if new != dom[v]:
dom[v], changed = new, True
return dom
def idoms(dom):
idom = {}
for v in dom:
strict = dom[v] - {v}
for d in strict:
if strict <= dom[d]:
idom[v] = d
return idom
def is_reducible(prog):
"""Reducible if and only if the graph without the edges u -> v with v
dominating u is acyclic."""
dom = dominator_sets(prog)
indeg = {v: 0 for v in prog.blocks}
fwd = {v: [w for w in toyir.succs(prog, v) if w not in dom[v]] for v in prog.blocks}
for v in fwd:
for w in fwd[v]:
indeg[w] += 1
work = [v for v in indeg if indeg[v] == 0]
seen = 0
while work:
v = work.pop()
seen += 1
for w in fwd[v]:
indeg[w] -= 1
if indeg[w] == 0:
work.append(w)
return seen == len(prog.blocks)
def block_live_in(prog):
live = {lab: set() for lab in prog.blocks}
changed = True
while changed:
changed = False
for lab in reversed(list(prog.blocks)):
b = prog.blocks[lab]
cur = set(toyir.term_uses(b.term))
for s in toyir.succs(prog, lab):
cur |= live[s]
for ins in reversed(b.instrs):
cur.discard(ins[1])
cur |= set(toyir.uses(ins))
if cur != live[lab]:
live[lab], changed = cur, True
return live
def to_ssa(prog):
"""Pruned SSA form: phis at the iterated dominance frontier where the
name is live, then renaming along the dominator tree."""
dom = dominator_sets(prog)
idom = idoms(dom)
pred = toyir.preds(prog)
live = block_live_in(prog)
df = {v: set() for v in prog.blocks}
for v in prog.blocks:
if len(pred[v]) >= 2:
for p in pred[v]:
r = p
while r != idom.get(v):
df[r].add(v)
r = idom[r]
defsites = {}
for p in prog.params:
defsites.setdefault(p, set()).add(prog.entry)
for lab, b in prog.blocks.items():
for ins in b.instrs:
defsites.setdefault(ins[1], set()).add(lab)
phis = {lab: [] for lab in prog.blocks}
for x, sites in sorted(defsites.items()):
work, placed = list(sites), set()
while work:
v = work.pop()
for w in df[v]:
if w not in placed:
placed.add(w)
if x in live[w]:
phis[w].append(x)
if w not in sites:
work.append(w)
children = {v: [] for v in prog.blocks}
for v, d in idom.items():
children[d].append(v)
count, stacks = {}, {p: [p] for p in prog.params}
blocks, phi_name = {}, {}
phi_args = {lab: {x: {} for x in phis[lab]} for lab in prog.blocks}
def new(x):
count[x] = count.get(x, 0) + 1
name = "%s.%d" % (x, count[x])
stacks.setdefault(x, []).append(name)
return name
def top(a):
return stacks[a][-1] if isinstance(a, str) else a
def walk(v):
pushed = []
for x in phis[v]:
phi_name[(v, x)] = new(x)
pushed.append(x)
body = []
for ins in prog.blocks[v].instrs:
if ins[0] == "const":
body.append(("const", None, ins[2]))
elif ins[0] == "copy":
body.append(("copy", None, top(ins[2])))
else:
body.append(("op", None, ins[2], top(ins[3]), top(ins[4])))
body[-1] = (body[-1][0], new(ins[1])) + body[-1][2:]
pushed.append(ins[1])
t = prog.blocks[v].term
if t[0] in ("br", "ret"):
t = (t[0], top(t[1])) + t[2:]
blocks[v] = (body, t)
for s in toyir.succs(prog, v):
for x in phis[s]:
phi_args[s][x][v] = top(x)
for c in sorted(children[v], key=list(prog.blocks).index):
walk(c)
for x in pushed:
stacks[x].pop()
walk(prog.entry)
out = {}
for lab in prog.blocks:
body, t = blocks[lab]
ph = [("phi", phi_name[(lab, x)], phi_args[lab][x]) for x in phis[lab]]
out[lab] = toyir.Block(ph + body, t)
return toyir.Program(list(prog.params), out)
def random_ssa(rng, acyclic):
"""A random reducible program and its SSA form."""
while True:
prog = toyir.random_program(rng, rng.randint(2, 6), rng.randint(1, 8), acyclic)
if is_reducible(prog):
return prog, to_ssa(prog)
# --------------------------------------------- independent liveness by search
def items_of(prog):
"""(label, kind, j, defs, reads) for the phi group (if any), each other
instruction and the terminator of each block. A phi operand is read by
the terminator of its predecessor."""
items, first = [], {}
for lab, b in prog.blocks.items():
first[lab] = len(items)
ph = [ins for ins in b.instrs if ins[0] == "phi"]
body = [ins for ins in b.instrs if ins[0] != "phi"]
if ph:
items.append((lab, "phi", None, {i[1] for i in ph}, set()))
for j, ins in enumerate(body):
items.append((lab, "ins", j, {ins[1]}, set(toyir.uses(ins))))
reads = set(toyir.term_uses(b.term))
for s in toyir.succs(prog, lab):
for ins in prog.blocks[s].instrs:
if ins[0] == "phi" and isinstance(ins[2][lab], str):
reads.add(ins[2][lab])
items.append((lab, "term", len(body), set(), reads))
nxt = [[first[s] for s in toyir.succs(prog, it[0])] if it[1] == "term" else [n + 1] for n, it in enumerate(items)]
return items, nxt
def brute_live_out(prog):
"""For each item, the names live just after it: a name is live if some
path of items reaches a read of it with no definition before. Slots
(mem.x) are left out."""
items, nxt = items_of(prog)
prv = [[] for _ in items]
for n, ss in enumerate(nxt):
for s in ss:
prv[s].append(n)
live_in = [set() for _ in items]
for x in set().union(*(it[4] for it in items)) - {x for it in items for x in it[4] if x.startswith("mem.")}:
work = [n for n, it in enumerate(items) if x in it[4]]
seen = set(work)
while work:
v = work.pop()
for p in prv[v]:
if p not in seen and x not in items[p][3]:
seen.add(p)
work.append(p)
for n in seen:
live_in[n].add(x)
return items, [set().union(*(live_in[s] for s in nxt[n])) for n in range(len(items))]
def position_after(item, pos, start):
lab, kind, j = item[0], item[1], item[2]
return start[lab] + 1 if kind == "phi" else pos[(lab, j)] + 1
# ------------------------------------------------------------------- tests
def check(orig, ssa, k, rng):
work = prepare(ssa)
out, reg, spilled = allocate(ssa, k)
items, live_out = brute_live_out(work)
for it, o in zip(items, live_out):
here = [x for x in it[3] | o if x not in spilled and not x.startswith("mem.")]
assert all(0 <= reg[x] < k for x in here)
assert len({reg[x] for x in here}) == len(here), (it, here)
for b in out.blocks.values():
assert all(ins[0] != "phi" for ins in b.instrs)
for _ in range(4):
args = [rng.randint(-6, 6), rng.randint(-6, 6)]
assert toyir.run(out, args, fuel=200000) == toyir.run(orig, args, fuel=200000)
return reg, spilled
def test_random_programs_keep_their_outputs():
rng = random.Random(11)
spills = 0
for trial in range(120):
orig, ssa = random_ssa(rng, acyclic=trial % 2 == 0)
for k in (1, 2, 3, 4):
spills += len(check(orig, ssa, k, rng)[1])
assert spills > 0
def test_intervals_are_exact_liveness():
rng = random.Random(5)
for trial in range(150):
_, ssa = random_ssa(rng, acyclic=trial % 3 == 0)
work = prepare(ssa)
order = block_order(work)
ranges, pos, start, _ = build_intervals(work, order)
items, live_out = brute_live_out(work)
for it, o in zip(items, live_out):
p = position_after(it, pos, start)
expect = set(o)
if it[1] == "term":
# The phi operands stay live to the end of the block, where
# the parallel copy reads them.
for s in toyir.succs(work, it[0]):
for ins in work.blocks[s].instrs:
if ins[0] == "phi" and isinstance(ins[2][it[0]], str):
expect.add(ins[2][it[0]])
assert {x for x in ranges if covers(ranges[x], p)} == expect, (it, expect)
# Every definition is inside the interval of its name.
for it in items:
for y in it[3]:
q = start[it[0]] if it[1] == "phi" else pos[(it[0], it[2])]
assert covers(ranges[y], q)
def test_block_order_respects_dominance_and_loops():
rng = random.Random(9)
for trial in range(150):
_, ssa = random_ssa(rng, acyclic=False)
work = prepare(ssa)
order = block_order(work)
assert sorted(order) == sorted(work.blocks)
at = {v: i for i, v in enumerate(order)}
dom = dominator_sets(work)
for v in order:
assert all(at[d] <= at[v] for d in dom[v])
# The loop of a header is the union of the natural loops of its back edges.
pred = toyir.preds(work)
loops = {}
for u in work.blocks:
for h in toyir.succs(work, u):
if h in dom[u]:
loop, stack = loops.setdefault(h, {h}), [u]
while stack:
v = stack.pop()
if v not in loop:
loop.add(v)
stack.extend(pred[v])
for h, loop in loops.items():
spots = sorted(at[v] for v in loop)
assert spots == list(range(spots[0], spots[0] + len(spots)))
assert order[spots[0]] == h
def test_no_spill_and_max_live_registers_when_pressure_fits():
rng = random.Random(3)
for trial in range(150):
orig, ssa = random_ssa(rng, acyclic=trial % 2 == 1)
items, live_out = brute_live_out(prepare(ssa))
m = max(len(it[3] | o) for it, o in zip(items, live_out))
for k in (m, m + 1):
reg, spilled = check(orig, ssa, k, rng)
assert not spilled
assert len(set(reg.values())) == m
def test_irreducible_graph_is_rejected():
text = """# params: p
A:
br p B C
B:
x = p + 1
jump C
C:
y = p + 2
br y B D
D:
ret p
"""
prog = toyir.parse(text)
assert not is_reducible(prog)
with pytest.raises(ValueError):
allocate(prog, 2)
def test_diamond_hole_saves_a_register():
prog = toyir.parse(DIAMOND)
work = prepare(prog)
order = block_order(work)
assert order == ["start", "entry", "R", "L", "J"]
ranges, pos, start, end = build_intervals(work, order)
assert ranges["a"] == [[8, 12], [20, 22]]
assert ranges["p"] == [[2, 16], [20, 22]]
# The interval of a has a hole over R, where b and c live.
hull = {x: (r[0][0], r[-1][1]) for x, r in ranges.items()}
overlap = max(sum(1 for a, e in hull.values() if a <= q < e) for q in range(end["J"]))
assert overlap == 3
out, reg, spilled = allocate(prog, 2)
assert not spilled
assert reg == {"p": 0, "a": 1, "b": 1, "c": 0, "d": 0, "e": 0}
for p in range(-3, 4):
assert toyir.run(out, [p]) == toyir.run(prog, [p])
def test_scan_spills_furthest_end():
ranges = {"x": [[0, 20]], "y": [[1, 5]], "z": [[2, 4]]}
reg, spilled = linear_scan(ranges, 2)
assert spilled == {"x"}
assert reg == {"y": 1, "z": 0}
def test_inactive_interval_never_meets_current():
# In strict SSA with a dominance order, an earlier interval in a hole at
# the start of cur never meets cur, so the inactive test is never needed.
rng = random.Random(5)
pairs = 0
for trial in range(150):
_, ssa = random_ssa(rng, acyclic=trial % 2 == 0)
work = prepare(ssa)
ranges = build_intervals(work, block_order(work))[0]
cells = {x: {q for a, e in r for q in range(a, e)} for x, r in ranges.items()}
names = sorted(ranges, key=lambda x: (ranges[x][0][0], x))
for i, cur in enumerate(names):
p = ranges[cur][0][0]
for x in names[:i]:
if max(cells[x]) >= p and p not in cells[x]:
pairs += 1
assert not cells[x] & cells[cur]
assert pairs > 100
History
Poletto and Sarkar (1999) introduced linear scan for fast code generation, with one interval per name. Traub, Holloway and Smith (1998) used lifetimes with holes in their second-chance binpacking allocator. Mössenböck and Pfeiffer (2002) built a linear scan on lifetime intervals of an SSA-based intermediate form with register constraints, and Wimmer and Mössenböck (2005) added interval splitting and register hints in the allocator of the Java HotSpot client compiler. These allocators still left SSA form before the scan. Wimmer and Franz (2010) changed the HotSpot client allocator to work on SSA form. They built the intervals without iterative liveness, skipped the intersection tests that SSA form makes unneeded, and removed the phis in the resolution phase. They reported code that was as good or slightly better, and a faster allocator.
References
- Christian Wimmer and Michael Franz, Linear scan register allocation on SSA form, CGO 2010, 170-179, the block order with dominators first and contiguous loops, the construction of the lifetime intervals in one backward pass over the blocks with a range over the whole loop for names live at a loop header, the intersection tests that SSA form makes unneeded, and the removal of the phis in the resolution phase after allocation
- Christian Wimmer and Hanspeter Mössenböck, Optimized interval splitting in a linear scan register allocator, VEE 2005, 132-141, the lifetime intervals with holes, the active and inactive sets of the scan, interval splitting and register hints, and the resolution of moves on the edges in the HotSpot client compiler
- Hanspeter Mössenböck and Michael Pfeiffer, Linear scan register allocation in the context of SSA form and register constraints, Compiler Construction (CC 2002), LNCS, 229-246, linear scan on lifetime intervals of a program in SSA form, with register constraints of the machine and the phis turned into moves after allocation
- Omri Traub, Glenn Holloway and Michael D. Smith, Quality and speed in linear-scan register allocation, PLDI 1998, 142-151, lifetimes with holes in second-chance binpacking, where a value in a hole does not hold its register
- Massimiliano Poletto and Vivek Sarkar, Linear scan register allocation, ACM TOPLAS 21(5), 1999, 895-913, the original scan over live intervals sorted by start, with the spill of the interval that ends last
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 SBG2CF Edit this page History Report an error Markdown