Repository navigation
Register Allocation 03 liveness
Relevant source files
The following files were used as context for generating this wiki page:
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).
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.
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
| 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).
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 |
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
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
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.
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.
- 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