Repository navigation
Register Allocation 09.3 tii hooks
Relevant source files
The following files were used as context for generating this wiki page:
Declarations at the pinned commit, who calls each hook, what AArch64 does, and illustrative sketches for the made-up "Toy" target (not LLVM source).
virtual void copyPhysReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI, const DebugLoc &DL,
Register DestReg, Register SrcReg, bool KillSrc,
bool RenamableDest = false,
bool RenamableSrc = false) const {
llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg!");
}Emit an instruction (or a sequence) that copies SrcReg to DestReg. Both are physical registers. It is called after allocation, when ExpandPostRAPseudos lowers each remaining COPY, and by the Fast allocator and frame lowering.
Handle every pair of register classes that can appear in a COPY:
- same class (GPR to GPR);
- across classes (GPR to FPR, if your ISA has a move for it);
- register pairs and tuples (copy each sub-register; take care with overlapping source and destination, copy in the right direction);
- special registers (flags, if a
COPYof them can occur).
If a pair is impossible, make sure it never reaches COPY: use getCrossCopyRegClass or CopyCost = -1 on the class.
AArch64 forwards to copyPhysRegImpl, a large function that covers GPR, FPR, SVE, tuples and flag registers.
// ToyInstrInfo.cpp (illustrative, not LLVM source)
void ToyInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator I,
const DebugLoc &DL, Register Dst, Register Src,
bool KillSrc, bool, bool) const {
if (Toy::GPRRegClass.contains(Dst, Src)) {
BuildMI(MBB, I, DL, get(Toy::MOVrr), Dst)
.addReg(Src, getKillRegState(KillSrc));
return;
}
if (Toy::GPRPairRegClass.contains(Dst, Src)) {
// Copy halves; if they overlap, copy the high half first.
Register DLo = RI.getSubReg(Dst, Toy::sub_lo), DHi = RI.getSubReg(Dst, Toy::sub_hi);
Register SLo = RI.getSubReg(Src, Toy::sub_lo), SHi = RI.getSubReg(Src, Toy::sub_hi);
bool HiFirst = DLo == SHi;
auto Copy = [&](Register D, Register S) {
BuildMI(MBB, I, DL, get(Toy::MOVrr), D).addReg(S, getKillRegState(KillSrc));
};
if (HiFirst) { Copy(DHi, SHi); Copy(DLo, SLo); }
else { Copy(DLo, SLo); Copy(DHi, SHi); }
return;
}
llvm_unreachable("Impossible register copy");
}Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:1083-1093, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:6365-6375
virtual void storeRegToStackSlot(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const;
virtual void loadRegFromStackSlot(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg,
int FrameIndex, const TargetRegisterClass *RC, Register VReg,
unsigned SubReg = 0,
MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const;Insert, before MI, a store of SrcReg (or a load into DestReg) to frame index FrameIndex, using an instruction suitable for class RC.
Callers and what they pass:
| Caller | Register passed | Notes |
|---|---|---|
InlineSpiller (Greedy, Basic, PBQP) |
A virtual register | Your instruction must accept a virtual register of class RC. You may constrain its class (AArch64 does) |
RegAllocFast |
A physical register; VReg is the virtual register being spilled |
|
| Prologue/epilogue insertion (callee-saved saves) | A physical register; Flags is FrameSetup / FrameDestroy
|
Pass the flag through to the instructions you create |
The AArch64 version chooses the opcode by spill size and class:
MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
MachineMemOperand *MMO =
MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
...
switch (RI.getSpillSize(*RC)) {
...
case 4:
if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
Opc = AArch64::STRWui;
if (SrcReg.isVirtual())
MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR32RegClass);That is the STRWui ... %stack.N, 0 seen in the spill example. Three things to copy from it:
-
Always attach a
MachineMemOperandfor the fixed stack slot. Alias analysis, the scheduler and the load/store optimiser rely on it. - Pick by spill size and class, and cover every allocatable class. A missing case is a crash under register pressure, which may not show up until a big test.
-
Use the frame index as the address operand (
.addFrameIndex(FI).addImm(0));eliminateFrameIndexfixes it later.
// ToyInstrInfo.cpp (illustrative, not LLVM source)
void ToyInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator I, Register Src, bool IsKill, int FI,
const TargetRegisterClass *RC, Register, MachineInstr::MIFlag Flags) const {
MachineFunction &MF = *MBB.getParent();
MachineFrameInfo &MFI = MF.getFrameInfo();
auto *MMO = MF.getMachineMemOperand(
MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
unsigned Opc = Toy::GPRRegClass.hasSubClassEq(RC) ? Toy::STW
: Toy::GPRPairRegClass.hasSubClassEq(RC) ? Toy::STD
: 0;
assert(Opc && "Cannot store this register class to a stack slot");
BuildMI(MBB, I, DebugLoc(), get(Opc))
.addReg(Src, getKillRegState(IsKill))
.addFrameIndex(FI).addImm(0)
.addMemOperand(MMO)
.setMIFlag(Flags);
}loadRegFromStackSlot mirrors it with MOLoad and a load opcode.
Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:1195-1226, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:6400-6440, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:6580
virtual Register isLoadFromStackSlot(const MachineInstr &MI,
int &FrameIndex) const {
return 0;
}
virtual Register isStoreToStackSlot(const MachineInstr &MI,
int &FrameIndex) const {
return 0;
}Recognise your own spill and reload instructions: return the register and set FrameIndex, or return 0. The header requires returning 0 "if the instruction has any side effects other than loading from the stack slot". The spiller uses them to delete redundant spills and reloads (coalesceStackAccess, eliminateRedundantSpills), Stack Slot Coloring uses them, and the AsmPrinter uses them to print the // 4-byte Spill comments. With the defaults, everything still works but spill code is worse.
Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:320-365, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:2852-2881
Mark instructions isReMaterializable = 1 in TableGen (and usually isAsCheapAsAMove = 1). That is often enough: the generic check accepts an instruction whose uses are only constants or unallocatable physical registers:
/// Return true if the instruction is trivially rematerializable, meaning it
/// has no side effects and requires no operands that aren't always available.
/// This means the only allowed uses are constants and unallocatable physical
/// registers so that the instructions result is independent of the place
/// in the function.
bool isTriviallyReMaterializable(const MachineInstr &MI) const {| Hook | Override when |
|---|---|
isReMaterializableImpl(MI) |
The flag is set but some forms of the instruction are not safe to recompute (e.g. a load that is only safe from invariant memory). Must return false if the instruction has any side effects other than producing a value |
reMaterialize(MBB, MI, DestReg, SubIdx, Orig, UsedLanes) |
The copy needs adjusting (e.g. a different opcode when DestReg is a sub-register) |
Effects: the coalescer can duplicate the definition instead of keeping a copy (coalescer), the spill weight is halved (spill weights), and the spiller recomputes instead of reloading (inline spiller).
Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:171-218, llvm/include/llvm/CodeGen/TargetInstrInfo.h:488-495
virtual std::optional<DestSourcePair>
isCopyInstrImpl(const MachineInstr &MI) const {
return std::nullopt;
}If your target has move instructions that survive until allocation (for example a MOVrr emitted by ISel instead of a COPY), report them here so copy hints, sibling-copy detection in the spiller and copy propagation treat them as copies. AArch64's is at AArch64InstrInfo.cpp:11511.
Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:1112-1120, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:11511
virtual MachineInstr *
foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,
ArrayRef<unsigned> Ops, int FrameIndex,
MachineInstr *&CopyMI, LiveIntervals *LIS = nullptr,
VirtRegMap *VRM = nullptr) const {
return nullptr;
}Ops are the operand indices of MI that refer to the register being spilled. If MI has a form that reads (or writes) memory directly, build it with the frame index instead and return it; return nullptr otherwise. The generic foldMemoryOperand wrapper adds the memory operand. Worth doing for CISC-style ISAs; load/store ISAs can skip it.
Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:1450-1475, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:7154
virtual bool expandPostRAPseudo(MachineInstr &MI) const { return false; }Called on pseudo instructions that remain after allocation. A useful pattern: during ISel, emit a pseudo with simple register constraints (so allocation is easy), and expand it here into the real sequence once registers are known. AArch64's MOVi32imm is an example: it is selected as a rematerialisable pseudo and expanded later.
Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:1228-1234, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:2559
findCommutedOpIndices, commuteInstructionImpl, convertToThreeAddress: see PHI Elimination and Two-Address Lowering.
| Hook | Status | Missing it causes |
|---|---|---|
copyPhysReg |
Required |
llvm_unreachable on the first COPY
|
storeRegToStackSlot, loadRegFromStackSlot
|
Required |
llvm_unreachable the first time anything spills |
isLoadFromStackSlot, isStoreToStackSlot
|
Recommended | Redundant spill code; no spill comments |
isReMaterializable / isReMaterializableImpl
|
Recommended | Constants spilled instead of recomputed |
isCopyInstrImpl |
Recommended if target moves survive ISel | Missed hints and copy propagation |
foldMemoryOperandImpl |
Optional | Extra loads on CISC targets |
expandPostRAPseudo |
As needed | Pseudos reach the AsmPrinter |
- 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