16. Register Allocation

Mapping variables to finite registers

A bytecode VM uses a stack to hold intermediate values. That's clean and simple, but real CPUs don't work that way — they have a small, fixed number of registers, and arithmetic only happens between registers. When a compiler targets native code, it has to decide which variable goes in which register. That decision is called register allocation, and it's one of the hardest problems in compilation.

Why registers matter

Stack machines push and pop values through memory on every operation. Register machines keep hot values in registers — tiny storage locations built into the CPU that are orders of magnitude faster than RAM.

A modern x86-64 chip has 16 general-purpose registers. ARM64 has 31. Your program might have hundreds of live variables. Something has to give.

// Stack machine: every op touches memory
PUSH a
PUSH b
ADD        // pop a,b from memory, push result to memory

// Register machine: values stay in registers
ADD r0, r1, r2   // r2 = r0 + r1, no memory access

The compiler's job is to map an unlimited number of "virtual" registers (temporaries) onto this finite set of physical registers — and when it runs out, decide which values to spill to the stack.

Liveness analysis

Before you can assign registers, you need to know when each variable is alive. A variable is "live" from the point it's defined (assigned a value) to the point it's last used. Two variables that are never live at the same time can safely share a register.

Consider this code:

a = 1        // a is born
b = 2        // b is born
c = a + b    // a and b are used, then c is born
d = c * 2    // c is used, then d is born
return d     // d is used, then d dies

The liveness intervals are:

a: [1, 3]    // defined at line 1, last used at line 3
b: [2, 3]    // defined at line 2, last used at line 3
c: [3, 4]    // defined at line 3, last used at line 4
d: [4, 5]    // defined at line 4, last used at line 5

At line 3, both a and b are live (we need them for the addition), so they must be in different registers. But a and d are never live at the same time, so they can share a register.

Computing liveness

For straight-line code, liveness is simple — scan backward, marking each variable as live from its last use to its definition. For code with branches and loops, you need dataflow analysis: information flows backward from uses to definitions, merging at control-flow join points.

function computeLiveness(instructions) {
  const intervals = new Map();  // variable → { start, end }

  for (let i = instructions.length - 1; i >= 0; i--) {
    const instr = instructions[i];

    // Each variable used here is live at this point
    for (const v of instr.uses) {
      if (!intervals.has(v)) {
        intervals.set(v, { start: i, end: i });
      }
      // Extend the start backward
      intervals.get(v).start = i;
    }

    // Each variable defined here starts its life
    for (const v of instr.defs) {
      if (!intervals.has(v)) {
        intervals.set(v, { start: i, end: i });
      }
    }
  }
  return intervals;
}

The result is a set of intervals — one per variable — that tells the allocator exactly when each value needs to be in a register.

Linear scan allocation

The simplest practical algorithm is linear scan, introduced by Poletto and Sarkar in 1999 and used in production by V8 and early versions of the Go compiler.

The idea: sort all intervals by start point, then walk through them in order. Maintain a list of "active" intervals — variables currently occupying registers. When a new interval starts, try to give it a free register. If none are free, spill the interval that ends latest (it won't be needed for the longest time).

function linearScan(intervals, numRegisters) {
  // Sort by start point
  intervals.sort((a, b) => a.start - b.start);

  const active = [];           // currently assigned intervals
  const freeRegs = [];         // available register numbers
  for (let i = numRegisters - 1; i >= 0; i--) freeRegs.push(i);

  const assignment = new Map(); // variable → register or 'spilled'

  for (const interval of intervals) {
    // Expire old intervals that ended before this one starts
    for (let i = active.length - 1; i >= 0; i--) {
      if (active[i].end < interval.start) {
        freeRegs.push(assignment.get(active[i].name));
        active.splice(i, 1);
      }
    }

    if (freeRegs.length > 0) {
      // Assign a free register
      assignment.set(interval.name, freeRegs.pop());
      active.push(interval);
    } else {
      // Spill: pick the active interval that ends latest
      active.sort((a, b) => a.end - b.end);
      const victim = active[active.length - 1];
      if (victim.end > interval.end) {
        // Spill the victim, give its register to the new interval
        assignment.set(interval.name, assignment.get(victim.name));
        assignment.set(victim.name, 'spilled');
        active.pop();
        active.push(interval);
      } else {
        // Spill the new interval itself
        assignment.set(interval.name, 'spilled');
      }
    }
  }
  return assignment;
}

Linear scan runs in O(nlog⁡n)O(n \log n) time (dominated by the sort) and produces decent allocations. It's not optimal, but it's fast — exactly what you want for a JIT compiler that has to allocate registers at runtime.

Worked example: 2 registers, 4 variables

Let's trace through our earlier example with only 2 registers (R0, R1):

Step Interval Active Free regs Action
1 a [1,3] — R0, R1 Assign a → R0
2 b [2,3] a R1 Assign b → R1
3 c [3,4] a, b — a and b still active. Spill b (ends at 3, same as a — pick either). Assign c → R1
4 d [4,5] c R0 expired Assign d → R0

Result: a → R0, b → spilled, c → R1, d → R0. We only need one spill.

When a variable is spilled, the compiler inserts a store instruction after the definition and a load before each use. Those memory accesses are the cost of running out of registers.

Graph coloring

The more principled approach is graph coloring. Build an interference graph where each variable is a node and there's an edge between two variables if their liveness intervals overlap (they can't share a register). Then color the graph with KK colors, where KK is the number of available registers.

function buildInterferenceGraph(intervals) {
  const edges = new Set();
  const names = intervals.map(iv => iv.name);

  for (let i = 0; i < intervals.length; i++) {
    for (let j = i + 1; j < intervals.length; j++) {
      const a = intervals[i], b = intervals[j];
      // Do the intervals overlap?
      if (a.start <= b.end && b.start <= a.end) {
        edges.add(`${a.name}-${b.name}`);
      }
    }
  }
  return { nodes: names, edges };
}

For our example, the interference graph has edges between:

  • a — b (both live at line 2-3)
  • a — c (both live at line 3)
  • b — c (both live at line 3)

Variables c and d don't interfere (c dies at 4, d starts at 4 — depending on exact semantics they may or may not overlap). Variables a and d don't interfere either.

Graph coloring with KK colors is NP-complete in general, but Chaitin's algorithm uses a clever heuristic. Repeatedly remove nodes with fewer than KK neighbors (they can always be colored). If you get stuck, spill a node, remove it, and continue. Then assign colors in reverse removal order.

function chaitinColor(graph, K) {
  const stack = [];
  const remaining = new Set(graph.nodes);
  const neighbors = buildAdjacencyList(graph);

  // Simplify: remove nodes with degree < K
  let changed = true;
  while (changed) {
    changed = false;
    for (const node of remaining) {
      const deg = [...neighbors.get(node)].filter(n => remaining.has(n)).length;
      if (deg < K) {
        stack.push({ node, spilled: false });
        remaining.delete(node);
        changed = true;
      }
    }
    // If stuck, spill the highest-degree node
    if (remaining.size > 0 && !changed) {
      let worst = null, worstDeg = -1;
      for (const node of remaining) {
        const deg = [...neighbors.get(node)].filter(n => remaining.has(n)).length;
        if (deg > worstDeg) { worst = node; worstDeg = deg; }
      }
      stack.push({ node: worst, spilled: true });
      remaining.delete(worst);
      changed = true;
    }
  }

  // Assign colors in reverse order
  const colors = new Map();
  while (stack.length > 0) {
    const { node, spilled } = stack.pop();
    if (spilled) { colors.set(node, 'spilled'); continue; }
    const usedColors = new Set(
      [...neighbors.get(node)].filter(n => colors.has(n)).map(n => colors.get(n))
    );
    for (let c = 0; c < K; c++) {
      if (!usedColors.has(c)) { colors.set(node, c); break; }
    }
  }
  return colors;
}

Linear scan vs. graph coloring

Linear scan Graph coloring
Speed O(nlog⁡n)O(n \log n) O(n2)O(n^2) or worse
Quality Good Optimal (for chordal graphs)
Use case JIT compilers Ahead-of-time compilers
Examples V8, Go GCC, early LLVM

The tradeoff is compile speed vs. code quality. A JIT compiler runs at runtime, so it can't afford to spend milliseconds on register allocation. An AOT compiler runs once and the user runs the binary millions of times, so optimal allocation pays off.

Real-world register allocation

LLVM uses a "greedy" allocator that's a hybrid — it processes intervals in priority order (like linear scan) but considers interference (like graph coloring). It also handles register classes (some values must go in specific registers, like floating-point values in XMM registers on x86).

V8 (the JavaScript engine in Chrome and Node.js) uses linear scan because JIT compilation speed is critical. It processes liveness intervals in a single pass and inserts spill code on the fly.

GCC historically used graph coloring (Chaitin-Briggs) but has moved to an "integrated register allocator" that combines coloring with coalescing (eliminating unnecessary moves between registers).

All production allocators also handle register constraints — some instructions require specific registers (e.g., x86 division uses rax and rdx), and the allocator has to respect those constraints while minimizing spills.

The big picture

Register allocation sits near the end of the compilation pipeline:

source → parse → AST → IR → optimize → register allocate → emit machine code

By this point, the compiler has already done its optimizations on the intermediate representation. Register allocation is the step that makes the code concrete — it maps the abstract "use variable x" into the physical "read register R3". Get it wrong and your program spills constantly. Get it right and the code flies.

Try It Yourself — Register Allocator

Enter a sequence of variable assignments and uses. The visualizer computes liveness intervals, builds an interference graph, and runs linear scan allocation with a configurable number of registers. Variables that don't fit are spilled to the stack.

Result