Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Register allocation and assignment

Practical explanation of register allocation and assignment, covering interference graphs, graph-coloring (Chaitin-style) and linear-scan methods, spill heuristics, worked traces, common mistakes and exam guidance.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Register allocation decides which program values live at run-time are kept in the CPU's limited fast storage (registers) versus slower memory. Good allocation increases program speed and reduces energy; poor allocation causes many slow memory accesses (spills). Engineers use these techniques in the compiler back end and in code-generator passes (after data-flow analysis and basic-block construction).

Key ideas

Define terms before using them.

  • Register: a small, fast storage cell inside the CPU. Typical names: r0, r1, ...; the hardware provides a fixed number K of these.
  • Virtual register (or temporary): an abstract variable produced by earlier compiler passes (for example, three-address code) that needs mapping to physical registers.
  • Register allocation: the compiler pass that chooses which virtual registers should live in physical registers at program points.
  • Register assignment (register coloring): the final mapping from a virtual register to a specific physical register number.
  • Live range: the program interval (set of positions) where a variable is live (its value may be read later before being overwritten). Build live ranges using liveness (data-flow) analysis.
  • Interference graph: an undirected graph G=(V,E) where each node v ∈ V is a virtual register and an edge (u,v) ∈ E means u and v have overlapping live ranges (they interfere) and therefore cannot share the same physical register. In three-address IR, a def at instruction i interferes with variables live-out of i, not with operands used at i; i.e., variables defined at i do not (by themselves) interfere with the inputs of that same instruction.
  • Spill: when a virtual register cannot be given a physical register for all its live range, the compiler stores it in memory (stack) for some parts—this is a spill, and it adds load/store instructions.
  • Coalescing: combining two nodes (usually connected by a move instruction) into one to eliminate the move; safe coalescing reduces copies but can increase interference.

Important statements and assumptions used in allocation algorithms:

  1. (Colourability reduction) If an interference graph has a node v with degree < K (where K is the number of physical registers), then removing v (and its incident edges) yields a graph G' such that any K-coloring of G' can be extended to a K-coloring of the original graph by giving v a color not used by its neighbors. This is the key simplification lemma used in Chaitin-style algorithms. Assumptions: simple undirected graph, K fixed, colors correspond to physical registers.

  2. (NP-completeness) The general problem of deciding whether an arbitrary graph can be colored with K colors (graph K-colorability) is NP-complete for K ≥ 3 (while 2-colorability is polynomial). Therefore exact optimal register assignment for arbitrary interference graphs (without restricting to chordal graphs etc.) is intractable in the worst case; compilers use heuristics.

  3. (Spill heuristic idea) Because spilling is expensive, compilers estimate a spill cost for each variable (based on frequency of use, loop nesting, and live-range length) and choose low-cost nodes to spill when necessary. A simple commonly-used heuristic is prioritize for spill those nodes with low benefit: priority(v) = estimated_uses_per_execution / degree(v).

Algorithms (high level, exact steps to write down in an exam): A. Chaitin-style graph-coloring allocator (simplified exact steps you should list and justify):

  1. Build live ranges and interference graph G.
  2. Simplify: repeatedly find a node v with degree < K, push v onto a stack, and remove v and incident edges from G.
  3. If no such node exists, pick a node to spill (using a heuristic), remove it (mark as potential spill) and continue; continue until G is empty.
  4. Assign colors: pop nodes from the stack in reverse order, for each node choose a color (a physical register) different from colors already assigned to its neighbors. If a popped node was marked for spill, try to re-color; if impossible, insert spill code and restart allocation on the new code.

Diagrams to draw for an exam: draw the interference graph as nodes labelled with virtual registers, draw edges for interference. Beside the graph, show a stack and record the removal order with degrees. After coloring, draw mapping v -> rX.

B. Linear-scan allocator (for JITs and single-pass allocation) — step-by-step idea:

  1. Compute live intervals [start, end) for each variable; sort intervals by start position.
  2. Maintain a set Active of intervals currently assigned to registers.
  3. For each interval in order: expire intervals in Active whose end ≤ new interval's start; if Active size < K, assign free register to new interval and insert into Active; else pick an interval to spill (longest remaining or lowest priority) and either spill it or spill the new one depending on heuristic.

Linear-scan is faster (linear in number of intervals) and simpler, but can produce less optimal allocation than graph coloring.

Trade-offs and practical points:

  • Coalescing and conservative coalescing (Briggs/George): merge nodes connected by a move only when it is safe. Briggs’ test: coalesce x and y if, after merging, the resulting node has fewer than K neighbors whose degree is ≥ K. George’s test (with precolored nodes): for every neighbor t of the non-precolored node, either t already interferes with the precolored node or deg(t) < K.
  • Spill code insertion changes live ranges; many allocators iterate: allocate → insert spills → recompute live ranges → reallocate.
  • Register classes (e.g., separate integer and floating-point registers) mean you must build interference graphs per class or use multi-color sets; treat K per class. Precolored/reserved physical registers (from instructions or calling conventions) are modeled as fixed-color nodes and can raise neighbor degrees; simplification and coloring must respect these constraints.

Formulas

K — number of physical registers available. K is unitless; it is a small integer (e.g., 8, 16) specific to the target CPU and applies to all algorithms here (graph-coloring or linear scan).

degree(v) — number of neighbours of node v in the interference graph. Unitless; applies when applying simplification lemma.

spill_priority(v) = estimated_uses(v) / degree(v) — a simple heuristic score: higher means more worth keeping in register. estimated_uses(v) is the (unitless) count or weighted count (by loop nesting frequency) of uses; degree(v) as above. Use when choosing spill candidates.

spill_cost(v) = exec_freq(blocks_using_v) * memory_access_cost * uses(v) — rough model to estimate runtime cost of spilling v. exec_freq(blocks_using_v) is an expected execution count or weight (unitless, e.g., per invocation or from a profile), memory_access_cost is time per memory access (time units per load/store), and uses(v) is the number of spill loads/stores introduced. Use when comparing possible spills.

For linear-scan: intervals are half-open [start, end) positions in program order (start and end are indices of instructions). These are unitless instruction indices used to compare ordering.

Worked examples

Example 1 — Graph-coloring allocation (K = 3 registers r0,r1,r2) Code (three-address) and live ranges (positions are instruction indices): 1: a = ... (a defined at 1) 2: b = ... (b defined at 2) 3: c = a + b (uses a,b; defines c at 3) 4: d = c + a (uses c,a; defines d at 4) 5: e = b + d (uses b,d; defines e at 5) 6: return e (uses e) Live ranges (conservative, by instruction index):

  • a: [1,4] (used at 3 and 4)
  • b: [2,5]
  • c: [3,4]
  • d: [4,5]
  • e: [5,6] Build interference edges using liveness (defs interfere with variables live-out of their instruction, not with same-instruction uses):
  • Edges: a-b (from def b at 2), a-c and b-c (from def c at 3), b-d (from def d at 4). No edges with e. Graph degrees: deg(a)=2, deg(b)=3, deg(c)=2, deg(d)=1, deg(e)=0. K=3. Simplify: remove e (deg 0), then d (1), then c (2), then a (2); finally remove b (3) after neighbors are gone. Stack pop order (top to bottom): b, a, c, d, e. Assign colors by popping:
  • pop b: neighbors colored none → assign r0.
  • pop a: neighbor b has r0 → assign r1.
  • pop c: neighbors a,b have r1,r0 → assign r2.
  • pop d: neighbor b has r0 → assign r1 (or r2).
  • pop e: no neighbors → assign any, say r0. Final answer: no spills are required; one valid assignment is a:r1, b:r0, c:r2, d:r1, e:r0.

Example 2 — Linear-scan allocation (K = 2 registers r0,r1) Intervals (instruction indices): I1: v1 [1,4) I2: v2 [2,6) I3: v3 [3,5) Sorted by start: v1(1-4), v2(2-6), v3(3-5) Active initially empty.

  • v1: Active size 0 < 2 → assign r0 to v1; Active={v1}
  • v2: expire none (v1 ends at 4 > 2). Active size 1 < 2 → assign r1 to v2; Active={v1,v2}
  • v3: expire none (v1 ends 4 > 3). Active size 2 == K, need to spill: compare end points: v2 end=6 (longest), v1 end=4, v3 end=5. Choose to spill v2 (longest remaining) — spill v2: remove v2 from Active and free r1; assign r1 to v3; Active={v1,v3}. At run-time, v2 will be spilled to memory and loaded where used. This shows linear-scan decision-making.

Common mistakes

  • Assuming simplification lemma is symmetric: removing node with degree ≥ K does not guarantee colorability; only degree < K gives the safe simplification.
  • Coalescing greedily: students often coalesce moves without checking the degree/alias condition and accidentally make the graph uncolorable.
  • For linear-scan, forgetting to expire intervals before considering new ones (off-by-one using start/end indices).

For your exam

Typical question types: definitions (define live range, interference graph, spill), short notes (compare linear-scan vs graph-coloring), derivations (prove the simplification lemma: removing node with degree < K preserves K-colorability extension), algorithm trace (given code or intervals, show interference graph and simulate Chaitin or linear-scan), and small programs (implement pseudo-code for simplification and coloring).

What a full-marks answer includes:

  • Clear definitions of all bolded terms used.
  • Correct construction of live ranges (mention liveness analysis) and interference graph.
  • Step-by-step run of the chosen algorithm, showing node degrees, stack operations, and final mapping or spill decisions. If graph-coloring, show remove/push order and pop/color order.
  • If asked, draw the interference graph and label nodes with degrees and chosen colors; show where spills are inserted and explain why they are necessary.
  • Mention complexity/trade-offs: graph-coloring is more global and higher-quality but slower and may require iteration; linear-scan is O(n log n) (due to sorting) or O(n) with bucketed intervals, and suited to JITs.

Quick check

  1. What is an interference graph?
  2. State the simplification lemma used in graph-coloring allocation.
  3. Give one advantage and one disadvantage of linear-scan allocation.

Answers: 1) A graph where nodes are virtual registers and an edge means two registers have overlapping live ranges and cannot share a physical register. 2) If a node v has degree < K, removing v yields a graph whose K-coloring can be extended to a K-coloring of the original graph by giving v a color not used by its neighbors. 3) Advantage: very fast, single pass (suitable for JIT); Disadvantage: can give worse-quality allocation (more spills) than global graph-coloring.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?