Repository navigation
Frame Lowering 04 pei pass
Relevant source files
The following files were used as context for generating this wiki page:
The order of steps in PEIImpl::run and what each one does. The hooks themselves are on TargetFrameLowering Hooks.
bool PEIImpl::run(MachineFunction &MF) {
...
RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr;
FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(MF);
...
TFI->spillFPBP(MF);
...
calculateCallFrameInfo(MF);
...
calculateSaveRestoreBlocks(MF);
...
if (MF.getTarget().usesPhysRegsForValues())
spillCalleeSavedRegs(MF);
...
TFI->processFunctionBeforeFrameFinalized(MF, RS);
...
calculateFrameObjectOffsets(MF);
...
if (!F.hasFnAttribute(Attribute::Naked))
insertPrologEpilogCode(MF);
...
TFI->processFunctionBeforeFrameIndicesReplaced(MF, RS);
...
if (TFI->needsFrameIndexResolution(MF)) {
...
if (TRI->eliminateFrameIndicesBackwards())
replaceFrameIndicesBackward(MF);
else
replaceFrameIndices(MF);
}
...
if (TRI->requiresRegisterScavenging(MF) && FrameIndexVirtualScavenging)
scavengeFrameVirtualRegs(MF, *RS);flowchart TD
A["1. calculateCallFrameInfo<br/>max call frame size; remove call-frame pseudos"] --> B["2. calculateSaveRestoreBlocks<br/>entry + return blocks, or shrink-wrap points"]
B --> C["3. spillCalleeSavedRegs<br/>determineCalleeSaves, slots, save/restore code"]
C --> D["4. processFunctionBeforeFrameFinalized (target)"]
D --> E["5. calculateFrameObjectOffsets<br/>offset for every object, stack size"]
E --> F["6. insertPrologEpilogCode<br/>emitPrologue / emitEpilogue"]
F --> G["7. replaceFrameIndices<br/>eliminateFrameIndex per operand"]
G --> H["8. scavengeFrameVirtualRegs"]
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:211-283
calculateCallFrameInfo computes MaxCallFrameSize (the largest outgoing argument area) from the ADJCALLSTACKDOWN/UP pseudos. If the target can simplify them (canSimplifyCallFramePseudos, true when the call frame is reserved), it calls eliminateCallFramePseudoInstr on each one right away. Targets with no call-frame pseudos (opcode ~0u) skip the whole step.
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:370-407
// Use the points found by shrink-wrapping, if any.
if (!MFI.getSavePoints().empty()) {
...
SaveBlocks.push_back(SavePoint.first);
...
return;
}
// Save refs to entry and return blocks.
SaveBlocks.push_back(&MF.front());
for (MachineBasicBlock &MBB : MF) {
if (MBB.isEHFuncletEntry())
SaveBlocks.push_back(&MBB);
if (MBB.isReturnBlock())
RestoreBlocks.push_back(&MBB);
}Without shrink wrapping, the prologue goes in the entry block and an epilogue in every return block. A tail-call block (ending in TCRETURN) is a return block too, so it gets an epilogue before its jump.
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:411-443
// Determine which of the registers in the callee save list should be saved.
BitVector SavedRegs;
TFI->determineCalleeSaves(MF, SavedRegs, RS);
// Assign stack slots for any callee-saved registers that must be spilled.
assignCalleeSavedSpillSlots(MF, SavedRegs);
...
for (MachineBasicBlock *SaveBlock : SaveBlocks)
insertCSRSaves(*SaveBlock, CSI);insertCSRSaves (line 618) first offers the whole list to the target's spillCalleeSavedRegisters. If that returns false, it calls TargetFrameLowering::spillCalleeSavedRegister once per register, and that default calls TII->storeRegToStackSlot. insertCSRRestores (634) does the same before the block's first terminator, in reverse order, through restoreCalleeSavedRegister and loadRegFromStackSlot:
MachineBasicBlock::iterator I = SaveBlock.begin();
if (!TFI->spillCalleeSavedRegisters(SaveBlock, I, CSI, TRI)) {
for (const CalleeSavedInfo &CS : CSI) {
TFI->spillCalleeSavedRegister(SaveBlock, I, CS, TII, TRI);
}
}Details on Callee-Saved Registers.
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:652-700, llvm/lib/CodeGen/PrologEpilogInserter.cpp:618-650, llvm/lib/CodeGen/TargetFrameLoweringImpl.cpp:211-240
calculateFrameObjectOffsets walks the objects in a fixed order: past the fixed objects, then callee-saved slots, then the local block, then other objects (protected objects for stack protectors first), aligning each one. Offsets are measured in the direction of stack growth from the incoming SP:
// Start at the beginning of the local area.
// The Offset is the distance from the stack top in the direction
// of stack growth -- so it's always nonnegative.
int LocalAreaOffset = TFI.getOffsetOfLocalArea();At the end it adds MaxCallFrameSize if the call frame is reserved, then rounds up to the stack alignment. It uses getStackAlign() if the function has calls or allocas, otherwise getTransientStackAlign(), and in either case at least the largest object alignment. Finally it calls setStackSize. For AArch64 withcall the result is stackSize: 16 with x19 at offset −8 and lr at −16 (see MachineFrameInfo).
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:854-900, llvm/lib/CodeGen/PrologEpilogInserter.cpp:1112-1158
// Add prologue to the function...
for (MachineBasicBlock *SaveBlock : SaveBlocks)
TFI.emitPrologue(MF, *SaveBlock);
// Add epilogue to restore the callee-save registers in each exiting block.
for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
TFI.emitEpilogue(MF, *RestoreBlock);Then optional extras: zeroing call-used registers, inline stack probes, segmented stacks, HiPE. The prologue is emitted after the callee-saved stores already placed by step 3, so emitPrologue usually skips over them (they carry the FrameSetup flag).
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:1165-1199
replaceFrameIndices (line 1377) walks every instruction, tracks the SP adjustment between call-frame pseudos that were not removed, and calls TRI->eliminateFrameIndex for each frame-index operand. Targets that set eliminateFrameIndicesBackwards use replaceFrameIndicesBackward (1349), which lets the register scavenger run backwards in the same walk. Any virtual registers the target created during elimination are then given physical registers by scavengeFrameVirtualRegs. See Frame Index Elimination.
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:1349-1392
llc -O2 -mtriple=aarch64-linux-gnu -stop-before=prolog-epilog and -stop-after=prolog-epilog print the function on either side of this pass; the walkthroughs compare 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