Repository navigation
Register Allocation 05 framework
Relevant source files
The following files were used as context for generating this wiki page:
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).
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"]
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 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
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:
- Start from
TRI->getRawAllocationOrder(RC, MF): the class members, or theAltOrdersentry chosen byAltOrderSelect. -
Drop reserved registers (
Reserved.test(PhysReg)). - 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.
- 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
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 $w0hints%0toward$w0. The coalescer leaves such copies in place and the spill-weight pass records them (see Spill Weights). That is how%0and%4in 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
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
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
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look