LinScan
Report (PDF)

Compiler Design · Research paper implementation

Linear Scan Register Allocation, reproduced and improved

An implementation of Poletto & Sarkar's Linear Scan Register Allocation (ACM TOPLAS, 1999) inside a compiler written from scratch, plus the improvements the paper lists as future work. Every number on this page comes from the code in the repository, and the playground below runs that same code in your browser.

Paper's algorithm vs graph colouring
+11.8%
extra cycles; the paper says “within 12%”
LinScan+ (my version) vs graph colouring
−0.6%
as good as the slow, “gold standard” method
Speed vs graph colouring
458×
faster with 2,048 live variables
Random programs checked
7,200
0 wrong outputs; 33 unit tests pass

The problem

Which variables get the CPU's registers?

Registers are the fastest storage in a CPU, but there are only a handful of them. A program has many variables. The register allocator is the compiler phase that decides which variable lives in which register, and which ones have to be pushed out to memory.

1

Registers are few and fast

An x86-64 CPU has 16 general registers. Reading one costs about one cycle. Memory is much slower.

2

Spilling is expensive

A variable that doesn't get a register is spilled to memory. Every read then needs a load and every write a store. A good allocator spills rarely, and spills the variables used least.

3

When can two variables share?

When they are never live at the same time. A variable is live at a point if its current value will still be read later.

Two ways to solve it

The classic: Chaitin 1982

Graph colouring

Make every variable a node. Join two nodes if the variables are live at the same time. Colour the graph with K colours, one per register. Nodes that can't be coloured are spilled.

  • Very good code: the quality benchmark
  • The graph can have about n²/2 edges
  • Too slow for JIT compilers, which compile while the program runs
The paper: Poletto & Sarkar 1999

Linear scan

No graph. Give each variable a live interval, the stretch of code from its first to its last use. Then make one pass over the intervals, sorted by start:

  1. Expire the intervals that have ended; their registers become free.
  2. If a register is free, give it to the new interval.
  3. If none is free, spill the interval that ends furthest away, because it would block a register longest.
  • One pass: O(V log R). Used in JIT compilers such as Java HotSpot's client compiler and V8
  • Code is about 12% slower than graph colouring

Walkthrough

Watch the allocator work, step by step

The program below adds up 0² + 1² + … + 9² with only 3 registers. Each bar is one variable's live interval. Press Next to move the scan line and see each decision. Switch between the paper's algorithm and my improved one to see why they end up so different.

My contribution

Three improvements

Section 6.5 of the paper names two refinements the authors “have not yet implemented”: lifetime holes and move coalescing. I implemented both, plus a better spill rule. Each one was also measured on its own.

1 Lifetime holes

The paper treats a variable as busy from its first use to its last. But in s = s + t, the old s is dead between being read and being rewritten. I keep the exact live ranges. During a hole, the register can be lent to a short variable that fits inside it.

s  ██████████┄┄██████
t3           ██      ← fits in the hole

From Traub et al. (PLDI 1998) and Wimmer & Mössenböck (VEE 2005), whose allocator is in Java HotSpot.

Gap to graph colouring: 11.8% → 5.3%

2 Move coalescing

Compilers produce many copies such as mov s, t3. If t3 gets the same register as s, the copy becomes mov r1, r1 and is deleted. When allocating, I prefer the register of the copy partner (a hint).

add r1, r1, r0
mov r1, r1   ← deleted

This only works together with holes. Without them, t3 looks like it overlaps s, so they can't share. The paper predicted this, and my data confirms it.

Alone: no change. With holes: 5.3% → 2.4%

3 Smarter spilling

The paper spills whatever ends last, even a loop counter used thousands of times. I spill the interval with the lowest use density: weighted uses ÷ length, where a use inside a loop counts 10× per loop level.

density = Σ 10^(loop depth) / length
n: 11/25 = 0.44   ← spill this
s: 22/24 = 0.92
i: 41/21 = 1.95

In the stencil benchmark the paper's rule spills the loop index k (about 1,420 uses). LinScan+ keeps it and spills values used about 200 times.

All three (LinScan+): 2.4% → −0.6%

Results

Benchmarks

12 benchmark programs (sorting, sieve, matrix multiply, stencil, hashing, …), each with 3, 4, 5, 6 and 8 registers. The cost model is 1 cycle per instruction and 3 cycles per memory access. Every compiled program's output is checked against a reference interpreter.

Extra cycles compared to graph colouring

Geometric mean over 12 programs × 5 register counts. Lower is better; 0 = as good as graph colouring.

Show as table (all allocators)

Allocation time as the program grows

Paper's stress test (a): n variables all live at once. Log scales; lower is better.

Show as table

Per program

Cycles relative to graph colouring (geometric mean over K = 3…8). Below 0 means faster than graph colouring.

Show as table

Reproduces the paper

Linear scan as published comes out 11.8% slower than graph colouring; the paper reports “within 12%”. The simple usage-count baseline is 2.6× slower, matching the paper's finding that naive schemes are several times worse.

Why graph colouring is slow

With 2,048 variables live at once, its graph has 2.1 million edges. It took 3.8 s, while the paper's linear scan took 8 ms and LinScan+ 64 ms. LinScan+ does extra work for holes but stays about 60× faster.

Correctness

An independent checker verifies that no two variables that are live at the same time share a register. On 7,200 runs of randomly generated programs, the compiled output matched the interpreter every time.

Playground

Try it on any program

This runs the actual Python compiler from the repository in your browser (via Pyodide), with no server involved. Pick a benchmark or write your own MiniC code, choose the number of registers, and compare every allocator.

3

MiniC: var x = 1; array a[10]; if/else, while, print(e);, operators + - * / % < <= == != && || !.

Press Compile & allocate. The first run loads Python (about 10 MB, a few seconds).

How it's built

A complete compiler, written from scratch

About 1,800 lines of Python with no dependencies. Each stage is a textbook compiler phase.

Lexer & parserlexer.py · parser.py

Recursive descent for MiniC. Builds the syntax tree, checks scopes, renames shadowed variables.

Three-address codeirgen.py

Dragon Book syntax-directed translation: x = a+b → t1 = a+b; x = t1. Short-circuit &&/||.

Control-flow graphir.py

Basic blocks and edges; unreachable blocks removed.

Livenessliveness.py

Iterative data flow: in = use ∪ (out − def). Builds live intervals with holes.

Register allocationalloc.py

Paper's linear scan, LinScan+, graph colouring, usage counts, and the separate ablation variants.

Spill codecodegen.py

Maps variables to registers, inserts loads and stores, deletes mov r, r.

Simulator & checksmachine.py · verify.py

Runs the result and counts cycles. An independent checker validates every allocation.

Run it locally

git clone https://github.com/Absterrg0/linscan-regalloc
cd linscan-regalloc
python main.py intervals examples/sumsq.mc
python main.py compare   programs/stencil.mc -k 4
python benchmark.py        # every experiment → results/
python -m pytest -q        # 33 tests

Limitations & future work

  • Simulated machine. Cycles come from a simple cost model, not real hardware.
  • Small programs. The benchmarks are 12 kernels, not SPEC.
  • No interval splitting. A variable is in a register or in memory for its whole life. HotSpot and LLVM's greedy allocator split intervals; that's the natural next step.
  • No SSA form. SSA-based allocation gives cleaner intervals.
  • Python timings. Absolute times are from Python; only the ratios matter.

References

  1. M. Poletto and V. Sarkar. Linear Scan Register Allocation. ACM TOPLAS 21(5):895–913, 1999. PDF
  2. O. Traub, G. Holloway and M. D. Smith. Quality and Speed in Linear-scan Register Allocation. PLDI 1998. DOI
  3. C. Wimmer and H. Mössenböck. Optimized Interval Splitting in a Linear Scan Register Allocator. VEE 2005. link
  4. T. Kotzmann et al. Design of the Java HotSpot Client Compiler for Java 6. ACM TACO 5(1), 2008. link
  5. G. J. Chaitin. Register Allocation and Spilling via Graph Coloring. SIGPLAN Symp. on Compiler Construction, 1982.
  6. P. Briggs, K. D. Cooper and L. Torczon. Improvements to Graph Coloring Register Allocation. ACM TOPLAS 16(3), 1994.
  7. J. Olesen. Greedy Register Allocation in LLVM 3.0. LLVM Project Blog, 2011. link
  8. A. V. Aho, M. S. Lam, R. Sethi and J. D. Ullman. Compilers: Principles, Techniques, and Tools, 2nd ed., 2006.