Skip to content

Register Allocation 01 overview

Mugundan edited this page Nov 27, 2026 · 1 revision

Register Allocation Overview

Relevant source files

The following files were used as context for generating this wiki page:

Register allocation is the step of the LLVM code generator that replaces every *virtual register* (an unlimited supply of names such as `%4`) with a real *physical register* of the target (such as `$w0`). When there are more values alive at once than the machine has registers, the allocator stores some of them in stack slots (*spilling*) and loads them back before use (*reloading*).

Purpose and Scope

This wiki explains register allocation in llvm/lib/CodeGen/, from the basic ideas to the internals of the Greedy allocator, using the AArch64 backend as the worked example. It is written for someone who knows C++ and has seen LLVM IR, but has not worked on a code generator before.

It covers:

  • the vocabulary: physical and virtual registers, register classes, sub-registers, register units, liveness;
  • the passes that prepare the code (PHI elimination, two-address lowering, coalescing);
  • the analyses the allocators share (SlotIndexes, LiveIntervals, LiveRegMatrix, VirtRegMap);
  • the four allocators LLVM ships: Fast, Basic, Greedy and PBQP;
  • spilling, live range splitting and rematerialisation;
  • the rewriting step and the post-allocation passes;
  • everything a custom backend must provide so that the allocator works for it: see Writing Register Allocation Support for a Custom Backend.

It does not cover GlobalISel register bank selection (RegBankSelect), which picks a register bank, not a register.

Why Register Allocation Is Needed

Instruction selection (SelectionDAG, GlobalISel or FastISel) produces MachineInstrs that use as many virtual registers as it likes. Each virtual register is written once (SSA form) and has a register class that says which physical registers it may live in. A real CPU has a small fixed set of registers, so something must decide:

  1. which physical register holds each value, and for how long;
  2. which values do not fit and must live in memory for part of their life;
  3. how to satisfy fixed constraints: arguments arrive in specific registers, calls destroy (clobber) some registers, and some instructions require their result in the same register as an operand.

A wrong answer is a miscompile (two live values in one register). A poor answer is slow code (extra loads, stores and copies). Register allocation is therefore both a correctness pass and one of the most important optimisations in the back end.

Where Register Allocation Fits

flowchart LR
  ISEL["Instruction selection<br/>SSA MIR, virtual registers, PHIs"] --> PRE["Pre-RA MIR passes<br/>CSE, LICM, peephole"]
  PRE --> PREP["Preparation<br/>PHIElimination, TwoAddress,<br/>RegisterCoalescer, MachineScheduler"]
  PREP --> RA["Register allocator<br/>Greedy (or Fast at -O0)"]
  RA --> RW["VirtRegRewriter<br/>vregs replaced by physregs"]
  RW --> POST["StackSlotColoring, MachineCopyPropagation,<br/>Prologue/Epilogue insertion"]
  POST --> MC["AsmPrinter and MC layer"]
Loading

Before allocation, MIR is in SSA form with virtual registers. After the rewriter, every register operand is physical, and the function has a set of stack slots (%stack.N) for spilled values. Prologue/epilogue insertion later turns those slots into concrete sp- or fp-relative offsets and saves any callee-saved registers the allocator used.

Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1483-1549

A First Example

Compile this function for AArch64 at -O2:

define i32 @f(i32 %a, i32 %b, i32 %c) {
  %m = mul i32 %a, %b
  %s = add i32 %m, %c
  ret i32 %s
}

Just before the allocator (llc -mtriple=aarch64 -O2 -stop-before=greedy) the body uses virtual registers:

bb.0 (%ir-block.0):
  liveins: $w0, $w1, $w2
  %1:gpr32 = COPY $w1
  %0:gpr32 = COPY $w0
  %2:gpr32 = COPY $w2
  %4:gpr32 = MADDWrrr %0, %1, %2
  $w0 = COPY %4
  RET_ReallyLR implicit $w0

After the rewriter (-stop-after=virtregrewriter) there are no virtual registers and no copies:

bb.0 (%ir-block.0):
  liveins: $w0, $w1, $w2
  renamable $w0 = MADDWrrr killed renamable $w0, killed renamable $w1, killed renamable $w2
  RET_ReallyLR implicit $w0

The allocator followed hints: %0 was copied from $w0, so it prefers $w0; %4 is copied into $w0, so it prefers $w0 too. Once every copy has the same register on both sides it is an identity copy, and the rewriter deletes it. The final assembly is one instruction, madd w0, w0, w1, w2.

The Four Allocators

Allocator -regalloc= Used by default Idea Page
Fast fast -O0 Walks each block once, bottom to top, assigning registers on demand; values that cross block boundaries go through stack slots Fast Register Allocator
Basic basic never Priority queue of whole live intervals; spills on conflict. A simple reference for the shared framework Basic Register Allocator
Greedy greedy -O1 and above Priority queue plus eviction, region/block/local splitting, then spilling Greedy Register Allocator
PBQP pbqp never (opt-in) Models allocation as a Partitioned Boolean Quadratic Problem and solves it PBQP Register Allocator

Each allocator registers itself under its -regalloc= name with a RegisterRegAlloc object. The default is chosen by TargetPassConfig::createTargetRegisterAllocator: Greedy when optimising, Fast otherwise.

Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1413-1418, llvm/lib/CodeGen/RegAllocGreedy.cpp:148, llvm/lib/CodeGen/RegAllocFast.cpp:61, llvm/lib/CodeGen/RegAllocBasic.cpp:38, llvm/lib/CodeGen/RegAllocPBQP.cpp:94

Component Map

Component Class File Role
Pipeline TargetPassConfig::addOptimizedRegAlloc, addFastRegAlloc TargetPassConfig.cpp Decides which passes run and in what order
Instruction numbering SlotIndexes SlotIndexes.cpp Gives every instruction a position so ranges can be compared
Liveness LiveIntervals, LiveInterval, LiveRange LiveIntervals.cpp, LiveInterval.cpp Where each register is alive
Coalescing RegisterCoalescer RegisterCoalescer.cpp Merges registers joined by copies
Interference LiveRegMatrix, LiveIntervalUnion LiveRegMatrix.cpp, LiveIntervalUnion.cpp What is already assigned to each physical register
Assignment record VirtRegMap VirtRegMap.cpp Virtual register to physical register or stack slot
Shared driver RegAllocBase RegAllocBase.cpp Priority-queue loop used by Basic and Greedy
Allocators RAGreedy, RABasic, RegAllocFast, RegAllocPBQP RegAlloc*.cpp The policy
Spiller InlineSpiller InlineSpiller.cpp Inserts spill and reload code, rematerialises
Splitter SplitAnalysis, SplitEditor SplitKit.cpp Cuts a live range into pieces
Rewriter VirtRegRewriter VirtRegMap.cpp Replaces virtual registers in instructions

What a Target Provides

The allocator itself is target-independent. A backend teaches it about the machine through:

Provided by What Page
<Target>RegisterInfo.td Registers, sub-registers, register classes, allocation order, callee-saved lists Register Definitions in TableGen
<Target>RegisterInfo.cpp Reserved registers, callee-saved registers, call-preserved masks, hints, frame index elimination TargetRegisterInfo Hooks
<Target>InstrInfo.cpp Copying, spilling and reloading a register, rematerialisation, folding TargetInstrInfo Hooks
<Target>TargetMachine.cpp Extra passes around allocation, choice of allocator Pass Pipeline Hooks

Reading Guide

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally