Skip to content

Register Allocation 07.1 spill weights

Mugundan edited this page Nov 27, 2026 · 1 revision

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):

  1. physical-register hints before virtual-register hints;
  2. then by accumulated weight, highest first;
  3. then non-callee-saved before callee-saved;
  4. 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

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