Skip to content

Register Allocation 07.2 inline spiller

Mugundan edited this page Nov 27, 2026 · 1 revision

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
Loading

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 MachineInstrSpan and 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; a KILL is 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.

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