Skip to content

Graph-Coloring Register Allocator

This semester, I took a Compilers course where the problem sets involved incrementally implementing compiler features in OCaml. In this series, I’ll briefly summarize each piece. Taken together, I hope these posts provide a good foundation for understanding how compilers work.

The problem sets were fairly open-ended as long as the compiler produced correct results. My approaches won’t always match what a production compiler would do, but I’ve attempted to preserve the core ideas. Code is available in this repo.

Although the articles closely follow the problem sets, some also cover topics that weren’t directly tied to a specific problem set.


In ps7, we converted the input program into a CFG, then performed liveness analysis to build an interference graph. This graph captured which variables interfered with each other. In the mini project, we use this information to implement graph-coloring register allocation, assigning registers to reduce register conflicts and unnecessary memory spills.


Registers are fast, but there are only so many of them. When there are more live values than available registers, some have to be spilled to memory. Since accessing memory is much slower than accessing registers, we want to reduce unnecessary spills.

Register allocation is the problem of assigning each temp to one of k available registers. Given an interference graph, this becomes a graph coloring problem: each temp is a node, and two temps connected by an edge cannot be assigned the same register. Although graph coloring is a NP-complete problem, a compiler does not need to find the exact solution. Instead, it relies on best-effort polynomial-time heuristic, which usually works well but may fail to color the graph without spilling some values to memory.

The heuristic we use is to simplify the graph. If a node has degree less than k, then it is guaranteed to be colorable after the rest of the graph has been colored. This means we can temporarily remove that node, color the remaining graph, and then add the node back with some available register. We repeat this simplification step as much as possible. When no remaining node has degree less than k, we choose a node to spill.

Let’s take a look at an example. The graph below matches the code snippet.

{live-in: j, k}
g := *(j+12)
h := k - 1
f := g * h
e := *(j+8)
m := *(j+16)
b := *(f+0)
c := e + 8
d := c
k := m + 4
j := b
{live-out: d, j, k}

Let’s say k=4. First, we can remove node G since its degree is 3, and push it onto a stack of removed nodes. If we imagine the graph after removing G, we can also remove H, whose degree is now 1. If we continue removing nodes with degree less than k, we eventually reach a happy case where all nodes can be removed, so we do not have to spill any nodes. At the end, we pop nodes from the stack and assign each one a color.

Then, we can rewrite the code by replacing each temp with its assigned color. Here, t1 through t4 represent the four available colors.

t2 := *(t4+12)
t1 := t1 - 1
t2 := t2 * t1
t3 := *(t4+8)
t1 := *(t4+16)
t2 := *(t2+0)
t3 := t3 + 8
t3 := t3 // we can remove moves like this one.
t1 := t1 + 4
t4 := t2

Let’s walk through the example one more time, but this time with k=3. We can remove nodes H, C, and then G, but we are soon stuck in a state where we can no longer remove any nodes.

To continue, we have to choose one node and spill it to memory. The rule of thumb is to spill a high degree temp that is used infrequently. Removing a high degree temp makes it more likely that we can color the rest of the graph, and picking an infrequently used node will likely generate better code (e.g., spilling a register used inside a loop is probably not a good idea). Here, let’s pick M.

After spilling to the stack, we must also rewrite our code. Notice that M no longer interferes with B, C, and D.

Rewrite:
{live-in: j, k}
g := *(j+12)
h := k - 1
f := g * h
e := *(j+8)
m := *(j+16)
*(fp+<moff>) := m
b := *(f+0)
c := e + 8
d := c
m2 := *(fp+<moff>)
k := m2 + 4
j := b
{live-out: d, j, k}

This gives us a new interference graph, which we can continue simplifying and then coloring.


The mini project was the final assignment for this class. We had to optimize the Cish compiler from ps4, with performance measured by running the generated RISC-V code on a gem5 simulator.

To receive full marks, the optimized compiler had to bring the average execution time down to 65% of the baseline across nine benchmark programs.

The gem5 simulator was packaged as a Docker image and provided as part of the starter code. I did not look into the simulator configuration in detail, but the simulated machine had the following specs:

  • A simple in-order CPU running at 2 GHz
  • An instruction cache, but no data cache
  • 512 MB of DDR3 RAM

The problem set was open-ended and we were encouraged to explore different optimization techniques. However, we were told that a rudimentary register allocation algorithm should be enough to reach the target performance, so I focused on register allocation.


We first identify the registers available for allocation. Excluding registers reserved for specific purposes, the allocator can use 24 registers.

(*
Pre-colored (not-allocatable) registers
x0 : hardwired zero register
x1 : return address
x2 : stack pointer
x8 : frame pointer
x30/x31 : scratch registers reserved by cfg_compile.ml
*)
let allocatable_registers =
[ Riscv.R5; Riscv.R6; Riscv.R7; Riscv.R9; Riscv.R10;
Riscv.R11; Riscv.R12; Riscv.R13; Riscv.R14; Riscv.R15;
Riscv.R16; Riscv.R17; Riscv.R18; Riscv.R19; Riscv.R20;
Riscv.R21; Riscv.R22; Riscv.R23; Riscv.R24; Riscv.R25;
Riscv.R26; Riscv.R27; Riscv.R28; Riscv.R29 ]

The graph-coloring part closely follows the explanation above.

Pseudocode for Register Allocation
reg_alloc(blocks):
igraph = build_interfere_graph(blocks)
stack = simplify_graph(igraph)
result = try_allocation(igraph, stack)
if result = Allocated alloc:
return rewrite_cfg_with_alloc(alloc, blocks)
else if result = NeedSpill spills:
return reg_alloc(SP.spill(blocks, spills))

Given an interference graph (igraph), we first try to simplify it. The simplify_graph function builds a stack of temps in the order we will later try to color them. It repeatedly removes low-degree temps from the graph. If no such temp exists, it chooses a spill candidate and removes that instead. Note that at this stage, we are only marking potential spill candidates, not actually spilling them to memory (this requires rewriting the code). For now, we simply remove them from the graph and push them onto the stack. At the end of this process, we have a coloring order, but we still do not know whether every node can be assigned a valid register.

try_allocation is the phase where we actually try to color the nodes. try_allocation either returns a completed register assignment, or a list of temps that must be spilled before allocation can succeed. If some temps cannot be colored by the end, we spill them, rewrite the program, and recursively restart register allocation on the new interference graph.


The actual implementation is more complicated than the pseudocode version, but once I understood the algorithm, the code itself was relatively straightforward to write. I was surprised to see that even a rudimentary register allocator could noticeably improve performance. It made register allocation feel less like an abstract graph problem and more like a practical backend optimization. It also gave me a deeper appreciation for production compilers, which quietly save the world from the inefficient code we would otherwise make them generate.