Skip to content

Register Allocation 05 framework

Mugundan edited this page Nov 27, 2026 · 1 revision

Allocation Framework

Relevant source files

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

Basic, Greedy and PBQP do not edit instructions while they decide. They record decisions in a few shared data structures and leave the editing to the [rewriter](#rewriting-post-ra). Basic and Greedy also share the same main loop. Learning these pieces once makes every allocator easier to read.

Purpose and Scope

This page covers the four shared structures (VirtRegMap, LiveRegMatrix, RegisterClassInfo, AllocationOrder) and the RegAllocBase driver loop. The Fast allocator uses none of them (see Fast Register Allocator).

The Big Picture

flowchart LR
  LIS["LiveIntervals<br/>where each vreg is live"] --> RA["Allocator<br/>selectOrSplit"]
  RCI["RegisterClassInfo<br/>usable registers per class"] --> AO["AllocationOrder<br/>hints first, then class order"]
  AO --> RA
  RA -->|"checkInterference"| LRM["LiveRegMatrix<br/>what is assigned to each reg unit"]
  RA -->|"assign / unassign"| LRM
  LRM --> VRM["VirtRegMap<br/>vreg to physreg or stack slot"]
  VRM --> RW["VirtRegRewriter<br/>edits the instructions"]
Loading

VirtRegMap: The Decision Record

VirtRegMap is two arrays indexed by virtual register:

Query or update Meaning
assignVirt2Phys(V, P), getPhys(V), hasPhys(V), clearVirt(V) Virtual to physical register
assignVirt2StackSlot(V), createSpillSlot(RC), getStackSlot(V) Virtual register to spill slot (a frame index)
hasPreferredPhys(V), hasKnownPreference(V) Whether V has a physical-register hint, and whether that hint is satisfied
getOriginal(V), setIsSplitFromReg(V, Orig) After splitting, which register a piece came from

Allocators never write MachineOperands directly. Unassigning (for eviction) is just clearing an entry, which is why eviction is cheap.

Sources: llvm/lib/CodeGen/VirtRegMap.cpp:92-150

LiveRegMatrix: Who Is Using Each Register

LiveRegMatrix answers "if I put V in P, what does it collide with?" It keeps one LiveIntervalUnion per register unit. A union is a sorted map from slot ranges to the virtual registers currently assigned there.

Assigning records the decision in VirtRegMap, then adds V's segments to the union of every unit of P:

void LiveRegMatrix::assign(const LiveInterval &VirtReg, MCRegister PhysReg) {
  ...
  VRM->assignVirt2Phys(VirtReg.reg(), PhysReg);

  foreachUnit(
      TRI, VirtReg, PhysReg, [&](MCRegUnit Unit, const LiveRange &Range) {
        ...
        Matrix[Unit].unify(VirtReg, Range);
        return false;
      });
  ...
}

unassign does the reverse with extract. Greedy calls it to evict a register.

Checking runs three tests, cheapest first, and reports which one failed:

LiveRegMatrix::InterferenceKind
LiveRegMatrix::checkInterference(const LiveInterval &VirtReg,
                                 MCRegister PhysReg) {
  if (VirtReg.empty())
    return IK_Free;

  // Regmask interference is the fastest check.
  if (checkRegMaskInterference(VirtReg, PhysReg))
    return IK_RegMask;

  // Check for fixed interference.
  if (checkRegUnitInterference(VirtReg, PhysReg))
    return IK_RegUnit;

  // Check the matrix for virtual register interference.
  bool Interference = foreachUnit(TRI, VirtReg, PhysReg,
                                  [&](MCRegUnit Unit, const LiveRange &LR) {
                                    return query(LR, Unit).checkInterference();
                                  });
  if (Interference)
    return IK_VirtReg;

  return IK_Free;
}
Result Meaning Can the allocator fix it?
IK_Free P is free for all of V Assign it
IK_RegMask A call inside V's range clobbers P No. Try another register, or split around the call
IK_RegUnit Fixed physical liveness overlaps (an argument, a return value, an implicit-def) No. Same as above
IK_VirtReg Another virtual register already sits in P Yes, by evicting it (Greedy) or spilling it (Basic)

The difference between the last two rows matters. Only IK_VirtReg interference can be removed by evicting someone. query(LR, Unit) returns a LiveIntervalUnion::Query, which can also list the interfering virtual registers: Q.interferingVRegs() returns them (it calls collectInterferingVRegs() to fill the InterferingVRegs list). That list is what eviction and Basic's spilling work from.

Sources: llvm/lib/CodeGen/LiveRegMatrix.cpp:113-160, llvm/lib/CodeGen/LiveRegMatrix.cpp:195-225, llvm/include/llvm/CodeGen/LiveIntervalUnion.h:122-130

RegisterClassInfo: The Usable Order

The register class in TableGen lists all its members, including reserved ones. RegisterClassInfo::compute turns that raw list into the order the allocator actually uses, once per class per function:

  1. Start from TRI->getRawAllocationOrder(RC, MF): the class members, or the AltOrders entry chosen by AltOrderSelect.
  2. Drop reserved registers (Reserved.test(PhysReg)).
  3. Move callee-saved registers to the end, keeping the target's order otherwise. A callee-saved register costs a save and restore in the prologue and epilogue the first time it is used, so volatile registers are tried first.
  4. Record the minimum cost (from TableGen CostPerUse) and whether the class is a proper sub-class of a larger legal class (getLargestLegalSuperClass). Greedy uses that flag to decide whether a split piece could move to a larger class.
    if (getLastCalleeSavedAlias(PhysReg) && ...)
      // PhysReg aliases a CSR, save it for later.
      CSRAlias.push_back(PhysReg);
    else {
      ...
      RCI.Order[N++] = PhysReg;
    }
  ...
  // CSR aliases go after the volatile registers, preserve the target's order.
  for (unsigned PhysReg : CSRAlias) {

For AArch64 GPR32 this gives roughly w8 … w18, w0 … w7, w19 … w30: the rotated order with reserved registers removed and callee-saved registers last. This is why ordinary temporaries land in w8, w9, w10, and why w19 shows up only when a value lives across a call. The exact list depends on the function, because reserved registers do (for example w18 on platforms that reserve it, or fp when a frame pointer is needed).

-stress-regalloc=N cuts every class to its first N registers. It is a useful way to force spills in small tests.

Sources: llvm/lib/CodeGen/RegisterClassInfo.cpp:186-258, llvm/lib/CodeGen/RegisterClassInfo.cpp:37

AllocationOrder: Hints First

When the allocator considers one virtual register, it builds an AllocationOrder:

AllocationOrder AllocationOrder::create(Register VirtReg, const VirtRegMap &VRM,
                                        const RegisterClassInfo &RegClassInfo,
                                        const LiveRegMatrix *Matrix) {
  ...
  auto Order = RegClassInfo.getOrder(MF.getRegInfo().getRegClass(VirtReg));
  SmallVector<MCPhysReg, 16> Hints;
  bool HardHints =
      TRI->getRegAllocationHints(VirtReg, Order, Hints, MF, &VRM, Matrix);

Iterating it yields the hints first, then the rest of the class order with the hints skipped. If getRegAllocationHints returns true (hard hints), only the hints are tried.

Hints come from two places:

  • Copies to and from physical registers. %0 = COPY $w0 hints %0 toward $w0. The coalescer leaves such copies in place and the spill-weight pass records them (see Spill Weights). That is how %0 and %4 in the first example both got $w0.
  • The target, by overriding TargetRegisterInfo::getRegAllocationHints. Use this for constraints like "these two registers should form an even/odd pair" (see TargetRegisterInfo Hooks).

Sources: llvm/lib/CodeGen/AllocationOrder.cpp:29-46, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:839

RegAllocBase: The Shared Loop

Basic and Greedy derive from RegAllocBase. The base class provides the loop, and each allocator provides four virtual functions:

Virtual Basic Greedy
enqueueImpl(LI) Push into a priority queue ordered by spill weight Push with a priority from getPriority (see Greedy)
dequeue() Pop the heaviest Pop the highest priority
selectOrSplit(LI, NewVRegs) Assign, or spill whatever is lighter Assign, evict, split, or spill
spiller() InlineSpiller InlineSpiller

The loop:

void RegAllocBase::allocatePhysRegs() {
  seedLiveRegs();

  // Continue assigning vregs one at a time to available physical registers.
  while (const LiveInterval *VirtReg = dequeue()) {
    ...
    VirtRegVec SplitVRegs;
    MCRegister AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);

    if (AvailablePhysReg == ~0u) {
      // selectOrSplit failed to find a register!
      ...
      AvailablePhysReg = getErrorAssignment(*RC, MI);
      cleanupFailedVReg(VirtReg->reg(), AvailablePhysReg, SplitVRegs);
    } else if (AvailablePhysReg)
      Matrix->assign(*VirtReg, AvailablePhysReg);

    for (Register Reg : SplitVRegs) {
      ...
      enqueue(SplitVirtReg);
    }
  }
}

selectOrSplit returns one of three things:

Return value Meaning What the loop does
A physical register Assign VirtReg to it Matrix->assign
0 (no register) VirtReg was split, spilled or deferred; the new or requeued intervals are in NewVRegs Queue every register in NewVRegs
~0u Nothing worked Report "ran out of registers", force an assignment so compilation can continue

The ~0u case almost always means impossible constraints: inline assembly that asks for more registers than exist, or a register class with no allocatable members. getErrorAssignment prints the familiar error: ran out of registers during register allocation (or the inline-asm variant). The function is then rewritten so it still passes the verifier, but the output is not meaningful.

seedLiveRegs queues every virtual register that has non-debug uses. postOptimization runs after the loop and lets the spiller hoist spills and delete instructions that became dead after rematerialisation.

Sources: llvm/lib/CodeGen/RegAllocBase.cpp:60-168, llvm/lib/CodeGen/RegAllocBase.cpp:170-218, llvm/lib/CodeGen/RegAllocBase.cpp:249-252, llvm/lib/CodeGen/RegAllocBasic.h:27-50

Filtering Which Registers an Allocator Handles

Every allocator constructor accepts a RegAllocFilterFunc, and RegAllocBase::enqueue skips registers the filter rejects (shouldAllocateRegister). A target can use this to run the allocator twice: once for one register class, then again for the rest. AMDGPU does this to allocate scalar and vector registers in separate passes. Most targets do not need it.

Sources: llvm/lib/CodeGen/RegAllocBase.cpp:199-214, llvm/lib/CodeGen/RegAllocGreedy.cpp:337, llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp:214-365

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