Repository navigation
Register Allocation 09.2 tri hooks
Relevant source files
The following files were used as context for generating this wiki page:
For each hook: the declaration at the pinned commit, what calls it, what AArch64 does, and a short illustrative sketch for the made-up "Toy" target where useful. Toy code is not LLVM source.
These are pure virtual (= 0) or have defaults that are wrong for any real target.
virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;Return every register the allocator must never assign: the stack pointer, the zero register, the frame pointer when this function needs one, platform registers, and the super-registers of all of them. The comment in the header says it directly: "It is often necessary to reserve the super registers of a reserved register as well, to avoid them getting allocated indirectly. You may use markSuperRegs() and checkAllSuperRegsMarked()".
Called by MachineRegisterInfo::freezeReservedRegs at the start of allocation (framework) and by RegisterClassInfo to build allocation orders.
AArch64 splits the set in two. getStrictlyReservedRegs holds registers that are never usable at all:
BitVector Reserved(getNumRegs());
markSuperRegs(Reserved, AArch64::WSP);
markSuperRegs(Reserved, AArch64::WZR);
if (TFI->isFPReserved(MF))
markSuperRegs(Reserved, AArch64::W29);
...
if (hasBasePointer(MF))
markSuperRegs(Reserved, AArch64::W19);and getReservedRegs adds registers kept from the allocator only, such as lr while the function still has virtual registers:
if (MF.getSubtarget<AArch64Subtarget>().isLRReservedForRA()) {
// In order to prevent the register allocator from using LR, we need to
// mark it as reserved. However we don't want to keep it reserved throughout
// the pipeline since it prevents other infrastructure from reasoning about
// it's liveness. We use the NoVRegs property instead of IsSSA because
// IsSSA is removed before VirtRegRewriter runs.
if (!MF.getProperties().hasNoVRegs())Note markSuperRegs(Reserved, AArch64::WSP): reserving wsp also reserves sp. Reserve the smallest register and mark upwards.
Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:400-404, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:419-470, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:535-550
virtual const MCPhysReg*
getCalleeSavedRegs(const MachineFunction *MF) const = 0;Return the null-terminated list of registers this function must preserve, normally a TableGen _SaveList. It may depend on the function's calling convention and attributes. AArch64 switches on both:
if (TLI->supportSwiftError() &&
F.getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
if (Darwin)
return CSR_Darwin_AArch64_AAPCS_SwiftError_SaveList;
...
}
switch (F.getCallingConv()) {
case CallingConv::GHC:
// GHC set of callee saved regs is empty as all those regs are
// used for passing STG regs around
return CSR_AArch64_NoRegs_SaveList;Used by RegisterClassInfo (callee-saved registers go last in allocation orders), Greedy's callee-saved cost, and prologue/epilogue insertion (which saves the ones actually used).
Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:325-330, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:72-100
virtual const uint32_t *getCallPreservedMask(const MachineFunction &MF,
CallingConv::ID) const {
// The default mask clobbers everything. All targets should override.
return nullptr;
}Return the register mask for calls with the given calling convention, normally a TableGen _RegMask. Your call lowering attaches it to each call instruction (DAG.getRegisterMask(Mask) in LowerCall), and LiveIntervals records where those masks are (liveness). This is how the allocator learns which registers a call destroys.
If you forget it, every value live across a call interferes with every register, and the allocator will spill everything around every call, or fail.
Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:355-364, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:271
virtual Register getFrameRegister(const MachineFunction &MF) const = 0;The register that addresses the frame. AArch64:
return TFI->hasFP(MF) ? AArch64::FP : AArch64::SP;Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:1080-1082, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:753-756
virtual bool eliminateFrameIndex(MachineBasicBlock::iterator MI,
int SPAdj, unsigned FIOperandNum,
RegScavenger *RS = nullptr) const = 0;Called by prologue/epilogue insertion for every operand that is a frame index (every spill and reload, plus allocas). Replace operand FIOperandNum with the frame register and add the slot's offset to the instruction's immediate. Return true only if you erased MI.
The hard case: the offset does not fit the immediate. Then you need a scratch register to build the address, after allocation, when all registers may be in use. That is what the register scavenger is for (next section). Illustrative Toy sketch:
// ToyRegisterInfo.cpp (illustrative, not LLVM source)
bool ToyRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
int SPAdj, unsigned FIOp,
RegScavenger *RS) const {
MachineInstr &MI = *II;
MachineFunction &MF = *MI.getParent()->getParent();
int FI = MI.getOperand(FIOp).getIndex();
Register FrameReg;
int64_t Off = getFrameLowering(MF)
->getFrameIndexReference(MF, FI, FrameReg).getFixed() +
MI.getOperand(FIOp + 1).getImm();
if (isInt<12>(Off)) { // fits the immediate
MI.getOperand(FIOp).ChangeToRegister(FrameReg, false);
MI.getOperand(FIOp + 1).ChangeToImmediate(Off);
return false;
}
// Too far: materialise FrameReg + Off in a scratch virtual register;
// the scavenger (requiresFrameIndexScavenging) assigns it later.
...
}AArch64's real implementation is at AArch64RegisterInfo.cpp:978.
Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:1015-1022, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:978
After allocation there are no virtual registers, yet eliminateFrameIndex (and some pseudo expansions) may need a temporary register. Two hooks opt in:
virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
return false;
}
...
virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
return false;
}| Hook | Effect when true |
|---|---|
requiresRegisterScavenging |
Prologue/epilogue insertion creates a RegScavenger and passes it to eliminateFrameIndex. The scavenger finds a free physical register at a point, or spills one to an emergency slot |
requiresFrameIndexScavenging |
After frame index elimination, any virtual registers you created there are assigned physical registers by the scavenger |
useFPForScavengingIndex |
Place the emergency spill slot near the frame pointer (default true) |
AArch64 returns true for both main hooks. A target whose immediates can reach any offset in practice can leave them false. If your frame can be larger than your immediate range, turn them on and make your frame lowering reserve an emergency slot (RS->addScavengingFrameIndex) in processFunctionBeforeFrameFinalized.
Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:882-898, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:758-790
Optional; defaults are safe.
virtual bool
getRegAllocationHints(Register VirtReg, ArrayRef<MCPhysReg> Order,
SmallVectorImpl<MCPhysReg> &Hints,
const MachineFunction &MF,
const VirtRegMap *VRM = nullptr,
const LiveRegMatrix *Matrix = nullptr) const;Append preferred physical registers to Hints. They are tried first by every allocator that uses AllocationOrder (framework). Return true for hard hints: only those registers will be tried. The header advises: "Targets that override this function should typically call this default implementation as well and expect to see generic copy hints added."
Typical uses:
-
Register pairs. Instruction selection sets a target hint with
MRI.setRegAllocationHint(Reg, ToyHint::EvenPart, PartnerVReg); the hook reads it, looks at where the partner was assigned (VRM->getPhys), and hints the matching even or odd register. When one half is coalesced,updateRegAllocHintlets you fix the other half's hint. - Short encodings. Hint the registers that allow a compact instruction form.
AArch64's override is at AArch64RegisterInfo.cpp:1191.
Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:835-853, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:1191
virtual const TargetRegisterClass *
getLargestLegalSuperClass(const TargetRegisterClass *RC,
const MachineFunction &) const {
/// The default implementation is very conservative and doesn't allow the
/// register allocator to inflate register classes.
return RC;
}After splitting, a piece of a register may only have uses that accept a bigger class (for example gpr32all instead of gpr32common). Returning the largest legal super-class with the same spill size lets the allocator inflate the piece's class and choose from more registers. Implement this if your classes form a lattice.
Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:735-745
| Hook | Default | Override when |
|---|---|---|
getCSRFirstUseCost(MF) |
0 (use a callee-saved register whenever free) |
Saving a callee-saved register is costly relative to spilling (Greedy) |
shouldCoalesce(...) |
true |
Some merges create classes that are too constrained (coalescer) |
shouldRegionSplitForVirtReg(MF, LI) |
true | Region splitting is too slow for some huge intervals (splitting) |
reverseLocalAssignment() |
false |
Many registers and huge blocks; allocate local intervals bottom-up (header warns this is "no longer guaranteed to optimally color") |
regClassPriorityTrumpsGlobalness(MF) |
false |
Your AllocationPriority should outrank the global/local distinction |
getRegPressureLimit(RC, MF) |
from TableGen | Scheduler pressure tracking should assume fewer usable registers |
getSpillWeightScaleFactor(RC) |
1.0 |
Some classes are cheaper or dearer to spill (spill weights) |
getCrossCopyRegClass(RC) |
RC |
Registers of RC cannot be copied directly and need an intermediate class |
isConstantPhysReg(R) |
false |
Hardware zero registers (AArch64 xzr); lets liveness ignore them |
isAsmClobberable(MF, R) |
true |
A reserved register must not appear in inline asm clobber lists |
Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:418-431, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:731-753, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:855-873, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:1039-1073
TargetSubtargetInfo::enableSubRegLiveness() (default false) turns on per-lane liveness (liveness). Enable it if your registers are commonly built from or used as parts (vector lanes, register pairs, tuples); it lets the coalescer and allocator treat halves independently. Leave it off until your sub-register indices and lane masks are right, because it exposes every mistake in them.
- 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