Repository navigation
Register Allocation 09.1 tablegen registers
Relevant source files
The following files were used as context for generating this wiki page:
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.
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
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
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
- 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.
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
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
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", ...>;
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.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look