Repository navigation
Register Allocation 08 rewriting post ra
Relevant source files
The following files were used as context for generating this wiki page:
This page covers VirtRegRewriter in detail and the passes between it and prologue/epilogue insertion. The Fast allocator rewrites operands itself and does not use this pass.
bool VirtRegRewriter::run(MachineFunction &fn) {
...
// Add kill flags while we still have virtual registers.
LIS->addKillFlags(VRM);
// Live-in lists on basic blocks are required for physregs.
addMBBLiveIns();
// Rewrite virtual registers.
rewrite();
if (ClearVirtRegs) {
// Write out new DBG_VALUE instructions.
...
DebugVars->emitDebugValues(VRM);
// All machine operands and other references to virtual registers have been
// replaced. Remove the virtual registers and release all the transient data.
VRM->clearAllVirt();
MRI->clearVirtRegs();
}
return true;
}| Step | Why |
|---|---|
addKillFlags |
Liveness is about to be thrown away; killed flags on physical registers are what later passes (and the register scavenger) rely on |
addMBBLiveIns |
After allocation, each block must list the physical registers live on entry (liveins: in MIR). That is computed from each virtual register's interval and its assignment, per lane when sub-register liveness is on (addLiveInsForSubRanges) |
rewrite |
The actual operand replacement |
emitDebugValues |
LiveDebugVariables put back DBG_VALUEs that point at the final registers or stack slots |
clearVirtRegs |
No virtual registers remain; the function gets the NoVRegs property |
ClearVirtRegs is false when a target runs the allocator in several rounds (with filters) and only the last round's rewriter should clear everything.
Sources: llvm/lib/CodeGen/VirtRegMap.cpp:343-376, llvm/lib/CodeGen/VirtRegMap.cpp:378-424
for (MachineInstr &MI : llvm::make_early_inc_range(MBBI->instrs())) {
for (MachineOperand &MO : MI.operands()) {
// Make sure MRI knows about registers clobbered by regmasks.
if (MO.isRegMask())
MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
if (!MO.isReg() || !MO.getReg().isVirtual())
continue;
Register VirtReg = MO.getReg();
MCRegister PhysReg = VRM->getPhys(VirtReg);
...
RewriteRegs.insert(PhysReg);
assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
// Preserve semantics of sub-register operands.
unsigned SubReg = MO.getSubReg();
if (SubReg != 0) {
...For each virtual register operand:
- Look up its physical register in
VirtRegMap. It is a bug (assertion) if the allocator assigned a reserved register. - If the operand has a sub-register index, the result is the matching sub-register of the physical register.
%15.sub_32with%15 → $x9becomes$w9, as in the loop example. When sub-register liveness is not tracked, implicit operands are added for the full register so that writing half a register still counts as touching the whole of it. - Replace the operand. The rewritten operand is marked
renamable, which tells later passes (copy propagation, post-RA scheduling) that the allocator chose this register freely and it may be renamed. - Record the physical register as used (
RewriteRegs, and regmask clobbers viaaddPhysRegsUsedFromRegMask). Prologue/epilogue insertion uses the "used physical registers" set to decide which callee-saved registers to save.
Sources: llvm/lib/CodeGen/VirtRegMap.cpp:654-693
Once operands are rewritten, many COPYs have the same register on both sides. handleIdentityCopy deals with them:
void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) {
if (!MI.isIdentityCopy())
return;
...
// Copies like:
// %r0 = COPY undef %r0
// %al = COPY %al, implicit-def %eax
// give us additional liveness information: The target (super-)register
// must not be valid before this point. Replace the COPY with a KILL
// instruction to maintain this information.
if (MI.getOperand(1).isUndef() || MI.getNumOperands() > 2) {
MI.setDesc(TII->get(TargetOpcode::KILL));
return;
}
if (Indexes)
Indexes->removeSingleMachineInstrFromMaps(MI);
MI.eraseFromBundle();
}This is where all the hint work pays off. In the first example the COPYs %0 = COPY $w0, %1 = COPY $w1, %2 = COPY $w2 and $w0 = COPY %4 all became $wN = COPY $wN and were erased, leaving the single MADDWrrr.
Copy bundles created by splitting with sub-registers are expanded into separate copies (expandCopyBundle).
Sources: llvm/lib/CodeGen/VirtRegMap.cpp:492-528, llvm/lib/CodeGen/VirtRegMap.cpp:529
The call example (-stop-before=greedy versus -stop-after=virtregrewriter):
%1:gpr32 = COPY $w1 renamable $w19 = COPY $w1
%0:gpr32 = COPY $w0 (deleted: identity copy $w0 = COPY $w0)
ADJCALLSTACKDOWN 0, 0, ... ADJCALLSTACKDOWN 0, 0, ...
$w0 = COPY %0 (deleted: identity copy)
BL @g, csr_aarch64_aapcs, ... BL @g, csr_aarch64_aapcs, ...
ADJCALLSTACKUP 0, 0, ... ADJCALLSTACKUP 0, 0, ...
%2:gpr32 = COPY $w0 (deleted: identity copy)
$w0 = ADDWrr %2, %1 $w0 = ADDWrr killed renamable $w0, killed renamable $w19
RET_ReallyLR implicit $w0 RET_ReallyLR implicit $w0
%1 crosses the call, so it got callee-saved $w19, and its copy from $w1 remains as a real move (mov w19, w1). %0 and %2 got $w0 and their copies disappeared.
From the observed AArch64 -O2 pipeline (Pipeline):
| Pass | What it does for allocated code |
|---|---|
Stack Slot Coloring (stack-slot-coloring) |
Spill slots whose live ranges (from LiveStacks) do not overlap are merged, so the frame is smaller. It also removes load/store pairs made redundant by the merge |
addPostRewrite() |
Target hook; AArch64 adds a sub-register mitigation pass when enabled |
Machine Copy Propagation (machine-cp) |
Forwards the source of remaining physical-register copies into later uses and deletes copies that become dead |
Machine LICM (machinelicm, post-RA) |
Hoists loop-invariant reloads and rematerialised instructions out of loops |
addPostRegAlloc() |
Target hook; AArch64 runs redundant copy elimination and A57 FP load balancing |
| PostRA Machine Sinking, Shrink Wrapping (optimised builds only) | Sink copies toward their uses; choose where the prologue and epilogue go so cold paths avoid saving callee-saved registers |
Prologue/Epilogue Insertion (prologepilog) |
Saves and restores the callee-saved registers that were used, lays out the frame, and turns every frame index (%stack.N) into a concrete address by calling TargetRegisterInfo::eliminateFrameIndex
|
Post-RA pseudo expansion (ExpandPostRAPseudos) |
Lowers COPY to real instructions via TargetInstrInfo::copyPhysReg; target-specific pseudos via expandPostRAPseudo
|
Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1532-1548, llvm/lib/CodeGen/TargetPassConfig.cpp:1176-1206, llvm/lib/CodeGen/VirtRegMap.cpp:754
After the rewriter, a spill looks like STRWui killed renamable $w8, %stack.11, 0. The slot still has offset: 0 in the MIR stack: section. Prologue/epilogue insertion assigns each slot an offset from sp or the frame pointer and calls eliminateFrameIndex on every instruction that names a frame index. In the 24-load test, the final assembly shows the result: str w8, [sp, #32]. Later the AArch64 load/store optimiser paired neighbouring accesses into stp w8, w10, [sp, #48], which is why some spills print as "8-byte Folded Spill".
If the offset does not fit in the instruction's immediate, eliminateFrameIndex needs a scratch register. That is what the register scavenger provides after allocation; see TargetRegisterInfo Hooks.
- 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