Skip to content

Register Allocation 03 liveness

Mugundan edited this page Nov 27, 2026 · 1 revision

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"]
Loading

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:

  1. no virtual register already assigned to a register containing U has a live segment overlapping V's (checked in LiveRegMatrix with LiveIntervalUnion queries);
  2. the fixed physical liveness of U (arguments, return values, implicit defs) does not overlap V's;
  3. no register mask inside V's live range clobbers P.

Checks 1–3 are exactly LiveRegMatrix::checkInterference, covered on Allocation Framework.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally