Repository navigation
Register Allocation 01.1 pipeline
Relevant source files
The following files were used as context for generating this wiki page:
This page lists the exact passes in both chains, explains what each one is for in one or two sentences, and shows how -regalloc= selects the chain. Each preparation pass has its own page later.
TargetPassConfig::getOptimizeRegAlloc decides:
- If
-regalloc=was given on the command line, the optimised chain runs for every allocator exceptfast. - Otherwise the optimised chain runs whenever the optimisation level is not
-O0.
bool TargetPassConfig::getOptimizeRegAlloc() const {
// An explicit -regalloc choice implies its pipeline: only the fast
// allocator uses the unoptimized one.
...
RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
if (Ctor != (RegisterRegAlloc::FunctionPassCtor)&useDefaultRegisterAllocator)
return Ctor !=
(RegisterRegAlloc::FunctionPassCtor)&createFastRegisterAllocator;
return getOptLevel() != CodeGenOptLevel::None;
}So llc -O2 -regalloc=fast uses the unoptimised chain (no coalescer, no scheduler), and llc -O0 -regalloc=greedy uses the optimised one. The unoptimised chain only accepts the Fast allocator; addRegAssignAndRewriteFast reports a fatal usage error for anything else.
Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1393-1403, llvm/lib/CodeGen/TargetPassConfig.cpp:1445-1457
void TargetPassConfig::addFastRegAlloc() {
addPass(&PHIEliminationID);
addPass(&TwoAddressInstructionPassID);
addRegAssignAndRewriteFast();
}Three passes: remove PHIs, make two-address instructions explicit, then let the Fast allocator assign and rewrite in one go. The Fast allocator writes physical registers directly into the instructions, so there is no separate rewriter.
Observed with llc -mtriple=aarch64 -O0 -debug-pass=Structure (filtered):
Eliminate PHI nodes for register allocation
Two-Address instruction pass
Fast Register Allocator
Prologue/Epilogue Insertion & Frame Finalization
Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1483-1488
void TargetPassConfig::addOptimizedRegAlloc() {
addPass(&DetectDeadLanesID);
addPass(&InitUndefID);
addPass(&ProcessImplicitDefsID);
addPass(&UnreachableMachineBlockElimID);
addPass(&LiveVariablesID);
addPass(&MachineLoopInfoID);
addPass(&PHIEliminationID);
if (EarlyLiveIntervals)
addPass(&LiveIntervalsID);
addPass(&TwoAddressInstructionPassID);
addPass(&RegisterCoalescerID);
addPass(&RenameIndependentSubregsID);
addPass(&MachineSchedulerID);
if (addRegAssignAndRewriteOptimized()) {
addPass(&StackSlotColoringID);
addPostRewrite();
addPass(&MachineCopyPropagationID);
addPass(&MachineLICMID);
}
}(Comments removed; see the source for them.) addRegAssignAndRewriteOptimized adds the allocator, then the target's addPreRewrite() hook, then VirtRegRewriter, then a scoring pass that does nothing unless an ML eviction policy is being trained.
Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1459-1473, llvm/lib/CodeGen/TargetPassConfig.cpp:1493-1549
| # | Pass (-debug-pass name) |
Command-line name | Purpose |
|---|---|---|---|
| 1 | Detect Dead Lanes | detect-dead-lanes |
Finds sub-register lanes that are never read and marks them dead or undef, so they do not create false liveness |
| 2 | Init Undef Pass | init-undef |
An undef input does not stop the allocator from giving it the same register as an early-clobber result, so this pass replaces such undefined inputs with a temporary pseudo definition. It also rewrites NoReg tied operands back to IMPLICIT_DEF before two-address lowering |
| 3 | Process Implicit Definitions | processimpdefs |
Removes IMPLICIT_DEF instructions and marks their uses undef
|
| 4 | Remove unreachable machine basic blocks | unreachable-mbb-elimination |
Required before LiveVariables
|
| 5 | Live Variable Analysis | livevars |
Computes kill flags on SSA MIR; used by the next two passes |
| 6 | Eliminate PHI nodes | phi-node-elimination |
Replaces each PHI with COPYs in the predecessor blocks. See PHI Elimination and Two-Address Lowering
|
| 7 | Two-Address instruction pass | twoaddressinstruction |
For instructions whose result must use the same register as an operand, inserts a COPY so that holds. Ends SSA form |
| 8 | Slot index numbering, Live Interval Analysis |
slotindexes, liveintervals
|
Number the instructions and compute live intervals (required by the coalescer, so they run here) |
| 9 | Register Coalescer | register-coalescer |
Removes COPYs by merging the two registers into one. See Register Coalescer
|
| 10 | Rename Disconnected Subregister Components | rename-independent-subregs |
Splits a register whose sub-register parts are independent into separate registers |
| 11 | Machine Instruction Scheduler | machine-scheduler |
Pre-RA scheduling; it tracks register pressure so it can avoid creating spills |
| 12 | (analyses) |
livedebugvars, livestacks, virtregmap, liveregmatrix, edge-bundles, spill-code-placement
|
Required by Greedy; built just before it |
| 13 | Greedy Register Allocator | greedy |
Assigns, evicts, splits and spills. See Greedy Register Allocator |
| 14 | Virtual Register Rewriter | virtregrewriter |
Replaces each virtual register in the instructions with its physical register. See Rewriting and Post-RA Passes |
| 15 | Stack Slot Coloring | stack-slot-coloring |
Lets spill slots whose live ranges do not overlap share memory |
| 16 | Machine Copy Propagation | machine-cp |
Forwards copies that the coalescer could not remove |
| 17 | Machine Loop Invariant Code Motion | machinelicm |
Post-RA: hoists reloads and rematerialised constants out of loops |
From llc -mtriple=aarch64 -O2 -debug-pass=Structure on a trivial function, filtered to the passes around allocation:
AArch64 PTRUE Coalescing
Detect Dead Lanes
Init Undef Pass
Process Implicit Definitions
Remove unreachable machine basic blocks
Live Variable Analysis
Eliminate PHI nodes for register allocation
Two-Address instruction pass
Slot index numbering
Live Interval Analysis
Register Coalescer
Rename Disconnected Subregister Components
Machine Instruction Scheduler
AArch64 Post Coalescer pass
Debug Variable Analysis
Live Stack Slot Analysis
Virtual Register Map
Live Register Matrix
Spill Code Placement Analysis
Greedy Register Allocator
Virtual Register Rewriter
Register Allocation Pass Scoring
Stack Slot Coloring
Machine Copy Propagation Pass
Machine Loop Invariant Code Motion
Prologue/Epilogue Insertion & Frame Finalization
Two AArch64 passes appear. AArch64 PTRUE Coalescing comes from addMachineSSAOptimization, earlier in the pipeline. AArch64 Post Coalescer pass sits right before the allocator because AArch64 overrides addRegAssignAndRewriteOptimized to add it first:
bool AArch64PassConfig::addRegAssignAndRewriteOptimized() {
addPass(createAArch64PostCoalescerPass());
return TargetPassConfig::addRegAssignAndRewriteOptimized();
}This pattern (override a hook, add your pass, call the base version) is the usual way for a target to insert work around allocation. See Pass Pipeline Hooks.
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:817-829, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:970-973
flowchart TD
A["addPreRegAlloc()"] --> B["addOptimizedRegAlloc()<br/>or addFastRegAlloc()"]
B --> C["addRegAssignAndRewriteOptimized()<br/>allocator pass"]
C --> D["addPreRewrite()"]
D --> E["VirtRegRewriter"]
E --> F["StackSlotColoring"]
F --> G["addPostRewrite()"]
G --> H["MachineCopyPropagation, MachineLICM"]
H --> I["addPostRegAlloc()"]
I --> J["Prologue/Epilogue insertion"]
| Hook | When it runs | AArch64 uses it for |
|---|---|---|
addPreRegAlloc |
Before the whole allocation chain | Dead register definitions to wzr/xzr, AdvSIMD scalar, machine pipeliner |
addRegAssignAndRewriteOptimized |
Wraps allocator plus rewriter | The Post Coalescer pass |
addPreRewrite |
After the allocator, before the rewriter | (not used) |
addPostRewrite |
After the rewriter | A sub-register mitigation pass, when enabled |
addPostRegAlloc |
After the chain, before prologue/epilogue | Redundant copy elimination, A57 FP load balancing |
addPostFastRegAllocRewrite |
After the Fast allocator | (not used) |
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:852-886, llvm/lib/CodeGen/TargetPassConfig.cpp:1157-1184, llvm/lib/CodeGen/InitUndef.cpp:9-37
| After | MIR property |
|---|---|
| Instruction selection | SSA, virtual registers, PHIs, IMPLICIT_DEFs |
| PHI elimination | No PHIs; extra COPYs at the end of predecessors |
| Two-address | Not SSA any more: a register can be defined more than once (TiedOpsRewritten) |
| Coalescer | Most COPYs gone; fewer, longer virtual registers |
| Allocator |
VirtRegMap says where each register lives; instructions still name virtual registers; spill code inserted |
| Rewriter | Only physical registers; NoVRegs property set |
The Coalescer page shows one loop at each of these points.
- 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