Repository navigation
Register Allocation 07.1 spill weights
Relevant source files
The following files were used as context for generating this wiki page:
This page gives the exact formula from VirtRegAuxInfo::weightCalcHelper, explains each factor, and lists the target hooks that change it.
| User | How |
|---|---|
| Basic | Queue order (heaviest first); only spills interference lighter than the current interval |
| Greedy | Eviction cost (EvictionCost::MaxWeight), split cost decisions |
| PBQP | The "spill" entry of each node's cost vector |
| AllocationOrder | The recorded copy hints are tried first |
VirtRegAuxInfo::calculateSpillWeightsAndHints runs over every virtual register at the start of allocation. LiveRangeEdit::calculateRegClassAndHint recomputes weights for new intervals created by splitting and spilling.
Step by step, as weightCalcHelper does it:
1. Per instruction. For every non-debug instruction that reads or writes the register (identity copies and IMPLICIT_DEF excluded):
float Weight = isDef + isUse;
// When optimizing for size we only consider the codesize impact of spilling
// the register, not the runtime impact.
if (OptForSize)
return Weight;
return Weight * MBFI->getBlockFreqRelativeToEntryBlock(MBB);An instruction that both reads and writes counts 2. Each instruction is scaled by how often its block runs relative to the function entry, so a use inside a loop that runs 100 times counts about 100 times more.
2. Induction variables. A definition in a loop-exiting block whose value is live out of that block (it looks like a loop counter update) counts 3 times:
// Give extra weight to what looks like a loop induction variable update.
if (Writes && IsExiting && LIS.isLiveOutOfMBB(LI, MBB))
Weight *= 3;3. Sum. All instruction weights are added to TotalWeight.
4. Hinted registers get a tiny boost: TotalWeight *= 1.01F if any copy hint was found.
5. Unspillable intervals. If every segment is tiny (isZeroLength) and the interval does not cross a call (isLiveAtIndexes(RegMaskSlots)), spilling it would not help, so it is marked not spillable and gets weight -1 (the allocator treats it as infinite). Reload intervals created by the spiller fall in this category. Intervals defined by unspillable terminators (TII::isUnspillableTerminator) are also unspillable.
6. Rematerialisable intervals are cheaper to spill, because no store is needed: TotalWeight *= 0.5F.
7. Class scale. TotalWeight *= TRI.getSpillWeightScaleFactor(RC). A target can make some register classes more or less attractive to spill.
8. Normalise by length.
static inline float normalizeSpillWeight(float UseDefFreq, unsigned Size,
unsigned NumInstr) {
// The constant 25 instructions is added to avoid depending too much on
// accidental SlotIndex gaps for small intervals. The effect is that small
// intervals have a spill weight that is mostly proportional to the number
// of uses, while large intervals get a spill weight that is closer to a use
// density.
return UseDefFreq / (Size + 25*SlotIndex::InstrDist);
}Size is the interval's length in slot index units (LI.getSize()). NumInstr is passed but not used in the default formula.
So, in one line:
weight = (sum over uses/defs of (reads + writes) * blockFreq * [3 for IV updates])
* [1.01 if hinted] * [0.5 if rematerialisable] * classScale
/ (size + 25 * 16)
Sources: llvm/lib/CodeGen/CalcSpillWeights.cpp:221-401, llvm/include/llvm/CodeGen/CalcSpillWeights.h:35-43, llvm/lib/CodeGen/LiveIntervals.cpp:965-975
- Heavily used, short intervals have high weight: spilling them would add many loads for little gain. They keep registers.
- Long intervals with few uses have low weight: one store and a few loads free a register for a long stretch. They are spilled first.
- Uses in hot loops dominate, because block frequency multiplies them.
- Constants (rematerialisable) are half price, because "spilling" them is just re-executing a cheap instruction.
Using the first example after coalescing (slot indexes from -print-after=greedy):
48B %0:gpr32 = COPY $w0
80B %4:gpr32 = MADDWrrr %0, %1, %2
For %0 (computed by hand from the formula; release llc does not print weights):
| Step | Value |
|---|---|
COPY writes %0, entry block (frequency 1) |
1 |
MADDWrrr reads %0, entry block |
1 |
| Sum | 2 |
Copy hint $w0 found, × 1.01 |
2.02 |
| Not rematerialisable (defined by a copy from a physical register) | 2.02 |
| Size: 48 to 80 | 32 |
| Normalise: 2.02 / (32 + 400) | ≈ 0.0047 |
The + 400 dominates for such a short interval, which is exactly what the source comment says: small intervals are weighted mostly by their number of uses.
While visiting instructions, the same loop records hints from copies:
// Get allocation hints from copies.
if (!TII.isCopyInstr(*MI))
continue;
Register HintReg = copyHint(MI, LI.reg(), TRI, MRI);
if (HintReg && (HintReg.isVirtual() || MRI.isAllocatable(HintReg)))
Hint[HintReg] += Weight;Each register on the other side of a copy accumulates the weight of the copies that connect to it. The hints are sorted and stored in MachineRegisterInfo (addRegAllocationHint):
- physical-register hints before virtual-register hints;
- then by accumulated weight, highest first;
- then non-callee-saved before callee-saved;
- then by register number.
AllocationOrder later puts these hints at the front of the order. A target hint already set with MRI.setRegAllocationHint(Reg, Type, Hint) (non-zero type) is kept and passed to TargetRegisterInfo::getRegAllocationHints, which can interpret it (see TargetRegisterInfo Hooks).
Sources: llvm/lib/CodeGen/CalcSpillWeights.cpp:54-88, llvm/lib/CodeGen/CalcSpillWeights.cpp:265-368
isRematerializable returns true only if every value number of the interval is defined by an instruction the target says is trivially rematerialisable. It follows full copies created by splitting back to the original definition. Any PHI-def makes it false.
Sources: llvm/lib/CodeGen/CalcSpillWeights.cpp:88-130
| Hook | Effect |
|---|---|
TargetRegisterInfo::getSpillWeightScaleFactor(RC) |
Multiplies every weight of that class (step 7) |
TargetInstrInfo::isReMaterializableImpl / isReMaterializable in TableGen |
Halves the weight (step 6) |
TargetInstrInfo::isUnspillableTerminator (non-virtual query; see its declaration for the virtual it forwards to) |
Makes an interval defined by such a terminator unspillable |
TargetInstrInfo::isCopyInstrImpl |
Lets target-specific move instructions produce hints |
| Branch probabilities and block frequencies | Drive the frequency factor in step 1 |
Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:803, llvm/include/llvm/CodeGen/TargetInstrInfo.h:176, llvm/include/llvm/CodeGen/TargetInstrInfo.h:422, llvm/include/llvm/CodeGen/TargetInstrInfo.h:1118
- 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