Repository navigation
Register Allocation 01 overview
Relevant source files
The following files were used as context for generating this wiki page:
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.
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:
- which physical register holds each value, and for how long;
- which values do not fit and must live in memory for part of their life;
- 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.
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"]
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
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.
| 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 | 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 |
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 |
- New to the topic: read Registers, Virtual Registers and Register Classes, then Liveness, then Greedy Register Allocator.
- Bringing up a new backend: go straight to Writing Register Allocation Support for a Custom Backend and its checklist.
- Debugging bad code or a crash: Tooling and Debugging and the AArch64 Walkthroughs.
- 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