LLVM Backend Guide
This guide combines seven wikis plus an assignment track into one reference for writing an LLVM code generator backend, from an empty target directory to -O2 object files. AArch64 is the real reference target throughout; a made-up "Toy" target is used for minimal examples, and every Toy code block is marked illustrative.
Purpose and Scope
The parts follow the order a function travels through the code generator, after the bring-up part that explains how all the pieces fit together. Links between parts were rewritten so the whole guide works as one page set.
Parts
| Part | Topic | What it covers |
|---|---|---|
| 1 | Target Bring-up End to End | Start here. The pieces of a backend, the order to write them in, and a minimal Toy target; every chapter points into the deeper parts below. |
| 2 | SelectionDAG Instruction Selection | How LLVM IR becomes machine instructions: DAG construction, combining, legalization, pattern matching and emission. |
| 3 | Calling Conventions and Call Lowering | CallingConv.td, CCState, LowerFormalArguments, LowerCall, LowerReturn, varargs, byval, sret and tail calls. |
| 4 | Instruction Scheduling | The scheduling DAG, MachineScheduler, register pressure, post-RA scheduling and the SchedMachineModel language. |
| 5 | Register Allocation | Liveness, coalescing, the allocators, spilling and splitting, and the register hooks a target provides. |
| 6 | Frame Lowering | Stack layout, prologue/epilogue insertion, callee-saved spills, frame index elimination, shrink wrapping and CFI. |
| 7 | The MC Layer | Streamers, the assembler, fixups and relocations, and the MC objects a backend writes for .s and .o output. |
| 8 | Hands-on Assignments: Build the Toy Backend | Fourteen stages, one per topic, that build a complete Toy backend step by step, ending with clang compiling C to Toy ELF objects. |
flowchart LR
IR["LLVM IR"] --> SD["Part 2: SelectionDAG<br/>(uses Part 3: call lowering)"]
SD --> MS["Part 4: pre-RA scheduling"]
MS --> RA["Part 5: register allocation"]
RA --> FL["Part 6: frame lowering"]
FL --> PS["Part 4: post-RA scheduling"]
PS --> MC["Part 7: MC layer (.s / .o)"]
Reading Paths
| Goal | Read |
|---|---|
| Bring up a new target | Part 1 in order, following its links into Parts 2–7 |
| Make functions and calls work | Bring-up calling conventions, then Part 3 |
Fix selection failures (Cannot select) | TargetLowering setup, then Part 2 legalization and pattern pages |
| Fix spills, register classes, CSRs | Part 5, especially its custom-backend section |
| Fix prologue/epilogue or stack offsets | Part 6 |
| Tune performance for a CPU | Part 4 |
| Emit object files, assembler, disassembler | Part 7 |
| Final checks | Bring-up checklist |
| Learn by building | Part 8: hands-on assignments, one stage per topic |
Provenance
- Parts 1 and 3–7 cite llvm/llvm-project at commit
a2171756dd5d690faf30bafe63810d1dc6cdb342; Part 2 (SelectionDAG) cites commit7a941df. Every Sources: line links to the exact lines at its commit. - All MIR and assembly output was produced by an LLVM 24.0.0git release
llc; options that need an assertions build are listed but not demonstrated.
Part 1: Target Bring-up End to End
Start here. The pieces of a backend, the order to write them in, and a minimal Toy target; every chapter points into the deeper parts below.
Pages
- 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
Target Bring-up Overview
Relevant source files
The following files were used as context for generating this wiki page:
An LLVM backend is a set of C++ classes and TableGen files under llvm/lib/Target/<T>/. The generic code generator calls them through a few interfaces: TargetMachine, TargetSubtargetInfo, TargetLowering, TargetInstrInfo, TargetRegisterInfo, TargetFrameLowering, and the MC layer objects. This wiki walks through writing each piece for a new target, in the order you would write them, using AArch64 as the real reference and a made-up "Toy" target for minimal examples.
Purpose and Scope
This wiki covers the whole path from an empty directory to a target that compiles a function to assembly and then to object files. It ties together six other wikis:
| Wiki | What it covers in depth |
|---|---|
| SelectionDAG | Turning LLVM IR into machine instructions |
| Register allocation | Assigning physical registers, spilling |
| MC layer | Printing assembly, encoding, object files |
| Calling conventions | Arguments, returns, calls |
| Frame lowering | Prologue, epilogue, stack layout |
| Instruction scheduling | Machine scheduler and scheduling models |
Each page here explains what the piece is, shows what AArch64 does, gives a minimal Toy version, and links to the wiki that goes deeper.
The Pieces of a Backend
flowchart TD
TI["TargetInfo: getTheToyTarget()"] --> TM["ToyTargetMachine"]
TD["Toy.td + included .td files"] -->|llvm-tblgen| GEN["ToyGen*.inc"]
TM --> ST["ToySubtarget"]
ST --> TL["ToyTargetLowering"]
ST --> TII["ToyInstrInfo"]
ST --> TRI["ToyRegisterInfo"]
ST --> TFL["ToyFrameLowering"]
TM --> PC["ToyPassConfig"]
PC --> ISEL["ToyDAGToDAGISel"]
TM --> AP["ToyAsmPrinter"]
AP --> MC["MC layer: MCAsmInfo, InstPrinter, CodeEmitter, AsmBackend"]
GEN --> TL
GEN --> TII
GEN --> TRI
GEN --> ISEL
GEN --> MC
| Piece | Base class | Job | Page |
|---|---|---|---|
| Target registration | Target, TargetRegistry | Lets tools find the target by name or triple | Layout and CMake |
| Target description | TableGen Target | Registers, instructions, calling conventions, processors | The Target .td File |
| Target machine | CodeGenTargetMachineImpl | Data layout, pass pipeline, subtarget cache | TargetMachine and Subtarget |
| Subtarget | TargetSubtargetInfo | Owns the per-CPU objects listed below | TargetMachine and Subtarget |
| Lowering | TargetLowering | Legal types, operation actions, custom lowering | TargetLowering Setup |
| Calling convention | TableGen CallingConv, LowerCall etc. | Arguments and returns | Calling Conventions |
| Instructions and selection | TargetInstrInfo, SelectionDAGISel | Instruction definitions and patterns | Instructions and ISel |
| Registers | TargetRegisterInfo | Register classes, reserved registers, allocation hooks | Registers and Allocation |
| Frame | TargetFrameLowering | Prologue, epilogue, stack offsets | Frame Lowering |
| Printing and encoding | AsmPrinter, MC classes | .s and .o output | AsmPrinter and MC |
| Scheduling model | TableGen SchedMachineModel | Latencies and resources | Scheduling |
Order the Pieces Run In
For each function, llc runs the pass pipeline built by the target's TargetPassConfig. The order below is from llc -O2 -debug-pass=Structure for aarch64-linux-gnu (-mcpu=cortex-a57), shortened:
... -codegenprepare ... -aarch64-isel -finalize-isel ...
-machine-cse -machine-sink -peephole-opt ...
-phi-node-elimination -twoaddressinstruction -liveintervals -register-coalescer
-machine-scheduler ... -greedy -virtregrewriter ...
-shrink-wrap -prolog-epilog ... -postrapseudos -aarch64-expand-pseudo
-aarch64-ldst-opt ... -postmisched ... -block-placement ...
-branch-relaxation ... -aarch64-asm-printer
flowchart LR
IR["LLVM IR"] --> ISEL["Instruction selection<br/>(TargetLowering, CC, patterns)"]
ISEL --> PRE["SSA machine opts"]
PRE --> MS["MachineScheduler<br/>(sched model)"]
MS --> RA["Register allocation<br/>(TargetRegisterInfo)"]
RA --> PEI["Shrink wrap + PEI<br/>(TargetFrameLowering)"]
PEI --> POST["Post-RA passes,<br/>post-RA scheduler"]
POST --> AP["AsmPrinter -> MC"]
Instruction selection is where TargetLowering and the calling convention are used. The scheduling model is consulted by the machine scheduler before allocation and again after it. Frame lowering runs after allocation, because only then is it known which callee-saved registers are used and how many spill slots exist.
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:580-615, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:760-770
A First Milestone
The first useful goal is one function compiled to assembly. For AArch64 this IR:
define i32 @add(i32 %a, i32 %b) {
%s = add i32 %a, %b
ret i32 %s
}
gives, with llc -O2 -mtriple=aarch64-linux-gnu:
add: // @add
.cfi_startproc
add w0, w0, w1
ret
.Lfunc_end0:
.cfi_endproc
To get this far a target needs every piece in the table above except the code emitter, asm backend and scheduling model. A Minimal Toy Target shows the smallest version of each, and the checklist lists the milestones after it.
How to Read This Wiki
- Layout and CMake: files, libraries, registration.
- The Target .td File: the TableGen root.
- TargetMachine and Subtarget.
- TargetLowering Setup.
- Calling Conventions.
- Instructions and ISel.
- Registers and Allocation.
- Frame Lowering.
- AsmPrinter and MC.
- Scheduling.
- A Minimal Toy Target.
- Bring-up Checklist.
- Tooling and Glossary.
Directory Layout, CMake and Registration
Relevant source files
The following files were used as context for generating this wiki page:
A target lives in llvm/lib/Target/<T>/ and is built as several small libraries. Each library exports an LLVMInitialize<T>... function that registers its part with TargetRegistry. Tools such as llc call all of these functions at startup and then look the target up by name (-march=toy) or by triple (-mtriple=toy-unknown-elf).
Purpose and Scope
The files and directories a target needs, how CMake builds them, how LLVM_TARGETS_TO_BUILD selects targets, and the registration functions. Instruction and register TableGen are on The Target .td File.
Directory Layout
| Directory | Contents | Library | Init function |
|---|---|---|---|
lib/Target/<T>/ | <T>.td, <T>TargetMachine, <T>Subtarget, <T>ISelLowering, <T>ISelDAGToDAG, <T>InstrInfo, <T>RegisterInfo, <T>FrameLowering, <T>AsmPrinter, <T>MCInstLower | LLVM<T>CodeGen | LLVMInitialize<T>Target, LLVMInitialize<T>AsmPrinter |
lib/Target/<T>/TargetInfo/ | getThe<T>Target() | LLVM<T>Info | LLVMInitialize<T>TargetInfo |
lib/Target/<T>/MCTargetDesc/ | MC objects (asm info, printer, code emitter, asm backend) | LLVM<T>Desc | LLVMInitialize<T>TargetMC |
lib/Target/<T>/AsmParser/ | Assembly parser | LLVM<T>AsmParser | LLVMInitialize<T>AsmParser |
lib/Target/<T>/Disassembler/ | Disassembler | LLVM<T>Disassembler | LLVMInitialize<T>Disassembler |
The TargetInfo library is tiny and depends on nothing else in the target, so tools that only need the target's name can link it alone. The MC libraries must not depend on CodeGen (see the MC custom backend page).
Choosing Targets to Build
llvm/CMakeLists.txt lists the core targets in LLVM_ALL_TARGETS and the experimental ones in LLVM_ALL_EXPERIMENTAL_TARGETS. LLVM_TARGETS_TO_BUILD defaults to all core targets; a new target starts as experimental and is enabled with LLVM_EXPERIMENTAL_TARGETS_TO_BUILD.
set(LLVM_ALL_TARGETS
AArch64
AMDGPU
...
X86
XCore
)
set(LLVM_ALL_EXPERIMENTAL_TARGETS
ARC
CSKY
M68k
Xtensa
)
For a new target, configure with -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=Toy (and, to save build time, -DLLVM_TARGETS_TO_BUILD=AArch64 or similar). CMake checks every requested name against these lists and stops with an error listing the valid names if one is unknown.
Sources: llvm/CMakeLists.txt:578-607, llvm/CMakeLists.txt:716, llvm/CMakeLists.txt:1157-1165
The Target's CMakeLists.txt
AArch64's file does three things:
- Names the root TableGen file:
set(LLVM_TARGET_DEFINITIONS AArch64.td). - Runs
llvm-tblgenonce per backend, each producing one.incfile:
tablegen(LLVM AArch64GenAsmMatcher.inc -gen-asm-matcher)
tablegen(LLVM AArch64GenAsmWriter.inc -gen-asm-writer)
tablegen(LLVM AArch64GenCallingConv.inc -gen-callingconv)
tablegen(LLVM AArch64GenDAGISel.inc -gen-dag-isel)
tablegen(LLVM AArch64GenDisassemblerTables.inc -gen-disassembler)
tablegen(LLVM AArch64GenInstrInfo.inc -gen-instr-info)
tablegen(LLVM AArch64GenMCCodeEmitter.inc -gen-emitter)
tablegen(LLVM AArch64GenRegisterInfo.inc -gen-register-info)
tablegen(LLVM AArch64GenSubtargetInfo.inc -gen-subtarget)
...
add_public_tablegen_target(AArch64CommonTableGen)
- Declares the CodeGen library with
add_llvm_target(AArch64CodeGen ...)listing the.cppfiles andLINK_COMPONENTS, then adds the subdirectories (TargetInfo,MCTargetDesc,AsmParser,Disassembler,Utils).
The first line, add_llvm_component_group(AArch64 HAS_JIT), creates the AArch64 component name used by llvm-config and by other components' LINK_COMPONENTS.
tablegen backend |
Output used by | Needed for first milestone |
|---|---|---|
-gen-register-info | <T>RegisterInfo, MC register info | Yes |
-gen-instr-info | <T>InstrInfo, MC instr info | Yes |
-gen-subtarget | <T>Subtarget, scheduling model | Yes |
-gen-callingconv | <T>ISelLowering.cpp | Yes |
-gen-dag-isel | <T>ISelDAGToDAG.cpp | Yes |
-gen-asm-writer | <T>InstPrinter | Yes |
-gen-emitter | <T>MCCodeEmitter | For .o |
-gen-asm-matcher | <T>AsmParser | For .s input |
-gen-disassembler | <T>Disassembler | For llvm-objdump |
Sources: llvm/lib/Target/AArch64/CMakeLists.txt:1-33
Registration
sequenceDiagram
participant llc
participant Info as LLVMInitializeToyTargetInfo
participant TM as LLVMInitializeToyTarget
participant MC as LLVMInitializeToyTargetMC
participant AP as LLVMInitializeToyAsmPrinter
llc->>Info: RegisterTarget (name, description, triple arch)
llc->>TM: RegisterTargetMachine, initialize passes
llc->>MC: Register MCAsmInfo, InstrInfo, RegInfo, ...
llc->>AP: RegisterAsmPrinter
llc->>llc: TargetRegistry::lookupTarget(triple)
TargetInfo
Each target is a single static Target object returned by a function. RegisterTarget<Arch, HasJIT> binds it to a Triple::ArchType, a short name for -march, and a description:
Target &llvm::getTheAArch64leTarget() {
static Target TheAArch64leTarget;
return TheAArch64leTarget;
}
...
extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
LLVMInitializeAArch64TargetInfo() {
...
RegisterTarget<Triple::aarch64, /*HasJIT=*/true> Z(
getTheAArch64leTarget(), "aarch64", "AArch64 (little endian)", "AArch64");
...
}
A new architecture also needs an entry in Triple::ArchType and the triple parser (llvm/lib/TargetParser/Triple.cpp), so that toy-unknown-elf parses to Triple::toy. The data layout for the triple is computed in llvm/lib/TargetParser/TargetDataLayout.cpp (see TargetMachine and Subtarget).
Sources: llvm/lib/Target/AArch64/TargetInfo/AArch64TargetInfo.cpp:14-52
Target machine, MC and AsmPrinter
LLVMInitializeAArch64Target registers the target machine class for each Target object and initializes the target's own machine passes so they can be named on the command line:
extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
LLVMInitializeAArch64Target() {
// Register the target.
RegisterTargetMachine<AArch64leTargetMachine> X(getTheAArch64leTarget());
RegisterTargetMachine<AArch64beTargetMachine> Y(getTheAArch64beTarget());
...
auto &PR = *PassRegistry::getPassRegistry();
initializeGlobalISel(PR);
initializeAArch64A53Fix835769LegacyPass(PR);
...
}
The AsmPrinter is registered from the CodeGen library too:
LLVMInitializeAArch64AsmPrinter() {
RegisterAsmPrinter<AArch64AsmPrinter> X(getTheAArch64leTarget());
RegisterAsmPrinter<AArch64AsmPrinter> Y(getTheAArch64beTarget());
...
}
MC registration (LLVMInitializeAArch64TargetMC) is shown on the MC custom backend page.
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:234-287, llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp:4187-4192
Minimal Files for Toy (Illustrative)
Illustrative, not LLVM source.
# lib/Target/Toy/CMakeLists.txt (illustrative)
add_llvm_component_group(Toy)
set(LLVM_TARGET_DEFINITIONS Toy.td)
tablegen(LLVM ToyGenRegisterInfo.inc -gen-register-info)
tablegen(LLVM ToyGenInstrInfo.inc -gen-instr-info)
tablegen(LLVM ToyGenSubtargetInfo.inc -gen-subtarget)
tablegen(LLVM ToyGenCallingConv.inc -gen-callingconv)
tablegen(LLVM ToyGenDAGISel.inc -gen-dag-isel)
tablegen(LLVM ToyGenAsmWriter.inc -gen-asm-writer)
tablegen(LLVM ToyGenMCCodeEmitter.inc -gen-emitter)
add_public_tablegen_target(ToyCommonTableGen)
add_llvm_target(ToyCodeGen
ToyAsmPrinter.cpp ToyFrameLowering.cpp ToyInstrInfo.cpp
ToyISelDAGToDAG.cpp ToyISelLowering.cpp ToyMCInstLower.cpp
ToyRegisterInfo.cpp ToySubtarget.cpp ToyTargetMachine.cpp
LINK_COMPONENTS
AsmPrinter CodeGen CodeGenTypes Core MC SelectionDAG Support Target
TargetParser ToyDesc ToyInfo
ADD_TO_COMPONENT Toy)
add_subdirectory(MCTargetDesc)
add_subdirectory(TargetInfo)
// TargetInfo/ToyTargetInfo.cpp (illustrative)
Target &llvm::getTheToyTarget() {
static Target TheToyTarget;
return TheToyTarget;
}
extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeToyTargetInfo() {
RegisterTarget<Triple::toy> X(getTheToyTarget(), "toy", "Toy example", "Toy");
}
After this step llc --version lists toy under "Registered Targets", even before the target machine exists.
The Target .td File
Relevant source files
The following files were used as context for generating this wiki page:
<T>.td is the root TableGen file of a target. llvm-tblgen reads it, follows its include lines, and every -gen-* backend listed in the target's CMakeLists.txt produces one .inc file from the same set of records. The file itself is short: it includes the generic Target.td, includes the target's own .td files in dependency order, and ends with one def <T> : Target record.
Purpose and Scope
What goes in <T>.td, the order of includes, how processors and features are declared, and the Target record. Registers are covered by the regalloc TableGen page, instructions and patterns by the SelectionDAG pattern language page, calling conventions by the calling conventions wiki and scheduling models by the scheduling wiki.
Include Order
TableGen is single pass: a record can only refer to records defined earlier. AArch64's root file therefore includes, in order:
| Line | Include | Defines |
|---|---|---|
| 16 | llvm/Target/Target.td | Generic classes: Register, RegisterClass, Instruction, Target, Processor, CallingConv, SchedMachineModel, ... |
| 21-22 | AArch64Features.td, AArch64FMV.td | SubtargetFeature records and predicates |
| 28-30 | AArch64RegisterInfo.td, AArch64RegisterBanks.td, AArch64CallingConvention.td | Registers, classes, banks, calling conventions (which name registers) |
| 36-41 | AArch64Schedule.td, AArch64InstrInfo.td, scheduling predicates, AArch64Combine.td | SchedWrite types first, then instructions that use them |
| 45 | def AArch64InstrInfo : InstrInfo; | The instruction set record |
| 125-155 | AArch64Sched*.td | One SchedMachineModel per CPU family |
| 157 | AArch64Processors.td | ProcessorModel records tying CPU names to models and features |
| 163-194 | Parser and writer variants | AsmParserVariant, AsmWriter |
| 200-205 | def AArch64 : Target | The root record |
AArch64Schedule.td comes before AArch64InstrInfo.td because instruction definitions list SchedWrite/SchedRead types (Sched<[WriteI, ReadI, ReadI]>). The per-CPU models come after the instructions because InstRW refers to instruction names.
Sources: llvm/lib/Target/AArch64/AArch64.td:16-58, llvm/lib/Target/AArch64/AArch64.td:125-157
The Target Record
def GenericAsmWriter : AsmWriter {
string AsmWriterClassName = "InstPrinter";
int PassSubtarget = 1;
int Variant = 0;
bit isMCAsmWriter = 1;
}
...
def AArch64 : Target {
let InstructionSet = AArch64InstrInfo;
let AssemblyParserVariants = [GenericAsmParserVariant, AppleAsmParserVariant];
let AssemblyWriters = [GenericAsmWriter, AppleAsmWriter];
let AllowRegisterRenaming = 1;
}
| Field | Meaning |
|---|---|
InstructionSet | The InstrInfo record; required |
AssemblyWriters | Printer variants; AsmWriterClassName gives the generated class name <T><Name> (here AArch64InstPrinter) |
AssemblyParserVariants | Parser variants for -gen-asm-matcher |
AllowRegisterRenaming | Lets post-RA passes rename registers (only safe if the target has no hidden register constraints) |
The record's name (AArch64) is the target name TableGen uses for generated identifiers: AArch64GenInstrInfo, AArch64GenRegisterInfo, the AArch64:: namespace for opcodes and registers.
Sources: llvm/lib/Target/AArch64/AArch64.td:163-205
Processors and Features
A SubtargetFeature becomes a boolean field of the generated subtarget (HasSVE and so on) and a -mattr= name. A ProcessorModel names a CPU for -mcpu=, its scheduling model and its features:
def : ProcessorModel<"cortex-a57", CortexA57Model, ProcessorFeatures.A53,
[TuneA57]>;
-gen-subtarget turns these into tables in <T>GenSubtargetInfo.inc, and the generated ParseSubtargetFeatures(CPU, TuneCPU, FS) sets the feature fields from them. The TargetMachine and Subtarget page shows where that function is called; the scheduling wiki covers the scheduling model argument.
Sources: llvm/lib/Target/AArch64/AArch64Processors.td:1312-1313
Minimal Toy.td (Illustrative)
Illustrative, not LLVM source. Each included file is sketched on the page named in the comment.
include "llvm/Target/Target.td"
// Features and processors
def FeatureMul : SubtargetFeature<"mul", "HasMul", "true", "Has MUL">;
include "ToyRegisterInfo.td" // Registers and Allocation
include "ToyCallingConv.td" // Calling Conventions
include "ToySchedule.td" // Scheduling (SchedWrite types)
include "ToyInstrInfo.td" // Instructions and ISel
def ToyInstrInfo : InstrInfo;
def : ProcessorModel<"generic", NoSchedModel, []>;
def : ProcessorModel<"toy2", ToyModel, [FeatureMul]>;
def Toy : Target {
let InstructionSet = ToyInstrInfo;
}
NoSchedModel (from TargetSchedule.td) is fine at first; add a real model when you care about performance.
Checking the Records
llvm-tblgen can print every record after parsing, which is the fastest way to find TableGen errors before CMake runs all the backends:
llvm-tblgen -print-records -I llvm/include -I llvm/lib/Target/Toy llvm/lib/Target/Toy/Toy.td
Each backend can also be run by hand, for example -gen-register-info to look at the generated register enum.
TargetMachine and Subtarget
Relevant source files
The following files were used as context for generating this wiki page:
The target machine is created once per compilation. It fixes the data layout, relocation model and code model, creates the pass pipeline, and hands out a subtarget for each function. The subtarget is created per combination of CPU and features; it owns the objects the code generator actually calls: TargetLowering, TargetInstrInfo, TargetRegisterInfo and TargetFrameLowering.
Purpose and Scope
The <T>TargetMachine constructor, the data layout string, per-function subtarget lookup, and what the subtarget must own. The pass pipeline hooks are summarized here; the regalloc wiki's pass config hooks page covers the ones around register allocation.
Object Ownership
classDiagram
class ToyTargetMachine {
TLOF : TargetLoweringObjectFile
SubtargetMap
getSubtargetImpl(Function)
createPassConfig(PM)
}
class ToySubtarget {
InstrInfo : ToyInstrInfo
FrameLowering : ToyFrameLowering
TLInfo : ToyTargetLowering
feature bits (generated)
}
class ToyInstrInfo { RI : ToyRegisterInfo }
ToyTargetMachine --> ToySubtarget : creates, caches
ToySubtarget --> ToyInstrInfo
ToySubtarget --> ToyFrameLowering
ToySubtarget --> ToyTargetLowering
ToyInstrInfo --> ToyRegisterInfo
The Constructor
AArch64TargetMachine::AArch64TargetMachine(const Target &T, const Triple &TT,
StringRef CPU, StringRef FS,
const TargetOptions &Options,
std::optional<Reloc::Model> RM,
std::optional<CodeModel::Model> CM,
CodeGenOptLevel OL, bool JIT,
bool LittleEndian)
: CodeGenTargetMachineImpl(T, TT.computeDataLayout(), TT,
computeDefaultCPU(TT, CPU), FS, Options,
getEffectiveRelocModel(TT, RM),
getEffectiveAArch64CodeModel(TT, CM, JIT), OL),
TLOF(createTLOF(getTargetTriple())), isLittle(LittleEndian) {
initAsmInfo();
...
}
| Argument / step | What a new target supplies |
|---|---|
| Data layout | TT.computeDataLayout() (see below) |
| Relocation model | A helper that picks a default when RM is empty (AArch64: static on ELF, PIC on Darwin/Windows) |
| Code model | A helper that rejects unsupported models and picks a default |
TLOF | A TargetLoweringObjectFile subclass (usually TargetLoweringObjectFileELF) that chooses sections for globals |
initAsmInfo() | Must be called in the constructor: it creates MCAsmInfo, MCRegisterInfo, MCInstrInfo, MCSubtargetInfo from the MC registry |
The rest of AArch64's constructor sets target options (trap on unreachable for Mach-O, TLS size, GlobalISel at -O0, the machine outliner); a new target can leave these out.
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:304-429
The Data Layout String
At this commit the data layout is not written in the target: Triple::computeDataLayout switches on the architecture and calls one function per target in llvm/lib/TargetParser/TargetDataLayout.cpp. For AArch64 ELF:
std::string Endian = TT.isLittleEndian() ? "e" : "E";
std::string Ptr32 = TT.getEnvironment() == Triple::GNUILP32 ? "-p:32:32" : "";
return Endian + "-m:e" + Ptr32 +
"-p270:32:32-p271:32:32-p272:64:64-i8:8:32-i16:16:32-i64:64-i128:128-"
"n32:64-S128-Fn32";
| Part | Meaning |
|---|---|
e | Little endian |
m:e | ELF name mangling (private symbols start with .L) |
p270:32:32 ... | Pointer sizes for special address spaces (pointer size in address space 0 defaults to 64) |
i64:64, i128:128 | ABI alignment of integer types |
i8:8:32 | i8 ABI alignment 8 bits, preferred 32 |
n32:64 | Native integer widths |
S128 | Stack alignment 128 bits |
Fn32 | Function pointer alignment is independent of function alignment, 32 bits |
A new target adds a case Triple::toy: there returning its string. The string must agree with what TargetLowering says is legal, and with the stack alignment given to TargetFrameLowering.
Sources: llvm/lib/TargetParser/TargetDataLayout.cpp:81-97, llvm/lib/TargetParser/TargetDataLayout.cpp:565-575
Per-Function Subtargets
Functions can carry "target-cpu", "tune-cpu" and "target-features" attributes, so the subtarget is looked up per function. AArch64 builds a key from the CPU, features and other options and caches one subtarget per key:
const AArch64Subtarget *
AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
Attribute CPUAttr = F.getFnAttribute("target-cpu");
Attribute TuneAttr = F.getFnAttribute("tune-cpu");
Attribute FSAttr = F.getFnAttribute("target-features");
StringRef CPU = CPUAttr.isValid() ? CPUAttr.getValueAsString() : TargetCPU;
StringRef TuneCPU = TuneAttr.isValid() ? TuneAttr.getValueAsString() : CPU;
StringRef FS = FSAttr.isValid() ? FSAttr.getValueAsString() : TargetFS;
...
auto &I = SubtargetMap[Key];
if (!I) {
I = std::make_unique<AArch64Subtarget>(
TargetTriple, CPU, TuneCPU, FS, *this, isLittle, MinSVEVectorSize,
...);
}
...
return I.get();
}
A simple target can use CPU + FS as the key.
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:437-507
The Subtarget
The subtarget class derives from the generated <T>GenSubtargetInfo and holds the per-CPU objects as members. Member order matters: InstrInfo is initialized from initializeSubtargetDependencies, which parses the features first, so that later members (and the instruction info) see the right feature bits.
AArch64Subtarget::AArch64Subtarget(const Triple &TT, StringRef CPU,
StringRef TuneCPU, StringRef FS,
const TargetMachine &TM, bool LittleEndian,
...)
: AArch64GenSubtargetInfo(TT, CPU, TuneCPU, FS),
...
TargetTriple(TT),
InstrInfo(initializeSubtargetDependencies(FS, CPU, TuneCPU, HasMinSize)),
TLInfo(TM, *this) {
AArch64Subtarget &AArch64Subtarget::initializeSubtargetDependencies(
StringRef FS, StringRef CPUString, StringRef TuneCPUString,
bool HasMinSize) {
if (CPUString.empty())
CPUString = "generic";
if (TuneCPUString.empty())
TuneCPUString = CPUString;
ParseSubtargetFeatures(CPUString, TuneCPUString, FS);
initializeProperties(HasMinSize);
return *this;
}
The members in AArch64Subtarget.h include AArch64FrameLowering FrameLowering;, AArch64InstrInfo InstrInfo; and AArch64TargetLowering TLInfo;. The subtarget overrides the TargetSubtargetInfo getters to return them:
Getter (TargetSubtargetInfo) |
Default | Must override |
|---|---|---|
getInstrInfo() | nullptr | Yes |
getFrameLowering() | nullptr | Yes |
getTargetLowering() | nullptr | Yes |
getRegisterInfo() | pure virtual | Yes |
getSelectionDAGInfo() | nullptr | Usually (generated SDNodeInfo) |
enableMachineScheduler() | false | Recommended; AArch64 returns true |
enablePostRAScheduler() | false | Optional |
AArch64 also creates its GlobalISel objects in the constructor body; a SelectionDAG-only target does not need them.
Sources: llvm/lib/Target/AArch64/AArch64Subtarget.cpp:110-125, llvm/lib/Target/AArch64/AArch64Subtarget.cpp:351-395, llvm/lib/Target/AArch64/AArch64Subtarget.h:101-104, llvm/lib/Target/AArch64/AArch64Subtarget.h:144-161, llvm/include/llvm/CodeGen/TargetSubtargetInfo.h:111-142, llvm/include/llvm/CodeGen/TargetSubtargetInfo.h:225-255
The Pass Config
createPassConfig returns a TargetPassConfig subclass. The only hook a SelectionDAG target must override is addInstSelector, which adds the target's SelectionDAGISel pass:
TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
return new AArch64PassConfig(*this, PM);
}
...
bool AArch64PassConfig::addInstSelector() {
addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
...
return false;
}
AArch64PassConfig overrides about twenty hooks (addIRPasses, addPreISel, addPreRegAlloc, addPostRegAlloc, addPreSched2, addPreEmitPass, ...) to add its own passes. Its constructor also swaps the old post-RA list scheduler for the post-RA machine scheduler when optimizing: substitutePass(&PostRASchedulerID, &PostMachineSchedulerID) (see the scheduling wiki).
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:580-615, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:640-642, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:760-770
Minimal Toy Versions (Illustrative)
Illustrative, not LLVM source.
// ToySubtarget.h (illustrative)
class ToySubtarget : public ToyGenSubtargetInfo {
bool HasMul = false; // set by ParseSubtargetFeatures
ToyInstrInfo InstrInfo;
ToyFrameLowering FrameLowering;
ToyTargetLowering TLInfo;
SelectionDAGTargetInfo TSInfo;
public:
ToySubtarget(const Triple &TT, StringRef CPU, StringRef FS,
const TargetMachine &TM)
: ToyGenSubtargetInfo(TT, CPU, CPU, FS),
InstrInfo(initDeps(CPU, FS)), FrameLowering(),
TLInfo(TM, *this) {}
ToySubtarget &initDeps(StringRef CPU, StringRef FS) {
ParseSubtargetFeatures(CPU.empty() ? "generic" : CPU, CPU, FS);
return *this;
}
void ParseSubtargetFeatures(StringRef CPU, StringRef TuneCPU, StringRef FS);
const ToyInstrInfo *getInstrInfo() const override { return &InstrInfo; }
const ToyRegisterInfo *getRegisterInfo() const override {
return &InstrInfo.getRegisterInfo();
}
const ToyFrameLowering *getFrameLowering() const override { return &FrameLowering; }
const ToyTargetLowering *getTargetLowering() const override { return &TLInfo; }
const SelectionDAGTargetInfo *getSelectionDAGInfo() const override { return &TSInfo; }
bool enableMachineScheduler() const override { return true; }
};
// ToyTargetMachine.cpp (illustrative)
ToyTargetMachine::ToyTargetMachine(const Target &T, const Triple &TT,
StringRef CPU, StringRef FS, const TargetOptions &Options,
std::optional<Reloc::Model> RM, std::optional<CodeModel::Model> CM,
CodeGenOptLevel OL, bool JIT)
: CodeGenTargetMachineImpl(T, TT.computeDataLayout(), TT, CPU, FS, Options,
RM.value_or(Reloc::Static),
getEffectiveCodeModel(CM, CodeModel::Small), OL),
TLOF(std::make_unique<TargetLoweringObjectFileELF>()),
Subtarget(TT, CPU, FS, *this) {
initAsmInfo();
}
namespace {
class ToyPassConfig : public TargetPassConfig {
public:
ToyPassConfig(ToyTargetMachine &TM, PassManagerBase &PM)
: TargetPassConfig(TM, PM) {}
bool addInstSelector() override {
addPass(createToyISelDag(getTM<ToyTargetMachine>(), getOptLevel()));
return false;
}
};
}
TargetPassConfig *ToyTargetMachine::createPassConfig(PassManagerBase &PM) {
return new ToyPassConfig(*this, PM);
}
extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeToyTarget() {
RegisterTargetMachine<ToyTargetMachine> X(getTheToyTarget());
}
A single subtarget member is enough until the target needs per-function CPUs or features; then switch to a cache like AArch64's SubtargetMap.
TargetLowering Setup
Relevant source files
The following files were used as context for generating this wiki page:
<T>TargetLowering tells SelectionDAG what the target can do natively. Its constructor runs once per subtarget and fills in tables: which value types live in which register class, and for each (operation, type) pair whether the operation is Legal, should be Promoted, Expanded into other operations, turned into a library call, or handled by target code (Custom). The legalizer and DAG combiner read those tables; the target only writes code for the Custom cases.
Purpose and Scope
The constructor of TargetLowering: register classes, computeRegisterProperties, operation actions, and the LowerOperation hook for Custom. How the legalizer uses these tables is covered by the SelectionDAG wiki's legalization, type legalization and operation and vector legalization pages. The call-lowering hooks on the same class are covered on Calling Conventions.
The Constructor in Three Steps
flowchart TD
A["addRegisterClass(VT, RC) for each legal type"] --> B["computeRegisterProperties(TRI)"]
B --> C["setOperationAction / setLoadExtAction / setTruncStoreAction / setCondCodeAction"]
C --> D["other settings: boolean contents, stack pointer register, alignment, libcalls"]
1. Register classes make types legal
A type is legal exactly when a register class has been added for it:
AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
const AArch64Subtarget &STI)
: TargetLowering(TM, STI), Subtarget(&STI) {
// AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
// we have to make something up. Arbitrarily, choose ZeroOrOne.
setBooleanContents(ZeroOrOneBooleanContent);
...
// Set up the register classes.
addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
...
if (Subtarget->hasFPARMv8()) {
...
addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
Feature checks (hasFPARMv8(), hasLS64()) mean the set of legal types depends on the subtarget. i8 and i16 get no class on AArch64, so the type legalizer promotes them to i32.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:475-500
2. computeRegisterProperties
After all classes are added, one call derives the rest of the type tables (how each illegal type is promoted, expanded or split, the number of registers per type):
// Compute derived properties from the register classes
computeRegisterProperties(Subtarget->getRegisterInfo());
It must come after the last addRegisterClass and before code that queries isTypeLegal.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:566-567
3. Operation actions
Every operation on a legal type defaults to Legal. The target lists the exceptions:
// Provide all sorts of operation actions
setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
setOperationAction(ISD::SETCC, MVT::i32, Custom);
setOperationAction(ISD::SETCC, MVT::i64, Custom);
...
setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
...
setOperationAction(ISD::SREM, MVT::i32, Expand);
setOperationAction(ISD::SREM, MVT::i64, Expand);
| Action | Meaning | Who does the work |
|---|---|---|
Legal | A pattern selects it directly | TableGen patterns |
Promote | Do it in a wider type | Legalizer |
Expand | Rewrite into other nodes (for SREM: divide, multiply, subtract) or a libcall | Legalizer |
LibCall | Call a runtime function | Legalizer |
Custom | Call LowerOperation | Target code |
AArch64 marks GlobalAddress Custom because the address needs a target-specific sequence (adrp + add :lo12:) that depends on the code model. SREM is Expand because there is no remainder instruction.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:569-575, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:783-790
Custom Lowering
For every Custom entry the legalizer calls LowerOperation(SDValue Op, SelectionDAG &DAG). The usual form is a switch on the opcode that dispatches to one function per node:
// ToyISelLowering.cpp (illustrative, not LLVM source)
SDValue ToyTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
switch (Op.getOpcode()) {
case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
case ISD::BR_CC: return LowerBR_CC(Op, DAG);
default: llvm_unreachable("unexpected custom lowering");
}
}
Custom lowering usually produces target-specific nodes (ToyISD::HI, ToyISD::LO, ToyISD::CALL). Their opcodes and type profiles are declared in TableGen (SDNode records) and matched by patterns; see Instructions and ISel.
Minimal Toy Constructor (Illustrative)
Illustrative, not LLVM source. A 32-bit target with one GPR class and no floating point:
ToyTargetLowering::ToyTargetLowering(const TargetMachine &TM,
const ToySubtarget &STI)
: TargetLowering(TM, STI) {
addRegisterClass(MVT::i32, &Toy::GPRRegClass);
computeRegisterProperties(STI.getRegisterInfo());
setStackPointerRegisterToSaveRestore(Toy::SP);
setBooleanContents(ZeroOrOneBooleanContent);
setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
setOperationAction(ISD::BR_CC, MVT::i32, Expand); // use SETCC + BRCOND
setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
for (unsigned Op : {ISD::SDIV, ISD::UDIV, ISD::SREM, ISD::UREM,
ISD::SDIVREM, ISD::UDIVREM})
setOperationAction(Op, MVT::i32, Expand); // libcalls
if (!STI.hasMul())
setOperationAction(ISD::MUL, MVT::i32, Expand); // __mulsi3
for (unsigned Op : {ISD::MULHS, ISD::MULHU, ISD::SMUL_LOHI, ISD::UMUL_LOHI,
ISD::ROTL, ISD::ROTR, ISD::CTPOP, ISD::CTLZ, ISD::CTTZ})
setOperationAction(Op, MVT::i32, Expand);
for (MVT VT : {MVT::i1, MVT::i8, MVT::i16}) {
setLoadExtAction(ISD::EXTLOAD, MVT::i32, VT, Promote);
}
setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
setOperationAction(ISD::VASTART, MVT::Other, Custom);
setOperationAction(ISD::VAARG, MVT::Other, Expand);
setOperationAction(ISD::VACOPY, MVT::Other, Expand);
setOperationAction(ISD::VAEND, MVT::Other, Expand);
setMinFunctionAlignment(Align(4));
}
Finding Missing Actions
If an operation has no pattern and no action, instruction selection fails with LLVM ERROR: Cannot select: ... and prints the node. The fix is either a pattern (if the instruction exists) or an action. llc -debug-only=isel prints each DAG stage and -view-legalize-dags draws it, but both need an assertions (or debug) build of LLVM. With a release build like the one used for this wiki, reduce the input IR (for example with llvm-reduce) until the failing node is obvious. The SelectionDAG wiki's tooling page lists the options.
Calling Conventions
Relevant source files
The following files were used as context for generating this wiki page:
A calling convention says where each argument and return value lives: which register, or which stack offset. In LLVM the rules are written in TableGen (CallingConv records), compiled by -gen-callingconv into C++ functions, and used by three TargetLowering hooks that every target must implement: LowerFormalArguments, LowerCall and LowerReturn.
Purpose and Scope
The minimum a new target needs for calls to work, with AArch64 as reference. The calling conventions wiki covers each part in depth: the TableGen language, CCState, the three hooks, varargs and tail calls. Where call lowering happens during DAG building is on the SelectionDAG DAG construction page.
The Three Pieces
flowchart LR
TD["ToyCallingConv.td<br/>CC_Toy, RetCC_Toy, CSR_Toy"] -->|-gen-callingconv| INC["ToyGenCallingConv.inc"]
INC --> LFA["LowerFormalArguments<br/>(incoming args)"]
INC --> LC["LowerCall<br/>(outgoing args, call node, results)"]
INC --> LR["LowerReturn<br/>(return values)"]
TD -->|-gen-register-info| CSR["CSR_Toy_SaveList / RegMask"]
CSR --> TRI["ToyRegisterInfo::getCalleeSavedRegs,<br/>getCallPreservedMask"]
TableGen rules
AArch64's AAPCS rules are one list of actions tried in order for each value. Integer rules from that list:
CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
CCIfType<[i32], CCAssignToReg<[W0, W1, W2, W3, W4, W5, W6, W7]>>,
...
CCIfType<[i64], CCAssignToReg<[X0, X1, X2, X3, X4, X5, X6, X7]>>,
...
// If more than will fit in registers, pass them on the stack instead.
CCIfType<[i1, i8, i16, f16, bf16], CCAssignToStack<8, 8>>,
CCIfType<[i32, f32], CCAssignToStack<8, 8>>,
let Entry = 1 in def CC_AArch64_AAPCS : CallingConv<AArch64_Common>; makes the generated function visible to C++. The callee-saved set is a separate record:
def CSR_AArch64_AAPCS : CalleeSavedRegs<(add X19, X20, X21, X22, X23, X24,
-gen-register-info turns it into CSR_AArch64_AAPCS_SaveList and CSR_AArch64_AAPCS_RegMask, returned by getCalleeSavedRegs and getCallPreservedMask (see the regalloc registers page).
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:95-126, llvm/lib/Target/AArch64/AArch64CallingConvention.td:594
Choosing the rules per call
AArch64 picks a generated function by calling convention and OS:
CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
bool IsVarArg) const {
switch (CC) {
...
case CallingConv::C:
case CallingConv::Fast:
...
if (!Subtarget->isTargetDarwin())
return CC_AArch64_AAPCS;
A new target with one convention just names CC_Toy directly.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9197-9257
The hooks
| Hook | Runs for | Builds |
|---|---|---|
LowerFormalArguments | Function entry | CopyFromReg from live-in registers; loads from fixed stack objects |
LowerCall | Each call site | CALLSEQ_START, copies to argument registers, stores to the stack, target call node with a register mask, CALLSEQ_END, CopyFromReg of results |
LowerReturn | Each ret | Copies to return registers and a target return node |
CanLowerReturn | Optional | Says whether the return fits in registers; if not, LLVM adds an sret pointer |
Each hook follows the same pattern: make a CCState, call Analyze* with the generated function, then walk the resulting CCValAssign list.
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9314-9335, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10442, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11172-11194, llvm/include/llvm/CodeGen/CallingConvLower.h:171
What the Result Looks Like
For a call with ten i64 arguments, llc -O2 -mtriple=aarch64-linux-gnu puts arguments 1–8 in x0–x7 and the last two on the stack (abridged):
mov w8, #9 // =0x9
mov w9, #8 // =0x8
mov w1, #1 // =0x1
...
stp x8, x30, [sp, #8] // 8-byte Folded Spill
str x9, [sp]
bl callee
The calling conventions walkthroughs show the full output and the MIR after instruction selection.
Minimal Toy Version (Illustrative)
Illustrative, not LLVM source.
// ToyCallingConv.td
def CC_Toy : CallingConv<[
CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
CCIfType<[i32], CCAssignToReg<[R0, R1, R2, R3]>>,
CCIfType<[i32], CCAssignToStack<4, 4>>
]>;
def RetCC_Toy : CallingConv<[
CCIfType<[i32], CCAssignToReg<[R0, R1]>>
]>;
def CSR_Toy : CalleeSavedRegs<(add R8, R9, R10, R11, LR)>;
A full LowerFormalArguments, LowerCall and LowerReturn for this convention is on the calling conventions custom backend page.
Order of Implementation
Every function goes through LowerFormalArguments and LowerReturn, so those two are needed before even the first function compiles. LowerCall is only reached when the function contains a call, so it can come second. The defaults in TargetLowering do not report a useful error:
virtual SDValue
LowerCall(CallLoweringInfo &/*CLI*/,
SmallVectorImpl<SDValue> &/*InVals*/) const {
llvm_unreachable("Not Implemented");
}
With assertions enabled this prints Not Implemented and aborts; in a release build llvm_unreachable is undefined behaviour, so a missing hook can crash anywhere. Build LLVM with -DLLVM_ENABLE_ASSERTIONS=ON while bringing up a target.
Sources: llvm/include/llvm/CodeGen/TargetLowering.h:4893-4898, llvm/include/llvm/CodeGen/TargetLowering.h:5187-5191, llvm/include/llvm/CodeGen/TargetLowering.h:5215-5222
Instructions and Instruction Selection
Relevant source files
The following files were used as context for generating this wiki page:
Instructions are TableGen records derived from Instruction. Each record gives the operands, the assembly string, the encoding, scheduling information and, optionally, a DAG pattern. -gen-instr-info turns them into opcode enums and descriptor tables; -gen-dag-isel turns the patterns into a matcher table that the target's SelectionDAGISel subclass runs node by node.
Purpose and Scope
What a target writes to get instruction selection working: instruction records, target DAG nodes, the selector class, and the TargetInstrInfo hooks that later passes need. The pattern syntax is covered by the SelectionDAG pattern language page, the matcher by the matcher interpreter page, and AArch64's hand-written selection by the AArch64 selection page.
Instruction Records
AArch64 builds most instructions from multiclasses in AArch64InstrFormats.td, which share operand lists and encoding layouts. Integer add and subtract are one line in AArch64InstrInfo.td:
defm ADD : AddSub<0, "add", "sub", add>;
AddSub (defined in AArch64InstrFormats.td) expands into the register, immediate, shifted-register and extended-register forms for 32 and 64 bits (ADDWrr, ADDXri, ...), and the last argument, the generic add node, becomes the selection pattern. That is why the first-milestone MIR shows ADDWrr:
%1:gpr32 = COPY $w1
%0:gpr32 = COPY $w0
%2:gpr32 = ADDWrr %0, %1
$w0 = COPY %2
RET_ReallyLR implicit $w0
(llc -O2 -mtriple=aarch64-linux-gnu -stop-after=finalize-isel on the add function from the overview.)
Sources: llvm/lib/Target/AArch64/AArch64InstrInfo.td:2811, llvm/lib/Target/AArch64/AArch64InstrFormats.td:3096
Target DAG Nodes
Custom lowering (for calls, returns, globals) creates target-specific nodes. Each needs an SDNode record so patterns can match it:
def AArch64call : SDNode<"AArch64ISD::CALL",
...
def AArch64retglue : SDNode<"AArch64ISD::RET_GLUE", SDTNone,
The string is the C++ enum value; -gen-sd-node-info (AArch64GenSDNodeInfo.inc in AArch64's CMake file) generates the enum and the node names used in debug output.
Sources: llvm/lib/Target/AArch64/AArch64InstrInfo.td:820, llvm/lib/Target/AArch64/AArch64InstrInfo.td:895, llvm/lib/Target/AArch64/CMakeLists.txt:26
The Selector Class
flowchart LR
N["SDNode"] --> S["ToyDAGToDAGISel::Select(N)"]
S -->|special cases| H["hand-written C++ (frame index, constants)"]
S -->|everything else| SC["SelectCode(N)<br/>(generated matcher table)"]
SC --> M["MachineSDNode"]
AArch64DAGToDAGISel derives from SelectionDAGISel, includes the generated matcher inside the class, and overrides Select. Select handles nodes that patterns cannot express and ends with a call to the generated SelectCode(Node). createAArch64ISelDag wraps it in a legacy pass for addInstSelector.
| Location | Line |
|---|---|
class AArch64DAGToDAGISel : public SelectionDAGISel | 49 |
#include "AArch64GenDAGISel.inc" (inside the class) | 460 |
void AArch64DAGToDAGISel::Select(SDNode *Node) | 5157 |
SelectCode(Node); at the end of Select | 7820 |
createAArch64ISelDag | 7825 |
Sources: llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:49, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:460, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:5157, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:7820-7825
TargetInstrInfo Hooks Needed Early
Selection alone is not enough: later generic passes ask TargetInstrInfo to create copies, spills and branches.
| Hook | Called by | AArch64 line | Needed for |
|---|---|---|---|
copyPhysReg | Copy expansion after allocation | 6365 | Any function with a COPY that survives |
storeRegToStackSlot / loadRegFromStackSlot | Spiller, callee-saved spills | 6400 / 6580 | Any spill |
analyzeBranch, insertBranch, removeBranch | Branch folding, block placement | 523 / 839 / 772 | Correct -O2 with control flow |
expandPostRAPseudo | postrapseudos pass | 2559 | Pseudos like RET_ReallyLR that expand late |
analyzeBranch may return true ("can't analyze") at first; passes then leave the branches alone. The regalloc wiki's TII hooks page shows the copy and spill hooks in detail.
Sources: llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:523, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:772, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:839, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:2559, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:6365-6580
Minimal Toy Instructions (Illustrative)
Illustrative, not LLVM source.
// ToyInstrInfo.td
def SDT_ToyCall : SDTypeProfile<0, -1, [SDTCisVT<0, i32>]>;
def ToyCall : SDNode<"ToyISD::CALL", SDT_ToyCall,
[SDNPHasChain, SDNPOptInGlue, SDNPOutGlue, SDNPVariadic]>;
def ToyRet : SDNode<"ToyISD::RET", SDTNone,
[SDNPHasChain, SDNPOptInGlue, SDNPVariadic]>;
class ToyInst<dag outs, dag ins, string asm, list<dag> pat>
: Instruction {
let Namespace = "Toy";
let OutOperandList = outs;
let InOperandList = ins;
let AsmString = asm;
let Pattern = pat;
let Size = 4;
field bits<32> Inst;
}
def simm16 : Operand<i32>, ImmLeaf<i32, [{ return isInt<16>(Imm); }]>;
def ADD : ToyInst<(outs GPR:$rd), (ins GPR:$rs, GPR:$rt),
"add $rd, $rs, $rt", [(set GPR:$rd, (add GPR:$rs, GPR:$rt))]>;
def ADDI : ToyInst<(outs GPR:$rd), (ins GPR:$rs, simm16:$imm),
"addi $rd, $rs, $imm", [(set GPR:$rd, (add GPR:$rs, simm16:$imm))]>;
def LW : ToyInst<(outs GPR:$rd), (ins GPR:$base, simm16:$off),
"lw $rd, ${off}(${base})", []> { let mayLoad = 1; }
def SW : ToyInst<(outs), (ins GPR:$rs, GPR:$base, simm16:$off),
"sw $rs, ${off}(${base})", []> { let mayStore = 1; }
let isReturn = 1, isTerminator = 1, isBarrier = 1, Uses = [LR] in
def RET : ToyInst<(outs), (ins), "ret", [(ToyRet)]>;
let isCall = 1, Defs = [LR] in
def CALL : ToyInst<(outs), (ins i32imm:$target), "call $target", []>;
def : Pat<(ToyCall tglobaladdr:$dst), (CALL tglobaladdr:$dst)>;
// load/store patterns using a ComplexPattern for base+offset
def AddrFI : ComplexPattern<iPTR, 2, "SelectAddr", [frameindex], []>;
def : Pat<(load AddrFI:$addr), (LW AddrFI:$addr)>;
def : Pat<(store GPR:$v, AddrFI:$addr), (SW GPR:$v, AddrFI:$addr)>;
// ToyISelDAGToDAG.cpp (illustrative)
class ToyDAGToDAGISel : public SelectionDAGISel {
public:
explicit ToyDAGToDAGISel(ToyTargetMachine &TM, CodeGenOptLevel OL)
: SelectionDAGISel(TM, OL) {}
void Select(SDNode *N) override {
if (N->isMachineOpcode()) { N->setNodeId(-1); return; }
if (N->getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(N)->getIndex();
SDValue TFI = CurDAG->getTargetFrameIndex(FI, MVT::i32);
ReplaceNode(N, CurDAG->getMachineNode(Toy::ADDI, SDLoc(N), MVT::i32, TFI,
CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32)));
return;
}
SelectCode(N);
}
bool SelectAddr(SDValue Addr, SDValue &Base, SDValue &Off);
#include "ToyGenDAGISel.inc"
};
Frame-index operands produced here are rewritten to real offsets by eliminateFrameIndex; see Frame Lowering.
Registers and Allocation Hooks
Relevant source files
The following files were used as context for generating this wiki page:
Registers are described once in TableGen (Register, RegisterClass, sub-register indices). -gen-register-info produces the register enum, class tables and a <T>GenRegisterInfo base class. The target's <T>RegisterInfo derives from it and answers the questions the register allocator and frame lowering ask: which registers are reserved, which are callee-saved, what a call clobbers, and how to turn a frame index into a register plus offset.
Purpose and Scope
The minimum register description and TargetRegisterInfo hooks for a new target. The register allocation wiki covers this in depth: TableGen registers, TRI hooks, TII hooks, pass config hooks and its backend checklist.
How the Pieces Connect
flowchart LR
RTD["ToyRegisterInfo.td<br/>registers, classes"] -->|-gen-register-info| GEN["ToyGenRegisterInfo.inc"]
CTD["ToyCallingConv.td<br/>CSR_Toy"] -->|-gen-register-info| GEN
GEN --> TRI["ToyRegisterInfo"]
TRI -->|getReservedRegs| RA["Register allocator"]
TRI -->|getCalleeSavedRegs| PEI["Prologue/epilogue insertion"]
TRI -->|getCallPreservedMask| LC["LowerCall regmask operand"]
TRI -->|eliminateFrameIndex| PEI
TL["TargetLowering::addRegisterClass"] --> RA
A register class becomes usable for a value type only when TargetLowering adds it with addRegisterClass (TargetLowering Setup). AArch64's addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass) is where the generated GPR64allRegClass object is first used.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:486-487
The Hooks a New Target Writes
| Hook | Question it answers | AArch64 line | Required |
|---|---|---|---|
getCalleeSavedRegs(MF) | Which registers must a function preserve? Returns the generated CSR_*_SaveList | 72 | Yes (pure virtual) |
getCallPreservedMask(MF, CC) | Which registers survive a call? Returns CSR_*_RegMask, attached to every call | 270-271 | Yes, for calls |
getReservedRegs(MF) | Which registers the allocator must never use (SP, zero register, FP when used) | 534-535 | Yes (pure virtual) |
getFrameRegister(MF) | Base register for frame references (FP or SP) | 752-753 | Yes (pure virtual) |
eliminateFrameIndex(...) | Rewrite a frame-index operand into register + offset | 978 | Yes (pure virtual) |
requiresRegisterScavenging(MF) | Can frame-index elimination need a scratch register? | 758 | Usually |
requiresFrameIndexScavenging(MF) | Scavenge virtual registers created during elimination | 787 | Optional |
hasBasePointer(MF) | Need a third frame base register (realigned stack plus variable-sized objects)? | 623 | Optional |
AArch64 splits reserved registers into two functions: getStrictlyReservedRegs (never allocatable, such as SP and the zero register) at line 418-419 and getReservedRegs at 534-535, which adds registers the user asked to reserve.
The callee-saved list comes straight from the calling convention file:
def CSR_AArch64_AAPCS : CalleeSavedRegs<(add X19, X20, X21, X22, X23, X24,
Sources: llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:72, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:270-271, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:418-419, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:534-535, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:623, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:752-787, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:978, llvm/lib/Target/AArch64/AArch64CallingConvention.td:594
What the Allocator Does with Them
With these hooks in place the generic allocators work without further target code. In the AArch64 notail function (from the calling conventions walkthroughs), the value of x0 must survive a call, so the allocator picks the callee-saved x19, and frame lowering then saves and restores it because it is in the CSR_AArch64_AAPCS list:
stp x30, x19, [sp, #-16]! // 16-byte Folded Spill
...
mov x19, x0
bl g
add x0, x0, x19
ldp x30, x19, [sp], #16 // 16-byte Folded Reload
ret
(llc -O2 -mtriple=aarch64-linux-gnu.) The regmask on the BL instruction is what told the allocator that x0-x18 do not survive the call.
Minimal Toy Registers (Illustrative)
Illustrative, not LLVM source.
// ToyRegisterInfo.td
class ToyReg<bits<5> num, string n> : Register<n> {
let HWEncoding{4-0} = num;
let Namespace = "Toy";
}
foreach i = 0-15 in
def R#i : ToyReg<i, "r"#i>, DwarfRegNum<[i]>;
def SP : ToyReg<16, "sp">, DwarfRegNum<[16]>;
def LR : ToyReg<17, "lr">, DwarfRegNum<[17]>;
def GPR : RegisterClass<"Toy", [i32], 32,
(add (sequence "R%u", 0, 15), SP, LR)>;
// ToyRegisterInfo.cpp (illustrative)
ToyRegisterInfo::ToyRegisterInfo() : ToyGenRegisterInfo(Toy::LR) {}
const MCPhysReg *ToyRegisterInfo::getCalleeSavedRegs(const MachineFunction *) const {
return CSR_Toy_SaveList;
}
const uint32_t *ToyRegisterInfo::getCallPreservedMask(const MachineFunction &,
CallingConv::ID) const {
return CSR_Toy_RegMask;
}
BitVector ToyRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
BitVector R(getNumRegs());
R.set(Toy::SP);
if (getFrameLowering(MF)->hasFP(MF))
R.set(Toy::R11); // frame pointer
return R;
}
Register ToyRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
return getFrameLowering(MF)->hasFP(MF) ? Toy::R11 : Toy::SP;
}
eliminateFrameIndex for Toy is on the Frame Lowering page.
Frame Lowering
Relevant source files
The following files were used as context for generating this wiki page:
Until register allocation is finished, stack slots are abstract frame indices and there is no prologue or epilogue. The generic prologue/epilogue insertion pass (PEI, -prolog-epilog) decides the final stack layout and then calls the target's TargetFrameLowering to emit the code that builds and tears down the frame, and TargetRegisterInfo::eliminateFrameIndex to turn each frame index into a register plus offset.
Purpose and Scope
The minimum frame lowering a new target needs. The frame lowering wiki covers MachineFrameInfo, all the hooks, the PEI pass step by step, callee-saved spilling, frame index elimination, shrink wrapping and CFI.
What PEI Calls, in Order
flowchart TD
A["calculateCallFrameInfo<br/>(eliminateCallFramePseudoInstr)"] --> B["calculateSaveRestoreBlocks"]
B --> C["spillCalleeSavedRegs<br/>(determineCalleeSaves, spill/restoreCalleeSavedRegisters)"]
C --> D["processFunctionBeforeFrameFinalized"]
D --> E["calculateFrameObjectOffsets"]
E --> F["insertPrologEpilogCode<br/>(emitPrologue, emitEpilogue)"]
F --> G["replaceFrameIndices<br/>(eliminateFrameIndex)"]
G --> H["scavengeFrameVirtualRegs"]
This is the order in PEIImpl::run. Target hooks are in parentheses.
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:211-283
Required Hooks
| Hook | Class | Declared at | Purpose |
|---|---|---|---|
Constructor (StackDirection, StackAlign, LocalAreaOffset) | TargetFrameLowering | TargetFrameLowering.h:86 | Stack grows down, alignment, offset of local area |
emitPrologue, emitEpilogue | TargetFrameLowering | 211, 213 | Pure virtual: build and remove the frame |
hasFPImpl | TargetFrameLowering | 520 | Pure virtual: does this function need a frame pointer? (hasFP at 306 calls it) |
hasReservedCallFrame | TargetFrameLowering | 315 | Whether outgoing argument space is part of the fixed frame |
eliminateCallFramePseudoInstr | TargetFrameLowering | 431 | Removes ADJCALLSTACKDOWN/UP; the default is llvm_unreachable, so any target that uses call-frame pseudos must override it |
eliminateFrameIndex | TargetRegisterInfo | TargetRegisterInfo.h:1020 | Pure virtual: rewrites frame-index operands |
AArch64's versions are short wrappers at this commit: emitPrologue and emitEpilogue construct an AArch64PrologueEmitter / AArch64EpilogueEmitter (in AArch64PrologueEpilogue.cpp) and call it:
void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
AArch64PrologueEmitter PrologueEmitter(MF, MBB, *this);
PrologueEmitter.emitPrologue();
}
The default for call-frame pseudos:
eliminateCallFramePseudoInstr(MachineFunction &MF,
MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI) const {
llvm_unreachable("Call Frame Pseudo Instructions do not exist on this "
"target!");
}
Sources: llvm/include/llvm/CodeGen/TargetFrameLowering.h:86, llvm/include/llvm/CodeGen/TargetFrameLowering.h:211-213, llvm/include/llvm/CodeGen/TargetFrameLowering.h:306-315, llvm/include/llvm/CodeGen/TargetFrameLowering.h:431-436, llvm/include/llvm/CodeGen/TargetFrameLowering.h:520, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:1020, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:1236-1246
What It Produces
Two AArch64 functions from llc -O2 -mtriple=aarch64-linux-gnu. A leaf function gets no frame at all:
leaf: // @leaf
.cfi_startproc
mul x0, x0, x1
ret
A function with a call saves the return address and the callee-saved register it uses in one paired store, and emits CFI for the unwinder:
withcall: // @withcall
.cfi_startproc
stp x30, x19, [sp, #-16]! // 16-byte Folded Spill
.cfi_def_cfa_offset 16
.cfi_offset w19, -8
.cfi_offset w30, -16
mov x19, x0
bl h
add x0, x0, x19
ldp x30, x19, [sp], #16 // 16-byte Folded Reload
ret
The frame lowering walkthroughs show the MIR before and after PEI and the large-frame and alloca cases.
Minimal Toy Frame Lowering (Illustrative)
Illustrative, not LLVM source. Fixed-size frames only, no frame pointer, outgoing arguments in the reserved call frame:
class ToyFrameLowering : public TargetFrameLowering {
public:
ToyFrameLowering()
: TargetFrameLowering(StackGrowsDown, Align(8), /*LocalAreaOffset=*/0) {}
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override {
uint64_t Size = MF.getFrameInfo().getStackSize();
if (!Size) return;
const auto &TII = *MF.getSubtarget<ToySubtarget>().getInstrInfo();
auto MBBI = MBB.begin();
BuildMI(MBB, MBBI, DebugLoc(), TII.get(Toy::ADDI), Toy::SP)
.addReg(Toy::SP).addImm(-(int64_t)Size)
.setMIFlag(MachineInstr::FrameSetup);
}
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override {
uint64_t Size = MF.getFrameInfo().getStackSize();
if (!Size) return;
const auto &TII = *MF.getSubtarget<ToySubtarget>().getInstrInfo();
auto MBBI = MBB.getFirstTerminator();
BuildMI(MBB, MBBI, DebugLoc(), TII.get(Toy::ADDI), Toy::SP)
.addReg(Toy::SP).addImm(Size)
.setMIFlag(MachineInstr::FrameDestroy);
}
MachineBasicBlock::iterator
eliminateCallFramePseudoInstr(MachineFunction &, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const override {
return MBB.erase(I); // valid because hasReservedCallFrame() is true
}
protected:
bool hasFPImpl(const MachineFunction &) const override { return false; }
};
// ToyRegisterInfo.cpp (illustrative)
bool ToyRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
int SPAdj, unsigned FIOp,
RegScavenger *RS) const {
MachineInstr &MI = *II;
MachineFunction &MF = *MI.getMF();
int FI = MI.getOperand(FIOp).getIndex();
int64_t Off = MF.getFrameInfo().getObjectOffset(FI) +
MF.getFrameInfo().getStackSize() +
MI.getOperand(FIOp + 1).getImm();
assert(isInt<16>(Off) && "large frames need a scratch register");
MI.getOperand(FIOp).ChangeToRegister(Toy::SP, false);
MI.getOperand(FIOp + 1).ChangeToImmediate(Off);
return false; // MI was not erased
}
This assumes every frame-index user has the operand pair (base, offset) as in the LW/SW/ADDI records on Instructions and ISel. Callee-saved registers need no extra code: the default spillCalleeSavedRegisters returns false, so PEI calls TargetFrameLowering::spillCalleeSavedRegister for each register, which uses ToyInstrInfo::storeRegToStackSlot (restores go through loadRegFromStackSlot). See the frame wiki's PEI page.
AsmPrinter and the MC Layer
Relevant source files
The following files were used as context for generating this wiki page:
The last CodeGen pass is the target's AsmPrinter. It walks every MachineInstr, converts it to an MCInst (a flat opcode plus operands, with no links to the function), and hands it to an MCStreamer. From there on everything is MC layer: the streamer either prints text through the MCInstPrinter or encodes bytes through the MCCodeEmitter and MCAsmBackend.
Purpose and Scope
The AsmPrinter subclass, MCInstLower, and the minimum MC objects needed for .s output. The MC layer itself is covered by the MC wiki: streamers, MCAsmInfo and the printer, code emitter, asm backend, fixups and relocations and its checklist.
From MachineInstr to Output
flowchart LR
MI["MachineInstr"] --> AP["ToyAsmPrinter::emitInstruction"]
AP -->|"pseudo expansion (generated)"| MCI["MCInst"]
AP -->|"ToyMCInstLower::Lower"| MCI
MCI --> S["MCStreamer"]
S -->|.s| IP["ToyInstPrinter (-gen-asm-writer)"]
S -->|.o| CE["ToyMCCodeEmitter (-gen-emitter)"]
CE --> AB["ToyAsmBackend: fixups"]
AB --> OW["ToyELFObjectWriter: relocations"]
The AsmPrinter Subclass
AArch64AsmPrinter (declared at line 98) derives from AsmPrinter. Its emitInstruction first tries the TableGen-generated pseudo lowering (-gen-pseudo-lowering, included just above it), then handles special opcodes, and finally falls back to the generic path:
#include "AArch64GenMCPseudoLowering.inc"
void AArch64AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
S.emitInstruction(Inst, *STI);
...
}
void AArch64AsmPrinter::emitInstruction(const MachineInstr *MI) {
...
// Do any auto-generated pseudo lowerings.
if (MCInst OutInst; lowerPseudoInstExpansion(MI, OutInst)) {
EmitToStreamer(*OutStreamer, OutInst);
return;
}
...
At the end of the function, ordinary instructions go through MCInstLowering.Lower(MI, TmpInst) and EmitToStreamer(*OutStreamer, TmpInst).
The printer is registered with RegisterAsmPrinter<AArch64AsmPrinter> in LLVMInitializeAArch64AsmPrinter (see Layout and CMake).
Sources: llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp:98, llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp:3256-3279, llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp:3969-3970, llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp:4187-4192
MCInstLower
AArch64MCInstLower copies the opcode and converts each MachineOperand to an MCOperand:
| Function | Line | Job |
|---|---|---|
LowerSymbolOperand | 321 | Global, external symbol, block address, constant pool, jump table → MCSymbolRefExpr, with the target flag (:lo12:, :got: ...) turned into a specifier |
lowerOperand | 332 | Register → MCOperand::createReg, immediate → createImm, symbols → LowerSymbolOperand; implicit operands and register masks are dropped |
Lower | 376 | OutMI.setOpcode(MI->getOpcode()), then each operand |
A new target's version is short: a switch over MachineOperand kinds. Operand target flags are the bridge between instruction selection (which marks MO_LO/MO_HI style flags) and the MC fixups that become relocations.
Sources: llvm/lib/Target/AArch64/AArch64MCInstLower.cpp:321-376
Minimum MC Objects for .s Output
initAsmInfo() in the target machine constructor (TargetMachine and Subtarget) fails unless these are registered in LLVMInitialize<T>TargetMC:
| Object | Source | Needed for |
|---|---|---|
MCAsmInfo | Hand-written (comment string, directives, alignment) | Everything |
MCInstrInfo, MCRegisterInfo, MCSubtargetInfo | Generated, a few lines of glue | Everything |
MCInstPrinter | Generated printInstruction + hand-written printOperand | .s |
MCCodeEmitter | Generated getBinaryCodeForInstr + operand encoders | .o |
MCAsmBackend, MCELFObjectTargetWriter | Hand-written | .o |
The registration code is on the MC custom backend page.
Minimal Toy Versions (Illustrative)
Illustrative, not LLVM source.
// ToyMCInstLower.cpp
void ToyMCInstLower::Lower(const MachineInstr *MI, MCInst &Out) const {
Out.setOpcode(MI->getOpcode());
for (const MachineOperand &MO : MI->operands()) {
switch (MO.getType()) {
case MachineOperand::MO_Register:
if (MO.isImplicit()) continue;
Out.addOperand(MCOperand::createReg(MO.getReg()));
break;
case MachineOperand::MO_Immediate:
Out.addOperand(MCOperand::createImm(MO.getImm()));
break;
case MachineOperand::MO_GlobalAddress:
Out.addOperand(MCOperand::createExpr(MCSymbolRefExpr::create(
Printer.getSymbol(MO.getGlobal()), Ctx)));
break;
case MachineOperand::MO_MachineBasicBlock:
Out.addOperand(MCOperand::createExpr(
MCSymbolRefExpr::create(MO.getMBB()->getSymbol(), Ctx)));
break;
case MachineOperand::MO_RegisterMask:
continue;
default:
llvm_unreachable("unknown operand type");
}
}
}
// ToyAsmPrinter.cpp
class ToyAsmPrinter : public AsmPrinter {
ToyMCInstLower MCInstLowering;
public:
ToyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> S)
: AsmPrinter(TM, std::move(S)), MCInstLowering(OutContext, *this) {}
StringRef getPassName() const override { return "Toy Assembly Printer"; }
void emitInstruction(const MachineInstr *MI) override {
MCInst I;
MCInstLowering.Lower(MI, I);
EmitToStreamer(*OutStreamer, I);
}
};
extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeToyAsmPrinter() {
RegisterAsmPrinter<ToyAsmPrinter> X(getTheToyTarget());
}
Pseudo instructions that survive to this point (for example a RET pseudo with implicit operands) must either be expanded in expandPostRAPseudo or given a PseudoInstExpansion in TableGen so lowerPseudoInstExpansion handles them.
Scheduling
Relevant source files
The following files were used as context for generating this wiki page:
A backend produces correct code without any scheduling model: the schedulers fall back to default latencies. A model becomes necessary when performance matters. It tells the machine scheduler how many micro-ops issue per cycle, which execution units each instruction uses, and how long results take.
Purpose and Scope
What a new target needs for scheduling: enabling the machine scheduler, SchedWrite types on instructions, and a per-CPU SchedMachineModel. The instruction scheduling wiki covers the scheduling DAG, the machine scheduler, register pressure, post-RA scheduling, the model language and how a target wires it up. Where the pre-RA scheduler sits relative to register allocation is on the regalloc pipeline page; the older SelectionDAG scheduler is on the SelectionDAG scheduling and emission page.
Three Steps
flowchart TD
A["1. Subtarget: enableMachineScheduler() returns true"] --> B["2. ToySchedule.td: SchedWrite types; instructions list them with Sched<[...]>"]
B --> C["3. ToySchedModel.td: SchedMachineModel + ProcResource + WriteRes per SchedWrite"]
C --> D["ProcessorModel<'toy2', ToyModel, ...>"]
1. Turn the machine scheduler on
AArch64's subtarget header has bool enableMachineScheduler() const override { return true; }. Without it the pre-RA machine-scheduler pass does nothing for the target.
Sources: llvm/lib/Target/AArch64/AArch64Subtarget.h:160-161
2. Abstract scheduling types
AArch64Schedule.td defines target-wide types, one per kind of operation:
def WriteI : SchedWrite; // ALU
def WriteISReg : SchedWrite; // ALU of Shifted-Reg
def ReadI : SchedRead; // ALU
...
def WriteIM64 : SchedWrite; // 64-bit Multiply
def WriteBr : SchedWrite; // Branch
def WriteLD : SchedWrite; // Load from base addr plus immediate offset
def WriteST : SchedWrite; // Store to base addr plus immediate offset
Instructions list these in Sched<[...]>, one entry per defined operand followed by one per read operand. They say nothing about any particular CPU.
Sources: llvm/lib/Target/AArch64/AArch64Schedule.td:24-44
3. A per-CPU model
The Cortex-A57 model sets machine-wide parameters, declares execution units, and maps each SchedWrite to units and a latency:
def CortexA57Model : SchedMachineModel {
let IssueWidth = 3; // 3-way decode and dispatch
let MicroOpBufferSize = 128; // 128 micro-op re-order buffer
let LoadLatency = 4; // Optimistic load latency
let MispredictPenalty = 14; // Fetch + Decode/Rename/Dispatch + Branch
...
let CompleteModel = 1;
...
}
...
def A57UnitB : ProcResource<1>; // Type B micro-ops
def A57UnitI : ProcResource<2>; // Type I micro-ops
def A57UnitM : ProcResource<1>; // Type M micro-ops
def A57UnitL : ProcResource<1>; // Type L micro-ops
...
def : SchedAlias<WriteLD, A57Write_4cyc_1L>;
...
def : WriteRes<WriteFMul, [A57UnitV]> { let Latency = 5;}
ProcessorModel<"cortex-a57", CortexA57Model, ...> in AArch64Processors.td attaches the model to the CPU name (see The Target .td File). CompleteModel = 1 makes TableGen report every instruction that has no scheduling information.
Sources: llvm/lib/Target/AArch64/AArch64SchedA57.td:23-51, llvm/lib/Target/AArch64/AArch64SchedA57.td:85-98, llvm/include/llvm/Target/TargetSchedule.td:76-97
Target Hooks Around the Scheduler
| Hook | Where | AArch64 does |
|---|---|---|
createMachineScheduler | TargetMachine | Adds load and store clustering mutations, and macro fusion when the CPU supports it |
createPostMachineScheduler | TargetMachine | Uses its own post-RA strategy; macro fusion again |
overrideSchedPolicy | Subtarget | Schedules both top-down and bottom-up (OnlyTopDown = OnlyBottomUp = false) |
substitutePass(&PostRASchedulerID, &PostMachineSchedulerID) | Pass config constructor | Uses the post-RA machine scheduler instead of the old list scheduler |
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:524-550, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:582-587, llvm/lib/Target/AArch64/AArch64Subtarget.cpp:513-523
What It Changes
For a small dot-product function (three pairs of loads, multiplies, adds), with llc -O2 -mtriple=aarch64-linux-gnu -mcpu=cortex-a57, the pre-RA scheduler moves the second load from %0 next to the first, because the load-clustering mutation keeps same-base loads together (MIR just before and just after machine-scheduler):
before: after:
%2:gpr64 = LDRXui %0, 0 %2:gpr64 = LDRXui %0, 0
%3:gpr64 = LDRXui %1, 0 %5:gpr64 = LDRXui %0, 1
%5:gpr64 = LDRXui %0, 1 %3:gpr64 = LDRXui %1, 0
%6:gpr64 = LDRXui %1, 1 %6:gpr64 = LDRXui %1, 1
The full comparison, including what the post-RA scheduler changes, is on the scheduling walkthroughs page.
Minimal Toy Model (Illustrative)
Illustrative, not LLVM source.
// ToySchedule.td: target-wide types
def WriteALU : SchedWrite;
def WriteLoad : SchedWrite;
def WriteStore : SchedWrite;
def WriteBranch : SchedWrite;
def ReadALU : SchedRead;
// ToySchedToy2.td: one CPU
def ToyModel : SchedMachineModel {
let IssueWidth = 1;
let MicroOpBufferSize = 0; // in-order
let LoadLatency = 2;
let CompleteModel = 1;
}
let SchedModel = ToyModel in {
def ToyALU : ProcResource<1>;
def ToyLSU : ProcResource<1>;
def : WriteRes<WriteALU, [ToyALU]> { let Latency = 1; }
def : WriteRes<WriteLoad, [ToyLSU]> { let Latency = 2; }
def : WriteRes<WriteStore, [ToyLSU]> { let Latency = 1; }
def : WriteRes<WriteBranch, [ToyALU]> { let Latency = 1; }
def : ReadAdvance<ReadALU, 0>;
}
Instructions then carry Sched<[WriteALU, ReadALU, ReadALU]> and so on. The scheduling custom backend page explains how to check that the model is complete.
A Minimal Toy Target
Relevant source files
The following files were used as context for generating this wiki page:
This page collects the Toy pieces from the earlier pages into one ordered build-up, from an empty directory to llc -march=toy printing assembly for a function with a call. Every code block on this page is illustrative, not LLVM source; Toy is not an LLVM target and none of this output was produced by a tool. Each step lists what to test before moving on.
Purpose and Scope
The order of work and the test after each step. The code itself is on the pages linked from each step. For object-file output, continue with the MC checklist.
The Toy Machine
| Property | Choice |
|---|---|
| Word size | 32-bit, little endian |
| Registers | r0–r15, sp, lr; r11 is the frame pointer when one is needed |
| Calling convention | Arguments in r0–r3, then the stack; return in r0/r1; r8–r11 and lr callee-saved |
| Instructions | add, addi, lw, sw, call, ret, a compare and a branch |
| Data layout | e-m:e-p:32:32-i64:64-n32-S64 |
Files
llvm/lib/Target/Toy/
CMakeLists.txt
Toy.td ToyRegisterInfo.td ToyCallingConv.td ToySchedule.td ToyInstrInfo.td
ToyTargetMachine.{h,cpp} ToySubtarget.{h,cpp}
ToyISelLowering.{h,cpp} ToyISelDAGToDAG.cpp
ToyInstrInfo.{h,cpp} ToyRegisterInfo.{h,cpp} ToyFrameLowering.{h,cpp}
ToyAsmPrinter.cpp ToyMCInstLower.{h,cpp}
TargetInfo/{CMakeLists.txt, ToyTargetInfo.cpp}
MCTargetDesc/{CMakeLists.txt, ToyMCTargetDesc.cpp, ToyMCAsmInfo.cpp, ToyInstPrinter.cpp}
Outside the directory: Triple::toy in llvm/include/llvm/TargetParser/Triple.h and its parser, a case Triple::toy: in llvm/lib/TargetParser/TargetDataLayout.cpp (the file where AArch64's string is built, lines 81–97), and Toy added to LLVM_ALL_EXPERIMENTAL_TARGETS in llvm/CMakeLists.txt.
Sources: llvm/lib/TargetParser/TargetDataLayout.cpp:81-97, llvm/CMakeLists.txt:602-607
Steps
flowchart TD
S1["1. Triple + TargetInfo"] --> S2["2. Toy.td: registers, empty instr set"]
S2 --> S3["3. MC glue: MCAsmInfo, generated infos, InstPrinter"]
S3 --> S4["4. TargetMachine + Subtarget + PassConfig"]
S4 --> S5["5. TargetLowering, LowerFormalArguments, LowerReturn"]
S5 --> S6["6. ADD, RET + selector"]
S6 --> S7["7. FrameLowering + eliminateFrameIndex + AsmPrinter"]
S7 --> S8["8. Loads, stores, branches, LowerCall"]
S8 --> S9["9. -O2: analyzeBranch, copyPhysReg, spills"]
| Step | Write | Page | Test |
|---|---|---|---|
| 1 | Triple::toy, ToyTargetInfo.cpp, CMake for TargetInfo/ | Layout and CMake | llc --version lists toy |
| 2 | Toy.td, ToyRegisterInfo.td, empty ToyInstrInfo.td | The Target .td File, Registers | llvm-tblgen -gen-register-info succeeds |
| 3 | ToyMCTargetDesc.cpp, ToyMCAsmInfo, ToyInstPrinter | AsmPrinter and MC | Library links |
| 4 | ToyTargetMachine, ToySubtarget, ToyPassConfig::addInstSelector | TargetMachine and Subtarget | llc -march=toy on an empty module succeeds |
| 5 | ToyTargetLowering constructor, CC_Toy, RetCC_Toy, LowerFormalArguments, LowerReturn | TargetLowering, Calling Conventions | define void @f() { ret void } reaches instruction selection |
| 6 | ADD, RET records, ToyDAGToDAGISel | Instructions and ISel | llc -march=toy -stop-after=finalize-isel prints ADD |
| 7 | ToyFrameLowering, getReservedRegs, eliminateFrameIndex, ToyAsmPrinter, ToyMCInstLower | Frame Lowering, AsmPrinter and MC | llc -march=toy -O0 prints add r0, r0, r1 / ret |
| 8 | LW, SW, branch, LowerCall, CALL pattern, getCallPreservedMask | Calling Conventions | A function that calls another compiles at -O0 |
| 9 | copyPhysReg, storeRegToStackSlot, loadRegFromStackSlot, analyzeBranch | Instructions and ISel | The same tests at -O2; -verify-machineinstrs passes |
Expected Output After Step 7
For the same add function as on the overview, the Toy target should print something like this (illustrative: Toy does not exist, so this was not produced by llc):
add:
add r0, r0, r1
ret
Compare it with the real AArch64 output from the overview (add w0, w0, w1 / ret): the same shape, with Toy's register names and mnemonics.
Common First Failures
| Symptom | Usual cause |
|---|---|
No available targets are compatible with triple | Triple parser does not know toy, or RegisterTarget uses a different ArchType |
Crash in initAsmInfo | An MC factory (asm info, register info, instr info, subtarget info) is not registered |
Cannot select: ... | Missing pattern or missing setOperationAction (TargetLowering) |
Not Implemented (assertions build) | A required call-lowering hook is missing (Calling Conventions) |
Call Frame Pseudo Instructions do not exist on this target! | ADJCALLSTACKDOWN/UP used but eliminateCallFramePseudoInstr not overridden (Frame Lowering) |
Bad machine code from -verify-machineinstrs | Wrong register class in a pattern, missing Defs/Uses on calls and returns |
Unknown operand type in MCInstLower | An operand kind not handled (often MO_RegisterMask or an implicit register) |
Always test with -verify-machineinstrs: it catches most mistakes right after the pass that made them. The regalloc wiki's backend checklist has more checks for the allocation-related steps.
Bring-up Checklist and AArch64 File Map
Relevant source files
The following files were used as context for generating this wiki page:
A list of milestones from "empty target" to -O2 object files, each with a test, followed by a map of where each piece lives in the AArch64 backend so you can read the real version.
Purpose and Scope
A checklist to track progress. Each item links to the page that explains it. The MC-specific steps (encoding, fixups, relocations, parser, disassembler) are listed in detail on the MC checklist, and the allocation-specific ones on the regalloc backend checklist.
Milestones
A. The target exists
- ☐
Triple::toyparses; data layout case added (TargetMachine and Subtarget) - ☐
ToyTargetInforegistered;llc --versionlists it (Layout and CMake) - ☐ CMake builds
LLVMToyInfo,LLVMToyDesc,LLVMToyCodeGenwithLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=Toy - ☐
Toy.tdparses withllvm-tblgen -print-records(The Target .td File)
B. A function compiles to assembly at -O0
- ☐ Registers and one register class (Registers and Allocation)
- ☐ MC glue: asm info, instr/reg/subtarget info, instruction printer (AsmPrinter and MC)
- ☐
ToyTargetMachine,ToySubtarget,ToyPassConfig::addInstSelector - ☐
ToyTargetLoweringconstructor:addRegisterClass,computeRegisterProperties(TargetLowering Setup) - ☐
LowerFormalArguments,LowerReturn,CC_Toy,RetCC_Toy(Calling Conventions) - ☐
ADD,RETand a selector (Instructions and ISel) - ☐
ToyFrameLowering,getReservedRegs,getFrameRegister,eliminateFrameIndex(Frame Lowering) - ☐
ToyAsmPrinter,ToyMCInstLower - ☐ Test:
llc -march=toy -O0 -verify-machineinstrs add.ll
C. Real programs at -O0
- ☐ Loads, stores, constants, globals (custom
GlobalAddresslowering) - ☐ Compares and branches (
BR_CCexpanded or custom) - ☐
LowerCall,CALLpattern,getCallPreservedMask, call-frame pseudos (calling conventions wiki) - ☐
copyPhysReg,storeRegToStackSlot,loadRegFromStackSlot(regalloc TII hooks) - ☐ Operation actions for everything the hardware lacks (division, wide multiplies, rotates)
- ☐ Test: a small C program compiled by
clang --target=toy -O0 -S, every function verified
D. -O2
- ☐
analyzeBranch,insertBranch,removeBranchso branch folding and block placement work - ☐ Callee-saved spills appear and are correct (frame wiki: callee saves)
- ☐ Large frames:
eliminateFrameIndexwith the register scavenger (frame wiki: frame index) - ☐ Frame pointer and variable-sized objects (
hasFPImpl) - ☐ Varargs and tail calls (calling conventions wiki, tail calls)
- ☐
enableMachineScheduler, a scheduling model (scheduling wiki) - ☐ Test: the same programs at
-O2 -verify-machineinstrs; run them on hardware or a simulator
E. Object files and tools
- ☐ Encodings in TableGen,
MCCodeEmitter, fixup kinds,MCAsmBackend, ELF object writer (MC checklist) - ☐ CFI from frame lowering so debuggers and unwinders work (frame wiki: CFI)
- ☐ Asm parser (
llvm-mc, inline asm) and disassembler (llvm-objdump) - ☐
littests underllvm/test/CodeGen/Toyandllvm/test/MC/Toy
AArch64 File Map
Where to look in llvm/lib/Target/AArch64/ for the real version of each piece:
| Piece | AArch64 file | Wiki page |
|---|---|---|
| Root TableGen | AArch64.td | The Target .td File |
| Features, processors | AArch64Features.td, AArch64Processors.td | The Target .td File |
| Registers | AArch64RegisterInfo.td, AArch64RegisterInfo.cpp | Registers and Allocation |
| Calling conventions | AArch64CallingConvention.td, AArch64CallingConvention.cpp | Calling Conventions |
| Instructions | AArch64InstrFormats.td, AArch64InstrInfo.td, AArch64InstrInfo.cpp | Instructions and ISel |
| Lowering | AArch64ISelLowering.cpp | TargetLowering Setup |
| Selector | AArch64ISelDAGToDAG.cpp | Instructions and ISel |
| Target machine, pass config | AArch64TargetMachine.cpp | TargetMachine and Subtarget |
| Subtarget | AArch64Subtarget.cpp, AArch64Subtarget.h | TargetMachine and Subtarget |
| Frame | AArch64FrameLowering.cpp, AArch64PrologueEpilogue.cpp | Frame Lowering |
| Scheduling | AArch64Schedule.td, AArch64Sched*.td | Scheduling |
| Printer | AArch64AsmPrinter.cpp, AArch64MCInstLower.cpp | AsmPrinter and MC |
| MC | MCTargetDesc/ | MC wiki |
| Target info | TargetInfo/AArch64TargetInfo.cpp | Layout and CMake |
| Build | CMakeLists.txt | Layout and CMake |
Sources: llvm/lib/Target/AArch64/CMakeLists.txt:1-33, llvm/lib/Target/AArch64/AArch64.td:16-58
Tooling and Glossary
Relevant source files
The following files were used as context for generating this wiki page:
The commands used while bringing up a target, and the terms used across this wiki. Each of the other wikis has its own tooling page with more detail: SelectionDAG, register allocation, MC, calling conventions, frame lowering and scheduling.
Purpose and Scope
llc and llvm-tblgen options useful during bring-up, and a glossary. All tool output in this wiki comes from an LLVM 24.0.0git release build of llc (no assertions) at commit a2171756; options that need an assertions build are marked.
llc Options
| Option | Use | Used in this wiki |
|---|---|---|
-mtriple=<triple>, -march=<name> | Choose the target | Yes |
-mcpu=<cpu>, -mattr=+f,-g | Choose CPU (and scheduling model) and features | Yes (cortex-a57, cortex-a55) |
-O0 ... -O3 | Optimization level; -O0 is the easiest first target | Yes |
-stop-after=<pass>, -stop-before=<pass> | Print MIR at a point in the pipeline | Yes (finalize-isel, prolog-epilog, machine-scheduler) |
-run-pass=<pass> | Run one pass on a .mir file | — |
-debug-pass=Structure | Print the pass pipeline and pass names | Yes |
-verify-machineinstrs | Run the machine verifier after each pass | — |
-filetype=obj | Write an object file (needs the MC code emitter and asm backend) | — |
-debug-only=<type>, -view-*-dags | Debug output, DAG graphs | Needs an assertions build |
Pass names for -stop-after are the DEBUG_TYPE strings, which can differ from the class name. For example the prologue/epilogue pass is prolog-epilog:
#define DEBUG_TYPE "prolog-epilog"
-debug-pass=Structure prints every pass name in order (... -shrink-wrap -prolog-epilog ...), which is the quickest way to find the right one.
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:69
llvm-tblgen
| Command | Use |
|---|---|
llvm-tblgen -print-records -I llvm/include -I lib/Target/Toy Toy.td | Check the .td files parse; see every record |
llvm-tblgen -gen-register-info ... (and other -gen-*) | Run one backend by hand to inspect its output |
Glossary
| Term | Meaning |
|---|---|
| Target | The Target object returned by getThe<T>Target(), registered with TargetRegistry |
| Triple | arch-vendor-os-env string such as aarch64-unknown-linux-gnu |
| Data layout | String giving endianness, type sizes and alignments, stack alignment |
| TargetMachine | Per-compilation object: data layout, reloc and code model, pass pipeline |
| Subtarget | Per CPU-and-features object owning lowering, instr, register and frame info |
| TargetLowering | Legal types and operation actions; custom lowering; call lowering |
| Operation action | Legal, Promote, Expand, LibCall or Custom for an (operation, type) pair |
| Calling convention | Rules for placing arguments and return values; CallingConv records |
| Register mask | Bit set of registers preserved by a call, attached to call instructions |
| Callee-saved register | Register a function must restore before returning |
| Frame index | Abstract stack slot used before frame layout is final |
| PEI | Prologue/epilogue insertion pass (prolog-epilog) |
| Scheduling model | SchedMachineModel with resources and latencies for one CPU |
SchedWrite / SchedRead | Abstract per-operand scheduling types attached to instructions |
| MCInst | Flat instruction used by the MC layer |
| AsmPrinter | Last CodeGen pass; turns MachineInstr into MCInst and streams it |
| Pseudo instruction | Instruction with no encoding, expanded before or during emission |
| Toy | The made-up target used for illustrative examples in these wikis |
Part 2: SelectionDAG Instruction Selection
How LLVM IR becomes machine instructions: DAG construction, combining, legalization, pattern matching and emission.
Pages
- 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
SelectionDAG Overview
Relevant source files
The following files were used as context for generating this wiki page:
- llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
- llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
- llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
- llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp
- llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp
- llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp
- llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp
- llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp
- llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
- llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp
- llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
SelectionDAG is the LLVM instruction selector that turns one basic block of target-independent LLVM IR into target machine instructions. It first builds a directed acyclic graph of operations for the block, then rewrites that graph in stages until every node is a real target instruction, and finally flattens the graph into a linear list of MachineInstrs.
Purpose and Scope
This wiki explains the SelectionDAG instruction selector in llvm/lib/CodeGen/SelectionDAG/, using the AArch64 backend (llvm/lib/Target/AArch64/) as the worked example. It covers the data structures, every phase from DAG construction to MIR emission, the TableGen pattern matcher, and how PHI nodes are resolved.
It does not cover GlobalISel or FastISel in depth; see Selector Comparison and Glossary for how they differ.
Where SelectionDAG Fits
SelectionDAG runs once per function, after the IR-level code generation preparation passes and before any machine-level optimisation. Its output is MIR in SSA form: MachineBasicBlocks holding MachineInstrs in linear order that use virtual registers, with PHI instructions still present.
flowchart LR IR["LLVM IR<br/>Function in SSA form"] --> PREP["IR passes<br/>CodeGenPrepare, LSR, AtomicExpand"] PREP --> ISEL["Instruction selection<br/>SelectionDAGISel"] ISEL --> MIR["MachineFunction<br/>SSA MIR, virtual registers, PHIs"] MIR --> PRE["Pre-RA MIR passes<br/>machine-combiner, CSE, LICM"] PRE --> PHIE["PHIElimination<br/>TwoAddressInstruction"] PHIE --> RA["Register allocation"] RA --> POST["Frame lowering, ldst-opt,<br/>post-RA passes"] POST --> MC["AsmPrinter and MC layer"]
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:947-1200, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:766-776
Inputs, Outputs and Unit of Work
| Description | |
|---|---|
| Input | One LLVM IR Function in SSA form, already cleaned by IR passes such as CodeGenPrepare |
| Output | A MachineFunction whose blocks hold MachineInstrs in linear order, using virtual registers (MIR before register allocation) |
| Unit of work | One IR basic block at a time. One IR block can become several machine blocks (switch lowering, stack-protector checks), and with FastISel enabled the DAG covers only the tail that FastISel could not select |
| Cross-block values | Never DAG edges. They travel through virtual registers using CopyToReg and CopyFromReg nodes |
SelectionDAGISel::SelectAllBasicBlocks walks the function's blocks in reverse post-order and calls SelectBasicBlock for each, which builds the DAG and runs the phases in CodeGenAndEmitDAG.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1656-1971, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:884-908
Component Map
| Component | Class or function | File | Role |
|---|---|---|---|
| Driver | SelectionDAGISel, CodeGenAndEmitDAG | SelectionDAGISel.cpp | Runs the phases for each block |
| IR to DAG | SelectionDAGBuilder::visit* | SelectionDAGBuilder.cpp | One visitor per IR instruction |
| Optimiser | DAGCombiner::Run | DAGCombiner.cpp | Worklist peephole optimiser, run up to four times |
| Type legalizer | DAGTypeLegalizer::run | LegalizeTypes.cpp and siblings | Promote, expand, split, widen types |
| Operation legalizer | SelectionDAG::Legalize, SelectionDAGLegalize | LegalizeDAG.cpp | Legal, Custom, Expand, LibCall, Promote |
| Vector legalizer | VectorLegalizer::Run | LegalizeVectorOps.cpp | Make vector operations supported |
| Matcher | SelectCodeCommon plus generated tables | SelectionDAGISel.cpp, AArch64GenDAGISel.inc | Pattern matching and node creation |
| Scheduler | ScheduleDAGRRList and friends | ScheduleDAGRRList.cpp | Order machine nodes |
| Emitter | InstrEmitter | InstrEmitter.cpp | Create MachineInstrs and virtual registers |
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:947-1200, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:1372-1418, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1846-1963, llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp:200-487, llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:6328-6375, llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp:207-247, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:848-1093
AArch64 Components
| Role | Class or file | What it provides |
|---|---|---|
| Lowering | AArch64TargetLowering in AArch64ISelLowering.cpp | Legal types and operations (setOperationAction), LowerOperation, ReplaceNodeResults, PerformDAGCombine, argument, call and return lowering |
| Selector | AArch64DAGToDAGISel in AArch64ISelDAGToDAG.cpp | Custom Select, ComplexPattern implementations, tryIndexedLoad, tryBitfieldExtractOp |
| Patterns | AArch64InstrInfo.td, AArch64InstrFormats.td | Instruction definitions with embedded patterns, standalone Pat<> records, AArch64ISD:: node definitions |
| Node info | AArch64SelectionDAGInfo.h | In current LLVM the AArch64ISD:: enum is generated into AArch64GenSDNodeInfo.inc from the SDNode records; older releases declare it by hand |
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:460-554, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:5096-5173, llvm/lib/Target/AArch64/AArch64SelectionDAGInfo.h:10-25
Which Selector Runs on AArch64
On AArch64 the selector depends on the optimisation level. AArch64TargetMachine enables GlobalISel when the optimisation level is at or below -aarch64-enable-global-isel-at-O (default 0, so -O0), and otherwise the pipeline uses SelectionDAG through AArch64PassConfig::addInstSelector, which adds the AArch64ISelDag pass.
Observed with llc 23.1.4 (-debug-pass=Structure): at -O2 the pass list contains the GlobalISel passes (IRTranslator, Legalizer, RegBankSelect, InstructionSelect) followed by AArch64 Instruction Selection, but the IRTranslator immediately marks the function as failed, so the SelectionDAG pass does the work and -global-isel-abort=2 reports "Instruction selection used fallback path". At -O0, -global-isel-abort=1 produces no error, so GlobalISel selects the function.
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:159-162, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:404-418, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:766-776
The Phases in Brief
| # | Phase | Result | Page |
|---|---|---|---|
| 1 | Build the DAG from IR | Generic ISD:: nodes, any type | DAG Construction |
| 2 | DAG Combine 1 | Simplified DAG | DAG Combiner |
| 3 | Type legalization (then Combine 2) | Every value type is legal | Type Legalization |
| 4 | Vector legalization (then types and Combine 3 if it changed anything) | Vector operations supported | Operation and Vector Legalization |
| 5 | Operation legalization | Every operation Legal or custom-lowered | Operation and Vector Legalization |
| 6 | DAG Combine 4 | Legal DAG, cleaned up | DAG Combiner |
| 7 | Instruction selection | Machine nodes | Instruction Selection |
| 8 | Scheduling and emission | Linear MachineInstrs | Scheduling and MIR Emission |
The exact order, the traversal each phase uses and a sequence diagram are on Pipeline, Phases and Traversal Orders. PHI handling spans several phases and has its own page: PHI Node Resolution.
Reading Guide
- New to the codebase: Core Data Structures, then follow the pages in order.
- Interested in AArch64 behaviour: AArch64 Walkthroughs, starting with the End-to-End Example.
- Adding a pattern, combine or lowering: Tooling, Debugging and Extending.
Pipeline, Phases and Traversal Orders
Relevant source files
The following files were used as context for generating this wiki page:
- llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
- llvm/include/llvm/CodeGen/DAGCombine.h
- llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
- llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp
- llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp
- llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp
- llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp
This page gives the exact order of the phases in SelectionDAGISel::CodeGenAndEmitDAG and the order in which each phase visits the nodes of the DAG.
Purpose and Scope
It documents the control flow inside one CodeGenAndEmitDAG call and summarises the traversal strategy of each phase, because the traversal direction explains many behaviours (why a pattern can absorb its operands, why combines see operands in their original shape, why legalization repeats).
Each phase has its own page; this page is the reference for how they connect. See SelectionDAG Overview for the big picture.
Phase Order in CodeGenAndEmitDAG
CodeGenAndEmitDAG sets NewNodesMustHaveLegalTypes = false for the first combine, then switches it to true after type legalization.
sequenceDiagram
participant D as SelectionDAGISel
participant C as DAGCombiner
participant T as DAGTypeLegalizer
participant V as VectorLegalizer
participant L as SelectionDAGLegalize
participant S as Scheduler and InstrEmitter
D->>C: Combine(BeforeLegalizeTypes)
D->>T: LegalizeTypes()
alt types changed
D->>C: Combine(AfterLegalizeTypes)
end
D->>V: LegalizeVectors()
alt vectors changed
D->>T: LegalizeTypes() again
D->>C: Combine(AfterLegalizeVectorOps)
end
D->>L: Legalize()
D->>C: Combine(AfterLegalizeDAG)
D->>D: ComputeLiveOutVRegInfo()
D->>D: DoInstructionSelection()
D->>S: Run(), EmitSchedule()
Notes taken from the source:
- Combine runs 2 and 3 are conditional:
Combine(AfterLegalizeTypes)runsif (Changed)afterLegalizeTypes, and the vector-legalized sequence runs only ifLegalizeVectors()returned true. ComputeLiveOutVRegInfo(skipped at-O0) records known-bits and sign-bit facts for integer values copied to virtual registers, which later blocks use.- Debug dump titles in order: Initial selection DAG, Optimized lowered selection DAG, Type-legalized selection DAG, Optimized type-legalized selection DAG, Vector-legalized selection DAG, Vector/type-legalized selection DAG, Optimized vector-legalized selection DAG, Legalized selection DAG, Optimized legalized selection DAG, Selected selection DAG.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:947-1200, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:910-945
Combine Levels
The CombineLevel enum tells each fold how much it may assume. Inside DAGCombiner::Run three flags are derived from it.
| Run | CombineLevel |
LegalTypes |
LegalOperations |
LegalDAG |
|---|---|---|---|---|
| 1 | BeforeLegalizeTypes | false | false | false |
| 2 | AfterLegalizeTypes | true | false | false |
| 3 | AfterLegalizeVectorOps | true | true | false |
| 4 | AfterLegalizeDAG | true | true | true |
Sources: llvm/include/llvm/CodeGen/DAGCombine.h:15-20, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1846-1851
Traversal Orders at a Glance
| Step | Visit order | In one sentence |
|---|---|---|
| Block order | Reverse post-order of the CFG | Predecessors are selected before successors where the CFG allows |
| Build DAG | IR instruction order inside the block | One visit per IR instruction, forward |
| DAGCombiner | Worklist, last-in-first-out, seeded in AllNodes order | Starts at the root, descends into operands; every change re-queues the changed node's users |
| Type legalizer | Operands before users | A node is processed once all its operands are |
| Vector legalizer | Operands before users (topological order) | One sweep over the nodes |
| Operation legalizer | End of AllNodes toward the start (users before operands), repeated until nothing new is legalized | Reaches a fixed point because legalization creates new nodes |
| Instruction selection | End of AllNodes toward the start (root first), single sweep | Users first, so a pattern can absorb its operands |
| Scheduling | Bottom-up list scheduling from the exit node, then reversed | Source-order priority on AArch64 |
| Emission | The scheduled sequence, forward | One MachineInstr per machine node |
flowchart TB
subgraph UF["Users before operands (root first)"]
A1["DAGCombiner<br/>worklist LIFO"]
A2["SelectionDAG::Legalize<br/>sweeps, repeat to fixed point"]
A3["DoInstructionSelection<br/>single sweep"]
end
subgraph OF["Operands before users (leaves first)"]
B1["DAGTypeLegalizer::run<br/>ready-node worklist"]
B2["VectorLegalizer::Run<br/>topological order"]
end
Sources: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1846-1963, llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp:200-487, llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp:207-247, llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:6328-6375, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1287-1392, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp:1580-1621
Pipeline Diagram
flowchart TD P1["1 Build DAG<br/>SelectionDAGBuilder"] --> P2["2 DAG Combine 1"] P2 --> P3["3 Type legalization<br/>then Combine 2 if changed"] P3 --> P4["4 Vector legalization<br/>then types and Combine 3 if changed"] P4 --> P5["5 Operation legalization"] P5 --> P6["6 DAG Combine 4"] P6 --> P7["7 Instruction selection<br/>DoInstructionSelection"] P7 --> P8["8 Scheduling and emission<br/>InstrEmitter"] P8 --> OUT["MachineInstrs in the MachineBasicBlock"]
Core Data Structures
Relevant source files
The following files were used as context for generating this wiki page:
A SelectionDAG is a graph of SDNodes where an edge is an SDValue (a node plus which of its results is used). Edges come in three kinds: data, chain (ordering of side effects) and glue (must stay adjacent).
Purpose and Scope
This page defines the vocabulary used by every later page: SelectionDAG, SDNode, SDValue, SDUse, value types, opcode ranges, chains, glue, uniquing and node numbering. It ends with a first DAG, (a * b) + c, printed in the format of -debug-only=isel.
Class Relationships
classDiagram
class SelectionDAG {
AllNodes
EntryNode
Root
getNode()
AssignTopologicalOrder()
ReplaceAllUsesWith()
}
class SDNode {
NodeId
NodeType
ValueList
OperandList
}
class SDValue {
Node
ResNo
}
class SDUse {
Val
User
}
SelectionDAG "1" o-- "*" SDNode : owns
SDNode "1" *-- "*" SDUse : operands
SDUse --> SDValue : holds
SDValue --> SDNode : points to
| Type | Meaning | Key facts |
|---|---|---|
SelectionDAG | The graph for one block | Owns every node in an intrusive list (AllNodes), keeps a FoldingSet for uniquing, has an EntryNode and a Root (the last chain) |
SDNode | One operation | An opcode (NodeType), result types (ValueList), operands (OperandList, an array of SDUse), flags (nsw, nuw, fast-math), a debug location and a NodeId |
SDValue | One result of a node | A pair (SDNode*, ResNo); printed t5 for result 0 and t5:1 for result 1 |
SDUse | One operand slot | Records the user and the used value and links into the definition's use list, so ReplaceAllUsesWith is cheap |
EVT / MVT | Value type | MVT is a simple type (i32, v4i32, MVT::Other, MVT::Glue); EVT also covers extended types such as i7, i128, v3i16 |
Sources: llvm/include/llvm/CodeGen/SelectionDAG.h:231-273, llvm/include/llvm/CodeGen/SelectionDAGNodes.h:147, llvm/include/llvm/CodeGen/SelectionDAGNodes.h:279, llvm/include/llvm/CodeGen/SelectionDAGNodes.h:510, llvm/include/llvm/CodeGen/SelectionDAGNodes.h:656-663
Opcode Ranges
The value of a node's opcode tells you how far the node has come in the pipeline.
| Range | Name | Example | Created by |
|---|---|---|---|
0 .. ISD::BUILTIN_OP_END-1 | Target-independent ISD:: | ISD::ADD, ISD::LOAD, ISD::SETCC | SelectionDAGBuilder, combiner, legalizer |
>= ISD::BUILTIN_OP_END | Target-specific DAG nodes | AArch64ISD::CSEL, AArch64ISD::ADRP, AArch64ISD::CALL | Target LowerOperation and PerformDAGCombine |
negative (~MachineOpc) | Machine nodes (already selected) | AArch64::ADDWrr | AArch64DAGToDAGISel and the generated matcher |
SDNode::isTargetOpcode() tests NodeType >= ISD::BUILTIN_OP_END; isMachineOpcode() tests NodeType < 0 and getMachineOpcode() returns the instruction number. After selection the DAG holds only machine nodes plus a few structural kinds (CopyToReg, CopyFromReg, TokenFactor, EntryToken).
Sources: llvm/include/llvm/CodeGen/SelectionDAGNodes.h:709, llvm/include/llvm/CodeGen/SelectionDAGNodes.h:758-765, llvm/include/llvm/CodeGen/ISDOpcodes.h:1666-1668
The Three Kinds of Edge
- Data edges carry values such as
i32orv4f32. Independent data-only nodes have no order between them. - Chain edges have type
MVT::Other, printedch. They serialise anything with a side effect (loads, stores, calls,CopyToReg, barriers). A node takes a chain in and produces a chain out; independent chains are merged withISD::TokenFactor. The chain starts atISD::EntryTokenand ends at the DAG'sRoot. - Glue edges have type
MVT::Glue, printedglue. Glue says the producer and consumer must be scheduled back to back. It is used where hardware has an implicit register dependency, such as theCopyToRegof outgoing arguments right before a call.
AArch64 models condition flags as an explicit i32 value instead of glue: AArch64ISD::SUBS returns (i32, i32) where result 1 is NZCV.
A load shows all three ideas: t9: i32,ch = load<(load (s32) from %ir.p)> t0, t4, undef:i64 has results (value, chain) and operands (chain, base pointer, offset); the trailing <...> is its MachineMemOperand.
Sources: llvm/include/llvm/CodeGen/ISDOpcodes.h:48-53, llvm/include/llvm/CodeGen/ISDOpcodes.h:224-230
Uniquing: Free Common-Subexpression Elimination
SelectionDAG::getNode builds a FoldingSetNodeID from opcode, result types, operands and flags and looks it up. If an identical node exists, it is returned instead of creating a new one, so the same add t2, t4 built twice is one node with two users. Nodes whose last result is MVT::Glue are not uniqued, and loads and stores are only equal if their chain operand is equal.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1018-1043, llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:7458
Special Nodes in Dumps
| Dump text | Opcode | Meaning |
|---|---|---|
t0: ch,glue = EntryToken | ISD::EntryToken | Start of the chain |
t2: i32,ch = CopyFromReg t0, Register:i32 %0 | ISD::CopyFromReg | Read a virtual or physical register: how arguments and cross-block values enter a block's DAG |
t9: ch,glue = CopyToReg t0, Register:i32 $w0, t7 | ISD::CopyToReg | Write a register: return values, outgoing arguments and live-out values leave this way |
Constant:i32<3> | ISD::Constant | A constant that combine and legalization may change |
TargetConstant:i32<3> | ISD::TargetConstant | A final immediate; selection places it in the instruction as is |
GlobalAddress:i64<ptr @g> 0 | ISD::GlobalAddress | Address of a symbol; the target lowers it (ADRP + ADD :lo12:) |
FrameIndex:i64<0> | ISD::FrameIndex | Address of a stack slot |
t6: ch = TokenFactor t3:1, t5:1 | ISD::TokenFactor | Joins independent chains |
Node Numbering
Every node has an integer NodeId. SelectionDAG::AssignTopologicalOrder() runs a Kahn-style sort and renumbers AllNodes so every node appears after all its operands (EntryToken first, Root last). Instruction selection uses this order backwards, and the node ids double as a cycle-safety check during folding. See Pipeline, Phases and Traversal Orders.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:13469-13551
Example: (a * b) + c
For i32 madd(i32 a, i32 b, i32 c) the initial DAG is shown below. The text dump follows the -debug-only=isel format; node numbers are illustrative.
t0: ch,glue = EntryToken
t2: i32,ch = CopyFromReg t0, Register:i32 %0 ; a (live-in $w0 copied to vreg %0)
t4: i32,ch = CopyFromReg t0, Register:i32 %1 ; b
t6: i32,ch = CopyFromReg t0, Register:i32 %2 ; c
t7: i32 = mul t2, t4
t8: i32 = add t7, t6
t10: ch,glue = CopyToReg t0, Register:i32 $w0, t8 ; return value into $w0
t11: ch = AArch64ISD::RET_GLUE t10, Register:i32 $w0, t10:1
flowchart LR n0["t0 EntryToken"] n2["t2 CopyFromReg %0"] n4["t4 CopyFromReg %1"] n6["t6 CopyFromReg %2"] n7["t7 mul"] n8["t8 add"] n10["t10 CopyToReg $w0"] n11["t11 RET_GLUE"] n0 -.-> n2 n0 -.-> n4 n0 -.-> n6 n2 --> n7 n4 --> n7 n7 --> n8 n6 --> n8 n8 --> n10 n0 -.-> n10 n10 -.-> n11
Solid arrows are data edges and dashed arrows are chain edges. The chain t0 -> t10 -> t11 is the only ordering; the glue operand t10:1 makes the return sit directly after the copy into $w0.
DAG Construction
Relevant source files
The following files were used as context for generating this wiki page:
SelectionDAGBuilder walks the instructions of one IR basic block in program order and turns each into SDNodes, using a per-block map from IR Value to SDValue. Values that live across blocks are exchanged through virtual registers with CopyToReg and CopyFromReg.
Purpose and Scope
This page covers phase 1: the driver loop, the translation of each IR instruction, chain handling while building, cross-block values and function arguments. PHI handling during construction is summarised here and detailed in PHI Node Resolution.
Driver Flow
flowchart TD A["runOnMachineFunction"] --> B["FunctionLoweringInfo::set<br/>vregs, MBBs, empty machine PHIs"] B --> C["SelectAllBasicBlocks"] C --> D["LowerArguments<br/>entry block only"] C --> E["for each block in reverse post-order"] E --> F["SelectBasicBlock"] F --> G["SDB visit for each instruction"] G --> H["CodeGenAndEmitDAG"] E --> I["FinishBasicBlock<br/>patch successor PHIs, switch extras"]
FunctionLoweringInfo::setcreates oneMachineBasicBlockper IR block, assigns virtual registers to values used outside their block or by a PHI, and creates an empty machinePHIfor every live IR PHI.SelectAllBasicBlocksvisits blocks in reverse post-order. For the entry block it first callsLowerArguments, which calls the target'sLowerFormalArguments.SelectBasicBlock(Begin, End)callsSDB->visit(*I)for each instruction, sets the DAG root togetControlRoot(), and callsCodeGenAndEmitDAG().FinishBasicBlockattaches PHI operands, handles switch-lowering extras (jump tables, bit tests, stack-protector blocks) and runsCodeGenAndEmitDAGagain for any extra machine block it created.
One IR block normally yields one DAG, but it can become several machine blocks, and with FastISel only the part FastISel could not select is built as a DAG.
Sources: llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:86-335, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1656-1971, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:884-908, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1974-2227
IR Instruction to DAG Node
SelectionDAGBuilder::visit(const Instruction&) dispatches on the IR opcode. After visiting a non-terminator it calls CopyToExportRegsIfNeeded, and just before a terminator it calls HandlePHINodesInSuccessorBlocks.
| LLVM IR | Builder function | Initial DAG node(s) |
|---|---|---|
add, sub, mul, and, or, xor, shl, lshr, ashr | visitBinary | ISD::ADD, SUB, MUL, AND, OR, XOR, SHL, SRL, SRA; nsw/nuw/exact become node flags |
sdiv, udiv, srem, urem | visitBinary | ISD::SDIV, UDIV, SREM, UREM |
icmp | visitICmp | ISD::SETCC with result type i1 and a CondCodeSDNode |
select | visitSelect | ISD::SELECT (VSELECT for vectors) |
zext, sext, trunc, bitcast | visitZExt ... | ZERO_EXTEND, SIGN_EXTEND, TRUNCATE, BITCAST |
getelementptr | visitGetElementPtr | ADD ptr, (MUL idx, size); constant indices fold into one offset; a power-of-two size becomes SHL |
load | visitLoad | ISD::LOAD chain, ptr, undef, results (value, chain) |
store | visitStore | ISD::STORE chain, value, ptr, undef, result chain |
phi | none | No node. The PHI's virtual register is read with CopyFromReg when used |
br | visitCondBr, visitUncondBr | ISD::BR, or ISD::BRCOND chain, cond, BasicBlock plus ISD::BR |
call | visitCall, LowerCallTo | The target's LowerCall: CALLSEQ_START, CopyToReg per argument, AArch64ISD::CALL, CALLSEQ_END, CopyFromReg per result |
ret | visitRet | The target's LowerReturn: CopyToReg $w0/$x0/$q0 and AArch64ISD::RET_GLUE |
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:1372-1418, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:3738-3756, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:3808-3833, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:3863-4007, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:4497-4666, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:4740-4862, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:4920-4993, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2217-2379, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2840-2926, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:9316-9437
Chains While Building
The builder keeps a current root chain and a few pending lists so independent memory operations do not get a false order.
- Loads are collected in
PendingLoads. A load takes the current chain as input but does not become the new root; the chains are merged with aTokenFactoronly when something needs a full ordering. Two loads can therefore be reordered freely. - Stores, calls and ABI register copies (return values, outgoing arguments) ask for the root with
getRoot()(stores usegetMemoryRoot()), which first flushesPendingLoadsinto aTokenFactor. They chain on top of the result and become the new root. - Exports (
CopyToRegfor values leaving the block) are collected inPendingExportsand joined bygetControlRoot(), which becomes the DAG'sRoot.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:1206-1229
Values Across Blocks
getValue(V) checks NodeMap first, then getCopyFromRegs (is there a virtual register for V in FuncInfo.ValueMap?), then builds a constant or other leaf. A value is therefore a direct SDValue in its defining block and a CopyFromReg in any other block.
After each non-terminator, CopyToExportRegsIfNeeded emits a CopyToReg into the value's virtual register if one was assigned. FunctionLoweringInfo::set assigns registers to every value that is used outside its block or by a PHI.
sequenceDiagram participant FLI as FunctionLoweringInfo participant SDB as SelectionDAGBuilder participant DAG as SelectionDAG FLI->>FLI: InitializeRegForValue for exported values SDB->>DAG: visit(add) creates the ADD node SDB->>DAG: CopyToExportRegsIfNeeded emits CopyToReg to vreg Note over SDB,DAG: another block later SDB->>DAG: getValue finds vreg in ValueMap, emits CopyFromReg
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:1798-1815, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2384-2395, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:11860-11884, llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:46-55, llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:392-400
Function Arguments on AArch64
AArch64TargetLowering::LowerFormalArguments runs the calling-convention rules from AArch64CallingConvention.td over the IR argument types. For an argument passed in $w0 it registers a live-in (MF.addLiveIn, returning a vreg such as %0) and creates CopyFromReg Chain, Register:i32 %0. In the final MIR this appears as liveins: $w0 on the block and %0:gpr32 = COPY $w0 at its top; the copies are inserted by MachineRegisterInfo::EmitLiveInCopies after all blocks are selected (see Scheduling and MIR Emission).
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9059-9520, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:12077-12441
Example: smin
define i32 @smin(i32 %a, i32 %b) {
%c = icmp slt i32 %a, %b
%r = select i1 %c, i32 %a, i32 %b
ret i32 %r
}
Initial DAG (reconstructed in -debug-only=isel format; node numbers are illustrative):
t0: ch,glue = EntryToken
t2: i32,ch = CopyFromReg t0, Register:i32 %0
t4: i32,ch = CopyFromReg t0, Register:i32 %1
t5: i1 = setcc t2, t4, setlt:ch
t6: i32 = select t5, t2, t4
t8: ch,glue = CopyToReg t0, Register:i32 $w0, t6
t9: ch = AArch64ISD::RET_GLUE t8, Register:i32 $w0, t8:1
AArch64 has no 1-bit registers, so i1 is an illegal type. Here the problem disappears early, because the combiner rewrites select (setcc ...) as select_cc before type legalization starts (see DAG Combiner). A setcc whose i1 result survives is promoted by the type legalizer (see Type Legalization). The example continues on Operation and Vector Legalization.
DAG Combiner
Relevant source files
The following files were used as context for generating this wiki page:
DAGCombiner is the DAG's peephole optimiser: a worklist algorithm that rewrites nodes until nothing more fires. It runs up to four times during selection, each time with different rules about what it may create.
Purpose and Scope
This page describes the DAGCombiner::Run algorithm, the four combine levels, the categories of folds, the AArch64 target hooks, and three worked examples. It is not a single top-to-bottom pass, and not a fixed-point loop over the whole graph either: only nodes touched by a change are revisited.
The Algorithm
flowchart TD
S["Seed worklist with every node in AllNodes order"] --> P["Pop node N from the back"]
P --> D{"N has no users?"}
D -- yes --> DEL["Delete N and re-queue its operands"]
DEL --> P
D -- no --> LG{"Level is AfterLegalizeDAG?"}
LG -- yes --> RL["Re-legalize N"]
RL --> Q
LG -- no --> Q["Queue N's operands that were not combined before"]
Q --> C["combine of N"]
C --> R{"Replacement found?"}
R -- no --> P
R -- yes --> REP["ReplaceAllUsesWith, queue the new node and all its users"]
REP --> P
- Seed. Every node in
DAG.allnodes()is pushed on a worklist. With-combiner-topological-sorting(or when the target'suseTopologicalSorting()says so) the DAG is first sorted and pushed in reverse. Each node stores its worklist index in the node itself;-2means already combined once. - Pop from the back. The worklist is a vector used as a stack, so the node created last (normally the root) is processed first.
- Dead node? A popped node with no users is deleted and its operands are queued again.
- After legalization only: at
AfterLegalizeDAGthe node is first re-legalized withDAG.LegalizeOp, so combines never see an illegal node. - Queue the operands that have not been combined yet. Because the list is last-in-first-out, the operands are visited next: the walk descends from users toward operands.
combine(N), stopping at the first success:- the generic
visit(N), onevisitXxxper opcode; - the target hook
TLI.PerformDAGCombine(N, DCI), called only if the target registered the opcode withsetTargetDAGCombine(or N is a target opcode); - operation promotion (
PromoteIntBinOpand friends); - for commutative operations, reuse of an existing operand-swapped node.
- Replace. If a replacement
RVcame back,ReplaceAllUsesWith(N, RV)rewires every user, and the new node and all its users go on the worklist. A dead N is deleted.
Two consequences follow. A pattern rooted at a user sees its operands in their original shape, and when an operand later simplifies the user is re-queued for a second look. And termination relies on every fold making the DAG better by some measure: two folds that undo each other make llc hang.
Uniquing (see Core Data Structures) makes common-subexpression elimination implicit.
Sources: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1846-1963, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:235-252, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:274-294, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:2152-2222
The Four Invocations
The CombineLevel enum is in DAGCombine.h. Run derives LegalTypes, LegalOperations and LegalDAG from it (see the table on Pipeline, Phases and Traversal Orders).
| Run | Level | Runs | Illegal types allowed? | Illegal operations allowed? |
|---|---|---|---|---|
| 1 | BeforeLegalizeTypes | always | yes | yes |
| 2 | AfterLegalizeTypes | only if type legalization changed the DAG | no | yes |
| 3 | AfterLegalizeVectorOps | only if vector legalization changed the DAG | no | no |
| 4 | AfterLegalizeDAG | always | no | no |
Combines guard themselves with the flags, for example if (!LegalOperations || TLI.isOperationLegal(ISD::ROTL, VT)), so a fold never introduces something the target cannot select. TargetLowering::DAGCombinerInfo exposes isBeforeLegalize(), isBeforeLegalizeOps() (true for levels 1 and 2) and isAfterLegalizeDAG() to target code.
Sources: llvm/include/llvm/CodeGen/DAGCombine.h:15-20, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1846-1851, llvm/include/llvm/CodeGen/TargetLowering.h:4574-4587
What the Combines Do
| Category | Example fold | Where |
|---|---|---|
| Constant folding | add 3, 4 becomes 7 | getNode folds on creation |
| Identities | x + 0, x * 1, x & -1, x ^ x | visitADD, visitMUL, ... |
| Reassociation | (x + c1) + c2 becomes x + (c1 + c2) | reassociateOps |
| Strength reduction | mul x, 8 becomes shl x, 3; udiv x, c becomes multiply-high and shifts | visitMUL, visitUDIV |
| Extension folding | zext (load i8) becomes a ZEXTLOAD; trunc (zext x) becomes x | visitZERO_EXTEND, visitTRUNCATE |
| Demanded bits | Remove masks or extensions whose bits no user reads | SimplifyDemandedBits |
| Compare and select | select (setcc a, b, cc), x, y becomes select_cc a, b, x, y, cc when SELECT_CC is legal or Custom; brcond (setcc ...) becomes br_cc | visitSELECT, visitBRCOND |
| Memory | Store-to-load forwarding, store merging, load narrowing, forming pre/post-indexed loads and stores | visitLOAD, visitSTORE, CombineToPreIndexedLoadStore, CombineToPostIndexedLoadStore |
| Vectors | Fold extract_vector_elt (build_vector ...), merge shuffles, detect splats | visitEXTRACT_VECTOR_ELT, visitVECTOR_SHUFFLE |
Sources: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:13243-13440, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:376-377, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:4868
AArch64 Target Combines
AArch64TargetLowering registers the opcodes it wants with setTargetDAGCombine in its constructor, and PerformDAGCombine is a switch over N->getOpcode() that dispatches to specialised functions: performAddSubCombine, performMulCombine, performANDCombine, performORCombine, performSelectCombine, performSETCCCombine, performLOADCombine, performSTORECombine, performExtendCombine, performBRCONDCombine, performTBZCombine and more. They match target-aware shapes the generic combiner cannot know, such as turning mul x, (2^n + 1) into add (shl x, n), x.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:1188-1205, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:30803-31168
Example 1: x * 9
performMulCombine returns early while DCI.isBeforeLegalizeOps() is true, so the fold fires in the later runs. It sees that 9 is 2^3 + 1 and rewrites:
before: t5: i32 = mul t2, Constant:i32<9>
after: t6: i32 = shl t2, Constant:i64<3>
t7: i32 = add t2, t6 ; replaces t5 for all users
Instruction Selection then matches the add plus shl to a single ADDWrs. Real llc output confirms it: the MIR contains only ADDWrs %0, %0, 3 and the assembly is add w0, w0, w0, lsl #3.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:21202-21213, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:21266-21306
Example 2: x / 10 (unsigned 32-bit)
The generic visitUDIV replaces division by a constant with multiplication by a magic reciprocal (TargetLowering::BuildUDIV). AArch64 has a fast 32 by 32 to 64 multiply, so the result is a widening multiply and a shift:
t3: i32 = udiv t2, Constant:i32<10>
==>
t7: i64 = zero_extend t2
t9: i64 = mul t7, Constant:i64<3435973837> ; 0xCCCCCCCD
t10: i64 = srl t9, Constant:i64<35>
t11: i32 = truncate t10
The real post-selection MIR matches: MOVi32imm -858993459 (the same constant as a signed 32-bit value), UMADDLrrr %0, killed %1, $xzr, UBFMXri killed %2, 35, 63, then a sub_32 copy for the truncate.
Example 3: Post-Indexed Load Formation
In the loop of PHI Node Resolution the IR is a load i32, ptr %p followed in the same iteration by getelementptr i8, ptr %p, i64 4. CombineToPostIndexedLoadStore asks the target getPostIndexedAddressParts; AArch64 answers yes for a small constant offset, so the load and the pointer add merge into one indexed load node that produces both the loaded value and the incremented pointer. AArch64 Instruction Selection shows it selected as LDRWpost.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:31289-31350
Switches That Help When Debugging
-combiner-disabled turns the generic combiner off (a quick check for whether a miscompile comes from a combine), -combiner-topological-sorting changes the visit order, -combiner-global-alias-analysis lets store and load combines use IR alias analysis, and -combiner-store-merging=false disables store merging. -debug-counter=dagcombine-skip=N,dagcombine-count=M bisects combines in assertion builds. See Tooling, Debugging and Extending.
Legalization
Relevant source files
The following files were used as context for generating this wiki page:
Legalization rewrites the DAG so that every value has a type the target keeps in a register and every operation is one the target can select. It is split into three components that run in a fixed order, with combine runs in between.
Purpose and Scope
This page is the overview of legalization: what the three legalizers are, how the target describes what it supports, and how they interact. The detail is on Type Legalization and Operation and Vector Legalization.
The Three Legalizers
flowchart LR A["DAG after Combine 1<br/>any type, any operation"] --> T["DAGTypeLegalizer<br/>types become legal"] T --> C2["Combine 2<br/>if changed"] C2 --> V["VectorLegalizer<br/>vector operations supported"] V --> T2["DAGTypeLegalizer again<br/>if vectors changed"] T2 --> C3["Combine 3"] C3 --> O["SelectionDAGLegalize<br/>operations legal or Custom"] O --> C4["Combine 4"]
| Legalizer | Entry point | Question it answers | Mechanism |
|---|---|---|---|
| Type legalizer | SelectionDAG::LegalizeTypes() calling DAGTypeLegalizer::run | Can this value live in a register? | Promote, expand, soften, scalarize, split, widen |
| Vector legalizer | SelectionDAG::LegalizeVectors() calling VectorLegalizer::Run | Does the target have this vector operation? | Promote, Custom, Expand (often by unrolling) |
| Operation legalizer | SelectionDAG::Legalize() calling SelectionDAGLegalize | Does the target have this operation on this type? | Legal, Custom, Expand, LibCall, Promote |
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp:200-487, llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp:207-247, llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp:2513-2515, llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:6328-6375
How a Target Declares Support
Everything is declared in the AArch64TargetLowering constructor and read back by the generic code through TargetLowering queries.
| Declaration | Meaning | Read back with |
|---|---|---|
addRegisterClass(MVT, RegClass) then computeRegisterProperties | Which types are legal, and the type action for every other type | getTypeAction, getTypeToTransformTo |
setOperationAction(ISD::OP, MVT, Action) | The action for an opcode on a type | getOperationAction, isOperationLegal, isOperationLegalOrCustom |
setLoadExtAction, setTruncStoreAction, setCondCodeAction | Extending loads, truncating stores, condition codes | matching getters |
setIndexedLoadAction, setIndexedStoreAction | Pre/post-increment addressing | isIndexedLoadLegal |
setTargetDAGCombine(ISD::OP) | Opcodes the target wants in PerformDAGCombine | hasTargetDAGCombine |
setBooleanContents(...) | What a boolean looks like in a register | getBooleanContents |
The five actions of TargetLowering::LegalizeAction are:
| Action | Meaning |
|---|---|
Legal | The target supports the operation natively |
Promote | Execute the operation in a larger type |
Expand | Rewrite using other operations; fall back to a libcall if impossible |
LibCall | Always use a library call |
Custom | Call the target's LowerOperation hook |
Sources: llvm/include/llvm/CodeGen/TargetLowering.h:221-242, llvm/include/llvm/CodeGen/TargetLowering.h:1312, llvm/include/llvm/CodeGen/TargetLowering.h:2713-2740, llvm/include/llvm/CodeGen/TargetLowering.h:2918, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:460-554
Division of Labour
Type legalization changes types and does not care whether an operation exists for the new type: i32 = ctlz t2 stays as it is even if the target has no count-leading-zeros instruction. Whether the operation is legal for its (now legal) type is the job of the operation legalizer. The one overlap is that type-legalization handlers sometimes build a different, equivalent operation (such as uaddo plus uaddo_carry when expanding an i128 add), which operation legalization then checks in turn.
After the last combine, SelectionDAGISel::ComputeLiveOutVRegInfo records known-bits and sign-bit facts for integer values copied to virtual registers, which later blocks use to simplify their own DAGs. After that the DAG contains only operations the instruction selector can match.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:910-945
Type Legalization
Relevant source files
The following files were used as context for generating this wiki page:
Type legalization rewrites the whole DAG so that every value has a type the target keeps in a register. It does not care whether an operation exists for that type.
Purpose and Scope
This page covers DAGTypeLegalizer: which types are legal on AArch64, the type actions, the algorithm, and worked examples of promotion, expansion, vector splitting and the setcc result type. The code is in LegalizeTypes.cpp, LegalizeIntegerTypes.cpp, LegalizeFloatTypes.cpp, LegalizeVectorTypes.cpp and LegalizeTypesGeneric.cpp, entered through CurDAG->LegalizeTypes(). See Legalization for the overall structure.
Legal Types and Type Actions on AArch64
The target declares legal types with addRegisterClass(MVT, RegClass) and then calls computeRegisterProperties, which fills a table mapping each type to a type action. On AArch64 the scalar registers are i32 (GPR32all) and i64 (GPR64all); the FP registers are f16, bf16, f32, f64 and f128 whenever FP is available; NEON vectors such as v4i32 live in FPR128 and FPR64.
Action (LegalizeTypeAction) |
Meaning | AArch64 example |
|---|---|---|
TypePromoteInteger | Make the integer wider | i1, i8, i16 become i32 |
TypeExpandInteger | Split into two integers of half the width | i128 becomes two i64 |
TypeSoftenFloat | Treat a float as an integer and use library calls | Not used for AArch64 f32/f64 (FP hardware exists) |
TypeExpandFloat | Split a float into two halves | Rare (ppcf128) |
TypeScalarizeVector | One-element vector becomes its element | |
TypeSplitVector | Split into two half-width vectors | <8 x i32> becomes two <4 x i32> |
TypeWidenVector | Pad to a legal vector | <3 x i32> becomes <4 x i32>; AArch64 also widens v1i8, v1i16, v1i32 |
TypeSoftPromoteHalf | Keep half as i16 and compute in float | Targets with no f16 register class (AArch64 keeps f16 legal and promotes its arithmetic to f32) |
A related query is the setcc result type: AArch64TargetLowering::getSetCCResultType returns i32 for scalar compares and an integer vector of the same shape for vector compares.
Sources: llvm/include/llvm/CodeGen/TargetLowering.h:231-242, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:471-486, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:552, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:2685-2692, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:32176-32184
The Algorithm
DAGTypeLegalizer::run() works bottom-up in dependency order, the opposite of the combiner.
flowchart TD
I["Label nodes<br/>leaves ReadyToProcess, others count unprocessed operands"] --> W["Pop ready node N"]
W --> R{"Any result type illegal?"}
R -- yes --> RH["Result handler<br/>PromoteIntegerResult, ExpandIntegerResult, SplitVectorResult, ..."]
R -- no --> O{"Any operand type illegal?"}
O -- yes --> OH["Operand handler<br/>PromoteIntegerOperand, SplitVectorOperand, ..."]
O -- no --> OK["N is legally typed"]
RH --> DONE["Mark Processed and decrement the counts of N's users"]
OH --> DONE
OK --> DONE
DONE --> NX["Users whose count reaches zero become ready"]
NX --> W
- Leaves (no operands) are
ReadyToProcessand go on a worklist; every other node gets a count of its unprocessed operands. - Pop a ready node. Scan its result types; at the first illegal one call the matching handler, which must deal with all results of the node.
- If all result types are legal, scan operand types. An illegal operand (for example a store of an
i8) is handled by an operand handler that updates the node in place or replaces it. - When a node is done, decrement the pending count of each user; a user at zero is ready.
- Replacements are recorded in side tables (
PromotedIntegers,ExpandedIntegers,SplitVectors,WidenedVectors, ...). A user asks for the legal form of an illegal value withGetPromotedInteger,GetExpandedInteger,GetSplitVector, and so on. New nodes are re-analysed so they are legal too. - At the end dead nodes are removed.
Because operands are always done before users, a handler can rely on the legalised form of every operand.
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp:200-487
Promotion
Promoting i8 to i32 leaves the upper 24 bits unspecified (an any-extend) unless the operation cares. The handlers pick the cheapest extension that is still correct:
add,sub,mul,and,or,xor,shl: low bits of the result depend only on low bits of the inputs, so any-extend is fine.lshr,ashr,udiv,sdiv,urem,srem, comparisons,ctpop,uitofp/sitofp: high bits matter, so the operand is first fixed withzero_extend_inreg(anandwith a mask) orsign_extend_inreg.- A value that must be exactly
i8again (8-bit store, return in a register) is narrowed withtruncateor stored as a truncating store.
Example (real llc result: add8 in Arithmetic and Data Movement):
before: t3: i8 = truncate t2 ; t2 = CopyFromReg i32 (value arrives in $w0)
t5: i8 = truncate t4
t6: i8 = add t3, t5
t7: i32 = any_extend t6 ; return value convention
after: t6: i32 = add t2, t4 ; promoted; operands are the original i32 values
; t7 disappears: any_extend (truncate x) folds to x
The result is a single ADDWrr; the garbage upper bits are never observed.
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp:1454-1494
Expansion: i128
An i128 add goes through ExpandIntegerResult, whose add handler splits the operands into low and high i64 halves with GetExpandedInteger and emits a carry chain:
before: t10: i128 = add a, b
after: t11: i64,i32 = uaddo lo_a, lo_b ; low half, produces carry
t12: i64,i32 = uaddo_carry hi_a, hi_b, t11:1
; result = (t11, t12); no i128 value remains
The real MIR is ADDSXrr %0, %2, implicit-def $nzcv followed by ADCXr %1, %3, implicit $nzcv, i.e. adds x0, x0, x2 and adc x1, x1, x3. Other i128 operations expand differently: shifts use funnel-shift sequences, multiplies use umul_lohi pieces, and division becomes a runtime call (__divti3).
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp:3905-4046
Vectors: Split and Widen
<8 x i32> is not a register type, so SplitVectorResult splits every operation on it into two operations on <4 x i32>, with extract_subvector for the inputs and concat_vectors for the result. After the combiner cleans up the extract and concat scaffolding, the real MIR is two ADDv4i32 instructions. A <3 x i32> is widened instead (padded with undef), so one 128-bit operation runs and one lane is ignored.
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp:1358-1685
The setcc Result
Take ret i32 (zext (icmp slt a, b)). The setcc has an illegal i1 result and no combine removes it, because nothing uses it as a select condition. PromoteIntRes_SETCC re-creates it with the target's getSetCCResultType (i32), and the zero_extend of a value that is already 0 or 1 is dropped. AArch64 sets setBooleanContents(ZeroOrOneBooleanContent) in its constructor, which tells the legalizer that a promoted boolean holds exactly 0 or 1 in all 32 bits, so no masking is needed:
before: t5: i1 = setcc t2, t4, setlt:ch
t6: i32 = zero_extend t5
after: t6: i32 = setcc t2, t4, setlt:ch ; promoted result, the zero_extend folded away
Operation legalization then lowers the Custom setcc into a flag-setting subtract and a conditional-select-increment of the zero register (the cset idiom). The real MIR is SUBSWrr %0, %1 followed by CSINCWr $wzr, $wzr, 10 (condition 10 is GE, the inverse of lt), and the assembly is cmp w0, w1 then cset w0, lt.
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp:1454-1494, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:460-468
Operation and Vector Legalization
Relevant source files
The following files were used as context for generating this wiki page:
Once every type is legal, legalization asks for every node: does the target have this operation on this type? Each answer is one of five actions, and the target supplies the Custom ones through LowerOperation.
Purpose and Scope
This page covers the scalar operation legalizer (SelectionDAG::Legalize, SelectionDAGLegalize), the vector operation legalizer (VectorLegalizer), the two target hooks LowerOperation and ReplaceNodeResults, and AArch64 examples. See Legalization for how the three legalizers connect.
Registered Actions on AArch64
setOperationAction(ISD::OPCODE, MVT, Action) in the AArch64TargetLowering constructor fills a table indexed by opcode and simple value type. Anything left unset defaults to Legal for opcodes every target supports and Expand for the rest.
| Action | Registered for | Why on AArch64 |
|---|---|---|
| Custom | SETCC, SELECT, SELECT_CC, BR_CC on i32/i64/f16/f32/f64; BRCOND; also GlobalAddress, ConstantPool, JumpTable, VASTART, UADDO_CARRY, BITCAST | The generic node is not an instruction; the target builds the real sequence |
| Expand | ROTL on i32/i64 | AArch64 has rotate-right only, so rotl x, n is rewritten as rotr x, (size - n) |
| Expand | SDIVREM, UDIVREM, UMUL_LOHI, SMUL_LOHI, MULHU, MULHS (i32) | No combined divide-and-remainder or widening-multiply-pair instruction |
| Expand | EXTLOAD from f16/f32/f64 to wider FP types | Handled by an explicit fpext after a plain load |
| Legal | Indexed (pre/post-increment) LOAD/STORE for i8 to i64, f64 | The hardware has ldr x, [base], #imm forms, so the combiner may form them |
| Legal or Custom | CTPOP on i32/i64 | Legal with the CSSC extension; otherwise Custom (move to a vector register, cnt, addv, move back) |
| Legal or default | SMIN/SMAX/UMIN/UMAX/ABS on i32/i64 | Legal with CSSC; without it SMIN/SMAX expand to compare and select and ABS is Custom |
| LibCall | FADD and friends on f128 | No quad-precision hardware; becomes a call such as __addtf3 |
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:574-593, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:621, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:716-731, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:733-773, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:1138-1142, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:1164-1168
The Scalar Legalizer Algorithm
flowchart TD
A["AssignTopologicalOrder"] --> B["Sweep AllNodes from the end to the start"]
B --> C{"Node dead and not the root?"}
C -- yes --> D["DeleteNode"]
C -- no --> E{"Already in LegalizedNodes?"}
E -- yes --> B
E -- no --> F["LegalizeOp of N"]
F --> B
B --> G{"Whole sweep legalized nothing new?"}
G -- no --> B
G -- yes --> H["RemoveDeadNodes"]
AssignTopologicalOrder()sortsAllNodesoperands-first.- The sweep goes from the end toward the beginning, so users are visited before their operands. The source comment explains it: nodes are seen "with their original operands intact".
- A node with no users that is not the root is deleted; otherwise, if it is not yet in the
LegalizedNodesset,LegalizeOpruns. - Legalization can create new nodes that themselves need legalizing, so the sweep repeats until a whole pass legalizes nothing new.
Inside LegalizeOp the action comes from TLI.getOperationAction. The type used for the lookup depends on the opcode: usually the result type, but for SINT_TO_FP and EXTRACT_VECTOR_ELT it is the operand type, for SIGN_EXTEND_INREG the inner type, for atomics the memory type, and for SETCC/SELECT_CC/BR_CC the condition code is consulted too. Then:
flowchart TD
A["getOperationAction"] --> L{"Action"}
L -- Legal --> N["Nothing to do"]
L -- Custom --> CU["TLI.LowerOperation"]
CU --> CR{"Returned a value?"}
CR -- yes --> RN["ReplaceNode with the result"]
CR -- no --> EX
L -- Expand --> EX["ExpandNode"]
EX --> ER{"Expanded?"}
ER -- yes --> DONE["Done"]
ER -- no --> LC["ConvertNodeToLibcall"]
L -- LibCall --> LC
L -- Promote --> PR["PromoteNode<br/>extend operands, operate wide, truncate"]
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:6328-6375, llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:985-1426, llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:1357-1406
The Two Target Hooks
LowerOperation(SDValue Op, SelectionDAG &DAG)is called for a node whose action is Custom and whose result types are all legal. It returns the replacement, whose result types must match the original; an emptySDValuemeans "I could not", and the generic code falls through to Expand. In AArch64 it is one switch:LowerSETCC,LowerSELECT_CC,LowerBR_CC,LowerGlobalAddress,lowerADDSUBO_CARRY, and so on.ReplaceNodeResults(SDNode *N, Results, DAG)is called when a node has a result of an illegal type and the operation is marked Custom for it, which happens during type legalization. The target pushes legal-typed replacement values, one per result of N, or nothing to decline. AArch64 uses it fori128atomics, certainREAD_REGISTERforms and a few vector conversions.
Sources: llvm/include/llvm/CodeGen/TargetLowering.h:5273-5284, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:8432-8850, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:31808-32145
Example: smin
For select (setcc a, b, setlt), a, b, DAGCombiner::visitSELECT has already rewritten the node in Combine 1 as select_cc a, b, a, b, setlt, because AArch64 registers SELECT_CC as Custom and operations do not have to be legal yet at that level. If a plain select survives instead, LowerSELECT forwards to the same logic; its source comment says it "lowers it the same way as we would lower a SELECT_CC node". LowerSELECT_CC emits a flag-setting subtract and a conditional select that reads its flag result:
before: t6: i32 = select_cc t2, t4, t2, t4, setlt
after: t10: i32,i32 = AArch64ISD::SUBS t2, t4 ; result 1 is the NZCV flags
t11: i32 = AArch64ISD::CSEL t2, t4, Constant:i32<11>, t10:1 ; 11 = condition code LT
The two new nodes are AArch64ISD:: opcodes, not machine instructions yet. The real post-selection MIR confirms the shape: %2:gpr32 = SUBSWrr %0, %1, implicit-def $nzcv then %3:gpr32 = CSELWr %0, %1, 11, implicit $nzcv.
LowerSELECT_CC also checks whether both arms are constants that differ by one, in which case it builds AArch64ISD::CSINC (or CSINV / CSNEG for related constants) directly.
Sources: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:13408-13415, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:12744-13022, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:13078-13156, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:12868-12912
Example: Global Addresses
ISD::GlobalAddress is Custom. For a dso_local global in the small code model, LowerGlobalAddress builds a two-part address: AArch64ISD::ADRP (the 4 KiB page of the symbol) plus AArch64ISD::ADDlow (the low 12 bits). The real MIR for load i32, ptr @g shows selection folding the low part into the load:
%0:gpr64common = ADRP target-flags(aarch64-page) @g
%1:gpr32 = LDRWui killed %0, target-flags(aarch64-pageoff, aarch64-nc) @g :: (dereferenceable load (s32) from @g)
If only the pointer is needed (ret ptr @g) the pair is the pseudo MOVaddr, expanded into adrp and add :lo12: after register allocation. For a preemptible global in a position-independent build, LOADgot becomes adrp plus an ldr from the GOT slot.
Vector Operation Legalization (VectorLegalizer)
Type legalization made vector types legal; the VectorLegalizer makes vector operations legal. It runs on its own because many rewrites only make sense once types are legal.
Runfirst scans the DAG and returns immediately if no node produces a vector value.- It then walks the nodes operands-first (topological order), calling
LegalizeOpon each. - The same action switch applies: Legal, Promote, Custom (
LowerOperationWrapper) and Expand. - Expansion tries an equivalent sequence of other vector operations and, as the last resort,
UnrollVectorOp, which extracts each lane, applies the scalar operation and rebuilds the vector. NEON has no integer vector divide, sosdiv <4 x i32>ends up as four scalarsdivs. - If it changed anything, type legalization runs a second time (the expansion may have created illegal scalar types), followed by Combine 3.
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp:207-247, llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp:559-609
Instruction Selection
Relevant source files
The following files were used as context for generating this wiki page:
Instruction selection replaces each remaining generic or AArch64ISD:: node with machine nodes by matching small trees of nodes against patterns written in TableGen. It works from the root of the DAG toward the leaves and chooses greedily: at each root the first matching pattern, in a fixed priority order, wins.
Purpose and Scope
This page covers the traversal and the per-node dispatch of DoInstructionSelection. The pattern language and the build-time generator are on TableGen Pattern Language; the interpreter that runs the generated matcher and the folding rules are on Matcher Interpreter and Folding; AArch64's hand-written parts are on AArch64 Instruction Selection.
Traversal: Root First
SelectionDAGISel::DoInstructionSelection does the following (verified in SelectionDAGISel.cpp):
flowchart TD
A["PreprocessISelDAG"] --> B["AssignTopologicalOrder<br/>number every node"]
B --> C["HandleSDNode keeps the root alive"]
C --> D["Start at the last node of AllNodes, the root"]
D --> E{"Node has users?"}
E -- no --> F["Skip, it is dead"]
E -- yes --> G["Select of Node"]
F --> H{"More nodes toward the entry?"}
G --> H
H -- yes --> D
H -- no --> I["PostprocessISelDAG"]
PreprocessISelDAG(): an optional target hook.CurDAG->AssignTopologicalOrder(): number every node so operands have smaller ids than users.- Walk
AllNodesbackward from the root toEntryToken. Skip a node with no users (dead; nodes folded into an earlier selection become dead this way), lower strict-FP nodes to plain ones if the target lacks them, then callSelect(Node). PostprocessISelDAG(): another optional hook.
The backward order is deliberate. When add is selected first, its operand shl is still a generic node, so the pattern add x, (shl y, 3) can see it and absorb it into a single ADDWrs. If operands were selected first, the shl would already be a separate UBFM instruction. An ISelUpdater keeps the iterator valid while nodes are deleted or replaced, and node ids are a safety net: a selected node gets id -1, and the code asserts that no unselected node has a selected predecessor.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1287-1392, llvm/include/llvm/CodeGen/SelectionDAGISel.h:143
Per-Node Dispatch
AArch64DAGToDAGISel::Select(SDNode *Node) runs three tiers:
flowchart TD
N["Select of Node"] --> M{"Already a machine node?"}
M -- yes --> M1["Mark selected, done"]
M -- no --> S{"Opcode handled in the C++ switch?"}
S -- yes --> T["tryXxx helper"]
T --> TR{"Helper succeeded?"}
TR -- yes --> DONE["Replaced, done"]
TR -- no --> G
S -- no --> G["SelectCode of Node<br/>generated matcher"]
G --> GM{"Pattern matched?"}
GM -- yes --> DONE
GM -- no --> ERR["Cannot select error"]
- Already machine? If
Node->isMachineOpcode(), the node was created pre-selected, so it is marked done. - Hand-written selection in a C++
switchfor cases the pattern language cannot express well:ISD::LOADcallstryIndexedLoad;SRL,AND,SRA,SIGN_EXTEND_INREGtrytryBitfieldExtractOp;ORtriestryBitfieldInsertOp; atomics, system registers,EXTRACT_SUBVECTORand NEON/SVE load-store intrinsics have their own helpers. - Generated matcher. Anything left goes to
SelectCode(Node)at the end of the switch.
SelectCodeCommon first accepts, without patterns, node kinds that are already in final form: EntryToken, Register, CopyFromReg, CopyToReg, TokenFactor, TargetConstant, TargetGlobalAddress, BasicBlock and similar. It turns UNDEF into IMPLICIT_DEF and handles INLINEASM specially.
Sources: llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:5096-5173, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:7754, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:3354-3443
What Selection Produces
When the backward sweep ends the DAG consists of machine nodes plus the structural nodes (CopyToReg, CopyFromReg, TokenFactor, EntryToken). -debug-only=isel prints it as Selected selection DAG. It is still a graph: nothing says in which order independent instructions must appear. That is the scheduler's job; see Scheduling and MIR Emission.
Not Everything Is Decided Here
Some familiar AArch64 optimisations are not SelectionDAG decisions. In real output the fused multiply-add and load/store pairs appear only later:
a*b + cis selected asMADDWrrr %0, %1, $wzr(a plain multiply) followed byADDWrr. The MachineCombiner pass later fuses them intomadd w0, w0, w1, w2. The source ofperformMulCombinesays so in a comment: "in MachineCombiner pass, add+mul will be combined into madd".- Two adjacent
LDRXuibecomeldp(and twoSTRXuibecomestp) inAArch64LoadStoreOptimizer, after register allocation.
The split is intentional: those fusions depend on register pressure, scheduling and pairing rules that the DAG cannot see.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:21215-21217, llvm/lib/Target/AArch64/AArch64InstrInfo.td:2911-2921
TableGen Pattern Language
Relevant source files
The following files were used as context for generating this wiki page:
- llvm/include/llvm/Target/TargetSelectionDAG.td
- llvm/lib/Target/AArch64/AArch64InstrInfo.td
- llvm/lib/Target/AArch64/AArch64InstrFormats.td
- llvm/utils/TableGen/DAGISelEmitter.cpp
- llvm/utils/TableGen/DAGISelMatcherGen.cpp
- llvm/utils/TableGen/DAGISelMatcherOpt.cpp
- llvm/utils/TableGen/DAGISelMatcherEmitter.cpp
- llvm/utils/TableGen/Common/CodeGenDAGPatterns.cpp
A pattern pairs a source tree over DAG nodes with a result tree over machine instructions. TableGen turns thousands of such patterns into one generated decision procedure that SelectCode runs for every node.
Purpose and Scope
This page documents the pattern vocabulary defined in TargetSelectionDAG.td and used by AArch64InstrInfo.td, and the build-time pipeline (llvm-tblgen -gen-dag-isel) that produces AArch64GenDAGISel.inc. The run-time side is on Matcher Interpreter and Folding.
Pattern Vocabulary
| Construct | What it is | AArch64 example |
|---|---|---|
SDNode | Names a DAG opcode and its operand/result type profile | def AArch64csel : SDNode<"AArch64ISD::CSEL", SDT_AArch64CSel>; and def add : SDNode<"ISD::ADD", SDTIntBinOp, ...>; |
| Operand leaf with class | A value of a register class; binds a name | GPR32:$Rn |
| Immediate leaf | A constant, optionally constrained by a predicate | imm, imm0_63, simm9 |
Pat<src, dst> | A standalone pattern | def : Pat<(i32 (mul GPR32:$Rn, GPR32:$Rm)), (MADDWrrr GPR32:$Rn, GPR32:$Rm, WZR)>; |
| Pattern inside an instruction | The instruction lists what it computes and TableGen derives the pattern | def MOVi32imm : Pseudo<(outs GPR32:$dst), (ins i32imm:$src), [(set GPR32:$dst, imm:$src)]>; |
PatFrag / PatFrags | A named reusable sub-pattern with a C++ predicate | load, sextloadi8, zextloadi8 |
ComplexPattern | Delegates matching of one operand to a C++ function that may produce several output operands | ro_Xindexed32 calls SelectAddrModeXRO<32>; arith_shifted_reg32 calls SelectArithShiftedRegister |
SDNodeXForm | A C++ snippet that transforms a matched constant before use | inv_cond_XFORM inverts a condition code |
Predicates = [...] | Subtarget feature test checked at match time | [HasCSSC], [HasNEON] |
AddedComplexity | Priority bonus | let AddedComplexity = 5 in { ... MADD patterns }; register-offset loads use 10 |
Two real definitions, shortened. First, register-offset loads from AArch64InstrFormats.td; second, a conditional-select pattern from AArch64InstrInfo.td:
let AddedComplexity = 10 in
def roX : LoadStore32RO<sz, V, opc, asm, (outs regtype:$Rt),
(ins GPR64sp:$Rn, GPR64:$Rm, ro_Xextend32:$extend),
[(set (Ty regtype:$Rt),
(loadop (ro_Xindexed32 GPR64sp:$Rn, GPR64:$Rm,
ro_Xextend32:$extend)))]>;
def : Pat<(AArch64csel GPR32:$tval, (i32 1), (i32 imm:$cc), NZCV),
(CSINCWr GPR32:$tval, WZR, (i32 imm:$cc))>;
The first says a load whose address SelectAddrModeXRO accepts becomes the LDR ... [Xn, Xm, extend] form, with $Rn, $Rm and the extend/shift flags as operands. The second says a csel whose false value is the constant 1 is better done as csinc with the zero register.
Sources: llvm/include/llvm/Target/TargetSelectionDAG.td:368, llvm/include/llvm/Target/TargetSelectionDAG.td:1000, llvm/include/llvm/Target/TargetSelectionDAG.td:1042, llvm/include/llvm/Target/TargetSelectionDAG.td:1195, llvm/include/llvm/Target/TargetSelectionDAG.td:2460-2468, llvm/lib/Target/AArch64/AArch64InstrInfo.td:851, llvm/lib/Target/AArch64/AArch64InstrInfo.td:2667-2675, llvm/lib/Target/AArch64/AArch64InstrInfo.td:2911-2921, llvm/lib/Target/AArch64/AArch64InstrInfo.td:3555-3562, llvm/lib/Target/AArch64/AArch64InstrFormats.td:3927-3949, llvm/lib/Target/AArch64/AArch64InstrFormats.td:4210-4233
From Patterns to a Matcher Table
flowchart LR PAT["Pat and instruction<br/>definitions in .td files"] --> CGP["CodeGenDAGPatterns<br/>parse, infer types, complexity"] CGP --> SORT["DAGISelEmitter<br/>stable_sort by PatternSortingPredicate"] SORT --> GEN["DAGISelMatcherGen<br/>one linear matcher per pattern"] GEN --> OPT["OptimizeMatcher<br/>ContractNodes, FactorNodes"] OPT --> EMIT["DAGISelMatcherEmitter<br/>uint8_t MatcherTable"] EMIT --> INC["AArch64GenDAGISel.inc"] INC --> SC["SelectCode calls SelectCodeCommon"]
CodeGenDAGPatternsparses every pattern, infers types, and gives each pattern a complexity: pattern size (roughly the number of nodes it covers, with bonuses for constants and predicates) plusAddedComplexity.DAGISelEmitterputs all patterns in a list and runsstable_sortwithPatternSortingPredicate: larger and more specific patterns first, ties keep source order. That order is the match priority.DAGISelMatcherGenconverts each pattern into a linear matcher: checks and captures followed by emit steps.OptimizeMatcherrunsContractNodes(fuse common step pairs, such as moving to a child and recording it) andFactorNodes, which merges patterns that start the same way into shared prefixes withSwitchOpcodeandSwitchTypebranches. The result is a decision tree rather than a list tried one by one.DAGISelMatcherEmitterwrites auint8_ttable inAArch64GenDAGISel.inc; its comments show each pattern as// Src:and// Dst:lines next to the matcher bytes, which is the easiest way to see where a pattern landed.SelectCode()passes the table toSelectCodeCommon.
Sources: llvm/utils/TableGen/Common/CodeGenDAGPatterns.cpp:1463-1511, llvm/utils/TableGen/DAGISelEmitter.cpp:84-149, llvm/utils/TableGen/DAGISelEmitter.cpp:184-192, llvm/utils/TableGen/DAGISelMatcherOpt.cpp:25-304, llvm/utils/TableGen/DAGISelMatcherOpt.cpp:353-662, llvm/utils/TableGen/DAGISelMatcherOpt.cpp:664-667
Build-Time Notes for AArch64
In the current tree the AArch64ISD:: node enum is generated into AArch64GenSDNodeInfo.inc from the SDNode<"AArch64ISD::..."> records, and AArch64SelectionDAGInfo derives from the generated SelectionDAGGenTargetInfo. Older releases declare the enum by hand in AArch64ISelLowering.h. Adding a new AArch64ISD:: node therefore starts with a record in the .td files.
Sources: llvm/lib/Target/AArch64/AArch64SelectionDAGInfo.h:10-30
Matcher Interpreter and Folding
Relevant source files
The following files were used as context for generating this wiki page:
The generated matcher table is bytecode for a small state machine implemented by SelectionDAGISel::SelectCodeCommon. It matches a tree rooted at the current node, records operands, and when the match completes creates machine nodes and replaces the original.
Purpose and Scope
This page explains the interpreter's state, the bytecode groups, what happens when matching fails, and the rules that decide whether a pattern may swallow an operand node. It ends with a worked example. Pattern syntax is on TableGen Pattern Language.
Interpreter State and Control Flow
State kept by SelectCodeCommon: a NodeStack (where we are in the tree being matched), RecordedNodes (operands captured so far), MatchScopes (backtracking points), MatchedMemRefs, and the current input chain and glue. It starts at the root with only the opcode switch, using an OpcodeOffset table so the first lookup is direct.
flowchart TD
S["Start at the root node<br/>jump via OpcodeOffset"] --> SW["SwitchOpcode and SwitchType<br/>choose the candidate patterns"]
SW --> CH["Check steps<br/>CheckType, CheckInteger, CheckPredicate,<br/>CheckPatternPredicate, CheckComplexPat"]
CH --> OK{"Check passed?"}
OK -- no --> BT["Pop to the latest OPC_Scope<br/>try the next alternative"]
BT --> SW
OK -- yes --> MV["MoveChild, RecordChild, MoveParent<br/>walk and capture operands"]
MV --> MORE{"More of the pattern?"}
MORE -- yes --> CH
MORE -- no --> EM["Emit steps<br/>EmitInteger, EmitRegister, EmitNode, MorphNodeTo"]
EM --> CM["CompleteMatch<br/>ReplaceUses of the original node"]
BT --> FAIL{"No alternatives left?"}
FAIL -- yes --> ERR["Cannot select error"]
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:3354-3443, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:3447-3503
Bytecode Groups
The opcodes are the BuiltinOpcodes enum in SelectionDAGISel.h.
| Group | Opcodes | Purpose |
|---|---|---|
| Branching | OPC_SwitchOpcode, OPC_SwitchType, OPC_Scope | Choose among alternatives; OPC_Scope marks where to resume if a check fails |
| Walking the tree | OPC_MoveChild, OPC_MoveSibling, OPC_MoveParent | Descend into an operand, step to the next, come back up |
| Checks | OPC_CheckOpcode, OPC_CheckType, OPC_CheckInteger, OPC_CheckSame, OPC_CheckPredicate, OPC_CheckPatternPredicate, OPC_CheckComplexPat, OPC_CheckFoldableChainNode | Test node kind, type, constant value, equality of two operands, a PatFrag predicate, a subtarget feature, call a ComplexPattern function, and check that folding is allowed |
| Capture and emit | OPC_RecordChild0..7, OPC_RecordNode, OPC_EmitInteger, OPC_EmitRegister, OPC_EmitConvertToTarget, OPC_EmitNodeXForm, OPC_EmitMergeInputChains, OPC_EmitNode, OPC_MorphNodeTo, OPC_CompleteMatch | Remember operands, build immediates and registers, create the machine node, rewire chains, and finish by replacing the original node's uses |
Sources: llvm/include/llvm/CodeGen/SelectionDAGISel.h:146-354
When Matching Fails
If all alternatives fail, selection stops with the familiar LLVM ERROR: Cannot select: tN: .... That error means the legalizer let a node through that no pattern covers. It is always a missing Custom or Expand registration, or a missing pattern for a legal operation. See Tooling, Debugging and Extending.
Folding Rules
A pattern that spans several nodes, for example add x, (shl y, 3), absorbs the inner node. That is allowed only if:
- the inner node has exactly one use.
IsProfitableToFoldreturnsN.hasOneUse(), and returnsfalseat-O0, because otherwise the inner value must be computed anyway and folding would duplicate work; - it is legal to fold.
IsLegalToFoldchecks that absorbing the node cannot create a cycle with another path from the root to it, and that chain and glue ordering stays valid, so a load is only merged if no store or call sits between it and the root; - for a
ComplexPattern, the C++ function agrees. For exampleSelectAddrModeXROrefuses anaddwhose result is also used by a non-memory instruction, because the add has to be kept alive anyway.
When a fold is refused the longer pattern fails and a shorter one matches instead. This is how add x, (shl y, 3) degrades to UBFM plus ADDWrr when the shl is shared.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:2420-2425, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:2429-2495, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:1490-1507
Worked Example: x + (y << 3) Becomes One Instruction
DAG at selection time (after legalization and the last combine):
t5: i32 = shl t3, Constant:i64<3>
t6: i32 = add t2, t5
The walk reaches t6 first (root-first). The matcher switches on ISD::ADD and i32, then tries candidates in priority order. The ADDWrs candidate has the shape (add GPR32:$Rn, (arith_shifted_reg32 ...)). OPC_CheckComplexPat calls SelectArithShiftedRegister on t5; that calls SelectShiftedRegister, which sees a shl by a constant, sets Reg = t3 and Shift = TargetConstant(LSL, 3), and checks isWorthFoldingALU. All checks pass, OPC_EmitNode creates ADDWrs t2, t3, TargetConstant<3> and OPC_CompleteMatch replaces t6. t5 is now unused and is skipped later in the sweep.
The real MIR is %2:gpr32 = ADDWrs %0, %1, 3 and the assembly add w0, w0, w1, lsl #3. The immediate 3 is the encoded shifter operand (type LSL, amount 3).
Sources: llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:1023-1045, llvm/lib/Target/AArch64/AArch64InstrFormats.td:1286-1305, llvm/lib/Target/AArch64/AArch64InstrFormats.td:3118-3121
AArch64 Instruction Selection
Relevant source files
The following files were used as context for generating this wiki page:
AArch64 combines three mechanisms: generated pattern matching, ComplexPattern C++ functions for addressing modes and shifted operands, and hand-written tryXxx selectors for cases the pattern language handles poorly.
Purpose and Scope
This page documents the AArch64-specific selection code in AArch64ISelDAGToDAG.cpp with real MIR and assembly: addressing modes, indexed loads, constants, bitfields, and compare-and-select. The generic machinery is on Instruction Selection.
Addressing Modes for Loads and Stores
One IR load i32 becomes one of several instructions depending on the address expression. Each form is a different ComplexPattern.
| Address in IR | Matched by | Real MIR | Assembly |
|---|---|---|---|
p + i*4, i is i64 | ro_Xindexed32 (SelectAddrModeXRO) | LDRWroX %0, %1, 0, 1 | ldr w0, [x0, x1, lsl #2] |
p + sext(i32 i)*4 | ro_Windexed32 (SelectAddrModeWRO) | LDRWroW %0, %1, 1, 1 | ldr w0, [x0, w1, sxtw #2] |
p + 12 | am_indexed32 (SelectAddrModeIndexed), immediate scaled by 4 | LDRWui %0, 3 | ldr w0, [x0, #12] |
p - 4 | am_unscaled32 (SelectAddrModeUnscaled), signed 9-bit byte offset | LDURWi %0, -4 | ldur w0, [x0, #-4] |
zext of an i8 load | zextloadi8 pattern | LDRBBui %0, 0 then SUBREG_TO_REG | ldrb w0, [x0] |
The two trailing operands of LDRWroX (0, 1) are the sign-extend flag (false: the index is a 64-bit register) and the shift flag (true: shift by the access size). SelectAddrModeXRO produces them: it requires the address to be an ISD::ADD, refuses if the add has non-memory users, looks for a shl on either operand through SelectExtendedSHL, and otherwise returns base and index with no shift. It also handles a wide constant offset by materialising it with MOVi64imm so the register-offset form saves an add.
Stores work the same way (STRWroX, STRWui, STURWi), using the Store32RO multiclass. Scaled (ui) forms need an offset that is a non-negative multiple of the access size; anything else falls to the unscaled LDUR family.
Sources: llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:1490-1563, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:1277-1330, llvm/lib/Target/AArch64/AArch64InstrFormats.td:3744, llvm/lib/Target/AArch64/AArch64InstrFormats.td:3927-3949, llvm/lib/Target/AArch64/AArch64InstrFormats.td:4210-4233, llvm/lib/Target/AArch64/AArch64InstrFormats.td:4455
Pre- and Post-Indexed Loads
An indexed load is a single DAG node (LOAD with POST_INC addressing mode) with three results: value, updated base pointer, chain. The pattern language is awkward for multi-result addressing-mode choices, so AArch64DAGToDAGISel::tryIndexedLoad handles it. It reads LD->getAddressingMode() (PRE_INC or POST_INC), the memory type and extension kind, picks an opcode (LDRWpost, LDRXpre, LDRSWpost, LDRBBpost, ...), and builds the machine node, adding a SUBREG_TO_REG when a zero-extended 32-bit result must become 64 bits. Real MIR from the loop on PHI Node Resolution:
early-clobber %14:gpr64sp, %15:gpr32 = LDRWpost %0:gpr64sp(tied-def 0), 4 :: (load (s32) from %ir.lsr.iv1)
early-clobber and tied-def 0 encode that the written-back pointer must share a register with the incoming base. The DAG node itself was formed earlier by CombineToPostIndexedLoadStore, using getPostIndexedAddressParts; see DAG Combiner.
Sources: llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:1801-1939, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:31289-31350, llvm/lib/Target/AArch64/AArch64InstrInfo.td:4610
Constants, Bitfields and Compare-and-Select
- Constants.
ISD::Constantis matched by[(set GPR32:$dst, imm:$src)]on theMOVi32immpseudo (andMOVi64imm). The pseudo exists so the constant can be rematerialised cheaply; after register allocationAArch64ExpandPseudoInststurns it into the realmovz/movk/orrsequence. Real output forx / 10:MOVi32imm -858993459in MIR andmov w8, #52429plusmovk w8, #52428, lsl #16in the assembly. Small constants that fit an instruction's immediate field never get this far; patterns likeADDWriabsorb them directly. - Bitfield extract.
and (srl x, 8), 255is claimed bytryBitfieldExtractOpand becomesUBFMXri %0, 8, 15, printed asubfx x0, x0, #8, #8. - Compare and select. After legalization the DAG holds
AArch64ISD::SUBSandAArch64ISD::CSEL. Patterns match them toSUBSWrrandCSELWr. The flags value flows between them as ani32in the DAG and as the physical registerNZCVin MIR (implicit-def $nzcvon the compare,implicit $nzcvon the select). When one arm of the select is the constant1, a more specificPatproducesCSINCWr. When both arms are constants that differ by one,LowerSELECT_CCbuildsAArch64ISD::CSINCitself, before any pattern runs: the real MIR forselect i1 %c, i32 5, i32 6isCSINCWr %2, %2, 12, i.e.cinc w0, w8, le. - Return.
RET_ReallyLRis defined asPseudo<(outs), (ins), [(AArch64retglue)]>, soAArch64ISD::RET_GLUEselects to it and it expands toretat the end.
Sources: llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:3082-3108, llvm/lib/Target/AArch64/AArch64InstrInfo.td:2667-2675, llvm/lib/Target/AArch64/AArch64InstrInfo.td:3555-3562, llvm/lib/Target/AArch64/AArch64InstrInfo.td:3703, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:12868-12912
Scheduling and MIR Emission
Relevant source files
The following files were used as context for generating this wiki page:
- llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
- llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp
- llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp
- llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp
- llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
- llvm/lib/Target/AArch64/AArch64Subtarget.h
- llvm/include/llvm/CodeGen/TargetSubtargetInfo.h
A DAG says what depends on what; it does not say what comes first. Scheduling picks one total order for the machine nodes that respects every data, chain and glue edge, and emission walks that order and creates one MachineInstr per node, with virtual registers for values.
Purpose and Scope
This page covers phases 6 and 7 of the pipeline: choosing the scheduler, building the scheduling graph, list scheduling, and InstrEmitter. It is the step where the graph becomes the linear MIR you see in -stop-after dumps.
Choosing the Scheduler
CodeGenAndEmitDAG calls CreateScheduler(), which honours the -pre-RA-sched= option (default: createDefaultScheduler). That function decides in this order:
- If the subtarget supplies its own DAG scheduler (
getDAGScheduler), use it. - If the optimisation level is
-O0, or the subtarget enables the MachineScheduler and lets it be the default (enableMachineScheduler() && enableMachineSchedDefaultSched()), or the target's preference isSched::Source: use the source-order list scheduler. - Otherwise pick by
TLI->getSchedulingPreference():RegPressuregives the bottom-up register-pressure scheduler, thenHybrid,VLIW,Fast,Linearize, or by defaultILP.
On AArch64, AArch64Subtarget::enableMachineScheduler() returns true and the base class returns true for enableMachineSchedDefaultSched(), so rule 2 applies even though the constructor calls setSchedulingPreference(Sched::Hybrid). The DAG scheduler on AArch64 therefore keeps instructions in roughly the original IR order, and the performance scheduling is left to the MachineScheduler that runs later on MIR with real latency and resource models.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:301-330, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1164-1183, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:1276, llvm/lib/Target/AArch64/AArch64Subtarget.h:160, llvm/include/llvm/CodeGen/TargetSubtargetInfo.h:210-214
Building the Scheduling Graph
flowchart LR R["ScheduleDAGSDNodes::Run"] --> S["Schedule"] S --> U["BuildSchedUnits<br/>one SUnit per node, glued nodes merged"] U --> E["AddSchedEdges<br/>data, order, physreg edges"] E --> L["ListScheduleBottomUp<br/>priority queue from the exit node"] L --> V["Reverse the sequence"] V --> EM["EmitSchedule<br/>InstrEmitter per SUnit"]
BuildSchedUnitscreates anSUnitper node, but nodes joined by glue are merged into one unit, since glue means "emit these back to back". For example, theCopyToRegnodes that place outgoing arguments in registers and theBLthat reads them form one unit.AddSchedEdgesadds dependency edges (SDep): data edges for operands, order edges for chains, and physical-register edges where an instruction implicitly defines or uses a register (such asNZCV). Latencies come from the target's itineraries or scheduling model when available.- Each
SUnitrecords a source-order number (SDNodeOrderfrom the builder), used as the tie-breaker.
Sources: llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:55-65, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:324-439, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:441-530
List Scheduling
ScheduleDAGRRList::ListScheduleBottomUp builds the order from the bottom: it starts at the exit unit (the root) and repeatedly picks one available unit (one whose users have all been scheduled) from a priority queue, schedules it, then makes its operands available. The priority function for the source-order variant (src_ls_rr_sort) prefers the node with the higher source order, so the bottom-up walk reproduces the program order. At the end the sequence is reversed (std::reverse(Sequence...)) to get top-down order. The other variants add heuristics for register pressure, ILP, and two-address and physical-register constraints.
Sources: llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp:1580-1621, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp:1662-1673
Emission: EmitSchedule and InstrEmitter
ScheduleDAGSDNodes::EmitSchedule creates an InstrEmitter positioned in the MachineBasicBlock, then for each SUnit in Sequence emits its node(s) with Emitter.EmitNode. What each node kind becomes:
| Node | Emitted as |
|---|---|
Machine node (ADDWrr, LDRWui, BL, ...) | EmitMachineNode: a MachineInstr built from the instruction's descriptor. Defs get a new virtual register whose register class comes from the instruction's operand constraint (gpr32, gpr64, fpr128); uses come from VRBaseMap (a map from (SDNode, result number) to its vreg); constants become immediate operands; MachineMemOperands and IR flags are attached |
CopyToReg dst, src | A COPY into dst (a physical register such as $w0, or a virtual register for a value that leaves the block). If the source is IMPLICIT_DEF, an IMPLICIT_DEF instruction instead |
CopyFromReg src | If src is virtual: no instruction; the node's result aliases that vreg in VRBaseMap. If physical: a COPY from it into a fresh vreg |
COPY_TO_REGCLASS, EXTRACT_SUBREG, INSERT_SUBREG, SUBREG_TO_REG, REG_SEQUENCE | COPY with subregister indices or the right register class (special-cased in EmitSubregNode, EmitRegSequence) |
EntryToken, TokenFactor | Nothing: they only carried ordering |
Two details explain visible features of MIR (as produced by the 23.1.4 llc the examples use):
- Kill flags. In
AddRegisterOperanda use is markedkilledwhen its defining node has a single use, is not aCopyFromReg, and the instruction operand is not tied. That is why%3iskilledinADDWrr killed %3, %2below while%0and%1, which come fromCopyFromReg, never are. - Register class constraints. For each virtual-register use the emitter calls
MRI->constrainRegClassto narrow the class of the vreg to what the instruction accepts, or inserts aCOPYinto a new vreg if narrowing is impossible. This is why an incoming pointer becomes%0:gpr64common(a class that excludesxzr, which cannot be a base address) in load examples, while ani64argument that is only added staysgpr64.
Sources: llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:848-1093, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:88-183, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:185-263, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:340-392, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:503-634, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:1003-1258, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:1263-1310
Live-In Copies and finalize-isel
After all blocks of the function have been selected, SelectionDAGISel::runOnMachineFunction calls MachineRegisterInfo::EmitLiveInCopies for the entry block. It inserts one COPY per live-in physical register at the very top, each placed at the block's beginning, which is why they appear in reverse (%2 = COPY $w2, %1 = COPY $w1, %0 = COPY $w0). A later pass, finalize-isel ("Finalize ISel and expand pseudo-instructions"), handles instructions that need a custom inserter and applies post-ISel hooks.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:688
Complete Example: (a * b) + c
The DAG from Core Data Structures after selection, scheduling and emission produces exactly this MIR (real output from llc -mtriple=aarch64 -O2 -stop-after=finalize-isel):
bb.0 (%ir-block.0):
liveins: $w0, $w1, $w2
%2:gpr32 = COPY $w2 ; live-in copies, inserted at the top, in reverse
%1:gpr32 = COPY $w1
%0:gpr32 = COPY $w0
%3:gpr32 = MADDWrrr %0, %1, $wzr ; mul a, b (a multiply is a MADD with the zero register)
%4:gpr32 = ADDWrr killed %3, %2 ; add, %3 is single-use so it is killed
$w0 = COPY %4 ; CopyToReg $w0
RET_ReallyLR implicit $w0 ; AArch64ISD::RET_GLUE, glued to the copy
Every MIR instruction maps back to one DAG node: three CopyFromReg (which became no instruction; the COPYs at the top are the live-in copies of the physical registers, and %0..%2 are the vregs they alias), the mul, the add, the CopyToReg, and the glued return.
PHI Node Resolution
Relevant source files
The following files were used as context for generating this wiki page:
SelectionDAG has no PHI node. A DAG describes one block, while a PHI chooses a value according to which edge was taken, so PHIs are handled across block boundaries with virtual registers in four hand-offs.
Purpose and Scope
This page follows an IR PHI from FunctionLoweringInfo through SelectionDAGBuilder and FinishBasicBlock to the PHIElimination pass, with a real loop example and its MIR at each stage. It touches DAG Construction and Scheduling and MIR Emission.
Overview of the Four Hand-Offs
sequenceDiagram
participant FLI as FunctionLoweringInfo
participant SDB as SelectionDAGBuilder
participant ISEL as SelectionDAGISel
participant PE as PHIElimination
FLI->>FLI: set creates export vregs, MBBs, empty machine PHIs
loop for each IR block, reverse post-order
SDB->>SDB: HandlePHINodesInSuccessorBlocks before the terminator
Note right of SDB: CopyToReg of incoming value into PHI operand vreg, record PHI and vreg pair
ISEL->>ISEL: CodeGenAndEmitDAG for the block
ISEL->>ISEL: FinishBasicBlock adds vreg and MBB operands to the PHIs
end
PE->>PE: LowerPHINode turns each PHI into COPYs, splits critical edges
- Before any DAG is built, empty machine
PHIs and their registers are created. - At the end of each predecessor's DAG, the incoming value is copied into a virtual register.
- After the predecessor is emitted, that register is attached as the PHI's operand for that edge.
- Much later, the
PHIEliminationpass turns every machine PHI intoCOPYs, and the register coalescer removes most of them.
Step 1: Set-Up Before Selection (FunctionLoweringInfo::set)
This runs once per function, before the first DAG is built:
- Every IR value that is used outside its defining block, or by a PHI, gets one or more virtual registers (
InitializeRegForValue, stored inFuncInfo.ValueMap). The number of registers follows the type: one fori32, two fori128. These are the export registers. - A
MachineBasicBlockis created for every IR block, so successors already exist as targets. - For every live IR PHI (one that has users and a non-empty type), an empty machine
PHIinstruction is created at the top of its MBB, defining the PHI's registers:BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i). No operands yet.
Sources: llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:46-55, llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:231-235, llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:291-315
Step 2: At the End of Each Predecessor (HandlePHINodesInSuccessorBlocks)
Just before SelectionDAGBuilder::visit handles a block's terminator, it looks at every successor that begins with PHIs (each successor once, even if a switch reaches it through several edges). For each live PHI it takes the value this block contributes, PN.getIncomingValueForBlock(thisBlock), and:
- If it is a constant: allocate (or reuse, via a per-block
ConstantsOutmap) a fresh virtual register and emitCopyToRegof the constant into it. Integer constants are sign- or zero-extended according toTLI.signExtendConstant, so later known-bits analysis of PHI results is valid. - If it is an instruction or argument: look up its export register in
ValueMap. ACopyToReginto that register was already emitted right after the value was computed, byCopyToExportRegsIfNeeded. - Record the pair (machine PHI instruction, register) in
FuncInfo.PHINodesToUpdate, once per register of the value.
The pair is only recorded here, not applied, because lowering the block can create several machine blocks, so the last one (the one that actually branches to the successor) is not known yet.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:12450-12523, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2384-2395, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:11860-11884
Step 3: Attaching Operands (FinishBasicBlock)
After the block's DAG has been emitted, SelectionDAGISel::FinishBasicBlock walks PHINodesToUpdate and, for each pair, appends the operands (register, FuncInfo->MBB) to the machine PHI. The condition FuncInfo->MBB->isSuccessor(PHI->getParent()) guards against stale entries. If the block was split (a jump table, bit tests, a stack-protector check), the code that creates the extra blocks fixes up the pairs so each PHI gets the right predecessor. PHINodesToUpdate is cleared before the next IR block.
Because blocks are selected in reverse post-order, the register for a value arriving on a loop back edge is still undefined when the loop header's PHI is created. That is fine: the register number was fixed in step 1, and the definition appears later in the MIR, which is still valid SSA.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1974-1992, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:2117-2126
Real Example: A Loop with Three PHIs
This function sums n integers. After the IR-level loop strength reduction pass, the IR that reaches instruction selection is:
entry:
%c = icmp sgt i32 %n, 0
br i1 %c, label %loop.preheader, label %exit
loop.preheader:
br label %loop
loop:
%lsr.iv1 = phi ptr [ %p, %loop.preheader ], [ %scevgep, %loop ]
%lsr.iv = phi i32 [ %n, %loop.preheader ], [ %lsr.iv.next, %loop ]
%acc = phi i32 [ %acc.next, %loop ], [ 0, %loop.preheader ]
%v = load i32, ptr %lsr.iv1, align 4
%acc.next = add i32 %acc, %v
%lsr.iv.next = add i32 %lsr.iv, -1
%scevgep = getelementptr i8, ptr %lsr.iv1, i64 4
%done = icmp eq i32 %lsr.iv.next, 0
br i1 %done, label %exit, label %loop
exit:
%r = phi i32 [ 0, %entry ], [ %acc.next, %loop ]
ret i32 %r
The real MIR straight out of instruction selection (llc -mtriple=aarch64 -O2 -stop-after=finalize-isel):
bb.0.entry:
successors: %bb.1, %bb.3
liveins: $x0, $w1
%8:gpr32common = COPY $w1
%7:gpr64 = COPY $x0
%10:gpr32all = COPY $wzr ; constant 0 flowing to %r's PHI, edge entry->exit
%9:gpr32all = COPY %10
%11:gpr32 = SUBSWri %8, 1, 0, implicit-def $nzcv
Bcc 11, %bb.3, implicit $nzcv
B %bb.1
bb.1.loop.preheader:
%13:gpr32all = COPY $wzr ; constant 0 flowing to %acc's PHI
%12:gpr32all = COPY %13
bb.2.loop:
%0:gpr64sp = PHI %7, %bb.1, %5, %bb.2 ; %lsr.iv1
%1:gpr32sp = PHI %8, %bb.1, %4, %bb.2 ; %lsr.iv
%2:gpr32 = PHI %12, %bb.1, %3, %bb.2 ; %acc
early-clobber %14:gpr64sp, %15:gpr32 = LDRWpost %0, 4 ; load + pointer increment, one instruction
%16:gpr32 = ADDWrr %2, killed %15 ; %acc.next
%3:gpr32all = COPY %16 ; export of %acc.next
%17:gpr32 = SUBSWri %1, 1, 0, implicit-def dead $nzcv ; %lsr.iv.next
%4:gpr32all = COPY %17 ; export of %lsr.iv.next
%5:gpr64all = COPY %14 ; export of %scevgep
CBNZW %17, %bb.2
B %bb.3
bb.3.exit:
%6:gpr32all = PHI %9, %bb.0, %3, %bb.2 ; %r
$w0 = COPY %6
RET_ReallyLR implicit $w0
| MIR | Source |
|---|---|
%0, %1, %2, %6 = PHI ... | The empty machine PHIs from step 1, now with operand pairs from step 3 |
%7, %8 (COPY $x0, COPY $w1) | Live-in copies of the arguments %p and %n, the incoming values from the preheader edge |
%12 = COPY %13, %13 = COPY $wzr | The constant 0 arriving at %acc from loop.preheader: step 2's constant path |
%9 = COPY %10, %10 = COPY $wzr | The constant 0 arriving at %r from entry |
%3 = COPY %16, %4 = COPY %17, %5 = COPY %14 | The CopyToReg exports of %acc.next, %lsr.iv.next, %scevgep, which feed the loop's own PHIs on the back edge and the exit PHI |
LDRWpost | load plus getelementptr i8, 4 merged by the combiner into one indexed load (see DAG Combiner and AArch64 Instruction Selection) |
Step 4: PHI Elimination (PHIElimination)
The machine PHIs survive all the SSA-form machine passes (machine CSE, LICM, sinking, peepholes) and are removed just before register allocation, because PHIs cannot be allocated. For each %d = PHI [%a, bbA], [%b, bbB] the pass:
flowchart TD
P["PHI: d = PHI a from bbA, b from bbB"] --> T["Create one fresh vreg t<br/>IncomingReg"]
T --> D["At the PHI position:<br/>d = COPY t"]
T --> A["At the end of bbA before terminators:<br/>t = COPY a"]
T --> B["At the end of bbB before terminators:<br/>t = COPY b"]
A --> CE{"Critical edge?<br/>pred has several successors<br/>and block has several preds"}
B --> CE
CE -- yes --> SP["Split the edge with a new block<br/>and put the copy there"]
CE -- no --> OK["Copy stays in the predecessor"]
Using a fresh temporary that is read only at the top of the destination block avoids the classic lost-copy and swap problems of naive PHI lowering. Real output for the loop above (-stop-after=phi-node-elimination, trimmed):
bb.1: ; NEW block: splits the critical edge entry -> exit
%10:gpr32all = COPY $wzr
%9:gpr32all = COPY killed %10
%21:gpr32all = COPY killed %9 ; copy into the exit PHI's temporary
B %bb.4
bb.2.loop.preheader:
%13:gpr32all = COPY $wzr
%12:gpr32all = COPY killed %13
%18:gpr64sp = COPY killed %7 ; temporaries for the three loop PHIs,
%19:gpr32sp = COPY killed %8 ; written on the preheader edge
%20:gpr32 = COPY killed %12
bb.3.loop:
%2:gpr32 = COPY killed %20 ; the PHIs themselves are now copies at the top
%1:gpr32sp = COPY killed %19
%0:gpr64sp = COPY killed %18
early-clobber %14:gpr64sp, %15:gpr32 = LDRWpost killed %0, 4
%16:gpr32 = ADDWrr killed %2, killed %15
%3:gpr32all = COPY killed %16
%17:gpr32 = SUBSWri killed %1, 1, 0, implicit-def $nzcv
%4:gpr32all = COPY killed %17
%5:gpr64all = COPY killed %14
%18:gpr64sp = COPY killed %5 ; back-edge copies into the same temporaries
%19:gpr32sp = COPY killed %4
%20:gpr32 = COPY %3
%21:gpr32all = COPY killed %3 ; value for the exit PHI
Bcc 1, %bb.3, implicit killed $nzcv
B %bb.4
bb.4.exit:
%6:gpr32all = COPY killed %21 ; exit PHI is a copy from its temporary
$w0 = COPY killed %6
RET_ReallyLR implicit killed $w0
bb.1 did not exist in the IR: both ends of the entry -> exit edge have several neighbours, so PHI elimination inserted a block. PHIElimination may also reuse one incoming register across PHIs in the same block when it can (reusedIncoming).
Sources: llvm/lib/CodeGen/PHIElimination.cpp:365-420, llvm/lib/CodeGen/PHIElimination.cpp:860-880
Step 5: Copy Cleanup and the Final Code
TwoAddressInstruction handles tied operands, and the register coalescer merges registers joined by COPY whenever their live ranges do not interfere. After it, the loop is:
bb.3.loop:
early-clobber %18:gpr64common, %15:gpr32 = LDRWpost %18, 4
%21:gpr32 = ADDWrr %21, %15
%19:gpr32common = SUBSWri %19, 1, 0, implicit-def $nzcv
Bcc 1, %bb.3, implicit killed $nzcv
B %bb.4
and the final assembly has no copies in the loop at all:
sum:
cmp w1, #1
b.lt .LBB0_4
mov w8, wzr ; acc = 0 (constant from the preheader edge)
.LBB0_2:
ldr w9, [x0], #4 ; LDRWpost
subs w1, w1, #1
add w8, w8, w9
b.ne .LBB0_2
mov w0, w8 ; exit PHI, loop path
ret
.LBB0_4:
mov w8, wzr ; exit PHI, entry path (the constant 0)
mov w0, w8
ret
Special Cases
- Multi-register PHIs. A PHI of an illegal type that spans several registers (
i128on AArch64 is twoi64) becomes one machine PHI per register, andPHINodesToUpdategets one entry per register. - Dead PHIs (no users) and PHIs of empty types create nothing.
- PHI of
i1ori8. The PHI's registers have the promoted type (a 32-bit register), and the exported value is extended with the node kind chosen byPreferredExtendTypeor any-extend. undefincoming value. TheCopyToRegsource isIMPLICIT_DEF, andInstrEmitteremits anIMPLICIT_DEFinstruction for the register instead of aCOPY.- Switches that reach a PHI block through several edges are handled once per successor block.
Summary
| When | Where | What |
|---|---|---|
| Before ISel | FunctionLoweringInfo::set | Allocate export vregs; create MBBs; create empty machine PHIs |
| End of each IR block's DAG | SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks | CopyToReg of constants and incoming values into PHI-operand vregs; record (PHI, vreg) pairs |
| After each block is emitted | SelectionDAGISel::FinishBasicBlock | Add (vreg, MBB) operands to the machine PHIs |
| Pre-register-allocation | PHIElimination | One temp vreg per PHI; copies in predecessors; critical-edge splitting |
| Register allocation | register-coalescer, greedy | Remove copies, assign physical registers |
AArch64 Walkthroughs
Relevant source files
The following files were used as context for generating this wiki page:
This section applies the earlier pages to concrete AArch64 code: arithmetic, data movement, memory, control flow, calls, and one function traced through every phase.
Purpose and Scope
Each child page has the same layout: the IR, what the DAG phases did, the MIR after instruction selection, and the final assembly. The MIR and assembly are real output from llc; the DAGs between phases are reconstructed from the algorithms documented on the earlier pages, because the available llc is a release build without -debug-only=isel.
| Page | Covers |
|---|---|
| Arithmetic and Data Movement | Add, multiply, divide by constant, i128, vectors, floating point, constants, copies, extensions, global addresses |
| Memory Instructions | Addressing modes, indexed loads, store forms, ldp/stp pairing, chain ordering |
| Control Flow and Calls | Compare and branch, select, calls, returns |
| End-to-End Example | One function through all eight phases, plus the -O0 contrast |
How the Examples Were Produced
| Item | Value |
|---|---|
| Compiler | llc LLVM 23.1.4 (optimised build, no assertions), -mtriple=aarch64 -O2 |
| MIR after selection | -stop-after=finalize-isel |
| MIR after PHI elimination or coalescing | -stop-after=phi-node-elimination, -stop-after=register-coalescer |
| Source citations | Pinned to the llvmorg-23.1.4 release commit, so cited code matches the measured output |
| Reconstructed DAGs | Written in -debug-only=isel format; node numbers are illustrative |
Reading Real MIR
flowchart LR A["IR instruction"] --> B["DAG nodes<br/>ISD and AArch64ISD"] B --> C["Machine nodes<br/>AArch64::ADDWrr"] C --> D["MachineInstr in MIR<br/>virtual registers"] D --> E["Assembly after register allocation<br/>and pseudo expansion"]
%0:gpr32is a virtual register of classgpr32;gpr64commonexcludesxzr;gpr32allandgpr64allare the loosest classes.$w0,$x0,$wzrand$nzcvare physical registers.- Condition codes in
BccandCSELare numeric:0= EQ,1= NE,10= GE,11= LT,12= GT,13= LE. - Pseudos such as
MOVi32imm,MOVaddr,LOADgotandRET_ReallyLRare expanded after register allocation, which is why the assembly can differ from the MIR.
Arithmetic and Data Movement
Relevant source files
The following files were used as context for generating this wiki page:
Arithmetic work happens mostly in the combiner and legalizer (what to compute); selection is mostly a lookup (which instruction does it). Constants are selected as rematerialisable pseudos and expanded after register allocation.
Purpose and Scope
This page lists real AArch64 results for arithmetic, floating point, vectors, constants, copies, extensions and global addresses, and points to the page that explains each step.
Arithmetic Instructions
| IR | What the DAG phases did | MIR after instruction selection | Final assembly |
|---|---|---|---|
add i8 %a, %b | Type legalization promoted i8 to i32 (Type Legalization) | ADDWrr %0, %1 | add w0, w0, w1 |
%m = mul i32 %a, %b then add i32 %m, %c | Selected as plain multiply (a MADD with $wzr) plus add; fused later by the MachineCombiner (Instruction Selection) | %3 = MADDWrrr %0, %1, $wzr and %4 = ADDWrr killed %3, %2 | madd w0, w0, w1, w2 |
shl i32 %b, 3 then add i32 %a, %s | arith_shifted_reg32 swallowed the shl (Matcher Interpreter and Folding) | ADDWrs %0, %1, 3 | add w0, w0, w1, lsl #3 |
mul i32 %x, 9 | Combine: x*9 becomes add (shl x,3), x (DAG Combiner), then the same ADDWrs pattern | ADDWrs %0, %0, 3 | add w0, w0, w0, lsl #3 |
udiv i32 %x, 10 | Combine: magic-number multiply; constant materialised with MOVi32imm | MOVi32imm -858993459, UMADDLrrr %0, killed %1, $xzr, UBFMXri killed %2, 35, 63 | mov w8, #52429 movk w8, #52428, lsl #16 umull x8, w0, w8 lsr x0, x8, #35 |
add i128 %a, %b | Integer expansion into low and high i64 halves with a carry | ADDSXrr %0, %2, implicit-def $nzcv and ADCXr %1, %3, implicit $nzcv | adds x0, x0, x2 adc x1, x1, x3 |
lshr i64 %x, 8 then and ..., 255 | tryBitfieldExtractOp (AArch64 Instruction Selection) | UBFMXri %0, 8, 15 | ubfx x0, x0, #8, #8 |
sext i32 %a to i64 then add i64 %e, %b | The sign extension is folded into the add's extended-register form | ADDXrx %1, %0, 48 | add x0, x1, w0, sxtw |
fmul then fadd on float | No fast-math flags, so no fusion into fmadd; both keep nofpexcept and implicit $fpcr | nofpexcept FMULSrr %0, %1, implicit $fpcr and nofpexcept FADDSrr killed %3, %2, implicit $fpcr | fmul s0, s0, s1 fadd s0, s0, s2 |
add <4 x i32> | Legal type and operation | ADDv4i32 %0, %1 | add v0.4s, v0.4s, v1.4s |
add <8 x i32> | Type legalization split it into two <4 x i32> operations | ADDv4i32 %0, %2 and ADDv4i32 %1, %3 | add v1.4s, v1.4s, v3.4s add v0.4s, v0.4s, v2.4s |
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:21202-21215, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:21266-21306, llvm/lib/Target/AArch64/AArch64InstrInfo.td:2911-2921, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:3017-3039
Data Movement: Constants, Copies, Extensions, Addresses
| IR | Mechanism | MIR | Final assembly |
|---|---|---|---|
ret i32 4096 | ISD::Constant matched by the imm pattern on pseudo MOVi32imm | MOVi32imm 4096 | mov w0, #4096 |
ret i32 -65536 | same | MOVi32imm -65536 | mov w0, #-65536 (0xffff0000) |
ret i32 1431655765 | same; 0x55555555 is a valid logical immediate | MOVi32imm 1431655765 | mov w0, #1431655765 |
ret i64 1311768467463790320 | same, 64-bit pseudo | MOVi64imm 1311768467463790320 | mov x0, #57072 movk x0, #39612, lsl #16 movk x0, #22136, lsl #32 movk x0, #4660, lsl #48 |
function argument i32 %a | LowerFormalArguments makes a live-in vreg and CopyFromReg | liveins: $w0 and %0:gpr32 = COPY $w0 | no instruction |
ret i32 %x | CopyToReg $w0, then AArch64ISD::RET_GLUE | $w0 = COPY %4 and RET_ReallyLR implicit $w0 | ret |
load i8 then zext to i64 | Combine folds into a zero-extending load; 32-bit load widened with SUBREG_TO_REG | %1:gpr32 = LDRBBui %0, 0 and %2:gpr64all = SUBREG_TO_REG killed %1, %subreg.sub_32 | ldrb w0, [x0] |
load i32, ptr @g (non-preemptible, small code model) | GlobalAddress lowered to ADRP plus ADDlow, low part folded into the load | ADRP target-flags(aarch64-page) @g and LDRWui killed %0, target-flags(aarch64-pageoff, aarch64-nc) @g | adrp x8, g ldr w0, [x8, :lo12:g] |
ret ptr @g (same) | MOVaddr pseudo for the pair | MOVaddr target-flags(aarch64-page) @g, target-flags(aarch64-pageoff, aarch64-nc) @g | adrp x0, g add x0, x0, :lo12:g |
load i32, ptr @g (preemptible, GOT) | LOADgot pseudo | LOADgot target-flags(aarch64-got) @g and LDRWui killed %0, 0 | adrp x8, :got:g ldr x8, [x8, :got_lo12:g] ldr w0, [x8] |
Constants never become mov instructions inside SelectionDAG: it selects a rematerialisable pseudo, and AArch64ExpandPseudoInsts picks the cheapest real sequence after register allocation. That is why the MIR column is identical for four very different assembly sequences.
Sources: llvm/lib/Target/AArch64/AArch64InstrInfo.td:2667-2675, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9059-9520, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11187-11218, llvm/lib/Target/AArch64/AArch64InstrInfo.td:3703
Memory Instructions
Relevant source files
The following files were used as context for generating this wiki page:
Loads and stores are ISD::LOAD and ISD::STORE nodes with a chain. The initial DAG builds the address as plain ADD, MUL and SHL nodes, the combiner shapes it, and then ComplexPatterns choose an addressing mode.
Purpose and Scope
This page lists the AArch64 memory instructions that selection produces and the ordering guarantees the chain provides. The addressing-mode matchers are explained on AArch64 Instruction Selection; chain construction on DAG Construction.
Load and Store Forms
| IR | MIR | Assembly |
|---|---|---|
load i32, ptr (gep i32, p, i64 %i) | LDRWroX %0, %1, 0, 1 | ldr w0, [x0, x1, lsl #2] |
store i32 %v, ptr (gep i32, p, i64 %i) | STRWroX %2, %0, %1, 0, 1 | str w2, [x0, x1, lsl #2] |
load i32, ptr (gep i32, p, i64 3) | LDRWui %0, 3 | ldr w0, [x0, #12] |
load i32, ptr (gep i32, p, i64 -1) | LDURWi %0, -4 | ldur w0, [x0, #-4] |
load i32, ptr (gep i32, p, sext i32 %i) | LDRWroW %0, %1, 1, 1 | ldr w0, [x0, w1, sxtw #2] |
loop load plus pointer bump by 4 | LDRWpost %0, 4 (via tryIndexedLoad) | ldr w9, [x0], #4 |
two loads at p and p+8 | LDRXui %0, 0 and LDRXui %0, 1 | ldp x8, x9, [x0] |
two stores at p and p+8 | STRXui %1, %0, 0 and STRXui %2, %0, 1 | stp x1, x2, [x0] |
Two points worth noting. Scaled (ui) forms need an offset that is a non-negative multiple of the access size; anything else (the -4 above) falls to the unscaled LDUR family, which is a different ComplexPattern. And ldp and stp do not come from SelectionDAG: the last two rows show two independent instructions after selection, and AArch64LoadStoreOptimizer pairs them later, after register allocation.
Sources: llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:1490-1563, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:1801-1939, llvm/lib/Target/AArch64/AArch64InstrFormats.td:4210-4233, llvm/lib/Target/AArch64/AArch64InstrInfo.td:4610
How the Chain Keeps Memory Ordered
Chain edges make memory ordering safe. For store p, 1; x = load p; store p, 2 the DAG gives the load a chain input from the first store and the second store a chain input that depends on the load, so no later phase can reorder them, whatever it does with the data edges.
flowchart TD E["EntryToken"] --> S1["store p, 1"] S1 -- chain --> L["load p"] L -- chain --> S2["store p, 2"] S2 -- chain --> R["Root"] L -- value --> U["users of x"]
Independent loads, by contrast, are collected in PendingLoads while building and are not ordered against each other (see DAG Construction), so the DAG does not constrain their relative order; pairing into ldp happens later, after selection.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:4920-4993, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:1206-1229
Control Flow and Calls
Relevant source files
The following files were used as context for generating this wiki page:
A conditional branch is ISD::BRCOND (or BR_CC after combining). AArch64 marks both as Custom, so LowerBR_CC chooses between a compare-and-branch-on-zero form and a flag-setting compare plus b.cond. Calls and returns are lowered by LowerCall and LowerReturn.
Purpose and Scope
This page shows real results for branches, select, calls and returns on AArch64, and the lowering functions that produce them.
Branches and Select
| IR | MIR | Assembly |
|---|---|---|
br (icmp eq i32 %x, 0) | CBZW %0, %bb.2 then B %bb.3 | cbz w0, .LBB0_2 |
br (icmp slt i32 %x, %y) | %2 = SUBSWrr %0, %1, implicit-def $nzcv, Bcc 11, %bb.2, implicit $nzcv, B %bb.3 | cmp w0, w1 b.ge .LBB2_2 (the layout pass inverted the condition) |
select (icmp slt %a, %b), %a, %b | SUBSWrr %0, %1 and CSELWr %0, %1, 11, implicit $nzcv | cmp w0, w1 csel w0, w0, w1, lt |
select (icmp sgt %x, 10), 5, 6 | SUBSWri %0, 10, MOVi32imm 5, CSINCWr %2, %2, 12 | mov w8, #5 cmp w0, #10 cinc w0, w8, le |
br (icmp eq %x, 0) with trivial arms | SimplifyCFG turned it into a select before ISel, so no branch: SUBSWri %0, 0, CSINCWr %1, %1, 0 | cmp w0, #0 cinc w0, w1, ne |
The 11, 12 and 0 in Bcc and CSEL are AArch64 condition codes (0 = EQ, 1 = NE, 10 = GE, 11 = LT, 12 = GT, 13 = LE). The unconditional B %bb.3 that follows a Bcc is the DAG's fall-through ISD::BR; branch folding and block placement remove it when the target is the next block.
LowerBR_CC emits AArch64ISD::CBZ, CBNZ, TBZ or TBNZ for comparisons with zero and single-bit tests, and AArch64ISD::BRCOND with a condition code and flags from SUBS otherwise.
flowchart TD
B["ISD::BRCOND or BR_CC<br/>Custom on AArch64"] --> LB["LowerBR_CC"]
LB --> Z{"Compare with zero<br/>or single-bit test?"}
Z -- yes --> CB["AArch64ISD::CBZ, CBNZ,<br/>TBZ or TBNZ"]
Z -- no --> SU["AArch64ISD::SUBS<br/>sets NZCV"]
SU --> BC["AArch64ISD::BRCOND<br/>condition code and flags"]
CB --> S1["Selected: CBZW, CBNZW, TBZ"]
BC --> S2["Selected: Bcc"]
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11803-11990, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:12744-13022, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:13078-13156, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2840-2926
Calls and Returns
declare i32 @g(i32)
define i32 @call(i32 %x) {
%r = call i32 @g(i32 %x)
%s = add i32 %r, 1
ret i32 %s
}
visitCall calls LowerCallTo, which calls AArch64TargetLowering::LowerCall. That function assigns locations with the AAPCS rules (AArch64CallingConvention.td), emits CALLSEQ_START, one CopyToReg per register argument (glued to the call), stores for stack arguments, the AArch64ISD::CALL node with the callee and the register mask csr_aarch64_aapcs, CALLSEQ_END, and a CopyFromReg for each result. After selection and emission:
%0:gpr32 = COPY $w0
ADJCALLSTACKDOWN 0, 0, implicit-def dead $sp, implicit $sp
$w0 = COPY %0
BL @g, csr_aarch64_aapcs, implicit-def dead $lr, implicit $sp, implicit $w0, implicit-def $sp, implicit-def $w0
ADJCALLSTACKUP 0, 0, implicit-def dead $sp, implicit $sp
%1:gpr32sp = COPY $w0
%2:gpr32sp = ADDWri %1, 1, 0
$w0 = COPY %2
RET_ReallyLR implicit $w0
ADJCALLSTACKDOWN and UP are CALLSEQ_START and END: they bracket the argument setup and are rewritten by prologue/epilogue insertion once the frame size is known. BL implicitly defines $lr, which is why the function must save x30; that is why the assembly begins with str x30, [sp, #-16]! and ends with ldr x30, [sp], #16, even though nothing in the IR mentions it. The csr_aarch64_aapcs mask tells later passes which registers survive the call.
The return is CopyToReg $w0 followed by AArch64ISD::RET_GLUE, glued so the copy cannot be separated from the return. RET_ReallyLR is defined as Pseudo<(outs), (ins), [(AArch64retglue)]>, so selection turns RET_GLUE into it, and it is expanded to ret at the end.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10176-10934, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10947-11090, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:9316-9437, llvm/lib/Target/AArch64/AArch64InstrInfo.td:3703
End-to-End Example
Relevant source files
The following files were used as context for generating this wiki page:
One function followed through every phase: a register-offset load, a multiply by a constant, and a compare with select.
Purpose and Scope
The IR, the final MIR and the assembly are real llc output (LLVM 23.1.4, -mtriple=aarch64 -O2). The intermediate DAGs are reconstructed from the algorithms documented on the earlier pages; node numbers and some auxiliary nodes (such as undef offsets and TokenFactors) will differ from a real dump, but the sequence of transformations is what the passes do.
define i32 @f(ptr %p, i64 %i, i32 %k) {
%g = getelementptr inbounds i32, ptr %p, i64 %i
%v = load i32, ptr %g, align 4
%m = mul i32 %v, 9
%c = icmp slt i32 %m, %k
%r = select i1 %c, i32 %m, i32 %k
ret i32 %r
}
The function is one basic block with no PHIs and no values used across blocks, so FunctionLoweringInfo creates only the entry MBB.
Evolution of the DAG
flowchart TD A["1 Initial DAG<br/>shl, add, load, mul, setcc i1, select"] --> B["2 Combine 1<br/>select of setcc becomes select_cc"] B --> C["3 Type legalization<br/>nothing to do, Combine 2 skipped"] C --> D["4 Operation legalization<br/>select_cc becomes SUBS and CSEL"] D --> E["5 Combine 4<br/>mul by 9 becomes add of shl"] E --> F["6 Selection<br/>LDRWroX, ADDWrs, SUBSWrr, CSELWr"] F --> G["7 Emission<br/>MIR with virtual registers"]
Phase 1: Initial DAG
Arguments arrive through LowerFormalArguments as three live-in registers ($x0, $x1, $w2) read with CopyFromReg. The GEP becomes a shift (the element size 4 is a power of two) and an add. The load takes the entry chain, and because it is the only pending load the return lowering uses its chain output directly.
t0: ch,glue = EntryToken
t2: i64,ch = CopyFromReg t0, Register:i64 %0 ; p
t4: i64,ch = CopyFromReg t0, Register:i64 %1 ; i
t6: i32,ch = CopyFromReg t0, Register:i32 %2 ; k
t8: i64 = shl t4, Constant:i64<2>
t9: i64 = add t2, t8 ; address
t10: i32,ch = load<(load (s32) from %ir.g)> t0, t9, undef:i64
t12: i32 = mul t10, Constant:i32<9>
t13: i1 = setcc t12, t6, setlt:ch ; i1 is not a legal type
t14: i32 = select t13, t12, t6
t16: ch,glue = CopyToReg t10:1, Register:i32 $w0, t14
t17: ch = AArch64ISD::RET_GLUE t16, Register:i32 $w0, t16:1
Phase 2: DAG Combine 1
One fold applies. visitSELECT sees select (setcc t12, t6, setlt), t12, t6 and, because AArch64 registers SELECT_CC as Custom and LegalOperations is still false, rewrites it as a select_cc. The i1 setcc disappears with it. AArch64's performMulCombine still does nothing, because it returns early while DCI.isBeforeLegalizeOps() is true, so mul x, 9 is untouched for now.
t14: i32 = select_cc t12, t6, t12, t6, setlt ; replaces t13 (setcc) and the old t14 (select)
Sources: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:13408-13415, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:21202-21215
Phase 3: Type Legalization
No node has an illegal type any more: the only candidate, the i1 from setcc, vanished in Combine 1, and the shl amount is already i64, which AArch64 uses as its scalar shift-amount type. LegalizeTypes therefore reports no change, and Combine 2 (AfterLegalizeTypes) is skipped, because CodeGenAndEmitDAG only runs it if (Changed).
t14: i32 = select_cc t12, t6, t12, t6, setlt ; unchanged: every type is already legal
The vector legalizer, which runs next, will also find nothing to do.
Phase 4: Operation Legalization
The vector legalizer returns immediately because no node has a vector type. In operation legalization every node is visited, root first. add, shl and load are Legal. select_cc is Custom, so LowerSELECT_CC runs: it emits a flag-setting subtract and a CSEL that reads the flags with condition code 11 (LT). The old select_cc node dies.
t20: i32,i32 = AArch64ISD::SUBS t12, t6 ; result 1 = NZCV
t21: i32 = AArch64ISD::CSEL t12, t6, Constant:i32<11>, t20:1
t16: ch,glue = CopyToReg t10:1, Register:i32 $w0, t21
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:12744-13022
Phase 4b: DAG Combine 4
Now the legal-operations level is reached, so performMulCombine fires: 9 = 2^3 + 1, so mul x, 9 becomes add (shl x, 3), x, and all users of t12 (the SUBS and the CSEL) are rewired to the new add. The dead mul is deleted.
t22: i32 = shl t10, Constant:i64<3>
t23: i32 = add t10, t22
t20: i32,i32 = AArch64ISD::SUBS t23, t6
t21: i32 = AArch64ISD::CSEL t23, t6, Constant:i32<11>, t20:1
Phase 5: Instruction Selection
DoInstructionSelection walks the nodes from the root toward the entry. Each row is one Select decision, in order.
| Order | Node visited | What the matcher or C++ code does | Result |
|---|---|---|---|
| 1 | AArch64ISD::RET_GLUE | Pattern AArch64retglue | RET_ReallyLR |
| 2 | CopyToReg $w0 | Structural node; kept as is | stays |
| 3 | AArch64ISD::CSEL t23, t6, 11, t20:1 | Pattern on AArch64csel with the NZCV operand | CSELWr t23, t6, 11 |
| 4 | AArch64ISD::SUBS t23, t6 | Pattern on AArch64sub_flag | SUBSWrr t23, t6 |
| 5 | add t10, t22 | arith_shifted_reg32 sees shl t10, 3 on the second operand and absorbs it | ADDWrs t10, t10, 3 |
| 6 | shl t10, 3 | No users any more, skipped | removed |
| 7 | load t0, t9 | ro_Xindexed32 (SelectAddrModeXRO) sees add t2, (shl t4, 2) with only memory users | LDRWroX t2, t4, 0, 1 |
| 8 | add t2, t8, shl t4, 2 | Absorbed into the load's addressing mode, dead | removed |
| 9 | CopyFromReg nodes, EntryToken | Structural | stay |
Phases 6 and 7: Scheduling and Emission
The source-order list scheduler produces the order load, add, subtract, select, copy, return. InstrEmitter creates virtual registers for each machine node's result (class from the instruction's operand constraint), turns the CopyToReg into $w0 = COPY %6, and then EmitLiveInCopies inserts the three live-in copies at the top. Real output (-stop-after=finalize-isel):
bb.0 (%ir-block.0):
liveins: $x0, $x1, $w2
%2:gpr32 = COPY $w2
%1:gpr64 = COPY $x1
%0:gpr64common = COPY $x0
%3:gpr32 = LDRWroX %0, %1, 0, 1 :: (load (s32) from %ir.g)
%4:gpr32 = ADDWrs %3, %3, 3
%5:gpr32 = SUBSWrr %4, %2, implicit-def $nzcv
%6:gpr32 = CSELWr %4, %2, 11, implicit $nzcv
$w0 = COPY %6
RET_ReallyLR implicit $w0
The base pointer is %0:gpr64common, not plain gpr64: the emitter constrained its register class because a load base cannot be xzr. The index %1 stays gpr64 because SelectAddrModeXRO produced it as the index operand.
After SelectionDAG
Register allocation, the coalescer and frame lowering eliminate the COPYs. The SUBSWrr result is dead (only its flags are used), so it becomes a cmp alias. The final assembly:
f:
ldr w8, [x0, x1, lsl #2]
add w8, w8, w8, lsl #3
cmp w8, w2
csel w0, w8, w2, lt
ret
Five instructions for six IR instructions: the address computation and the multiply were folded away (into an addressing mode and a shifted-operand add), and the icmp plus select pair became cmp plus csel.
Contrast: the Same IR at -O0
At -O0 on AArch64 the selector is GlobalISel, not SelectionDAG (-global-isel-abort=1 reports no fallback), and the output shows the difference: there is no combiner pass that rewrites mul x, 9.
f:
ldr w8, [x0, x1, lsl #2]
mov w9, #9
mul w8, w8, w9
subs w9, w8, w2
csel w0, w8, w2, lt
ret
The load address still became a single register-offset load, but the multiply stays a mul, and the compare still writes a result register (subs) rather than being a cmp.
Tooling, Debugging and Extending
Relevant source files
The following files were used as context for generating this wiki page:
To see the DAG at each phase you need an llc built with assertions: -debug-only and the graph viewers exist only in such builds. A release llc still gives everything at the MIR level.
Purpose and Scope
This page lists the llc switches that matter for SelectionDAG work, how to read a DAG dump, a debugging recipe for bad code, and the three ways to extend selection: a pattern, a combine and a custom lowering.
Building an llc That Can Print DAGs
cmake -G Ninja -S llvm -B build -DCMAKE_BUILD_TYPE=Release \
-DLLVM_ENABLE_ASSERTIONS=ON -DLLVM_TARGETS_TO_BUILD=AArch64
ninja -C build llc llvm-tblgen FileCheck
Release with assertions is much faster than a full Debug build and has all the -debug-only output.
Command-Line Switches
| Goal | Switch | Notes |
|---|---|---|
| Print every DAG stage plus the matcher trace | -debug-only=isel | Needs assertions. Titles: Initial selection DAG, Optimized lowered selection DAG, Type-legalized selection DAG, Optimized type-legalized selection DAG, Vector-legalized selection DAG, Vector/type-legalized selection DAG, Optimized vector-legalized selection DAG, Legalized selection DAG, Optimized legalized selection DAG, Selected selection DAG |
| Print only the DAG dumps | -debug-only=isel-dump | ISEL_DUMP_DEBUG_TYPE is DEBUG_TYPE "-dump" |
| One block only | -filter-view-dags=<block name> | Also limits the graph viewers |
| Draw a stage as a graph (needs Graphviz) | -view-dag-combine1-dags, -view-legalize-types-dags, -view-dag-combine-lt-dags, -view-legalize-dags, -view-dag-combine2-dags, -view-isel-dags, -view-sched-dags, -view-sunit-dags | One per phase |
| Sort nodes in dumps | -dump-sorted-dags | Topological order, easier to diff |
| Stop after instruction selection and print MIR | -stop-after=finalize-isel | Works in release builds; also -stop-before=..., -print-after-all |
| Show the pass pipeline | -debug-pass=Structure | Find aarch64-isel, finalize-isel, phi-node-elimination, register-coalescer |
| Pick the selector | -global-isel=0 / 1, -fast-isel, -O0..-O3 | At -O0 AArch64 uses GlobalISel by default, with SelectionDAG fallback |
| Pick the DAG scheduler | -pre-RA-sched=source, list-burr, list-ilp, list-hybrid, fast, linearize | See Scheduling and MIR Emission |
| Disable the generic combiner | -combiner-disabled | Quick check whether a miscompile comes from a combine |
| Bisect combines | -debug-counter=dagcombine-skip=N,dagcombine-count=M | Needs assertions; DAGCombiner::combine checks the counter |
| Features that change legality | -mattr=+cssc, -mcpu=... | Changes setOperationAction results |
| Make fallbacks loud | -global-isel-abort=1, -fast-isel-abort=1 | Turns silent fallbacks into errors |
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:118, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:130, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:149-182, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:219, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:98, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:157-160, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp:70-87
Reading a DAG Dump
t0: ch,glue = EntryToken
t2: i64,ch = CopyFromReg t0, Register:i64 %0
t4: i32 = truncate t2
t5: i32 = add nsw t4, Constant:i32<1>
t6: ch = store<(store (s32) into %ir.p)> t0, t5, t2, undef:i64
tNis a node, printed asresult types = opcode operands;t2:1names result 1 oft2.chis a chain (MVT::Other),glueis a glue edge, others are data types.- Flags such as
nswfollow the opcode; the<...>afterloadorstoreis its memory operand. Constant:i32<1>is anISD::Constant;TargetConstant:i32<1>is a final immediate.undefas the offset of a load or store is the unindexed placeholder.
Debugging Recipe for Bad Code
flowchart TD
A["Reduce to a small .ll"] --> B["llc -O2 -stop-after=finalize-isel"]
B --> C{"MIR as expected?"}
C -- yes --> L["Look at later MIR passes<br/>print-after-all, find the first change"]
C -- no --> D["Assertion build: -debug-only=isel-dump"]
D --> E["Read Optimized legalized selection DAG"]
E --> F{"DAG shape already wrong?"}
F -- yes --> G["Compare consecutive dumps,<br/>find the combine or legalization"]
F -- no --> H["Wrong instruction chosen:<br/>search .td patterns and AddedComplexity,<br/>read the isel matcher trace"]
Adding Behaviour: Three Recipes
A new instruction pattern (selection only). Add a Pat next to similar ones in AArch64InstrInfo.td with a sensible AddedComplexity, then rebuild. The shape, from the existing file:
def : Pat<(i32 (mul GPR32:$Rn, GPR32:$Rm)),
(MADDWrrr GPR32:$Rn, GPR32:$Rm, WZR)>;
The build regenerates AArch64GenDAGISel.inc; its // Src: and // Dst: comments show how the pattern was placed in the decision tree.
A new DAG combine (optimisation). Register interest in the constructor with setTargetDAGCombine(ISD::XYZ), add case ISD::XYZ: return performXYZCombine(N, DCI, DAG); in AArch64TargetLowering::PerformDAGCombine, and write the function using DCI.isBeforeLegalize(), isBeforeLegalizeOps() and DAG.getNode(...). Always check legality when the level is past legalization, and make sure the replacement does not match your own fold again.
A new custom lowering (a generic node the target cannot select). Call setOperationAction(ISD::FOO, MVT::i32, Custom) in the constructor, add case ISD::FOO: return LowerFOO(Op, DAG); in LowerOperation, build target nodes there (for example an AArch64ISD::BAR declared by an SDNode<"AArch64ISD::BAR", ...> record in the .td files) and add a Pat that maps AArch64bar to the machine instruction. If the result type is illegal, implement ReplaceNodeResults instead.
Sources: llvm/lib/Target/AArch64/AArch64InstrInfo.td:2911-2921, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:30803-31168, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:8432-8850
Tests
Backend tests live in llvm/test/CodeGen/AArch64/ and look like ; RUN: llc < %s -mtriple=aarch64 | FileCheck %s. The script llvm/utils/update_llc_test_checks.py regenerates the CHECK lines. For MIR-level tests use -stop-after, -run-pass, or llvm/utils/update_mir_test_checks.py.
Selector Comparison and Glossary
Relevant source files
The following files were used as context for generating this wiki page:
LLVM ships three instruction selectors, and AArch64 supports all of them. They differ in what intermediate form they use and how much of the function they see at once.
Purpose and Scope
This page compares SelectionDAG with FastISel and GlobalISel, summarises the traversal orders, and defines the vocabulary used across the wiki.
SelectionDAG, FastISel and GlobalISel
flowchart LR IR["LLVM IR"] --> SD["SelectionDAG<br/>DAG per block"] IR --> FI["FastISel<br/>direct, backward in block"] IR --> GI["GlobalISel<br/>IRTranslator to generic MIR"] FI -.->|falls back per instruction| SD GI -.->|falls back per function| SD SD --> MIR["Selected MIR"] FI --> MIR GI --> MIR
| SelectionDAG | FastISel | GlobalISel | |
|---|---|---|---|
| Default on AArch64 | -O1 and above | Exists (AArch64FastISel) but only used on request | -O0 (controlled by -aarch64-enable-global-isel-at-O); falls back to SelectionDAG per function |
| Intermediate form | A DAG of SDNodes per block | None: emits MachineInstrs directly | Generic MIR (G_ADD, G_LOAD, with low-level types such as s32, <4 x s32>) |
| Scope | One block | One block, walked backward from the terminator | Whole function |
| Optimisation | DAGCombiner, up to four runs | None | Rule-based combiners before and after legalization, written in TableGen (GICombineRule) |
| Legalization | Type legalizer, then operation legalizer (+ vector legalizer) | None: gives up on anything it cannot select | One Legalizer pass driven by per-opcode LegalizerInfo rules |
| Instruction choice | Generated matcher from TableGen patterns | Hand-written plus generated fast selectors for common cases | Generated from the same Pat records and ComplexPatterns (GIComplexPatternEquiv, seen as gi_ro_Xindexed32 in AArch64InstrFormats.td) |
| Register class or bank | Picked during selection from the instruction's operand constraints | Same | A separate RegBankSelect pass (general vs FP/SIMD), then instruction selection |
| PHIs | Machine PHIs created ahead of time; operands added per block (PHI Node Resolution) | Shares the SelectionDAG driver and its PHI machinery | IRTranslator creates G_PHI directly; no export step is needed because the whole function is visible |
| Failure mode | A Cannot select fatal error | Falls back to SelectionDAG for the rest of the block | Falls back to SelectionDAG for the whole function ("Instruction selection used fallback path") |
| Strength | Best code quality, the most mature target coverage | Very fast compile at -O0 | Faster than SelectionDAG, good cross-block optimisation, still maturing |
The llc used for the examples confirmed two of these directly. At -O0, -global-isel-abort=1 produced no error for the example functions, so GlobalISel selected them. At -O2, the pass list printed by -debug-pass=Structure contains the GlobalISel passes, but the IRTranslator immediately marks the function as failed and the aarch64-isel pass (the SelectionDAG selector) does the work; -global-isel-abort=2 reports "Instruction selection used fallback path". FastISel iterates each block backward from the terminator, as SelectAllBasicBlocks shows (for (; BI != Begin; --BI)).
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:404-418, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1656-1971, llvm/lib/Target/AArch64/AArch64InstrFormats.td:3927-3949
Traversal Orders at a Glance
| Step | Visit order | In one sentence |
|---|---|---|
| Block order | Reverse post-order of the CFG | Predecessors are selected before successors where the CFG allows |
| Build DAG | IR instruction order inside the block | One visit per IR instruction, forward |
| DAGCombiner | Worklist, last-in-first-out, seeded in AllNodes order | Starts at the root, then descends into operands; every change re-queues the changed node's users |
| Type legalizer | Operands before users | A node is processed once all its operands are |
| Vector legalizer | Operands before users (topological order) | One sweep |
| Operation legalizer | Users before operands, sweeps repeated until nothing new is legalized | Reaches a fixed point because legalization creates new nodes |
| Instruction selection | Root first, single sweep | Users first, so a pattern can absorb its operands |
| Scheduling | Bottom-up list scheduling from the exit node, then reversed | Source-order priority on AArch64 |
| Emission | The scheduled sequence, forward | One MachineInstr per machine node |
Glossary
| Term | Meaning |
|---|---|
| SDNode / SDValue | A DAG node, and one of its results (node pointer plus result number) |
| MVT / EVT | Simple and extended value types (i32, v4i32; i7, i128) |
| Chain | MVT::Other edge that orders side effects; starts at EntryToken |
| Glue | MVT::Glue edge that forces two nodes to be adjacent |
| ISD node | Target-independent opcode in the ISD:: namespace |
| Target node | Opcode in the AArch64ISD:: namespace, still a DAG node |
| Machine node | A node whose opcode is an instruction (AArch64::ADDWrr), created by selection |
| Legalization | Rewriting the DAG so every type and operation is supported by the target |
| Promote / Expand / Custom / LibCall / Legal | The five actions a target can register for an operation |
| LowerOperation / ReplaceNodeResults | Target hooks called for Custom operations (legal result types and illegal result types respectively) |
| DAGCombine | The DAG peephole optimiser; the target hook is PerformDAGCombine |
| PatFrag | A named TableGen sub-pattern, often with a C++ predicate |
| ComplexPattern | A pattern operand matched by a C++ function (addressing modes, shifted operands) |
| SDNodeXForm | A C++ transformation applied to a matched constant before it is used |
| AddedComplexity | Manual priority bonus for a pattern |
| Matcher table | The generated bytecode that SelectCodeCommon interprets |
| Fold | A pattern absorbing an operand node (needs one use and legality) |
| SUnit | A scheduling unit: a machine node or a glued group of them |
| Export register | A virtual register used to carry an IR value across blocks |
| PHINodesToUpdate | List of (machine PHI, vreg) pairs waiting for the block to be emitted |
| MIR | Machine IR: MachineInstrs in a MachineFunction, with virtual registers before allocation |
| NZCV | AArch64 condition-flags register, written by SUBS, ADDS, ANDS, read by CSEL and Bcc |
Where Do I Look?
| Question | Look at |
|---|---|
| Why did my IR instruction become a libcall or a long sequence? | setOperationAction(...) for that opcode and type in AArch64ISelLowering.cpp (Operation and Vector Legalization) |
| Why did this type change before selection? | addRegisterClass, getTypeAction (Type Legalization) |
| Which AArch64 instruction does a node become? | The patterns in AArch64InstrInfo.td and AArch64InstrFormats.td, or a tryXxx in AArch64ISelDAGToDAG.cpp (Instruction Selection) |
| Why was an addressing mode not folded? | The ComplexPattern function (SelectAddrModeXRO and friends) and the one-use rule (Matcher Interpreter and Folding) |
Why is a madd or ldp missing right after ISel? | They are formed after selection: MachineCombiner and the load/store optimiser |
Why do I see a COPY for a value that never leaves the block? | Cross-block exports and PHI copies (PHI Node Resolution) |
Cannot select: tN: ... | A node with no pattern and no custom lowering; check legalization actions first |
| A fold fires too early or too late | Its CombineLevel guard, isBeforeLegalizeOps() and friends (DAG Combiner) |
Part 3: Calling Conventions and Call Lowering
CallingConv.td, CCState, LowerFormalArguments, LowerCall, LowerReturn, varargs, byval, sret and tail calls.
Pages
Calling Conventions Overview
Relevant source files
The following files were used as context for generating this wiki page:
A calling convention is the contract between a caller and a callee: which registers or stack slots hold each argument, where the return value goes, which registers the callee must preserve, and who cleans up the stack. In LLVM the placement rules are written once in TableGen, and three TargetLowering hooks use them while the SelectionDAG is being built from IR.
Purpose and Scope
This wiki explains how a backend implements calling conventions, with AArch64 (AAPCS64) as the real example and a made-up "Toy" target for minimal code. It covers the TableGen language, CCState, the three lowering hooks, varargs and special arguments, tail calls, a custom-backend guide and real llc walkthroughs. For where this fits in a whole backend see the bring-up wiki.
What a Calling Convention Decides
| Question | Where LLVM answers it |
|---|---|
| Which register or stack offset holds argument N? | CallingConv record in <T>CallingConv.td (CC_*) |
| Where does the return value go? | RetCC_* record |
| Which registers survive a call? | CalleeSavedRegs record → register mask on each call |
| How are small integers extended? | CCPromoteToType and the LocInfo of each CCValAssign |
| Who removes stack arguments? | Target code in LowerCall (CALLSEQ_END bytes) |
| Can this call be a jump? | isEligibleForTailCallOptimization |
Where Lowering Happens
flowchart TD
IR["LLVM IR function"] --> SDB["SelectionDAGBuilder"]
SDB -->|function entry| LA["SelectionDAGISel::LowerArguments"]
LA --> LFA["Target::LowerFormalArguments"]
SDB -->|each call| LCT["SelectionDAGBuilder::LowerCallTo"]
LCT --> TLCT["TargetLowering::LowerCallTo"]
TLCT --> LC["Target::LowerCall"]
SDB -->|each ret| VR["SelectionDAGBuilder::visitRet"]
VR --> LR["Target::LowerReturn"]
LFA --> CC["CCState + generated CC_* function"]
LC --> CC
LR --> CC
Generic code splits every IR argument into legal-typed pieces (ISD::InputArg / ISD::OutputArg, each with flags such as sext, byval, sret) before calling the target. The target only sees legal value types.
| Generic entry point | Line | Calls |
|---|---|---|
SelectionDAGBuilder::visitRet | 2214 | LowerReturn |
SelectionDAGBuilder::LowerCallTo | 9202 | TargetLowering::LowerCallTo |
TargetLowering::LowerCallTo | 11333-11334 | LowerCall |
SelectionDAGISel::LowerArguments | 11970 | LowerFormalArguments |
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2214, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:9202, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:11333-11334, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:11970
The DAG-building side of this is described on the SelectionDAG wiki's DAG construction page.
A First Example
llc -O2 -mtriple=aarch64-linux-gnu on a function with ten i64 arguments that returns a0 + a9 + a8:
many: // @many
.cfi_startproc
ldp x9, x8, [sp]
add x8, x0, x8
add x0, x8, x9
ret
a0 arrives in x0; a8 and a9 did not fit in x0–x7, so they are at [sp] and [sp, #8] and are loaded with one ldp. The result goes back in x0. Every piece of that comes from the rules on the next pages.
Pages
The CallingConv.td Language
Relevant source files
The following files were used as context for generating this wiki page:
A CallingConv record is an ordered list of actions. For each value, the generated C++ function tries the actions from top to bottom. Predicate actions (CCIfType, CCIf...) wrap another action and only apply when their test passes. The first action that assigns a location ends the search. If no action matches, the function returns true ("not handled").
Purpose and Scope
The action classes in TargetCallingConv.td, how AArch64 combines them, the Entry flag, CCDelegateTo, CCCustom, and CalleeSavedRegs. How the generated function is driven is on CCState and CCValAssign.
How a Rule List Is Evaluated
flowchart TD
V["value: ValVT, LocVT, ArgFlags"] --> A1{"action 1 applies?"}
A1 -->|"no"| A2{"action 2 applies?"}
A1 -->|"yes: changes type (Promote/BitConvert)"| A2
A1 -->|"yes: assigns location"| DONE["CCValAssign added, return false"]
A2 --> AN["... action N"]
AN -->|"nothing assigned"| FAIL["return true (unhandled)"]
Type-changing actions (CCPromoteToType, CCBitConvertToType) do not end the search: they change LocVT and LocInfo, and evaluation continues with the next action using the new type. That is why AArch64 can write CCIfType<[i1, i8, i16], CCPromoteToType<i32>> once and then handle all of them with the i32 rules.
Action Classes
| Class | Line | Effect |
|---|---|---|
CCCustom<"fn"> | 18 | Call a hand-written C++ function |
CCIfType<[types], A> | 30 | Apply A if LocVT is in the list |
CCIf<"cond", A> | 35 | Apply A if the C++ expression is true |
CCIfByVal<A> | 41 | Argument has the byval attribute |
CCIfSwiftSelf, CCIfSwiftAsync, CCIfSwiftError | 51-61 | Swift ABI attributes |
CCIfConsecutiveRegs<A> | 71 | Part of an aggregate split into consecutive registers (HFAs) |
CCIfCC<"CC", A> | 75 | Current calling convention is CC |
CCIfInReg, CCIfNest, CCIfSplit, CCIfSRet | 80-92 | Argument flags |
CCIfVarArg, CCIfNotVarArg | 95-98 | Function or call is variadic |
CCIfArgFixed, CCIfArgVarArg | 101-104 | This particular argument is a fixed or variadic one |
CCAssignToReg<[regs]> | 118 | First free register in the list |
CCAssignToRegWithShadow<[regs], [shadows]> | 131 | Same, but also marks the matching shadow register used |
CCAssignToStack<size, align> | 141 | Next stack slot (size 0 means "size of the type") |
CCAssignToStackWithShadow<size, align, [regs]> | 149 | Stack slot, and mark registers used |
CCPassByVal<size, align> | 169 | Copy a byval aggregate to the stack |
CCPromoteToType<type> | 176 | Extend to a wider type (sign/zero/any from the flags) |
CCBitConvertToType<type> | 188 | Reinterpret as another type of the same size |
CCPassIndirect<type> | 200 | Pass a pointer to a copy |
CCDelegateTo<CC> | 206 | Run another CallingConv's rules |
CallingConv<[actions]> | 212 | The record itself |
CalleeSavedRegs<(add ...)> | 235 | Registers a callee must preserve |
Sources: llvm/include/llvm/Target/TargetCallingConv.td:14-235
AArch64's AAPCS Rules
AArch64 keeps the common rules in a defvar list and builds several conventions from it. The order matters:
- Special-purpose arguments first:
nestinX15,sretinX8,byvalto the stack, Swift registers, HFA blocks viaCCCustom. - Type normalization: pointers as
i64, some vectors bit-converted,i1/i8/i16promoted toi32. - Registers:
W0–W7/X0–X7for integers,H/S/D/Q0–7 for floating point and vectors,Z0–Z7andP0–P3for SVE. - Stack, when the registers run out.
// In AAPCS, an SRet is passed in X8, not X0 like a normal pointer parameter.
...
CCIfSRet<CCIfType<[i64], CCAssignToReg<[X8]>>>,
// Put ByVal arguments directly on the stack. Minimum size and alignment of a
// slot is 64-bit.
CCIfByVal<CCPassByVal<8, 8>>,
...
CCIfConsecutiveRegs<CCCustom<"CC_AArch64_Custom_Block">>,
...
CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
CCIfType<[i32], CCAssignToReg<[W0, W1, W2, W3, W4, W5, W6, W7]>>,
// i128 is split to two i64s, we can't fit half to register X7.
CCIfType<[i64], CCIfSplit<CCAssignToRegWithShadow<[X0, X2, X4, X6],
[X0, X1, X3, X5]>>>,
...
CCIfType<[i64], CCAssignToReg<[X0, X1, X2, X3, X4, X5, X6, X7]>>,
...
CCIfType<[f64], CCAssignToReg<[D0, D1, D2, D3, D4, D5, D6, D7]>>,
...
// If more than will fit in registers, pass them on the stack instead.
CCIfType<[i1, i8, i16, f16, bf16], CCAssignToStack<8, 8>>,
CCIfType<[i32, f32], CCAssignToStack<8, 8>>,
The i128 rule shows CCAssignToRegWithShadow: the first half of an i128 must go in an even register (X0, X2, ...), and assigning X2 also uses up X1, so the pair never starts at an odd register.
Integer and floating-point registers are counted separately, because CCAssignToReg only looks at the listed registers. A function (i32, double, i8, float) gets w0, d0, w1, s1; see the walkthroughs.
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:30-123
Entry Points and Delegation
let Entry = 1 in
def CC_AArch64_AAPCS : CallingConv<AArch64_Common>;
let Entry = 1 in
def RetCC_AArch64_AAPCS : CallingConv<[
...
Entry = 1 makes -gen-callingconv emit a non-static function that C++ can name. Conventions without it are only usable through CCDelegateTo from other records. The generated functions have the CCAssignFn signature and are included into AArch64ISelLowering.cpp (and the GlobalISel call lowering) from AArch64GenCallingConv.inc.
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:125-162, llvm/lib/Target/AArch64/CMakeLists.txt:8
CCCustom
When a rule cannot be written in TableGen, CCCustom<"Name"> calls a C++ function with the CCCustomFn-like signature (ValNo, ValVT, LocVT, LocInfo, ArgFlags, State) returning true if it handled the value. AArch64 uses CC_AArch64_Custom_Block for homogeneous floating-point aggregates, which must go in consecutive registers or entirely on the stack; it collects the pieces in State.getPendingLocs() until the last one arrives, then allocates them together.
| Function | Line |
|---|---|
finishStackBlock | 43 |
CC_AArch64_Custom_Stack_Block | 116 |
CC_AArch64_Custom_Block | 135 |
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.cpp:43-135
Callee-Saved Registers
def CSR_AArch64_AAPCS : CalleeSavedRegs<(add X19, X20, X21, X22, X23, X24,
...
def CSR_AArch64_AAPCS_ThisReturn : CalleeSavedRegs<(add CSR_AArch64_AAPCS, X0)>;
...
def CSR_AArch64_NoRegs : CalleeSavedRegs<(add)>;
-gen-register-info produces <Name>_SaveList (a null-terminated list, for getCalleeSavedRegs) and <Name>_RegMask (a bit mask, for getCallPreservedMask). Variants are built with add: ThisReturn adds X0 for calls whose result is known to equal the first argument. How register masks are used by the allocator is on the regalloc registers page.
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:594, llvm/lib/Target/AArch64/AArch64CallingConvention.td:702, llvm/lib/Target/AArch64/AArch64CallingConvention.td:720
Target-Specific Predicates
A target can define its own predicate classes on top of CCIf. AArch64 defines three at the top of its file:
/// CCIfBigEndian - Match only if we're in big endian mode.
class CCIfBigEndian<CCAction A> :
CCIf<"State.getMachineFunction().getDataLayout().isBigEndian()", A>;
class CCIfILP32<CCAction A> :
CCIf<"State.getMachineFunction().getDataLayout().getPointerSize() == 4", A>;
/// CCIfSubtarget - Match if the current subtarget has a feature F.
class CCIfSubtarget<string F, CCAction A>
The string is pasted into the generated C++, where State is the CCState& argument.
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:13-24
CCState and CCValAssign
Relevant source files
The following files were used as context for generating this wiki page:
CCState is the bookkeeping object passed to every generated calling-convention function. It records which registers are already taken and how much stack has been used, and it collects the result: one CCValAssign per value, saying "this value lives in register R" or "this value lives at stack offset N", plus how it was extended or converted on the way.
Purpose and Scope
The CCValAssign record, the CCAssignFn signature, the CCState allocation functions and the Analyze* drivers. How the three lowering hooks consume the result is on LowerFormalArguments, LowerCall and LowerReturn.
Data Flow
flowchart LR
INS["Ins / Outs<br/>(ISD::InputArg / OutputArg)"] --> AN["CCState::Analyze*"]
AN -->|"for each value"| FN["CCAssignFn<br/>(generated CC_Toy)"]
FN -->|"AllocateReg / AllocateStack"| ST["CCState: UsedRegs, StackSize"]
FN -->|"addLoc"| LOCS["SmallVector<CCValAssign>"]
LOCS --> HOOK["target hook walks the list"]
CCValAssign
Each entry holds the value number, its original type (ValVT), the type in the location (LocVT), either a register or a stack offset, and a LocInfo describing the conversion:
class CCValAssign {
public:
enum LocInfo {
Full, // The value fills the full location.
SExt, // The value is sign extended in the location.
ZExt, // The value is zero extended in the location.
AExt, // The value is extended with undefined upper bits.
...
BCvt, // The value is bit-converted in the location.
Trunc, // The value is truncated in the location.
...
FPExt, // The floating-point value is fp-extended in the location.
Indirect // The location contains pointer to the value.
| Accessor | Meaning |
|---|---|
isRegLoc() / getLocReg() | Value is in a physical register |
isMemLoc() / getLocMemOffset() | Value is on the stack at this offset from the start of the argument area |
getValVT() / getLocVT() | Type before and after conversion |
getLocInfo() | How to convert (SExt → emit AssertSext on entry, SIGN_EXTEND at a call, ...) |
needsCustom() | Set by a CCCustom handler; the hook must handle it specially |
Sources: llvm/include/llvm/CodeGen/CallingConvLower.h:34-55
The CCAssignFn Signature
Every Entry = 1 record becomes a function of this type:
typedef bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT,
CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
Type *OrigTy, CCState &State);
It returns false when it assigned a location and true when no rule matched. Targets can also write these by hand and mix them with generated ones.
Sources: llvm/include/llvm/CodeGen/CallingConvLower.h:157-166
Allocation
CCAssignToReg<[...]> turns into a call to AllocateReg, which picks the first unallocated register in the list and marks it (and its aliases) used:
MCRegister AllocateReg(ArrayRef<MCPhysReg> Regs) {
unsigned FirstUnalloc = getFirstUnallocated(Regs);
if (FirstUnalloc == Regs.size())
return MCRegister(); // Didn't find the reg.
// Mark the register and any aliases as allocated.
MCPhysReg Reg = Regs[FirstUnalloc];
MarkAllocated(Reg);
return Reg;
Because aliases are marked, assigning W0 also makes X0 unavailable. CCAssignToStack<Size, Align> becomes AllocateStack:
int64_t AllocateStack(unsigned Size, Align Alignment) {
int64_t Offset;
if (NegativeOffsets) {
StackSize = alignTo(StackSize + Size, Alignment);
Offset = -StackSize;
} else {
Offset = alignTo(StackSize, Alignment);
StackSize = Offset + Size;
}
MaxStackArgAlign = std::max(Alignment, MaxStackArgAlign);
ensureMaxAlignment(Alignment);
return Offset;
}
After the analysis, getStackSize() is the total size of the outgoing (or incoming) stack argument area. LowerCall passes it to CALLSEQ_START.
Sources: llvm/include/llvm/CodeGen/CallingConvLower.h:246, llvm/include/llvm/CodeGen/CallingConvLower.h:333-360, llvm/include/llvm/CodeGen/CallingConvLower.h:408-431
The Analyze Drivers
| Function | Used by | Input | On failure |
|---|---|---|---|
AnalyzeFormalArguments(Ins, Fn) | LowerFormalArguments | ISD::InputArg | report_fatal_error("unable to allocate function argument #N") |
AnalyzeCallOperands(Outs, Fn) | LowerCall | ISD::OutputArg | llvm_unreachable (prints the type in debug builds) |
AnalyzeCallResult(Ins, Fn) | LowerCall | ISD::InputArg | fatal error |
AnalyzeReturn(Outs, Fn) | LowerReturn | ISD::OutputArg | report_fatal_error("unable to allocate function return #N") |
CheckReturn(Outs, Fn) | CanLowerReturn | ISD::OutputArg | returns false |
All of them are the same loop: call Fn for each value with ValVT == LocVT and LocInfo == Full:
CCState::AnalyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Ins,
CCAssignFn Fn) {
unsigned NumArgs = Ins.size();
for (unsigned i = 0; i != NumArgs; ++i) {
MVT ArgVT = Ins[i].VT;
ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, Ins[i].OrigTy, *this))
report_fatal_error("unable to allocate function argument #" + Twine(i));
}
}
CheckReturn is the only one that does not fail: it is used to ask whether the return fits, and if not, LLVM rewrites the function to return through a hidden sret pointer.
AArch64 does not use AnalyzeFormalArguments directly: it writes the loop itself so it can pass the original i8/i16 type as ValVT for stack arguments (see LowerFormalArguments).
Sources: llvm/lib/CodeGen/CallingConvLower.cpp:85-141, llvm/lib/CodeGen/CallingConvLower.cpp:164-180
Construction and byval
CCState::CCState(CallingConv::ID CC, bool IsVarArg, MachineFunction &MF,
SmallVectorImpl<CCValAssign> &Locs, LLVMContext &Context,
bool NegativeOffsets)
IsVarArg is what CCIfVarArg tests. NegativeOffsets is for targets whose argument area grows the other way.
HandleByVal (reached from CCPassByVal) takes the size and alignment from the byval attribute, lets the target claim registers for part of the aggregate through TargetLowering::HandleByVal, and allocates the rest on the stack:
Align Alignment = ArgFlags.getNonZeroByValAlign();
unsigned Size = ArgFlags.getByValSize();
...
MF.getSubtarget().getTargetLowering()->HandleByVal(this, Size, Alignment);
Size = unsigned(alignTo(Size, MinAlign));
uint64_t Offset = AllocateStack(Size, Alignment);
addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
Sources: llvm/lib/CodeGen/CallingConvLower.cpp:28-59, llvm/include/llvm/CodeGen/CallingConvLower.h:433-442
Other Helpers
| Function | Line | Use |
|---|---|---|
getRemainingRegParmsForType | 203 | Registers still free for a type (musttail forwarding) |
analyzeMustTailForwardedRegisters | 243 | Keep unused argument registers live through a musttail vararg thunk |
resultsCompatible | 264 | Do two conventions return values in the same places? (tail-call check) |
LowerFormalArguments
Relevant source files
The following files were used as context for generating this wiki page:
LowerFormalArguments runs once per function, at the start of DAG building. It receives the function's incoming arguments as a list of legal-typed ISD::InputArgs and must return one SDValue per entry in InVals. Register arguments become CopyFromReg nodes from virtual registers tied to live-in physical registers; stack arguments become loads from fixed frame objects.
Purpose and Scope
The steps of AArch64's LowerFormalArguments, and the pattern a new target should copy. Line numbers for AArch64ISelLowering.cpp are from the committed file at a2171756.
The Hook
virtual SDValue LowerFormalArguments(
SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
llvm_unreachable("Not Implemented");
}
It is called from SelectionDAGISel::LowerArguments, which builds Ins from the IR arguments (splitting i128 into two i64s, setting sext/zext/byval flags) and maps the returned values back to the IR arguments.
Sources: llvm/include/llvm/CodeGen/TargetLowering.h:4893-4898, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:11970
Steps in AArch64
flowchart TD
A["1. CCState + assign a location to every Ins[i]"] --> B{"for each CCValAssign"}
B -->|byval| BV["fixed object at LocMemOffset, pass its frame index"]
B -->|register| R["pick reg class, MF.addLiveIn, CopyFromReg, undo extension"]
B -->|stack| S["CreateFixedObject, extending load"]
R --> I["InVals.push_back"]
S --> I
BV --> I
I --> V["2. varargs: save remaining registers, record stack offset"]
V --> F["3. record stack argument size for tail calls"]
1. Assign locations
// Assign locations to all of the incoming arguments.
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
...
CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, UseVarArgCC);
for (unsigned i = 0; i != NumArgs; ++i) {
MVT ValVT = Ins[i].VT;
if (Ins[i].isOrigArg()) {
...
// If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
ValVT = MVT::i8;
else if (ActualMVT == MVT::i16)
ValVT = MVT::i16;
}
bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags,
Ins[i].OrigTy, CCInfo);
assert(!Res && "Call operand has unhandled type");
AArch64 runs the loop itself instead of calling AnalyzeFormalArguments so that an i8 passed on the stack is treated as one byte (the stack rule CCAssignToStack<8, 8> keeps the slot 8 bytes, but the load is a byte load).
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9314-9372
2. Register arguments
For each register location, choose a register class from the location type, make the physical register a live-in of the function (which creates a virtual register), and copy from it:
if (VA.isRegLoc()) {
// Arguments stored in registers.
EVT RegVT = VA.getLocVT();
const TargetRegisterClass *RC;
if (RegVT == MVT::i32)
RC = &AArch64::GPR32RegClass;
else if (RegVT == MVT::i64)
RC = &AArch64::GPR64RegClass;
...
// Transform the arguments in physical registers into virtual ones.
Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
...
ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
Then LocInfo decides the conversion back to the value type. BCvt adds a BITCAST; SExt/ZExt/AExt need nothing here on AArch64 (the truncation to the IR type is inserted by generic code).
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9405-9486
3. Stack arguments
A stack location becomes a fixed frame object: its offset is relative to the stack pointer at the call, which frame lowering later turns into an offset from SP or FP (see the frame wiki).
} else {
int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
// Create load nodes to retrieve arguments from the stack.
FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
}
...
ArgValue = DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN, PtrInfo,
MemVT);
ExtType comes from LocInfo (SExt → SEXTLOAD ...). The last true marks the object immutable, which lets later passes treat the load as invariant.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9487-9552
4. byval
A byval argument is already in the caller's outgoing area, so the callee just creates a fixed object over it and passes its address:
if (Ins[i].Flags.isByVal()) {
...
unsigned FrameIdx =
MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
InVals.push_back(FrameIdxN);
continue;
}
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9384-9399
5. Varargs and stack size
If the function calls va_start, the unused argument registers are spilled (saveVarArgRegisters) and the offset of the first variadic stack argument is recorded; see Varargs, byval, sret. Finally the size of the incoming stack argument area is saved, because tail calls may reuse it:
unsigned StackArgSize = CCInfo.getStackSize();
...
FuncInfo->setBytesInStackArgArea(StackArgSize);
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9640-9660, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9702-9720
Result
llc -O2 -mtriple=aarch64-linux-gnu on double @mixed(i32 %i, double %d, i8 %c, float %f) (body: sext %c, add to %i, convert, add %d and fpext %f):
mixed: // @mixed
.cfi_startproc
add w8, w0, w1, sxtb
fcvt d1, s1
scvtf d2, w8
fadd d0, d2, d0
fadd d0, d0, d1
ret
%i is in w0, %d in d0, %c in w1 (the next free GPR, not w2), %f in s1. The sxtb shows that the i8 arrives with undefined upper bits and the callee extends it.
Minimal Pattern (Illustrative)
Illustrative, not LLVM source. For a target with only i32 arguments:
SDValue ToyTargetLowering::LowerFormalArguments(
SDValue Chain, CallingConv::ID CC, bool IsVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
MachineFunction &MF = DAG.getMachineFunction();
SmallVector<CCValAssign, 16> Locs;
CCState CCInfo(CC, IsVarArg, MF, Locs, *DAG.getContext());
CCInfo.AnalyzeFormalArguments(Ins, CC_Toy);
for (CCValAssign &VA : Locs) {
SDValue V;
if (VA.isRegLoc()) {
Register VReg = MF.addLiveIn(VA.getLocReg(), &Toy::GPRRegClass);
V = DAG.getCopyFromReg(Chain, DL, VReg, VA.getLocVT());
} else {
int FI = MF.getFrameInfo().CreateFixedObject(4, VA.getLocMemOffset(), true);
V = DAG.getLoad(VA.getLocVT(), DL, Chain, DAG.getFrameIndex(FI, MVT::i32),
MachinePointerInfo::getFixedStack(MF, FI));
}
if (VA.getLocInfo() == CCValAssign::SExt)
V = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), V,
DAG.getValueType(VA.getValVT()));
if (VA.getLocInfo() != CCValAssign::Full)
V = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), V);
InVals.push_back(V);
}
return Chain;
}
LowerCall
Relevant source files
The following files were used as context for generating this wiki page:
LowerCall turns one call site into a sequence of DAG nodes: open a call frame, put each argument in its register or stack slot, emit the target's call node with a register mask, close the call frame, and copy the results out of their return registers. It is the largest of the three call-lowering hooks because it handles both the caller's side of the arguments and the callee's results.
Purpose and Scope
The structure of AArch64's LowerCall and what each part produces. Tail calls are on Tail Calls and Sibling Calls; varargs and byval on Varargs, byval, sret. Line numbers for AArch64ISelLowering.cpp are from the committed file at a2171756.
Entry
Generic code fills a CallLoweringInfo (callee, arguments as Outs/OutVals, expected results as Ins, calling convention, IsTailCall, IsVarArg) in SelectionDAGBuilder::LowerCallTo, and TargetLowering::LowerCallTo calls the target hook:
virtual SDValue
LowerCall(CallLoweringInfo &/*CLI*/,
SmallVectorImpl<SDValue> &/*InVals*/) const {
llvm_unreachable("Not Implemented");
}
Sources: llvm/include/llvm/CodeGen/TargetLowering.h:5187-5191, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:9202, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:11333-11334
The Node Sequence
flowchart TD
A["analyze operands (CC_*) and results (RetCC_*)"] --> B{"tail call possible?"}
B --> C["CALLSEQ_START NumBytes"]
C --> D["argument values: extend / bitcast per LocInfo"]
D --> E["registers: RegsToPass list"]
D --> F["stack: store to SP + offset (MemOpChains)"]
F --> G["TokenFactor of stores"]
E --> H["CopyToReg chain, glued"]
G --> H
H --> I["AArch64ISD::CALL (callee, arg regs, regmask, glue)"]
I --> J["CALLSEQ_END NumBytes"]
J --> K["LowerCallResult: CopyFromReg per RetCC location"]
| Step | Lines | Notes |
|---|---|---|
| Analyze operands and results | 10471-10492 | analyzeCallOperands (a static helper at 9977) and AnalyzeCallResult |
| Tail-call decision | 10516-10532 | See Tail Calls |
| Stack size | 10535-10541 | CCInfo.getStackSize(), 0 for sibling calls |
CALLSEQ_START | 10648-10649 | Not emitted for sibling calls |
| Argument registers and stores | 10666-10941 | RegsToPass, MemOpChains |
| Call node and mask | 10999-11083 | CALL or TC_RETURN |
CALLSEQ_END | 11119-11122 | Records how many bytes the callee pops |
| Results | 11127-11129 | LowerCallResult (9875) |
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10442-10541, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9977, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9875
Analysis
// Analyze operands of the call, assigning locations to each operand.
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
...
analyzeCallOperands(*this, Subtarget, CLI, CCInfo);
CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
// Assign locations to each value returned by this call.
SmallVector<CCValAssign, 16> RVLocs;
CCState RetCCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
*DAG.getContext());
RetCCInfo.AnalyzeCallResult(Ins, RetCC);
Two separate CCState objects are used: one for arguments, one for results, because the same registers (x0...) can appear in both.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10471-10492
Call Frame Markers
CALLSEQ_START and CALLSEQ_END bracket the call. They become the ADJCALLSTACKDOWN / ADJCALLSTACKUP pseudo instructions, which frame lowering later removes or turns into SP adjustments (eliminateCallFramePseudoInstr, see the frame wiki). The byte count is the outgoing stack argument area:
// Get a count of how many bytes are to be pushed on the stack.
unsigned NumBytes = CCInfo.getStackSize();
...
Chain = DAG.getCALLSEQ_START(Chain, IsTailCall ? 0 : NumBytes, 0, DL);
...
uint64_t CalleePopBytes =
DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Chain = DAG.getCALLSEQ_END(Chain, NumBytes, CalleePopBytes, InGlue, DL);
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10535, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10649, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11119-11122
Arguments
For each CCValAssign, the argument value is first converted according to LocInfo (SExt → SIGN_EXTEND, BCvt → BITCAST, ...). Then:
- Register location: the pair (register, value) is added to
RegsToPass(line 10821). After all stores, the pairs become a chain ofCopyToRegnodes glued together, so nothing can be scheduled between the copies and the call. - Stack location: the value is stored at
SP + LocMemOffset; the store chains are collected inMemOpChainsand merged with oneTokenFactor(lines 10940-10941). For a tail call the store goes to a fixed object in the caller's own incoming area instead (line 10880).
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10666, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10821, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10880, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10940-10941
The Call Node and the Register Mask
The operands of AArch64ISD::CALL are: chain, callee, one register operand per argument register (so the registers are live into the call), the register mask, and the glue.
unsigned Opc = IsTailCall ? AArch64ISD::TC_RETURN : AArch64ISD::CALL;
std::vector<SDValue> Ops;
Ops.push_back(Chain);
Ops.push_back(Callee);
...
// Add a register mask operand representing the call-preserved registers.
const uint32_t *Mask;
const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
if (IsThisReturn) {
...
} else
Mask = TRI->getCallPreservedMask(MF, CallConv);
...
assert(Mask && "Missing call preserved mask for calling convention");
Ops.push_back(DAG.getRegisterMask(Mask));
The mask is what tells the register allocator which registers the call clobbers: every register not in the mask is dead after the call. It comes from the CalleeSavedRegs record through getCallPreservedMask (AArch64RegisterInfo.cpp, line 270-271). The regalloc wiki's registers page explains how the allocator uses it.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10999-11003, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11063-11083, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:270-271
Results
After CALLSEQ_END, LowerCallResult walks RVLocs and emits a CopyFromReg for each return register, glued to the call so the copies stay right after it, then undoes any extension:
// Handle result values, copying them out of physregs into vregs that we
// return.
SDValue Result = LowerCallResult(
Chain, InGlue, CallConv, IsVarArg, RVLocs, DL, DAG, InVals, IsThisReturn,
IsThisReturn ? OutVals[0] : SDValue(), RequiresSMChange);
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11125-11129
What It Looks Like After Selection
llc -O2 -mtriple=aarch64-linux-gnu -stop-after=finalize-isel for a call with ten i64 arguments (callee(x, 1, 2, ..., 9)), first lines of the body:
%0:gpr64 = COPY $x0
ADJCALLSTACKDOWN 16, 0, implicit-def dead $sp, implicit $sp
%1:gpr64sp = COPY $sp
%2:gpr32 = MOVi32imm 9
%3:gpr64 = SUBREG_TO_REG killed %2, %subreg.sub_32
STRXui killed %3, %1, 1 :: (store (s64) into stack + 8)
%4:gpr32 = MOVi32imm 8
%5:gpr64 = SUBREG_TO_REG killed %4, %subreg.sub_32
STRXui killed %5, %1, 0 :: (store (s64) into stack)
%6:gpr32 = MOVi32imm 1
...
$x0 = COPY %0
$x1 = COPY %7
$x2 = COPY %9
...
ADJCALLSTACKDOWN 16 is the CALLSEQ_START with 16 bytes for the two stack arguments; the two STRXui stores are the MemOpChains; the $xN = COPY lines are RegsToPass. The full function, including the BL with its register mask, is on the walkthroughs page.
LowerReturn and CanLowerReturn
Relevant source files
The following files were used as context for generating this wiki page:
LowerReturn is called for every ret instruction. It copies each return value into the register the RetCC_* rules choose, and ends the block with the target's return node. CanLowerReturn is asked first: if the return values do not fit in registers, generic code rewrites the function to return through a hidden pointer argument (sret demotion), and LowerReturn then only sees a void return.
Purpose and Scope
Both hooks as implemented by AArch64, and the minimal version for a new target. Line numbers for AArch64ISelLowering.cpp are from the committed file at a2171756.
CanLowerReturn
bool AArch64TargetLowering::CanLowerReturn(
CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context,
const Type *RetTy) const {
CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
SmallVector<CCValAssign, 16> RVLocs;
CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
return CCInfo.CheckReturn(Outs, RetCC);
}
CheckReturn runs the return rules and returns false as soon as one value cannot be placed. RetCC_AArch64_AAPCS has no stack rules, so anything beyond eight integer or eight FP/vector registers fails, and the function is demoted. The default TargetLowering::CanLowerReturn returns true, which is only safe if the return rules can place every value the target can return:
virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
MachineFunction &/*MF*/, bool /*isVarArg*/,
const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
LLVMContext &/*Context*/, const Type *RetTy) const
{
// Return true by default to get preexisting behavior.
return true;
}
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11172-11180, llvm/lib/CodeGen/CallingConvLower.cpp:99-109, llvm/lib/Target/AArch64/AArch64CallingConvention.td:128-162, llvm/include/llvm/CodeGen/TargetLowering.h:5199-5206
LowerReturn
flowchart LR
A["AnalyzeReturn(Outs, RetCC)"] --> B["for each RVLoc: extend/bitcast, CopyToReg (glued)"]
B --> C["RetOps: chain, one register operand per return reg"]
C --> D["sret pointer in X0 (Win64), CSRs via copy"]
D --> E["AArch64ISD::RET_GLUE"]
AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
bool isVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals,
const SDLoc &DL, SelectionDAG &DAG) const {
...
CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
SmallVector<CCValAssign, 16> RVLocs;
CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
CCInfo.AnalyzeReturn(Outs, RetCC);
// Copy the result values into the output registers.
SDValue Glue;
...
Each copy is glued to the previous one so the copies and the return stay together. Every return register is also added to RetOps as a register operand: that makes the register live-out (used by the return instruction), so the copies are not deleted as dead. The function ends with:
RetOps[0] = Chain; // Update chain.
// Add the glue if we have it.
if (Glue.getNode())
RetOps.push_back(Glue);
...
return DAG.getNode(AArch64ISD::RET_GLUE, DL, MVT::Other, RetOps);
RET_GLUE is matched by the pattern on the RET_ReallyLR pseudo, def RET_ReallyLR : Pseudo<(outs), (ins), [(AArch64retglue)]>, seen in MIR as RET_ReallyLR implicit $w0; it becomes ret before emission.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11182-11200, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11292-11326, llvm/lib/Target/AArch64/AArch64InstrInfo.td:895, llvm/lib/Target/AArch64/AArch64InstrInfo.td:3758
In MIR
llc -O2 -mtriple=aarch64-linux-gnu -stop-after=finalize-isel on i32 @add(i32 %a, i32 %b):
%1:gpr32 = COPY $w1
%0:gpr32 = COPY $w0
%2:gpr32 = ADDWrr %0, %1
$w0 = COPY %2
RET_ReallyLR implicit $w0
$w0 = COPY %2 is the CopyToReg from LowerReturn; implicit $w0 on the return is the register operand added to RetOps.
Minimal Version (Illustrative)
Illustrative, not LLVM source.
SDValue ToyTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CC,
bool IsVarArg, const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
SelectionDAG &DAG) const {
SmallVector<CCValAssign, 4> RVLocs;
CCState CCInfo(CC, IsVarArg, DAG.getMachineFunction(), RVLocs,
*DAG.getContext());
CCInfo.AnalyzeReturn(Outs, RetCC_Toy);
SDValue Glue;
SmallVector<SDValue, 4> RetOps(1, Chain);
for (unsigned i = 0; i != RVLocs.size(); ++i) {
CCValAssign &VA = RVLocs[i];
SDValue V = OutVals[i];
if (VA.getLocInfo() == CCValAssign::SExt)
V = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), V);
else if (VA.getLocInfo() == CCValAssign::ZExt)
V = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), V);
else if (VA.getLocInfo() == CCValAssign::AExt)
V = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), V);
Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), V, Glue);
Glue = Chain.getValue(1);
RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
}
RetOps[0] = Chain;
if (Glue.getNode())
RetOps.push_back(Glue);
return DAG.getNode(ToyISD::RET, DL, MVT::Other, RetOps);
}
bool ToyTargetLowering::CanLowerReturn(CallingConv::ID CC, MachineFunction &MF,
bool IsVarArg, const SmallVectorImpl<ISD::OutputArg> &Outs,
LLVMContext &Ctx, const Type *RetTy) const {
SmallVector<CCValAssign, 4> RVLocs;
CCState CCInfo(CC, IsVarArg, MF, RVLocs, Ctx);
return CCInfo.CheckReturn(Outs, RetCC_Toy);
}
With CanLowerReturn in place, an i128 return on a 32-bit Toy (four i32 parts, only r0/r1 available) is demoted to a hidden sret pointer automatically.
Varargs, byval, sret and swifterror
Relevant source files
The following files were used as context for generating this wiki page:
Most arguments are plain values in registers or stack slots. A few need extra work from the target: variadic functions must make the unnamed register arguments reachable through va_list; byval aggregates are copies placed in the argument area; sret pointers have a dedicated register on AArch64; Swift's special arguments have dedicated callee-saved registers. Each is a TableGen rule plus some C++ in the lowering hooks.
Purpose and Scope
How AArch64 handles each of these, with real llc -O2 -mtriple=aarch64-linux-gnu output. Line numbers for AArch64ISelLowering.cpp are from the committed file at a2171756.
Summary
| Kind | TableGen rule (AAPCS) | C++ work |
|---|---|---|
| Varargs (callee) | Same rules as fixed arguments | saveVarArgRegisters, LowerVASTART fills va_list |
| Varargs (caller) | Same rules on Linux; Darwin and Windows use separate *_VarArg conventions | Chosen in CCAssignFnForCall |
byval | CCIfByVal<CCPassByVal<8, 8>> | Caller copies with memcpy; callee uses a fixed object |
sret | CCIfSRet<CCIfType<[i64], CCAssignToReg<[X8]>>> | None on Linux; Windows returns the pointer in X0 |
swifterror | CCIfSwiftError<CCIfType<[i64], CCAssignToReg<[X21]>>> | Special register handling in frame lowering |
swiftself | CCIfSwiftSelf<... [X20]> | — |
nest | CCIfNest<CCAssignToReg<[X15]>> | — |
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:30-79, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9197-9257
Varargs in the Callee
On AAPCS64 a variadic function receives its arguments exactly like a normal one: named and unnamed arguments share x0–x7, q0–q7 and the stack. So if the function calls va_start, LowerFormalArguments must store the argument registers that the named arguments did not use, so that va_arg can find them later:
// varargs
if (isVarArg) {
if (DAG.getMachineFunction().getFrameInfo().hasVAStart()) {
if (!Subtarget->isTargetDarwin() || IsWin64) {
// The AAPCS variadic function ABI is identical to the non-variadic
// one. As a result there may be more arguments in registers and we
// should save them for future reference.
...
saveVarArgRegisters(CCInfo, DAG, DL, Chain);
}
// This will point to the next argument passed via stack.
unsigned VarArgsOffset = CCInfo.getStackSize();
...
FuncInfo->setVarArgsStackIndex(
MFI.CreateFixedObject(4, VarArgsOffset, true));
saveVarArgRegisters asks CCState for the first unallocated GPR and makes a stack object large enough for the rest:
unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
int GPRIdx = 0;
if (GPRSaveSize != 0) {
if (IsWin64) {
...
} else
GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
It does the same for the FP/SIMD registers.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9640-9660, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9777-9809
va_start
va_start is Custom lowered. On AAPCS it fills the five fields of the va_list structure from the frame indices recorded above:
// void *__stack at offset 0
...
// void *__gr_top at offset 8 (4 on ILP32)
...
// void *__vr_top at offset 16 (8 on ILP32)
...
// int __gr_offs at offset 24 (12 on ILP32)
...
DAG.getStore(Chain, DL, DAG.getSignedConstant(-GPRSize, DL, MVT::i32),
...
// int __vr_offs at offset 28 (16 on ILP32)
LowerVASTART picks the Windows, Darwin (a single pointer) or AAPCS version.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:13594-13684
Result
define i32 @sum(i32 %n, ...) with one va_arg ptr %ap, i32:
sum: // @sum
.cfi_startproc
sub sp, sp, #224
.cfi_def_cfa_offset 224
mov x8, sp
mov x9, #-56 // =0xffffffffffffffc8
add x10, sp, #136
movk x9, #65408, lsl #32
add x8, x8, #128
ldr w11, [sp, #224]
stp x8, x9, [sp, #208]
add x9, sp, #224
add x8, x10, #56
orr x9, x9, #0x8
stp x1, x2, [sp, #136]
add w0, w0, w11
stp x3, x4, [sp, #152]
stp x5, x6, [sp, #168]
str x7, [sp, #184]
stp q0, q1, [sp]
stp q2, q3, [sp, #32]
stp q4, q5, [sp, #64]
stp q6, q7, [sp, #96]
stp x9, x8, [sp, #192]
add sp, sp, #224
ret
%n used w0, so x1–x7 (56 bytes, hence #-56 for __gr_offs) are saved at [sp, #136] and q0–q7 (128 bytes) at [sp]. The va_list itself is at [sp, #192]. (The ldr w11, [sp, #224] reads the va_arg value; the optimizer folded the va_arg through the known va_list contents.)
Varargs in the Caller
On Linux, a call to a variadic function uses the normal convention, so printf("%d\n", x, 1.0) puts the double in d0:
callprintf: // @callprintf
.cfi_startproc
str x30, [sp, #-16]! // 8-byte Folded Spill
.cfi_def_cfa_offset 16
.cfi_offset w30, -16
fmov d0, #1.00000000
mov w1, w0
adrp x0, .Lfmt
add x0, x0, :lo12:.Lfmt
bl printf
ldr x30, [sp], #16 // 8-byte Folded Reload
ret
On Darwin, CCAssignFnForCall returns CC_AArch64_DarwinPCS_VarArg, which puts every unnamed argument on the stack; that is why the hook takes an IsVarArg parameter.
byval
A byval argument is a copy of an aggregate that the callee owns. CCPassByVal<8, 8> makes CCState::HandleByVal allocate a stack slot of the aggregate's size (at least 8, aligned to at least 8). The caller copies the aggregate into that slot with a memcpy node in LowerCall; the callee just uses the slot's address (see LowerFormalArguments). A callee that ignores the argument needs no code at all:
take_byval: // @take_byval
.cfi_startproc
ret
Sources: llvm/lib/CodeGen/CallingConvLower.cpp:45-59, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9384-9399
sret
In AAPCS64 the address of an indirect result goes in x8, not x0. The rule comes before the general i64 rule so it wins:
CCIfSRet<CCIfType<[i64], CCAssignToReg<[X8]>>>,
A caller of void @make(ptr sret(%struct.Big)), with the 32-byte struct on its own stack:
use_sret: // @use_sret
.cfi_startproc
sub sp, sp, #48
str x30, [sp, #32] // 8-byte Spill
.cfi_def_cfa_offset 48
.cfi_offset w30, -16
mov x8, sp
bl make
ldr x0, [sp, #16]
ldr x30, [sp, #32] // 8-byte Reload
add sp, sp, #48
ret
mov x8, sp passes the struct address; after the call the third field is loaded from [sp, #16]. On Windows the inreg variant puts it in x0 or x1 (rule at line 62-63), and LowerFormalArguments saves the pointer so LowerReturn can return it in x0.
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:48-65, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9680-9700
swifterror and other Swift registers
Swift passes an error value in a callee-saved register so that it survives calls; the callee may write it, and the caller reads it back after the call. The rule appears in both the argument list and RetCC_AArch64_AAPCS, because the value also comes back:
// Pass SwiftSelf in a callee saved register.
CCIfSwiftSelf<CCIfType<[i64], CCAssignToReg<[X20]>>>,
// A SwiftError is passed in X21.
CCIfSwiftError<CCIfType<[i64], CCAssignToReg<[X21]>>>,
// Pass SwiftAsync in an otherwise callee saved register so that it will be
// preserved for normal function calls.
CCIfSwiftAsync<CCIfType<[i64], CCAssignToReg<[X22]>>>,
Because X21 is normally callee-saved, functions with a swifterror argument use a different callee-saved list without it (CSR_AArch64_AAPCS_SwiftError at line 704), so the prologue does not save and the epilogue does not restore it.
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:71-79, llvm/lib/Target/AArch64/AArch64CallingConvention.td:135, llvm/lib/Target/AArch64/AArch64CallingConvention.td:704
For a New Target
Start with no varargs support (VASTART as Custom that reports an error, or omit it), no byval beyond CCPassByVal, and the default sret handling (the pointer is just the first argument). Add varargs once ordinary calls work: the key pieces are saving the unused argument registers in LowerFormalArguments and a LowerVASTART that matches your va_list layout (often just a pointer, with VAARG set to Expand).
Tail Calls and Sibling Calls
Relevant source files
The following files were used as context for generating this wiki page:
A tail call replaces call f; ret with a jump to f, so f returns directly to our caller. It saves a stack frame and an instruction, and for musttail it is required for correctness. LLVM distinguishes a sibling call (a tail call that needs no change to the calling convention, because the callee's arguments fit in the space the caller already has) from a guaranteed tail call (tailcc, swifttailcc, or fastcc with -tailcallopt), where the callee pops its own arguments.
Purpose and Scope
How AArch64 decides whether a call marked tail can really be a tail call, and what LowerCall does differently for it. Line numbers for AArch64ISelLowering.cpp are from the committed file at a2171756.
The Decision in LowerCall
if (IsTailCall) {
// Check if it's really possible to do a tail call.
IsTailCall = isEligibleForTailCallOptimization(CLI);
// A sibling call is one where we're under the usual C ABI and not planning
// to change that but can still do a tail call:
if (!ZAMarkerNode && !TailCallOpt && IsTailCall &&
CallConv != CallingConv::Tail && CallConv != CallingConv::SwiftTail)
IsSibCall = true;
...
}
if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
report_fatal_error("failed to perform tail call elimination on a call "
"site marked musttail");
The IR tail marker is only a hint; the target decides. musttail turns a "no" into a fatal error.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10516-10532
isEligibleForTailCallOptimization
The checks, in order (function starts at line 10055):
| Check | Lines | Why |
|---|---|---|
Callee convention can be tail called (mayTailCallThisCC) | 10058-10059 | Some conventions never allow it |
| SME streaming / ZA state changes | 10071-10079 | State must be restored after the call |
| Windows convention on non-Windows OS | 10091-10096 | X18 must be saved and restored |
Caller has a byval argument | 10098-10105 | The callee's arguments would overwrite it |
Windows inreg sret mismatch | 10107-10121 | x0 must be returned |
| Guaranteed TCO convention | 10126 | If so, eligible (the remaining checks are for sibcalls) |
| Weak external callee | 10129-10141 | Linker may replace the call with a NOP |
Return values in the same places (resultsCompatible) | 10154-10158 | Callee's return goes straight to our caller |
Callee preserves every register the caller must (regmaskSubsetEqual) | 10159-10169 | Otherwise our caller sees clobbered CSRs |
| Variadic stack arguments | 10181-10191 | Conservatively rejected |
| Stack arguments fit our incoming area | 10209-10212 | CCInfo.getStackSize() > FuncInfo->getBytesInStackArgArea() → no |
| Arguments in callee-saved registers match | 10215-10216 | parametersInCSRMatch |
The stack-size check is why LowerFormalArguments records setBytesInStackArgArea (see LowerFormalArguments).
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10055-10218, llvm/lib/CodeGen/CallingConvLower.cpp:264
What Changes in LowerCall
| Normal call | Sibling call | Guaranteed tail call | |
|---|---|---|---|
NumBytes | Stack size of arguments | 0 | Aligned to 16; FPDiff = reusable bytes − needed |
CALLSEQ_START | Yes | No | Yes, with 0 |
| Stack argument stores | SP + offset | Into the caller's incoming area | Into fixed objects offset by FPDiff |
| Node | AArch64ISD::CALL | AArch64ISD::TC_RETURN | AArch64ISD::TC_RETURN |
| After the node | CALLSEQ_END, result copies | Nothing: it ends the block | Nothing |
// Get a count of how many bytes are to be pushed on the stack.
unsigned NumBytes = CCInfo.getStackSize();
if (IsSibCall) {
// Since we're not changing the ABI to make this a tail call, the memory
// operands are already available in the caller's incoming argument space.
NumBytes = 0;
}
...
// If we're doing a tall call, use a TC_RETURN here rather than an
// actual call instruction.
if (IsTailCall) {
MF.getFrameInfo().setHasTailCall();
SDValue Ret = DAG.getNode(Opc, DL, MVT::Other, Ops);
...
return Ret;
}
setHasTailCall tells frame lowering that the epilogue must be placed before the TC_RETURN jump (see the frame wiki).
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10534-10560, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11091-11105
Example
declare i64 @g(i64)
define i64 @sib(i64 %x) {
%r = tail call i64 @g(i64 %x)
ret i64 %r
}
define i64 @notail(i64 %x) {
%r = call i64 @g(i64 %x)
%s = add i64 %r, %x
ret i64 %s
}
After instruction selection (-stop-after=finalize-isel), sib has no call frame and no return, just the tail-call pseudo carrying the register mask:
%0:gpr64 = COPY $x0
$x0 = COPY %0
TCRETURNdi @g, 0, csr_aarch64_aapcs, implicit $sp, implicit $x0
Final assembly (llc -O2 -mtriple=aarch64-linux-gnu):
sib: // @sib
.cfi_startproc
b g
.Lfunc_end0:
.cfi_endproc
notail: // @notail
.cfi_startproc
stp x30, x19, [sp, #-16]! // 16-byte Folded Spill
.cfi_def_cfa_offset 16
.cfi_offset w19, -8
.cfi_offset w30, -16
mov x19, x0
bl g
add x0, x0, x19
ldp x30, x19, [sp], #16 // 16-byte Folded Reload
ret
notail cannot be a tail call because work remains after the call, so it needs a frame, a saved link register and a callee-saved register for %x.
For a New Target
Tail calls are optional. Return false from your eligibility check (or ignore CLI.IsTailCall, setting it to false) until normal calls work; only musttail IR then fails. When adding sibling calls, start with the strictest version: same calling convention, no stack arguments, no byval, results in the same registers. Add a TCRETURN pseudo that the epilogue code recognizes and that expands to a branch after frame lowering.
Custom Backend Guide and Checklist
Relevant source files
The following files were used as context for generating this wiki page:
This page puts the pieces together for a made-up "Toy" target: a 32-bit machine with arguments in r0–r3, then the stack; results in r0/r1; r8–r11 and lr callee-saved. Every code block is illustrative, not LLVM source; check exact signatures against TargetLowering.h at your LLVM version.
Purpose and Scope
The files to write, a complete LowerCall, and a checklist with tests. LowerFormalArguments and LowerReturn for Toy are on LowerFormalArguments and LowerReturn. Where this fits in a whole backend is on the bring-up wiki.
Files
| File | Contents |
|---|---|
ToyCallingConv.td | CC_Toy, RetCC_Toy, CSR_Toy |
Toy.td | include "ToyCallingConv.td" after the registers |
CMakeLists.txt | tablegen(LLVM ToyGenCallingConv.inc -gen-callingconv) |
ToyISelLowering.cpp | #include "ToyGenCallingConv.inc", the three hooks, CanLowerReturn |
ToyInstrInfo.td | ToyISD::CALL/RET nodes, CALL, RET, ADJCALLSTACKDOWN/UP pseudos |
ToyRegisterInfo.cpp | getCalleeSavedRegs → CSR_Toy_SaveList, getCallPreservedMask → CSR_Toy_RegMask |
ToyFrameLowering.cpp | eliminateCallFramePseudoInstr |
TableGen
def CC_Toy : CallingConv<[
CCIfByVal<CCPassByVal<4, 4>>,
CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
CCIfType<[i32], CCAssignToReg<[R0, R1, R2, R3]>>,
CCIfType<[i32], CCAssignToStack<4, 4>>
]>;
def RetCC_Toy : CallingConv<[
CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
CCIfType<[i32], CCAssignToReg<[R0, R1]>>
]>;
def CSR_Toy : CalleeSavedRegs<(add R8, R9, R10, R11, LR)>;
// Call-frame pseudos: become CALLSEQ_START / CALLSEQ_END
let Defs = [SP], Uses = [SP] in {
def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2),
[(callseq_start timm:$amt1, timm:$amt2)]>;
def ADJCALLSTACKUP : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2),
[(callseq_end timm:$amt1, timm:$amt2)]>;
}
The call-frame pseudos must also be passed to the TargetInstrInfo constructor (ToyGenInstrInfo(STI, Toy::ADJCALLSTACKDOWN, Toy::ADJCALLSTACKUP)), so that generic code knows their opcodes.
LowerCall
SDValue ToyTargetLowering::LowerCall(CallLoweringInfo &CLI,
SmallVectorImpl<SDValue> &InVals) const {
SelectionDAG &DAG = CLI.DAG;
SDLoc DL = CLI.DL;
MachineFunction &MF = DAG.getMachineFunction();
CLI.IsTailCall = false; // no tail calls yet
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CLI.CallConv, CLI.IsVarArg, MF, ArgLocs, *DAG.getContext());
CCInfo.AnalyzeCallOperands(CLI.Outs, CC_Toy);
unsigned NumBytes = CCInfo.getStackSize();
SDValue Chain = DAG.getCALLSEQ_START(CLI.Chain, NumBytes, 0, DL);
SmallVector<std::pair<Register, SDValue>, 4> RegsToPass;
SmallVector<SDValue, 8> MemOps;
SDValue SP = DAG.getRegister(Toy::SP, MVT::i32);
for (unsigned i = 0; i != ArgLocs.size(); ++i) {
CCValAssign &VA = ArgLocs[i];
SDValue Arg = CLI.OutVals[i];
switch (VA.getLocInfo()) {
case CCValAssign::Full: break;
case CCValAssign::SExt: Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); break;
case CCValAssign::ZExt: Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); break;
case CCValAssign::AExt: Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); break;
default: llvm_unreachable("unexpected LocInfo");
}
if (VA.isRegLoc()) {
RegsToPass.push_back({VA.getLocReg(), Arg});
} else {
SDValue Addr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP,
DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
MemOps.push_back(DAG.getStore(Chain, DL, Arg, Addr, MachinePointerInfo()));
}
}
if (!MemOps.empty())
Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
SDValue Glue;
for (auto &[Reg, Val] : RegsToPass) {
Chain = DAG.getCopyToReg(Chain, DL, Reg, Val, Glue);
Glue = Chain.getValue(1);
}
SDValue Callee = CLI.Callee;
if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, MVT::i32);
else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee))
Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
SmallVector<SDValue, 8> Ops = {Chain, Callee};
for (auto &[Reg, Val] : RegsToPass)
Ops.push_back(DAG.getRegister(Reg, Val.getValueType()));
const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
Ops.push_back(DAG.getRegisterMask(TRI->getCallPreservedMask(MF, CLI.CallConv)));
if (Glue.getNode())
Ops.push_back(Glue);
Chain = DAG.getNode(ToyISD::CALL, DL, {MVT::Other, MVT::Glue}, Ops);
Glue = Chain.getValue(1);
Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
Glue = Chain.getValue(1);
SmallVector<CCValAssign, 4> RVLocs;
CCState RetInfo(CLI.CallConv, CLI.IsVarArg, MF, RVLocs, *DAG.getContext());
RetInfo.AnalyzeCallResult(CLI.Ins, RetCC_Toy);
for (CCValAssign &VA : RVLocs) {
SDValue V = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
Chain = V.getValue(1);
Glue = V.getValue(2);
if (VA.getLocVT() != VA.getValVT())
V = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), V);
InVals.push_back(V);
}
return Chain;
}
This follows the same order as AArch64's version (see LowerCall): analyze, CALLSEQ_START, convert, store or queue, glued copies, call node with mask, CALLSEQ_END, results.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10442-10492, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11063-11129, llvm/include/llvm/CodeGen/CallingConvLower.h:284-304
Checklist
- ☐
CC_ToyandRetCC_Toycover every legal type (otherwiseunable to allocate function argument #N) - ☐
CSR_Toymatches the ABI document;getCalleeSavedRegsandgetCallPreservedMaskreturn it - ☐
LowerFormalArguments: oneInValsentry perInsentry, registers viaaddLiveIn, stack viaCreateFixedObject - ☐
LowerReturn: glued copies, return registers as operands of the return node - ☐
CanLowerReturnusesCheckReturn, so large returns are demoted tosret - ☐
LowerCall: register mask on every call;CALLSEQ_START/ENDwith the right byte count - ☐
ADJCALLSTACKDOWN/UPpseudos registered withTargetInstrInfo, removed byeliminateCallFramePseudoInstr - ☐ Extensions: arguments marked
signext/zeroextare extended by the caller (LocInfoSExt/ZExt) - ☐ Varargs and tail calls disabled until the basics pass
| Test | Expect |
|---|---|
i32 f(i32 a, i32 b) { return a + b; } | a in r0, b in r1, result in r0 |
Six i32 arguments | Fifth and sixth loaded from the incoming stack area |
| Call with six arguments | Two stores to [sp], [sp+4]; ADJCALLSTACKDOWN 8 in MIR |
i8 signext argument | Caller sign-extends; callee sees AssertSext |
| Value live across a call | Allocator uses r8–r11; prologue saves it |
i64 return on 32-bit Toy | Split over r0/r1 |
i128 return | Demoted to a hidden sret pointer |
Run each with llc -march=toy -verify-machineinstrs and compare with -stop-after=finalize-isel output, as in the AArch64 walkthroughs.
AArch64 Walkthroughs
Relevant source files
The following files were used as context for generating this wiki page:
Four small functions compiled with the real llc (LLVM 24.0.0git release build at a2171756), each traced back to the rules and hooks on the earlier pages. All commands use -O2 -mtriple=aarch64-linux-gnu; MIR is from -stop-after=finalize-isel.
Purpose and Scope
Concrete evidence for each rule: incoming arguments, an outgoing call with stack arguments, mixed integer and floating-point arguments, and a tail call. Varargs, sret and byval output is on Varargs, byval, sret.
1. Ten Incoming Arguments
define i64 @many(i64 %a0, i64 %a1, i64 %a2, i64 %a3, i64 %a4, i64 %a5, i64 %a6, i64 %a7, i64 %a8, i64 %a9) {
%s = add i64 %a0, %a9
%t = add i64 %s, %a8
ret i64 %t
}
many: // @many
.cfi_startproc
ldp x9, x8, [sp]
add x8, x0, x8
add x0, x8, x9
ret
| Argument | Rule | Location |
|---|---|---|
%a0–%a7 | CCIfType<[i64], CCAssignToReg<[X0, ..., X7]>> | x0–x7 |
%a8 | CCIfType<[i64, ...], CCAssignToStack<8, 8>> | [sp] (offset 0) |
%a9 | same | [sp, #8] |
LowerFormalArguments made two fixed frame objects at offsets 0 and 8 and loaded them; the load/store optimizer later merged the two loads into one ldp. The function has no frame of its own, so the fixed objects are addressed directly from sp at entry.
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:106, llvm/lib/Target/AArch64/AArch64CallingConvention.td:119-120, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9487-9552
2. An Outgoing Call with Stack Arguments
declare i64 @callee(i64, i64, i64, i64, i64, i64, i64, i64, i64, i64)
define i64 @caller(i64 %x) {
%r = call i64 @callee(i64 %x, i64 1, i64 2, i64 3, i64 4, i64 5, i64 6, i64 7, i64 8, i64 9)
%s = add i64 %r, 1
ret i64 %s
}
MIR after selection (abridged in the middle):
%0:gpr64 = COPY $x0
ADJCALLSTACKDOWN 16, 0, implicit-def dead $sp, implicit $sp
%1:gpr64sp = COPY $sp
%2:gpr32 = MOVi32imm 9
%3:gpr64 = SUBREG_TO_REG killed %2, %subreg.sub_32
STRXui killed %3, %1, 1 :: (store (s64) into stack + 8)
%4:gpr32 = MOVi32imm 8
%5:gpr64 = SUBREG_TO_REG killed %4, %subreg.sub_32
STRXui killed %5, %1, 0 :: (store (s64) into stack)
...
$x0 = COPY %0
$x1 = COPY %7
...
$x7 = COPY %19
BL @callee, csr_aarch64_aapcs, implicit-def dead $lr, implicit $sp, implicit $x0, implicit $x1, implicit $x2, implicit $x3, implicit $x4, implicit $x5, implicit $x6, implicit $x7, implicit-def $sp, implicit-def $x0
ADJCALLSTACKUP 16, 0, implicit-def dead $sp, implicit $sp
%20:gpr64sp = COPY $x0
%21:gpr64sp = ADDXri %20, 1, 0
$x0 = COPY %21
RET_ReallyLR implicit $x0
| MIR | Comes from |
|---|---|
ADJCALLSTACKDOWN 16 / ADJCALLSTACKUP 16 | CALLSEQ_START / CALLSEQ_END with CCInfo.getStackSize() = 16 |
Two STRXui to stack and stack + 8 | Stack locations for arguments 9 and 10, MemOpChains |
$x0 = COPY ... ... $x7 = COPY ... | RegsToPass → glued CopyToReg |
csr_aarch64_aapcs on BL | Register mask from getCallPreservedMask |
implicit $x0 ... implicit $x7 | Argument register operands on the call node |
implicit-def $x0 | The result register, from RetCC_AArch64_AAPCS |
%20 = COPY $x0 | LowerCallResult |
Final assembly:
caller: // @caller
.cfi_startproc
sub sp, sp, #32
.cfi_def_cfa_offset 32
.cfi_offset w30, -16
mov w8, #9 // =0x9
mov w9, #8 // =0x8
mov w1, #1 // =0x1
mov w2, #2 // =0x2
mov w3, #3 // =0x3
mov w4, #4 // =0x4
mov w5, #5 // =0x5
mov w6, #6 // =0x6
mov w7, #7 // =0x7
stp x8, x30, [sp, #8] // 8-byte Folded Spill
str x9, [sp]
bl callee
ldr x30, [sp, #16] // 8-byte Reload
add x0, x0, #1
add sp, sp, #32
ret
The 16-byte outgoing area sits at the bottom of the 32-byte frame (AArch64 reserves the call frame, so ADJCALLSTACKDOWN/UP became no SP change). Frame lowering put the saved x30 at [sp, #16], right after argument 10 at [sp, #8], and the store of argument 10 merged with the x30 save into one stp. x0 (%x) needed no copy because it was already in place.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10535-10541, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11063-11129
3. Mixed Integer and Floating-Point Arguments
define double @mixed(i32 %i, double %d, i8 %c, float %f) {
%e = sext i8 %c to i32
%x = add i32 %i, %e
%y = sitofp i32 %x to double
%fe = fpext float %f to double
%z = fadd double %y, %d
%w = fadd double %z, %fe
ret double %w
}
mixed: // @mixed
.cfi_startproc
add w8, w0, w1, sxtb
fcvt d1, s1
scvtf d2, w8
fadd d0, d2, d0
fadd d0, d0, d1
ret
| Argument | Rule | Location |
|---|---|---|
i32 %i | CCIfType<[i32], CCAssignToReg<[W0, ...]>> | w0 |
double %d | CCIfType<[f64], CCAssignToReg<[D0, ...]>> | d0 |
i8 %c | CCPromoteToType<i32>, then the i32 rule | w1 |
float %f | CCIfType<[f32], CCAssignToReg<[S0, ...]>> | s1 |
return double | RetCC_AArch64_AAPCS f64 rule | d0 |
Integer and FP registers are allocated independently, so %c takes w1 even though %d came between. S1 and D0 are different registers from CCState's point of view (only aliases are marked used), so %f gets s1.
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:97-110, llvm/lib/Target/AArch64/AArch64CallingConvention.td:150
4. Sibling Call
%0:gpr64 = COPY $x0
$x0 = COPY %0
TCRETURNdi @g, 0, csr_aarch64_aapcs, implicit $sp, implicit $x0
sib: // @sib
.cfi_startproc
b g
No ADJCALLSTACKDOWN, no result copy, no RET_ReallyLR: LowerCall returned the TC_RETURN node directly, which ends the block. See Tail Calls for the eligibility checks, and the frame wiki's walkthroughs for how the epilogue is placed before such jumps.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10516-10541, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11091-11105
Reproducing
llc -O2 -mtriple=aarch64-linux-gnu args.ll -o -
llc -O2 -mtriple=aarch64-linux-gnu -stop-after=finalize-isel call.ll -o -
The SelectionDAG wiki's AArch64 walkthroughs show the same kind of trace for instruction selection, and the MC wiki's streamers page shows how the final bl and b become encoded instructions with relocations.
Tooling and Glossary
Relevant source files
The following files were used as context for generating this wiki page:
Commands for inspecting calling-convention decisions, common errors, and the terms used in this wiki. The bring-up tooling page covers the general llc options.
Purpose and Scope
All output in this wiki comes from an LLVM 24.0.0git release llc (no assertions) at commit a2171756.
Commands
| Command | Shows |
|---|---|
llc -O2 -mtriple=aarch64-linux-gnu f.ll -o - | Final placement of arguments and results |
llc ... -stop-after=finalize-isel | MIR after selection: live-in copies, ADJCALLSTACKDOWN/UP, argument copies, the call's register mask and implicit operands |
llc ... -stop-after=prolog-epilog | How stack arguments and the outgoing area ended up in the frame |
llc ... -O0 | Same lowering without later optimizations hiding the copies |
llvm-tblgen -gen-callingconv -I llvm/include -I lib/Target/T T.td | The generated CC_* C++ functions |
llc ... -debug-only=isel | DAGs before and after each stage (assertions build only) |
Common Errors
| Message | Source | Cause |
|---|---|---|
unable to allocate function argument #N | CCState::AnalyzeFormalArguments | No rule in CC_* matched the argument's type |
unable to allocate function return #N | CCState::AnalyzeReturn | No rule in RetCC_*, and CanLowerReturn did not demote it |
Call operand #N has unhandled type (debug) then unreachable | CCState::AnalyzeCallOperands | No rule for an outgoing argument type |
failed to perform tail call elimination on a call site marked musttail | AArch64 LowerCall | musttail call failed the eligibility checks |
Not Implemented | TargetLowering defaults | A call-lowering hook is missing |
Sources: llvm/lib/CodeGen/CallingConvLower.cpp:85-141, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10530-10532
Glossary
| Term | Meaning |
|---|---|
| Calling convention | Rules for where arguments and results live and which registers survive a call |
| AAPCS64 | The Arm 64-bit Procedure Call Standard, implemented by CC_AArch64_AAPCS |
CallingConv record | TableGen list of actions; Entry = 1 makes a callable C++ function |
CCAssignFn | Signature of a generated (or hand-written) assignment function |
CCState | Tracks allocated registers and stack size during analysis |
CCValAssign | One result: value number, register or stack offset, LocInfo |
LocInfo | How the value was converted for its location (Full, SExt, ZExt, AExt, BCvt, Indirect, ...) |
ISD::InputArg / OutputArg | Legal-typed argument pieces with flags, built by generic code |
| Shadow register | Register marked used as a side effect of assigning another |
CALLSEQ_START / CALLSEQ_END | DAG nodes bracketing a call; become ADJCALLSTACKDOWN/UP |
| Register mask | Bit set of registers preserved by a call, attached as an operand |
byval | Aggregate passed as a copy in the argument area |
sret | Hidden pointer to the caller's result buffer (x8 on AArch64) |
sret demotion | Rewriting a too-large return into an sret argument, triggered by CanLowerReturn |
| Sibling call | Tail call that needs no ABI change; NumBytes = 0 |
| Guaranteed tail call | tailcc/swifttailcc (or -tailcallopt): callee pops arguments |
TC_RETURN | AArch64 tail-call node; becomes TCRETURNdi/TCRETURNri then b/br |
va_list | AAPCS64: five fields (__stack, __gr_top, __vr_top, __gr_offs, __vr_offs) |
Part 4: Instruction Scheduling
The scheduling DAG, MachineScheduler, register pressure, post-RA scheduling and the SchedMachineModel language.
Pages
Instruction Scheduling Overview
Relevant source files
The following files were used as context for generating this wiki page:
Instruction scheduling reorders instructions inside a region (usually a basic block) without changing what the program computes. Its goals are to hide latency (start long operations early), to keep execution units busy, and to keep register pressure low enough that the allocator does not have to spill. LLVM schedules up to three times, and all of them read the same per-CPU scheduling model written in TableGen.
Purpose and Scope
This wiki covers the scheduling DAG, the machine scheduler (before register allocation), register pressure tracking, post-RA scheduling, the scheduling model language, how a target wires a model to its CPUs, a custom-backend guide and real AArch64 output. Where scheduling fits in a whole backend is on the bring-up wiki.
Where Scheduling Runs
flowchart LR
ISEL["SelectionDAG scheduler<br/>(orders DAG nodes into MachineInstrs)"] --> SSA["SSA machine passes"]
SSA --> MS["machine-scheduler<br/>pre-RA, ScheduleDAGMILive"]
MS --> RA["register allocation"]
RA --> PEI["prolog-epilog"]
PEI --> PMS["postmisched<br/>post-RA, ScheduleDAGMI"]
| Scheduler | Pass | When | Main concern | Page |
|---|---|---|---|---|
| SelectionDAG scheduler | part of instruction selection | Linearizing the selected DAG | A legal order; little else on targets using the machine scheduler | SelectionDAG scheduling and emission |
| Machine scheduler | machine-scheduler | After coalescing, before allocation | Latency and register pressure together | MachineScheduler |
| Post-RA machine scheduler | postmisched | After PEI | Latency and resources with physical registers | Post-RA Scheduling |
| Old post-RA list scheduler | post-RA-sched | Same slot | Replaced by postmisched on AArch64 | Post-RA Scheduling |
From the AArch64 pipeline (llc -O2 -mtriple=aarch64-linux-gnu -mcpu=cortex-a57 -debug-pass=Structure): ... -register-coalescer -rename-independent-subregs -machine-scheduler -aarch64-post-coalescer ... -greedy ... and later ... -aarch64-ldst-opt ... -postmisched .... The regalloc wiki's pipeline and preparation pages show the passes around the pre-RA scheduler.
The two machine-scheduler passes are entered at MachineSchedulerImpl::run and PostMachineSchedulerImpl::run; both build a scheduler with the target's factory and call scheduleRegions.
Sources: llvm/lib/CodeGen/MachineScheduler.cpp:540-610, llvm/lib/CodeGen/MachineScheduler.cpp:810, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:582-587
The Pieces
flowchart TD
TD["SchedMachineModel (.td)<br/>ProcResource, WriteRes, ReadAdvance, InstRW"] -->|"-gen-subtarget"| MCS["MCSchedModel tables"]
MCS --> TSM["TargetSchedModel<br/>latency / resource queries"]
SDI["ScheduleDAGInstrs<br/>SUnits + SDep edges"] --> MS["ScheduleDAGMI(Live)"]
TSM --> SDI
MS --> STRAT["MachineSchedStrategy<br/>GenericScheduler / PostGenericScheduler"]
RP["RegPressureTracker"] --> STRAT
MUT["DAG mutations<br/>(clustering, macro fusion)"] --> MS
Pages
The Scheduling DAG
Relevant source files
The following files were used as context for generating this wiki page:
Before a region can be reordered, the scheduler needs to know which instructions must stay in order. ScheduleDAGInstrs::buildSchedGraph creates one SUnit (scheduling unit) per instruction and adds an SDep edge for every ordering constraint: register data flow, register reuse, and memory ordering. Each edge carries a latency taken from the scheduling model.
Purpose and Scope
The node and edge types, and how each kind of edge is found. How the DAG is used is on MachineScheduler. The SelectionDAG has a different DAG (of SDNodes); see the SelectionDAG data structures page.
Edge Kinds
enum Kind {
Data, ///< Regular data dependence (aka true-dependence).
Anti, ///< A register anti-dependence (aka WAR).
Output, ///< A register output-dependence (aka WAW).
Order ///< Any other ordering dependency.
};
Order edges have a sub-kind:
Barrier, ///< An unknown scheduling barrier.
MayAliasMem, ///< Nonvolatile load/Store instructions that may alias.
MustAliasMem, ///< Nonvolatile load/Store instructions that must alias.
Artificial, ///< Arbitrary strong DAG edge (no real dependence).
Weak, ///< Arbitrary weak DAG edge.
Cluster ///< Weak DAG edge linking a chain of clustered instrs.
| Edge | Example | Latency |
|---|---|---|
| Data (RAW) | %2 = LDRXui ... then MADDXrrr %2, ... | Producer's write latency (minus any ReadAdvance) |
| Anti (WAR) | read of $x0, then a later write of $x0 | 0 |
| Output (WAW) | two writes of the same register | usually 1 |
| Memory order | store then a load that may alias | 0 or 1 |
| Barrier | call, hasUnmodeledSideEffects, volatile access | — |
| Weak / Cluster | added by mutations | may be violated |
Before allocation most values are virtual registers in SSA form, so Anti and Output edges come mostly from physical registers (arguments, return values, $sp). After allocation every register is physical, so post-RA DAGs have many more of them.
Sources: llvm/include/llvm/CodeGen/ScheduleDAG.h:55-77
Building the Graph
buildSchedGraph (line 710) walks the region bottom to top, keeping maps from each register and each memory object to the instructions that use or define it:
| Function | Line | Adds |
|---|---|---|
addPhysRegDataDeps | 247 | Data edges for physical register uses (SDep(SU, SDep::Data, UseReg), line 286) |
addPhysRegDeps | 303 | Anti/Output edges for physical registers (line 319) |
addVRegDefDeps | 413 | Data edges from a virtual register def to its uses (463), Output edges (507) |
addVRegUseDeps | 533 | Records virtual register uses |
addChainDependencies | 683, 690 | Memory edges between possibly aliasing accesses |
addBarrierChain | 699 | Edges to a barrier instruction from everything pending |
For memory, each access is mapped to its underlying IR objects; two accesses that depend only on different identified objects need no edge. Spill and reload instructions are in their own NonAlias domain because they never alias IR values.
Sources: llvm/lib/CodeGen/ScheduleDAGInstrs.cpp:247-319, llvm/lib/CodeGen/ScheduleDAGInstrs.cpp:413-533, llvm/lib/CodeGen/ScheduleDAGInstrs.cpp:683-759
Example
The dot-product region from the walkthroughs, before the pre-RA scheduler:
%2:gpr64 = LDRXui %0, 0 :: (load (s64) from %ir.a)
%3:gpr64 = LDRXui %1, 0 :: (load (s64) from %ir.b)
%5:gpr64 = LDRXui %0, 1 :: (load (s64) from %ir.pa1)
%6:gpr64 = LDRXui %1, 1 :: (load (s64) from %ir.pb1)
%7:gpr64 = MADDXrrr %5, %6, $xzr
%8:gpr64 = LDRXui %0, 2 :: (load (s64) from %ir.pa2)
%9:gpr64 = LDRXui %1, 2 :: (load (s64) from %ir.pb2)
%11:gpr64 = MADDXrrr %2, %3, %7
%12:gpr64 = MADDXrrr %8, %9, %11
flowchart TD
L2["%2 LDR a[0]"] --> M11["%11 MADD"]
L3["%3 LDR b[0]"] --> M11
L5["%5 LDR a[1]"] --> M7["%7 MUL"]
L6["%6 LDR b[1]"] --> M7
M7 --> M11
L8["%8 LDR a[2]"] --> M12["%12 MADD"]
L9["%9 LDR b[2]"] --> M12
M11 --> M12
All edges are Data edges. The six loads only read memory, so there are no memory edges between them and the scheduler may put them in any order.
Mutations
After the graph is built, target DAG mutations may add edges before scheduling starts. AArch64 adds load and store clustering (Cluster edges between memory operations on the same base, so they end up adjacent and can be paired) and, on CPUs that support it, macro fusion (instruction pairs the hardware fuses). See Wiring.
MachineScheduler and GenericScheduler
Relevant source files
The following files were used as context for generating this wiki page:
The machine scheduler (machine-scheduler) is a framework: ScheduleDAGMILive splits each block into regions, builds the scheduling DAG for each, and repeatedly asks a strategy which ready instruction to place next. The default strategy, GenericScheduler, places instructions from both ends of the region and picks between candidates with an ordered list of heuristics.
Purpose and Scope
Regions, scheduling direction, the policy hooks and the heuristic order of GenericScheduler. Register pressure is on Register Pressure Tracking; the post-RA version on Post-RA Scheduling.
Structure
flowchart TD
RUN["MachineSchedulerImpl::run"] --> REG["scheduleRegions: split blocks at calls / terminators / barriers"]
REG --> SCHED["ScheduleDAGMILive::schedule (per region)"]
SCHED --> BUILD["buildDAGWithRegPressure"]
BUILD --> MUT["postProcessDAG (mutations)"]
MUT --> LOOP{"pickNode loop"}
LOOP -->|"top or bottom"| STRAT["GenericScheduler::pickNode"]
STRAT --> MOVE["move MI into place, update boundaries and pressure"]
MOVE --> LOOP
| Function | Line |
|---|---|
MachineSchedulerImpl::run | 540 |
MachineSchedulerBase::scheduleRegions | 810 |
ScheduleDAGMI::schedule (no liveness, used post-RA) | 1057 |
ScheduleDAGMILive::initRegPressure | 1477 |
ScheduleDAGMILive::schedule | 1691 |
SchedBoundary::getLatencyStallCycles | 2579 |
SchedBoundary::bumpCycle | 2848 |
GenericScheduler::initPolicy | 3667 |
GenericScheduler::tryCandidate | 3944 |
GenericScheduler::pickNodeBidirectional / pickNode | 4081 / 4159 |
createConvergingSched (default scheduler factory) | 4294 |
Each scheduling direction has a SchedBoundary (class at MachineScheduler.h:861) that tracks the current cycle, issued micro-ops and resource use, using the model's IssueWidth and ProcResource counts.
Sources: llvm/lib/CodeGen/MachineScheduler.cpp:540, llvm/lib/CodeGen/MachineScheduler.cpp:810, llvm/lib/CodeGen/MachineScheduler.cpp:1057, llvm/lib/CodeGen/MachineScheduler.cpp:1477, llvm/lib/CodeGen/MachineScheduler.cpp:1691, llvm/lib/CodeGen/MachineScheduler.cpp:2579-2848, llvm/lib/CodeGen/MachineScheduler.cpp:4081-4294, llvm/include/llvm/CodeGen/MachineScheduler.h:861
Policy
initPolicy runs per region. It turns on pressure tracking for regions larger than half the allocatable integer registers, defaults to bottom-up only, then lets the subtarget override:
// For generic targets, we default to bottom-up, because it's simpler and more
// compile-time optimizations have been implemented in that direction.
RegionPolicy.OnlyBottomUp = true;
// Allow the subtarget to override default policy.
SchedRegion Region(Begin, End, NumRegionInstrs);
MF.getSubtarget().overrideSchedPolicy(RegionPolicy, Region);
Command-line options (-misched-regpressure, -misched-prera-direction) are applied after the override. AArch64 schedules in both directions:
void AArch64Subtarget::overrideSchedPolicy(MachineSchedPolicy &Policy,
const SchedRegion &Region) const {
// LNT run (at least on Cyclone) showed reasonably significant gains for
// bi-directional scheduling. 253.perlbmk.
Policy.OnlyTopDown = false;
Policy.OnlyBottomUp = false;
...
Policy.DisableLatencyHeuristic = DisableLatencySchedHeuristic;
}
MachineSchedPolicy is declared at MachineScheduler.h:200.
Sources: llvm/lib/CodeGen/MachineScheduler.cpp:3667-3715, llvm/lib/Target/AArch64/AArch64Subtarget.cpp:513-523, llvm/include/llvm/CodeGen/MachineScheduler.h:200
Heuristic Order
tryCandidate compares a new candidate against the best so far and stops at the first heuristic that prefers one of them. The reason is recorded as a CandReason (NoCand, Only1, PhysReg, RegExcess, ..., declared at MachineScheduler.h:1099).
| # | Heuristic | Lines | Prefers |
|---|---|---|---|
| 1 | tryBiasPhysRegs | 3953-3955 | Physical-register copies next to their uses/defs |
| 2 | Register excess | 3957-3962 | Not exceeding a pressure set's limit |
| 3 | Critical max pressure | 3964-3969 | Not raising pressure in the region's critical sets |
| 4 | Acyclic latency (loops) | 3978-3983 | Latency, when a loop is latency-bound |
| 5 | Stall cycles | 3985-3988 | Instructions that do not stall on unbuffered resources |
| 6 | Cluster | 3991-4006 | Keeping clustered instructions together |
| 7 | Weak edges | 4009-4013 | Fewer unscheduled weak predecessors |
| 8 | Current max pressure | 4016-4021 | Not raising the region's max pressure |
| 9 | Resources | 4024-4032 | Less critical resource use; more demanded resources |
| 10 | Latency | 4034-4038 | Not serializing long chains (tryLatency, 3470) |
| 11 | Node order | 4040-4044 | Original order, as a tie break |
Pressure comes before latency: before allocation, avoiding spills usually matters more than a few cycles. Clustering comes before latency too, which is why the loads in the walkthrough are grouped by base register.
Sources: llvm/lib/CodeGen/MachineScheduler.cpp:3944-4048, llvm/lib/CodeGen/MachineScheduler.cpp:3470, llvm/include/llvm/CodeGen/MachineScheduler.h:1095-1103
Turning It On and Off
The pass only runs for a subtarget whose enableMachineScheduler() returns true (AArch64: always). -enable-misched=false (option at line 474) disables it; the walkthroughs use that to show its effect.
Sources: llvm/lib/CodeGen/MachineScheduler.cpp:474-483, llvm/lib/Target/AArch64/AArch64Subtarget.h:160
Register Pressure Tracking
Relevant source files
The following files were used as context for generating this wiki page:
The pre-RA scheduler runs on virtual registers, so it can make register allocation easier or harder. Moving a definition earlier lengthens its live range; doing that to many values at once can push the number of simultaneously live values in a register class above what the hardware has, and the allocator then spills. The scheduler therefore tracks register pressure (live values per pressure set) while it schedules, and its first heuristics avoid raising it.
Purpose and Scope
The pressure data structures, how they are updated, and how GenericScheduler uses them. Live intervals, which the tracker reads, are described on the regalloc liveness page.
Data Structures
| Type | Line in RegisterPressure.h |
Holds |
|---|---|---|
RegisterPressure | 48 | Max pressure per pressure set over a range, plus live-in/live-out registers |
PressureDiff | 141 | Change in pressure caused by one instruction (per SUnit) |
PressureDiffs | 214 | One PressureDiff per instruction in the region |
RegPressureTracker | 375 | Current live set and pressure at a position; moved up or down instruction by instruction |
A pressure set is a group of register units that compete for the same physical registers (for example all 64-bit GPRs). TableGen computes the sets and their limits from the register classes; TargetRegisterInfo::getRegPressureSetLimit returns the limit.
Sources: llvm/include/llvm/CodeGen/RegisterPressure.h:48, llvm/include/llvm/CodeGen/RegisterPressure.h:141, llvm/include/llvm/CodeGen/RegisterPressure.h:214, llvm/include/llvm/CodeGen/RegisterPressure.h:375
Updating
flowchart LR
BOT["bottom of region:<br/>live-outs"] -->|"recede() per instruction"| TOP["top of region:<br/>live-ins"]
TOP -->|"advance() per instruction"| BOT
The tracker walks upward with recede (a use makes a register live, a def kills it going up) and downward with advance:
| Function | Line in RegisterPressure.cpp |
|---|---|
RegPressureTracker::recede(const RegisterOperands &, ...) | 772 |
RegPressureTracker::recede(SmallVectorImpl<VRegMaskOrUnit> *) | 880 |
RegPressureTracker::advance(const RegisterOperands &) | 903 |
RegPressureTracker::advance() | 954 |
ScheduleDAGMILive::initRegPressure (MachineScheduler.cpp:1477) sets up one tracker at each end of the region; as instructions are scheduled from the top or the bottom, the matching tracker moves.
Sources: llvm/lib/CodeGen/RegisterPressure.cpp:772-954, llvm/lib/CodeGen/MachineScheduler.cpp:1477
Use in GenericScheduler
Three of the first heuristics in tryCandidate are pressure checks (see MachineScheduler): register excess (would this candidate push any set over its limit), critical max (would it raise pressure in a set that is already the region's bottleneck) and current max (would it raise the region's maximum). tryPressure (MachineScheduler.cpp:3784) compares the two candidates' PressureChanges.
Tracking costs compile time, so initPolicy only enables it when the region has more instructions than half the allocatable registers of the widest legal integer class. -misched-regpressure=false (line 251) turns it off completely.
Sources: llvm/lib/CodeGen/MachineScheduler.cpp:3673-3686, llvm/lib/CodeGen/MachineScheduler.cpp:3784, llvm/lib/CodeGen/MachineScheduler.cpp:3957-3969, llvm/lib/CodeGen/MachineScheduler.cpp:251
Why the Order Matters
Where the pre-RA scheduler runs (after the coalescer, before greedy allocation) is shown on the regalloc pipeline page. Because allocation comes later, a schedule that minimizes cycles but raises pressure can be slower overall once spills are added; the scheduler favors pressure first and latency second for that reason. After allocation there are no virtual registers left, so the post-RA scheduler does not track pressure.
Post-RA Scheduling
Relevant source files
The following files were used as context for generating this wiki page:
After register allocation and frame lowering, the code contains spill code, prologue and epilogue, and expanded pseudos that the pre-RA scheduler never saw. A second scheduling pass can reorder this final code. Register pressure no longer matters (all registers are physical), so the post-RA scheduler cares about latency and execution resources only, and it must respect the extra anti and output dependencies that physical registers create.
Purpose and Scope
The two post-RA schedulers, how a target picks one, and what AArch64 does.
Two Implementations
| Post-RA machine scheduler | Old post-RA list scheduler | |
|---|---|---|
| Pass | postmisched | post-RA-sched |
| Code | PostMachineSchedulerImpl::run (MachineScheduler.cpp:588), ScheduleDAGMI, PostGenericScheduler | SchedulePostRATDList (PostRASchedulerList.cpp) |
| Direction | Configurable (-misched-postra-direction, line 190) | Top-down only (ListScheduleTopDown, line 544) |
| Enabled by | enablePostRAMachineScheduler() / -enable-post-misched (line 479) | enablePostRAScheduler() and opt level, or -post-RA-scheduler (line 56) |
| Strategy hooks | createPostMachineScheduler, overridePostRASchedPolicy | Hazard recognizer, anti-dependence breaker |
PostGenericScheduler::tryCandidate (line 4375) uses a shorter heuristic list than the pre-RA version: no pressure checks, but stall cycles, clustering, resources and latency.
Sources: llvm/lib/CodeGen/MachineScheduler.cpp:479-483, llvm/lib/CodeGen/MachineScheduler.cpp:588-610, llvm/lib/CodeGen/MachineScheduler.cpp:190-191, llvm/lib/CodeGen/MachineScheduler.cpp:4375-4523, llvm/lib/CodeGen/PostRASchedulerList.cpp:53-56, llvm/lib/CodeGen/PostRASchedulerList.cpp:270-283, llvm/lib/CodeGen/PostRASchedulerList.cpp:544
How the Old Scheduler Is Enabled
static bool enablePostRAScheduler(const TargetSubtargetInfo &ST,
CodeGenOptLevel OptLevel) {
// Check for explicit enable/disable of post-ra scheduling.
if (EnablePostRAScheduler.getPosition() > 0)
return EnablePostRAScheduler;
return ST.enablePostRAScheduler() &&
OptLevel >= ST.getOptLevelToEnablePostRAScheduler();
}
AArch64's Choice
AArch64 replaces the old pass with the machine-scheduler version in its pass config constructor:
AArch64PassConfig(AArch64TargetMachine &TM, PassManagerBase &PM)
: TargetPassConfig(TM, PM) {
if (TM.getOptLevel() != CodeGenOptLevel::None)
substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
and provides its own post-RA strategy, plus macro fusion again because some fusible pairs only appear after pseudo expansion:
ScheduleDAGInstrs *
AArch64TargetMachine::createPostMachineScheduler(MachineSchedContext *C) const {
const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
ScheduleDAGMI *DAG = createSchedPostRA<AArch64PostRASchedStrategy>(C);
if (ST.hasFusion()) {
// Run the Macro Fusion after RA again since literals are expanded from
// pseudos then (v. addPreSched2()).
DAG->addMutation(createAArch64MacroFusionDAGMutation());
return DAG;
}
Whether the old list scheduler would run for a CPU depends on the subtarget's enablePostRAScheduler(), which AArch64 forwards to usePostRAScheduler(). That accessor is not written by hand in AArch64Subtarget.h/.cpp; it comes from the TableGen-generated subtarget (a feature bit), and this page does not trace which CPUs set it. The SchedMachineModel record also has a PostRAScheduler bit (see The Scheduling Model).
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:538-550, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:582-587, llvm/lib/Target/AArch64/AArch64Subtarget.h:161, llvm/include/llvm/Target/TargetSchedule.td:88
Effect
In the walkthrough, -mcpu=cortex-a57: with both schedulers off the two loads ldr x11, [x0, #16] and ldr x12, [x1, #16] stay next to each other after the mul; with only the post-RA scheduler on, ldr x12 is hoisted above the second ldp so its 4-cycle latency overlaps the other loads.
The Scheduling Model
Relevant source files
The following files were used as context for generating this wiki page:
A scheduling model describes one CPU: how many micro-ops it issues per cycle, which execution units (processor resources) it has, and for each kind of instruction which units it uses and how long its result takes. It is written in TableGen with the classes from TargetSchedule.td; -gen-subtarget turns it into MCSchedModel tables, and TargetSchedModel answers latency and resource questions from them.
Purpose and Scope
The per-operand model (the one all current AArch64 CPUs use): machine parameters, resources, SchedWrite/SchedRead types, WriteRes, ReadAdvance, InstRW, SchedAlias, and variants. Itineraries, the older model, are mentioned at the end.
Two Levels
flowchart LR
I["Instruction record<br/>Sched<[WriteI, ReadI, ReadI]>"] --> T["target-wide types<br/>SchedWrite / SchedRead"]
T -->|"per CPU: WriteRes / SchedAlias / ReadAdvance"| R["ProcResources + latency"]
I -->|"per CPU override: InstRW"| R
Instructions name abstract types once; each CPU model maps the types to costs. An InstRW overrides the mapping for specific instructions on one CPU.
Machine Parameters
class SchedMachineModel {
int IssueWidth = -1; // Max micro-ops that may be scheduled per cycle.
int MicroOpBufferSize = -1; // Max micro-ops that can be buffered.
int LoopMicroOpBufferSize = -1; // Max micro-ops that can be buffered for
...
int LoadLatency = -1; // Cycles for loads to access the cache.
int HighLatency = -1; // Approximation of cycles for "high latency" ops.
int MispredictPenalty = -1; // Extra cycles for a mispredicted branch.
...
bit PostRAScheduler = false; // Enable Post RegAlloc Scheduler pass.
...
bit CompleteModel = true;
-1 means "use the default". MicroOpBufferSize = 0 models an in-order core (the scheduler must avoid stalls), a large value an out-of-order core. CompleteModel makes TableGen check that every instruction has scheduling information. NoSchedModel (line 127) is the empty default. The generated fields appear in MCSchedModel (MCSchedule.h:273: IssueWidth 285, MicroOpBufferSize 302, LoadLatency 314, CompleteModel 331).
Sources: llvm/include/llvm/Target/TargetSchedule.td:76-127, llvm/include/llvm/MC/MCSchedule.h:273-331
The Classes
| Class | Line in TargetSchedule.td |
Purpose |
|---|---|---|
ProcResource<N> | 197 | An execution unit with N copies |
ProcResGroup<[...]> | 200 | A set of units any of which can be used |
SchedWrite / SchedRead | 225 / 229 | Target-wide abstract operand types |
WriteRes<Write, [units]> | 310 | Map a SchedWrite to units and Latency for this model |
SchedWriteRes<[units]> | 318 | An anonymous write type, used with InstRW |
ReadAdvance<Read, N, [writes]> | 347 | Operand read N cycles late (forwarding), optionally only from given writes |
SchedReadAdvance | 355 | Anonymous read type |
SchedVar / SchedVariant / SchedWriteVariant | 426 / 434 / 447 | Choose a write type by a predicate on the instruction |
InstRW<[rw...], (instrs ...)> | 464 | Override types for specific instructions |
ItinRW | 477 | Map itinerary classes to types |
SchedAlias<Match, Alias> | 490 | Make a type an alias of another for this model |
Sources: llvm/include/llvm/Target/TargetSchedule.td:134-490
Cortex-A57 Example
def CortexA57Model : SchedMachineModel {
let IssueWidth = 3; // 3-way decode and dispatch
let MicroOpBufferSize = 128; // 128 micro-op re-order buffer
let LoadLatency = 4; // Optimistic load latency
let MispredictPenalty = 14; // Fetch + Decode/Rename/Dispatch + Branch
...
let LoopMicroOpBufferSize = 16;
let CompleteModel = 1;
...
def A57UnitI : ProcResource<2>; // Type I micro-ops
def A57UnitM : ProcResource<1>; // Type M micro-ops
def A57UnitL : ProcResource<1>; // Type L micro-ops
...
def A57UnitV : ProcResGroup<[A57UnitX, A57UnitW]>; // Type V micro-ops
...
def : SchedAlias<WriteLD, A57Write_4cyc_1L>;
...
def : WriteRes<WriteFMul, [A57UnitV]> { let Latency = 5;}
...
// Forwarding logic is only modeled for multiply and accumulate
def : ReadAdvance<ReadI, 0>;
...
def : ReadAdvance<ReadIMA, 2, [WriteIM32, WriteIM64]>;
...
def : InstRW<[A57Write_6cyc_1M], (instrs SMULHrr, UMULHrr)>;
Reading it: a plain load is a 4-cycle use of the load unit; the accumulator input of a multiply-accumulate (ReadIMA) is read 2 cycles late when it comes from another multiply, which is why chains of madd are cheap; SMULH/UMULH get a specific 6-cycle cost. Records are wrapped in let SchedModel = CortexA57Model in { ... } so they apply only to this model.
Sources: llvm/lib/Target/AArch64/AArch64SchedA57.td:23-61, llvm/lib/Target/AArch64/AArch64SchedA57.td:85-120, llvm/lib/Target/AArch64/AArch64SchedA57.td:157
How the Scheduler Reads It
TargetSchedModel (initialized in init, TargetSchedule.cpp:43) wraps the generated tables. hasInstrSchedModel (35) tells whether a per-operand model exists; getNumMicroOps (91) and computeOperandLatency (169) are what the DAG builder and SchedBoundary call. The generated tables are arrays of MCSchedClassDesc (MCSchedule.h:129) pointing into MCWriteProcResEntry (74), MCWriteLatencyEntry (97) and MCReadAdvanceEntry (114) lists, plus one MCProcResourceDesc (42) per unit.
Sources: llvm/lib/CodeGen/TargetSchedule.cpp:35-169, llvm/include/llvm/MC/MCSchedule.h:42-129
Itineraries
The older itinerary model (InstrItinClass, stage-by-stage pipeline tables) still exists and ItinRW can bridge it to SchedWrite types, but new models should use the per-operand form shown here. The same model also feeds llvm-mca (not available in this build).
Wiring a Model to a Target
Relevant source files
The following files were used as context for generating this wiki page:
A model has no effect until a CPU name points to it and the scheduler is enabled for the subtarget. A target can then customize scheduling in three places: the scheduler factories on TargetMachine, the policy hooks on the subtarget, and DAG mutations.
Purpose and Scope
The connections from -mcpu= to the model and from the target to the scheduler passes.
From CPU Name to Model
flowchart LR
MCPU["-mcpu=cortex-a57"] --> PM["ProcessorModel<'cortex-a57', CortexA57Model, ...>"]
PM -->|"-gen-subtarget"| TAB["processor table in GenSubtargetInfo.inc"]
TAB --> ST["Subtarget::getSchedModel()"]
ST --> TSM["TargetSchedModel::init"]
def : ProcessorModel<"generic", CortexA510Model, ProcessorFeatures.Generic,
...
def : ProcessorModel<"cortex-a55", CortexA55Model, ProcessorFeatures.A55,
...
def : ProcessorModel<"cortex-a57", CortexA57Model, ProcessorFeatures.A53,
[TuneA57]>;
At this commit AArch64's generic CPU uses the Cortex-A510 model. The model files must be included in AArch64.td before AArch64Processors.td (lines 125-157), as shown on the bring-up target .td page.
Sources: llvm/lib/Target/AArch64/AArch64Processors.td:1291-1313, llvm/lib/Target/AArch64/AArch64.td:125-157
Hooks
| Hook | Class | Header line | AArch64 |
|---|---|---|---|
enableMachineScheduler() | TargetSubtargetInfo | 225 | true (AArch64Subtarget.h:160) |
enablePostRAScheduler() | TargetSubtargetInfo | 251 | usePostRAScheduler() (AArch64Subtarget.h:161) |
enablePostRAMachineScheduler() | TargetSubtargetInfo | 255 | default |
overrideSchedPolicy(Policy, Region) | TargetSubtargetInfo | 268 | bidirectional (AArch64Subtarget.cpp:513) |
overridePostRASchedPolicy | TargetSubtargetInfo | 278 | default |
createMachineScheduler(C) | TargetMachine | — | AArch64TargetMachine.cpp:524 |
createPostMachineScheduler(C) | TargetMachine | — | AArch64TargetMachine.cpp:538 |
adjustSchedDependency | TargetSubtargetInfo | — | Fixes latencies through BUNDLEs (AArch64Subtarget.cpp:525) |
Sources: llvm/include/llvm/CodeGen/TargetSubtargetInfo.h:225-278, llvm/lib/Target/AArch64/AArch64Subtarget.cpp:513-562, llvm/lib/Target/AArch64/AArch64Subtarget.h:160-161
DAG Mutations
AArch64's pre-RA factory starts from the generic live scheduler and adds mutations:
ScheduleDAGInstrs *
AArch64TargetMachine::createMachineScheduler(MachineSchedContext *C) const {
const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
ScheduleDAGMILive *DAG = createSchedLive(C);
DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
if (ST.hasFusion())
DAG->addMutation(createAArch64MacroFusionDAGMutation());
...
return DAG;
}
Load/store clustering asks TargetInstrInfo (getMemOperandsWithOffsetWidth, shouldClusterMemOps) which memory operations share a base and should stay adjacent; that is what keeps [x0] and [x0, #8] next to each other so aarch64-ldst-opt can form an ldp. Macro fusion adds edges for pairs the CPU fuses (such as compare + branch).
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:524-536
Custom Backend Guide and Checklist
Relevant source files
The following files were used as context for generating this wiki page:
A first scheduling model for a new CPU can be small: a handful of SchedWrite types, one or two processor resources, and a WriteRes per type. It can be refined later with InstRW overrides and ReadAdvance forwarding once measurements show where the model is wrong. All code here is for the made-up "Toy" target and is illustrative, not LLVM source.
Purpose and Scope
Steps to write a minimal model, and how to check that it is complete. The model language is on The Scheduling Model; the hooks on Wiring.
Steps
| Step | Write | Check |
|---|---|---|
| 1 | enableMachineScheduler() returns true in the subtarget | machine-scheduler appears in -debug-pass=Structure and changes MIR |
| 2 | Target-wide SchedWrite/SchedRead types (ToySchedule.td), included before the instructions | .td parses |
| 3 | Sched<[...]> on every instruction class: one write per def, then one read per use | — |
| 4 | SchedMachineModel with IssueWidth, MicroOpBufferSize, LoadLatency, CompleteModel = 1 | — |
| 5 | ProcResources and a WriteRes (or SchedAlias) per SchedWrite, ReadAdvance per SchedRead, inside let SchedModel = ... in | llvm-tblgen -gen-subtarget reports no missing information |
| 6 | ProcessorModel<"toy2", ToyModel, [...]> | llc -mcpu=toy2 uses it |
| 7 | Optional: mutations in createMachineScheduler, overrideSchedPolicy | Compare MIR before/after machine-scheduler |
Minimal Model (Illustrative)
Illustrative, not LLVM source.
// ToySchedule.td: target-wide types, included from Toy.td before ToyInstrInfo.td
def WriteALU : SchedWrite;
def WriteMul : SchedWrite;
def WriteLoad : SchedWrite;
def WriteStore: SchedWrite;
def WriteBr : SchedWrite;
def ReadALU : SchedRead;
// In ToyInstrInfo.td
// def ADD : ToyInst<...>, Sched<[WriteALU, ReadALU, ReadALU]>;
// def LW : ToyInst<...>, Sched<[WriteLoad, ReadALU]>;
// ToySchedToy2.td
def ToyModel : SchedMachineModel {
let IssueWidth = 2;
let MicroOpBufferSize = 0; // in-order
let LoadLatency = 3;
let CompleteModel = 1;
}
let SchedModel = ToyModel in {
def ToyALU : ProcResource<2>;
def ToyMUL : ProcResource<1>;
def ToyLSU : ProcResource<1>;
def : WriteRes<WriteALU, [ToyALU]> { let Latency = 1; }
def : WriteRes<WriteMul, [ToyMUL]> { let Latency = 3; }
def : WriteRes<WriteLoad, [ToyLSU]> { let Latency = 3; }
def : WriteRes<WriteStore,[ToyLSU]> { let Latency = 1; }
def : WriteRes<WriteBr, [ToyALU]> { let Latency = 1; }
def : ReadAdvance<ReadALU, 0>;
}
Checking Completeness
With CompleteModel = 1, TableGen reports instructions that have no scheduling information for the model. Pseudos that never reach the scheduler can be marked hasNoSchedulingInfo, or the model can list them as unsupported. AArch64 models exclude whole feature groups with UnsupportedFeatures lists built from records such as SVEUnsupported in AArch64.td.
Sources: llvm/include/llvm/Target/TargetSchedule.td:76-97, llvm/lib/Target/AArch64/AArch64.td:68-123, llvm/lib/Target/AArch64/AArch64Schedule.td:24-44
Checklist
- ☐ Machine scheduler enabled for the subtarget
- ☐ Every instruction has
Sched<[...]>with writes first, then reads - ☐ Model compiles with
CompleteModel = 1 - ☐
MicroOpBufferSizematches the core (0 for in-order) - ☐
ProcessorModelattaches the model to a CPU name - ☐ Same test compiled with
-enable-misched=falseand without, MIR compared - ☐ Spill count checked: a model that ignores pressure can make code slower
AArch64 Walkthroughs
Relevant source files
The following files were used as context for generating this wiki page:
One small function compiled with the real llc (LLVM 24.0.0git release build at a2171756) using -O2 -mtriple=aarch64-linux-gnu -mcpu=cortex-a57, under four scheduler settings. The point is to show which pass changed what, and also that later passes can hide a scheduler's effect.
Purpose and Scope
The pre-RA scheduler's effect on MIR, the post-RA scheduler's effect on assembly, and why the final code with only the pre-RA scheduler switched off is the same as the default.
The Function
define i64 @dot(ptr %a, ptr %b) {
; loads a[0..2], b[0..2]; returns a0*b0 + a1*b1 + a2*b2
...
}
1. Pre-RA Scheduler: MIR Before and After
-stop-before=machine-scheduler:
%2:gpr64 = LDRXui %0, 0 :: (load (s64) from %ir.a)
%3:gpr64 = LDRXui %1, 0 :: (load (s64) from %ir.b)
%5:gpr64 = LDRXui %0, 1 :: (load (s64) from %ir.pa1)
%6:gpr64 = LDRXui %1, 1 :: (load (s64) from %ir.pb1)
%7:gpr64 = MADDXrrr %5, %6, $xzr
%8:gpr64 = LDRXui %0, 2 :: (load (s64) from %ir.pa2)
%9:gpr64 = LDRXui %1, 2 :: (load (s64) from %ir.pb2)
%11:gpr64 = MADDXrrr %2, %3, %7
%12:gpr64 = MADDXrrr %8, %9, %11
-stop-after=machine-scheduler:
%2:gpr64 = LDRXui %0, 0 :: (load (s64) from %ir.a)
%5:gpr64 = LDRXui %0, 1 :: (load (s64) from %ir.pa1)
%3:gpr64 = LDRXui %1, 0 :: (load (s64) from %ir.b)
%6:gpr64 = LDRXui %1, 1 :: (load (s64) from %ir.pb1)
%7:gpr64 = MADDXrrr %5, %6, $xzr
%8:gpr64 = LDRXui %0, 2 :: (load (s64) from %ir.pa2)
%9:gpr64 = LDRXui %1, 2 :: (load (s64) from %ir.pb2)
%11:gpr64 = MADDXrrr %2, %3, %7
%12:gpr64 = MADDXrrr %8, %9, %11
The only change: a[1] moved up next to a[0], so the two adjacent loads from %0 are together, and the two from %1 likewise. That is the load-clustering mutation added in createMachineScheduler (Cluster edges win over latency in tryCandidate; see MachineScheduler). The rest of the order already satisfied the model.
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:524-536
2. Final Assembly Under Four Settings
| Setting | Assembly body |
|---|---|
| Default (both schedulers) | ldp x8, x9, [x0] / ldr x12, [x1, #16] / ldp x10, x11, [x1] / mul x9, x9, x11 / ldr x11, [x0, #16] / madd x8, x8, x10, x9 / madd x0, x11, x12, x8 |
-enable-misched=false | ldp x8, x10, [x0] / ldr x12, [x1, #16] / ldp x9, x11, [x1] / mul x10, x10, x11 / ldr x11, [x0, #16] / madd x8, x8, x9, x10 / madd x0, x11, x12, x8 |
-enable-misched=false -enable-post-misched=false | ldp x8, x10, [x0] / ldp x9, x11, [x1] / mul x10, x10, x11 / ldr x11, [x0, #16] / ldr x12, [x1, #16] / madd x8, x8, x9, x10 / madd x0, x11, x12, x8 |
Observations:
- Default vs. pre-RA off: same instruction order, different register numbers. The pre-RA scheduler's clustering did not change the final code here, because the load/store optimizer (
aarch64-ldst-opt, which runs after allocation) forms theldppairs either way. Its effect is visible in MIR and in register choice only. - Post-RA on vs. off: with
postmischeddisabled,ldr x12, [x1, #16]stays after themul; with it enabled, that load is hoisted above the secondldpso its 4-cycle latency (WriteLD→A57Write_4cyc_1L) overlaps the other loads before the finalmaddneeds it.
Sources: llvm/lib/Target/AArch64/AArch64SchedA57.td:87, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:538-550
Lesson
To see what a scheduler did, compare the MIR right before and right after that pass, not just the final assembly: later passes (load/store pairing, the other scheduler, register allocation) can make a scheduler's change invisible or even undo it.
Reproducing
llc -O2 -mtriple=aarch64-linux-gnu -mcpu=cortex-a57 sched.ll -o -
llc ... -enable-misched=false sched.ll -o -
llc ... -enable-misched=false -enable-post-misched=false sched.ll -o -
llc ... -stop-before=machine-scheduler sched.ll -o before.mir
llc ... -stop-after=machine-scheduler sched.ll -o after.mir
The regalloc wiki's AArch64 walkthroughs show what allocation does with scheduled MIR.
Tooling and Glossary
Relevant source files
The following files were used as context for generating this wiki page:
Commands for inspecting scheduling, and the terms used in this wiki. General llc options are on the bring-up tooling page.
Purpose and Scope
All output in this wiki comes from an LLVM 24.0.0git release llc (no assertions) at commit a2171756. llvm-mca was not available in this build.
Commands
| Command | Shows | Needs assertions |
|---|---|---|
llc ... -mcpu=<cpu> | Select the CPU and its scheduling model | No |
llc ... -stop-before=machine-scheduler / -stop-after=machine-scheduler | MIR on either side of the pre-RA scheduler | No |
llc ... -stop-before=postmisched / -stop-after=postmisched | MIR on either side of the post-RA scheduler | No |
llc ... -enable-misched=false | Disable the pre-RA scheduler (option at line 474) | No |
llc ... -enable-post-misched=false | Disable the post-RA machine scheduler (line 479) | No |
llc ... -misched-prera-direction=topdown|bottomup|bidirectional | Force direction (line 179) | No |
llc ... -misched-regpressure=false | Disable pressure tracking (line 251) | No |
llc ... -misched-cluster=false | Disable memory-op clustering (line 257) | No |
llc ... -misched-print-dags, -debug-only=machine-scheduler | Print DAGs and every scheduling decision | Yes |
llc ... -view-misched-dags | Draw the DAG (line 212) | Debug build + Graphviz |
llvm-mca -mcpu=<cpu> file.s | Static throughput analysis from the same model | No (tool not built here) |
Sources: llvm/lib/CodeGen/MachineScheduler.cpp:179-257, llvm/lib/CodeGen/MachineScheduler.cpp:474-483, llvm/lib/CodeGen/PostRASchedulerList.cpp:53-56
Glossary
| Term | Meaning |
|---|---|
| Region | Instruction range scheduled as a unit; split at calls, terminators and barriers |
SUnit | One scheduling node, wrapping a MachineInstr |
SDep | DAG edge: Data, Anti, Output or Order (with sub-kinds such as Barrier, Cluster) |
| Latency | Cycles from a write until a dependent read can use it |
ScheduleDAGMILive | Pre-RA scheduler with live intervals and pressure |
ScheduleDAGMI | Scheduler without liveness, used post-RA |
GenericScheduler | Default pre-RA strategy (bidirectional, ordered heuristics) |
PostGenericScheduler | Default post-RA strategy |
SchedBoundary | Per-direction state: current cycle, issued micro-ops, resource use |
| Pressure set | Group of register units that compete for the same registers |
| DAG mutation | Post-processing that adds edges (clustering, macro fusion) |
SchedMachineModel | Per-CPU model: issue width, buffer size, latencies |
ProcResource | An execution unit (with a count) |
SchedWrite / SchedRead | Target-wide abstract operand types |
WriteRes | Maps a SchedWrite to resources and latency for one model |
ReadAdvance | Forwarding: operand read N cycles late |
InstRW | Per-instruction override of scheduling types |
CompleteModel | TableGen checks that every instruction has scheduling data |
| Macro fusion | Hardware executes an instruction pair as one; scheduler keeps them adjacent |
Part 5: Register Allocation
Liveness, coalescing, the allocators, spilling and splitting, and the register hooks a target provides.
Pages
- 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
Register Allocation Overview
Relevant source files
The following files were used as context for generating this wiki page:
Register allocation is the step of the LLVM code generator that replaces every virtual register (an unlimited supply of names such as %4) with a real physical register of the target (such as $w0). When there are more values alive at once than the machine has registers, the allocator stores some of them in stack slots (spilling) and loads them back before use (reloading).
Purpose and Scope
This wiki explains register allocation in llvm/lib/CodeGen/, from the basic ideas to the internals of the Greedy allocator, using the AArch64 backend as the worked example. It is written for someone who knows C++ and has seen LLVM IR, but has not worked on a code generator before.
It covers:
- the vocabulary: physical and virtual registers, register classes, sub-registers, register units, liveness;
- the passes that prepare the code (PHI elimination, two-address lowering, coalescing);
- the analyses the allocators share (
SlotIndexes,LiveIntervals,LiveRegMatrix,VirtRegMap); - the four allocators LLVM ships: Fast, Basic, Greedy and PBQP;
- spilling, live range splitting and rematerialisation;
- the rewriting step and the post-allocation passes;
- everything a custom backend must provide so that the allocator works for it: see Writing Register Allocation Support for a Custom Backend.
It does not cover GlobalISel register bank selection (RegBankSelect), which picks a register bank, not a register.
Why Register Allocation Is Needed
Instruction selection (SelectionDAG, GlobalISel or FastISel) produces MachineInstrs that use as many virtual registers as it likes. Each virtual register is written once (SSA form) and has a register class that says which physical registers it may live in. A real CPU has a small fixed set of registers, so something must decide:
- which physical register holds each value, and for how long;
- which values do not fit and must live in memory for part of their life;
- how to satisfy fixed constraints: arguments arrive in specific registers, calls destroy (clobber) some registers, and some instructions require their result in the same register as an operand.
A wrong answer is a miscompile (two live values in one register). A poor answer is slow code (extra loads, stores and copies). Register allocation is therefore both a correctness pass and one of the most important optimisations in the back end.
Where Register Allocation Fits
flowchart LR ISEL["Instruction selection<br/>SSA MIR, virtual registers, PHIs"] --> PRE["Pre-RA MIR passes<br/>CSE, LICM, peephole"] PRE --> PREP["Preparation<br/>PHIElimination, TwoAddress,<br/>RegisterCoalescer, MachineScheduler"] PREP --> RA["Register allocator<br/>Greedy (or Fast at -O0)"] RA --> RW["VirtRegRewriter<br/>vregs replaced by physregs"] RW --> POST["StackSlotColoring, MachineCopyPropagation,<br/>Prologue/Epilogue insertion"] POST --> MC["AsmPrinter and MC layer"]
Before allocation, MIR is in SSA form with virtual registers. After the rewriter, every register operand is physical, and the function has a set of stack slots (%stack.N) for spilled values. Prologue/epilogue insertion later turns those slots into concrete sp- or fp-relative offsets and saves any callee-saved registers the allocator used.
Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1483-1549
A First Example
Compile this function for AArch64 at -O2:
define i32 @f(i32 %a, i32 %b, i32 %c) {
%m = mul i32 %a, %b
%s = add i32 %m, %c
ret i32 %s
}
Just before the allocator (llc -mtriple=aarch64 -O2 -stop-before=greedy) the body uses virtual registers:
bb.0 (%ir-block.0):
liveins: $w0, $w1, $w2
%1:gpr32 = COPY $w1
%0:gpr32 = COPY $w0
%2:gpr32 = COPY $w2
%4:gpr32 = MADDWrrr %0, %1, %2
$w0 = COPY %4
RET_ReallyLR implicit $w0
After the rewriter (-stop-after=virtregrewriter) there are no virtual registers and no copies:
bb.0 (%ir-block.0):
liveins: $w0, $w1, $w2
renamable $w0 = MADDWrrr killed renamable $w0, killed renamable $w1, killed renamable $w2
RET_ReallyLR implicit $w0
The allocator followed hints: %0 was copied from $w0, so it prefers $w0; %4 is copied into $w0, so it prefers $w0 too. Once every copy has the same register on both sides it is an identity copy, and the rewriter deletes it. The final assembly is one instruction, madd w0, w0, w1, w2.
The Four Allocators
| Allocator | -regalloc= |
Used by default | Idea | Page |
|---|---|---|---|---|
| Fast | fast | -O0 | Walks each block once, bottom to top, assigning registers on demand; values that cross block boundaries go through stack slots | Fast Register Allocator |
| Basic | basic | never | Priority queue of whole live intervals; spills on conflict. A simple reference for the shared framework | Basic Register Allocator |
| Greedy | greedy | -O1 and above | Priority queue plus eviction, region/block/local splitting, then spilling | Greedy Register Allocator |
| PBQP | pbqp | never (opt-in) | Models allocation as a Partitioned Boolean Quadratic Problem and solves it | PBQP Register Allocator |
Each allocator registers itself under its -regalloc= name with a RegisterRegAlloc object. The default is chosen by TargetPassConfig::createTargetRegisterAllocator: Greedy when optimising, Fast otherwise.
Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1413-1418, llvm/lib/CodeGen/RegAllocGreedy.cpp:148, llvm/lib/CodeGen/RegAllocFast.cpp:61, llvm/lib/CodeGen/RegAllocBasic.cpp:38, llvm/lib/CodeGen/RegAllocPBQP.cpp:94
Component Map
| Component | Class | File | Role |
|---|---|---|---|
| Pipeline | TargetPassConfig::addOptimizedRegAlloc, addFastRegAlloc | TargetPassConfig.cpp | Decides which passes run and in what order |
| Instruction numbering | SlotIndexes | SlotIndexes.cpp | Gives every instruction a position so ranges can be compared |
| Liveness | LiveIntervals, LiveInterval, LiveRange | LiveIntervals.cpp, LiveInterval.cpp | Where each register is alive |
| Coalescing | RegisterCoalescer | RegisterCoalescer.cpp | Merges registers joined by copies |
| Interference | LiveRegMatrix, LiveIntervalUnion | LiveRegMatrix.cpp, LiveIntervalUnion.cpp | What is already assigned to each physical register |
| Assignment record | VirtRegMap | VirtRegMap.cpp | Virtual register to physical register or stack slot |
| Shared driver | RegAllocBase | RegAllocBase.cpp | Priority-queue loop used by Basic and Greedy |
| Allocators | RAGreedy, RABasic, RegAllocFast, RegAllocPBQP | RegAlloc*.cpp | The policy |
| Spiller | InlineSpiller | InlineSpiller.cpp | Inserts spill and reload code, rematerialises |
| Splitter | SplitAnalysis, SplitEditor | SplitKit.cpp | Cuts a live range into pieces |
| Rewriter | VirtRegRewriter | VirtRegMap.cpp | Replaces virtual registers in instructions |
What a Target Provides
The allocator itself is target-independent. A backend teaches it about the machine through:
| Provided by | What | Page |
|---|---|---|
<Target>RegisterInfo.td | Registers, sub-registers, register classes, allocation order, callee-saved lists | Register Definitions in TableGen |
<Target>RegisterInfo.cpp | Reserved registers, callee-saved registers, call-preserved masks, hints, frame index elimination | TargetRegisterInfo Hooks |
<Target>InstrInfo.cpp | Copying, spilling and reloading a register, rematerialisation, folding | TargetInstrInfo Hooks |
<Target>TargetMachine.cpp | Extra passes around allocation, choice of allocator | Pass Pipeline Hooks |
Reading Guide
- New to the topic: read Registers, Virtual Registers and Register Classes, then Liveness, then Greedy Register Allocator.
- Bringing up a new backend: go straight to Writing Register Allocation Support for a Custom Backend and its checklist.
- Debugging bad code or a crash: Tooling and Debugging and the AArch64 Walkthroughs.
The Register Allocation Pipeline
Relevant source files
The following files were used as context for generating this wiki page:
Register allocation is not one pass. It is a chain of passes that first reshape the code into a form the allocator can handle, then assign registers, then clean up. TargetPassConfig builds one of two chains: a short one for -O0 and a long one when optimising.
Purpose and Scope
This page lists the exact passes in both chains, explains what each one is for in one or two sentences, and shows how -regalloc= selects the chain. Each preparation pass has its own page later.
Which Chain Runs
TargetPassConfig::getOptimizeRegAlloc decides:
- If
-regalloc=was given on the command line, the optimised chain runs for every allocator exceptfast. - Otherwise the optimised chain runs whenever the optimisation level is not
-O0.
bool TargetPassConfig::getOptimizeRegAlloc() const {
// An explicit -regalloc choice implies its pipeline: only the fast
// allocator uses the unoptimized one.
...
RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
if (Ctor != (RegisterRegAlloc::FunctionPassCtor)&useDefaultRegisterAllocator)
return Ctor !=
(RegisterRegAlloc::FunctionPassCtor)&createFastRegisterAllocator;
return getOptLevel() != CodeGenOptLevel::None;
}
So llc -O2 -regalloc=fast uses the unoptimised chain (no coalescer, no scheduler), and llc -O0 -regalloc=greedy uses the optimised one. The unoptimised chain only accepts the Fast allocator; addRegAssignAndRewriteFast reports a fatal usage error for anything else.
Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1393-1403, llvm/lib/CodeGen/TargetPassConfig.cpp:1445-1457
The Unoptimised Chain (-O0)
void TargetPassConfig::addFastRegAlloc() {
addPass(&PHIEliminationID);
addPass(&TwoAddressInstructionPassID);
addRegAssignAndRewriteFast();
}
Three passes: remove PHIs, make two-address instructions explicit, then let the Fast allocator assign and rewrite in one go. The Fast allocator writes physical registers directly into the instructions, so there is no separate rewriter.
Observed with llc -mtriple=aarch64 -O0 -debug-pass=Structure (filtered):
Eliminate PHI nodes for register allocation
Two-Address instruction pass
Fast Register Allocator
Prologue/Epilogue Insertion & Frame Finalization
Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1483-1488
The Optimised Chain (-O1 and above)
void TargetPassConfig::addOptimizedRegAlloc() {
addPass(&DetectDeadLanesID);
addPass(&InitUndefID);
addPass(&ProcessImplicitDefsID);
addPass(&UnreachableMachineBlockElimID);
addPass(&LiveVariablesID);
addPass(&MachineLoopInfoID);
addPass(&PHIEliminationID);
if (EarlyLiveIntervals)
addPass(&LiveIntervalsID);
addPass(&TwoAddressInstructionPassID);
addPass(&RegisterCoalescerID);
addPass(&RenameIndependentSubregsID);
addPass(&MachineSchedulerID);
if (addRegAssignAndRewriteOptimized()) {
addPass(&StackSlotColoringID);
addPostRewrite();
addPass(&MachineCopyPropagationID);
addPass(&MachineLICMID);
}
}
(Comments removed; see the source for them.) addRegAssignAndRewriteOptimized adds the allocator, then the target's addPreRewrite() hook, then VirtRegRewriter, then a scoring pass that does nothing unless an ML eviction policy is being trained.
Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1459-1473, llvm/lib/CodeGen/TargetPassConfig.cpp:1493-1549
What Each Pass Does
| # | Pass (-debug-pass name) |
Command-line name | Purpose |
|---|---|---|---|
| 1 | Detect Dead Lanes | detect-dead-lanes | Finds sub-register lanes that are never read and marks them dead or undef, so they do not create false liveness |
| 2 | Init Undef Pass | init-undef | An undef input does not stop the allocator from giving it the same register as an early-clobber result, so this pass replaces such undefined inputs with a temporary pseudo definition. It also rewrites NoReg tied operands back to IMPLICIT_DEF before two-address lowering |
| 3 | Process Implicit Definitions | processimpdefs | Removes IMPLICIT_DEF instructions and marks their uses undef |
| 4 | Remove unreachable machine basic blocks | unreachable-mbb-elimination | Required before LiveVariables |
| 5 | Live Variable Analysis | livevars | Computes kill flags on SSA MIR; used by the next two passes |
| 6 | Eliminate PHI nodes | phi-node-elimination | Replaces each PHI with COPYs in the predecessor blocks. See PHI Elimination and Two-Address Lowering |
| 7 | Two-Address instruction pass | twoaddressinstruction | For instructions whose result must use the same register as an operand, inserts a COPY so that holds. Ends SSA form |
| 8 | Slot index numbering, Live Interval Analysis | slotindexes, liveintervals | Number the instructions and compute live intervals (required by the coalescer, so they run here) |
| 9 | Register Coalescer | register-coalescer | Removes COPYs by merging the two registers into one. See Register Coalescer |
| 10 | Rename Disconnected Subregister Components | rename-independent-subregs | Splits a register whose sub-register parts are independent into separate registers |
| 11 | Machine Instruction Scheduler | machine-scheduler | Pre-RA scheduling; it tracks register pressure so it can avoid creating spills |
| 12 | (analyses) | livedebugvars, livestacks, virtregmap, liveregmatrix, edge-bundles, spill-code-placement | Required by Greedy; built just before it |
| 13 | Greedy Register Allocator | greedy | Assigns, evicts, splits and spills. See Greedy Register Allocator |
| 14 | Virtual Register Rewriter | virtregrewriter | Replaces each virtual register in the instructions with its physical register. See Rewriting and Post-RA Passes |
| 15 | Stack Slot Coloring | stack-slot-coloring | Lets spill slots whose live ranges do not overlap share memory |
| 16 | Machine Copy Propagation | machine-cp | Forwards copies that the coalescer could not remove |
| 17 | Machine Loop Invariant Code Motion | machinelicm | Post-RA: hoists reloads and rematerialised constants out of loops |
Observed on AArch64 at -O2
From llc -mtriple=aarch64 -O2 -debug-pass=Structure on a trivial function, filtered to the passes around allocation:
AArch64 PTRUE Coalescing
Detect Dead Lanes
Init Undef Pass
Process Implicit Definitions
Remove unreachable machine basic blocks
Live Variable Analysis
Eliminate PHI nodes for register allocation
Two-Address instruction pass
Slot index numbering
Live Interval Analysis
Register Coalescer
Rename Disconnected Subregister Components
Machine Instruction Scheduler
AArch64 Post Coalescer pass
Debug Variable Analysis
Live Stack Slot Analysis
Virtual Register Map
Live Register Matrix
Spill Code Placement Analysis
Greedy Register Allocator
Virtual Register Rewriter
Register Allocation Pass Scoring
Stack Slot Coloring
Machine Copy Propagation Pass
Machine Loop Invariant Code Motion
Prologue/Epilogue Insertion & Frame Finalization
Two AArch64 passes appear. AArch64 PTRUE Coalescing comes from addMachineSSAOptimization, earlier in the pipeline. AArch64 Post Coalescer pass sits right before the allocator because AArch64 overrides addRegAssignAndRewriteOptimized to add it first:
bool AArch64PassConfig::addRegAssignAndRewriteOptimized() {
addPass(createAArch64PostCoalescerPass());
return TargetPassConfig::addRegAssignAndRewriteOptimized();
}
This pattern (override a hook, add your pass, call the base version) is the usual way for a target to insert work around allocation. See Pass Pipeline Hooks.
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:817-829, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:970-973
Where the Target Can Plug In
flowchart TD A["addPreRegAlloc()"] --> B["addOptimizedRegAlloc()<br/>or addFastRegAlloc()"] B --> C["addRegAssignAndRewriteOptimized()<br/>allocator pass"] C --> D["addPreRewrite()"] D --> E["VirtRegRewriter"] E --> F["StackSlotColoring"] F --> G["addPostRewrite()"] G --> H["MachineCopyPropagation, MachineLICM"] H --> I["addPostRegAlloc()"] I --> J["Prologue/Epilogue insertion"]
| Hook | When it runs | AArch64 uses it for |
|---|---|---|
addPreRegAlloc | Before the whole allocation chain | Dead register definitions to wzr/xzr, AdvSIMD scalar, machine pipeliner |
addRegAssignAndRewriteOptimized | Wraps allocator plus rewriter | The Post Coalescer pass |
addPreRewrite | After the allocator, before the rewriter | (not used) |
addPostRewrite | After the rewriter | A sub-register mitigation pass, when enabled |
addPostRegAlloc | After the chain, before prologue/epilogue | Redundant copy elimination, A57 FP load balancing |
addPostFastRegAllocRewrite | After the Fast allocator | (not used) |
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:852-886, llvm/lib/CodeGen/TargetPassConfig.cpp:1157-1184, llvm/lib/CodeGen/InitUndef.cpp:9-37
What Changes Along the Way
| After | MIR property |
|---|---|
| Instruction selection | SSA, virtual registers, PHIs, IMPLICIT_DEFs |
| PHI elimination | No PHIs; extra COPYs at the end of predecessors |
| Two-address | Not SSA any more: a register can be defined more than once (TiedOpsRewritten) |
| Coalescer | Most COPYs gone; fewer, longer virtual registers |
| Allocator | VirtRegMap says where each register lives; instructions still name virtual registers; spill code inserted |
| Rewriter | Only physical registers; NoVRegs property set |
The Coalescer page shows one loop at each of these points.
Registers, Virtual Registers and Register Classes
Relevant source files
The following files were used as context for generating this wiki page:
Before any algorithm makes sense you need the vocabulary. This page explains the two kinds of register in MIR, what a register class is, how sub-registers and register units describe overlap, and which registers the allocator is not allowed to touch.
Purpose and Scope
Everything here is used by every allocator. AArch64 definitions are quoted as concrete examples; how to write your own is on Register Definitions in TableGen.
Physical and Virtual Registers
LLVM represents both kinds with the same type, Register (a 32-bit number):
| Kind | MIR spelling | Number range | Meaning |
|---|---|---|---|
| Physical | $w0, $x19, $sp | Small numbers from TableGen (AArch64::W0, ...) | A real hardware register |
| Virtual | %0, %15 | Top bit set (VirtualRegFlag = 1u << 31) | An unlimited name created by instruction selection |
| Stack slot | %stack.3 (in operands: frame index) | Between StackSlotZero and VirtualRegFlag | Used inside some analyses to stand for a frame index |
static constexpr unsigned VirtualRegFlag = 1u << 31;
...
static Register index2VirtReg(unsigned Index) {
...
return Index | Register::VirtualRegFlag;
}
constexpr bool isVirtual() const { return isVirtualRegister(Reg); }
constexpr bool isPhysical() const { return isPhysicalRegister(Reg); }
So %5 is just 5 | 0x80000000. Register::index2VirtReg(i) and Register::virtReg2Index() convert between the dense index (used to index arrays such as VirtRegMap) and the register. You have already seen this loop in RegAllocBase::seedLiveRegs:
for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
Register Reg = Register::index2VirtReg(i);
...
}
Sources: llvm/include/llvm/CodeGen/Register.h:43-94, llvm/lib/CodeGen/RegAllocBase.cpp:75-84
Physical registers already present before allocation
MIR before allocation is not purely virtual. Physical registers appear wherever the ABI or an instruction fixes them:
liveins: $w0, $w1, $w2
%1:gpr32 = COPY $w1 ; argument arrives in $w1
...
$w0 = COPY %4 ; return value must be in $w0
RET_ReallyLR implicit $w0
BL @g, csr_aarch64_aapcs, implicit-def dead $lr, ..., implicit-def $w0
The allocator must treat these as fixed: between $w0 = COPY %4 and the RET, nothing else may be put in $w0. Liveness of physical registers is tracked separately (see "Register Units" below and Liveness).
Register Classes
A register class is a set of physical registers that can all hold the same kind of value and are interchangeable as operands of some instructions. Every virtual register has exactly one class, written after the colon: %4:gpr32.
The class answers the allocator's first question: which physical registers may this value go in? AArch64 defines, among many others:
def GPR32common : RegisterClass<"AArch64", [i32], 32, (sequence "W%u", 0, 30)> {
let AltOrders = [(rotl GPR32common, 8)];
let AltOrderSelect = [{ return 1; }];
}
def GPR32 : RegisterClass<"AArch64", [i32], 32, (add GPR32common, WZR)> { ... }
def GPR32sp : RegisterClass<"AArch64", [i32], 32, (add GPR32common, WSP)> { ... }
def GPR32all : RegisterClass<"AArch64", [i32], 32, (add GPR32common, WZR, WSP)>;
| Class | Members | Used where |
|---|---|---|
GPR32common | w0–w30 | Intersection of the two below |
GPR32 | w0–w30, wzr | Most ALU operands (encoding 31 means zero register) |
GPR32sp | w0–w30, wsp | Operands where encoding 31 means stack pointer (e.g. add immediate) |
GPR32all | all of the above | Common super-class, used for copies |
GPR64common | x0–x28, fp, lr | 64-bit equivalent |
tcGPR64 | GPR64common minus x19–x28, fp, lr | Indirect tail call target: must not be callee-saved |
The reason for so many classes is encoding: register number 31 means wzr in some instructions and wsp in others. Each instruction operand names the class it accepts, and when one virtual register is used by several instructions its class must be in the intersection. That is why the coalescer sometimes changes a register to a sub-class such as gpr64common, as you can see in the loop example (%15:gpr64common).
Classes form a lattice
Classes are related by sub-class and super-class. GPR32common is a sub-class of both GPR32 and GPR32sp. TableGen computes these relations and generates helpers such as getCommonSubClass(A, B), which the coalescer and MachineRegisterInfo::constrainRegClass use to find a class that satisfies two constraints at once. If none exists, the two registers cannot be merged.
Allocation order
The class's member list is also the default allocation order: the order in which the allocator tries free registers. A class can supply alternatives with AltOrders and choose one with AltOrderSelect. All AArch64 GPR classes rotate their list by 8 and always select that rotation (return 1), so the order is w8, w9, ..., w30, w0, ..., w7. Argument registers w0–w7 are tried last, which leaves them free for calls. This is why allocated AArch64 code is full of w8, w9, w10:
renamable $x9 = COPY $xzr
renamable $w8 = COPY $wzr
...
renamable $w10 = LDRWroX renamable $x0, renamable $x9, 0, 1
The allocator does not use the raw order directly; RegisterClassInfo removes reserved registers and moves callee-saved registers to the end (they cost a save/restore the first time they are used). See Allocation Framework.
Sources: llvm/lib/Target/AArch64/AArch64RegisterInfo.td:189-261, llvm/include/llvm/Target/Target.td:292-376
Sub-registers
Many registers overlap. On AArch64, w0 is the low 32 bits of x0. TableGen describes this with sub-register indices:
def sub_32 : SubRegIndex<32>;
...
def W0 : AArch64Reg<0, "w0" >, DwarfRegNum<[0]>;
def X0 : AArch64Reg<0, "x0", [W0, W0_HI]>, DwarfRegAlias<W0>;
X0 lists its sub-registers W0 and W0_HI (the top half, which has no name in assembly but must exist so the halves can be tracked separately). In MIR, %15.sub_32 means "the low 32 bits of the 64-bit virtual register %15":
dead $wzr = SUBSWrr %15.sub_32, %5, implicit-def $nzcv
After allocation %15 became $x9, so %15.sub_32 was rewritten to $w9:
dead $wzr = SUBSWrr renamable $w9, renamable $w1, implicit-def $nzcv
Three MIR instructions exist only to manipulate sub-registers; you will see them in coalescer output:
| Instruction | Meaning |
|---|---|
%d = INSERT_SUBREG %src, %val, sub_32 | %d is %src with the sub_32 part replaced by %val |
%d = SUBREG_TO_REG 0, %val, sub_32 | %d's sub_32 part is %val, and the rest is known to be zero (AArch64 32-bit writes zero the top half) |
%d = REG_SEQUENCE %a, sub0, %b, sub1 | Build a register tuple from parts |
Lane masks. Each sub-register index has a LaneBitmask, a bit set describing which parts of the register it covers. When sub-register liveness is enabled for a target (enableSubRegLiveness()), liveness is tracked per lane, so a write to %x.sub_32 does not kill the other half. AArch64 defines the _hi indices precisely so that overlapping registers get distinct lane masks:
// The _hi SubRegIndexes describe the high bits of a register which are not
// separately addressable. They need to be described so that partially
// overlapping registers end up with a different lane mask. This is required
// to enable subreg liveness tracking.
Sources: llvm/lib/Target/AArch64/AArch64RegisterInfo.td:13-60, llvm/lib/Target/AArch64/AArch64RegisterInfo.td:101-168, llvm/include/llvm/Target/Target.td:108
Register Units
To decide whether two physical registers clash, the allocator must know if they share any bits. Asking "do x0 and w0 overlap?" for every pair would be slow, so TableGen splits each register into register units: the smallest pieces that are never shared in part. Two physical registers interfere exactly when they share a unit.
| Register | Units (illustrative) |
|---|---|
w0 | U0 |
W0_HI | U1 |
x0 | U0, U1 |
All physical liveness in LLVM's allocators is stored per unit, not per register. LiveIntervals keeps one live range per register unit (getRegUnit(Unit)), and LiveRegMatrix keeps one LiveIntervalUnion per unit. Assigning %v to x0 adds %v's interval to the unions for U0 and U1; checking whether w0 is free looks only at U0. This makes aliasing correct automatically.
The iterator MCRegUnitIterator (or TRI->regunits(Reg)) walks the units of a register, and MCRegAliasIterator walks every register that overlaps one (used, for example, in RegAllocBase::cleanupFailedVReg).
Reserved Registers
Some registers must never be handed out: the stack pointer, the zero register, the frame pointer when the function needs one, platform registers. The target lists them in TargetRegisterInfo::getReservedRegs, which returns a BitVector. RegAllocBase::init freezes this set at the start of allocation:
MRI->freezeReservedRegs();
RegClassInfo.runOnMachineFunction(vrm.getMachineFunction());
Reserved registers are removed from every allocation order, and their liveness is not tracked precisely (a reserved register is treated as always live). On AArch64, wzr/xzr are additionally marked isConstant = true in TableGen: they always read as zero, so writes to them are harmless and reads do not need a definition.
Classes that contain only unusable registers are marked isAllocatable = 0:
// SP/WSP are always reserved.
let isAllocatable = 0 in {
def GPR32sponly : RegisterClass<"AArch64", [i32], 32, (add WSP)>;
def GPR64sponly : RegisterClass<"AArch64", [i64], 64, (add SP)>;
}
Sources: llvm/lib/CodeGen/RegAllocBase.cpp:60-70, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:404, llvm/lib/Target/AArch64/AArch64RegisterInfo.td:225-229
Caller-saved and Callee-saved Registers
The calling convention splits the allocatable registers in two:
| Kind | Who preserves it across a call | AArch64 (AAPCS64) |
|---|---|---|
| Caller-saved (volatile, clobbered) | Nobody: a call may destroy it | x0–x18, v0–v7, v16–v31 |
| Callee-saved (non-volatile) | The called function saves and restores it if it uses it | x19–x28, fp, lr, d8–d15 |
def CSR_AArch64_AAPCS : CalleeSavedRegs<(add X19, X20, X21, X22, X23, X24,
X25, X26, X27, X28, LR, FP,
D8, D9, D10, D11,
D12, D13, D14, D15)>;
TableGen turns this into two things the allocator uses:
CSR_AArch64_AAPCS_SaveList: returned bygetCalleeSavedRegs; tells prologue/epilogue insertion what to save and tells the allocator which registers cost a save the first time.CSR_AArch64_AAPCS_RegMask: a bit mask returned bygetCallPreservedMask, attached to every call as an operand (csr_aarch64_aapcsinBL @g, csr_aarch64_aapcs, ...). A regmask operand says "this instruction clobbers every register not in the mask".
This is what makes the call example work. %1 holds %b across bl g. Every caller-saved register is clobbered by the regmask, so the only registers free for the whole of %1's life are callee-saved ones. The allocator picked w19, and prologue insertion saved x19 (together with x30):
stp x30, x19, [sp, #-16]! // 16-byte Folded Spill
mov w19, w1
bl g
add w0, w0, w19
ldp x30, x19, [sp], #16 // 16-byte Folded Reload
Despite the comment, the stp/ldp here are prologue/epilogue saves, not register allocator spills. Distinguishing the two is the first skill you need when reading allocated code; see Spilling and Splitting.
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:594-597, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:330, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:360
Operand Flags You Will See
| Flag | Meaning |
|---|---|
killed | Last use of the register; it is dead afterwards |
dead | A definition whose value is never read |
undef | A use whose value does not matter (no definition needed) |
implicit, implicit-def | Operand not written in the assembly syntax (e.g. $nzcv flags) |
early-clobber | The definition is written before all uses are read, so it may not share a register with any use |
renamable | After allocation: this physical register was chosen by the allocator and later passes may rename it |
tied (%d = ADD %d(tied-def 0), ...) | The definition must use the same register as that use; see Two-Address Lowering |
Liveness: Slot Indexes and Live Intervals
Relevant source files
The following files were used as context for generating this wiki page:
A register is live at a point in the program if the value it holds there may still be read later. Two registers interfere if they are live at the same point and hold different values; interfering registers cannot share a physical register. Everything the optimising allocators do is built on answering "where is this register live?" quickly and exactly.
Purpose and Scope
This page explains how LLVM numbers instructions (SlotIndexes), how it stores liveness (LiveRange, LiveInterval, VNInfo), how it computes it (LiveIntervals), and how passes keep it correct when they change code. The Fast allocator does not use any of this; it computes liveness on the fly within one block (see Fast Register Allocator).
A Picture First
Take the first example after coalescing. The numbers on the left are slot indexes (explained next):
32B %1:gpr32 = COPY $w1
48B %0:gpr32 = COPY $w0
64B %2:gpr32 = COPY $w2
80B %4:gpr32 = MADDWrrr %0, %1, %2
96B $w0 = COPY %4
112B RET_ReallyLR implicit $w0
Each virtual register is live from its definition to its last use:
32 48 64 80 96
%1 |=================)
%0 |============)
%2 |=======)
%4 |====)
%0, %1 and %2 are all live just before the MADD, so they need three different registers. %4 starts exactly where the other three end, so it may reuse any of them; that is how %4 and %0 both ended up in $w0.
Slot Indexes
Liveness needs a total order on program points, so that "is point A before point B?" and "do these two ranges overlap?" are just integer comparisons. SlotIndexes gives every instruction (and every block boundary) a number, laid out in function order.
Each instruction does not get one number but four, called slots, because one instruction has several moments where a register can start or stop being live:
enum Slot {
/// Basic block boundary. Used for live ranges entering and leaving a
/// block without being live in the layout neighbor. Also used as the
/// def slot of PHI-defs.
Slot_Block,
/// Early-clobber register use/def slot. ...
Slot_EarlyClobber,
/// Normal register use/def slot. Normal instructions kill and define
/// register at this slot.
Slot_Register,
/// Dead def kill point. Kill slot for a range of a register that is
/// defined and dead at the same instruction.
Slot_Dead,
Slot_Count
};
| Slot | Printed as | Used for |
|---|---|---|
Slot_Block | B | Start/end of a block; value live-in to a block; PHI definitions |
Slot_EarlyClobber | e | Definitions marked early-clobber (they must not overlap the instruction's uses) |
Slot_Register | r | Normal uses end here and normal definitions start here |
Slot_Dead | d | End of a definition that is never read |
Instructions are spaced InstrDist = 4 * Slot_Count = 16 apart, which is exactly what the dump shows: 32B, 48B, 64B, ... The spacing leaves gaps, so a pass can insert a new instruction between two others without renumbering the whole function. When a gap runs out, SlotIndexes::renumberIndexes renumbers locally.
Why the r slot works for both uses and definitions. A use ending at 80r and a definition starting at 80r do not overlap, because live ranges are half-open intervals [start, end). So in %4 = MADD %0, %1, %2, %0 dies at 80r and %4 begins at 80r, and they can share a register. An early-clobber definition starts at 80e, before 80r, so it does overlap the uses and must get a different register: that is the whole point of the flag.
Sources: llvm/include/llvm/CodeGen/SlotIndexes.h:70-115, llvm/lib/CodeGen/SlotIndexes.cpp:63, llvm/lib/CodeGen/SlotIndexes.cpp:170
Slot indexes in practice
| API | Returns |
|---|---|
Indexes->getInstructionIndex(MI) | The base index of MI (the number printed in the dump); call .getRegSlot(), .getDeadSlot(), .getBaseIndex() etc. on it to get a specific slot |
Indexes->getMBBStartIdx(MBB), getMBBEndIdx(MBB) | First index of the block and the index just after it |
Indexes->getInstructionFromIndex(Idx) | The instruction at an index, or null if it was deleted |
A < B, SlotIndex::isSameInstr(A, B) | Ordering and same-instruction tests |
Indexes->insertMachineInstrInMaps(MI) | Give a newly inserted instruction an index (the spiller does this) |
You can see the numbers with llc -print-after=<pass> for any pass that runs while SlotIndexes is alive (from the coalescer to the rewriter).
Live Ranges, Segments and Value Numbers
A LiveRange is a sorted list of segments, each [start, end) plus a value number. In the textual form LLVM prints in -debug-only=regalloc output (assertion builds only), %0 from the example above would be:
%0 [48r,80r:0) 0@48r
(Worked out by hand from the slot indexes in the dump; the release llc used for this wiki cannot print intervals.) Read this as: one segment from 48r to 80r holding value number 0, and value 0 is defined at 48r.
A value number (VNInfo) identifies one definition. After two-address lowering or PHI elimination a register can be defined several times, and liveness has to remember which definition reaches which point. For example, the loop counter after coalescing:
bb.0: %15 = COPY $xzr ; value 0
bb.1: %15 = ADDXri %15, 1, 0 ; value 1, reads value 0 or 1
Its interval (written by hand from this shape) looks like:
%15 [Ar,Bend:0)[bb1start,Xr:2)[Xr,bb1end:1) 0@Ar 1@Xr 2@bb1start-phi
Value 2 is a PHI-def: it is the value that is live at the top of bb.1, which is value 0 coming from bb.0 or value 1 coming round the loop. PHI-defs are defined at a B slot and are created by liveness computation automatically; they do not correspond to a PHI instruction.
Why value numbers matter to the allocator. Two registers may be live at the same point and still not interfere, if they hold the same value. The coalescer relies on this: after %b = COPY %a, %a and %b hold the same value until one of them is redefined, so they can be merged even if both are live. Value numbers are how it tells.
| Class | What it is |
|---|---|
LiveRange | Segments plus value numbers |
LiveRange::Segment | start, end, valno |
VNInfo | id and def (the SlotIndex of the definition); isPHIDef(), isUnused() |
LiveInterval | A LiveRange for one virtual register, plus its reg(), its spill weight(), and optional per-lane SubRanges |
LiveInterval::SubRange | A LiveRange for a subset of lanes (LaneMask), used with sub-register liveness |
Useful queries:
| Query | Meaning |
|---|---|
LI.liveAt(Idx) | Is the register live at Idx? |
LI.overlaps(Other) | Do two ranges share any point? |
LI.Query(Idx) (LiveQueryResult) | Value in, value out, is it killed here, is it defined here |
LI.getVNInfoAt(Idx) | Which definition is live at Idx |
LI.beginIndex(), LI.endIndex(), LI.getSize() | Extent; getSize() is used by Greedy's priority |
Computing Live Intervals
LiveIntervals is the analysis that builds an interval for every virtual register in use and a range for every physical register unit.
flowchart TD A["LiveIntervals::analyze"] --> B["computeVirtRegs<br/>one LiveInterval per vreg"] A --> C["computeRegMasks<br/>where calls clobber registers"] A --> D["computeLiveInRegUnits<br/>live-in ranges of physical register units"] D --> F["getRegUnit / computeRegUnitRange<br/>full range of one unit, computed on first request"] B --> E["computeVirtRegInterval<br/>LiveIntervalCalc: defs, then extend to every use"]
For each virtual register, computeVirtRegInterval creates a value number at every definition, then extends liveness backwards from every use until it reaches a definition. When it crosses into a block from several predecessors carrying different values, it creates a PHI-def at the block start. This is classic SSA-style liveness, done by LiveRangeCalc using the dominator tree.
Physical registers are handled per register unit. computeLiveInRegUnits creates the ranges for units that are live into blocks, and the full range of any unit is built by computeRegUnitRange the first time something calls getRegUnit(Unit) for it. Register masks are recorded separately (computeRegMasks): rather than adding a tiny dead segment for every clobbered unit at every call, LiveIntervals keeps a sorted list of call positions and their masks, and LiveRegMatrix::checkRegMaskInterference consults it. This is how %1 in the call example learns that it cannot be in any caller-saved register.
Sources: llvm/lib/CodeGen/LiveIntervals.cpp:159-250, llvm/lib/CodeGen/LiveIntervals.cpp:350-394
Keeping Liveness Up to Date
LiveIntervals is expensive to compute, so it is computed once (before the coalescer) and then updated by every pass up to and including the rewriter. Any code you write in that window that changes instructions must update it too, or the verifier will complain and the allocator will miscompile.
| You did | Call |
|---|---|
| Inserted an instruction | LIS->InsertMachineInstrInMaps(MI), then extend or create the affected intervals |
| Removed an instruction | LIS->RemoveMachineInstrFromMaps(MI) before erasing it |
| Moved an instruction within a block | LIS->handleMove(MI) |
| Removed some uses of a register | LIS->shrinkToUses(&LI) to trim the now-unneeded tail |
| Created a new virtual register | LIS->createAndComputeVirtRegInterval(Reg) |
| Made new uses that need liveness extended | LIS->extendToIndices(LR, Indices) |
| A register's interval fell into disconnected pieces | LIS->splitSeparateComponents(LI, NewIntervals) |
Inside the allocator most of these are done for you by LiveRangeEdit (see Spilling and Splitting).
Sources: llvm/lib/CodeGen/LiveIntervals.cpp:524-769, llvm/lib/CodeGen/LiveIntervals.cpp:1623, llvm/lib/CodeGen/LiveIntervals.cpp:1866
LiveVariables and Kill Flags
The older LiveVariables analysis runs earlier, on SSA MIR, and only sets killed and dead flags on operands. PHI elimination and two-address lowering use those flags. It is a historical leftover: the comment in addOptimizedRegAlloc says it can be removed once two-address lowering no longer needs kill flags. After allocation, LiveIntervals::addKillFlags puts kill flags back based on the final assignment.
Interference, Precisely
Putting this together, a virtual register V can be assigned physical register P only if, for every register unit U of P:
- no virtual register already assigned to a register containing
Uhas a live segment overlappingV's (checked inLiveRegMatrixwithLiveIntervalUnionqueries); - the fixed physical liveness of
U(arguments, return values, implicit defs) does not overlapV's; - no register mask inside
V's live range clobbersP.
Checks 1–3 are exactly LiveRegMatrix::checkInterference, covered on Allocation Framework.
Preparing Code for Allocation
Relevant source files
The following files were used as context for generating this wiki page:
The allocators expect code with no PHI instructions, with every tied-operand constraint already satisfied, and with as few COPYs as possible. Three passes produce that form: PHI elimination, two-address lowering and the register coalescer.
Purpose and Scope
This page gives the big picture and shows the same loop at each step. The details are on PHI Elimination and Two-Address Lowering and Register Coalescer.
The Idea: Add Copies, Then Remove Them
The first two passes make the code correct for allocation by adding COPY instructions, many of them unnecessary. The coalescer then removes every copy it can prove is safe to remove. This split keeps each pass simple: PHI elimination and two-address lowering never have to be clever, because the coalescer cleans up after them.
flowchart LR A["SSA MIR<br/>PHIs, tied operands unmet"] --> B["PHIElimination<br/>PHI becomes COPYs"] B --> C["TwoAddressInstruction<br/>tied operands get a COPY"] C --> D["RegisterCoalescer<br/>merge COPY source and destination"] D --> E["Allocator input<br/>few COPYs, long live ranges"]
One Loop, Three Snapshots
Source (after LoopStrengthReduce):
loop:
%lsr.iv = phi i64 [ %lsr.iv.next, %loop ], [ 0, %entry ]
%acc = phi i32 [ 0, %entry ], [ %acc.next, %loop ]
...
%acc.next = add i32 %acc, %v
%lsr.iv.next = add nuw nsw i64 %lsr.iv, 1
After two-address lowering (llc -mtriple=aarch64 -O2 -stop-after=twoaddressinstruction): the two PHIs are gone and there are sixteen COPYs (eight in bb.0, seven in bb.1, one in bb.2).
bb.0.entry:
%5:gpr32 = COPY killed $w1
%4:gpr64common = COPY killed $x0
%8:gpr32all = COPY $wzr
%7:gpr32all = COPY killed %8
%9:gpr64all = COPY $xzr
%6:gpr64all = COPY killed %9
%15:gpr64common = COPY killed %6
%16:gpr32 = COPY killed %7
bb.1.loop:
%1:gpr32 = COPY killed %16
%0:gpr64common = COPY killed %15
%10:gpr32 = LDRWroX %4, %0, 0, 1 :: (load (s32) from %ir.scevgep)
%11:gpr32 = ADDWrr killed %1, killed %10
%2:gpr32all = COPY killed %11
%12:gpr64sp = nuw nsw ADDXri killed %0, 1, 0
%3:gpr64all = COPY %12
%13:gpr32 = COPY killed %12.sub_32
dead $wzr = SUBSWrr killed %13, %5, implicit-def $nzcv
%15:gpr64common = COPY killed %3
%16:gpr32 = COPY %2
Bcc 3, %bb.1, implicit killed $nzcv
B %bb.2
bb.2.exit:
$w0 = COPY killed %2
RET_ReallyLR implicit killed $w0
Note that %15 and %16 are defined twice (once per predecessor): the code is no longer in SSA form.
After the coalescer (-stop-after=register-coalescer): only the copies that connect to physical registers are left.
bb.0.entry:
%5:gpr32 = COPY $w1
%4:gpr64common = COPY $x0
%15:gpr64common = COPY $xzr
%16:gpr32 = COPY $wzr
bb.1.loop:
%10:gpr32 = LDRWroX %4, %15, 0, 1 :: (load (s32) from %ir.scevgep)
%16:gpr32 = ADDWrr %16, %10
%15:gpr64common = nuw nsw ADDXri %15, 1, 0
dead $wzr = SUBSWrr %15.sub_32, %5, implicit-def $nzcv
Bcc 3, %bb.1, implicit killed $nzcv
B %bb.2
bb.2.exit:
$w0 = COPY %16
RET_ReallyLR implicit $w0
Each PHI's whole web of copies (%0, %3, %6, %9, %12, %15, and the 32-bit view %13) collapsed into a single register, %15, whose class was narrowed to the intersection gpr64common. The accumulator web became %16. The machine scheduler then moved the ADDWrr below the compare, which is the order you see in the allocated loop on AArch64 Walkthroughs.
After allocation:
- The copies of
$xzr/$wzrbecamemov x9, xzrandmov w8, wzr. - The copies from
$w1and$x0disappeared, because%5and%4were given$w1and$x0(hints from the copies). $w0 = COPY %16stayed, asmov w0, w8.%16cannot be given$w0: the pointer%4lives in$x0for the whole loop, andw0is the low half ofx0, so they share a register unit and interfere.
Why Not Let the Allocator Handle Copies?
Greedy does try to give both sides of a copy the same register (through hints), and the rewriter deletes copies that end up as $wN = COPY $wN. But hints are only preferences that can be broken under pressure, while coalescing is a guarantee made before allocation starts. The trade-off is that coalescing makes live ranges longer, which can make allocation harder; the coalescer therefore refuses some merges (see Register Coalescer), and Greedy can undo a merge later by splitting.
The Other Preparation Passes
| Pass | What it does to prepare |
|---|---|
ProcessImplicitDefs | Deletes IMPLICIT_DEFs and marks their uses undef, so undefined values do not occupy registers |
DetectDeadLanes | Marks sub-register lanes that are never read, so they do not extend liveness |
RenameIndependentSubregs | If a register's sub-register parts are never used together, gives each part its own register |
MachineScheduler | Reorders instructions within blocks; its pressure tracking tries to keep the number of simultaneously live values below the register count |
PHI Elimination and Two-Address Lowering
Relevant source files
The following files were used as context for generating this wiki page:
These two passes take SSA MIR out of SSA form. PHI elimination replaces each PHI with ordinary copies. Two-address lowering makes sure every instruction whose result must reuse an input register actually does. Both add COPYs and leave it to the coalescer to remove the unnecessary ones.
Purpose and Scope
This page explains what each pass produces, why, and which target hooks affect it. The SelectionDAG side of PHIs (how they are created) is not covered here.
PHI Elimination
The problem
A PHI picks a value depending on which predecessor block control came from:
bb.1.loop:
%0:gpr64all = PHI %6, %bb.0, %3, %bb.1
No CPU has such an instruction. The value has to be placed in one agreed register before control reaches bb.1, on every incoming edge.
What the pass does
For each PHI result %d, PHIEliminationImpl::LowerPHINode:
- creates a new virtual register
%t(the "incoming" register); - at the end of each predecessor (before its terminator), inserts
%t = COPY <value from that predecessor>; - replaces the
PHIwith%d = COPY %tat the top of the block; - updates
LiveVariableskill flags (andLiveIntervals, if it already exists).
In the loop from Preparing Code for Allocation, the result is exactly what the two-address dump shows:
bb.0.entry:
...
%15:gpr64common = COPY killed %6 ; incoming copy on edge bb.0 -> bb.1
%16:gpr32 = COPY killed %7
bb.1.loop:
%1:gpr32 = COPY killed %16 ; PHI replaced by a copy
%0:gpr64common = COPY killed %15
...
%15:gpr64common = COPY killed %3 ; incoming copy on edge bb.1 -> bb.1
%16:gpr32 = COPY %2
%15 and %16 now have two definitions each, one per incoming edge. This is the point where MIR stops being SSA.
Critical edges
If a predecessor has several successors and the PHI's block has several predecessors, the edge between them is critical. A copy placed at the end of the predecessor would also run on its other outgoing edges, extending a live range where it is not needed. PHIEliminationImpl::SplitPHIEdges may split such edges (insert a new block) so copies go only where they are needed. It uses MachineLoopInfo to decide, which is why addOptimizedRegAlloc adds MachineLoopInfo just before PHI elimination ("Edge splitting is smarter with machine loop info").
Target involvement
None directly. PHI elimination uses only target-independent COPYs; turning a COPY into a real move instruction happens much later through TargetInstrInfo::copyPhysReg (see TargetInstrInfo Hooks).
Sources: llvm/lib/CodeGen/PHIElimination.cpp:236, llvm/lib/CodeGen/PHIElimination.cpp:319, llvm/lib/CodeGen/PHIElimination.cpp:367, llvm/lib/CodeGen/PHIElimination.cpp:803, llvm/lib/CodeGen/TargetPassConfig.cpp:1513-1515
Two-Address Lowering
The problem: tied operands
Many instruction sets (x86 most famously, and some instructions on every target) have two-address instructions: the destination register must be the same as one of the sources. add eax, ebx computes eax = eax + ebx; there is no way to write the result elsewhere.
TableGen expresses this as a constraint on the instruction definition:
let Constraints = "$dst = $src1" in
def ADD32rr : ... (outs GR32:$dst), (ins GR32:$src1, GR32:$src2) ...
In SSA MIR, the result and the tied input are still different virtual registers, and the tie is shown with tied-def:
%2:gr32 = ADD32rr %0(tied-def 0), %1
On AArch64 this is rarer: most instructions are three-address. Tied operands appear on instructions such as MOVK (insert 16 bits into an existing register), BFM/BFI (bitfield insert), many NEON accumulate forms (MLA, FMLA) and SVE destructive operations.
What the pass does
The example below is illustrative (x86-style), not llc output. Given
%2 = ADD32rr %0(tied-def 0), %1
... %0 used later ...
the allocator cannot simply give %2 and %0 the same register, because %0 is still needed afterwards. Two-address lowering rewrites it to
%2 = COPY %0
%2 = ADD32rr %2(tied-def 0), %1
After this, the instruction reads and writes the same virtual register, the constraint holds by construction, and the code is no longer SSA (%2 has two definitions). This is the TiedOpsRewritten property printed in MIR dumps.
If %0 is killed at the instruction (not used afterwards), the copy is still inserted, but the coalescer will almost always remove it, because %0 and %2 do not overlap.
Avoiding the copy
Before falling back to a copy, TwoAddressInstructionImpl::tryInstructionTransform tries cheaper options:
| Trick | Function | Target hook it needs |
|---|---|---|
| Commute the instruction so the tied operand is a source that dies here | tryInstructionCommute, isProfitableToCommute | TargetInstrInfo::findCommutedOpIndices, commuteInstructionImpl (instruction marked isCommutable = 1) |
Convert to three-address form (e.g. x86 ADD to LEA) | convertInstTo3Addr | TargetInstrInfo::convertToThreeAddress (instruction marked isConvertibleToThreeAddress = 1) |
| Reschedule the instruction below the last use of the source, so the source dies at it | rescheduleMIBelowKill | none |
Then processTiedPairs inserts whatever copies are still needed.
What a backend needs to do
- Declare tied operands with
Constraints = "$dst = $src"in the instruction definition. Do not try to enforce the constraint yourself in instruction selection. - Mark commutable instructions
isCommutable = 1. If the commutable operands are not simply operands 1 and 2, overridefindCommutedOpIndices. - If your target has a three-address equivalent for some two-address instruction, set
isConvertibleToThreeAddress = 1and implementconvertToThreeAddress. - Use
@earlyclobber $dst(in theConstraintsstring) for results that must not share a register with any input. This is the opposite constraint and is handled by liveness, not by this pass (see Liveness).
Sources: llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:647, llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:800, llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:927, llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:1284, llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:1349, llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:1592, llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:1878, llvm/include/llvm/CodeGen/TargetInstrInfo.h:235, llvm/include/llvm/CodeGen/TargetInstrInfo.h:519, llvm/include/llvm/CodeGen/TargetInstrInfo.h:569
Summary
| PHI elimination | Two-address lowering | |
|---|---|---|
| Input | SSA MIR with PHIs | SSA MIR with tied operands |
| Output | COPYs on incoming edges; registers with several definitions | Tied def and use are the same register; COPY before the instruction when needed |
| Ends SSA? | Yes | Yes |
| Target hooks | None | Commute, convert-to-three-address |
| Cleaned up by | Register coalescer | Register coalescer |
Register Coalescer
Relevant source files
The following files were used as context for generating this wiki page:
The register coalescer removes COPY instructions by merging ("joining") the source and destination registers into one register. After a successful join, the copy becomes an identity copy and is deleted. It is the pass that cleans up after PHI elimination and two-address lowering.
Purpose and Scope
This page explains when two registers can be joined, the order the coalescer works in, the special cases (physical registers, rematerialisation, sub-registers), and the hook a target can use to veto a join.
The Basic Rule
Given
%b = COPY %a
%a and %b can be merged if their live intervals do not interfere, where "interfere" means live at the same point with different values. Right after the copy both are live, but they hold the same value, so that overlap does not count. This is why value numbers (see Liveness) are essential: the coalescer compares value numbers, not just segments.
If the join succeeds:
- every operand that names
%bis rewritten to%a(or the other way round); - the two live intervals are merged into one, and their value numbers combined;
- the register class becomes the common sub-class of the two (for example
gpr64allandgpr64spjoin togpr64commonin the loop example); - the copy, now
%a = COPY %a, is erased.
If the two classes have no common sub-class, or the merged interval would have conflicting values somewhere, the join fails and the copy stays.
Order of Work
flowchart TD
A["RegisterCoalescer::run"] --> B["joinAllIntervals"]
B --> C["copyCoalesceInMBB for each block<br/>blocks ordered by loop depth, deepest first"]
C --> D["copyCoalesceWorkList"]
D --> E["joinCopy(copy)"]
E --> F{"Kind of copy"}
F -->|"vreg = COPY vreg"| G["joinIntervals: compare value numbers,<br/>resolve conflicts, merge"]
F -->|"vreg = COPY physreg<br/>or physreg = COPY vreg"| H["joinReservedPhysReg or<br/>physreg join (strict rules)"]
F -->|"source def is cheap"| I["reMaterializeDef:<br/>duplicate the def instead"]
E --> J["failed copies retried<br/>after other joins"]
In detail, joinAllIntervals:
- sorts the blocks by loop depth (
MBBPriorityInfo, usingMachineLoopInfo::getLoopDepth), so copies in deeper loops are tried first. Removing a copy that runs a million times matters more than one that runs once; - in each block, collects the copy-like instructions top-down, so that coalescing and rematerialisation propagate forward;
- keeps copies whose registers live only in one block (local copies) on a separate
LocalWorkList, joined when the walk moves to a shallower loop depth; - moves copies that match the terminal rule (
-terminal-rule) to the end of the list, so they do not block better joins; - finally re-runs
copyCoalesceWorkListon everything that failed, in a loop, until no more copies join. A later join can make an earlier one possible.
// Joining intervals can allow other intervals to be joined. Iteratively join
// until we make no progress.
while (copyCoalesceWorkList(WorkList))
/* empty */;
Sources: llvm/lib/CodeGen/RegisterCoalescer.cpp:4196-4290, llvm/lib/CodeGen/RegisterCoalescer.cpp:4103, llvm/lib/CodeGen/RegisterCoalescer.cpp:2053
Copies Involving Physical Registers
Joining a virtual register with a physical register (for example %4:gpr64common = COPY $x0) would pin the virtual register to that physical register for its whole life, before the allocator has seen anything. That is usually a bad idea, so the coalescer is very conservative:
- Copies to and from non-reserved physical registers are generally left alone. Instead, the copy becomes a hint: the allocator later prefers
$x0for%4, and if it gets it, the rewriter deletes the copy. This is what happened to everyCOPY $wNin the examples. - Copies involving reserved or constant registers (
$wzr,$xzr) are handled byjoinReservedPhysReg, under strict conditions.
That is why the coalesced loop still contains %15 = COPY $xzr and $w0 = COPY %16: they are not failures, they are hints waiting for the allocator.
Rematerialisation Instead of a Copy
If the source of a copy is defined by a cheap instruction with no inputs that might change (a constant move, for example), it can be cheaper to recompute the value directly into the destination than to keep both registers alive:
%a = MOVi32imm 42
... ; many instructions
%b = COPY %a
becomes
%a = MOVi32imm 42
...
%b = MOVi32imm 42
and %a may then die early. This is RegisterCoalescer::reMaterializeDef. It relies on the target marking such instructions rematerialisable (isReMaterializable = 1 in TableGen, and TargetInstrInfo::isReMaterializableImpl / reMaterialize; see TargetInstrInfo Hooks).
Sources: llvm/lib/CodeGen/RegisterCoalescer.cpp:1297
Other Tricks
| Function | What it does |
|---|---|
adjustCopiesBackFrom | When a value is copied back to where it came from (%b = COPY %a ... %a = COPY %b), extend %a's range so the second copy becomes an identity copy |
removeCopyByCommutingDef | If commuting the instruction that defines the copy's source makes the copy redundant, commute it |
Sources: llvm/lib/CodeGen/RegisterCoalescer.cpp:628
Sub-register Copies
A copy can read or write part of a register:
%13:gpr32 = COPY killed %12.sub_32
Joining %13 into %12 means rewriting every use of %13 as %12.sub_32. The coalescer does this when a register class exists that supports the sub-register index (TableGen generates getMatchingSuperRegClass for this). In the loop example that is exactly what produced SUBSWrr %15.sub_32, %5 after coalescing. With sub-register liveness enabled, these joins are done per lane, which allows more of them.
Why Joining Can Hurt
Merging makes one long live range out of two short ones. A long range interferes with more things and is harder to allocate. In extreme cases, aggressive coalescing turns a function that allocates without spills into one that spills. LLVM limits the damage in three ways:
- it does not join with non-reserved physical registers (it hints instead);
- a target can veto joins with
TargetRegisterInfo::shouldCoalesce; - Greedy can split a joined range again if it does not fit (see Live Range Splitting). Coalescing first and splitting later is the overall design.
Target Hook: shouldCoalesce
virtual bool shouldCoalesce(MachineInstr *MI,
const TargetRegisterClass *SrcRC,
unsigned SubReg,
const TargetRegisterClass *DstRC,
unsigned DstSubReg,
const TargetRegisterClass *NewRC,
LiveIntervals &LIS) const;
joinCopy calls this before joining two virtual registers (RegisterCoalescer.cpp:2079). SrcRC and DstRC are the classes of the two registers, and NewRC is the class the merged register would have. Returning false keeps the copy. Typical reasons a target overrides it:
- the merged class
NewRCis much smaller than the original classes (e.g. joining would force a value into a tiny class of registers that support some special instruction); - the merged register would be a very wide tuple of registers, which is hard to allocate.
The default returns true. Most targets never override it.
Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:1038-1046, llvm/lib/CodeGen/RegisterCoalescer.cpp:2079, llvm/lib/CodeGen/RegisterCoalescer.cpp:78
Useful Options
| Option | Effect |
|---|---|
-join-liveintervals=false | Disable coalescing entirely; useful to check whether a problem comes from the coalescer |
-stop-before=register-coalescer, -stop-after=register-coalescer | Snapshot MIR on either side of the pass |
-run-pass=register-coalescer | Run only this pass on a .mir file (write a test for a coalescing bug this way) |
Allocation Framework
Relevant source files
The following files were used as context for generating this wiki page:
Basic, Greedy and PBQP do not edit instructions while they decide. They record decisions in a few shared data structures and leave the editing to the rewriter. Basic and Greedy also share the same main loop. Learning these pieces once makes every allocator easier to read.
Purpose and Scope
This page covers the four shared structures (VirtRegMap, LiveRegMatrix, RegisterClassInfo, AllocationOrder) and the RegAllocBase driver loop. The Fast allocator uses none of them (see Fast Register Allocator).
The Big Picture
flowchart LR LIS["LiveIntervals<br/>where each vreg is live"] --> RA["Allocator<br/>selectOrSplit"] RCI["RegisterClassInfo<br/>usable registers per class"] --> AO["AllocationOrder<br/>hints first, then class order"] AO --> RA RA -->|"checkInterference"| LRM["LiveRegMatrix<br/>what is assigned to each reg unit"] RA -->|"assign / unassign"| LRM LRM --> VRM["VirtRegMap<br/>vreg to physreg or stack slot"] VRM --> RW["VirtRegRewriter<br/>edits the instructions"]
VirtRegMap: The Decision Record
VirtRegMap is two arrays indexed by virtual register:
| Query or update | Meaning |
|---|---|
assignVirt2Phys(V, P), getPhys(V), hasPhys(V), clearVirt(V) | Virtual to physical register |
assignVirt2StackSlot(V), createSpillSlot(RC), getStackSlot(V) | Virtual register to spill slot (a frame index) |
hasPreferredPhys(V), hasKnownPreference(V) | Whether V has a physical-register hint, and whether that hint is satisfied |
getOriginal(V), setIsSplitFromReg(V, Orig) | After splitting, which register a piece came from |
Allocators never write MachineOperands directly. Unassigning (for eviction) is just clearing an entry, which is why eviction is cheap.
Sources: llvm/lib/CodeGen/VirtRegMap.cpp:92-150
LiveRegMatrix: Who Is Using Each Register
LiveRegMatrix answers "if I put V in P, what does it collide with?" It keeps one LiveIntervalUnion per register unit. A union is a sorted map from slot ranges to the virtual registers currently assigned there.
Assigning records the decision in VirtRegMap, then adds V's segments to the union of every unit of P:
void LiveRegMatrix::assign(const LiveInterval &VirtReg, MCRegister PhysReg) {
...
VRM->assignVirt2Phys(VirtReg.reg(), PhysReg);
foreachUnit(
TRI, VirtReg, PhysReg, [&](MCRegUnit Unit, const LiveRange &Range) {
...
Matrix[Unit].unify(VirtReg, Range);
return false;
});
...
}
unassign does the reverse with extract. Greedy calls it to evict a register.
Checking runs three tests, cheapest first, and reports which one failed:
LiveRegMatrix::InterferenceKind
LiveRegMatrix::checkInterference(const LiveInterval &VirtReg,
MCRegister PhysReg) {
if (VirtReg.empty())
return IK_Free;
// Regmask interference is the fastest check.
if (checkRegMaskInterference(VirtReg, PhysReg))
return IK_RegMask;
// Check for fixed interference.
if (checkRegUnitInterference(VirtReg, PhysReg))
return IK_RegUnit;
// Check the matrix for virtual register interference.
bool Interference = foreachUnit(TRI, VirtReg, PhysReg,
[&](MCRegUnit Unit, const LiveRange &LR) {
return query(LR, Unit).checkInterference();
});
if (Interference)
return IK_VirtReg;
return IK_Free;
}
| Result | Meaning | Can the allocator fix it? |
|---|---|---|
IK_Free | P is free for all of V | Assign it |
IK_RegMask | A call inside V's range clobbers P | No. Try another register, or split around the call |
IK_RegUnit | Fixed physical liveness overlaps (an argument, a return value, an implicit-def) | No. Same as above |
IK_VirtReg | Another virtual register already sits in P | Yes, by evicting it (Greedy) or spilling it (Basic) |
The difference between the last two rows matters. Only IK_VirtReg interference can be removed by evicting someone. query(LR, Unit) returns a LiveIntervalUnion::Query, which can also list the interfering virtual registers: Q.interferingVRegs() returns them (it calls collectInterferingVRegs() to fill the InterferingVRegs list). That list is what eviction and Basic's spilling work from.
Sources: llvm/lib/CodeGen/LiveRegMatrix.cpp:113-160, llvm/lib/CodeGen/LiveRegMatrix.cpp:195-225, llvm/include/llvm/CodeGen/LiveIntervalUnion.h:122-130
RegisterClassInfo: The Usable Order
The register class in TableGen lists all its members, including reserved ones. RegisterClassInfo::compute turns that raw list into the order the allocator actually uses, once per class per function:
- Start from
TRI->getRawAllocationOrder(RC, MF): the class members, or theAltOrdersentry chosen byAltOrderSelect. - Drop reserved registers (
Reserved.test(PhysReg)). - Move callee-saved registers to the end, keeping the target's order otherwise. A callee-saved register costs a save and restore in the prologue and epilogue the first time it is used, so volatile registers are tried first.
- Record the minimum cost (from TableGen
CostPerUse) and whether the class is a proper sub-class of a larger legal class (getLargestLegalSuperClass). Greedy uses that flag to decide whether a split piece could move to a larger class.
if (getLastCalleeSavedAlias(PhysReg) && ...)
// PhysReg aliases a CSR, save it for later.
CSRAlias.push_back(PhysReg);
else {
...
RCI.Order[N++] = PhysReg;
}
...
// CSR aliases go after the volatile registers, preserve the target's order.
for (unsigned PhysReg : CSRAlias) {
For AArch64 GPR32 this gives roughly w8 … w18, w0 … w7, w19 … w30: the rotated order with reserved registers removed and callee-saved registers last. This is why ordinary temporaries land in w8, w9, w10, and why w19 shows up only when a value lives across a call. The exact list depends on the function, because reserved registers do (for example w18 on platforms that reserve it, or fp when a frame pointer is needed).
-stress-regalloc=N cuts every class to its first N registers. It is a useful way to force spills in small tests.
Sources: llvm/lib/CodeGen/RegisterClassInfo.cpp:186-258, llvm/lib/CodeGen/RegisterClassInfo.cpp:37
AllocationOrder: Hints First
When the allocator considers one virtual register, it builds an AllocationOrder:
AllocationOrder AllocationOrder::create(Register VirtReg, const VirtRegMap &VRM,
const RegisterClassInfo &RegClassInfo,
const LiveRegMatrix *Matrix) {
...
auto Order = RegClassInfo.getOrder(MF.getRegInfo().getRegClass(VirtReg));
SmallVector<MCPhysReg, 16> Hints;
bool HardHints =
TRI->getRegAllocationHints(VirtReg, Order, Hints, MF, &VRM, Matrix);
Iterating it yields the hints first, then the rest of the class order with the hints skipped. If getRegAllocationHints returns true (hard hints), only the hints are tried.
Hints come from two places:
- Copies to and from physical registers.
%0 = COPY $w0hints%0toward$w0. The coalescer leaves such copies in place and the spill-weight pass records them (see Spill Weights). That is how%0and%4in the first example both got$w0. - The target, by overriding
TargetRegisterInfo::getRegAllocationHints. Use this for constraints like "these two registers should form an even/odd pair" (see TargetRegisterInfo Hooks).
Sources: llvm/lib/CodeGen/AllocationOrder.cpp:29-46, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:839
RegAllocBase: The Shared Loop
Basic and Greedy derive from RegAllocBase. The base class provides the loop, and each allocator provides four virtual functions:
| Virtual | Basic | Greedy |
|---|---|---|
enqueueImpl(LI) | Push into a priority queue ordered by spill weight | Push with a priority from getPriority (see Greedy) |
dequeue() | Pop the heaviest | Pop the highest priority |
selectOrSplit(LI, NewVRegs) | Assign, or spill whatever is lighter | Assign, evict, split, or spill |
spiller() | InlineSpiller | InlineSpiller |
The loop:
void RegAllocBase::allocatePhysRegs() {
seedLiveRegs();
// Continue assigning vregs one at a time to available physical registers.
while (const LiveInterval *VirtReg = dequeue()) {
...
VirtRegVec SplitVRegs;
MCRegister AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
if (AvailablePhysReg == ~0u) {
// selectOrSplit failed to find a register!
...
AvailablePhysReg = getErrorAssignment(*RC, MI);
cleanupFailedVReg(VirtReg->reg(), AvailablePhysReg, SplitVRegs);
} else if (AvailablePhysReg)
Matrix->assign(*VirtReg, AvailablePhysReg);
for (Register Reg : SplitVRegs) {
...
enqueue(SplitVirtReg);
}
}
}
selectOrSplit returns one of three things:
| Return value | Meaning | What the loop does |
|---|---|---|
| A physical register | Assign VirtReg to it | Matrix->assign |
0 (no register) | VirtReg was split, spilled or deferred; the new or requeued intervals are in NewVRegs | Queue every register in NewVRegs |
~0u | Nothing worked | Report "ran out of registers", force an assignment so compilation can continue |
The ~0u case almost always means impossible constraints: inline assembly that asks for more registers than exist, or a register class with no allocatable members. getErrorAssignment prints the familiar error: ran out of registers during register allocation (or the inline-asm variant). The function is then rewritten so it still passes the verifier, but the output is not meaningful.
seedLiveRegs queues every virtual register that has non-debug uses. postOptimization runs after the loop and lets the spiller hoist spills and delete instructions that became dead after rematerialisation.
Sources: llvm/lib/CodeGen/RegAllocBase.cpp:60-168, llvm/lib/CodeGen/RegAllocBase.cpp:170-218, llvm/lib/CodeGen/RegAllocBase.cpp:249-252, llvm/lib/CodeGen/RegAllocBasic.h:27-50
Filtering Which Registers an Allocator Handles
Every allocator constructor accepts a RegAllocFilterFunc, and RegAllocBase::enqueue skips registers the filter rejects (shouldAllocateRegister). A target can use this to run the allocator twice: once for one register class, then again for the rest. AMDGPU does this to allocate scalar and vector registers in separate passes. Most targets do not need it.
Sources: llvm/lib/CodeGen/RegAllocBase.cpp:199-214, llvm/lib/CodeGen/RegAllocGreedy.cpp:337, llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp:214-365
The Register Allocators
Relevant source files
The following files were used as context for generating this wiki page:
LLVM ships four register allocators. They all produce the same kind of result (every virtual register in a physical register or a stack slot), but they differ in how much they look at before deciding, and so in compile time and code quality.
Purpose and Scope
This page compares the four and explains how one is chosen. Each has its own page.
Side by Side
| Fast | Basic | Greedy | PBQP | |
|---|---|---|---|---|
-regalloc= | fast | basic | greedy | pbqp |
| Default for | -O0 | nothing | -O1 and above | nothing |
| Unit of work | One instruction, one block at a time | One whole live interval | One live interval, or a piece of one | The whole function at once |
Uses LiveIntervals | No | Yes | Yes | Yes |
Uses LiveRegMatrix, VirtRegMap | No | Yes | Yes | VirtRegMap only |
| Pipeline | Unoptimised (no coalescer, no scheduler) | Optimised | Optimised | Optimised |
| On conflict | Spill a value currently in a register | Spill lighter interference, else spill itself | Evict, split, then spill | Solver picks "spill" for some nodes |
| Splitting | No | No | Yes (region, block, local, instruction) | No |
| Writes physical registers into instructions | Itself | VirtRegRewriter | VirtRegRewriter | VirtRegRewriter |
| Compile time | Lowest | Low | Medium | Highest |
Measured on One Example
The 24-load spill test from the walkthroughs, compiled with llc -mtriple=aarch64 -O2 -regalloc=X (counts from the assembly; "save/spill/reload lines" includes the 12 prologue/epilogue lines that save callee-saved registers):
| Allocator | Instructions | Save/spill/reload lines |
|---|---|---|
fast | 86 | 35 |
basic | 83 | 32 |
greedy | 83 | 32 |
pbqp | 82 | 31 |
This is a straight-line function, so there is nothing to split and the optimising allocators are almost the same. -regalloc=fast at -O2 also runs the unoptimised pipeline, which is part of why it is slightly worse. Differences become large in code with loops and calls, where Greedy's splitting keeps hot paths in registers.
How the Allocator Is Chosen
flowchart TD
A{"-regalloc= given?"} -->|"yes"| B["use it;<br/>optimised pipeline unless it is fast"]
A -->|"no"| C{"opt level -O0?"}
C -->|"yes"| D["createTargetRegisterAllocator(false)<br/>default: Fast"]
C -->|"no"| E["createTargetRegisterAllocator(true)<br/>default: Greedy"]
A target can override createTargetRegisterAllocator to pick a different default, or override addRegAssignAndRewriteOptimized / addRegAssignAndRewriteFast to run several allocators in sequence (AMDGPU does this with register filters). See Pass Pipeline Hooks.
Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1393-1473
Reading Order
Fast Register Allocator
Relevant source files
The following files were used as context for generating this wiki page:
The Fast allocator is the default at -O0. It makes one pass over each basic block, from the last instruction to the first, assigning physical registers as it meets uses and definitions. It never computes live intervals. Any value that may cross a block boundary lives in a stack slot between blocks. The result is quick to produce and easy to debug, but slow to run.
Purpose and Scope
This page explains the Fast algorithm, what its output looks like, and why a new backend usually gets it working first. It is the simplest allocator to read and a good first step before Greedy.
Why It Exists
- Compile time.
-O0builds want speed. Fast is roughly linear in the size of the function and needs noLiveIntervals, no coalescer and no scheduler: the pipeline is just PHI elimination, two-address lowering and Fast (see Pipeline). - Debuggability. Because values are stored to their stack slot between blocks, a debugger can usually find every variable in memory.
- Bring-up. A new backend can run
-O0code as soon as it can copy, spill and reload a register. Liveness, coalescing and splitting hooks are not needed yet.
The Algorithm
flowchart TD A["runOnMachineFunction"] --> B["for each block: allocateBasicBlock"] B --> C["mark live-out physregs as pre-assigned"] C --> D["walk instructions in reverse<br/>allocateInstruction"] D --> E["defs: free the register;<br/>if the value may live out, store it to its slot after the def"] D --> F["uses: if no register yet, pick one now<br/>(this is the value's last use, seen first)"] D --> G["at the block top: reloadAtBegin<br/>load every value still live-in from its slot"] G --> H["erase coalesced copies"]
Walking backwards is the key idea. Coming from the bottom, the first time the allocator sees a virtual register is at its last use, so it knows exactly when the register becomes free: at its definition, further up. No liveness analysis is needed within the block.
// Traverse block in reverse order allocating instructions one by one.
for (MachineInstr &MI : reverse(MBB)) {
...
allocateInstruction(MI);
...
}
...
// Spill all physical registers holding virtual registers now.
LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
reloadAtBegin(MBB);
For each instruction, allocateInstruction:
- handles definitions first: the register that holds the value becomes free above this point (
defineVirtReg,definePhysReg); - handles uses: a virtual register that has no register yet gets one now (
useVirtReg,allocVirtReg), choosing a free register from the class order, or displacing another value and reloading it later; - respects regmasks on calls: every clobbered register must be free across the call, so values live across a call are moved out of caller-saved registers.
Sources: llvm/lib/CodeGen/RegAllocFast.cpp:1794-1853, llvm/lib/CodeGen/RegAllocFast.cpp:1467
Values That Cross Blocks
Fast keeps no state between blocks. Every value that might be read in another block is stored to a stack slot right after its definition and reloaded at the top of each block that uses it.
The decision is made by mayLiveOut. It is conservative and cheap: a register is treated as crossing blocks if any of its first 8 uses is in another block, or if the block loops back to itself and the use is not dominated by the definition:
// See if the first \p Limit uses of the register are all in the current
// block.
static const unsigned Limit = 8;
unsigned C = 0;
for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
if (UseInst.getParent() != MBB || ++C >= Limit) {
MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
...
defineVirtReg then places the store just after the definition:
if (LRI->Reloaded || LRI->LiveOut) {
if (!MI.isImplicitDef()) {
MachineBasicBlock::iterator SpillBefore =
std::next((MachineBasicBlock::iterator)MI.getIterator());
...
spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
and reloadAtBegin loads, at the start of the block, every virtual register still recorded as live when the backwards walk reaches the top.
This is why -O0 code is full of str/ldr to the stack around branches. It is the expected behaviour, not a bug.
Sources: llvm/lib/CodeGen/RegAllocFast.cpp:530-598, llvm/lib/CodeGen/RegAllocFast.cpp:703-741, llvm/lib/CodeGen/RegAllocFast.cpp:1093-1158
Copies and Hints
There is no coalescer at -O0, but Fast does cheap coalescing on its own. When choosing a register for a value defined by a full COPY, it follows the copy chain (traceCopies, traceCopyChain) and prefers the register on the other side. If both sides end up in the same register, the copy is added to Coalesced and erased at the end of the block.
Example
The first example at -O0 (llc -mtriple=aarch64 -O0 -stop-before=regallocfast). There is no combiner at this level, so the multiply and add stay separate:
bb.1 (%ir-block.0):
liveins: $w0, $w1, $w2
%0:gpr32 = COPY $w0
%1:gpr32 = COPY $w1
%2:gpr32 = COPY $w2
%3:gpr32 = MADDWrrr %0, %1, $wzr
%4:gpr32 = ADDWrr %3, %2
$w0 = COPY %4
RET_ReallyLR implicit $w0
After -stop-after=regallocfast:
bb.1 (%ir-block.0):
liveins: $w0, $w1, $w2
renamable $w8 = MADDWrrr killed renamable $w0, killed renamable $w1, $wzr
renamable $w0 = ADDWrr killed renamable $w8, killed renamable $w2
RET_ReallyLR implicit killed $w0
Reading it bottom-up, as the allocator did:
$w0 = COPY %4:%4should be$w0, so%4is given$w0and the copy is coalesced away.%4 = ADDWrr %3, %2:%3needs a register. It is defined byMADDWrrr, not by a copy, so it has no hint, and Fast takes the first free register in the allocation order, which on AArch64 starts atw8(see Allocation order).%2traces back through its copy to$w2.%0,%1trace back to$w0and$w1, so all three argument copies vanish.
The function is a single block, so there are no slot stores. Add a branch and you will see them.
Using Fast on a New Backend
Fast needs only:
| Hook | Why |
|---|---|
Register classes and getReservedRegs | To know what it may use |
getCalleeSavedRegs, getCallPreservedMask | Regmasks on calls |
TargetInstrInfo::copyPhysReg | Turning COPY into a real move |
TargetInstrInfo::storeRegToStackSlot, loadRegFromStackSlot | Spills and reloads |
TargetRegisterInfo::eliminateFrameIndex | Turning the slot frame index into an address, later in prologue/epilogue insertion |
So the usual bring-up order is: get -O0 working with Fast first, then turn on -O2 and Greedy. See the checklist.
Sources: llvm/lib/CodeGen/RegAllocFast.cpp:891-932, llvm/include/llvm/CodeGen/TargetInstrInfo.h:1087, llvm/include/llvm/CodeGen/TargetInstrInfo.h:1199-1219
Basic Register Allocator
Relevant source files
The following files were used as context for generating this wiki page:
The Basic allocator is the smallest complete user of the allocation framework. It allocates whole live intervals in order of spill weight, heaviest first. When a register is not free, it spills either the cheaper interfering intervals or the current one. It never splits. It is not used by default anywhere, but it is the best code to read before Greedy.
Purpose and Scope
This page walks through the whole of RABasic::selectOrSplit, about fifty lines, and explains what Greedy adds on top.
Queue Order
Basic's queue is a std::priority_queue ordered by spill weight, with the register number as a tie-break:
struct CompSpillWeight {
bool operator()(const LiveInterval *A, const LiveInterval *B) const {
return std::tuple(A->weight(), A->reg()) <
std::tuple(B->weight(), B->reg());
}
};
The most expensive-to-spill intervals are allocated first, so they get the first choice of registers. Spill weight is roughly "how often this register is used, scaled by how often each use's block runs (block frequency), divided by its length".
Sources: llvm/lib/CodeGen/RegAllocBasic.h:27-50
selectOrSplit, Step by Step
flowchart TD
A["dequeue heaviest interval V"] --> B["for each P in AllocationOrder"]
B -->|"IK_Free"| C["return P"]
B -->|"IK_VirtReg"| D["remember P as spill candidate"]
B -->|"IK_RegMask / IK_RegUnit"| B
D --> E["for each candidate P:<br/>are all interferences spillable<br/>and lighter than V?"]
E -->|"yes"| F["unassign and spill them;<br/>return P"]
E -->|"no candidate works"| G{"V spillable?"}
G -->|"yes"| H["spill V; return 0"]
G -->|"no"| I["return ~0u (error)"]
1. Look for a free register
auto Order =
AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
for (MCRegister PhysReg : Order) {
switch (Matrix->checkInterference(VirtReg, PhysReg)) {
case LiveRegMatrix::IK_Free:
// PhysReg is available, allocate it.
return PhysReg;
case LiveRegMatrix::IK_VirtReg:
// Only virtual registers in the way, we may be able to spill them.
PhysRegSpillCands.push_back(PhysReg);
continue;
default:
// RegMask or RegUnit interference.
continue;
}
}
Hints come first in Order, so if the hinted register is free it wins. Registers blocked by calls (IK_RegMask) or fixed physical liveness (IK_RegUnit) are skipped for good. Registers blocked only by other virtual registers are remembered.
2. Try to spill something cheaper
For each remembered register, spillInterferences collects every virtual register occupying any of its units. It gives up on that register if any of them is not spillable, or is heavier than the current interval:
for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit);
for (const auto *Intf : reverse(Q.interferingVRegs())) {
if (!Intf->isSpillable() || Intf->weight() > VirtReg.weight())
return false;
Intfs.push_back(Intf);
}
}
Otherwise it unassigns each one from the matrix and calls spiller().spill(LRE). The spiller creates small new intervals around each use and reload. They go into SplitVRegs and the base loop puts them back in the queue.
Because the queue pops the heaviest interval first, every interval assigned earlier was at least as heavy as the current one at the time it was dequeued. Step 2 therefore fires mostly for intervals that join the queue later, such as the short reload intervals the spiller creates. They are tiny, so their weight (uses divided by length) is high, and they can push aside a long, lightly used interval that was assigned earlier.
3. Spill the current interval
If nothing could be freed, the current interval is spilled itself and 0 is returned, meaning "nothing to assign this round". If it is not spillable (for example it is already a tiny reload interval), ~0u is returned and RegAllocBase reports that it ran out of registers.
Sources: llvm/lib/CodeGen/RegAllocBasic.cpp:121-218
What Basic Does Not Do
| Missing feature | Effect | Greedy's answer |
|---|---|---|
| Splitting | A long interval that conflicts in one small place is spilled everywhere | Region, block and local splitting |
| Eviction for reassignment | An interfering interval is spilled, never moved to another free register | Evicted intervals are requeued and may find another register |
| Callee-saved cost | No special treatment of the first use of a callee-saved register | CSRCost, tryAssignCSRFirstTime |
| Hint repair | Broken copy hints stay broken | tryHintsRecoloring |
On the 24-load spill test from the walkthroughs, Basic and Greedy happen to produce code of the same size (32 spill/reload/save lines, 83 instructions). The difference shows up in larger functions with loops, where splitting matters.
When to Use It
- As a reference while reading Greedy.
- To check whether a miscompile is caused by Greedy's heuristics:
llc -regalloc=basic. If the bug disappears, the problem is likely in Greedy-specific logic (eviction, splitting). - As a simple template if you ever write your own allocator on top of
RegAllocBase.
Greedy Register Allocator
Relevant source files
The following files were used as context for generating this wiki page:
Greedy is LLVM's default allocator whenever optimisation is on. It uses the same priority-queue loop as Basic, but when a register is not free it has more options than spilling: it can evict a less important interval (which goes back in the queue), split the interval into pieces that each fit somewhere, and only as a last resort spill. Each interval moves through a fixed sequence of stages so the process always terminates.
Purpose and Scope
This page covers Greedy's priority function, its stages, the decision order inside selectOrSplitImpl, eviction, the splitting strategies at a high level, and the extra steps (callee-saved cost, last-chance recoloring, hint recoloring). The mechanics of splitting and spilling are on Spilling and Splitting.
The Main Idea in One Paragraph
Allocate big, important intervals first. If an interval does not fit, try to push aside something cheaper. If that fails, wait until everything smaller has been placed, then look at the gaps that remain and cut the interval so each piece fits a gap. Pieces that still do not fit are spilled. Because evicted and split intervals are put back in the queue, the allocator keeps refining its answer, and the stage system stops it from looping forever.
Stages
Every interval carries a stage, stored in Greedy's ExtraInfo:
enum LiveRangeStage {
/// Newly created live range that has never been queued.
RS_New,
/// Only attempt assignment and eviction. Then requeue as RS_Split.
RS_Assign,
/// Attempt live range splitting if assignment is impossible.
RS_Split,
/// Attempt more aggressive live range splitting that is guaranteed to make
/// progress. This is used for split products that may not be making
/// progress.
RS_Split2,
/// Live range will be spilled. No more splitting will be attempted.
RS_Spill,
/// There is nothing more we can do to this live range. Abort compilation
/// if it can't be assigned.
RS_Done
};
stateDiagram-v2 [*] --> RS_New RS_New --> RS_Assign: first enqueue RS_Assign --> assigned: free or evicted a register RS_Assign --> RS_Split: no luck, requeued RS_Split --> pieces: split succeeded RS_Split --> RS_Spill: splitting gave nothing pieces --> RS_Assign: new pieces pieces --> RS_Split2: piece did not make progress RS_Split2 --> RS_Spill RS_Spill --> RS_Done: spilled; reload intervals are RS_Done RS_Done --> assigned
Stages only move forward, which guarantees termination: an interval can be split only a limited number of times before it is spilled, and the tiny intervals around reloads (RS_Done) are never spilled again. The splitter itself sets stages on the pieces it creates: pieces that would not benefit from further splitting are marked RS_Spill, and pieces that are no smaller than the original (no progress) are marked RS_Split2, which forces the next split to make progress.
Sources: llvm/include/llvm/CodeGen/RegAllocEvictionAdvisor.h:50-72
Priority
Greedy's queue is ordered by an unsigned priority from DefaultPriorityAdvisor::getPriority. The bit layout is spelled out in the source:
// Priority bit layout:
// 31 RS_Assign priority
// 30 Preference priority
// if (RegClassPriorityTrumpsGlobalness)
// 29-25 AllocPriority
// 24 GlobalBit
// else
// 29 Global bit
// 28-24 AllocPriority
// 0-23 Size/Instr distance
In plain words:
| Bit(s) | Set when | Effect |
|---|---|---|
| 31 | Interval is not in stage RS_Split | Fresh intervals come before deferred ones. Deferred (RS_Split) intervals are ordered only by size, after everything else |
| 30 | Interval has a known physical-register preference (a hint) | Hinted intervals go first, so their hint is still free |
| 29 (default) | Interval is global (spans several blocks) or is huge | Global intervals before local ones |
| 28–24 | AllocationPriority of the register class, from TableGen | A target can push some classes ahead (for example tuples) |
| 23–0 | Global: the interval's size. Local: its distance from the end of the function | Big global intervals first; local intervals in instruction order |
Local intervals (inside one block) are allocated in instruction order. The source comment explains why: they are singly defined, so allocating them in order "produces optimal coloring in the absence of global interference". A local interval is treated as global if its class sets GlobalPriority or if it is longer than twice the number of allocatable registers (measured in instructions).
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:439-509, llvm/include/llvm/Target/Target.td:360-365
The Decision Order
Everything Greedy does for one interval is in selectOrSplitImpl:
flowchart TD
A["dequeue V"] --> B["tryAssign: a free register?"]
B -->|"yes, unused callee-saved"| C["tryAssignCSRFirstTime:<br/>is a CSR worth its save/restore?"]
B -->|"yes"| R["return it"]
B -->|"no"| D{"stage != RS_Split?"}
D -->|"yes"| E["tryEvict: push out cheaper intervals"]
E -->|"success"| R
E -->|"fail"| F{"stage < RS_Split?"}
D -->|"no"| F
F -->|"yes"| G["set RS_Split, requeue<br/>(wait for second round)"]
F -->|"no"| H["trySplit"]
H -->|"split made"| S["return 0, pieces queued"]
H -->|"nothing"| I{"RS_Done or not spillable?"}
I -->|"yes"| J["tryLastChanceRecoloring"]
I -->|"no"| K["spill V, pieces become RS_Done"]
The code, abbreviated:
// First try assigning a free register.
auto Order =
AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
if (MCRegister PhysReg =
tryAssign(VirtReg, Order, NewVRegs, FixedRegisters)) {
...
}
...
if (Stage != RS_Split) {
if (MCRegister PhysReg =
tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit,
FixedRegisters)) {
...
return PhysReg;
}
}
...
// The first time we see a live range, don't try to split or spill.
// Wait until the second time, when all smaller ranges have been allocated.
// This gives a better picture of the interference to split around.
if (Stage < RS_Split) {
ExtraInfo->setStage(VirtReg, RS_Split);
NewVRegs.push_back(VirtReg.reg());
return MCRegister();
}
if (Stage < RS_Spill && !VirtReg.empty()) {
// Try splitting VirtReg or interferences.
...
MCRegister PhysReg = trySplit(VirtReg, Order, NewVRegs, FixedRegisters);
if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore))
return PhysReg;
}
if (Stage >= RS_Done || !VirtReg.isSpillable()) {
return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
RecolorStack, Depth);
}
// Finally spill VirtReg itself.
LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
spiller().spill(LRE, &Order);
ExtraInfo->setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
The "wait for second round" step is the clever part. An interval that cannot get a register on its first visit is not split straight away. It goes to the back of the queue (bit 31 cleared), so by the time it comes back, every other interval has been placed and the allocator can see exactly where the gaps are.
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:2655-2755
tryAssign
tryAssign walks the allocation order and stops at the first free register. A free hint is returned immediately. A free non-hint register is kept, but Greedy then checks whether it can do better:
- If the interval has a simple hint (a copy to a physical register) that was not free, try to evict whatever sits in the hint cheaply (
canEvictHintInterference), or split around the hint in cold blocks (trySplitAroundHintReg). Otherwise record it as a broken hint for later repair. - If the free register has a non-zero
CostPerUse(TableGen field on registers), try evicting something from a cheaper register.
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:532-584
Eviction
tryEvict asks the eviction advisor for the best physical register to take over:
MCRegister BestPhys = EvictAdvisor->tryFindEvictionCandidate(
VirtReg, Order, CostPerUseLimit, FixedRegisters);
if (BestPhys.isValid())
evictInterference(VirtReg, BestPhys, NewVRegs);
return BestPhys;
For each candidate register the default advisor (DefaultEvictionAdvisor) checks every interfering interval and computes an EvictionCost (number of broken hints, then the largest spill weight to be evicted). It picks the candidate with the lowest cost, and only if evicting is worth it: the evicted intervals must be cheaper than the current one (shouldEvict, canEvictInterferenceBasedOnCost).
evictInterference unassigns every interfering interval from the LiveRegMatrix and pushes it back into the queue. Evicted intervals get another chance: they may find a different free register, or be split.
Cascade numbers stop eviction from going round in circles. When an interval evicts others, it is given a cascade number (a new, larger one if it has none) and that number is stamped on every interval it evicts. The advisor then refuses to evict anything with the same or a newer cascade number; in the words of the source, "Only evict older cascades or live ranges without a cascade." So A cannot evict B, which evicts A, forever.
The advisor is pluggable (RegAllocEvictionAdvisorAnalysis): LLVM also has an ML-trained eviction advisor, which is why Register Allocation Pass Scoring appears in the pass list.
A related constant, Hysteresis = 2007 / 2048.0f (about 0.98), is used when comparing floating-point weights, for example in local splitting's gap comparison, so tiny differences do not flip decisions.
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:617-727, llvm/lib/CodeGen/RegAllocEvictionAdvisor.cpp:211-338, llvm/include/llvm/CodeGen/RegAllocEvictionAdvisor.h:76-80, llvm/lib/CodeGen/RegAllocGreedy.cpp:329-331, llvm/lib/CodeGen/RegAllocGreedy.cpp:1891-1896
Splitting Strategies
trySplit chooses a strategy by the shape of the interval:
// Local intervals are handled separately.
if (LIS->intervalIsInOneMBB(VirtReg)) {
...
MCRegister PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
if (PhysReg || !NewVRegs.empty())
return PhysReg;
return tryInstructionSplit(VirtReg, Order, NewVRegs);
}
...
// First try to split around a region spanning multiple blocks. RS_Split2
// ranges already made dubious progress with region splitting, so they go
// straight to single block splitting.
if (ExtraInfo->getStage(VirtReg) < RS_Split2) {
MCRegister PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
if (PhysReg || !NewVRegs.empty())
return PhysReg;
}
// Then isolate blocks.
return tryBlockSplit(VirtReg, Order, NewVRegs);
| Strategy | Interval shape | Idea |
|---|---|---|
Region split (tryRegionSplit) | Spans many blocks | For each candidate physical register, find the set of blocks where it is free, using SpillPlacement (a min-cost flow over edge bundles, weighted by block frequency) to decide where the value should be in a register and where in memory. Split so one piece lives in that register over that region |
Block split (tryBlockSplit) | Spans many blocks | Give each block that uses the value its own small interval, connected by copies |
Local split (tryLocalSplit) | Inside one block | Find a gap between uses where a register is free and cut the interval there (calcGapWeights) |
Instruction split (tryInstructionSplit) | Inside one block, or a register that needs a smaller class at some uses | One tiny interval per use, so each can be constrained individually |
A split creates new virtual registers joined by COPYs at the cut points. The pieces are queued, each gets its own register (or is spilled), and copies between pieces that end up in the same register are later removed by the rewriter. The machinery (SplitAnalysis, SplitEditor) is on Live Range Splitting.
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:1975-2010, llvm/lib/CodeGen/RegAllocGreedy.cpp:1206-1513, llvm/lib/CodeGen/RegAllocGreedy.cpp:1591-1744
Callee-saved Registers
Using a callee-saved register for the first time costs a store in the prologue and a load in the epilogue. If tryAssign picks a callee-saved register that nothing has used yet, tryAssignCSRFirstTime compares that cost (CSRCost, from TargetRegisterInfo::getCSRFirstUseCost, scaled by entry frequency) against splitting or spilling the interval instead. On a hot function it is worth it; on a function where the value is only live across a rarely executed call, splitting may be cheaper. Targets tune this through getCSRFirstUseCost.
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:2384-2470, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:869
Last-chance Recoloring
If an interval cannot be spilled (RS_Done, or marked unspillable) and still has no register, tryLastChanceRecoloring tries a small search: temporarily assign the interval to a register, unassign the intervals in the way, and try to recolor those recursively. It is limited in depth and in the number of interferences (-lcr-max-depth, -lcr-max-interf) because it is exponential. If it fails, the base class reports "ran out of registers".
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:2045-2328
After the Loop
RAGreedy::run does a few things after allocatePhysRegs:
| Step | What it does |
|---|---|
tryHintsRecoloring | For each interval whose copy hint was broken, try to swap registers within its copy-related group so more copies become identity copies |
postOptimization | Spiller hoists and merges spills (HoistSpillHelper::hoistAllSpills); dead rematerialised definitions are deleted |
reportStats | Emits the regalloc optimisation remark with the number of spills, reloads and copies |
Example of the remark, from the 24-load test (-pass-remarks-missed=regalloc):
remark: <unknown>:0:0: 13 spills 1.300000e+01 total spills cost 13
reloads 1.300000e+01 total reloads cost generated in function
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:2534-2654, llvm/lib/CodeGen/RegAllocGreedy.cpp:2757-2942
Target Hooks Greedy Consults
| Hook | Effect on Greedy |
|---|---|
AllocationPriority, GlobalPriority (TableGen class fields) | Queue order |
TRI::regClassPriorityTrumpsGlobalness | Swap bits 29 and 24–28 of the priority |
TRI::reverseLocalAssignment | Allocate local intervals bottom-up instead |
TRI::getRegAllocationHints | Preferred registers, tried first |
TRI::getCSRFirstUseCost | When to use a fresh callee-saved register |
TRI::shouldRegionSplitForVirtReg | Skip expensive region splitting for some registers |
CostPerUse (TableGen register field) | Prefer cheap registers (e.g. ones with short encodings) |
TII::isReMaterializableImpl, reMaterialize | Cheaper "spilling" by recomputing |
TII::storeRegToStackSlot, loadRegFromStackSlot, foldMemoryOperandImpl | How spills are actually written |
See Writing Register Allocation Support for a Custom Backend for each one.
Useful Options
| Option | Effect |
|---|---|
-regalloc=greedy | Force Greedy (e.g. at -O0, which also switches to the optimised pipeline) |
-split-spill-mode=default|size|speed | How split pieces are spilled |
-lcr-max-depth=N, -lcr-max-interf=N | Limits for last-chance recoloring |
-exhaustive-register-search | Remove recoloring limits (slow; for experiments) |
-greedy-reverse-local-assignment | Allocate local intervals bottom-up |
-greedy-regclass-priority-trumps-globalness | Use the alternative priority bit layout |
-regalloc-csr-first-time-cost=N | Override the cost of using a callee-saved register for the first time |
-pass-remarks-missed=regalloc | Report spills and reloads per function and loop |
PBQP Register Allocator
Relevant source files
The following files were used as context for generating this wiki page:
PBQP (Partitioned Boolean Quadratic Problem) turns register allocation into an optimisation problem on a graph and hands it to a solver. It is not the default on any target, but it is useful for machines with irregular constraints (register pairs, banks, restricted operand combinations) that are awkward to express as hints.
Purpose and Scope
This page explains the PBQP model, the allocator's main loop, and how a target adds its own constraints. The solver internals are out of scope.
The Model
| PBQP element | Means in register allocation |
|---|---|
| Node | One virtual register |
| Node cost vector | One entry per option: "spill" plus each allowed physical register. The spill entry is the spill weight; register entries are usually 0 |
| Edge | Two virtual registers that interact |
| Edge cost matrix | Cost of each combination of choices. Interfering registers get infinite cost for the same (or overlapping) physical register. Copy-related registers get a negative or lower cost for the same register (coalescing) |
The solver picks one option per node so the total cost is as small as possible. An infinite cost means "forbidden". Choosing "spill" for a node means that virtual register is spilled.
The Main Loop
The comment in runOnMachineFunction summarises it:
// Allocator main loop:
//
// * Map current regalloc problem to a PBQP problem
// * Solve the PBQP problem
// * Map the solution back to a register allocation
// * Spill if necessary
//
// This process is continued till no more spills are generated.
flowchart TD A["calculateSpillWeightsAndHints"] --> B["findVRegIntervalsToAlloc"] B --> C["build constraint list:<br/>SpillCosts, Interference,<br/>Coalescing (optional), target constraints"] C --> D["initializeGraph: one node per vreg"] D --> E["apply constraints to graph"] E --> F["PBQP::RegAlloc::solve"] F --> G["mapPBQPToRegAlloc:<br/>assign or spill each vreg"] G -->|"something was spilled"| D G -->|"no spills"| H["finalizeAlloc, postOptimization"]
Spilling creates new short intervals (around reloads), so the problem changes and the graph is rebuilt and solved again. The loop ends when a round produces no spills.
ConstraintsRoot->addConstraint(std::make_unique<SpillCosts>());
ConstraintsRoot->addConstraint(std::make_unique<Interference>());
if (PBQPCoalescing)
ConstraintsRoot->addConstraint(std::make_unique<Coalescing>());
ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
...
while (!PBQPAllocComplete) {
PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
initializeGraph(G, VRM, *VRegSpiller);
ConstraintsRoot->apply(G);
...
PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
++Round;
}
PBQP uses the same VirtRegMap, InlineSpiller and VirtRegRewriter as Greedy, so everything after allocation is identical.
Sources: llvm/lib/CodeGen/RegAllocPBQP.cpp:783-879, llvm/lib/CodeGen/RegAllocPBQP.cpp:579-773
Adding Target Constraints
A target can add its own costs by returning a PBQPRAConstraint from TargetSubtargetInfo::getCustomPBQPConstraints(). The constraint's apply(PBQPRAGraph &G) may change any node vector or edge matrix. Examples of what can be expressed:
- "these two registers should be an even/odd pair": low cost on the matching pairs in the edge matrix;
- "this operand is cheaper in the low 8 registers": lower node cost for those entries;
- "these two must be in different banks": infinite cost for same-bank combinations.
This is the main reason to choose PBQP: costs between pairs of registers are first-class, whereas Greedy only has per-register hints.
Sources: llvm/include/llvm/CodeGen/TargetSubtargetInfo.h:349, llvm/lib/CodeGen/RegAllocPBQP.cpp:837
Trying It
llc -mtriple=aarch64 -O2 -regalloc=pbqp file.ll
On the 24-load spill test it produced 82 instructions (31 spill/reload/save lines) against Greedy's 83, a difference that is noise on this example. -pbqp-coalescing adds the coalescing constraint. In assertion builds, -pbqp-dump-graphs writes each round's graph to a file (see the PBQPDumpGraphs block in the source).
Sources: llvm/lib/CodeGen/RegAllocPBQP.cpp:98-104
When To Consider It
| Use PBQP if | Prefer Greedy if |
|---|---|
| Your target has strong pairwise register constraints | Compile time matters |
| You want to experiment with cost models | You want the best-tested, best-tuned code |
| Functions are small (the solver can be slow on big graphs) | Functions are large |
Spilling and Splitting
Relevant source files
The following files were used as context for generating this wiki page:
When a value cannot stay in a register for its whole life, the allocator has three tools. It can spill it (keep it in a stack slot and load it before each use), rematerialise it (recompute it instead of loading it), or split it (cut its live range into pieces, so that only the pieces that do not fit go to memory).
Purpose and Scope
This page introduces the three tools and the vocabulary. The details are on Spill Weights, The Inline Spiller and Live Range Splitting.
Spilling
Spilling interval %v means:
- give
%va stack slot (a frame index, printed%stack.N); - after every definition of
%v, insert a store to the slot; - before every use, insert a load from the slot into a brand-new, tiny virtual register;
- delete
%v. The tiny registers live for one instruction each, so they almost always fit.
Real output from the 24-load test (-stop-after=virtregrewriter, excerpt):
STRWui killed renamable $w8, %stack.11, 0 :: (store (s32) into %stack.11)
STRWui killed renamable $w8, %stack.2, 0 :: (store (s32) into %stack.2)
...
BL @g, csr_aarch64_aapcs, implicit-def dead $lr, implicit $sp, implicit-def $sp
renamable $w9 = LDRWui %stack.11, 0 :: (load (s32) from %stack.11)
renamable $w12 = LDRWui %stack.12, 0 :: (load (s32) from %stack.12)
Each loaded value was stored right after its load from %p, and is reloaded after the call just before the add that uses it. The stack section lists the slots as type: spill-slot with offset: 0. Real offsets are assigned later by prologue/epilogue insertion.
Allocator Spills Versus Callee-saved Saves
Both show up as stores and loads around sp, and the assembly comments can say "Spill" for both. Tell them apart like this:
| Allocator spill | Callee-saved save | |
|---|---|---|
| Inserted by | InlineSpiller (Greedy, Basic, PBQP) or Fast | Prologue/epilogue insertion |
| Where | Next to the definition and the uses of a value | Function entry and every return |
| In MIR after the rewriter | STRWui ... %stack.N (type spill-slot) | Not there yet; appears after prologepilog |
| Assembly comment (AArch64) | 4-byte Spill, 4-byte Reload (or Folded when the load/store optimiser pairs them) | 16-byte Folded Spill on stp x.., x.. at entry |
Reported by -pass-remarks-missed=regalloc | Yes | No |
In the 24-load test, the remark says 13 spills and 13 reloads, which matches exactly the 13 STRWui/LDRWui pairs. The six stp/ldp pairs of x19–x30 are callee-saved saves.
Rematerialisation
If a value is cheap to recompute and its inputs are always available, for example a constant mov w24, #11, the spiller recomputes it before each use instead of storing and loading it. No stack slot is needed. That is what happened in the first spill experiment on the walkthroughs page: constants stayed as MOVi32imm and nothing went to memory. Rematerialisation needs the target to mark such instructions isReMaterializable (see TargetInstrInfo Hooks).
Folding
Some instructions can read an operand directly from memory (x86 add eax, [rsp+8]). Instead of a load plus the instruction, the spiller asks the target to fold the stack slot into the instruction (foldMemoryOperandImpl). AArch64 is a load/store architecture and folds very little; x86 folds a lot.
Splitting
Spilling a long interval everywhere is wasteful if it only conflicts in one place, such as across one call or inside one hot loop. Splitting replaces %v with several smaller registers connected by COPYs:
before: %v live from A to Z
after: %v1 live A..M, %v2 = COPY %v1 at M, %v2 live M..Z
Each piece is allocated separately. One piece may get a register, another may get a different register, and only a piece that still does not fit is spilled. Copies between pieces that end up in the same register are removed by the rewriter. Greedy is the only allocator that splits.
How the Pieces Fit Together
flowchart TD G["Greedy selectOrSplit"] -->|"split"| SK["SplitAnalysis + SplitEditor<br/>(SplitKit.cpp)"] G -->|"spill"| IS["InlineSpiller"] SK --> LRE["LiveRangeEdit<br/>creates vregs, updates LiveIntervals"] IS --> LRE IS -->|"remat?"| RM["LiveRangeEdit::rematerializeAt"] IS -->|"fold?"| FO["TII::foldMemoryOperand"] IS -->|"store/load"| TII["TII::storeRegToStackSlot<br/>TII::loadRegFromStackSlot"] W["VirtRegAuxInfo<br/>spill weights + hints"] --> G
LiveRangeEdit is the shared helper. It creates new virtual registers derived from an original (createFrom), keeps LiveIntervals correct, deletes dead definitions, and tells the allocator about changes through callbacks (LRE_CanEraseVirtReg, LRE_WillShrinkVirtReg, LRE_DidCloneVirtReg).
Sources: llvm/lib/CodeGen/LiveRangeEdit.cpp:55-426, llvm/lib/CodeGen/RegAllocGreedy.cpp:370-412
Spill Weights and Copy Hints
Relevant source files
The following files were used as context for generating this wiki page:
Every live interval has a spill weight: a number estimating how much it would cost to spill it. Allocators use it to decide who gets a register and who goes to memory. The same pass that computes weights also records copy hints, the physical or virtual registers an interval would like to share with.
Purpose and Scope
This page gives the exact formula from VirtRegAuxInfo::weightCalcHelper, explains each factor, and lists the target hooks that change it.
Where It Is Used
| 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.
The Formula
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
What the Formula Means
- 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.
A Hand-worked Example
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.
Copy Hints
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
Rematerialisable Check
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
Target Hooks That Change Weights
| 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
The Inline Spiller
Relevant source files
The following files were used as context for generating this wiki page:
InlineSpiller is the spiller used by Basic, Greedy and PBQP. Given one live interval to spill, it first tries to avoid memory altogether (rematerialisation), then tries to fold the stack slot into instructions, and only then inserts real stores and loads. It is called "inline" because it edits the code immediately, while the allocator is still running.
Purpose and Scope
This page follows InlineSpiller::spill from start to finish and lists the target hooks it calls. The Fast allocator has its own, much simpler spilling (see Fast Register Allocator).
Entry Point
void InlineSpiller::spill(LiveRangeEdit &edit, AllocationOrder *order) {
++NumSpilledRanges;
Edit = &edit;
Order = order;
...
// Share a stack slot among all descendants of Original.
Original = VRM.getOriginal(edit.getReg());
StackSlot = VRM.getStackSlot(Original);
StackInt = nullptr;
...
collectRegsToSpill();
reMaterializeAll();
// Remat may handle everything.
if (!RegsToSpill.empty())
spillAll();
Edit->calculateRegClassAndHint(MF, VRAI);
}
flowchart TD A["spill(LRE)"] --> B["find Original register;<br/>reuse its stack slot if any"] B --> C["collectRegsToSpill<br/>the register plus its split 'snippets'"] C --> D["reMaterializeAll<br/>recompute values where possible"] D -->|"nothing left"| H["calculateRegClassAndHint"] D -->|"registers left"| E["spillAll"] E --> F["assign stack slot; merge into LiveStacks"] F --> G["spillAroundUses for each register:<br/>fold, or reload before use / store after def"] G --> H
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:1460-1486
One Stack Slot per Original Register
When Greedy splits %v into pieces and several pieces are later spilled, they all hold the same original value. VRM.getOriginal(Reg) finds the register they were split from, and the spiller reuses its slot (VRM.getStackSlot(Original)). All pieces therefore share one slot, and a value stored by one piece can be reloaded by another without extra copies.
Step 1: Collect Registers to Spill
collectRegsToSpill starts with the register being spilled and adds snippets: tiny sibling intervals (split from the same original) that are connected to it only by copies (isSnippet). Spilling them together lets the spiller delete those copies (SnippetCopies) instead of turning them into store/load pairs.
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:326, llvm/lib/CodeGen/InlineSpiller.cpp:389
Step 2: Rematerialise
reMaterializeAll visits each use of the registers to spill and calls reMaterializeFor. If the value used there was defined by an instruction the target marks rematerialisable, and its operands are still available at the use (LiveRangeEdit::canRematerializeAt), a copy of the defining instruction is inserted right before the use (LiveRangeEdit::rematerializeAt, which calls TargetInstrInfo::reMaterialize) into a new small register. The original definition may become dead; dead definitions are deleted later (DeadRemats, removed in RegAllocBase::postOptimization).
If every use was rematerialised, RegsToSpill ends up empty and no stack slot is created at all. This is why constants never appear as spills.
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:674, llvm/lib/CodeGen/InlineSpiller.cpp:834, llvm/lib/CodeGen/LiveRangeEdit.cpp:71-84, llvm/include/llvm/CodeGen/TargetInstrInfo.h:493
Step 3: spillAll
// Update LiveStacks now that we are committed to spilling.
if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
StackSlot = VRM.assignVirt2StackSlot(Original);
StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
...
}
...
for (Register Reg : RegsToSpill)
StackInt->MergeSegmentsInAsValue(LIS.getInterval(Reg),
StackInt->getValNumInfo(0));
...
// Spill around uses of all RegsToSpill.
for (Register Reg : RegsToSpill) {
spillAroundUses(Reg);
...
}
The stack slot gets its own live interval in LiveStacks. That is what Stack Slot Coloring uses later to let non-overlapping slots share memory. After spillAroundUses, the snippet copies and the spilled registers themselves are deleted.
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:1411-1458
Step 4: spillAroundUses
For each instruction that uses or defines the register, in this order:
| Check | Action |
|---|---|
DBG_VALUE | Rewrite it to point at the stack slot; debug info never affects codegen |
| Snippet copy | Skip; it will be deleted |
coalesceStackAccess | The instruction is already a load or store of the same slot: delete it |
| Copy from a sibling, writing the register | hoistSpillInsideBB: store the sibling earlier instead, and mark this copy dead |
| Copy from a sibling, reading | eliminateRedundantSpills: stores downstream of it are not needed |
foldMemoryOperand(Ops) | Ask the target to fold the slot into the instruction. On success no new register is needed |
| Otherwise | Create a new register NewVReg = Edit->createFrom(Reg); if the instruction reads, insertReload before it; rewrite the operands to NewVReg; if it writes, insertSpill after it |
// Attempt to fold memory ops.
if (foldMemoryOperand(Ops))
continue;
// Create a new virtual register for spill/fill.
Register NewVReg = Edit->createFrom(Reg);
if (RI.Reads)
insertReload(NewVReg, Idx, &MI);
...
if (RI.Writes)
if (hasLiveDef)
insertSpill(NewVReg, true, &MI);
Each NewVReg lives from its reload to the instruction, or from the instruction to its store: one instruction long. These are the tiny, unspillable intervals the allocator then queues as RS_Done.
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:1315-1408
insertReload and insertSpill
Both are thin wrappers around the target:
TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
MRI.getRegClass(NewVReg), Register());
LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
if (IsRealSpill)
TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, isKill, StackSlot,
MRI.getRegClass(NewVReg), Register());
else
// Don't spill undef value.
...
BuildMI(MBB, SpillBefore, MI->getDebugLoc(), TII.get(TargetOpcode::KILL))
.addReg(NewVReg, getKillRegState(isKill));
Note the details a target must get right:
- The hooks are called with a virtual register. The instruction you build must accept a virtual register of that class.
- You may emit more than one instruction. The spiller uses a
MachineInstrSpanand gives every new instruction a slot index. (A single-instruction store is also recorded as mergeable for spill hoisting.) - Storing an
IMPLICIT_DEF(an undefined value) is skipped; aKILLis emitted instead.
On AArch64, storeRegToStackSlot for a 32-bit GPR produces the STRWui ... %stack.N, 0 seen in the spill example, and loadRegFromStackSlot produces LDRWui.
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:1247-1312, llvm/include/llvm/CodeGen/TargetInstrInfo.h:1199-1219
After Allocation: Hoisting Spills
When allocation finishes, RegAllocBase::postOptimization calls the spiller's postOptimization, which runs HoistSpillHelper::hoistAllSpills. Different pieces of the same original value may each have stored to the shared slot. The helper looks for stores of the same value that can be merged into one, placed at a point that dominates them and runs less often, and removes the rest.
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:1489, llvm/lib/CodeGen/InlineSpiller.cpp:1812, llvm/lib/CodeGen/RegAllocBase.cpp:157-168
Target Hooks Used by the Spiller
| Hook | Required? | Used for |
|---|---|---|
storeRegToStackSlot | Yes | Spill store |
loadRegFromStackSlot | Yes | Reload |
isLoadFromStackSlot, isStoreToStackSlot | Strongly recommended | Recognising existing slot accesses (coalesceStackAccess, redundant-spill removal, stack slot coloring) |
isReMaterializableImpl (or TableGen isReMaterializable = 1), reMaterialize | Recommended | Rematerialisation |
foldMemoryOperandImpl | Optional | Folding the slot into instructions |
isCopyInstrImpl | Optional | Recognising target moves as copies (for sibling copies and snippets) |
See TargetInstrInfo Hooks for how to write each one.
Live Range Splitting
Relevant source files
The following files were used as context for generating this wiki page:
SplitKit is the library Greedy uses to cut a live interval into pieces. Greedy decides where to cut; SplitKit does the cutting: it creates the new virtual registers, inserts the COPYs at the cut points, and rebuilds the live intervals.
Purpose and Scope
This page explains the two SplitKit classes, the "interval" vocabulary used by SplitEditor, and how one Greedy strategy drives it. Which strategy Greedy picks is on Greedy Register Allocator.
Two Classes
| Class | Role |
|---|---|
SplitAnalysis | Read-only. For the interval being split, finds every use (analyzeUses) and, for each block it is live in, a BlockInfo: first and last use in the block, and whether the value is live in and live out (calcLiveBlockInfo) |
SplitEditor | Makes the change. Lets the caller open new intervals, say which parts of the original belong to which, and then finish() rewrites everything |
Sources: llvm/lib/CodeGen/SplitKit.h:96-121, llvm/lib/CodeGen/SplitKit.h:263, llvm/lib/CodeGen/SplitKit.cpp:167-199
The Editing Vocabulary
SplitEditor thinks in terms of numbered intervals. Interval 0 is the complement: everything not explicitly given to another interval. The caller opens new intervals and marks the regions they cover:
| Call | Meaning |
|---|---|
openIntv() | Create a new interval and make it current; returns its number |
selectIntv(Idx) | Make an existing interval current |
enterIntvBefore(Idx) | The current interval starts just before Idx; a copy from the complement is inserted there |
enterIntvAtEnd(MBB) | The current interval starts at the end of MBB (for a value live out of the block) |
useIntv(MBB) / useIntv(Start, End) | The current interval covers this whole block, or this range |
leaveIntvAfter(Idx) | The current interval ends just after Idx; a copy back to the complement is inserted |
leaveIntvBefore(Idx) | The current interval ends just before Idx |
finish(LRMap) | Create the new registers, insert the copies, rewrite every operand (rewriteAssigned), recompute the live intervals |
High-level helpers wrap the common patterns: splitSingleBlock(BI) isolates the uses in one block, and splitLiveThroughBlock handles a block the value passes through.
Sources: llvm/lib/CodeGen/SplitKit.cpp:690-822, llvm/lib/CodeGen/SplitKit.cpp:1361, llvm/lib/CodeGen/SplitKit.cpp:1545, llvm/lib/CodeGen/SplitKit.cpp:1650-1676
A Picture
An interval %v that is live through a loop containing a call, used before and after the loop:
entry loop (contains call) exit
%v |=====================================|
Greedy finds that every caller-saved register is clobbered inside the loop, but w8 is free outside it. A region split could produce (illustrative, not llc output):
entry: %v1 = ... ; %v1 in w8
%v2 = COPY %v1 ; leave interval at loop entry
loop: ... uses of %v2 ... ; %v2 needs a callee-saved reg, or is spilled
exit: %v3 = COPY %v2 ; enter interval at loop exit
... uses of %v3 ... ; %v3 in w8 again
%v1 and %v3 can share w8. The copies are on the loop boundary, which runs once, not inside the loop, which runs many times. That choice of cut points is what region splitting optimises.
How Region Splitting Chooses Cut Points
EdgeBundlesgroups CFG edges into bundles: sets of block boundaries that must agree on whether the value is in a register or in memory.- For one candidate physical register,
addSplitConstraintsrecords, per block, whether it prefers the value in a register on entry and exit (no interference there) or in memory (interference), weighted by block frequency.addThroughConstraintshandles blocks the value only passes through. SpillPlacementsolves for the bundle assignment with the lowest total cost (a min-cut style computation), andgrowRegionextends the region through neighbouring live-through blocks while that pays.calculateRegionSplitCostcompares candidates, andsplitAroundRegionusesSplitEditorto create the interval for the region in the best register, leaving the rest in the complement.
The result is that values stay in registers where they are used heavily and pay copies only on cold edges.
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:739-1206, llvm/lib/CodeGen/RegAllocGreedy.cpp:1239-1334, llvm/lib/CodeGen/EdgeBundles.cpp
The Complement and Spill Modes
After the region intervals are cut out, interval 0 (the complement) holds everything else. If it is later spilled, how its copies overlap the new intervals matters. -split-spill-mode chooses:
| Mode | Behaviour (from SplitKit.h) |
|---|---|
default (SM_Partition) | Make the complement not overlap the other intervals |
size (SM_Size) | Let intervals overlap to minimise the number of inserted copies |
speed (SM_Speed) | Like size, but minimise the expected execution frequency of the copies |
Sources: llvm/lib/CodeGen/SplitKit.h:281-311, llvm/lib/CodeGen/RegAllocGreedy.cpp:86-90
What Happens to the Pieces
finish returns the new registers. Greedy sets their stages (Greedy: Stages): pieces that should be spilled rather than split again get RS_Spill, pieces that made no progress get RS_Split2, and the rest start again at RS_New. All of them go back on the queue. Each piece records its original register (VirtRegMap::setIsSplitFromReg), so if several pieces are spilled they share one stack slot (The Inline Spiller).
Copies between pieces that end up in the same physical register become identity copies and are deleted by the rewriter.
Target Involvement
SplitKit inserts plain COPYs, which the target turns into moves with copyPhysReg after allocation. Two hooks influence splitting directly:
| Hook | Effect |
|---|---|
TargetRegisterInfo::shouldRegionSplitForVirtReg | Return false to skip region splitting for a register (compile time on huge intervals) |
TargetRegisterInfo::getLargestLegalSuperClass | Lets a split piece use a larger class than the original when its uses allow it |
Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:740, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:1051
Rewriting and Post-RA Passes
Relevant source files
The following files were used as context for generating this wiki page:
Basic, Greedy and PBQP only record their decisions in VirtRegMap. VirtRegRewriter is the pass that applies them: it replaces every virtual register operand with its physical register, deletes copies that became no-ops, and fills in block live-in lists. After it, the function contains no virtual registers. A few cleanup passes then run before the frame is laid out.
Purpose and Scope
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.
VirtRegRewriter::run
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
rewrite(): Operand by Operand
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
Identity Copies
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
Before and After, Side by Side
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.
The Passes After the Rewriter
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
Frame Indexes Become Addresses
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.
Writing Register Allocation Support for a Custom Backend
Relevant source files
The following files were used as context for generating this wiki page:
You do not write a register allocator for a new backend. LLVM's allocators are target-independent and work for every target. What you write is the description of your machine that they consume: which registers exist, how they overlap, which are reserved or preserved across calls, and how to copy, save and restore a register. This section is the practical guide to that description.
Purpose and Scope
This page is the roadmap. The sub-pages go through each part with AArch64 as the real reference and a small made-up "Toy" target for illustrative snippets (marked as such; Toy is not in LLVM).
| Page | You write |
|---|---|
| 9.1 Register Definitions in TableGen | <Target>RegisterInfo.td: registers, sub-registers, classes, allocation order; callee-saved lists in <Target>CallingConv.td |
| 9.2 TargetRegisterInfo Hooks | <Target>RegisterInfo.cpp: reserved registers, callee-saved registers and masks, frame index elimination, hints |
| 9.3 TargetInstrInfo Hooks | <Target>InstrInfo.cpp: copy, spill, reload, rematerialisation, folding |
| 9.4 Pass Pipeline Hooks | <Target>TargetMachine.cpp: passes around allocation, allocator choice |
| 9.5 Bring-up Checklist and Common Failures | Order of work, tests, and what each error means |
What the Allocator Asks Your Target
Every question the allocator asks maps to one piece of your backend:
| Question | Answered by | Required for |
|---|---|---|
| Which physical registers exist and how do they overlap? | TableGen Register, SubRegIndex, register units (generated) | Everything |
| Which registers may hold a value of this type / operand? | TableGen RegisterClass, instruction operand classes | Everything |
| Which order should I try them in? | Class member order, AltOrders, AltOrderSelect | Quality |
| Which registers may I never use? | getReservedRegs | Correctness |
| Which registers does a call destroy? | getCallPreservedMask (from CalleeSavedRegs) | Correctness |
| Which registers must this function save if it uses them? | getCalleeSavedRegs | Correctness |
| How do I copy register A to B? | copyPhysReg | Correctness |
| How do I store / load a register to a stack slot? | storeRegToStackSlot, loadRegFromStackSlot | Correctness at any register pressure |
| How do I turn a stack slot into an address? | eliminateFrameIndex, getFrameRegister (with frame lowering) | Correctness |
| Is this instruction cheap to recompute? | isReMaterializable (TableGen), isReMaterializableImpl | Quality |
| Can this instruction read from memory directly? | foldMemoryOperandImpl | Quality |
| Which register would this value like? | getRegAllocationHints | Quality |
The "correctness" rows are the minimum. With them, Fast works at -O0 and Greedy works at -O2. The "quality" rows make the code good.
The Data Flow
flowchart LR TD["Target.td + <Target>RegisterInfo.td<br/>+ <Target>CallingConv.td"] -->|"llvm-tblgen -gen-register-info"| GEN["<Target>GenRegisterInfo.inc<br/>register enums, classes, units,<br/>sub-reg tables, CSR save lists / masks"] GEN --> TRI["<Target>RegisterInfo<br/>(derives from <Target>GenRegisterInfo)"] TRI --> RA["Allocators, coalescer,<br/>LiveIntervals, rewriter"] TII["<Target>InstrInfo<br/>copy / spill / reload / remat"] --> RA PC["<Target>PassConfig<br/>pipeline hooks"] --> RA RA --> PEI["Prologue/Epilogue insertion<br/>+ <Target>FrameLowering"] TRI --> PEI
Minimal Skeleton (Illustrative)
For a made-up target "Toy" with sixteen 32-bit registers R0–R15, R15 the stack pointer and R14 the link register. This is an illustrative sketch, not LLVM source.
// ToyRegisterInfo.td (illustrative)
class ToyReg<bits<16> Enc, string n> : Register<n> {
let HWEncoding = Enc;
let Namespace = "Toy";
}
foreach i = 0-15 in
def R#i : ToyReg<i, "r"#i>, DwarfRegNum<[i]>;
def GPR : RegisterClass<"Toy", [i32], 32, (sequence "R%u", 0, 15)>;
// ToyRegisterInfo.cpp (illustrative)
BitVector ToyRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
BitVector Reserved(getNumRegs());
Reserved.set(Toy::R15); // stack pointer
if (getFrameLowering(MF)->hasFP(MF))
Reserved.set(Toy::R13); // frame pointer
return Reserved;
}
const MCPhysReg *
ToyRegisterInfo::getCalleeSavedRegs(const MachineFunction *) const {
return CSR_Toy_SaveList; // generated from ToyCallingConv.td
}
const uint32_t *
ToyRegisterInfo::getCallPreservedMask(const MachineFunction &,
CallingConv::ID) const {
return CSR_Toy_RegMask; // generated from ToyCallingConv.td
}
// ToyInstrInfo.cpp (illustrative)
void ToyInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator I,
const DebugLoc &DL, Register Dst, Register Src,
bool KillSrc, bool RenamableDest,
bool RenamableSrc) const {
BuildMI(MBB, I, DL, get(Toy::MOVrr), Dst)
.addReg(Src, getKillRegState(KillSrc));
}
That is enough for straight-line -O0 code with no spills. Spilling needs storeRegToStackSlot, loadRegFromStackSlot and eliminateFrameIndex; the sub-pages show each one. Check the exact current signatures in TargetRegisterInfo.h and TargetInstrInfo.h at your LLVM version: they change from release to release (for example, at the pinned commit storeRegToStackSlot takes a trailing MachineInstr::MIFlag).
Where AArch64 Implements Each Piece
| Piece | AArch64 file and line |
|---|---|
| Register and class definitions | AArch64RegisterInfo.td:13-261 |
| Callee-saved lists | AArch64CallingConvention.td:594 (CSR_AArch64_AAPCS) |
getCalleeSavedRegs | AArch64RegisterInfo.cpp:72 |
getCallPreservedMask | AArch64RegisterInfo.cpp:271 |
getStrictlyReservedRegs, getReservedRegs | AArch64RegisterInfo.cpp:419, 535 |
getFrameRegister, requiresRegisterScavenging, requiresFrameIndexScavenging | AArch64RegisterInfo.cpp:753-790 |
eliminateFrameIndex | AArch64RegisterInfo.cpp:978 |
getRegAllocationHints, shouldCoalesce | AArch64RegisterInfo.cpp:1191, 1459 |
copyPhysReg | AArch64InstrInfo.cpp:6365 |
storeRegToStackSlot, loadRegFromStackSlot | AArch64InstrInfo.cpp:6400, 6580 |
isLoadFromStackSlot, isStoreToStackSlot | AArch64InstrInfo.cpp:2852, 2881 |
foldMemoryOperandImpl | AArch64InstrInfo.cpp:7154 |
| Pass config hooks | AArch64TargetMachine.cpp:852-973 |
Sources: llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:72-1459, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:2852-7154, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:852-973
Register Definitions in TableGen
Relevant source files
The following files were used as context for generating this wiki page:
Everything the allocator knows about your registers starts in TableGen. You describe registers, how they nest, and which groups an operand may use. llvm-tblgen -gen-register-info turns that into <Target>GenRegisterInfo.inc: register enums, register classes, register units, sub-register tables, lane masks and callee-saved lists.
Purpose and Scope
This page explains each TableGen class and field that matters to register allocation, with the AArch64 definitions as the reference. Examples for the made-up "Toy" target are illustrative only.
Step 1: Registers
class Register<string n, list<string> altNames = []> {
...
list<Register> Aliases = [];
...
list<SubRegIndex> SubRegIndices = [];
...
list<int> CostPerUse = [0];
bit CoveredBySubRegs = false;
bits<16> HWEncoding = 0;
bit isArtificial = false;
...
}
| Field | What it means for allocation |
|---|---|
SubRegs + SubRegIndices | This register is made of these smaller registers, at these positions. Drives register units, lane masks and sub-register operands |
CoveredBySubRegs | The sub-registers cover all bits. Lets LLVM treat "all sub-registers defined" as "whole register defined" |
Aliases | Extra overlaps that are not sub-registers (rarely needed; prefer sub-registers) |
CostPerUse | Extra cost of using this register (for example a longer encoding). Greedy tries to avoid registers with non-zero cost (see Greedy: tryAssign) |
isArtificial | A register that does not exist in hardware but describes part of one (AArch64's W0_HI). Never allocated directly |
HWEncoding | Encoding number; used by the MC layer, not the allocator |
AArch64 uses a small helper class and lists sub-registers explicitly:
class AArch64Reg<bits<16> enc, string n, list<Register> subregs = [],
list<string> altNames = []>
: Register<n, altNames> {
let HWEncoding = enc;
let Namespace = "AArch64";
let SubRegs = subregs;
}
...
def W0 : AArch64Reg<0, "w0" >, DwarfRegNum<[0]>;
...
def X0 : AArch64Reg<0, "x0", [W0, W0_HI]>, DwarfRegAlias<W0>;
Sources: llvm/include/llvm/Target/Target.td:173-233, llvm/lib/Target/AArch64/AArch64RegisterInfo.td:13-19, llvm/lib/Target/AArch64/AArch64RegisterInfo.td:101-168
Step 2: Sub-register Indices
A SubRegIndex<size, offset> names a position inside a register:
class SubRegIndex<int size, int offset = 0> { ... }
AArch64 defines, among others:
def sub_32 : SubRegIndex<32>;
...
def ssub : SubRegIndex<32, 0>;
def dsub : SubRegIndex<64, 0>;
...
// sub_32_hi describes the top 32 bits in e.g. X0
def sub_32_hi : SubRegIndex<32, 32>;
Rules of thumb:
- Define an index for every way an instruction can name part of a register (
sub_32forwNinsidexN). - If a register has bits that no instruction can name on their own, still describe them with an artificial sub-register and a
_hiindex (as AArch64 does). Otherwise partially overlapping registers get the same lane mask, and sub-register liveness becomes wrong or impossible. - Composite indices (
ComposedSubRegIndex) describe "sub-register of a sub-register" for register tuples.
Sources: llvm/include/llvm/Target/Target.td:108, llvm/lib/Target/AArch64/AArch64RegisterInfo.td:21-60
Step 3: Register Classes
class RegisterClass<string namespace, list<ValueType> regTypes, int alignment,
dag regList, RegAltNameIndex idx = NoRegAltName> { ... }
The four arguments: namespace, the value types the class holds, the alignment in bits required when the registers are stored to or loaded from memory, and the member list (a set expression).
| Field | Default | What it controls |
|---|---|---|
member list (add ...), (sequence "R%u", 0, 15), (sub A, B), (rotl C, 8) | required | Which registers, and the default allocation order |
CopyCost | 1 | Cost of a copy between two registers of this class (1 = one instruction). A negative value means copying is extremely expensive or impossible |
isAllocatable | true | Set to 0 for classes the allocator must never assign from (SP-only classes, status registers) |
AltOrders, AltOrderSelect | none | Alternative allocation orders and the body of a function f(const MachineFunction &MF, bool Rev) that returns 0 for the default order, 1 for the first AltOrders entry, and so on |
AllocationPriority | 0 | Range 0–31; higher classes are assigned first. Folded into Greedy's priority (bits 28–24) |
GlobalPriority | false | Treat every interval of this class as global (allocate by size) |
Weight | computed | Register pressure weight per register; if unset, TableGen computes it from the number of register units. Set it for tuple classes |
GeneratePressureSet | true | Set to 0 to stop TableGen generating a pressure set for this class |
Size | 0 | Spill size in bits; 0 lets TableGen pick an appropriate size |
The default member order is usually good enough, because, as the AltOrders comment in Target.td says, "the register allocators automatically remove reserved registers and move callee-saved registers to the end."
AArch64 GPR classes, as quoted on Registers basics:
def GPR32common : RegisterClass<"AArch64", [i32], 32, (sequence "W%u", 0, 30)> {
let AltOrders = [(rotl GPR32common, 8)];
let AltOrderSelect = [{ return 1; }];
}
...
// SP/WSP are always reserved.
let isAllocatable = 0 in {
def GPR32sponly : RegisterClass<"AArch64", [i32], 32, (add WSP)>;
def GPR64sponly : RegisterClass<"AArch64", [i64], 64, (add SP)>;
}
Sources: llvm/include/llvm/Target/Target.td:292-376, llvm/include/llvm/Target/Target.td:340-343, llvm/lib/Target/AArch64/AArch64RegisterInfo.td:189-261
Design advice for classes
- One class per operand constraint. If register 31 means different things in different instructions (as on AArch64), define a class for each meaning and one common sub-class. TableGen computes the lattice; the coalescer uses it to find common sub-classes.
- Order matters. Put registers you want used first at the front: scratch (caller-saved) registers before callee-saved ones, and argument registers late, so they stay free for calls.
RegisterClassInfoalready moves callee-saved registers to the end, but the order among the rest is yours. - Do not put reserved registers in a separate class just to hide them. Keep them in the natural class and report them from
getReservedRegs. Reserved registers are removed from allocation orders automatically. - Make super-classes legal for copies. Splitting and coalescing create copies between related classes;
getLargestLegalSuperClassandgetCrossCopyRegClasssay what is allowed.
Step 4: Register Tuples
For instructions that use several consecutive registers (vector loads of 2–4 registers, 64-bit pairs on 32-bit targets), describe the tuples so the allocator can assign them as one unit:
class RegisterTuples<list<SubRegIndex> Indices, list<dag> Regs, ...> { ... }
Each tuple is a synthetic register whose sub-registers are the members. A class of tuples is then a normal RegisterClass. Greedy's AllocationPriority is often raised for tuple classes, because they are hardest to place.
Sources: llvm/include/llvm/Target/Target.td:469-478
Step 5: Callee-saved Lists
In <Target>CallingConv.td:
def CSR_AArch64_AAPCS : CalleeSavedRegs<(add X19, X20, X21, X22, X23, X24,
X25, X26, X27, X28, LR, FP,
D8, D9, D10, D11,
D12, D13, D14, D15)>;
TableGen generates CSR_AArch64_AAPCS_SaveList (a zero-terminated array for getCalleeSavedRegs) and CSR_AArch64_AAPCS_RegMask (a bit mask for getCallPreservedMask). Define one CalleeSavedRegs per calling convention variant; AArch64 has many (Darwin, Windows, Swift, GHC, preserve_most, ...).
Sources: llvm/lib/Target/AArch64/AArch64CallingConvention.td:594-597
Step 6: Use the Classes in Instructions
Instruction operands name a register class (or a RegisterOperand that wraps one). That is how instruction selection gives each virtual register its class, and how MachineRegisterInfo::constrainRegClass narrows classes when one value feeds several instructions. Tied and early-clobber constraints go in Constraints = "..." (see PHI Elimination and Two-Address Lowering).
Mark cheap, input-free definitions rematerialisable:
// illustrative (Toy)
let isReMaterializable = 1, isAsCheapAsAMove = 1 in
def MOVi : ToyInst<(outs GPR:$rd), (ins i32imm:$imm), "mov $rd, $imm", ...>;
A Complete Toy Register File (Illustrative)
Sixteen 32-bit registers, 64-bit pairs for a ldd-style instruction, and two classes. Illustrative only, not LLVM source.
let Namespace = "Toy" in {
def sub_lo : SubRegIndex<32, 0>;
def sub_hi : SubRegIndex<32, 32>;
}
class ToyReg<bits<16> Enc, string n> : Register<n> {
let HWEncoding = Enc;
let Namespace = "Toy";
}
foreach i = 0-15 in
def R#i : ToyReg<i, "r"#i>, DwarfRegNum<[i]>;
// Even/odd pairs: D0 = R0:R1, D1 = R2:R3, ...
let SubRegIndices = [sub_lo, sub_hi], CoveredBySubRegs = 1 in
foreach i = 0-7 in
def D#i : ToyReg<!mul(i, 2), "d"#i> {
let SubRegs = [!cast<Register>("R"#!mul(i, 2)),
!cast<Register>("R"#!add(!mul(i, 2), 1))];
}
// Scratch first (r0-r7), then callee-saved (r8-r12); r13-r15 reserved in C++.
def GPR : RegisterClass<"Toy", [i32], 32, (sequence "R%u", 0, 15)>;
def GPRPair : RegisterClass<"Toy", [i64], 64, (sequence "D%u", 0, 7)> {
let AllocationPriority = 2; // pairs are harder to place
}
Check the generated file (build/lib/Target/Toy/ToyGenRegisterInfo.inc) after every change: it shows the computed sub-classes, lane masks and units.
TargetRegisterInfo Hooks
Relevant source files
The following files were used as context for generating this wiki page:
<Target>RegisterInfo derives from the TableGen-generated <Target>GenRegisterInfo and adds the facts that depend on the function being compiled: which registers are off limits, which are preserved across calls, how to address a stack slot, and which register a value would like. This page goes through the hooks the allocator and its neighbours call, required ones first.
Purpose and Scope
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.
Required Hooks
These are pure virtual (= 0) or have defaults that are wrong for any real target.
getReservedRegs
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
getCalleeSavedRegs
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
getCallPreservedMask
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
getFrameRegister
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
eliminateFrameIndex
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
The Register Scavenger
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
Quality Hooks
Optional; defaults are safe.
getRegAllocationHints
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
getLargestLegalSuperClass
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
Other quality hooks
| 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
Sub-register Liveness
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.
TargetInstrInfo Hooks
Relevant source files
The following files were used as context for generating this wiki page:
<Target>InstrInfo tells the allocator how to move values: copy one register to another, store a register to a stack slot, load it back, recompute it, or read it straight from memory. Three of these hooks are mandatory. Without them the default implementations call llvm_unreachable, and compilation stops with "Target didn't implement ...".
Purpose and Scope
Declarations at the pinned commit, who calls each hook, what AArch64 does, and illustrative sketches for the made-up "Toy" target (not LLVM source).
Required Hooks
copyPhysReg
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
storeRegToStackSlot and loadRegFromStackSlot
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
Strongly Recommended
isLoadFromStackSlot and isStoreToStackSlot
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
Rematerialisation
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
isCopyInstrImpl
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
Optional
foldMemoryOperandImpl
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
expandPostRAPseudo
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
Two-address helpers
findCommutedOpIndices, commuteInstructionImpl, convertToThreeAddress: see PHI Elimination and Two-Address Lowering.
Summary
| 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 |
Pass Pipeline Hooks
Relevant source files
The following files were used as context for generating this wiki page:
Your <Target>PassConfig (derived from TargetPassConfig) decides which passes run around register allocation. Most targets need no change to the allocation chain itself: they add a few target passes before or after it through virtual hooks.
Purpose and Scope
This page lists the hooks, where each runs, and common reasons to use them. The full pass order is on The Register Allocation Pipeline.
The Hooks
Hook (TargetPassConfig.h) |
Line | Runs | Typical use |
|---|---|---|---|
addMachineSSAOptimization() | 365 | Before the allocation chain, on SSA MIR | Target SSA peepholes (AArch64: PTRUE coalescing) |
addPreRegAlloc() | 379 | Just before the allocation chain | Passes that shape register pressure or constraints (AArch64: dead register definitions to wzr/xzr, AdvSIMD scalar, machine pipeliner) |
createTargetRegisterAllocator(bool Optimized) | 383 | Chooses the allocator when no -regalloc= is given | Pick a different default |
addFastRegAlloc() | 387 | The whole -O0 chain | Rarely overridden |
addOptimizedRegAlloc() | 392 | The whole optimised chain | Rarely overridden; insert passes with insertPass instead |
addPreRewrite() | 406 | After the allocator, before VirtRegRewriter | Work that needs VirtRegMap (assignments known, operands still virtual) |
addPostFastRegAllocRewrite() | 412 | After the Fast allocator | Same idea for -O0 |
addPostRewrite() | 416 | After the rewriter and stack slot coloring | Expand pseudos that depend on the chosen registers, before copy propagation |
addPostRegAlloc() | 420 | After the chain, before prologue/epilogue insertion | Post-RA cleanups (AArch64: redundant copy elimination, A57 FP load balancing) |
addRegAssignAndRewriteFast() | 470 | Wraps Fast allocator | Run several allocators in sequence at -O0 |
addRegAssignAndRewriteOptimized() | 471 | Wraps allocator + rewriter | Insert a pass right before allocation, or run several allocators |
Sources: llvm/include/llvm/CodeGen/TargetPassConfig.h:365-471, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:817-886
Pattern 1: Add a Pass Right Before the Allocator
AArch64 does exactly this, and calls the base version so the standard allocator and rewriter still run:
bool AArch64PassConfig::addRegAssignAndRewriteOptimized() {
addPass(createAArch64PostCoalescerPass());
return TargetPassConfig::addRegAssignAndRewriteOptimized();
}
The pass runs after coalescing and scheduling, so it sees the final live intervals and can make last adjustments.
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:970-973
Pattern 2: Allocate Register Classes Separately
Pass a filter to the allocator so each run handles only some classes. AMDGPU defines onlyAllocateSGPRs and onlyAllocateVGPRs and creates allocators with them:
return createGreedyRegisterAllocator(onlyAllocateSGPRs);
...
return createBasicRegisterAllocator(onlyAllocateVGPRs);
A filter has the shape of RegAllocFilterFunc and returns whether a register should be allocated by that run (see framework). Only the last run's rewriter should clear virtual registers.
Sources: llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp:214-365
Pattern 3: Change the Default Allocator
// ToyTargetMachine.cpp (illustrative, not LLVM source)
FunctionPass *ToyPassConfig::createTargetRegisterAllocator(bool Optimized) {
if (Optimized)
return createGreedyRegisterAllocator();
return createFastRegisterAllocator();
}
That is what the base class already does (TargetPassConfig.cpp:1413-1418), so override it only if you really want another default. -regalloc= on the command line always wins.
Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1413-1438
Rules for Passes You Insert
| Position | You may | You must |
|---|---|---|
Before the chain (addPreRegAlloc) | Change instructions freely; MIR is SSA | Keep SSA form |
Between LiveIntervals and the rewriter | Change instructions | Keep SlotIndexes and LiveIntervals up to date (liveness), and declare them preserved |
| After the rewriter | Use physical registers only | Keep kill flags and block live-ins correct; create no virtual registers (unless the scavenger runs later) |
Run llc -verify-machineinstrs while developing: it checks these invariants after every pass.
Bring-up Checklist and Common Failures
Relevant source files
The following files were used as context for generating this wiki page:
This page puts the previous four pages in order: what to write first, how to test each step, and what each common failure means.
Purpose and Scope
A step-by-step plan for a new backend, followed by a table of symptoms and their usual causes.
Order of Work
Stage 1: Registers exist
- ☐
<Target>RegisterInfo.td: every register, sub-register indices,CoveredBySubRegswhere true (9.1). - ☐ One
RegisterClassper operand constraint; non-allocatable classes markedisAllocatable = 0. - ☐
<Target>CallingConv.td: aCalleeSavedRegsfor each calling convention. - ☐
<Target>RegisterInfoderived from<Target>GenRegisterInfo, withgetReservedRegs,getCalleeSavedRegs,getCallPreservedMask,getFrameRegister(9.2). - ☐ Call lowering attaches the register mask to every call.
Test: llc -O0 -stop-before=regallocfast on simple functions. Every virtual register should have one of your classes, and calls should carry your mask name.
Stage 2: -O0 works (Fast allocator)
- ☐
copyPhysRegfor every class pair that can appear in aCOPY(9.3). - ☐
storeRegToStackSlot,loadRegFromStackSlotfor every allocatable class, with aMachineMemOperand. - ☐
eliminateFrameIndex, with frame lowering that assigns slot offsets.
Test: llc -O0 -verify-machineinstrs on functions with branches. Fast spills every value that crosses a block boundary, so this exercises spill and reload code immediately (Fast).
Stage 3: -O2 works (Greedy)
- ☐
isLoadFromStackSlot,isStoreToStackSlot. - ☐
isReMaterializable = 1on constant materialisation instructions. - ☐ Tied operands declared with
Constraints = "$dst = $src", early-clobbers with@earlyclobber(two-address). - ☐
requiresRegisterScavenging/requiresFrameIndexScavengingand an emergency slot if frame offsets can exceed your immediate range (9.2).
Test: llc -O2 -verify-machineinstrs, plus -stress-regalloc=4 (or a small number) to force spills in small functions (framework). Also try -regalloc=basic and -regalloc=pbqp: they use the same hooks in different ways and find different bugs.
Stage 4: Quality
- ☐ Allocation order: scratch registers first, argument registers late (9.1).
- ☐
getRegAllocationHintsfor pairs or short encodings. - ☐
getLargestLegalSuperClassif your classes form a lattice. - ☐
isCopyInstrImplif target moves survive instruction selection. - ☐
foldMemoryOperandImplon CISC-style ISAs. - ☐
AllocationPriorityfor hard-to-place classes (tuples). - ☐ Consider
enableSubRegLiveness()once sub-register lane masks are correct.
Test: compare spill counts with -pass-remarks-missed=regalloc (Tooling) before and after each change.
Symptoms and Causes
| Symptom | Usual cause | Where to look |
|---|---|---|
Target didn't implement TargetInstrInfo::copyPhysReg! | copyPhysReg not overridden | 9.3 |
Target didn't implement TargetInstrInfo::storeRegToStackSlot! (or loadRegFromStackSlot) | Spill hooks missing; first appears when something spills | 9.3 |
Your own llvm_unreachable / assertion in copy or spill code | A register class not handled (often a pair or a cross-class copy) | copyPhysReg, spill hooks |
error: ran out of registers during register allocation | A class with too few allocatable registers for an instruction's operands at once; reserved registers removed too many; tied/early-clobber constraints impossible to satisfy together | getReservedRegs, class membership, operand constraints (framework) |
error: inline assembly requires more registers than available | An inline asm statement needs more registers of a class than are free | The asm constraints; reserved set |
| Values corrupted across calls | Missing or wrong call register mask; callee-saved list does not match what callees really preserve | getCallPreservedMask, CalleeSavedRegs |
| Stack pointer or frame pointer overwritten | Not reserved, or a super-register of it not reserved | getReservedRegs with markSuperRegs |
| Everything spills around every call | Call mask is null (default) or empty | getCallPreservedMask |
-verify-machineinstrs reports liveness errors after your pass | Your pass between LiveIntervals and the rewriter did not update them | Keeping liveness up to date |
Crash in eliminateFrameIndex on large frames | Offset does not fit; no scratch register | Scavenger hooks, emergency slot |
| Many needless copies remain | Copies are target moves the allocator does not recognise; classes too narrow to coalesce | isCopyInstrImpl, class lattice, shouldCoalesce (coalescer) |
| Constants spilled to the stack | Constant moves not rematerialisable | isReMaterializable, isReMaterializableImpl |
Bug disappears with -regalloc=basic | Interaction with Greedy's eviction or splitting; often a hint or super-class hook returning something unsafe | getRegAllocationHints, getLargestLegalSuperClass |
Sources: llvm/lib/CodeGen/RegAllocBase.cpp:216-258, llvm/include/llvm/CodeGen/TargetInstrInfo.h:1087-1226, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:360-364
Writing Tests
- IR to assembly:
; RUN: llc -mtriple=toy -O2 < %s | FileCheck %s, regenerated withllvm/utils/update_llc_test_checks.py. - One pass on MIR: stop before the pass with
-stop-before=greedy -o t.mir, reducet.mirby hand, then; RUN: llc -mtriple=toy -run-pass=greedy -verify-machineinstrs %s -o - | FileCheck %s, regenerated withllvm/utils/update_mir_test_checks.py. - Pressure tests: functions with more simultaneously live values than registers, values live across calls, and loops containing calls.
AArch64 Walkthroughs
Relevant source files
The following files were used as context for generating this wiki page:
Seven examples (six functions, one of them compiled twice) built with the llc from the pinned commit (LLVM 24.0.0git, release build), -mtriple=aarch64 -O2 unless noted. Every MIR and assembly listing on this page is real output, trimmed only by removing assembler directives; ... marks omitted lines.
Purpose and Scope
Each example shows one idea from earlier pages in practice. Read them in order; each says what to look for.
| # | Example | Shows |
|---|---|---|
| 1 | Straight-line arithmetic | Hints and identity copies |
| 2 | Value live across a call | Register masks and callee-saved registers |
| 3 | Simple loop | PHI elimination, coalescing, loop-carried values |
| 4 | Real spills | InlineSpiller stores and reloads |
| 5 | Forced pressure | -stress-regalloc |
| 6 | Loop containing a call | Callee-saved registers versus spilling |
| 7 | The same code at -O0 | Fast allocator |
1. Straight-line Arithmetic
define i32 @f(i32 %a, i32 %b, i32 %c) {
%m = mul i32 %a, %b
%s = add i32 %m, %c
ret i32 %s
}
Before Greedy (-stop-before=greedy):
%1:gpr32 = COPY $w1
%0:gpr32 = COPY $w0
%2:gpr32 = COPY $w2
%4:gpr32 = MADDWrrr %0, %1, %2
$w0 = COPY %4
RET_ReallyLR implicit $w0
After the rewriter:
renamable $w0 = MADDWrrr killed renamable $w0, killed renamable $w1, killed renamable $w2
RET_ReallyLR implicit $w0
Assembly: madd w0, w0, w1, w2 then ret.
What to look for. Each copy from or to $wN gave a copy hint. %0 and %4 don't interfere (%0 dies exactly where %4 is born, see slot indexes), so both got $w0. All four copies became identity copies and the rewriter deleted them.
2. A Value Live Across a Call
declare i32 @g(i32)
define i32 @h(i32 %a, i32 %b) {
%x = call i32 @g(i32 %a)
%y = add i32 %x, %b
ret i32 %y
}
Before Greedy:
%1:gpr32 = COPY $w1
%0:gpr32 = COPY $w0
ADJCALLSTACKDOWN 0, 0, implicit-def dead $sp, implicit $sp
$w0 = COPY %0
BL @g, csr_aarch64_aapcs, implicit-def dead $lr, implicit $sp, implicit $w0, implicit-def $sp, implicit-def $w0
ADJCALLSTACKUP 0, 0, implicit-def dead $sp, implicit $sp
%2:gpr32 = COPY $w0
$w0 = ADDWrr %2, %1
RET_ReallyLR implicit $w0
Assembly:
stp x30, x19, [sp, #-16]! // 16-byte Folded Spill
mov w19, w1
bl g
add w0, w0, w19
ldp x30, x19, [sp], #16 // 16-byte Folded Reload
ret
What to look for. csr_aarch64_aapcs on the BL is the register mask. It says every register outside CSR_AArch64_AAPCS is destroyed by the call. %1 (%b) is live across the call, so checkInterference returns IK_RegMask for every caller-saved register. The first free register is callee-saved w19. Prologue insertion then saves x19 (and x30, because there is a call). The stp/ldp are not allocator spills, even though the comment says "Spill".
3. A Simple Loop
define i32 @sum(ptr %p, i32 %n) {
entry:
br label %loop
loop:
%i = phi i32 [0, %entry], [%i.next, %loop]
%acc = phi i32 [0, %entry], [%acc.next, %loop]
%idx = zext i32 %i to i64
%addr = getelementptr i32, ptr %p, i64 %idx
%v = load i32, ptr %addr
%acc.next = add i32 %acc, %v
%i.next = add i32 %i, 1
%c = icmp ult i32 %i.next, %n
br i1 %c, label %loop, label %exit
exit:
ret i32 %acc.next
}
The snapshots after two-address lowering and after the coalescer are on Preparing Code for Allocation. After the rewriter:
bb.0.entry:
liveins: $w1, $x0
renamable $x9 = COPY $xzr
renamable $w8 = COPY $wzr
bb.1.loop:
liveins: $w1, $w8, $x0, $x9
renamable $w10 = LDRWroX renamable $x0, renamable $x9, 0, 1 :: (load (s32) from %ir.scevgep)
renamable $x9 = nuw nsw ADDXri killed renamable $x9, 1, 0
dead $wzr = SUBSWrr renamable $w9, renamable $w1, implicit-def $nzcv
renamable $w8 = ADDWrr killed renamable $w8, killed renamable $w10
Bcc 3, %bb.1, implicit killed $nzcv
B %bb.2
bb.2.exit:
liveins: $w8
$w0 = COPY killed renamable $w8
RET_ReallyLR implicit $w0
Assembly:
sum:
mov x9, xzr
mov w8, wzr
.LBB0_1:
ldr w10, [x0, x9, lsl #2]
add x9, x9, #1
cmp w9, w1
add w8, w8, w10
b.lo .LBB0_1
mov w0, w8
ret
What to look for.
- Each PHI became one register (
%15→x9,%16→w8) after coalescing. The loop has no copies at all. - Registers come from the rotated allocation order:
w8,x9,w10first. %15.sub_32was rewritten to$w9: a sub-register of$x9.liveins:lists appeared;addMBBLiveInscomputed them.mov w0, w8stays becausew0overlapsx0, which holds the pointer through the whole loop.
4. Real Spills
24 volatile loads, all live across a call. Volatile loads cannot be rematerialised, and 24 values do not fit in the callee-saved registers.
declare void @g()
define i32 @p(ptr %p) {
%q1 = getelementptr i32, ptr %p, i64 1
%v1 = load volatile i32, ptr %q1
... ; %v2 .. %v24 the same way
call void @g()
%s1 = add i32 %v1, %v2
... ; sum all 24
ret i32 %s23
}
After the rewriter (spill and reload lines only):
STRWui killed renamable $w8, %stack.11, 0 :: (store (s32) into %stack.11)
STRWui killed renamable $w8, %stack.2, 0 :: (store (s32) into %stack.2)
... 13 stores in total ...
BL @g, csr_aarch64_aapcs, implicit-def dead $lr, implicit $sp, implicit-def $sp
renamable $w9 = LDRWui %stack.11, 0 :: (load (s32) from %stack.11)
renamable $w12 = LDRWui %stack.12, 0 :: (load (s32) from %stack.12)
... 13 reloads in total ...
Remark (-pass-remarks-missed=regalloc):
remark: <unknown>:0:0: 13 spills 1.300000e+01 total spills cost 13
reloads 1.300000e+01 total reloads cost generated in function
Assembly excerpt:
stp x20, x19, [sp, #144] // 16-byte Folded Spill
str w8, [sp, #32] // 4-byte Spill
stp w8, w10, [sp, #48] // 8-byte Folded Spill
...
bl g
ldp w12, w9, [sp, #12] // 8-byte Folded Reload
ldr w9, [sp, #52] // 4-byte Reload
What to look for.
- 11 values went into callee-saved
w19–w29; the other 13 were spilled, each to its own slot%stack.0–%stack.12. - Each spill is
STRWuiright after its definition; each reload isLDRWuiright before its use. These come fromAArch64InstrInfo::storeRegToStackSlotandloadRegFromStackSlot(TII hooks). - In MIR the slot is still a frame index with offset 0. Prologue/epilogue insertion turned it into
[sp, #32]. - The AArch64 load/store optimiser later paired adjacent slots, hence "8-byte Folded Spill".
A spill that did not happen. The first attempt at this test computed 12 values with mul i32 %a, C instead of loading them. It produced no allocator spills: 11 values went into callee-saved registers, and the constants were rematerialised as mov w24, #11 and so on. Only values that are expensive to recompute get spilled.
5. Forcing Pressure with -stress-regalloc
The loop from example 3, with every register class cut to 2 registers (-stress-regalloc=2):
sum:
sub sp, sp, #32
mov x9, xzr
mov w8, wzr
str w1, [sp, #12] // 4-byte Spill
str x0, [sp] // 8-byte Spill
.LBB0_1:
str w8, [sp, #28] // 4-byte Spill
ldr x8, [sp] // 8-byte Reload
ldr w8, [x8, x9, lsl #2]
add x9, x9, #1
str x9, [sp, #16] // 8-byte Spill
str w8, [sp, #24] // 4-byte Spill
ldr w8, [sp, #12] // 4-byte Reload
cmp w9, w8
ldp w9, w8, [sp, #24] // 8-byte Folded Reload
add w8, w8, w9
ldr x9, [sp, #16] // 8-byte Reload
b.lo .LBB0_1
mov w0, w8
add sp, sp, #32
ret
What to look for. The loop now needs four values (p, n, i, acc) plus a temporary, but only two registers exist. n and p are spilled once before the loop, then reloaded at each use. This is the cheapest way to make a small test exercise your spill hooks while bringing up a backend (checklist).
6. A Loop Containing a Call
declare void @g()
define i32 @lc(ptr %p, i32 %n, i32 %k) {
entry:
br label %loop
loop:
%i = phi i32 [0, %entry], [%i.next, %latch]
%acc = phi i32 [0, %entry], [%acc.next, %latch]
... ; load %v = p[i]; acc += v
%c0 = icmp eq i32 %v, %k
br i1 %c0, label %cold, label %latch
cold:
call void @g()
br label %latch
latch:
... ; i++; loop while i < n
exit:
ret i32 %acc.next
}
Assembly:
lc:
str x30, [sp, #-64]! // 8-byte Folded Spill
stp x24, x23, [sp, #16] // 16-byte Folded Spill
stp x22, x21, [sp, #32] // 16-byte Folded Spill
stp x20, x19, [sp, #48] // 16-byte Folded Spill
mov w19, w2
mov w20, w1
mov x21, x0
mov x23, xzr
mov w22, wzr
b .LBB0_2
.LBB0_1: // %latch
add x23, x23, #1
add w22, w22, w24
cmp w23, w20
b.hs .LBB0_4
.LBB0_2: // %loop
ldr w24, [x21, x23, lsl #2]
cmp w24, w19
b.ne .LBB0_1
bl g
b .LBB0_1
.LBB0_4: // %exit
mov w0, w22
ldp x20, x19, [sp, #48] // 16-byte Folded Reload
...
ret
What to look for. Every value live in the loop (k, n, p, i, acc, v) is also live across bl g, so none of them can sit in a caller-saved register. Greedy put all six in callee-saved w19–x24. That costs four save/restore pairs, once per call of lc, and no memory traffic inside the loop. Splitting around the call would add copies or reloads on every iteration that takes the call. With callee-saved registers free, the cost model (Greedy: callee-saved registers) prefers them. A loop with more live values than callee-saved registers would force splitting or spilling.
7. The Same Code at -O0
Example 1 at -O0. Before the Fast allocator:
%0:gpr32 = COPY $w0
%1:gpr32 = COPY $w1
%2:gpr32 = COPY $w2
%3:gpr32 = MADDWrrr %0, %1, $wzr
%4:gpr32 = ADDWrr %3, %2
$w0 = COPY %4
RET_ReallyLR implicit $w0
After regallocfast:
renamable $w8 = MADDWrrr killed renamable $w0, killed renamable $w1, $wzr
renamable $w0 = ADDWrr killed renamable $w8, killed renamable $w2
RET_ReallyLR implicit killed $w0
What to look for. No combiner ran, so mul and add stay separate (the mul is a madd with wzr). Fast followed the copy chains and removed every copy. There is one block, so no slots were needed. With a branch, values crossing the block boundary would be stored and reloaded.
Reproducing These
llc -mtriple=aarch64 -O2 file.ll -stop-before=greedy -o -
llc -mtriple=aarch64 -O2 file.ll -stop-after=virtregrewriter -o -
llc -mtriple=aarch64 -O2 file.ll -o -
llc -mtriple=aarch64 -O2 file.ll -o /dev/null -pass-remarks-missed=regalloc
llc -mtriple=aarch64 -O2 -stress-regalloc=2 file.ll -o -
llc -mtriple=aarch64 -O0 file.ll -stop-after=regallocfast -o -
See Tooling and Debugging for more.
Tooling and Debugging
Relevant source files
The following files were used as context for generating this wiki page:
Most register allocation questions can be answered with a release llc by looking at MIR before and after each pass. The detailed allocator trace (-debug-only=regalloc) needs a build with assertions.
Purpose and Scope
Which options exist, which work in which kind of build, and a workflow for the common questions: why did this spill, why is this copy still here, and why did allocation fail.
Release Build or Assertions Build
Every option below was tried with the release llc built from the pinned commit (LLVM 24.0.0git, "Optimized build"):
| Option | Release llc |
Notes |
|---|---|---|
-stop-before=P, -stop-after=P | Works | Print MIR as a .mir file and stop |
-print-before=P, -print-after=P | Works | Print MIR with slot indexes (32B, 48B, ...) and keep going |
-run-pass=P1,P2 | Works | Run only these passes on a .mir input |
-verify-machineinstrs | Works | Run the machine verifier after every pass |
-verify-regalloc | Works | Extra verification inside the allocator |
-pass-remarks-missed=regalloc | Works | Greedy's spill and reload counts per function and loop |
-regalloc=fast|basic|greedy|pbqp | Works | Choose the allocator (which pipeline) |
-stress-regalloc=N | Works | Limit every class to N registers |
-join-liveintervals=false | Works | Disable the coalescer |
-split-spill-mode=default|size|speed, -lcr-max-depth=N | Work | Greedy tuning (Greedy options) |
-enable-subreg-liveness | Accepted | Force sub-register liveness on |
-time-passes | Works | Time spent in each pass, including the allocator |
-stats | Accepted | Statistics are only collected in builds with statistics enabled |
-debug-pass=Structure | Works | List the passes that run |
-debug-only=regalloc (and -debug-only=regalloc,register-coalescer,...) | Not available ("Unknown command line argument") | Needs an assertions build: configure with -DLLVM_ENABLE_ASSERTIONS=ON |
Workflow 1: Why Was This Value Spilled?
- Count spills:
llc ... -pass-remarks-missed=regalloc -o /dev/null. No remark means Greedy did not spill. AnySpillcomments in the assembly are then callee-saved saves (how to tell). - Look at the input to the allocator:
-stop-before=greedy. How many values are live at the hot point? Do they cross calls? - Look at its output:
-stop-after=virtregrewriter. Find theSTR...ui %stack.NandLDR...ui %stack.Ninstructions and the registers involved. - In an assertions build:
-debug-only=regalloc. It prints everyselectOrSplitdecision, with the interval, its weight, the stage, and whether it was assigned, evicted, split or spilled. - Experiments:
-regalloc=basic(no splitting) and-split-spill-mode=.... Also compare-O2with and without the scheduler's pressure tracking, by changing the input.
Workflow 2: Why Is This Copy Still Here?
-stop-after=register-coalescer: is the copy still there? If yes, the coalescer refused it. Usual reasons are physical-register copies (kept as hints), no common sub-class, or ashouldCoalesceveto (coalescer).-stop-after=virtregrewriter: does the copy now have different registers on each side? Then the hint was broken, usually because the hinted register is busy (example:mov w0, w8in the loop walkthrough).- If the copy came from splitting, it sits at a split boundary: a block edge or around a call.
Workflow 3: Why Did Allocation Fail?
error: ran out of registers during register allocation or error: inline assembly requires more registers than available:
- Find the instruction: the error names the function; with an assertions build
-debug-only=regallocshows the last interval. - Check that instruction's operand constraints. Do too many operands need the same small class at once? Is there an early-clobber definition plus many uses?
- Check
getReservedRegs: did a recent change reserve too much (checklist)? - Try
-regalloc=basicand-regalloc=pbqp. If every allocator fails, the constraints are impossible. If only Greedy fails, see the last-chance recoloring limits (-lcr-max-depth,-lcr-max-interf).
Workflow 4: Reduce a Bug to a MIR Test
llc -mtriple=aarch64 -O2 bug.ll -stop-before=greedy -o bug.mir
# edit bug.mir down to the smallest function that still fails
llc -mtriple=aarch64 -run-pass=greedy,virtregrewriter -verify-machineinstrs bug.mir -o -
Tried at the pinned commit on the loop example: the .mir round trip produced the same allocation as the full pipeline (renamable $w10 = LDRWroX renamable $x0, renamable $x9, 0, 1). Running just -run-pass=greedy leaves virtual registers in the output, assigned in VirtRegMap but not yet rewritten. Add virtregrewriter to see physical registers.
Turn it into a regression test with llvm/utils/update_mir_test_checks.py.
Reading MIR Quickly
| You see | It means |
|---|---|
%5:gpr32 | Virtual register 5, class gpr32 |
%15.sub_32 | The sub_32 part of %15 |
$w0, $x19 | Physical registers |
renamable $w8 | Assigned by the allocator; may be renamed later |
killed, dead, undef | Last use; never-read definition; value does not matter (flags) |
csr_aarch64_aapcs on a call | Register mask: registers outside it are clobbered |
%stack.3 | Frame index; type: spill-slot in the stack: section means an allocator spill slot |
32B before an instruction | Slot index (only in -print-* output; liveness) |
liveins: $w1, $x0 | Physical registers live into the block (after the rewriter) |
TiedOpsRewritten, NoPHIs, NoVRegs | Function properties: which preparation steps have happened |
Glossary and Where Do I Look
Relevant source files
The following files were used as context for generating this wiki page:
Short definitions of every term used in this wiki, with a link to the page that explains it, followed by a table that maps common questions to the code to read.
Purpose and Scope
A reference page. Terms are in alphabetical order.
Glossary
| Term | Meaning | Page |
|---|---|---|
| Allocation order | The order in which an allocator tries physical registers for a class: hints first, then the class order with reserved registers removed and callee-saved registers last | Framework |
| AllocationPriority | TableGen field (0–31) that pushes a register class earlier in Greedy's queue | TableGen |
| Callee-saved register | Preserved across calls; a function that uses it must save and restore it | Registers |
| Caller-saved (clobbered) register | Destroyed by calls; values live across a call cannot stay in one | Registers |
| Cascade number | Greedy's counter that prevents eviction loops | Greedy |
| Coalescing | Merging the source and destination of a COPY into one register so the copy disappears | Coalescer |
| Complement | Interval 0 in SplitEditor: everything not given to a new split interval | Splitting |
| Copy hint | A preferred register derived from a copy to or from it | Spill weights |
| Early-clobber | A definition that is written before the instruction's uses are read, so it cannot share a register with them | Liveness |
| Edge bundle | A set of block boundaries that must agree on register-or-memory for a value; used by region splitting | Splitting |
| Eviction | Unassigning a lower-priority interval so the current one can take its register; the evicted interval is requeued | Greedy |
| Frame index | Abstract stack slot number (%stack.N) replaced by an address in prologue/epilogue insertion | Rewriting |
| Identity copy | $r = COPY $r; deleted by the rewriter | Rewriting |
| Interference | Two registers live at the same point with different values; they cannot share a physical register | Liveness |
| Lane mask | Bit set describing which parts of a register a sub-register index covers | Registers |
| Live interval | LiveInterval: the set of program points where a virtual register is live, as segments plus value numbers | Liveness |
| LiveRegMatrix | Per-register-unit record of which virtual registers are assigned where; answers interference queries | Framework |
| Local interval | An interval contained in one basic block | Greedy |
| MIR | Machine IR: MachineInstrs in MachineBasicBlocks | Overview |
| PHI-def | A value number defined at a block start where several incoming values merge | Liveness |
| Physical register | A real hardware register ($w0) | Registers |
| Region split | Greedy split that keeps a value in one register over a set of blocks | Splitting |
| Register class | Set of interchangeable physical registers a virtual register may use | Registers |
| Register mask (regmask) | Call operand listing preserved registers; all others are clobbered | Registers |
| Register scavenger | Finds a free physical register after allocation, spilling to an emergency slot if needed | TRI hooks |
| Register unit | Smallest piece of register state never shared in part; physical liveness and interference are tracked per unit | Registers |
| Rematerialisation | Recomputing a cheap value instead of storing and reloading it | Inline spiller |
| Reserved register | Never allocated (sp, wzr, frame pointer when used, ...) | TRI hooks |
| Rewriter | VirtRegRewriter: replaces virtual registers with their assigned physical registers | Rewriting |
| Slot index | Position number of an instruction; four slots per instruction (B, e, r, d), 16 apart | Liveness |
| Snippet | A tiny split piece connected only by copies, spilled together with its sibling | Inline spiller |
| Spill | Keeping a value in a stack slot, with a store after each definition and a load before each use | Spilling |
| Spill weight | Estimated cost of spilling an interval: weighted uses divided by length | Spill weights |
| Split | Cutting an interval into pieces joined by copies | Splitting |
| Stage | Greedy's per-interval progress: RS_New, RS_Assign, RS_Split, RS_Split2, RS_Spill, RS_Done | Greedy |
| Sub-register | Named part of a register (sub_32 of x0 is w0) | Registers |
| Tied operand | A use that must be in the same register as a definition; handled by two-address lowering | Two-address |
| Value number | VNInfo: one definition of a register; lets liveness distinguish values | Liveness |
| Virtual register | Unlimited register name created by instruction selection (%5) | Registers |
| VirtRegMap | Records the physical register or stack slot chosen for each virtual register | Framework |
Where Do I Look?
| Question | Look at |
|---|---|
| Which passes run around allocation, and in what order? | TargetPassConfig::addOptimizedRegAlloc, addFastRegAlloc (Pipeline) |
Why does this value use w19 instead of w8? | It is live across a call; regmask on the call (Walkthrough 2) |
| Why is a copy still there after allocation? | Coalescer output, then hints (Tooling) |
| Why was this spilled? | -pass-remarks-missed=regalloc, then -stop-after=virtregrewriter (Tooling) |
Why are these stp/ldp at entry? | Callee-saved saves from prologue insertion, not spills (Spilling) |
| How does Greedy decide what to do? | RAGreedy::selectOrSplitImpl (Greedy) |
| How is spill code inserted? | InlineSpiller::spillAroundUses and your storeRegToStackSlot (Inline spiller) |
| What must my new backend implement? | Custom backend and its checklist |
| "ran out of registers" | Operand constraints, reserved set, class sizes (Checklist) |
Target didn't implement ... | The named TargetInstrInfo hook (TII hooks) |
| Liveness verifier errors after my pass | Update LiveIntervals (Liveness) |
Part 6: Frame Lowering
Stack layout, prologue/epilogue insertion, callee-saved spills, frame index elimination, shrink wrapping and CFI.
Pages
Frame Lowering Overview
Relevant source files
The following files were used as context for generating this wiki page:
A function's stack frame holds everything that does not fit in registers: incoming stack arguments, callee-saved registers, spill slots, local variables (alloca), and the outgoing argument area for calls. During most of code generation these are abstract frame indices in MachineFrameInfo. After register allocation, the prologue/epilogue insertion pass (PEI) gives every object an offset, asks the target to emit the prologue and epilogue, and rewrites every frame index into a real register plus offset.
Purpose and Scope
This wiki explains how a backend builds stack frames, using AArch64 as the real example and a made-up "Toy" target for minimal code. For the place of frame lowering in a whole backend see the bring-up wiki.
Who Builds the Frame
flowchart LR
ISEL["Instruction selection<br/>CreateFixedObject (stack args)<br/>CreateStackObject (allocas)"] --> RA["Register allocation<br/>CreateSpillStackObject"]
RA --> SW["ShrinkWrap<br/>(save/restore points)"]
SW --> PEI["PEI (prolog-epilog)<br/>layout, prologue, epilogue,<br/>frame index elimination"]
PEI --> MC["AsmPrinter: CFI directives"]
| Stage | Adds to the frame | Page |
|---|---|---|
| Call lowering | Fixed objects for incoming stack arguments, outgoing area size | calling conventions wiki |
| Instruction selection | Stack objects for alloca, variable-sized objects | MachineFrameInfo |
| Register allocation | Spill slots | regalloc spilling |
| Shrink wrapping | Where the prologue and epilogue go | Shrink Wrapping |
| PEI | Callee-saved slots, offsets, prologue/epilogue, real addresses | The PEI Pass |
In the pipeline (llc -O2 -debug-pass=Structure, AArch64): ... -greedy -virtregrewriter ... -shrink-wrap -prolog-epilog -machine-latecleanup ....
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:211-283
AArch64 Frame Shapes
Real output from llc -O2 -mtriple=aarch64-linux-gnu:
| Function | Frame |
|---|---|
| Leaf, no spills | None: mul x0, x0, x1 / ret |
| One call, one value kept | stp x30, x19, [sp, #-16]! ... ldp x30, x19, [sp], #16 |
70000-byte alloca | stp x29, x30 then sub sp, sp, #17, lsl #12 and sub sp, sp, #368 |
Variable-sized alloca | Frame pointer: mov x29, sp ... mov sp, x29 |
| Call only on a slow path | Prologue moved after the branch (shrink wrapping) |
The walkthroughs show each in full with the MIR before and after PEI.
Pages
MachineFrameInfo
Relevant source files
The following files were used as context for generating this wiki page:
MachineFrameInfo is the per-function table of stack objects. Each object has an index (the frame index), a size, an alignment, and, once PEI has run, an offset. Code refers to objects only by index (%stack.0, %fixed-stack.1 in MIR) until frame index elimination replaces the index with a register and an offset.
Purpose and Scope
The kinds of objects, how they are created, and the function-wide flags frame lowering reads. The pass that assigns offsets is on The PEI Pass.
Object Kinds
| Kind | Created with | Index | Offset known when created? | Example |
|---|---|---|---|---|
| Fixed object | CreateFixedObject(Size, SPOffset, IsImmutable) (line 723) | Negative | Yes, relative to SP at function entry | Incoming stack argument |
| Fixed spill object | CreateFixedSpillStackObject (728) | Negative | Yes | Some callee-saved slots |
| Stack object | CreateStackObject(Size, Align, IsSpillSlot) (831) | ≥ 0 | No, PEI assigns it | alloca, spill slot |
| Variable-sized object | CreateVariableSizedObject(Align, Alloca) (851) | ≥ 0 | No; sets HasVarSizedObjects | alloca i8, i64 %n |
isFixedObjectIndex (732) tells them apart. Each object also has a stack ID (getStackID, 794): Default for normal memory, others (such as scalable vectors on AArch64) for objects laid out separately.
Sources: llvm/include/llvm/CodeGen/MachineFrameInfo.h:112-129, llvm/include/llvm/CodeGen/MachineFrameInfo.h:723-732, llvm/include/llvm/CodeGen/MachineFrameInfo.h:794, llvm/include/llvm/CodeGen/MachineFrameInfo.h:831-851
Where Objects Come From
flowchart TD
LFA["LowerFormalArguments"] -->|"CreateFixedObject"| F["fixed objects (negative indices)"]
FLI["FunctionLoweringInfo (static allocas)"] -->|"CreateStackObject"| S["stack objects"]
DYN["dynamic alloca"] -->|"CreateVariableSizedObject"| V["variable-sized"]
RA["spiller"] -->|"CreateSpillStackObject"| S
PEI["PEI: assignCalleeSavedSpillSlots"] --> S
AArch64's LowerFormalArguments creates one fixed object per stack argument:
int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9515
Function-Wide Information
| Accessor | Line | Meaning |
|---|---|---|
hasVarSizedObjects() | 371 | Any dynamic alloca; usually forces a frame pointer |
getObjectOffset(FI) | 553 | Offset from the incoming SP (valid after PEI) |
getStackSize() / setStackSize() | 612 / 615 | Total frame size, set by PEI |
getMaxAlign() | 627 | Largest object alignment; may force stack realignment |
adjustsStack() | 644 | Function calls something or otherwise moves SP |
getMaxCallFrameSize() | 698 | Largest outgoing argument area of any call |
setCalleeSavedInfo() | 863 | List of callee-saved registers and their slots (CalleeSavedInfo, line 36) |
These appear in the frameInfo: section of MIR. For the AArch64 withcall function after PEI:
stackSize: 16
adjustsStack: true
hasCalls: true
maxCallFrameSize: 0
- { id: 0, name: '', type: spill-slot, offset: -8, size: 8, alignment: 8,
stack-id: default, callee-saved-register: '$x19', callee-saved-restored: true,
- { id: 1, name: '', type: spill-slot, offset: -16, size: 8, alignment: 8,
stack-id: default, callee-saved-register: '$lr', callee-saved-restored: true,
Before PEI the same function had stackSize: 0 and an empty stack: list; the two callee-saved slots were added by PEI.
Sources: llvm/include/llvm/CodeGen/MachineFrameInfo.h:36, llvm/include/llvm/CodeGen/MachineFrameInfo.h:371, llvm/include/llvm/CodeGen/MachineFrameInfo.h:553-698, llvm/include/llvm/CodeGen/MachineFrameInfo.h:863
TargetFrameLowering Hooks
Relevant source files
The following files were used as context for generating this wiki page:
TargetFrameLowering is the interface PEI and shrink wrapping call to learn about the target's stack and to emit target code. A few hooks are pure virtual; the rest have defaults that work for a simple target. The subtarget owns one instance and returns it from getFrameLowering().
Purpose and Scope
Every hook a backend usually touches, its default, and what AArch64 does. The order in which PEI calls them is on The PEI Pass.
Constructor
TargetFrameLowering(StackDirection D, Align StackAl, int LAO,
StackDirection (StackGrowsDown or StackGrowsUp, enum at line 51), the stack alignment (must match the S part of the data layout), and the local area offset (where locals start relative to the incoming SP, usually 0).
Sources: llvm/include/llvm/CodeGen/TargetFrameLowering.h:51, llvm/include/llvm/CodeGen/TargetFrameLowering.h:86
The Hooks
| Hook | Header line | Default | AArch64 (line in AArch64FrameLowering.cpp) |
|---|---|---|---|
emitPrologue(MF, MBB) | 211 | pure virtual | 1236: delegates to AArch64PrologueEmitter |
emitEpilogue(MF, MBB) | 213 | pure virtual | 1242: delegates to AArch64EpilogueEmitter |
hasFPImpl(MF) | 520 | pure virtual | 568 |
hasReservedCallFrame(MF) | 315 | !hasFP(MF) | 659: no variable-sized objects |
eliminateCallFramePseudoInstr | 431 | llvm_unreachable | 669 |
determineCalleeSaves(MF, SavedRegs, RS) | 401 | callee-saved registers that are modified | 2521 |
assignCalleeSavedSpillSlots | 165 | return false (let PEI choose) | 2800 |
spillCalleeSavedRegisters | 263 | return false (PEI uses storeRegToStackSlot) | 1975: paired stp |
restoreCalleeSavedRegisters | 285 | return false (PEI uses loadRegFromStackSlot) | 2194: paired ldp |
processFunctionBeforeFrameFinalized | 409 | nothing | 3014 |
getFrameIndexReference(MF, FI, FrameReg) | 338 | offset from getFrameRegister | via resolveFrameIndexReference (1372) |
enableShrinkWrapping(MF) | 194 | false | overridden in AArch64FrameLowering.h:110 |
canUseAsPrologue / canUseAsEpilogue | 458 / 470 | true | 955 |
The declarations of assignCalleeSavedSpillSlots and restoreCalleeSavedRegisters are at TargetFrameLowering.h:165 and TargetFrameLowering.h:285; the default hasReservedCallFrame (return !hasFP(MF);) is at TargetFrameLowering.h:315-317; AArch64's shrink-wrapping override is at AArch64FrameLowering.h:110.
Sources: llvm/include/llvm/CodeGen/TargetFrameLowering.h:194-520, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:568, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:955, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:1236-1246, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:1372, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:1975, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:2194, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:2521, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:2800, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:3014
hasFP
hasFP (line 306 of the header) is the public entry and calls the target's hasFPImpl. AArch64 needs a frame pointer when the user asked for one, or when SP-relative addressing would not work:
// Retain behavior of always omitting the FP for leaf functions when possible.
if (MF.getTarget().Options.DisableFramePointerElim(MF))
return true;
if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
MFI.hasStackMap() || MFI.hasPatchPoint() ||
RegInfo->hasStackRealignment(MF))
return true;
With a variable-sized object, SP moves by an unknown amount, so locals must be addressed from x29; that is why the dynalloca walkthrough sets up mov x29, sp.
Sources: llvm/include/llvm/CodeGen/TargetFrameLowering.h:306, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:588-594
Call-Frame Pseudos
If the call frame is reserved (part of the fixed frame), ADJCALLSTACKDOWN/UP can just be deleted. Otherwise they become real SP adjustments around each call:
bool AArch64FrameLowering::hasReservedCallFrame(
const MachineFunction &MF) const {
...
return !MF.getFrameInfo().hasVarSizedObjects();
}
MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
...
if (!hasReservedCallFrame(MF)) {
int64_t Amount = I->getOperand(0).getImm();
Amount = alignTo(Amount, getStackAlign());
if (!IsDestroy)
Amount = -Amount;
The outgoing argument area of a call is covered on the calling conventions LowerCall page.
Sources: llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:659-686
Prologue and Epilogue Emitters
At this commit AArch64 moved the prologue and epilogue bodies out of AArch64FrameLowering.cpp into helper classes:
| Function | Line in AArch64PrologueEpilogue.cpp |
|---|---|
AArch64PrologueEmitter::emitPrologue | 638 |
AArch64PrologueEmitter::emitFramePointerSetup | 1017 |
AArch64PrologueEmitter::emitCalleeSavedGPRLocations (CFI) | 1253 |
AArch64EpilogueEmitter::emitEpilogue | 1355 |
shouldCombineCSRLocalStackBump | 308 |
shouldCombineCSRLocalStackBump decides whether the callee-saved store and the local-area sub sp can be merged into one pre-indexed stp (as in stp x30, x19, [sp, #-16]!).
Sources: llvm/lib/Target/AArch64/AArch64PrologueEpilogue.cpp:308, llvm/lib/Target/AArch64/AArch64PrologueEpilogue.cpp:638, llvm/lib/Target/AArch64/AArch64PrologueEpilogue.cpp:1017, llvm/lib/Target/AArch64/AArch64PrologueEpilogue.cpp:1253, llvm/lib/Target/AArch64/AArch64PrologueEpilogue.cpp:1355
Related Hooks Elsewhere
TargetRegisterInfo provides eliminateFrameIndex, getFrameRegister, requiresRegisterScavenging and hasBasePointer (see Frame Index Elimination and the regalloc TRI hooks page). TargetInstrInfo provides storeRegToStackSlot and loadRegFromStackSlot, used for default callee-saved spills (regalloc TII hooks).
The PEI Pass
Relevant source files
The following files were used as context for generating this wiki page:
The prologue/epilogue insertion pass (PEIImpl, pass name prolog-epilog) runs once per function after register allocation and shrink wrapping. It performs the steps below in a fixed order. Each step either changes MachineFrameInfo or the instructions, and several call target hooks.
Purpose and Scope
The order of steps in PEIImpl::run and what each one does. The hooks themselves are on TargetFrameLowering Hooks.
The Order
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
1. Call Frame Information
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
2. Save and Restore Blocks
// 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
3. Callee-Saved Registers
// 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
5. Frame Object Offsets
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
6. Prologue and Epilogue
// 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
7–8. Frame Indices and Scavenging
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
Seeing It
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.
Callee-Saved Registers and Stack Layout
Relevant source files
The following files were used as context for generating this wiki page:
A callee-saved register must hold the same value on return as on entry. If the register allocator used one, the function has to save it in the prologue and restore it in the epilogue. PEI decides which registers need saving, gives each a stack slot, and inserts the saves and restores, with three target hooks that can each take over one part.
Purpose and Scope
The three steps (decide, assign slots, emit code), the defaults, and how AArch64 pairs saves into stp/ldp. Where the callee-saved list comes from is on the calling conventions wiki's TableGen page; how the allocator chooses to use them is on the regalloc registers page.
Three Steps
flowchart LR
D["determineCalleeSaves<br/>which registers"] --> A["assignCalleeSavedSpillSlots<br/>which slots"]
A --> S["spillCalleeSavedRegisters / restoreCalleeSavedRegisters<br/>which instructions"]
| Step | Default | AArch64 (AArch64FrameLowering.cpp) |
|---|---|---|
| Decide | TargetFrameLowering::determineCalleeSaves: every callee-saved register that is modified in the function | 2521: calls the default, then adds LR/FP when a frame record is needed, pairs registers, may add one extra register for the scavenger |
| Slots | PEI's static assignCalleeSavedSpillSlots (PrologEpilogInserter.cpp:445) creates one spill slot per register, unless the target hook returns true | 2800: assigns slots so pairs are adjacent |
| Emit | insertCSRSaves/insertCSRRestores → per-register spillCalleeSavedRegister → storeRegToStackSlot | 1975 / 2194: one stp/ldp per pair |
AArch64's override starts by calling the generic version:
void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
BitVector &SavedRegs,
RegScavenger *RS) const {
// All calls are tail calls in GHC calling conv, and functions have no
// prologue/epilogue.
if (MF.getFunction().getCallingConv() == CallingConv::GHC)
return;
...
TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Sources: llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:2521-2545, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:1975, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:2194, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:2800, llvm/lib/CodeGen/PrologEpilogInserter.cpp:445, llvm/lib/CodeGen/TargetFrameLoweringImpl.cpp:211-240
AArch64 Pairing
AArch64 can store two 64-bit registers with one stp, and the pre-indexed form also moves SP. So instead of the default one-store-per-register, spillCalleeSavedRegisters groups the saved registers into pairs and emits one store per pair. producePairRegisters (line 454) decides whether pairing is allowed for the function.
Real output (llc -O2 -mtriple=aarch64-linux-gnu), withcall, which keeps one value (x19) live across a call:
stp x30, x19, [sp, #-16]! // 16-byte Folded Spill
...
ldp x30, x19, [sp], #16 // 16-byte Folded Reload
The MIR after PEI shows the two slots behind that one instruction:
early-clobber $sp = frame-setup STPXpre killed $lr, killed $x19, $sp, -2 :: (store (s64) into %stack.1), (store (s64) into %stack.0)
...
early-clobber $sp, $lr, $x19 = frame-destroy LDPXpost $sp, 2 :: (load (s64) from %stack.1), (load (s64) from %stack.0)
%stack.0 (x19, offset −8) and %stack.1 (lr, offset −16) are the two callee-saved slots; the -2 is the pre-decrement in 8-byte units.
Sources: llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:454
With a Frame Pointer
With -frame-pointer=all, x29 and x30 form the frame record and are always the first pair; the remaining callee-saved register is stored alone:
withcall: // @withcall
.cfi_startproc
stp x29, x30, [sp, #-32]! // 16-byte Folded Spill
str x19, [sp, #16] // 8-byte Spill
mov x29, sp
...
ldr x19, [sp, #16] // 8-byte Reload
ldp x29, x30, [sp], #32 // 16-byte Folded Reload
ret
The frame grows to 32 bytes because AArch64 keeps SP 16-byte aligned; the odd register gets a 16-byte area of its own.
Layout Order
calculateFrameObjectOffsets places, from the incoming SP downwards: fixed objects (incoming arguments are above SP), callee-saved slots, the local block, protected objects (stack protector), the remaining locals and spill slots, and finally the reserved outgoing call frame at the bottom (see The PEI Pass). On AArch64 this means callee-saved registers sit right below the incoming SP, which is why the prologue can combine the save and the SP decrement.
Frame Index Elimination and the Register Scavenger
Relevant source files
The following files were used as context for generating this wiki page:
After PEI has laid out the frame, every instruction operand that names a frame index (%stack.0, %fixed-stack.1) must become a real base register plus an offset. PEI calls TargetRegisterInfo::eliminateFrameIndex once per such operand. If the offset does not fit the instruction's immediate field, the target must build the address in a scratch register; because register allocation is over, that register comes from the register scavenger.
Purpose and Scope
What eliminateFrameIndex must do, how AArch64 does it, and when the scavenger is needed. The PEI step that calls it is on The PEI Pass. The register allocator's own rewriting of virtual registers (before PEI) is on the regalloc rewriting page.
The Hook
bool AArch64RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
int SPAdj, unsigned FIOperandNum,
RegScavenger *RS) const {
| Parameter | Meaning |
|---|---|
II | The instruction |
SPAdj | SP adjustment in effect here (non-zero only between un-eliminated call-frame pseudos) |
FIOperandNum | Index of the frame-index operand |
RS | Scavenger, if requiresRegisterScavenging returned true |
| return value | true if the instruction was erased |
Sources: llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:978-980
AArch64's Steps
flowchart TD
A["frame index FI"] --> B["resolveFrameIndexReference:<br/>choose FP or SP (or base pointer), compute StackOffset"]
B --> C["rewriteAArch64FrameIndex:<br/>fold offset into the immediate if legal"]
C -->|fits| D["done"]
C -->|does not fit| E["create virtual scratch register,<br/>emitFrameOffset base+offset into it"]
E --> F["scavengeFrameVirtualRegs<br/>gives it a physical register later"]
} else {
Offset = TFI->resolveFrameIndexReference(
MF, FrameIndex, FrameReg, /*PreferFP=*/false, /*ForSimm=*/true);
}
// Modify MI as necessary to handle as much of 'Offset' as possible
if (rewriteAArch64FrameIndex(MI, FIOperandNum, FrameReg, Offset, TII))
return true;
assert((!RS || !RS->isScavengingFrameIndex(FrameIndex)) &&
"Emergency spill slot is out of reach");
Before that, special cases are handled: STACKMAP/PATCHPOINT/STATEPOINT (operand becomes register + immediate directly), LOCAL_ESCAPE, and memory-tagging instructions. resolveFrameIndexReference (in AArch64FrameLowering.cpp, line 1372, with the work in resolveFrameOffsetReference at 1383) decides whether to address from SP or FP: SP when the offset is small and SP is stable, FP when there are variable-sized objects.
Sources: llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:995-1060, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:1372-1383
Example
In the bigframe function (one 70000-byte alloca passed to a call), before PEI the address is a frame index:
$x0 = ADDXri %stack.0.buf, 0, 0
After PEI the buffer is at the bottom of the frame, so the index became $sp with offset 0:
$x0 = ADDXri $sp, 0, 0
The 70000-byte SP adjustment itself does not fit one add/sub immediate (12 bits, optionally shifted by 12), so the prologue splits it into sub sp, sp, #17, lsl #12 (69632) and sub sp, sp, #368.
The Register Scavenger
RegScavenger (class at RegisterScavenging.h:35) tracks which physical registers are free at a point after allocation. A target that may need scratch registers during elimination:
- Returns
truefromrequiresRegisterScavenging(AArch64:AArch64RegisterInfo.cpp:758) and usuallyrequiresFrameIndexScavenging(787), so PEI creates the scavenger and runsscavengeFrameVirtualRegsafterwards. - In
eliminateFrameIndex, creates a virtual register for the scratch value, as AArch64 does withcreateVirtualRegister(&AArch64::GPR64RegClass). - Reserves an emergency spill slot in
processFunctionBeforeFrameFinalizedwithRS->addScavengingFrameIndex(FI)(RegisterScavenging.h:113) when a frame is large, so the scavenger can spill a register if none is free.
| Function | Line in RegisterScavenging.cpp |
Job |
|---|---|---|
RegScavenger::spill | 233 | Save a register to the emergency slot |
RegScavenger::scavengeRegisterBackwards | 306 | Find a free register of a class, walking backwards |
scavengeFrameVirtualRegsInBlock | 401 | Replace virtual registers in one block |
llvm::scavengeFrameVirtualRegs | 473 | Do it for the whole function |
Sources: llvm/include/llvm/CodeGen/RegisterScavenging.h:35, llvm/include/llvm/CodeGen/RegisterScavenging.h:113, llvm/lib/CodeGen/RegisterScavenging.cpp:233-473, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:758-787, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:1031-1045
For a New Target
Start with frames small enough that every offset fits (assert on overflow, as the Toy example on the bring-up frame page does). Then add: requiresRegisterScavenging and requiresFrameIndexScavenging returning true, a virtual scratch register plus a "load immediate + add" sequence for large offsets, and an emergency slot when the frame size estimate exceeds the immediate range.
Shrink Wrapping
Relevant source files
The following files were used as context for generating this wiki page:
By default the prologue goes in the entry block and the epilogue in every return block, so even a fast path that never touches the stack pays for the frame. Shrink wrapping (-shrink-wrap, run just before PEI) moves the save point down and the restore point up, to the smallest region that contains every use of callee-saved registers and stack objects.
Purpose and Scope
What the pass computes, how PEI uses it, and what a target must provide. The PEI side is on The PEI Pass.
What It Computes
flowchart LR
A["find blocks that use CSRs or frame indices<br/>(useOrDefCSROrFI)"] --> B["Save = common dominator of those blocks"]
B --> C["Restore = common post-dominator"]
C --> D["move out of loops; ask target canUseAsPrologue / canUseAsEpilogue"]
D --> E["MFI.setSavePoints / setRestorePoints"]
| Function | Line | Job |
|---|---|---|
useOrDefCSROrFI | 304 | Does an instruction need the frame (CSR use, frame index, SP use)? |
postShrinkWrapping | 584 | Second chance to move the points when the first attempt fails |
updateSaveRestorePoints | 701 | Fold a new user block into the current points |
performShrinkWrapping | 836 | Walk blocks in RPO and build the points |
ShrinkWrapImpl::run | 945 | Driver; gives up on irreducible CFGs |
isShrinkWrapEnabled | 1039 | Command line, target hook, Windows CFI and sanitizers |
The result is just two blocks stored in MachineFrameInfo:
SaveRestorePoints SavePoints({{Save, {}}});
SaveRestorePoints RestorePoints({{Restore, {}}});
MFI.setSavePoints(SavePoints);
MFI.setRestorePoints(RestorePoints);
PEI's calculateSaveRestoreBlocks then uses them instead of the entry and return blocks (only one save and one restore point are supported).
Sources: llvm/lib/CodeGen/ShrinkWrap.cpp:304, llvm/lib/CodeGen/ShrinkWrap.cpp:584, llvm/lib/CodeGen/ShrinkWrap.cpp:701, llvm/lib/CodeGen/ShrinkWrap.cpp:836, llvm/lib/CodeGen/ShrinkWrap.cpp:945-996, llvm/lib/CodeGen/PrologEpilogInserter.cpp:411-433
When It Runs
switch (EnableShrinkWrapOpt) {
case cl::boolOrDefault::BOU_UNSET:
return TFI->enableShrinkWrapping(MF) &&
// Windows with CFI has some limitations that make it impossible
// to use shrink-wrapping.
!MF.getTarget().getMCAsmInfo().usesWindowsCFI() &&
...
case cl::boolOrDefault::BOU_TRUE:
return true;
case cl::boolOrDefault::BOU_FALSE:
return false;
}
So a target opts in with enableShrinkWrapping (default false, TargetFrameLowering.h:194), and -enable-shrink-wrap=true/false (option at line 99) overrides it. Sanitizer builds turn it off.
Sources: llvm/lib/CodeGen/ShrinkWrap.cpp:99, llvm/lib/CodeGen/ShrinkWrap.cpp:1039-1066, llvm/include/llvm/CodeGen/TargetFrameLowering.h:194-196
Example
define i64 @shrink(i64 %a, i1 %c) {
entry:
br i1 %c, label %slow, label %fast
fast:
ret i64 %a
slow:
%r = call i64 @h(i64 %a)
%s = add i64 %r, %a
ret i64 %s
}
llc -O2 -mtriple=aarch64-linux-gnu (shrink wrapping on, the AArch64 default):
shrink: // @shrink
.cfi_startproc
tbz w1, #0, .LBB4_2
stp x30, x19, [sp, #-16]! // 16-byte Folded Spill
.cfi_def_cfa_offset 16
.cfi_offset w19, -8
.cfi_offset w30, -16
mov x19, x0
bl h
add x0, x0, x19
ldp x30, x19, [sp], #16 // 16-byte Folded Reload
.LBB4_2: // %common.ret
ret
With -enable-shrink-wrap=false:
shrink: // @shrink
.cfi_startproc
stp x30, x19, [sp, #-16]! // 16-byte Folded Spill
.cfi_def_cfa_offset 16
.cfi_offset w19, -8
.cfi_offset w30, -16
tbz w1, #0, .LBB4_2
mov x19, x0
bl h
add x0, x0, x19
.LBB4_2: // %common.ret
ldp x30, x19, [sp], #16 // 16-byte Folded Reload
ret
With shrink wrapping, the fast path (tbz taken) runs two instructions and never touches memory.
Target Requirements
enableShrinkWrappingreturnstrue.emitPrologue/emitEpiloguemust work in any block, not just entry/return (for example, they must not assume no live registers).canUseAsPrologue/canUseAsEpilogue(defaulttrue) must reject blocks where the prologue/epilogue would clobber a live register, if it needs a scratch register.- CFI must be correct at both points; AArch64 enables the CFI fixup pass (
setCFIFixup(true)) so unwind info stays valid on paths that skip the prologue (see CFI).
CFI and Unwind Information
Relevant source files
The following files were used as context for generating this wiki page:
Debuggers, profilers and C++ exception unwinding need to know, at every instruction, how to find the caller's frame: where the canonical frame address (CFA) is, and where each saved register is stored. On ELF this is DWARF call frame information (CFI). Frame lowering produces it: while emitting the prologue, the target inserts CFI_INSTRUCTION pseudo instructions, which the AsmPrinter turns into .cfi_* directives and the MC layer turns into the .eh_frame section.
Purpose and Scope
Which CFI the prologue emits, how it looks in MIR and assembly, and how shrink wrapping interacts with it. How MC encodes .eh_frame is on the MC wiki's streamers page.
From Prologue to Directive
flowchart LR
P["emitPrologue"] -->|"BuildMI CFI_INSTRUCTION<br/>(MCCFIInstruction)"| MIR["frame-setup CFI_INSTRUCTION ..."]
MIR --> AP["AsmPrinter"]
AP --> S[".cfi_def_cfa_offset / .cfi_offset"]
S --> EH[".eh_frame (MC)"]
What AArch64 Emits
After PEI (-stop-after=prolog-epilog), withcall:
early-clobber $sp = frame-setup STPXpre killed $lr, killed $x19, $sp, -2 :: (store (s64) into %stack.1), (store (s64) into %stack.0)
frame-setup CFI_INSTRUCTION def_cfa_offset 16
frame-setup CFI_INSTRUCTION offset $w19, -8
frame-setup CFI_INSTRUCTION offset $w30, -16
and the assembly:
stp x30, x19, [sp, #-16]! // 16-byte Folded Spill
.cfi_def_cfa_offset 16
.cfi_offset w19, -8
.cfi_offset w30, -16
| Directive | Meaning |
|---|---|
.cfi_startproc / .cfi_endproc | Function boundaries (emitted by the AsmPrinter, not frame lowering) |
.cfi_def_cfa_offset N | CFA is sp + N after this instruction |
.cfi_def_cfa w29, N | CFA is x29 + N (used once a frame pointer is set up) |
.cfi_offset wR, -K | Register R is saved at CFA - K |
With a frame pointer (-frame-pointer=all) the CFA is rebased on x29 so later SP changes need no more CFI:
stp x29, x30, [sp, #-32]! // 16-byte Folded Spill
str x19, [sp, #16] // 8-byte Spill
mov x29, sp
.cfi_def_cfa w29, 32
.cfi_offset w19, -16
.cfi_offset w30, -24
.cfi_offset w29, -32
Without a frame pointer, every SP change needs a new .cfi_def_cfa_offset; the 70000-byte bigframe emits .cfi_def_cfa_offset 70016 once, after both sub sp instructions.
AArch64PrologueEmitter::emitCalleeSavedGPRLocations is the function that emits the offset entries for saved general-purpose registers.
Sources: llvm/lib/Target/AArch64/AArch64PrologueEpilogue.cpp:1253, llvm/lib/Target/AArch64/AArch64PrologueEpilogue.cpp:1017
Shrink Wrapping and the CFI Fixup Pass
CFI describes the state at each instruction in address order. When shrink wrapping puts the prologue in a non-entry block, the fall-through and the taken path disagree about the frame. AArch64 turns on the generic CFI fixup pass (-cfi-fixup, near the end of the pipeline) which inserts .cfi_remember_state/.cfi_restore_state style corrections where needed:
// AArch64 supports fixing up the DWARF unwind information.
if (!getMCAsmInfo().usesWindowsCFI())
setCFIFixup(true);
Windows on Arm uses SEH unwind codes instead (usesWindowsCFI), which is also why shrink wrapping is disabled there.
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:426-428, llvm/lib/CodeGen/ShrinkWrap.cpp:1044-1047
For a New Target
- In
MCAsmInfo, enable DWARF CFI (ExceptionsType = ExceptionHandling::DwarfCFI) and give the initial frame state (CFA = SP + 0 at entry) in the MC asm info factory. See the MC wiki's MCAsmInfo page. - In
emitPrologue, after each SP change emitMCCFIInstruction::cfiDefCfaOffset; after each callee-saved store emitMCCFIInstruction::createOffset; after setting up the frame pointer emitcfiDefCfa(FP, ...). UseTII.get(TargetOpcode::CFI_INSTRUCTION)withMF.addFrameInst(...)and mark themFrameSetup. - Give every register a
DwarfRegNumin TableGen so the directives can name it. - If you enable shrink wrapping, either enable CFI fixup or make sure the epilogue path is described correctly.
(Step details are illustrative; check the MCCFIInstruction factory names in llvm/include/llvm/MC/MCDwarf.h at your LLVM version.)
Custom Backend Guide and Checklist
Relevant source files
The following files were used as context for generating this wiki page:
Frame lowering for a new target is best built in stages: fixed frames first, then callee-saved registers, then a frame pointer, then large frames and dynamic allocation, then shrink wrapping and CFI. Each stage has a small test. All code here is for the made-up "Toy" target and is illustrative, not LLVM source.
Purpose and Scope
The order of work and a checklist. The minimal ToyFrameLowering and eliminateFrameIndex are on the bring-up frame page; the hooks are described on TargetFrameLowering Hooks.
Stages
| Stage | Write | Test |
|---|---|---|
| 1. Fixed frame | Constructor, emitPrologue/emitEpilogue (one SP add/sub), hasFPImpl returning false, eliminateFrameIndex for small offsets, eliminateCallFramePseudoInstr that erases | A function with a local array compiles; stackSize in MIR matches the sub sp |
| 2. Callee saves | storeRegToStackSlot/loadRegFromStackSlot in ToyInstrInfo (PEI uses them through the default spillCalleeSavedRegister) | A value live across a call: saved and restored around the body |
| 3. Frame pointer | hasFPImpl true for hasVarSizedObjects() and DisableFramePointerElim; set up FP in the prologue, restore SP from FP in the epilogue; reserve FP in getReservedRegs | -frame-pointer=all; a dynamic alloca |
| 4. Non-reserved call frame | hasReservedCallFrame false with variable-sized objects; eliminateCallFramePseudoInstr emits SP adjustments | Call inside a function with a dynamic alloca |
| 5. Large frames | requiresRegisterScavenging, scratch register in eliminateFrameIndex, emergency slot in processFunctionBeforeFrameFinalized | 100 KB alloca |
| 6. Shrink wrapping | enableShrinkWrapping, check canUseAsPrologue | Early-return function as on Shrink Wrapping |
| 7. CFI | CFI_INSTRUCTIONs in the prologue | .cfi_* directives present; unwinding works in a debugger |
Prologue With Callee Saves and FP (Illustrative)
Illustrative, not LLVM source.
void ToyFrameLowering::emitPrologue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
MachineFrameInfo &MFI = MF.getFrameInfo();
const auto &TII = *MF.getSubtarget<ToySubtarget>().getInstrInfo();
auto MBBI = MBB.begin();
DebugLoc DL;
uint64_t Size = MFI.getStackSize();
// PEI already inserted the callee-saved stores (FrameSetup flag) at the
// top of the block; this sub must come before them, so insert at begin().
BuildMI(MBB, MBBI, DL, TII.get(Toy::ADDI), Toy::SP)
.addReg(Toy::SP).addImm(-(int64_t)Size)
.setMIFlag(MachineInstr::FrameSetup);
unsigned CFI = MF.addFrameInst(
MCCFIInstruction::cfiDefCfaOffset(nullptr, Size));
BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFI).setMIFlag(MachineInstr::FrameSetup);
// Skip the callee-saved stores, then set up FP if needed.
while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
++MBBI;
if (hasFP(MF))
BuildMI(MBB, MBBI, DL, TII.get(Toy::ADDI), Toy::R11)
.addReg(Toy::SP).addImm(0)
.setMIFlag(MachineInstr::FrameSetup);
}
Callee-saved slots get their offsets from calculateFrameObjectOffsets, so the stores PEI inserted address them through frame indices that eliminateFrameIndex resolves later; the prologue does not need to know the offsets.
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:211-283, llvm/lib/CodeGen/PrologEpilogInserter.cpp:618-650
Checklist
- ☐ Stack alignment in the constructor equals the data layout
Svalue - ☐
getStackSize()is used, never recomputed, inemitPrologue/emitEpilogue - ☐ Prologue and epilogue instructions carry
FrameSetup/FrameDestroy - ☐ Epilogue is inserted before the first terminator, including
TCRETURNtail calls - ☐
eliminateCallFramePseudoInstris overridden ifADJCALLSTACKDOWN/UPexist - ☐
getFrameRegisteragrees withhasFP - ☐ FP (and base pointer, if any) are reserved when used
- ☐ Offsets out of immediate range are handled, or asserted
- ☐
-verify-machineinstrspasses afterprolog-epilog - ☐ MIR before/after
prolog-epilogcompared for each test (see Tooling)
AArch64 Walkthroughs
Relevant source files
The following files were used as context for generating this wiki page:
Five functions compiled with the real llc (LLVM 24.0.0git release build at a2171756) using -O2 -mtriple=aarch64-linux-gnu. MIR is from -stop-before=prolog-epilog and -stop-after=prolog-epilog.
Purpose and Scope
Concrete evidence for each frame shape: leaf, call, large frame, dynamic alloca, and shrink wrapping. Each case links back to the page that explains it.
1. Leaf Function
define i64 @leaf(i64 %a, i64 %b) {
%s = mul i64 %a, %b
ret i64 %s
}
leaf: // @leaf
.cfi_startproc
mul x0, x0, x1
ret
No callee-saved registers used, no stack objects, stackSize 0: emitPrologue emits nothing. With -frame-pointer=all the same function gets a frame record (stp x29, x30, [sp, #-16]!, mov x29, sp), because hasFPImpl returns true when frame-pointer elimination is disabled.
2. Function With a Call
declare i64 @h(i64)
define i64 @withcall(i64 %a) {
%r = call i64 @h(i64 %a)
%s = add i64 %r, %a
ret i64 %s
}
Before PEI:
renamable $x19 = COPY $x0
ADJCALLSTACKDOWN 0, 0, implicit-def dead $sp, implicit $sp
BL @h, csr_aarch64_aapcs, implicit-def dead $lr, implicit $sp, implicit $x0, implicit-def $sp, implicit-def $x0
ADJCALLSTACKUP 0, 0, implicit-def dead $sp, implicit $sp
$x0 = ADDXrr killed renamable $x0, killed renamable $x19
RET_ReallyLR implicit $x0
After PEI:
early-clobber $sp = frame-setup STPXpre killed $lr, killed $x19, $sp, -2 :: (store (s64) into %stack.1), (store (s64) into %stack.0)
frame-setup CFI_INSTRUCTION def_cfa_offset 16
frame-setup CFI_INSTRUCTION offset $w19, -8
frame-setup CFI_INSTRUCTION offset $w30, -16
renamable $x19 = COPY $x0
BL @h, csr_aarch64_aapcs, implicit-def dead $lr, implicit $sp, implicit $x0, implicit-def $sp, implicit-def $x0
$x0 = ADDXrr killed renamable $x0, killed renamable $x19
early-clobber $sp, $lr, $x19 = frame-destroy LDPXpost $sp, 2 :: (load (s64) from %stack.1), (load (s64) from %stack.0)
RET_ReallyLR implicit $x0
| Change | Step |
|---|---|
ADJCALLSTACKDOWN/UP gone | calculateCallFrameInfo (reserved call frame) |
x19 and lr saved | determineCalleeSaves + pairing in spillCalleeSavedRegisters |
Pre-indexed STPXpre also allocates the frame | Prologue combined the CSR store with the SP decrement |
CFI_INSTRUCTIONs | Prologue CFI (CFI) |
stackSize: 16, slots at −8 and −16 | calculateFrameObjectOffsets |
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:211-283
3. Large Frame
declare void @ext(ptr)
define void @bigframe() {
%buf = alloca [70000 x i8], align 16
call void @ext(ptr %buf)
ret void
}
Before PEI: $x0 = ADDXri %stack.0.buf, 0, 0. After PEI:
early-clobber $sp = frame-setup STPXpre killed $fp, killed $lr, $sp, -2 :: (store (s64) into %stack.2), (store (s64) into %stack.1)
$sp = frame-setup SUBXri $sp, 17, 12
$sp = frame-setup SUBXri $sp, 368, 0
frame-setup CFI_INSTRUCTION def_cfa_offset 70016
frame-setup CFI_INSTRUCTION offset $w30, -8
frame-setup CFI_INSTRUCTION offset $w29, -16
$x0 = ADDXri $sp, 0, 0
BL @ext, csr_aarch64_aapcs, implicit-def dead $lr, implicit $sp, implicit killed $x0, implicit-def $sp
$sp = frame-destroy ADDXri $sp, 17, 12
$sp = frame-destroy ADDXri $sp, 368, 0
early-clobber $sp, $fp, $lr = frame-destroy LDPXpost $sp, 2 :: (load (s64) from %stack.2), (load (s64) from %stack.1)
RET_ReallyLR
- The 70000-byte local (rounded to 70000 + 16 for the frame record = 70016) needs two
subinstructions: 17 × 4096 = 69632 plus 368. x29is saved and restored even thoughmov x29, spnever appears:determineCalleeSavesadded it to the saved set for this large frame (it is not used as a frame pointer here). The exact rule is inAArch64FrameLowering::determineCalleeSaves(line 2521 onwards); this page does not trace which condition triggered it.%stack.0.bufbecame$sp + 0ineliminateFrameIndex(Frame Index Elimination).
4. Variable-Sized alloca
define void @dynalloca(i64 %n) {
%p = alloca i8, i64 %n, align 16
call void @ext(ptr %p)
ret void
}
dynalloca: // @dynalloca
.cfi_startproc
stp x29, x30, [sp, #-16]! // 16-byte Folded Spill
mov x29, sp
.cfi_def_cfa w29, 16
.cfi_offset w30, -8
.cfi_offset w29, -16
add x9, x0, #15
mov x8, sp
and x9, x9, #0xfffffffffffffff0
sub x0, x8, x9
mov sp, x0
bl ext
mov sp, x29
ldp x29, x30, [sp], #16 // 16-byte Folded Reload
ret
hasVarSizedObjects() makes hasFPImpl true, so x29 is set up and the CFA is based on it (.cfi_def_cfa w29, 16). The allocation rounds %n up to 16 and moves SP; the epilogue restores SP from x29 (mov sp, x29) instead of adding a known size. See TargetFrameLowering Hooks.
Sources: llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:588-594, llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:659-667
5. Shrink Wrapping
The shrink function's prologue is placed after the tbz so the fast path has no frame; with -enable-shrink-wrap=false it is back in the entry block. Both outputs are on Shrink Wrapping.
Reproducing
llc -O2 -mtriple=aarch64-linux-gnu frame.ll -o -
llc -O2 -mtriple=aarch64-linux-gnu -stop-before=prolog-epilog frame.ll -o before.mir
llc -O2 -mtriple=aarch64-linux-gnu -stop-after=prolog-epilog frame.ll -o after.mir
llc -O2 -mtriple=aarch64-linux-gnu -frame-pointer=all frame.ll -o -
llc -O2 -mtriple=aarch64-linux-gnu -enable-shrink-wrap=false frame.ll -o -
The register allocation that chose x19 for the value kept across the call is traced in the regalloc wiki's AArch64 walkthroughs; the stack-argument side of calls is on the calling conventions walkthroughs.
Tooling and Glossary
Relevant source files
The following files were used as context for generating this wiki page:
Commands for inspecting frame lowering, and the terms used in this wiki. General llc options are on the bring-up tooling page.
Purpose and Scope
All output in this wiki comes from an LLVM 24.0.0git release llc (no assertions) at commit a2171756.
Commands
| Command | Shows |
|---|---|
llc ... -stop-before=prolog-epilog | Frame indices, call-frame pseudos, empty prologue; frameInfo: and stack: sections |
llc ... -stop-after=prolog-epilog | Prologue/epilogue, CFI pseudos, final stackSize and object offsets |
llc ... -stop-before=shrink-wrap / -stop-after=shrink-wrap | savePoint/restorePoint in frameInfo: |
llc ... -enable-shrink-wrap=false | Frame without shrink wrapping |
llc ... -frame-pointer=all (or none, non-leaf) | Force or omit the frame pointer |
llc ... -verify-machineinstrs | Machine verifier after each pass |
llc ... -debug-only=prolog-epilog,shrink-wrap | Pass debug output (assertions build only) |
The pass names come from #define DEBUG_TYPE "prolog-epilog" and #define DEBUG_TYPE "shrink-wrap".
Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:69, llvm/lib/CodeGen/ShrinkWrap.cpp:91
Glossary
| Term | Meaning |
|---|---|
| Frame index | Abstract stack slot number; negative for fixed objects |
| Fixed object | Stack object at a known offset from the incoming SP (incoming arguments) |
MachineFrameInfo | Per-function table of stack objects and frame flags |
| PEI | Prologue/epilogue insertion pass (prolog-epilog) |
| Prologue / epilogue | Code that builds / removes the frame |
| Callee-saved register (CSR) | Register a function must restore before returning |
| Frame pointer (FP) | Register (x29 on AArch64) pointing to a fixed place in the frame |
| Frame record | Saved FP and LR pair, forming the frame-pointer chain |
| Base pointer | Third base register used with both realignment and dynamic allocas |
| Reserved call frame | Outgoing argument area allocated once in the prologue |
| Call-frame pseudos | ADJCALLSTACKDOWN / ADJCALLSTACKUP |
eliminateFrameIndex | Replaces a frame-index operand with base register + offset |
| Register scavenger | Finds a free physical register after allocation |
| Emergency spill slot | Slot reserved so the scavenger can always free a register |
| Shrink wrapping | Moving prologue/epilogue to the smallest region that needs them |
| CFA | Canonical frame address, the reference point for unwinding |
| CFI | .cfi_* directives describing the CFA and saved registers |
| Red zone | Area below SP a leaf function may use without adjusting SP (canUseRedZone) |
Part 7: The MC Layer
Streamers, the assembler, fixups and relocations, and the MC objects a backend writes for .s and .o output.
Pages
- 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
MC Layer Overview
Relevant source files
The following files were used as context for generating this wiki page:
The MC ("Machine Code") layer is the bottom of LLVM's code generator and the core of its assembler and disassembler. It knows about instructions as opcodes plus operands (MCInst), not as MachineInstrs. It can print them as assembly text, encode them to bytes, write object files, parse assembly back into MCInsts, and decode bytes into MCInsts.
Purpose and Scope
This wiki explains llvm/lib/MC/ and the per-target MCTargetDesc, AsmParser and Disassembler directories, using AArch64 as the worked example. It runs from the basic data structures to everything a new backend has to write: see Writing an MC Layer for a Custom Backend.
It does not cover instruction selection or register allocation (see the other two wikis), or the linker.
All tool output on these pages was produced by the release llc built from the pinned commit. That build has no llvm-mc, llvm-objdump or llvm-readelf, so assembling .s files, disassembly and reading relocation tables back from objects are explained from the source code only, without listings.
Where MC Fits
flowchart LR
MI["MachineInstr<br/>after register allocation"] --> AP["AsmPrinter<br/>lowers each MI to an MCInst"]
AP --> S{"MCStreamer"}
S -->|"-filetype=asm"| AS["MCAsmStreamer<br/>MCInstPrinter prints text"]
S -->|"-filetype=obj"| OS["MCELFStreamer / MCObjectStreamer<br/>MCCodeEmitter encodes bytes"]
OS --> ASM["MCAssembler<br/>layout, relaxation, fixups"]
ASM --> OW["ELFObjectWriter<br/>sections, symbols, relocations"]
P[".s file"] --> PARSER["AsmParser<br/>MCTargetAsmParser"] --> S
BYTES["bytes"] --> DIS["MCDisassembler"] --> MCI["MCInst"] --> PR["MCInstPrinter"]
The MCStreamer is the hub. Everything that produces code (the compiler's AsmPrinter, the assembly parser) talks to a streamer, and the kind of streamer decides whether text or an object file comes out. The same MCInst can be printed or encoded, which is why llc can emit both from one pipeline.
How llc Builds It
CodeGenTargetMachineImpl::addAsmPrinter creates the streamer, then the AsmPrinter pass. createMCStreamer chooses by file type: getTarget().createAsmStreamer(...) for text, getTarget().createMCObjectStreamer(...) for objects.
AsmPrinter lowers each MachineInstr to an MCInst (AArch64: AArch64AsmPrinter::emitInstruction, using AArch64MCInstLower::lowerOperand) and hands it to the streamer through EmitToStreamer.
Sources: llvm/lib/CodeGen/CodeGenTargetMachineImpl.cpp:145-215, llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp:505, llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp:3258-3265, llvm/lib/Target/AArch64/AArch64MCInstLower.cpp:332
A First Look
@gv = global i32 0
declare i32 @g(i32)
define i32 @h(i32 %a) {
%v = load i32, ptr @gv
%x = call i32 @g(i32 %v)
%y = add i32 %x, %a
ret i32 %y
}
llc -mtriple=aarch64-linux-gnu -O2 -show-mc-encoding prints the assembly, the bytes the code emitter produced, and any fixups (excerpt):
adrp x8, :got:gv // encoding: [0x08'A',A,A,0x90'A']
// fixup A - offset: 0, value: :got:gv, kind: fixup_aarch64_pcrel_adrp_imm21
mov w19, w0 // encoding: [0xf3,0x03,0x00,0x2a]
bl g // encoding: [A,A,A,0b100101AA]
// fixup A - offset: 0, value: g, kind: fixup_aarch64_pcrel_call26
add w0, w0, w19 // encoding: [0x00,0x00,0x13,0x0b]
ret // encoding: [0xc0,0x03,0x5f,0xd6]
mov w19, w0 is fully known: four bytes. bl g is not: the address of g is unknown when the instruction is encoded. The emitter writes the opcode bits it knows and records a fixup (bits marked A), which is resolved later by the assembler or turned into a relocation for the linker. That distinction runs through the whole MC layer; see Fixups and Relocations.
Component Map
| Component | Class | Role | Page |
|---|---|---|---|
| Instruction | MCInst, MCOperand | Opcode + operands, target-independent container | Data Structures |
| Expressions, symbols, sections | MCExpr, MCSymbol, MCSection, MCContext | Values not known yet, names, output sections | Data Structures |
| Streamer | MCStreamer, MCAsmStreamer, MCObjectStreamer, MCELFStreamer | The interface code producers call | Streamers |
| Assembler | MCAssembler, fragments | Layout, relaxation, fixup evaluation | Assembler and Layout |
| Object writer | ELFObjectWriter | Writes the ELF file and relocations | Fixups and Relocations |
| Target: description | MCInstrInfo, MCRegisterInfo, MCSubtargetInfo, MCAsmInfo | Tables and syntax facts | Custom backend |
| Target: printer | <T>InstPrinter | MCInst to text | MCAsmInfo and Printer |
| Target: encoder | <T>MCCodeEmitter | MCInst to bytes + fixups | Code Emitter |
| Target: backend | <T>AsmBackend, <T>ELFObjectWriter | Apply fixups, relax, choose relocation types | AsmBackend and Object Writer |
| Target: parser, decoder | <T>AsmParser, <T>Disassembler | Text to MCInst, bytes to MCInst | Parser and Disassembler |
Reading Guide
- New to MC: Data Structures, Streamers, Assembler and Layout, Fixups and Relocations.
- Writing a backend: Custom backend and its checklist.
- Debugging output: Tooling and Glossary.
Core Data Structures
Relevant source files
The following files were used as context for generating this wiki page:
Six types carry almost everything through the MC layer: MCInst (an instruction), MCOperand (one of its operands), MCExpr (a value that may not be known yet), MCSymbol (a name), MCSection (an output section) and MCContext (the owner of all of them).
Purpose and Scope
What each type holds and how they relate. Fragments and fixups are on Assembler and Layout and Fixups and Relocations.
MCInst and MCOperand
An MCInst is an opcode number plus a list of MCOperands. It carries no basic block, no liveness, no flags like killed: those belong to MachineInstr. The opcode is the target enum generated by TableGen (AArch64::ADRP, AArch64::ORRWrs, ...).
An MCOperand is one of:
| Kind | Holds | Example |
|---|---|---|
| Register | An MCRegister | Reg:X8 |
| Immediate | int64_t | Imm:-2 |
| Floating-point immediate | uint64_t bit pattern | FP constants |
| Expression | const MCExpr * | Expr::got:gv (a symbol reference) |
| Instruction | const MCInst * | Bundles |
llc -asm-show-inst prints the MCInst behind each line. Real output for the example on Overview:
// <MCInst #7672 STPXpre
// <MCOperand Reg:SP>
// <MCOperand Reg:LR>
// <MCOperand Reg:X19>
// <MCOperand Reg:SP>
// <MCOperand Imm:-2>>
adrp x8, :got:gv // <MCInst #1865 ADRP
// <MCOperand Reg:X8>
// <MCOperand Expr::got:gv>>
mov w19, w0 // <MCInst #5666 ORRWrs
// <MCOperand Reg:W19>
// <MCOperand Reg:WZR>
Three things to notice:
- Operands follow the TableGen operand list, not the assembly text.
stp x30, x19, [sp, #-16]!isSTPXprewith five operands, includingSPtwice (the written-back base is a result, then the base is an input). The immediate is-2, not-16: it is stored scaled by 8, as the encoding needs. - Aliases are a printer concern.
mov w19, w0is reallyORRWrs w19, wzr, w0, 0. The printer chooses the alias; theMCInstis the canonical instruction. - Unknown values are expressions. The
adrpoperand is anMCExpr(:got:gv), not a number. The code emitter turns it into a fixup.
Sources: llvm/lib/MC/MCInst.cpp
MCExpr
MCExpr represents a value computed at assembly or link time:
| Class | Meaning |
|---|---|
MCConstantExpr | A number |
MCSymbolRefExpr | A symbol (g, .LBB0_2) |
MCBinaryExpr | A + B, A - B, ... |
MCUnaryExpr | -A, ~A |
MCSpecifierExpr / target subclasses | A target modifier around an expression, e.g. AArch64 :got:, :lo12:, :gottprel: |
When the assembler needs the value, it evaluates the expression to an MCValue = SymA - SymB + Constant plus a specifier (the target modifier). If SymA is defined in the same section and the fixup is resolvable, the value is computed and patched in. Otherwise a relocation is emitted. The specifier is what makes :got:gv become an R_AARCH64_ADR_GOT_PAGE relocation rather than a plain address (see Fixups and Relocations).
Sources: llvm/lib/MC/MCExpr.cpp, llvm/lib/MC/MCValue.cpp
MCSymbol
A symbol is a name with, eventually, a location (a fragment and an offset). Kinds you will meet:
| Kind | Example | Notes |
|---|---|---|
| Function or global | h, gv | Goes into the object's symbol table |
| Temporary | .Lfunc_end0, .LBB0_2 | Private prefix (.L on ELF, MCAsmInfo::PrivateGlobalPrefix); usually not in the symbol table |
| Undefined | g | Referenced but defined elsewhere; always needs a relocation |
On ELF, MCSymbolELF also stores binding (local, global, weak), type (function, object, TLS) and visibility. AArch64ELFObjectWriter::getRelocType even sets STT_TLS on symbols used through TLS specifiers.
MCSection
An MCSection (on ELF, MCSectionELF: name, type, flags) is a list of fragments. Fragment kinds are declared in MCSection.h:
FT_Data,
FT_Relaxable,
FT_Align,
FT_PrefAlign,
FT_Fill,
FT_LEB,
FT_Nops,
FT_Org,
FT_Dwarf,
FT_DwarfFrame,
...
Most code lives in FT_Data fragments (bytes plus fixups). An instruction that may need a longer encoding later gets its own FT_Relaxable fragment. Alignment, fills and variable-length DWARF data have their own kinds because their size depends on layout. See Assembler and Layout.
Sources: llvm/include/llvm/MC/MCSection.h:53-67
MCContext
MCContext owns every symbol, section and expression of one compilation and hands out unique temporaries (createTempSymbol). It also holds pointers to the target's MCAsmInfo, MCRegisterInfo and MCSubtargetInfo, and collects errors (reportError). Everything in MC is allocated in it, so objects are never freed one by one.
Sources: llvm/lib/MC/MCContext.cpp
Target Description Objects
| Object | Generated from | Gives |
|---|---|---|
MCInstrInfo | <T>InstrInfo.td | Per-opcode MCInstrDesc: size, operand list, flags (branch, call, may load) |
MCRegisterInfo | <T>RegisterInfo.td | Register names, sub-registers, register units, DWARF numbers |
MCSubtargetInfo | <T>.td processors and features | CPU and feature bits (which instructions are legal) |
MCAsmInfo | Hand-written | Syntax and object-format facts: comment string, directives, alignment rules |
The first three are mostly TableGen output; MCAsmInfo is written by hand. All are created through TargetRegistry (see Custom backend).
Streamers
Relevant source files
The following files were used as context for generating this wiki page:
MCStreamer is an abstract interface with one method per thing an assembly file can say: switch section, define a label, emit an instruction, emit some bytes, set a symbol attribute, align. Code producers only ever call this interface. Different subclasses turn the calls into text or into an object file.
Purpose and Scope
The streamer interface, its main subclasses, and target streamers for target-specific directives.
The Interface
| Call | Assembly equivalent |
|---|---|
switchSection(Sec) | .section .text |
emitLabel(Sym) | h: |
emitSymbolAttribute(Sym, MCSA_Global) | .globl h |
emitInstruction(Inst, STI) | one instruction |
emitBytes(Data), emitValue(Expr, Size) | .byte, .xword sym |
emitValueToAlignment(...) | .p2align 2 |
emitCFI..., emitDwarfLocDirective | .cfi_*, .loc |
MCStreamer::emitInstruction itself does nothing but sanity-check operands. The subclass decides what an instruction becomes.
Sources: llvm/lib/MC/MCStreamer.cpp:401, llvm/lib/MC/MCStreamer.cpp:1402, llvm/lib/MC/MCStreamer.cpp:1586-1597
The Subclasses
flowchart TD S["MCStreamer"] --> A["MCAsmStreamer<br/>prints text"] S --> O["MCObjectStreamer<br/>builds fragments for MCAssembler"] S --> N["null streamer<br/>discards everything"] O --> E["MCELFStreamer"] O --> M["MCMachOStreamer"] O --> C["MCWinCOFFStreamer"] E --> AE["AArch64ELFStreamer<br/>mapping symbols $x / $d"]
MCAsmStreamer (text)
MCAsmStreamer::emitInstruction asks the target's MCInstPrinter to print the MCInst. If asked (-show-mc-encoding), it also runs the code emitter and writes the bytes and fixups as a comment (AddEncodingComment). That is why llc -show-mc-encoding can show encodings without writing an object file. With -asm-show-inst it dumps the MCInst itself.
Sources: llvm/lib/MC/MCAsmStreamer.cpp:708, llvm/lib/MC/MCAsmStreamer.cpp:2627
MCObjectStreamer (objects)
MCObjectStreamer owns an MCAssembler. Each call appends to the current fragment of the current section. An instruction is either encoded straight into the current data fragment or, if it might need relaxing, given its own relaxable fragment:
if (!(Backend.mayNeedRelaxation(Inst.getOpcode(), Inst.getOperands(), STI) ||
Backend.allowEnhancedRelaxation())) {
emitInstToData(Inst, STI);
return;
}
// Otherwise, relax and emit it as data if RelaxAll is specified.
if (Assembler.getRelaxAll()) {
emitInstToData(relaxToFixpoint(Inst), STI);
return;
}
emitInstToFragment(Inst, STI);
emitInstToData calls the code emitter and appends the bytes and fixups:
getAssembler().getEmitter().encodeInstruction(Inst, Content, Fixups, STI);
appendContents(Content);
...
for (auto &Fixup : Fixups) {
Fixup.setOffset(Fixup.getOffset() + CodeOffset);
...
}
F->appendFixups(Fixups);
Fixup offsets come back from the emitter relative to the instruction; the streamer shifts them to be relative to the fragment. finishImpl (called at the end) runs MCAssembler::Finish, which lays out and writes the object.
Sources: llvm/lib/MC/MCObjectStreamer.cpp:402-488, llvm/lib/MC/MCObjectStreamer.cpp:803
MCELFStreamer
Adds the ELF meaning of symbol attributes (emitSymbolAttribute: binding, type, visibility), ELF section switching and the creation of standard sections (initSections). Targets can subclass it; AArch64's AArch64ELFStreamer adds the ELF mapping symbols that mark code and data.
Sources: llvm/lib/MC/MCELFStreamer.cpp:53-136, llvm/lib/MC/MCELFStreamer.cpp:451
Target Streamers
Directives that exist only on one target (AArch64 .variant_pcs, .inst, Windows SEH opcodes) go through a target streamer, an object attached to the streamer. Each target provides three: one for text (prints the directive), one for objects (does the work), one null. AArch64 registers all three:
TargetRegistry::RegisterObjectTargetStreamer(
*T, createAArch64ObjectTargetStreamer);
TargetRegistry::RegisterAsmTargetStreamer(*T,
createAArch64AsmTargetStreamer);
TargetRegistry::RegisterNullTargetStreamer(*T,
createAArch64NullTargetStreamer);
Both the AsmPrinter and the target AsmParser call the target streamer, so a directive parsed from a .s file and one produced by the compiler take the same path.
Sources: llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp:546-555
Assembler and Layout
Relevant source files
The following files were used as context for generating this wiki page:
While the object streamer runs, nothing has an address yet: sections are just lists of fragments. When the streamer finishes, MCAssembler gives every fragment an offset, grows instructions that turn out to be too short (relaxation), and then resolves fixups and writes the bytes.
Purpose and Scope
How MCAssembler::Finish turns fragments into final section contents. What happens to each fixup is on Fixups and Relocations.
Fragments
A section is a chain of fragments. Each kind knows how to compute its own size (MCAssembler::computeFragmentSize):
| Kind | Contents | Size |
|---|---|---|
FT_Data | Encoded bytes plus fixups | Fixed |
FT_Relaxable | One instruction that may need a longer form | Depends on the current encoding |
FT_Align | Padding to an alignment | Depends on the offset |
FT_Fill, FT_Nops, FT_Org | Repeated bytes, NOPs, move to an offset | Depends on expressions or offset |
FT_LEB, FT_Dwarf, FT_DwarfFrame | Variable-length encodings | Depends on symbol differences |
Sources: llvm/include/llvm/MC/MCSection.h:53-67, llvm/lib/MC/MCAssembler.cpp:208
Finish
flowchart TD A["MCObjectStreamer::finishImpl"] --> B["MCAssembler::Finish"] B --> C["layout()"] C --> D["layoutSection: assign offsets"] D --> E["relaxOnce until stable"] E --> F["backend finishLayout (optional extra pass)"] F --> G["object writer: executePostLayoutBinding"] B --> H["evaluate every fixup:<br/>apply value or record relocation"] H --> I["writeObject: sections, symbols, relocations"]
layout
// Layout until everything fits.
this->HasLayout = true;
for (MCSection &Sec : *this)
layoutSection(Sec);
unsigned FirstStable = Sections.size();
while ((FirstStable = relaxOnce(FirstStable)) > 0)
if (getContext().hadError())
return;
// Some targets might want to adjust fragment offsets. If so, perform another
// layout iteration.
if (getBackend().finishLayout())
for (MCSection &Sec : *this)
layoutSection(Sec);
First every section gets ordinals and an initial layout. Then relaxOnce repeats until no fragment changes size.
Sources: llvm/lib/MC/MCAssembler.cpp:668-720, llvm/lib/MC/MCAssembler.cpp:1121
Relaxation
for (MCFragment &F : Sec) {
if (F.Offset != Offset)
Changed = true;
Stretch = Offset - F.Offset;
F.Offset = Offset;
if (F.getKind() != MCFragment::FT_Data)
relaxFragment(F);
Offset += computeFragmentSize(F);
}
Each pass walks the fragments in order, sets their offsets, and lets every non-data fragment re-check itself. For an FT_Relaxable instruction, relaxInstruction asks the backend whether the fixup's value still fits the current encoding (fixupNeedsRelaxation). If not, the backend replaces the instruction with a larger one (MCAsmBackend::relaxInstruction), which moves everything after it, so another pass runs. If anything changed, all sections are re-checked, because cross-section differences can change too.
The classic example is x86: a short jmp with an 8-bit displacement grows to a 32-bit one when the target is too far away.
AArch64 hardly relaxes. Every instruction is 4 bytes, and branches have fixed ranges. Branches out of range are handled by the linker (veneers) or reported as errors, so AArch64AsmBackend does not override mayNeedRelaxation and its instructions go straight into data fragments (emitInstToData).
Sources: llvm/lib/MC/MCAssembler.cpp:1134-1160, llvm/lib/MC/MCAssembler.cpp:876, llvm/lib/MC/MCAssembler.cpp:1078, llvm/include/llvm/MC/MCAsmBackend.h:139-155
After Layout
With every fragment placed, every label has an address. MCAssembler::evaluateFixup computes each fixup's value. If it is fully known (same section, no symbol the linker might move) the backend's applyFixup patches it into the bytes. Otherwise the object writer records a relocation. Finally writeSectionData produces each section's bytes and the object writer writes the file.
Sources: llvm/lib/MC/MCAssembler.cpp:144, llvm/lib/MC/MCAssembler.cpp:603, llvm/lib/MC/MCAssembler.cpp:801
Fixups and Relocations
Relevant source files
The following files were used as context for generating this wiki page:
A fixup is a note left by the code emitter: "these bits of this instruction depend on this expression, fill them in later". After layout, each fixup is either resolved (the assembler knows the value and patches the bytes) or turned into a relocation (the object file asks the linker to patch it).
Purpose and Scope
The life of a fixup from the code emitter to the object file, with AArch64's fixup kinds and relocation choice.
What a Fixup Holds
| Field | Meaning |
|---|---|
| Offset | Byte offset in the fragment (the streamer shifts it from instruction-relative to fragment-relative) |
| Value | The MCExpr to compute |
| Kind | MCFixupKind: generic (FK_Data_4, FK_Data_8) or a target kind |
-show-mc-encoding prints them. Bits that depend on a fixup are shown as A:
adrp x8, :got:gv // encoding: [0x08'A',A,A,0x90'A']
// fixup A - offset: 0, value: :got:gv, kind: fixup_aarch64_pcrel_adrp_imm21
ldr x8, [x8, :got_lo12:gv] // encoding: [0x08,0bAAAAAA01,0b01AAAAAA,0xf9]
// fixup A - offset: 0, value: :got_lo12:gv, kind: fixup_aarch64_ldst_imm12_scale8
bl g // encoding: [A,A,A,0b100101AA]
// fixup A - offset: 0, value: g, kind: fixup_aarch64_pcrel_call26
Read bl g: the top six bits 100101 are the BL opcode; the low 26 bits are the branch offset, unknown yet.
Target Fixup Kinds
A target declares one kind per way an expression can be placed into an instruction. AArch64 (excerpt):
fixup_aarch64_pcrel_adr_imm21 = FirstTargetFixupKind,
fixup_aarch64_pcrel_adrp_imm21,
fixup_aarch64_add_imm12,
fixup_aarch64_ldst_imm12_scale1,
...
fixup_aarch64_ldst_imm12_scale8,
...
fixup_aarch64_pcrel_branch19,
fixup_aarch64_pcrel_branch26,
fixup_aarch64_pcrel_call26,
getFixupKindInfo describes each one: bit offset, bit size, and whether it is PC-relative. The generic code uses that to know which bits to touch.
Sources: llvm/lib/Target/AArch64/MCTargetDesc/AArch64FixupKinds.h:19-64, llvm/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp:44-73
Resolved or Relocated?
flowchart TD
F["fixup after layout"] --> E["MCAssembler::evaluateFixup<br/>expression to MCValue"]
E --> Q{"value fully known?<br/>(local symbol, same section,<br/>no forced relocation)"}
Q -->|"yes"| A["AsmBackend::applyFixup<br/>patch bits"]
Q -->|"no"| R["ELFObjectWriter::recordRelocation<br/>target getRelocType picks R_* type"]
R --> A2["applyFixup patches any addend bits"]
AArch64's applyFixup shows both paths in a few lines:
if (shouldForceRelocation(Fixup))
IsResolved = false;
maybeAddReloc(F, Fixup, Target, Value, IsResolved);
...
if (!Value)
return; // Doesn't change encoding.
...
// Apply any target-specific value adjustments.
Value = adjustFixupValue(Fixup, Target, Value, Ctx, TheTriple, IsResolved);
// Shift the value into position.
Value <<= Info.TargetOffset;
...
Data[i] |= uint8_t((Value >> (i * 8)) & 0xff);
adjustFixupValue converts a raw value into the field's encoding and checks its range. For branches, the byte offset is divided by 4 (return Value >> 2;), because AArch64 branch offsets count instructions.
Sources: llvm/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp:138-191, llvm/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp:404-470, llvm/lib/MC/MCAssembler.cpp:144
Choosing the Relocation Type
The target's ELF writer maps fixup kind + specifier + PC-relativity to an ELF relocation number in getRelocType. For the fixups above, the mapping in AArch64ELFObjectWriter.cpp is:
| Fixup (from the listing) | Relocation | Source line |
|---|---|---|
fixup_aarch64_pcrel_adrp_imm21 with :got: | R_AARCH64_ADR_GOT_PAGE | 168 |
fixup_aarch64_pcrel_adrp_imm21 with :gottprel: | R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21 | 178 |
fixup_aarch64_pcrel_branch26 | R_AARCH64_JUMP26 | 192 |
fixup_aarch64_pcrel_call26 | R_AARCH64_CALL26 | 194 |
fixup_aarch64_pcrel_branch19 | R_AARCH64_CONDBR19 | 221 |
The table is read from the source, not from an object file: this build has no llvm-readelf to print the relocation section.
The specifier matters as much as the kind: the same adrp fixup becomes a different relocation for :got:, :gottprel: or a plain symbol. getRelocType also reports impossible combinations (for example a :plt: specifier anywhere other than a .word).
Sources: llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp:85-221
The Generic ELF Writer
ELFObjectWriter (in lib/MC) does the format work so targets do not have to: recordRelocation collects relocations per section, executePostLayoutBinding resolves symbol aliases, and ELFWriter::writeObject writes the header, sections, symbol table, string tables and .rela sections. The target only supplies getRelocType and a few policy hooks (needsRelocateWithSymbol: relocate against the symbol or against its section).
Sources: llvm/lib/MC/ELFObjectWriter.cpp:722-991, llvm/lib/MC/ELFObjectWriter.cpp:1171-1403, llvm/include/llvm/MC/MCELFObjectWriter.h:88-91
Writing an MC Layer for a Custom Backend
Relevant source files
The following files were used as context for generating this wiki page:
The generic MC code (streamers, assembler, ELF writer) is shared by every target. A backend supplies a set of small target objects and registers a factory function for each with TargetRegistry. Tools such as llc, llvm-mc and llvm-objdump then find them by target triple.
Purpose and Scope
The list of pieces, how they are registered, and the order to write them. Each piece has its own page.
The Pieces
| Piece | Base class | Needed for | Page |
|---|---|---|---|
| Instruction, register, subtarget tables | MCInstrInfo, MCRegisterInfo, MCSubtargetInfo | Everything (mostly TableGen output) | Data Structures |
| Syntax facts | MCAsmInfo | Everything | MCAsmInfo and Printer |
| Instruction printer | MCInstPrinter | .s output, disassembler output | MCAsmInfo and Printer |
| Code emitter | MCCodeEmitter | .o output | Code Emitter |
| Asm backend | MCAsmBackend | .o output: fixups, relaxation, NOPs | AsmBackend and Object Writer |
| ELF object writer | MCELFObjectTargetWriter | .o output: relocation types | AsmBackend and Object Writer |
| Target streamer (optional) | MCTargetStreamer | Target-only directives | Streamers |
| Asm parser | MCTargetAsmParser | .s input, inline asm | Parser and Disassembler |
| Disassembler | MCDisassembler | llvm-objdump, llvm-mc --disassemble | Parser and Disassembler |
Directory Layout
| Directory | Contents | Library |
|---|---|---|
lib/Target/<T>/MCTargetDesc/ | <T>MCTargetDesc.cpp (registration), MCAsmInfo, InstPrinter, MCCodeEmitter, AsmBackend, ELFObjectWriter, FixupKinds.h | LLVM<T>Desc |
lib/Target/<T>/AsmParser/ | <T>AsmParser.cpp | LLVM<T>AsmParser |
lib/Target/<T>/Disassembler/ | <T>Disassembler.cpp | LLVM<T>Disassembler |
lib/Target/<T>/TargetInfo/ | getThe<T>Target() | LLVM<T>Info |
The MC libraries must not depend on CodeGen: llvm-mc links them without the compiler. AArch64 follows exactly this layout (see the file list of AArch64/MCTargetDesc).
Registration
AArch64 registers everything in LLVMInitializeAArch64TargetMC:
LLVMInitializeAArch64TargetMC() {
for (Target *T : {&getTheAArch64leTarget(), &getTheAArch64beTarget(),
&getTheAArch64_32Target(), &getTheARM64Target(),
&getTheARM64_32Target()}) {
// Register the MC asm info.
RegisterMCAsmInfoFn X(*T, createAArch64MCAsmInfo);
// Register the MC instruction info.
TargetRegistry::RegisterMCInstrInfo(*T, createAArch64MCInstrInfo);
// Register the MC register info.
TargetRegistry::RegisterMCRegInfo(*T, createAArch64MCRegisterInfo);
// Register the MC subtarget info.
TargetRegistry::RegisterMCSubtargetInfo(*T, createAArch64MCSubtargetInfo);
...
// Register the MC Code Emitter
TargetRegistry::RegisterMCCodeEmitter(*T, createAArch64MCCodeEmitter);
// Register the obj streamers.
TargetRegistry::RegisterELFStreamer(*T, createAArch64ELFStreamer);
...
// Register the MCInstPrinter.
TargetRegistry::RegisterMCInstPrinter(*T, createAArch64MCInstPrinter);
}
// Register the asm backend.
for (Target *T : {&getTheAArch64leTarget(), &getTheAArch64_32Target(),
&getTheARM64Target(), &getTheARM64_32Target()})
TargetRegistry::RegisterMCAsmBackend(*T, createAArch64leAsmBackend);
TargetRegistry::RegisterMCAsmBackend(getTheAArch64beTarget(),
createAArch64beAsmBackend);
}
The asm parser and disassembler register themselves in their own libraries (LLVMInitializeAArch64AsmParser, LLVMInitializeAArch64Disassembler). The ELF object writer is not registered: the asm backend creates it in createObjectTargetWriter.
When llc writes an object, CodeGenTargetMachineImpl::createMCStreamer asks the registry for the code emitter and asm backend and calls createMCObjectStreamer with them.
Sources: llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp:516-567, llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp:48, llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp:339-370, llvm/lib/CodeGen/CodeGenTargetMachineImpl.cpp:168-215
Minimal Registration for a New Target (Illustrative)
For a made-up "Toy" target. Illustrative, not LLVM source; check the exact factory signatures in TargetRegistry.h at your LLVM version.
// ToyMCTargetDesc.cpp (illustrative)
#define GET_INSTRINFO_MC_DESC
#include "ToyGenInstrInfo.inc"
#define GET_REGINFO_MC_DESC
#include "ToyGenRegisterInfo.inc"
#define GET_SUBTARGETINFO_MC_DESC
#include "ToyGenSubtargetInfo.inc"
static MCInstrInfo *createToyMCInstrInfo() {
auto *X = new MCInstrInfo();
InitToyMCInstrInfo(X); // generated
return X;
}
static MCRegisterInfo *createToyMCRegisterInfo(const Triple &) {
auto *X = new MCRegisterInfo();
InitToyMCRegisterInfo(X, Toy::R14); // return-address register
return X;
}
extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeToyTargetMC() {
Target &T = getTheToyTarget();
RegisterMCAsmInfo<ToyMCAsmInfo> X(T);
TargetRegistry::RegisterMCInstrInfo(T, createToyMCInstrInfo);
TargetRegistry::RegisterMCRegInfo(T, createToyMCRegisterInfo);
TargetRegistry::RegisterMCSubtargetInfo(T, createToyMCSubtargetInfo);
TargetRegistry::RegisterMCInstPrinter(T, createToyMCInstPrinter);
TargetRegistry::RegisterMCCodeEmitter(T, createToyMCCodeEmitter);
TargetRegistry::RegisterMCAsmBackend(T, createToyAsmBackend);
}
Order of Work
- TableGen: registers, instructions with encodings (
bits<32> Instand operand fields), assembly strings. One description drives the printer, the code emitter, the parser matcher and the decoder. MCAsmInfoandInstPrinter:llc -filetype=asmworks.MCCodeEmitter:llc -show-mc-encodingshows bytes.- Fixup kinds,
AsmBackend,ELFObjectWriter:llc -filetype=objworks. AsmParser:llvm-mcassembles.sfiles; inline asm works.Disassembler:llvm-objdump -dworks.
The checklist gives tests for each step.
MCAsmInfo and the Instruction Printer
Relevant source files
The following files were used as context for generating this wiki page:
MCAsmInfo holds the facts about the assembly syntax and object format that generic code needs: the comment string, directive spellings, label prefixes, alignment rules and the exception-handling model. MCInstPrinter turns one MCInst into text. These two pieces are enough to make llc -filetype=asm work.
Purpose and Scope
What to set in MCAsmInfo, and how a printer is built from TableGen output plus a few hand-written operand printers.
MCAsmInfo
MCAsmInfo has no virtual "do it" method. A target subclasses it and sets fields in its constructor. AArch64 has one subclass per object format. The ELF one sets, among other things:
| Field | AArch64 ELF value | Effect |
|---|---|---|
CommentString | "//" | The // encoding: ... comments in every listing |
Data64bitsDirective | "\t.xword\t" | How 8-byte data is printed |
SupportsDebugInformation | true | DWARF emission allowed |
ExceptionsType | ExceptionHandling::DwarfCFI | .cfi_* unwind directives |
The Darwin subclass uses ";" as its comment string, and the Microsoft COFF one uses ExceptionHandling::WinEH. createAArch64MCAsmInfo chooses the subclass from the triple.
// ToyMCAsmInfo.cpp (illustrative, not LLVM source)
ToyMCAsmInfo::ToyMCAsmInfo(const Triple &TT) {
CommentString = "#";
SupportsDebugInformation = true;
ExceptionsType = ExceptionHandling::DwarfCFI;
Data64bitsDirective = "\t.quad\t";
}
Sources: llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp:146-163, llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp:211-240, llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp:266-280, llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp:346
The Instruction Printer
There are two virtuals to provide:
virtual void printInst(const MCInst *MI, uint64_t Address, StringRef Annot,
const MCSubtargetInfo &STI, raw_ostream &OS) = 0;
virtual void printRegName(raw_ostream &OS, MCRegister Reg);
Most of the work is generated. -gen-asm-writer reads each instruction's AsmString (for example "add $Rd, $Rn, $Rm") and generates printInstruction, which prints the literal text and calls an operand printer for each $operand. It also generates printAliasInstr from InstAlias records. AArch64 runs the generator twice, once per syntax variant (AArch64GenAsmWriter.inc, AArch64GenAsmWriter1.inc).
The hand-written printInst deals with special cases, then falls back to the generated code:
if (!PrintAliases || !printAliasInstr(MI, Address, STI, O))
printInstruction(MI, Address, STI, O);
This is why the MCInst ORRWrs W19, WZR, W0 prints as mov w19, w0: an InstAlias matched first. Operand printers such as printOperand print registers, immediates and expressions. A target adds its own (for example printShifter) and names them in the operand definitions in TableGen with PrintMethod = "...".
Sources: llvm/include/llvm/MC/MCInstPrinter.h:145-153, llvm/lib/Target/AArch64/MCTargetDesc/AArch64InstPrinter.cpp:38-90, llvm/lib/Target/AArch64/MCTargetDesc/AArch64InstPrinter.cpp:374-375, llvm/lib/Target/AArch64/MCTargetDesc/AArch64InstPrinter.cpp:1243, llvm/lib/Target/AArch64/CMakeLists.txt:6-7
A Minimal Printer (Illustrative)
// ToyInstPrinter.cpp (illustrative, not LLVM source)
#include "ToyGenAsmWriter.inc" // printInstruction, getRegisterName
void ToyInstPrinter::printInst(const MCInst *MI, uint64_t Address,
StringRef Annot, const MCSubtargetInfo &STI,
raw_ostream &O) {
printInstruction(MI, Address, O);
printAnnotation(O, Annot);
}
void ToyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) {
const MCOperand &Op = MI->getOperand(OpNo);
if (Op.isReg()) O << getRegisterName(Op.getReg());
else if (Op.isImm()) O << Op.getImm();
else MAI.printExpr(O, *Op.getExpr());
}
The printer serves both llc output and disassembler output, so print exactly what your assembler accepts.
Code Emitter
Relevant source files
The following files were used as context for generating this wiki page:
The code emitter turns one MCInst into bytes. For every operand whose value is not known yet, it also produces a fixup. It never looks at addresses and never decides on relocations: it only says "these bits depend on this expression".
Purpose and Scope
What encodeInstruction has to do, what TableGen generates for you, and where fixups come from.
The Interface
virtual void encodeInstruction(const MCInst &Inst, SmallVectorImpl<char> &CB,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const = 0;
Append the bytes to CB and the fixups to Fixups. Fixup offsets are relative to the start of this instruction; the streamer shifts them (Streamers).
Sources: llvm/include/llvm/MC/MCCodeEmitter.h:35
AArch64's Implementation
void AArch64MCCodeEmitter::encodeInstruction(const MCInst &MI,
SmallVectorImpl<char> &CB,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
if (MI.getOpcode() == AArch64::TLSDESCCALL) {
...
addFixup(Fixups, 0, MI.getOperand(0).getExpr(), Reloc);
return;
}
if (MI.getOpcode() == AArch64::SPACE) {
// SPACE just increases basic block size, in both cases no actual code.
return;
}
uint64_t Binary = getBinaryCodeForInstr(MI, Fixups, STI);
support::endian::write<uint32_t>(CB, Binary, llvm::endianness::little);
++MCNumEmitted; // Keep track of the # of mi's emitted.
}
There are three parts:
- Special opcodes.
TLSDESCCALLemits no bytes, only a relocation on the next instruction.SPACEemits nothing. getBinaryCodeForInstris generated by-gen-emitter(AArch64GenMCCodeEmitter.inc) from each instruction'sbits<32> Instfield. It starts from the fixed opcode bits and ORs in each operand field.- Writing the word little-endian. An AArch64 instruction is always 4 bytes.
Sources: llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCCodeEmitter.cpp:725-779, llvm/lib/Target/AArch64/CMakeLists.txt:22
Operand Encoders and Fixups
For each operand field, the generated code calls an encoder function: getMachineOpValue by default, or the function named in the operand's TableGen EncoderMethod. An encoder returns the field value if the operand is a register or immediate. If the operand is an expression, it adds a fixup and returns 0. For example, the branch-target encoder picks fixup_aarch64_pcrel_call26 for BL:
? AArch64::fixup_aarch64_pcrel_call26
That is the origin of the [A,A,A,0b100101AA] encoding of bl g: opcode bits known, 26 bits left at 0 with a fixup.
Hand-written post-encoders adjust the generated value where the ISA has quirks. Examples are fixMulHigh, which fills the unused Ra field of SMULH/UMULH with ones, and fixOneOperandFPComparison. They are named with PostEncoderMethod in TableGen.
Sources: llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCCodeEmitter.cpp:455, llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCCodeEmitter.cpp:751-777
Checking Your Emitter
llc -show-mc-encoding runs the emitter even for text output. Real AArch64 output with no fixups:
mov w19, w0 // encoding: [0xf3,0x03,0x00,0x2a]
add w0, w0, w19 // encoding: [0x00,0x00,0x13,0x0b]
ret // encoding: [0xc0,0x03,0x5f,0xd6]
Compare these bytes against the ISA manual for a handful of instructions per format. That catches most mistakes in Inst field definitions.
A Minimal Emitter (Illustrative)
// ToyMCCodeEmitter.cpp (illustrative, not LLVM source)
void ToyMCCodeEmitter::encodeInstruction(const MCInst &MI,
SmallVectorImpl<char> &CB, SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
uint32_t Bits = getBinaryCodeForInstr(MI, Fixups, STI); // generated
support::endian::write<uint32_t>(CB, Bits, llvm::endianness::little);
}
unsigned ToyMCCodeEmitter::getBranchTargetOpValue(const MCInst &MI,
unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
if (MO.isImm())
return MO.getImm();
addFixup(Fixups, 0, MO.getExpr(), Toy::fixup_toy_branch24);
return 0;
}
AsmBackend and Object Writer
Relevant source files
The following files were used as context for generating this wiki page:
The asm backend is the target's part of the assembler. It describes its fixup kinds, patches resolved fixups into bytes, decides which instructions can be relaxed, writes NOP padding, and creates the target object writer. The object writer's only essential job is to map a fixup to a relocation number.
Purpose and Scope
The virtuals a backend implements, with AArch64's versions as the reference. How fixups flow is on Fixups and Relocations.
MCAsmBackend Virtuals
Virtual (MCAsmBackend.h) |
Line | Required? | Job |
|---|---|---|---|
createObjectTargetWriter() | 102 | Yes (pure) | Create the format-specific target writer |
getFixupKindInfo(Kind) | 111 | Yes for any target fixup | Name, bit offset, bit size, flags of each kind |
applyFixup(F, Fixup, Target, Data, Value, IsResolved) | 128 | Yes | Patch the value into the bytes; record a relocation if not resolved |
mayNeedRelaxation(Opcode, Operands, STI) | 139 | Only if you relax | Can this instruction grow? |
relaxInstruction(Inst, STI) | 155 | Only if you relax | Replace it with the longer form |
writeNopData(OS, Count, STI) | 194 | Yes | Fill Count bytes with NOPs (for alignment in code) |
Sources: llvm/include/llvm/MC/MCAsmBackend.h:93-194
AArch64's Backend
- Fixup info:
getFixupKindInfoholds a table of thefixup_aarch64_*kinds and falls back toMCAsmBackend::getFixupKindInfofor generic ones. - Applying fixups:
applyFixupforces a relocation where needed (shouldForceRelocation), callsmaybeAddReloc, then converts the value withadjustFixupValue(range checks, scaling: branch offsets>> 2), shifts it to the field's bit offset and ORs it into the bytes (code on Fixups and Relocations). - Relaxation: none. There is no
mayNeedRelaxationoverride, because AArch64 instructions are fixed size (Assembler and Layout). - NOPs:
writeNopDatawrites 4-bytenopwords. - Object writer: the ELF backend's
createObjectTargetWriterreturnscreateAArch64ELFObjectWriter(OSABI, IsILP32). Separate backend classes cover Mach-O and COFF. - Endianness: separate factories,
createAArch64leAsmBackendandcreateAArch64beAsmBackend.
Sources: llvm/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp:44-73, llvm/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp:404-498, llvm/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp:762-802
The ELF Target Writer
virtual unsigned getRelocType(const MCFixup &Fixup, const MCValue &Target,
bool IsPCRel) const = 0;
virtual bool needsRelocateWithSymbol(const MCValue &, unsigned Type) const {
getRelocType returns an R_<ARCH>_* number for every fixup that reaches the object file. Use the fixup kind, the specifier in Target (:got:, :lo12:, TLS forms) and IsPCRel. Report unsupported combinations with reportError and return R_<ARCH>_NONE rather than crashing. The constructor passes the ELF e_machine value and whether relocations carry explicit addends (RELA).
Sources: llvm/include/llvm/MC/MCELFObjectWriter.h:88-91, llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp:85-130, llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp:537
A Minimal Backend (Illustrative)
// ToyAsmBackend.cpp (illustrative, not LLVM source)
namespace Toy { enum { fixup_toy_branch24 = FirstTargetFixupKind }; }
MCFixupKindInfo ToyAsmBackend::getFixupKindInfo(MCFixupKind K) const {
static const MCFixupKindInfo Infos[] = {
// name offset bits flags
{"fixup_toy_branch24", 0, 24, 0},
};
if (K < FirstTargetFixupKind)
return MCAsmBackend::getFixupKindInfo(K);
return Infos[K - FirstTargetFixupKind];
}
void ToyAsmBackend::applyFixup(const MCFragment &F, const MCFixup &Fixup,
const MCValue &Target, uint8_t *Data,
uint64_t Value, bool IsResolved) {
maybeAddReloc(F, Fixup, Target, Value, IsResolved);
if (!Value) return;
if (Fixup.getKind() == Toy::fixup_toy_branch24)
Value = (Value >> 2) & 0xffffff; // word offset, 24 bits
unsigned N = getFixupKindInfo(Fixup.getKind()).TargetSize / 8;
for (unsigned I = 0; I != N; ++I)
Data[I] |= uint8_t(Value >> (I * 8));
}
std::unique_ptr<MCObjectTargetWriter>
ToyAsmBackend::createObjectTargetWriter() const {
return std::make_unique<ToyELFObjectWriter>(OSABI);
}
// ToyELFObjectWriter.cpp
unsigned ToyELFObjectWriter::getRelocType(const MCFixup &Fixup,
const MCValue &Target, bool IsPCRel) const {
switch (Fixup.getKind()) {
case Toy::fixup_toy_branch24: return ELF::R_TOY_BRANCH24;
case FK_Data_4: return ELF::R_TOY_32;
default:
reportError(Fixup.getLoc(), "unsupported relocation");
return ELF::R_TOY_NONE;
}
}
The field names in MCFixupKindInfo and the exact applyFixup signature change between releases. Copy them from MCAsmBackend.h and MCFixup.h at your commit.
Assembly Parser and Disassembler
Relevant source files
The following files were used as context for generating this wiki page:
These are the two input directions. The asm parser turns assembly text into MCInsts and streamer calls. The disassembler turns bytes into MCInsts, which the printer then prints. Both are generated mostly from the same TableGen instruction descriptions as the printer and the encoder.
Purpose and Scope
What a target writes for each, and what TableGen generates. The build used for this wiki has no llvm-mc or llvm-objdump, so this page has no tool output. In llc, the asm parser is only exercised through inline assembly.
The Asm Parser
The generic AsmParser (in lib/MC/MCParser) lexes the file, handles generic directives (.text, .globl, .byte, ...) and calls the target parser for everything else:
Virtual (MCTargetAsmParser.h) |
Line | Job |
|---|---|---|
parseRegister(Reg, StartLoc, EndLoc) | 408 | Parse one register name |
parseInstruction(Info, Name, NameLoc, Operands) | 432 | Split an instruction into a mnemonic token plus target operands |
ParseDirective / parseDirective | 450 / 462 | Target-specific directives; return "not mine" for the rest |
matchAndEmitInstruction(IDLoc, Opcode, Operands, Out, ErrorInfo, ...) | 470 | Choose the opcode, build the MCInst, emit it |
Matching is generated. -gen-asm-matcher (AArch64GenAsmMatcher.inc) produces MatchInstructionImpl, which compares the operand list against every instruction's AsmString and operand classes. AArch64's matchAndEmitInstruction first rewrites some aliases by hand (for example lsl with an immediate), then calls MatchInstructionImpl, and on success emits the result with Out.emitInstruction.
What you write per operand kind: an operand class (AArch64Operand in AArch64) with isXxx() predicates and addXxxOperands() methods. TableGen AsmOperandClass records name them through PredicateMethod and RenderMethod. AArch64's GPR64spPlus0Operand (AArch64RegisterInfo.td:231-236) is a small real example: PredicateMethod = "isGPR64<AArch64::GPR64spRegClassID>", RenderMethod = "addRegOperands", ParserMethod = "tryParseGPR64sp0Operand".
Sources: llvm/include/llvm/MC/MCParser/MCTargetAsmParser.h:408-470, llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp:2925, llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp:5255, llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp:6451-6470, llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp:6744, llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp:7064, llvm/lib/Target/AArch64/CMakeLists.txt:5
The Disassembler
There is one virtual to provide:
virtual DecodeStatus getInstruction(MCInst &Instr, uint64_t &Size,
ArrayRef<uint8_t> Bytes, uint64_t Address,
raw_ostream &CStream) const = 0;
AArch64's version is short because decoding is generated (-gen-disassembler, AArch64GenDisassemblerTables.inc):
Size = 0;
// We want to read exactly 4 bytes of data.
if (Bytes.size() < 4)
return Fail;
Size = 4;
// Encoded as a small-endian 32-bit word in the stream.
uint32_t Insn =
(Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | (Bytes[0] << 0);
const uint8_t *Tables[] = {DecoderTable32, DecoderTableFallback32};
for (const auto *Table : Tables) {
DecodeStatus Result =
decodeInstruction(Table, MI, Insn, Address, this, STI);
if (Result != MCDisassembler::Fail)
return Result;
}
return MCDisassembler::Fail;
The generated decoder table walks the instruction's fixed bits to pick an opcode, then calls decoder functions for each operand field, named in TableGen with DecoderMethod. AArch64's GPR classes use a shared template, for example let DecoderMethod = "DecodeSimpleRegisterClass<AArch64::GPR64RegClassID, 0, 32>"; (AArch64RegisterInfo.td:210). You write decoders for every register class and for any operand whose encoding is not a plain field.
The disassembler registers itself (with a symbolizer that names branch targets) in LLVMInitializeAArch64Disassembler.
Sources: llvm/include/llvm/MC/MCDisassembler/MCDisassembler.h:135, llvm/lib/Target/AArch64/Disassembler/AArch64Disassembler.cpp:1637-1663, llvm/lib/Target/AArch64/Disassembler/AArch64Disassembler.cpp:1683-1703, llvm/lib/Target/AArch64/CMakeLists.txt:10
One Description, Four Tools
| TableGen field | Printer | Encoder | Parser | Decoder |
|---|---|---|---|---|
AsmString | Text to print | Text to match | ||
bits<32> Inst + operand fields | Bit layout | Bit layout | ||
Operand PrintMethod | Yes | |||
Operand EncoderMethod | Yes | |||
Operand ParserMatchClass | Yes | |||
Operand DecoderMethod | Yes | |||
InstAlias | Prints the alias | Accepts the alias |
If one instruction encodes, prints, parses and decodes consistently, the round trip "assemble, then disassemble" gives back the same text. In a build that has the tools, that is the standard test: llvm-mc -show-encoding and llvm-mc --disassemble on the same lines.
Bring-up Checklist and Common Failures
Relevant source files
The following files were used as context for generating this wiki page:
This page orders the work of the previous pages into stages, each with a test you can run, followed by a table of common symptoms and their usual causes.
Purpose and Scope
A step-by-step plan for a new target's MC layer. The tests use llc; where llvm-mc or llvm-objdump is needed, that is noted (this wiki's build does not have them).
Stage 1: Text Output
- ☐ TableGen: every instruction has an
AsmString; every operand that is not a plain register or immediate has aPrintMethod. - ☐
<T>MCAsmInfowith at leastCommentStringset (page). - ☐
<T>InstPrinterincluding the generatedprintInstructionandgetRegisterName. - ☐
LLVMInitialize<T>TargetMCregisters asm info, instr info, register info, subtarget info and the printer (page). - ☐ The
MCTargetDesclibrary links only MC-level libraries (AArch64's linksMC,CodeGenTypes,Support, ... but notCodeGen).
Test: llc -mtriple=<t> -filetype=asm. Add -asm-show-inst to see the MCInst behind each line and check that operands are in the order you expect.
Stage 2: Encodings
- ☐ TableGen:
bits<N> Instwith operand fields for every instruction;EncoderMethodfor any operand that needs one. - ☐
<T>MCCodeEmitter::encodeInstructioncalling the generatedgetBinaryCodeForInstr(page). - ☐ Fixup kinds for every way an expression can be placed in an instruction (page).
Test: llc -show-mc-encoding. Check the bytes for a few instructions of each format against the ISA manual, and check that symbol operands produce fixup A - ... kind: fixup_<t>_... lines.
Stage 3: Object Files
- ☐
<T>AsmBackend:getFixupKindInfo,applyFixup,writeNopData,createObjectTargetWriter(page). - ☐
<T>ELFObjectWriter::getRelocTypecovering every fixup kind and specifier, reporting errors for the rest. - ☐ Relaxation only if your ISA has variable-size forms:
mayNeedRelaxation,relaxInstruction.
Test: llc -filetype=obj must succeed without assertions; this wiki's build produced a 1128-byte AArch64 object this way. To inspect it you need llvm-readelf -r -s and llvm-objdump -d -r.
Stage 4: Assembler and Disassembler
- ☐
<T>AsmParser:parseRegister,parseInstruction,matchAndEmitInstructionwith the generatedMatchInstructionImpl; operand classes with predicates and render methods (page). - ☐
<T>Disassembler::getInstructionwith the generated decoder tables, and aDecoderMethodfor every register class.
Test (needs llvm-mc): llvm-mc -triple=<t> -show-encoding on a file of instructions, then llvm-mc --disassemble on the bytes. The text must survive the round trip. Write these as llvm/test/MC/<T>/ tests.
Symptoms and Causes
| Symptom | Usual cause |
|---|---|
llc reports that it cannot create an object streamer or code emitter for the target | Code emitter or asm backend not registered in LLVMInitialize<T>TargetMC |
Wrong operand order in -asm-show-inst | ISel or MCInstLower builds operands in a different order from the TableGen (outs) + (ins) list |
| Encodings off by a few bits | Inst field ranges wrong in TableGen, or a missing PostEncoderMethod |
| Fixup kind missing from the listing | Encoder method returns a value for an expression operand instead of adding a fixup |
Assertion in applyFixup about the fixup offset | getFixupKindInfo size does not match the instruction size |
| Linker reports out-of-range or wrong relocation | getRelocType mapping wrong; check against your psABI. AArch64's mapping starts at AArch64ELFObjectWriter.cpp:85 |
| Alias printed where the canonical form was wanted (or the reverse) | InstAlias priority, or PrintAliases setting |
| Assembler accepts the text but the disassembly differs | AsmString, ParserMatchClass and DecoderMethod disagree for that operand |
| Alignment padding is not executable | writeNopData writes the wrong bytes or the wrong unit size |
Sources: llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp:516-567, llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp:85-130
Tooling and Glossary
Relevant source files
The following files were used as context for generating this wiki page:
Which tools show which part of the MC layer, and short definitions of the terms used in this wiki.
Purpose and Scope
A reference page. Options marked "tried" were run with the release llc built from the pinned commit.
llc Options
| Option | Shows | Status |
|---|---|---|
-filetype=asm (default) | Text through MCAsmStreamer and the printer | Tried |
-show-mc-encoding | Bytes from the code emitter, plus fixups (fixup A - offset ... kind ...) | Tried |
-asm-show-inst | The MCInst and its MCOperands for each line | Tried |
-filetype=obj | Writes an object through MCObjectStreamer, MCAssembler and the object writer | Tried (1128-byte AArch64 object) |
-mtriple=... | Selects the target, and with it the object format (ELF, Mach-O, COFF) | Tried (aarch64-linux-gnu) |
Tools This Build Does Not Have
| Tool | Use |
|---|---|
llvm-mc -show-encoding / -show-inst | Assemble .s files with the target asm parser |
llvm-mc -filetype=obj | Assemble straight to an object |
llvm-mc --disassemble | Decode bytes given as text |
llvm-objdump -d -r | Disassemble an object, with relocations |
llvm-readelf -r -s -S | Read relocations, symbols and sections |
Build them with cmake --build <build> --target llvm-mc llvm-objdump llvm-readelf. MC regression tests in llvm/test/MC/<Target>/ use them, usually with FileCheck.
Glossary
| Term | Meaning | Page |
|---|---|---|
| AsmBackend | Target part of the assembler: fixup info, applying fixups, relaxation, NOPs | AsmBackend |
| AsmPrinter | CodeGen pass that lowers MachineInstrs to MCInsts and drives the streamer | Overview |
| Code emitter | Turns an MCInst into bytes and fixups | Code Emitter |
| Fixup | A note that some bits depend on an expression not known yet | Fixups |
| Fixup kind | Which bits and how: generic (FK_Data_4) or target (fixup_aarch64_pcrel_call26) | Fixups |
| Fragment | A piece of a section: data, relaxable instruction, alignment, fill, ... | Assembler |
| Layout | Assigning offsets to all fragments, repeated until relaxation stops | Assembler |
| MCAsmInfo | Syntax and object-format facts of a target | Printer |
| MCContext | Owner of all symbols, sections and expressions | Data Structures |
| MCExpr | A value computed at assembly or link time | Data Structures |
| MCInst | Opcode plus operands; the unit everything in MC works on | Data Structures |
| MCInstPrinter | Turns an MCInst into text | Printer |
| MCStreamer | Interface for "emit label / instruction / bytes / directive" | Streamers |
| MCValue | An evaluated expression: SymA - SymB + Constant plus specifier | Data Structures |
| Object writer | Writes the file format; the target part picks relocation types | AsmBackend |
| Relaxation | Replacing an instruction with a longer form when its operand does not fit | Assembler |
| Relocation | An entry in the object asking the linker to patch bytes | Fixups |
| Specifier | Target modifier on an expression, e.g. AArch64 :got:, :lo12: | Fixups |
| Target streamer | Per-target object for directives only that target has | Streamers |
| TargetRegistry | Where each target registers factory functions for its MC objects | Custom backend |
Where Do I Look?
| Question | Look at |
|---|---|
| Why is this instruction printed this way? | <T>InstPrinter::printInst, InstAlias records |
| Why are these the bytes? | -show-mc-encoding; Inst field layout; encoder methods |
| Why is there a relocation here? | Fixup kind and specifier; <T>ELFObjectWriter::getRelocType |
| Why is the value wrong after linking? | adjustFixupValue in <T>AsmBackend.cpp |
| What does my backend need to implement? | Custom backend, checklist |
Part 8: Hands-on Assignments: Build the Toy Backend
Fourteen stages, one per topic, that build a complete Toy backend step by step, ending with clang compiling C to Toy ELF objects.
Pages
- 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
Assignments: Build the Toy Backend
Relevant source files
The following files were used as context for generating this wiki page:
A hands-on track that turns the guide into a working compiler backend. Each stage adds one piece of a backend for Toy, a small 32-bit RISC target, and ends with tests you can run. After the last stage, clang --target=toy-unknown-elf -O2 -c compiles small C programs to Toy ELF object files.
Purpose and Scope
The stages follow the guide's bring-up order. Each one names the pages to read, the files to write, the tests to run, and a "done when" list. No solution code is provided: the Toy snippets in the guide are illustrative starting points, and these assignments were written from the guide, not compiled, so expect to adapt signatures to your LLVM version.
The Toy Architecture
| Property | Value |
|---|---|
| Word | 32-bit, little endian, byte addressed |
| Registers | r0–r15; r15 = sp, r14 = lr, r11 = frame pointer when used, r0 reads as zero is not used (all general) |
| Calling convention | Args r0–r3, then stack (4-byte slots); return r0(/r1); callee-saved r4–r11, lr; stack 8-byte aligned, grows down |
| Data layout | e-m:e-p:32:32-i64:64-n32-S64 |
| Instruction size | 4 bytes |
| Format | Bits | Instructions |
|---|---|---|
| R | op[31:26] rd[25:21] rs[20:16] rt[15:11] 0[10:0] | add sub and or xor sll srl sra mul slt sltu |
| I | op[31:26] rd[25:21] rs[20:16] imm16[15:0] | addi andi ori lui lw lh lb lbu lhu sw sh sb beq bne blt bge |
| J | op[31:26] imm26[25:0] | call (pc-relative, word offset), jmp |
| Other | R form | ret (jump to lr), jr rs |
Pick any unused opcode numbers and write them in your ToyInstrInfo.td. Branch and call offsets are signed word offsets from the next instruction.
Stages
| Stage | Builds | Milestone |
|---|---|---|
| 1 | LLVM build with an experimental target | Build tree ready |
| 2 | Triple, TargetInfo, CMake | llc --version lists toy |
| 3 | Toy.td, registers, empty instruction set | TableGen runs |
| 4 | MC descriptors, MCAsmInfo, instruction printer | Libraries link |
| 5 | TargetMachine, Subtarget, PassConfig | llc -march=toy on an empty module |
| 6 | TargetLowering, arguments and returns | ret void reaches selection |
| 7 | ALU instructions, selector, AsmPrinter | First function prints |
| 8 | Register hooks, copies, spills | Register pressure test passes |
| 9 | Frame lowering | Locals and spills on the stack |
| 10 | Loads, stores, globals, branches | Loops and arrays |
| 11 | Calls | Recursive fib |
| 12 | Scheduling model | Measurable reordering |
| 13 | Encodings, code emitter, ELF | Object files |
| 14 | clang driver, test suite, extras | Complete backend |
Working Rules
- Build LLVM with assertions; run every test with
-verify-machineinstrs. - Keep each stage's tests as
litfiles underllvm/test/CodeGen/Toy/(andllvm/test/MC/Toy/from stage 13), so later stages cannot silently break earlier ones. - Compare against AArch64 when stuck: the guide links the AArch64 lines for every piece.
Stage 1: Build Setup
Relevant source files
The following files were used as context for generating this wiki page:
Get an LLVM build tree that can host a new experimental target and that reports errors usefully.
Purpose and Scope
A configured build of LLVM with assertions, ready to add Toy.
Read First
Tasks
- Configure a separate build directory with
-DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=ON -DLLVM_TARGETS_TO_BUILD=AArch64 -DLLVM_ENABLE_PROJECTS=clang. - Build
llc,llvm-tblgen,llvm-mc,llvm-objdump,FileCheckandllvm-lit. - Read
LLVM_ALL_EXPERIMENTAL_TARGETSinllvm/CMakeLists.txt; you will addToythere in stage 2.
Tests
llc --version lists aarch64; llc -debug-only=isel is accepted (proves assertions are on).
Done When
- ☐ Build finishes
- ☐
-debug-onlyworks - ☐
llvm-lit llvm/test/CodeGen/AArch64/arm64-ccmp.llpasses
Next: stage 2. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 2: Target Registration
Relevant source files
The following files were used as context for generating this wiki page:
Make LLVM know that a toy target exists, before it can do anything.
Purpose and Scope
Triple::toy, a data layout, the TargetInfo library and a CMake skeleton.
Read First
Tasks
- Add
toytoTriple::ArchTypeand the triple parser/printer; add the data layout string from the overview inTargetDataLayout.cpp. - Add
ToytoLLVM_ALL_EXPERIMENTAL_TARGETS; reconfigure with-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=Toy. - Create
lib/Target/Toy/CMakeLists.txtwithadd_llvm_component_group(Toy)andTargetInfo/withgetTheToyTarget()andLLVMInitializeToyTargetInfo(). - Add empty
LLVMInitializeToyTarget,...TargetMC,...AsmPrinterso the init macros link.
Tests
llc --version shows toy - Toy example. A unit test or llc -mtriple=toy-unknown-elf -o - empty.ll reaches "no target machine" instead of "unknown triple".
Done When
- ☐ Triple round-trips (
toy-unknown-elf) - ☐
toyregistered - ☐ Other targets still build
Next: stage 3. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 3: TableGen Skeleton
Relevant source files
The following files were used as context for generating this wiki page:
Describe the registers and an empty instruction set, and get every TableGen backend you need running.
Purpose and Scope
Toy.td, ToyRegisterInfo.td, an empty ToyInstrInfo.td, and the tablegen() lines in CMake.
Read First
Tasks
- Define
R0–R15withHWEncodingandDwarfRegNum; aliasSP/LRnames viaAltNamesor separate asm names. - Define
GPR : RegisterClass<"Toy", [i32], 32, (sequence "R%u", 0, 15)>. - Write
Toy.tdwith includes in dependency order anddef Toy : Target. - Add
-gen-register-info,-gen-instr-info,-gen-subtarget,-gen-asm-writer,-gen-dag-isel,-gen-callingconv,-gen-emitterto CMake.
Tests
llvm-tblgen -print-records -I llvm/include -I llvm/lib/Target/Toy Toy.td succeeds; ToyGenRegisterInfo.inc contains Toy::R15.
Done When
- ☐ All
.incfiles generate - ☐ Register enum has 16 entries plus
NoRegister
Next: stage 4. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 4: MC Layer for Assembly Output
Relevant source files
The following files were used as context for generating this wiki page:
Register the MC objects every tool needs: instruction, register and subtarget info, MCAsmInfo, and the instruction printer.
Purpose and Scope
MCTargetDesc/ with ToyMCTargetDesc.cpp, ToyMCAsmInfo, ToyInstPrinter and LLVMInitializeToyTargetMC.
Read First
Tasks
ToyMCAsmInfo : MCAsmInfoELFwith comment string#, 4-byte alignment, DWARF CFI.ToyInstPrinterusing generatedprintInstruction/getRegisterName; writeprintOperandfor registers and immediates, and a memory operand printerimm(reg).- Register asm info, instr info, register info, subtarget info and printer.
Tests
Everything links; llvm-mc -triple=toy-unknown-elf --version runs (no parser yet).
Done When
- ☐
LLVMToyDesclinks without CodeGen - ☐ No missing-factory crash when tools start
Next: stage 5. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 5: TargetMachine and Subtarget
Relevant source files
The following files were used as context for generating this wiki page:
Create the per-compilation and per-CPU objects and the pass pipeline.
Purpose and Scope
ToyTargetMachine, ToySubtarget, ToyPassConfig, empty ToyInstrInfo, ToyRegisterInfo, ToyFrameLowering stubs.
Read First
Tasks
- Constructor calls
CodeGenTargetMachineImpl(...)withTT.computeDataLayout(), theninitAsmInfo(). - Subtarget owns instr info, frame lowering and lowering; calls
ParseSubtargetFeatures. ToyPassConfig::addInstSelectoradds your selector (stub for now).ToyRegisterInfo:getCalleeSavedRegs,getReservedRegs(SP),getFrameRegister(stubs are fine).
Tests
llc -mtriple=toy-unknown-elf empty.ll -o - (a module with no functions) prints a file header and exits 0.
Done When
- ☐ Empty module compiles
- ☐
-mcpu=genericaccepted
Next: stage 6. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 6: TargetLowering, Arguments and Returns
Relevant source files
The following files were used as context for generating this wiki page:
Tell SelectionDAG which types are legal and lower function entry and return.
Purpose and Scope
ToyTargetLowering constructor, ToyCallingConv.td (CC_Toy, RetCC_Toy, CSR_Toy), LowerFormalArguments, LowerReturn, CanLowerReturn.
Read First
Tasks
addRegisterClass(MVT::i32, &Toy::GPRRegClass),computeRegisterProperties, thenExpandforSDIV,SREM,UDIV,UREM, rotates,CTPOP,BR_CC,SELECT_CC.- Calling convention exactly as in the overview.
ToyISD::RETnode and aRETpseudo or instruction withisReturn.
Tests
define void @f() { ret void } reaches instruction selection (error should now be Cannot select or succeed if RET has a pattern). Six-argument i32 function: -stop-after=finalize-isel shows two %fixed-stack loads.
Done When
- ☐
ret voidandret i32 %aselected - ☐
i64return splits intor0/r1 - ☐
i128return demoted tosret
Next: stage 7. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 7: Instruction Selection and the First Function
Relevant source files
The following files were used as context for generating this wiki page:
The first real milestone: a function with arithmetic compiles to Toy assembly.
Purpose and Scope
R- and I-format ALU instructions with patterns, immediates, ToyDAGToDAGISel, ToyAsmPrinter, ToyMCInstLower.
Read First
Tasks
- Instruction classes for R and I formats with
Sched<[]>placeholders. - Patterns for
add sub and or xor shl srl sra mul setlt setult;simm16anduimm16leaves. - Materialize 32-bit constants with
lui+ori(aPatonimm). - Selector with
SelectCode; AsmPrinter withMCInstLower. - Minimal
ToyFrameLowering(no frame) so PEI does not crash.
Tests
define i32 @f(i32 %a, i32 %b) { %s = add i32 %a, %b
%m = mul i32 %s, 12345678
ret i32 %m }
Expected shape (illustrative): add r0, r0, r1 / lui r1, ... / ori r1, r1, ... / mul r0, r0, r1 / ret. Add lit tests with FileCheck.
Done When
- ☐ All ALU operations selected at
-O0and-O2 - ☐ Large constants work
- ☐
-verify-machineinstrsclean
Stretch
Add -O2 patterns that fold add with an immediate into addi.
Next: stage 8. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 8: Registers, Copies and Spills
Relevant source files
The following files were used as context for generating this wiki page:
Make the register allocator work under pressure.
Purpose and Scope
copyPhysReg, storeRegToStackSlot, loadRegFromStackSlot, isLoadFromStackSlot/isStoreToStackSlot, correct reserved registers.
Read First
Tasks
copyPhysRegemitsaddi rd, rs, 0(or anor).- Spill/reload use
sw/lwwith a frame-index operand pair(FI, 0). - Reserve
sp; reserver11only whenhasFP.
Tests
Write a function that keeps 20 values live at once (sum of 20 loaded values used twice). With -O2, MIR after greedy must contain spill slots and assembly must contain reloads, and the result must be correct when run in a simulator if you have one.
Done When
- ☐ High-pressure test compiles at
-O0(fast allocator) and-O2(greedy) - ☐ No use of reserved registers
Next: stage 9. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 9: Frame Lowering
Relevant source files
The following files were used as context for generating this wiki page:
Give every function a correct stack frame.
Purpose and Scope
Real emitPrologue/emitEpilogue, eliminateFrameIndex, frame pointer support, large offsets.
Read First
Tasks
- Prologue
addi sp, sp, -N; epilogue before the first terminator. eliminateFrameIndexrewrites(FI, off)to(sp|fp, off + objectOffset + stackSize).hasFPImplfor variable-sized objects and-frame-pointer=all; save/restorer11.- Offsets beyond
simm16:requiresRegisterScavenging, build the address withlui/ori/addin a scavenged register. - Dynamic
alloca(DYNAMIC_STACKALLOCexpanded).
Tests
Local array of 16 words, a 100 KB local array, a dynamic alloca, and the stage-8 spill test. Compare -stop-before=prolog-epilog and -stop-after=prolog-epilog MIR.
Done When
- ☐ Stack stays 8-byte aligned
- ☐ Large frame compiles
- ☐
-frame-pointer=allworks
Stretch
CFI directives (CFI) and shrink wrapping.
Next: stage 10. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 10: Memory, Globals and Control Flow
Relevant source files
The following files were used as context for generating this wiki page:
Compile real loops: loads and stores of all widths, global addresses, compares and branches.
Purpose and Scope
Load/store patterns with an address ComplexPattern, GlobalAddress lowering, branch instructions, analyzeBranch/insertBranch/removeBranch.
Read First
Tasks
SelectAddrmatching(add base, simm16), frame indices and plain registers.- Sign/zero-extending loads and truncating stores (
lb,lbu,sb, ...). GlobalAddresscustom-lowered toToyISD::HI/LO→lui+addiwith%hi/%looperand flags printed by the instruction printer.BRCOND/SETCCpatterns usingbeq/bne/blt/bge/slt; unconditionaljmp.- Branch analysis hooks so
-O2branch folding and block placement work.
Tests
Array sum loop, strlen, a switch (expanded to compares), a global counter increment.
Done When
- ☐ Loops at
-O0and-O2 - ☐ All load/store widths
- ☐
-verify-machineinstrsclean after branch folding
Next: stage 11. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 11: Calls
Relevant source files
The following files were used as context for generating this wiki page:
Make functions call each other, including recursion and stack arguments.
Purpose and Scope
LowerCall, ToyISD::CALL, CALL instruction (isCall, Defs = [LR]), call-frame pseudos, getCallPreservedMask.
Read First
Tasks
- Implement
LowerCallfollowing the Toy version on the callconv custom backend page. ADJCALLSTACKDOWN/UPregistered in theToyInstrInfoconstructor;eliminateCallFramePseudoInstr.- Save
lrand used callee-saved registers in the prologue (default spill path).
Tests
Recursive fib(n), a call with six arguments, a call whose result is used after another call. Check lr is saved only in non-leaf functions.
Done When
- ☐ Recursion correct
- ☐ Stack arguments at the right offsets
- ☐ Values live across calls are in callee-saved registers
Stretch
Sibling calls (tail calls) and varargs (special arguments).
Next: stage 12. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 12: Scheduling Model
Relevant source files
The following files were used as context for generating this wiki page:
Give the scheduler real latencies for an imagined in-order Toy core.
Purpose and Scope
ToySchedule.td types on every instruction, a ToyModel, ProcessorModel<"toy2", ...>, enableMachineScheduler.
Read First
Tasks
- Model:
IssueWidth = 1,MicroOpBufferSize = 0, load latency 3, multiply latency 4,CompleteModel = 1. - Resources: one ALU, one multiplier, one load/store unit.
Tests
The dot-product function from the scheduling walkthroughs: compare -stop-before/after=machine-scheduler with -mcpu=toy2; loads should move ahead of the multiplies that use them.
Done When
- ☐ TableGen reports no missing scheduling info
- ☐ Reordering visible in MIR
Next: stage 13. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 13: Object Files
Relevant source files
The following files were used as context for generating this wiki page:
Emit Toy ELF objects with correct encodings and relocations.
Purpose and Scope
Inst encodings in TableGen, ToyMCCodeEmitter, fixup kinds, ToyAsmBackend, ToyELFObjectWriter.
Read First
Tasks
- Fill
Inst{31-26}etc. for every format from the overview. - Fixups:
fixup_toy_hi16,fixup_toy_lo16,fixup_toy_branch16,fixup_toy_call26; encoder methods for branch and call targets. applyFixupresolves local branches; others become relocations (pick an unusedEM_number and your own relocation numbers).
Tests
llc -filetype=obj on the stage-11 tests; llc -show-mc-encoding matches hand-encoded instructions; llvm-objdump -r shows relocations for global and external calls.
Done When
- ☐ Every instruction encodes
- ☐ Local branches resolved, external ones relocated
Stretch
Asm parser and disassembler (parser and disassembler) so llvm-mc and llvm-objdump -d work.
Next: stage 14. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.
Stage 14: Capstone, a Complete Toy Backend
Relevant source files
The following files were used as context for generating this wiki page:
Tie everything together: compile C with clang and prove the backend correct on a test suite.
Purpose and Scope
A clang target (clang/lib/Basic/Targets/Toy.{h,cpp}) and a regression and execution test suite.
Read First
Tasks
- Add a clang
TargetInfofortoy(type sizes matching the data layout, predefined__toy__). - Compile 10 programs at
-O0and-O2: arithmetic, loops, recursion, arrays, structs by value, globals,switch, function pointers,long longmath (libcalls), a spill-heavy function. - If you write or reuse a simple Toy simulator, run them and compare with host results; otherwise check assembly by hand against the ABI.
- Keep everything as
littests.
Tests
clang --target=toy-unknown-elf -O2 -c prog.c succeeds for all 10 programs; the whole llvm/test/CodeGen/Toy directory passes under llvm-lit.
Done When
- ☐ Every checklist item on the bring-up checklist ticked
Stretch
Varargs, tail calls, CFI and shrink wrapping, llvm-mca with your model, GlobalISel.
Next: stage 15. All Toy code and expected output on this page are illustrative, not LLVM source and not tool output; your exact output may differ.