Repository navigation
Register Allocation 06.2 regalloc basic
Relevant source files
The following files were used as context for generating this wiki page:
This page walks through the whole of RABasic::selectOrSplit, about fifty lines, and explains what Greedy adds on top.
Basic's queue is a std::priority_queue ordered by spill weight, with the register number as a tie-break:
struct CompSpillWeight {
bool operator()(const LiveInterval *A, const LiveInterval *B) const {
return std::tuple(A->weight(), A->reg()) <
std::tuple(B->weight(), B->reg());
}
};The most expensive-to-spill intervals are allocated first, so they get the first choice of registers. Spill weight is roughly "how often this register is used, scaled by how often each use's block runs (block frequency), divided by its length".
Sources: llvm/lib/CodeGen/RegAllocBasic.h:27-50
flowchart TD
A["dequeue heaviest interval V"] --> B["for each P in AllocationOrder"]
B -->|"IK_Free"| C["return P"]
B -->|"IK_VirtReg"| D["remember P as spill candidate"]
B -->|"IK_RegMask / IK_RegUnit"| B
D --> E["for each candidate P:<br/>are all interferences spillable<br/>and lighter than V?"]
E -->|"yes"| F["unassign and spill them;<br/>return P"]
E -->|"no candidate works"| G{"V spillable?"}
G -->|"yes"| H["spill V; return 0"]
G -->|"no"| I["return ~0u (error)"]
auto Order =
AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
for (MCRegister PhysReg : Order) {
switch (Matrix->checkInterference(VirtReg, PhysReg)) {
case LiveRegMatrix::IK_Free:
// PhysReg is available, allocate it.
return PhysReg;
case LiveRegMatrix::IK_VirtReg:
// Only virtual registers in the way, we may be able to spill them.
PhysRegSpillCands.push_back(PhysReg);
continue;
default:
// RegMask or RegUnit interference.
continue;
}
}Hints come first in Order, so if the hinted register is free it wins. Registers blocked by calls (IK_RegMask) or fixed physical liveness (IK_RegUnit) are skipped for good. Registers blocked only by other virtual registers are remembered.
For each remembered register, spillInterferences collects every virtual register occupying any of its units. It gives up on that register if any of them is not spillable, or is heavier than the current interval:
for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit);
for (const auto *Intf : reverse(Q.interferingVRegs())) {
if (!Intf->isSpillable() || Intf->weight() > VirtReg.weight())
return false;
Intfs.push_back(Intf);
}
}Otherwise it unassigns each one from the matrix and calls spiller().spill(LRE). The spiller creates small new intervals around each use and reload. They go into SplitVRegs and the base loop puts them back in the queue.
Because the queue pops the heaviest interval first, every interval assigned earlier was at least as heavy as the current one at the time it was dequeued. Step 2 therefore fires mostly for intervals that join the queue later, such as the short reload intervals the spiller creates. They are tiny, so their weight (uses divided by length) is high, and they can push aside a long, lightly used interval that was assigned earlier.
If nothing could be freed, the current interval is spilled itself and 0 is returned, meaning "nothing to assign this round". If it is not spillable (for example it is already a tiny reload interval), ~0u is returned and RegAllocBase reports that it ran out of registers.
Sources: llvm/lib/CodeGen/RegAllocBasic.cpp:121-218
| Missing feature | Effect | Greedy's answer |
|---|---|---|
| Splitting | A long interval that conflicts in one small place is spilled everywhere | Region, block and local splitting |
| Eviction for reassignment | An interfering interval is spilled, never moved to another free register | Evicted intervals are requeued and may find another register |
| Callee-saved cost | No special treatment of the first use of a callee-saved register |
CSRCost, tryAssignCSRFirstTime
|
| Hint repair | Broken copy hints stay broken | tryHintsRecoloring |
On the 24-load spill test from the walkthroughs, Basic and Greedy happen to produce code of the same size (32 spill/reload/save lines, 83 instructions). The difference shows up in larger functions with loops, where splitting matters.
- As a reference while reading Greedy.
- To check whether a miscompile is caused by Greedy's heuristics:
llc -regalloc=basic. If the bug disappears, the problem is likely in Greedy-specific logic (eviction, splitting). - As a simple template if you ever write your own allocator on top of
RegAllocBase.
- 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