Skip to content

Register Allocation 02 registers basics

Mugundan edited this page Nov 27, 2026 · 1 revision

Registers, Virtual Registers and Register Classes

Relevant source files

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

Before any algorithm makes sense you need the vocabulary. This page explains the two kinds of register in MIR, what a register class is, how sub-registers and register units describe overlap, and which registers the allocator is not allowed to touch.

Purpose and Scope

Everything here is used by every allocator. AArch64 definitions are quoted as concrete examples; how to write your own is on Register Definitions in TableGen.

Physical and Virtual Registers

LLVM represents both kinds with the same type, Register (a 32-bit number):

Kind MIR spelling Number range Meaning
Physical $w0, $x19, $sp Small numbers from TableGen (AArch64::W0, ...) A real hardware register
Virtual %0, %15 Top bit set (VirtualRegFlag = 1u << 31) An unlimited name created by instruction selection
Stack slot %stack.3 (in operands: frame index) Between StackSlotZero and VirtualRegFlag Used inside some analyses to stand for a frame index
static constexpr unsigned VirtualRegFlag = 1u << 31;
...
static Register index2VirtReg(unsigned Index) {
  ...
  return Index | Register::VirtualRegFlag;
}
constexpr bool isVirtual() const { return isVirtualRegister(Reg); }
constexpr bool isPhysical() const { return isPhysicalRegister(Reg); }

So %5 is just 5 | 0x80000000. Register::index2VirtReg(i) and Register::virtReg2Index() convert between the dense index (used to index arrays such as VirtRegMap) and the register. You have already seen this loop in RegAllocBase::seedLiveRegs:

for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  Register Reg = Register::index2VirtReg(i);
  ...
}

Sources: llvm/include/llvm/CodeGen/Register.h:43-94, llvm/lib/CodeGen/RegAllocBase.cpp:75-84

Physical registers already present before allocation

MIR before allocation is not purely virtual. Physical registers appear wherever the ABI or an instruction fixes them:

liveins: $w0, $w1, $w2
%1:gpr32 = COPY $w1          ; argument arrives in $w1
...
$w0 = COPY %4                ; return value must be in $w0
RET_ReallyLR implicit $w0
BL @g, csr_aarch64_aapcs, implicit-def dead $lr, ..., implicit-def $w0

The allocator must treat these as fixed: between $w0 = COPY %4 and the RET, nothing else may be put in $w0. Liveness of physical registers is tracked separately (see "Register Units" below and Liveness).

Register Classes

A register class is a set of physical registers that can all hold the same kind of value and are interchangeable as operands of some instructions. Every virtual register has exactly one class, written after the colon: %4:gpr32.

The class answers the allocator's first question: which physical registers may this value go in? AArch64 defines, among many others:

def GPR32common : RegisterClass<"AArch64", [i32], 32, (sequence "W%u", 0, 30)> {
  let AltOrders = [(rotl GPR32common, 8)];
  let AltOrderSelect = [{ return 1; }];
}
def GPR32   : RegisterClass<"AArch64", [i32], 32, (add GPR32common, WZR)> { ... }
def GPR32sp : RegisterClass<"AArch64", [i32], 32, (add GPR32common, WSP)> { ... }
def GPR32all : RegisterClass<"AArch64", [i32], 32, (add GPR32common, WZR, WSP)>;
Class Members Used where
GPR32common w0–w30 Intersection of the two below
GPR32 w0–w30, wzr Most ALU operands (encoding 31 means zero register)
GPR32sp w0–w30, wsp Operands where encoding 31 means stack pointer (e.g. add immediate)
GPR32all all of the above Common super-class, used for copies
GPR64common x0–x28, fp, lr 64-bit equivalent
tcGPR64 GPR64common minus x19–x28, fp, lr Indirect tail call target: must not be callee-saved

The reason for so many classes is encoding: register number 31 means wzr in some instructions and wsp in others. Each instruction operand names the class it accepts, and when one virtual register is used by several instructions its class must be in the intersection. That is why the coalescer sometimes changes a register to a sub-class such as gpr64common, as you can see in the loop example (%15:gpr64common).

Classes form a lattice

Classes are related by sub-class and super-class. GPR32common is a sub-class of both GPR32 and GPR32sp. TableGen computes these relations and generates helpers such as getCommonSubClass(A, B), which the coalescer and MachineRegisterInfo::constrainRegClass use to find a class that satisfies two constraints at once. If none exists, the two registers cannot be merged.

Allocation order

The class's member list is also the default allocation order: the order in which the allocator tries free registers. A class can supply alternatives with AltOrders and choose one with AltOrderSelect. All AArch64 GPR classes rotate their list by 8 and always select that rotation (return 1), so the order is w8, w9, ..., w30, w0, ..., w7. Argument registers w0–w7 are tried last, which leaves them free for calls. This is why allocated AArch64 code is full of w8, w9, w10:

renamable $x9 = COPY $xzr
renamable $w8 = COPY $wzr
...
renamable $w10 = LDRWroX renamable $x0, renamable $x9, 0, 1

The allocator does not use the raw order directly; RegisterClassInfo removes reserved registers and moves callee-saved registers to the end (they cost a save/restore the first time they are used). See Allocation Framework.

Sources: llvm/lib/Target/AArch64/AArch64RegisterInfo.td:189-261, llvm/include/llvm/Target/Target.td:292-376

Sub-registers

Many registers overlap. On AArch64, w0 is the low 32 bits of x0. TableGen describes this with sub-register indices:

def sub_32   : SubRegIndex<32>;
...
def W0    : AArch64Reg<0,   "w0" >, DwarfRegNum<[0]>;
def X0    : AArch64Reg<0,   "x0",  [W0,  W0_HI]>, DwarfRegAlias<W0>;

X0 lists its sub-registers W0 and W0_HI (the top half, which has no name in assembly but must exist so the halves can be tracked separately). In MIR, %15.sub_32 means "the low 32 bits of the 64-bit virtual register %15":

dead $wzr = SUBSWrr %15.sub_32, %5, implicit-def $nzcv

After allocation %15 became $x9, so %15.sub_32 was rewritten to $w9:

dead $wzr = SUBSWrr renamable $w9, renamable $w1, implicit-def $nzcv

Three MIR instructions exist only to manipulate sub-registers; you will see them in coalescer output:

Instruction Meaning
%d = INSERT_SUBREG %src, %val, sub_32 %d is %src with the sub_32 part replaced by %val
%d = SUBREG_TO_REG 0, %val, sub_32 %d's sub_32 part is %val, and the rest is known to be zero (AArch64 32-bit writes zero the top half)
%d = REG_SEQUENCE %a, sub0, %b, sub1 Build a register tuple from parts

Lane masks. Each sub-register index has a LaneBitmask, a bit set describing which parts of the register it covers. When sub-register liveness is enabled for a target (enableSubRegLiveness()), liveness is tracked per lane, so a write to %x.sub_32 does not kill the other half. AArch64 defines the _hi indices precisely so that overlapping registers get distinct lane masks:

// The _hi SubRegIndexes describe the high bits of a register which are not
// separately addressable. They need to be described so that partially
// overlapping registers end up with a different lane mask. This is required
// to enable subreg liveness tracking.

Sources: llvm/lib/Target/AArch64/AArch64RegisterInfo.td:13-60, llvm/lib/Target/AArch64/AArch64RegisterInfo.td:101-168, llvm/include/llvm/Target/Target.td:108

Register Units

To decide whether two physical registers clash, the allocator must know if they share any bits. Asking "do x0 and w0 overlap?" for every pair would be slow, so TableGen splits each register into register units: the smallest pieces that are never shared in part. Two physical registers interfere exactly when they share a unit.

Register Units (illustrative)
w0 U0
W0_HI U1
x0 U0, U1

All physical liveness in LLVM's allocators is stored per unit, not per register. LiveIntervals keeps one live range per register unit (getRegUnit(Unit)), and LiveRegMatrix keeps one LiveIntervalUnion per unit. Assigning %v to x0 adds %v's interval to the unions for U0 and U1; checking whether w0 is free looks only at U0. This makes aliasing correct automatically.

The iterator MCRegUnitIterator (or TRI->regunits(Reg)) walks the units of a register, and MCRegAliasIterator walks every register that overlaps one (used, for example, in RegAllocBase::cleanupFailedVReg).

Reserved Registers

Some registers must never be handed out: the stack pointer, the zero register, the frame pointer when the function needs one, platform registers. The target lists them in TargetRegisterInfo::getReservedRegs, which returns a BitVector. RegAllocBase::init freezes this set at the start of allocation:

MRI->freezeReservedRegs();
RegClassInfo.runOnMachineFunction(vrm.getMachineFunction());

Reserved registers are removed from every allocation order, and their liveness is not tracked precisely (a reserved register is treated as always live). On AArch64, wzr/xzr are additionally marked isConstant = true in TableGen: they always read as zero, so writes to them are harmless and reads do not need a definition.

Classes that contain only unusable registers are marked isAllocatable = 0:

// SP/WSP are always reserved.
let isAllocatable = 0 in {
  def GPR32sponly : RegisterClass<"AArch64", [i32], 32, (add WSP)>;
  def GPR64sponly : RegisterClass<"AArch64", [i64], 64, (add SP)>;
}

Sources: llvm/lib/CodeGen/RegAllocBase.cpp:60-70, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:404, llvm/lib/Target/AArch64/AArch64RegisterInfo.td:225-229

Caller-saved and Callee-saved Registers

The calling convention splits the allocatable registers in two:

Kind Who preserves it across a call AArch64 (AAPCS64)
Caller-saved (volatile, clobbered) Nobody: a call may destroy it x0–x18, v0–v7, v16–v31
Callee-saved (non-volatile) The called function saves and restores it if it uses it x19–x28, fp, lr, d8–d15
def CSR_AArch64_AAPCS : CalleeSavedRegs<(add X19, X20, X21, X22, X23, X24,
                                           X25, X26, X27, X28, LR, FP,
                                           D8,  D9,  D10, D11,
                                           D12, D13, D14, D15)>;

TableGen turns this into two things the allocator uses:

  • CSR_AArch64_AAPCS_SaveList: returned by getCalleeSavedRegs; tells prologue/epilogue insertion what to save and tells the allocator which registers cost a save the first time.
  • CSR_AArch64_AAPCS_RegMask: a bit mask returned by getCallPreservedMask, attached to every call as an operand (csr_aarch64_aapcs in BL @g, csr_aarch64_aapcs, ...). A regmask operand says "this instruction clobbers every register not in the mask".

This is what makes the call example work. %1 holds %b across bl g. Every caller-saved register is clobbered by the regmask, so the only registers free for the whole of %1's life are callee-saved ones. The allocator picked w19, and prologue insertion saved x19 (together with x30):

stp	x30, x19, [sp, #-16]!           // 16-byte Folded Spill
mov	w19, w1
bl	g
add	w0, w0, w19
ldp	x30, x19, [sp], #16             // 16-byte Folded Reload

Despite the comment, the stp/ldp here are prologue/epilogue saves, not register allocator spills. Distinguishing the two is the first skill you need when reading allocated code; see Spilling and Splitting.

Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:594-597, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:330, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:360

Operand Flags You Will See

Flag Meaning
killed Last use of the register; it is dead afterwards
dead A definition whose value is never read
undef A use whose value does not matter (no definition needed)
implicit, implicit-def Operand not written in the assembly syntax (e.g. $nzcv flags)
early-clobber The definition is written before all uses are read, so it may not share a register with any use
renamable After allocation: this physical register was chosen by the allocator and later passes may rename it
tied (%d = ADD %d(tied-def 0), ...) The definition must use the same register as that use; see Two-Address Lowering

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