Algorithm Search⌘K

Algorithmcore

Linear scan register allocation

Also called Poletto-Sarkar linear scan.

Sorts live intervals by start and assigns registers in one pass, spilling the interval that ends last when registers run out.

Time
O(l + s n + n log n) worst
Space
O(s n) extra
Where
k = the number of registers; l = the time of one liveness analysis; n = the number of names; s = the number of instructions and terminators
Properties
deterministicofflineiterative
Origin
Massimiliano Poletto, Vivek Sarkar, 1999

Linear scan register allocation gives registers to the names of a program without building an interference graph. It puts the instructions in one linear order, replaces each name by one interval from its first to its last live position, and visits the intervals by start. A free register goes to each new interval. When none is free, it spills the interval that ends last, which may be the new one. It runs in near-linear time, so JIT compilers use it, but it is a heuristic for the register allocation problem: an interval can contain points where its name is dead, and then it spills where a graph coloring allocator would not.

In plain words

Lay the whole function out as one long line of instructions. For each value, draw a bar from the first place it is needed to the last. Now walk along the line from left to right. When a bar starts, give it a free register. When a bar ends, its register becomes free again. If a bar starts and every register is busy, look at all the bars that cover this place, the new one included. Throw out the one that goes on the longest, and keep its value in memory. That choice frees a register for the longest time, and for bars on a line it is the best choice. The bars are rough, though: a bar can cover a branch where its value is never used, so the method can waste registers there.

The problem

The input is a program PP in the toy IR with const, copy and op instructions and no phi, and a number k≥1k \ge 1 of registers. The output is a program P′P' that uses only the registers r0,…,rk−1r_0, \ldots, r_{k-1}, two scratch registers s0s_0 and s1s_1 kept apart for spill code, and memory slots mem.x, and that has the same outcome as PP on every input.

Number the instructions and terminators of PP in the order of the blocks as items 0,1,…0, 1, \ldots. Item nn reads at position 2n2n and writes at position 2n+12n+1, so a value read for the last time by an item can give its register to the value that the same item writes. The interval of a name xx is the range from the first to the last position where xx is written or live before an item. The overlap of a set of intervals is the largest number of them that contain one position.

The algorithm

  1. LINEAR-SCAN-ALLOCATE(P, k)
  2. 1number the items of P in block order; item n reads at 2n and writes at 2n+1
  3. 2compute the names live just before each item
  4. 3I[x] <- [smallest, largest] of the write positions of x and the positions 2n with x live before item n
  5. 4active <- empty // sorted by end
  6. 5free <- {0, ..., k-1}
  7. 6for each interval i in order of increasing start do
  8. 7EXPIRE-OLD(i)
  9. 8if |active| = k then SPILL-AT(i)
  10. 9else reg[i] <- the lowest register in free; remove it from free; add i to active
  11. EXPIRE-OLD(i)
  12. 10for each j in active, in order of increasing end do
  13. 11if end[j] >= start[i] then return
  14. 12remove j from active; add reg[j] to free
  15. SPILL-AT(i)
  16. 13s <- the interval in active with the largest end
  17. 14if end[s] > end[i] then reg[i] <- reg[s]; spill s; remove s from active; add i to active
  18. 15else spill i
  19. 16return P with each kept name x renamed to r[reg[x]], each spilled name x kept in mem.x
  20. (loaded into s0 or s1 before a use, computed into s0 and stored after a definition),
  21. and each copy whose two sides get the same location deleted

Ties at line L6 go by end, then by name. Line L13 takes the largest end, then the largest start, then the last name, and line L14 keeps ii only if ss comes strictly later in that order. The implementation first adds a block that loads each parameter from its slot, as the Chaitin allocator does, so that a parameter has a definition.

Lines L6 to L15 are the interval partitioning greedy with a cap of kk colors. The spill rule of line L13 is the furthest end rule, the same rule as Belady's cache replacement, applied to intervals.

Example

Take this program with the parameter p and k=2k = 2:

entry:
  a = p + 1
  br p B1 B2
B1:
  b = p * 2
  c = b + p
  ret c
B2:
  d = a - p
  ret d

The items are numbered 0 to 6 in block order: a = p + 1 is 0, the branch is 1, b, c and ret c are 2 to 4, and d and ret d are 5 and 6. The names live before each item are {p}\{p\}, {p,a}\{p, a\}, {p}\{p\}, {p,b}\{p, b\}, {c}\{c\}, {p,a}\{p, a\} and {d}\{d\}. So the intervals are:

name written at live at interval
pp none 0, 2, 4, 6, 10 [0,10][0, 10]
aa 1 2, 10 [1,10][1, 10]
bb 5 6 [5,6][5, 6]
cc 7 8 [7,8][7, 8]
dd 11 12 [11,12][11, 12]

The value aa is dead in B1, but B1 lies between the definition of aa and its use in B2, so the interval of aa covers B1. Position 5 lies in the intervals of pp, aa and bb, so the overlap is 3. The scan goes:

interval expired action active after
p [0,10]p\ [0, 10] none p→r0p \to r_0 pp
a [1,10]a\ [1, 10] none a→r1a \to r_1 p,ap, a
b [5,6]b\ [5, 6] none full; s=as = a (end 10, start 1), 10>610 > 6: spill aa, b→r1b \to r_1 b,pb, p
c [7,8]c\ [7, 8] bb c→r1c \to r_1 c,pc, p
d [11,12]d\ [11, 12] cc, pp d→r0d \to r_0 dd

The implementation adds the block start with p = mem.p, which moves the other positions by 4, and gives:

start:
  r0 = mem.p
  jump entry
entry:
  s0 = r0 + 1
  mem.a = s0
  br r0 B1 B2
B1:
  r1 = r0 * 2
  r1 = r1 + r0
  ret r1
B2:
  s0 = mem.a
  r0 = s0 - r0
  ret r0

The interference graph has only the edges pp-aa and pp-bb. Two colors suffice (p→r0p \to r_0, aa and b→r1b \to r_1), so a graph coloring allocator needs no spill here. Linear scan spilled aa only because its interval covers B1. With the blocks in the order entry, B2, B1, the interval of aa ends before bb starts, the overlap is 2, and linear scan spills nothing. The block order matters.

Correctness

The full proof is in the proof file. Its parts are:

  • Intervals contain interference. If two names are live before the same item, or one is written while the other is live after the write, their intervals share a position. So the overlap graph of the intervals contains the interference graph.
  • Registers. An invariant on active shows that two kept intervals that overlap get different registers, and that at most kk kept intervals contain any position.
  • No spill and few registers. The scan spills nothing if and only if the overlap is at most kk. Then it uses exactly as many registers as the overlap, since the lowest free register is always below the number of intervals that contain the current start.
  • Fewest spills. For each prefix of the intervals, the kept set has at least as many intervals that end before any time tt as any other set with overlap at most kk. With t=∞t = \infty this says the scan keeps the most intervals. The proof uses only that line L13 drops an interval with the largest end.
  • Same outcome. At each point of a run, each live name that has a value is held by its register or its slot. A write goes to a register that no other live name holds, because of the first two parts.

So linear scan is optimal for its intervals, both in registers and in spills, and correct for the program. It is still a heuristic, because the intervals are larger than the live ranges: the example spills a program that two registers can hold.

Proof: Linear scan gives a correct program, and it is optimal for its intervalsfull

We prove five facts about LINEAR-SCAN-ALLOCATE. Lemma 1 links intervals to liveness. Lemmas 2 to 4 are about the scan on intervals: no two overlapping kept intervals share a register, no spill happens when the overlap is at most kk, and the number of spills is the smallest possible for the given intervals. Lemma 5 shows that the rewritten program has the same outcome as the input.

Setup

The program PP has const, copy and op instructions only, and it has been prepared: a new entry block copies each live parameter pp from its slot mem.p. Line L1 numbers the instructions and terminators of PP in block order as items 0,1,…,N−10, 1, \ldots, N-1. Item nn reads at position 2n2n and writes at position 2n+12n+1. Each instruction is followed in its block by another item, at least by the terminator, so the only successor of an instruction nn is item n+1n+1. The successors of a terminator are the first items of its successor blocks.

Write L(n)L(n) for the set of non-slot names live just before item nn, as line L2 computes it. The backward fixed point of live variable analysis gives exactly the names xx for which some path of items from nn reaches a read of xx with no write of xx before that read. For an instruction nn that writes yy and reads use(n)\mathrm{use}(n),

L(n)=use(n)∪(L(n+1)∖{y}),L(n) = \mathrm{use}(n) \cup (L(n+1) \setminus \{y\}),

and for a terminator, L(n)L(n) is the name it reads (if any) together with the union of L(m)L(m) over its successor items mm.

Line L3 gives each non-slot name xx the interval I(x)=[sx,ex]I(x) = [s_x, e_x], the smallest closed range of integers that contains every write position 2n+12n+1 of xx and every position 2n2n with x∈L(n)x \in L(n). Two intervals overlap when they share a position. The overlap of a set of intervals is the largest number of them that contain one position.

Intervals contain interference

Lemma 1. If x,y∈L(n)x, y \in L(n), then 2n∈I(x)∩I(y)2n \in I(x) \cap I(y). If item nn writes yy and x≠yx \ne y is live just after nn, then 2n+1∈I(x)∩I(y)2n+1 \in I(x) \cap I(y).

Proof. The first claim is the definition of II. For the second, item nn is an instruction, so the point just after it is the point just before item n+1n+1, and x∈L(n+1)x \in L(n+1). Since x≠yx \ne y, the equation above gives x∈L(n)x \in L(n). So 2n2n and 2n+22n+2 are both in I(x)I(x), and I(x)I(x) is a range, so 2n+1∈I(x)2n+1 \in I(x). The write of yy puts 2n+12n+1 in I(y)I(y). □\square

So the overlap graph of the intervals contains the interference graph. The converse fails: an interval may contain positions where its name is dead, as in the example on the page. That is the only reason why linear scan is a heuristic for the program and not for its intervals.

The scan on intervals

Let σ\sigma be the order of line L6: by start, then by end, then by name. Write XmX_m for the first mm intervals of σ\sigma, GmG_m for the set of intervals of XmX_m that hold a register after step mm, and qq for the start of the interval i=σ(m+1)i = \sigma(m+1) of the next step. For a set FF of intervals and an integer tt, let F<tF_{<t} be the members of FF that end before tt.

Invariant (A). Just after line L7 in the step of ii, the list active is the set of members of GmG_m that end at or after qq, the registers of its members are pairwise different, and free holds the other registers of {0,…,k−1}\{0, \ldots, k-1\}.

Proof. By induction on mm. At m=0m = 0 both sides are empty and free is full. Suppose (A) holds at the step of ii. Lines L10 to L12 have just removed the members that end before qq, and returned their registers. Every member of GmG_m that ends at or after qq ended at or after each earlier start too, so no earlier step removed it, and it is in active. Line L9 takes a register from free, which no active member holds. Line L14 moves the register of the removed interval ss to ii, and ss leaves active. Line L15 changes nothing. In each case the registers stay pairwise different, and active becomes the set of members of Gm+1G_{m+1} that end at or after qq. The next start q′q' is at least qq, so after line L7 of the next step, active is the set of members of Gm+1G_{m+1} that end at or after q′q'. □\square

Every member of active starts at or before qq and ends at or after qq. So in the step of ii, active ∪{i}\cup \{i\} is a set of intervals that all contain the position qq.

Lemma 2 (registers). Two kept intervals that overlap get different registers. Each GmG_m has overlap at most kk.

Proof. Let aa and bb be kept at the end with aa before bb in σ\sigma. If they overlap, then sa≤sb≤eas_a \le s_b \le e_a. A kept interval never loses its register, so aa is in GmG_m for every step mm after its own, and in the step of bb, it ends at or after sbs_b. By (A), aa is in active there. Interval bb gets its register at line L9 from free, or at line L14 from the removed interval s≠as \ne a. In both cases (A) says the register differs from that of aa, and aa keeps its register to the end.

For the overlap, take a position pp and let ii be the last interval of σ\sigma that contains pp and is in GmG_m. Every member of GmG_m that contains pp starts at or before si≤ps_i \le p and ends at or after pp, so it contains sis_i and was in active or was ii at the end of the step of ii. That set has at most kk members, since line L9 only adds an interval when fewer than kk are active, and line L14 swaps one for one. □\square

Lemma 3 (no spill and the number of registers). Let ω\omega be the overlap of all intervals. The scan spills nothing if and only if ω≤k\omega \le k, and then it uses exactly ω\omega registers.

Proof. A spill happens at line L8 only when ∣active∣=k|\textit{active}| = k, and then active ∪{i}\cup \{i\} is k+1k+1 intervals that contain sis_i, so ω>k\omega > k. Conversely, if nothing is spilled, every interval is kept, and Lemma 2 gives ω≤k\omega \le k.

Now let nothing be spilled. When interval ii arrives with aa active intervals, those aa intervals and ii contain sis_i, so a+1≤ωa + 1 \le \omega. The aa active intervals hold aa registers, so the lowest free register is at most a≤ω−1a \le \omega - 1. So only the registers 0,…,ω−10, \ldots, \omega - 1 are used. Some position lies in ω\omega intervals, and by Lemma 2 they hold ω\omega different registers. □\square

Lemma 4 (fewest spills). Let F⊆XmF \subseteq X_m be any set with overlap at most kk. Then for every integer tt, including t=∞t = \infty, ∣F<t∣≤∣(Gm)<t∣|F_{<t}| \le |(G_m)_{<t}|. In particular ∣F∣≤∣Gm∣|F| \le |G_m|, so for m=nm = n the scan spills as few intervals as possible.

Proof. By induction on mm. For m=0m = 0 both sides are 00. Assume the claim for mm and take F⊆Xm+1F \subseteq X_{m+1} with overlap at most kk. Let AA be active after line L7 in the step of i=σ(m+1)i = \sigma(m+1), so ∣A∣≤k|A| \le k. Write [ϕ]=1[\phi] = 1 when the statement ϕ\phi is true and 00 otherwise.

Case 1: i∉Fi \notin F. Then F⊆XmF \subseteq X_m and ∣F<t∣≤∣(Gm)<t∣|F_{<t}| \le |(G_m)_{<t}|. Line L9 adds ii, line L15 adds nothing, and line L14 replaces ss by ii with ei≤ese_i \le e_s, so [ei<t]≥[es<t][e_i < t] \ge [e_s < t]. In all three cases ∣(Gm+1)<t∣≥∣(Gm)<t∣|(G_{m+1})_{<t}| \ge |(G_m)_{<t}|.

Case 2: i∈Fi \in F and ∣A∣<k|A| < k. Line L9 runs, so Gm+1=Gm∪{i}G_{m+1} = G_m \cup \{i\}. With F′=F∖{i}⊆XmF' = F \setminus \{i\} \subseteq X_m,

∣F<t∣=∣F<t′∣+[ei<t]≤∣(Gm)<t∣+[ei<t]=∣(Gm+1)<t∣.|F_{<t}| = |F'_{<t}| + [e_i < t] \le |(G_m)_{<t}| + [e_i < t] = |(G_{m+1})_{<t}|.

Case 3: i∈Fi \in F and ∣A∣=k|A| = k. Lines L13 to L15 drop the interval rr of A∪{i}A \cup \{i\} with the largest end: r=sr = s at line L14, or r=ir = i at line L15. So Gm+1=(Gm∪{i})∖{r}G_{m+1} = (G_m \cup \{i\}) \setminus \{r\}, and we must show

∣F<t′∣+[er<t]≤∣(Gm)<t∣.(∗)|F'_{<t}| + [e_r < t] \le |(G_m)_{<t}|. \qquad (*)

If er≥te_r \ge t, this is the claim for mm applied to F′F'. Let er<te_r < t. Every member of AA and ii end before tt, and every member of GmG_m outside AA ends before q≤ei<tq \le e_i < t. So ∣(Gm)<t∣=∣Gm∣|(G_m)_{<t}| = |G_m|, and we must show ∣F′∣≤∣Gm∣−1|F'| \le |G_m| - 1. Every member of F′F' starts at or before qq, so those that end at or after qq contain qq. Together with ii, which contains qq, there are at most kk of them, so ∣F′∣−∣F<q′∣≤k−1|F'| - |F'_{<q}| \le k - 1. By the claim for mm with t=qt = q, ∣F<q′∣≤∣(Gm)<q∣=∣Gm∣−k|F'_{<q}| \le |(G_m)_{<q}| = |G_m| - k, because exactly the kk members of AA end at or after qq. Adding the two bounds gives ∣F′∣≤∣Gm∣−1|F'| \le |G_m| - 1. □\square

The proof uses only that the dropped interval has the largest end in A∪{i}A \cup \{i\}, so the way ties are broken does not matter. The kept set GnG_n is a largest subfamily with overlap at most kk, which is the unit weight case of the maximum kk-colorable interval subgraph.

The rewritten program has the same outcome

Lemma 5. Assume that no run of PP reads a name before it writes it. Let P′P' be the result of line L16: each kept name xx becomes the register rreg(x)r_{\mathrm{reg}(x)}, each spilled name xx becomes the slot mem.x, an operand in a slot is first loaded into the scratch register s0s_0 or s1s_1, a result that goes to a slot is computed into s0s_0 and then stored, and a copy whose two sides become the same location is deleted. Then for every input, PP and P′P' have the same outcome.

Proof. Run PP and P′P' on the same input, with stores σ\sigma and σ′\sigma'. Let loc(x)\mathrm{loc}(x) be the location of xx in P′P'. We show that the runs visit the same blocks and that this holds just before each item nn of PP and the code of P′P' for it:

(R) Each name x∈L(n)x \in L(n) that has been written has σ′(loc(x))=σ(x)\sigma'(\mathrm{loc}(x)) = \sigma(x), and each slot mem.p of a parameter that the first block has not yet read holds the argument.

At the start, (R) holds, because both programs get the same arguments in the same slots and no non-slot name has been written.

Take an instruction nn that writes yy. Its operands are in L(n)L(n) and have been written, so by (R) their locations hold the right values, and loading them into s0s_0 or s1s_1 changes no location of a name. So P′P' computes the same value ww as PP, or traps in the same way. Then P′P' writes ww to loc(y)\mathrm{loc}(y), directly or through s0s_0. A deleted copy y = a has loc(y)=loc(a)\mathrm{loc}(y) = \mathrm{loc}(a), which already holds σ(a)=w\sigma(a) = w. So the claim holds for yy after the step.

Let x≠yx \ne y be a name in L(n+1)L(n+1) that has been written. It is in L(n)L(n), so its location was right before the step. The step writes only loc(y)\mathrm{loc}(y) and the scratch registers. No name lives in a scratch register. If xx is spilled, its slot mem.x differs from loc(y)\mathrm{loc}(y). If xx and yy are both kept, Lemma 1 says that I(x)I(x) and I(y)I(y) overlap, and Lemma 2 gives them different registers. So loc(x)\mathrm{loc}(x) still holds σ(x)\sigma(x). The parameter slots are read only in the first block, which has no predecessor and runs once, and the slot of a parameter pp is written only when pp is spilled and pp itself is defined. So (R) holds before item n+1n+1.

A terminator reads a name in L(n)L(n), so both programs take the same branch or return the same value. Each name live at the start of the next block is in L(n)L(n), and the terminator writes nothing, so (R) holds there. By induction over the run, both programs end in the same way: with the same value, with the same trap, or not at all. □\square

Summary

The scan is optimal for the interval graph that it builds: it uses the fewest registers when no spill is needed (Lemma 3) and spills the fewest intervals otherwise (Lemma 4). The result is always correct (Lemma 5). The interval graph contains the interference graph (Lemma 1), and it may be larger, so the scan may spill a program that a graph coloring allocator colors with kk registers.

Complexity

With nn names, ss items, kk registers and ll the time of live variable analysis:

  • Intervals. One backward walk per block gives the live set before each item, in O(sn)O(s n) time and space. Each interval then needs only its smallest and largest position.
  • Scan. Sorting by start takes O(nlog⁡n)O(n \log n). With active in a balanced search tree keyed by end, each step costs O(log⁡k)O(\log k), so the scan costs O(nlog⁡k)O(n \log k) besides the sort. The implementation keeps active as a sorted list, O(k)O(k) per step, which is the same for a fixed machine.
  • Rewrite. One pass over the items, O(s)O(s).

The total is O(l+sn+nlog⁡n)O(l + s n + n \log n). In a real compiler, liveness is computed once on sets of bits and the intervals come from one backward pass over the blocks, so the time is close to linear in the size of the program. That is the whole reason for the method: no graph with up to n2/2n^2 / 2 edges is built.

Properties

  • Optimal on intervals. If the overlap is at most kk, it uses exactly the overlap number of registers. Otherwise it spills the fewest intervals that bring the overlap down to kk, which is the unit weight case of the maximum kk-colorable interval subgraph.
  • Not optimal on programs. An interval is a convex hull of a live range in the linear order. The overlap graph can have more edges than the interference graph, as in the example.
  • Depends on the block order. A different block order gives different intervals. Orders that keep a loop body together, such as reverse postorder, give shorter intervals.
  • Whole intervals. A name is either in one register for its whole interval or in memory everywhere. It never moves between two registers.
  • Not optimal in spill cost. It counts spilled intervals, not loads and stores. A spilled name that is used often in a loop costs more than its count of one.

Variants and improvements

  • Second-chance binpacking (Traub, Holloway and Smith, 1998) keeps the lifetime holes of each name, lets a value move between a register and memory, and adds resolution moves on the edges of the control flow graph.
  • Interval splitting (Wimmer and Mössenböck, 2005) keeps intervals with holes and splits an interval at a good position instead of spilling it whole. A split part can get a different register. This is the allocator of the Java HotSpot client compiler.
  • Linear scan on SSA form (Wimmer and Franz, 2010) builds the intervals on SSA form, which makes them simpler, and resolves the phis after allocation.
  • Spill weights. Many versions spill the interval with the lowest use count weighted by loop depth instead of the furthest end. That loses the optimality on intervals but often gives faster code.
  • SSA-based allocation keeps the speed of a linear walk but colors the true interference graph of an SSA program, which is chordal, with the fewest registers.

When to use it

Use it when compile time matters more than the last few percent of code quality: in a JIT compiler (just-in-time compilation), in a baseline tier, or for very large generated functions. It is also simple to write and to debug. For an ahead-of-time compiler that can afford a graph, graph coloring or SSA-based allocation gives fewer spills. Inside one basic block, local register allocation with the furthest next use rule spills fewer loads and stores, because it splits values at each use.

Pitfalls

  • Read before write. Give the reads of an item a position before its write. Otherwise x = y + 1 with yy dead after it needs two registers, and the overlap is one too high.
  • Dead definitions. A name that is written and never read still has an interval of one position. Without it, the write may land in the register of a live name.
  • Live across a back edge. A name live at a loop header must be live to the end of the loop body in the linear order. Liveness from the fixed point gives this; a single pass that looks only at definitions and uses does not.
  • Scratch registers. The spill code needs registers that no interval can hold. Here s0s_0 and s1s_1 are kept apart for loads, which is enough for an instruction with two operands.
  • Ties at line L14. Spilling the active interval when it ends at the same position as the new one moves a register for nothing. Keep the active one on a tie.
  • Parameters. A parameter live on entry needs a write position. The block that loads parameters from their slots gives it one.

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.

linear_scan_register_allocation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-scan-register-allocation/. The authors are listed in prov/5E24WB.jsonl.
"""Linear scan register allocation (Poletto and Sarkar, 1999).

linear_scan(iv, k) works on intervals: iv maps each name to (start, end),
with start <= end, both ends included. It returns (reg, spilled): reg maps
each kept name to a register number in 0 .. k-1, and spilled is the set of
names that get no register.

allocate(prog, k) works on a toy IR program with const, copy and op
instructions only (no phi). It numbers the instructions in block order,
builds one interval per name, runs linear_scan and rewrites the program.
It returns (out, reg, spilled). The names in out are the registers
r0 .. r(k-1), the two scratch registers s0 and s1 that hold spilled values
for one instruction, and memory slots whose names start with "mem.". The
parameters of out are the memory slots of the parameters of prog.
"""

import toyir

MEM = "mem."
SCRATCH = ("s0", "s1")


def is_mem(name):
    return isinstance(name, str) and name.startswith(MEM)


# ---------------------------------------------------------- interval level


def linear_scan(iv, k):
    if k < 0:
        raise ValueError("k must be at least 0")
    reg = {}
    spilled = set()
    active = []  # @line L4 (kept sorted by end)
    free = list(range(k))  # @line L5
    order = sorted(iv, key=lambda x: (iv[x][0], iv[x][1], x))

    def end_key(x):
        return (iv[x][1], iv[x][0], x)

    def expire_old(start):
        for j in list(active):  # @line L10
            if iv[j][1] >= start:  # @line L11
                return
            active.remove(j)  # @line L12
            free.append(reg[j])
            free.sort()

    for i in order:  # @line L6
        start, end = iv[i]
        expire_old(start)  # @line L7
        if len(active) == k:  # @line L8
            # SPILL-AT: of the k + 1 intervals that contain start, drop the
            # one that ends last.
            if k > 0:
                s = active[-1]  # @line L13
            if k > 0 and end_key(s) > end_key(i):  # @line L14
                reg[i] = reg.pop(s)
                spilled.add(s)
                active.pop()
                active.append(i)
                active.sort(key=end_key)
            else:
                spilled.add(i)  # @line L15
        else:
            reg[i] = free.pop(0)  # @line L9
            active.append(i)
            active.sort(key=end_key)
    return reg, spilled


def max_overlap(iv):
    """The largest number of intervals that contain one point."""
    events = []
    for s, e in iv.values():
        events.append((s, 0))
        events.append((e, 1))
    best = cur = 0
    for _, kind in sorted(events):
        if kind == 0:
            cur += 1
            best = max(best, cur)
        else:
            cur -= 1
    return best


# ----------------------------------------------------------- program level


def _check(prog):
    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 and live_out of each block, by the backward fixed point."""
    use, kill = {}, {}
    for label, b in prog.blocks.items():
        u, d = set(), set()
        for ins in b.instrs:
            u.update(a for a in toyir.uses(ins) if a not in d)
            d.add(ins[1])
        u.update(a for a in toyir.term_uses(b.term) if a not in d)
        use[label], kill[label] = u, d
    live_in = {label: set() for label in prog.blocks}
    live_out = {label: set() for label in prog.blocks}
    changed = True
    while changed:
        changed = False
        for label in reversed(list(prog.blocks)):
            out = set()
            for s in toyir.succs(prog, label):
                out |= live_in[s]
            new_in = use[label] | (out - kill[label])
            if out != live_out[label] or new_in != live_in[label]:
                live_out[label], live_in[label] = out, new_in
                changed = True
    return live_in, live_out


def linear_order(prog):
    """The instructions and terminators in block order, as a list of
    (label, item, is_term). Item n reads at 2n and writes at 2n + 1."""
    out = []
    for label, b in prog.blocks.items():
        for ins in b.instrs:
            out.append((label, ins, False))
        out.append((label, b.term, True))
    return out


def live_before(prog):
    """For each item n of linear_order, the names live just before it."""
    _, live_out = liveness(prog)
    order = linear_order(prog)
    result = [None] * len(order)
    n = len(order) - 1
    for label in reversed(list(prog.blocks)):
        b = prog.blocks[label]
        live = set(live_out[label]) | set(toyir.term_uses(b.term))
        result[n] = set(live)
        n -= 1
        for ins in reversed(b.instrs):
            live.discard(ins[1])
            live.update(toyir.uses(ins))
            result[n] = set(live)
            n -= 1
    return result


def intervals(prog):
    """One interval per name that is not a memory slot: from the first to
    the last position where the name is defined (2n + 1) or live before an
    item (2n)."""
    order = linear_order(prog)  # @line L1
    live = live_before(prog)  # @line L2
    pos = {}
    for n, (_, item, is_term) in enumerate(order):  # @line L3
        for x in live[n]:
            if not is_mem(x):
                pos.setdefault(x, []).append(2 * n)
        if not is_term and not is_mem(item[1]):
            pos.setdefault(item[1], []).append(2 * n + 1)
    return {x: (min(p), max(p)) for x, p in pos.items()}


def _names(prog):
    out = set(prog.params)
    for b in prog.blocks.values():
        for ins in b.instrs:
            out.add(ins[1])
            out.update(toyir.uses(ins))
        out.update(toyir.term_uses(b.term))
    return out


def prepare(prog):
    """A copy of prog whose arguments arrive in memory slots. A new entry
    block loads each parameter that is live on entry, then jumps to the old
    entry."""
    _check(prog)
    if any(is_mem(a) for a in _names(prog)):
        raise ValueError("names that start with %r are reserved" % MEM)
    live_in, _ = liveness(prog)
    label = "start"
    while label in prog.blocks:
        label += "_"
    pro = [("copy", p, MEM + p) for p in prog.params if p in live_in[prog.entry]]
    blocks = {label: toyir.Block(pro, ("jump", prog.entry))}
    for lab, b in prog.blocks.items():
        blocks[lab] = toyir.Block(list(b.instrs), b.term)
    return toyir.Program([MEM + p for p in prog.params], blocks)


def rewrite(prog, reg, spilled):
    """Replace each name by its location. A spilled name x lives in mem.x:
    each use loads it into a scratch register first, and each definition
    computes into s0 and then stores s0 into mem.x."""

    def loc(a):
        if not isinstance(a, str) or is_mem(a):
            return a
        if a in spilled:
            return MEM + a
        return "r%d" % reg[a]

    blocks = {}
    for label, b in prog.blocks.items():
        out = []
        for ins in b.instrs:
            x = loc(ins[1])
            if ins[0] == "const":
                out.append(("const", x, ins[2]))
                continue
            srcs = [ins[2]] if ins[0] == "copy" else [ins[3], ins[4]]
            locs = [loc(a) for a in srcs]
            if ins[0] == "copy":
                a = locs[0]
                if a == x:
                    continue
                if is_mem(a) and is_mem(x):
                    out += [("copy", "s0", a), ("copy", x, "s0")]
                else:
                    out.append(("copy", x, a))
                continue
            loaded = {}
            for a in locs:
                if is_mem(a) and a not in loaded:
                    loaded[a] = SCRATCH[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))
        term = b.term
        if term[0] in ("br", "ret") and is_mem(loc(term[1])):
            out.append(("copy", "s0", loc(term[1])))
            term = (term[0], "s0") + term[2:]
        elif term[0] in ("br", "ret"):
            term = (term[0], loc(term[1])) + term[2:]
        blocks[label] = toyir.Block(out, term)
    return toyir.Program(list(prog.params), blocks)


def allocate(prog, k):
    work = prepare(prog)
    iv = intervals(work)
    reg, spilled = linear_scan(iv, k)
    return rewrite(work, reg, spilled), reg, spilled  # @line L16
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_linear_scan_register_allocation.py 203 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-scan-register-allocation/. The authors are listed in prov/5E24WB.jsonl.

import itertools
import random

import toyir
from linear_scan_register_allocation import (
    allocate,
    intervals,
    is_mem,
    linear_order,
    linear_scan,
    max_overlap,
    prepare,
)

DIAMOND = """# params: p
entry:
  a = p + 1
  br p B1 B2
B1:
  b = p * 2
  c = b + p
  ret c
B2:
  d = a - p
  ret d
"""


def brute_live(prog):
    """Liveness by search on the graph of single items: x is live before
    item n when some path from n reaches a use of x and no item before that
    use on the path defines x. This does not use the block fixed point."""
    order = linear_order(prog)
    first = {}
    for n, (label, _, _) in enumerate(order):
        first.setdefault(label, n)
    nxt = []
    for n, (label, item, is_term) in enumerate(order):
        nxt.append([first[s] for s in toyir.succs(prog, label)] if is_term else [n + 1])
    prv = [[] for _ in order]
    for n, ss in enumerate(nxt):
        for s in ss:
            prv[s].append(n)
    names = set()
    used = [set() for _ in order]
    defined = [None] * len(order)
    for n, (_, item, is_term) in enumerate(order):
        used[n] = set(toyir.term_uses(item) if is_term else toyir.uses(item))
        if not is_term:
            defined[n] = item[1]
        names |= used[n]
    live = [set() for _ in order]
    for x in names:
        work = [n for n in range(len(order)) if x in used[n]]
        seen = set(work)
        while work:
            v = work.pop()
            for p in prv[v]:
                if p not in seen and defined[p] != x:
                    seen.add(p)
                    work.append(p)
        for n in seen:
            live[n].add(x)
    return order, nxt, live


def check_registers(prog, k):
    """No two values that are live at the same time share a register, by the
    independent liveness above. Returns the number of spilled names."""
    work = prepare(prog)
    out, reg, spilled = allocate(prog, k)
    assert set(reg) | spilled == set(intervals(work))
    assert not (set(reg) & spilled)
    assert all(0 <= r < k for r in reg.values())
    order, nxt, live = brute_live(work)
    for n in range(len(order)):
        held = [reg[x] for x in live[n] if x in reg]
        assert len(held) == len(set(held)), (n, live[n])
        _, item, is_term = order[n]
        y = None if is_term else item[1]
        if y in reg:
            after = set().union(*(live[s] for s in nxt[n]))
            for x in after:
                if x != y and x in reg:
                    assert reg[x] != reg[y], (n, x, y)
    allowed = {"r%d" % i for i in range(k)} | {"s0", "s1"}
    for b in out.blocks.values():
        for ins in b.instrs:
            for a in [ins[1]] + toyir.uses(ins):
                assert a in allowed or is_mem(a), a
    return len(spilled)


def test_random_programs_keep_their_outputs():
    rng = random.Random(5)
    spills = 0
    for trial in range(250):
        prog = toyir.random_program(rng, rng.randint(2, 7), rng.randint(1, 7), acyclic=trial % 2 == 0)
        for k in (1, 2, 3, 5):
            spills += check_registers(prog, k)
            out, _, _ = allocate(prog, k)
            for _ in range(4):
                args = [rng.randint(-6, 6), rng.randint(-6, 6)]
                assert toyir.run(out, args, fuel=100000) == toyir.run(prog, args, fuel=100000)
    assert spills > 0


def test_registers_used_is_max_overlap():
    rng = random.Random(11)
    seen_no_spill = seen_spill = 0
    for trial in range(200):
        prog = toyir.random_program(rng, rng.randint(2, 7), rng.randint(1, 6), acyclic=trial % 3 != 0)
        iv = intervals(prepare(prog))
        m = max_overlap(iv)
        for k in range(1, 7):
            reg, spilled = linear_scan(iv, k)
            if m <= k:
                assert not spilled
                assert len(set(reg.values())) == m
                seen_no_spill += 1
            else:
                assert spilled
                seen_spill += 1
    assert seen_no_spill and seen_spill


def overlap_of(iv, keep):
    return max_overlap({x: iv[x] for x in keep}) if keep else 0


def test_spill_count_is_minimum_on_intervals():
    rng = random.Random(3)
    for trial in range(400):
        n = rng.randint(1, 8)
        iv = {}
        for i in range(n):
            s = rng.randint(0, 12)
            iv["v%d" % i] = (s, s + rng.randint(0, 8))
        for k in range(0, 4):
            reg, spilled = linear_scan(iv, k)
            keep = set(reg)
            assert overlap_of(iv, keep) <= k
            for a, b in itertools.combinations(sorted(keep), 2):
                if iv[a][0] <= iv[b][1] and iv[b][0] <= iv[a][1]:
                    assert reg[a] != reg[b]
            best = min(
                n - len(sub)
                for r in range(n + 1)
                for sub in itertools.combinations(sorted(iv), r)
                if overlap_of(iv, sub) <= k
            )
            assert len(spilled) == best, (iv, k, spilled, best)


def two_colorable(prog):
    """The interference graph of prog by the independent liveness, and an
    exhaustive check that two colors suffice."""
    order, nxt, live = brute_live(prog)
    names = sorted(set().union(*live) | {item[1] for _, item, t in order if not t})
    adj = {x: set() for x in names}
    for n, (_, item, is_term) in enumerate(order):
        if is_term:
            continue
        y = item[1]
        for x in set().union(*(live[s] for s in nxt[n])):
            if x != y:
                adj[x].add(y)
                adj[y].add(x)
    for colors in itertools.product(range(2), repeat=len(names)):
        c = dict(zip(names, colors))
        if all(c[a] != c[b] for a in adj for b in adj[a]):
            return adj, True
    return adj, False


def test_diamond_spills_although_two_colors_suffice():
    prog = toyir.parse(DIAMOND)
    iv = intervals(prog)
    assert iv == {"p": (0, 10), "a": (1, 10), "b": (5, 6), "c": (7, 8), "d": (11, 12)}
    assert max_overlap(iv) == 3
    reg, spilled = linear_scan(iv, 2)
    assert spilled == {"a"}
    adj, ok = two_colorable(prog)
    assert ok
    assert adj["a"] == {"p"} and adj["b"] == {"p"}
    out, _, spilled = allocate(prog, 2)
    assert spilled == {"a"}
    for p in range(-5, 6):
        assert toyir.run(out, [p]) == toyir.run(prog, [p])


def test_block_order_changes_the_result():
    # The same program with B2 placed before B1: now a ends before b starts.
    text = DIAMOND.replace("B1:\n  b = p * 2\n  c = b + p\n  ret c\n", "")
    text += "B1:\n  b = p * 2\n  c = b + p\n  ret c\n"
    prog = toyir.parse(text)
    iv = intervals(prog)
    assert max_overlap(iv) == 2
    reg, spilled = linear_scan(iv, 2)
    assert not spilled

History

Poletto, Engler and Kaashoek (1997) used linear scan as the fast allocator of tcc, a dynamic code generator for the Tick C language. Poletto and Sarkar (1999) described the algorithm in full, gave the furthest end spill rule, and showed that it ran much faster than graph coloring and gave code that was almost as fast. Traub, Holloway and Smith (1998) had in the meantime added lifetime holes and moves between a register and memory in their second-chance binpacking allocator. Wimmer and Mössenböck (2005) brought interval splitting into the Java HotSpot client compiler, and Wimmer and Franz (2010) moved linear scan onto SSA form.

References

  1. Massimiliano Poletto and Vivek Sarkar, Linear scan register allocation, ACM Transactions on Programming Languages and Systems 21(5), 1999, 895-913, the live intervals in a linear order, the scan with the routines EXPIRE-OLD-INTERVALS and SPILL-AT-INTERVAL, the rule that spills the interval that ends furthest away, and the comparison with graph coloring on compile time and code quality
  2. Massimiliano Poletto, Dawson R. Engler and M. Frans Kaashoek, tcc, a system for fast, flexible, and high-level dynamic code generation, PLDI 1997, 109-121, the fast register allocator of the tcc dynamic compiler, the first use of linear scan
  3. Omri Traub, Glenn Holloway and Michael D. Smith, Quality and speed in linear-scan register allocation, PLDI 1998, 142-151, second-chance binpacking, lifetime holes, the split of a lifetime at a spill, and the resolution moves on the edges of the control flow graph
  4. Christian Wimmer and Hanspeter Mössenböck, Optimized interval splitting in a linear scan register allocator, VEE 2005, 132-141, lifetime intervals with holes, use positions, the split of an interval at an optimal position, fixed intervals for machine registers, and the use in the Java HotSpot client compiler

Where this leads

About this page

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

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