Repository navigation
Register Allocation 06.1 regalloc fast
Relevant source files
The following files were used as context for generating this wiki page:
This page explains the Fast algorithm, what its output looks like, and why a new backend usually gets it working first. It is the simplest allocator to read and a good first step before Greedy.
-
Compile time.
-O0builds want speed. Fast is roughly linear in the size of the function and needs noLiveIntervals, no coalescer and no scheduler: the pipeline is just PHI elimination, two-address lowering and Fast (see Pipeline). - Debuggability. Because values are stored to their stack slot between blocks, a debugger can usually find every variable in memory.
-
Bring-up. A new backend can run
-O0code as soon as it can copy, spill and reload a register. Liveness, coalescing and splitting hooks are not needed yet.
flowchart TD
A["runOnMachineFunction"] --> B["for each block: allocateBasicBlock"]
B --> C["mark live-out physregs as pre-assigned"]
C --> D["walk instructions in reverse<br/>allocateInstruction"]
D --> E["defs: free the register;<br/>if the value may live out, store it to its slot after the def"]
D --> F["uses: if no register yet, pick one now<br/>(this is the value's last use, seen first)"]
D --> G["at the block top: reloadAtBegin<br/>load every value still live-in from its slot"]
G --> H["erase coalesced copies"]
Walking backwards is the key idea. Coming from the bottom, the first time the allocator sees a virtual register is at its last use, so it knows exactly when the register becomes free: at its definition, further up. No liveness analysis is needed within the block.
// Traverse block in reverse order allocating instructions one by one.
for (MachineInstr &MI : reverse(MBB)) {
...
allocateInstruction(MI);
...
}
...
// Spill all physical registers holding virtual registers now.
LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
reloadAtBegin(MBB);For each instruction, allocateInstruction:
- handles definitions first: the register that holds the value becomes free above this point (
defineVirtReg,definePhysReg); - handles uses: a virtual register that has no register yet gets one now (
useVirtReg,allocVirtReg), choosing a free register from the class order, or displacing another value and reloading it later; - respects regmasks on calls: every clobbered register must be free across the call, so values live across a call are moved out of caller-saved registers.
Sources: llvm/lib/CodeGen/RegAllocFast.cpp:1794-1853, llvm/lib/CodeGen/RegAllocFast.cpp:1467
Fast keeps no state between blocks. Every value that might be read in another block is stored to a stack slot right after its definition and reloaded at the top of each block that uses it.
The decision is made by mayLiveOut. It is conservative and cheap: a register is treated as crossing blocks if any of its first 8 uses is in another block, or if the block loops back to itself and the use is not dominated by the definition:
// See if the first \p Limit uses of the register are all in the current
// block.
static const unsigned Limit = 8;
unsigned C = 0;
for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
if (UseInst.getParent() != MBB || ++C >= Limit) {
MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
...defineVirtReg then places the store just after the definition:
if (LRI->Reloaded || LRI->LiveOut) {
if (!MI.isImplicitDef()) {
MachineBasicBlock::iterator SpillBefore =
std::next((MachineBasicBlock::iterator)MI.getIterator());
...
spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);and reloadAtBegin loads, at the start of the block, every virtual register still recorded as live when the backwards walk reaches the top.
This is why -O0 code is full of str/ldr to the stack around branches. It is the expected behaviour, not a bug.
Sources: llvm/lib/CodeGen/RegAllocFast.cpp:530-598, llvm/lib/CodeGen/RegAllocFast.cpp:703-741, llvm/lib/CodeGen/RegAllocFast.cpp:1093-1158
There is no coalescer at -O0, but Fast does cheap coalescing on its own. When choosing a register for a value defined by a full COPY, it follows the copy chain (traceCopies, traceCopyChain) and prefers the register on the other side. If both sides end up in the same register, the copy is added to Coalesced and erased at the end of the block.
The first example at -O0 (llc -mtriple=aarch64 -O0 -stop-before=regallocfast). There is no combiner at this level, so the multiply and add stay separate:
bb.1 (%ir-block.0):
liveins: $w0, $w1, $w2
%0:gpr32 = COPY $w0
%1:gpr32 = COPY $w1
%2:gpr32 = COPY $w2
%3:gpr32 = MADDWrrr %0, %1, $wzr
%4:gpr32 = ADDWrr %3, %2
$w0 = COPY %4
RET_ReallyLR implicit $w0
After -stop-after=regallocfast:
bb.1 (%ir-block.0):
liveins: $w0, $w1, $w2
renamable $w8 = MADDWrrr killed renamable $w0, killed renamable $w1, $wzr
renamable $w0 = ADDWrr killed renamable $w8, killed renamable $w2
RET_ReallyLR implicit killed $w0
Reading it bottom-up, as the allocator did:
-
$w0 = COPY %4:%4should be$w0, so%4is given$w0and the copy is coalesced away. -
%4 = ADDWrr %3, %2:%3needs a register. It is defined byMADDWrrr, not by a copy, so it has no hint, and Fast takes the first free register in the allocation order, which on AArch64 starts atw8(see Allocation order).%2traces back through its copy to$w2. -
%0,%1trace back to$w0and$w1, so all three argument copies vanish.
The function is a single block, so there are no slot stores. Add a branch and you will see them.
Fast needs only:
| Hook | Why |
|---|---|
Register classes and getReservedRegs
|
To know what it may use |
getCalleeSavedRegs, getCallPreservedMask
|
Regmasks on calls |
TargetInstrInfo::copyPhysReg |
Turning COPY into a real move |
TargetInstrInfo::storeRegToStackSlot, loadRegFromStackSlot
|
Spills and reloads |
TargetRegisterInfo::eliminateFrameIndex |
Turning the slot frame index into an address, later in prologue/epilogue insertion |
So the usual bring-up order is: get -O0 working with Fast first, then turn on -O2 and Greedy. See the checklist.
Sources: llvm/lib/CodeGen/RegAllocFast.cpp:891-932, llvm/include/llvm/CodeGen/TargetInstrInfo.h:1087, llvm/include/llvm/CodeGen/TargetInstrInfo.h:1199-1219
- 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