Skip to content

Register Allocation 09.2 tri hooks

Mugundan edited this page Nov 27, 2026 · 1 revision

TargetRegisterInfo Hooks

Relevant source files

The following files were used as context for generating this wiki page:

`RegisterInfo` derives from the TableGen-generated `GenRegisterInfo` and adds the facts that depend on the function being compiled: which registers are off limits, which are preserved across calls, how to address a stack slot, and which register a value would like. This page goes through the hooks the allocator and its neighbours call, required ones first.

Purpose and Scope

For each hook: the declaration at the pinned commit, what calls it, what AArch64 does, and a short illustrative sketch for the made-up "Toy" target where useful. Toy code is not LLVM source.

Required Hooks

These are pure virtual (= 0) or have defaults that are wrong for any real target.

getReservedRegs

virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;

Return every register the allocator must never assign: the stack pointer, the zero register, the frame pointer when this function needs one, platform registers, and the super-registers of all of them. The comment in the header says it directly: "It is often necessary to reserve the super registers of a reserved register as well, to avoid them getting allocated indirectly. You may use markSuperRegs() and checkAllSuperRegsMarked()".

Called by MachineRegisterInfo::freezeReservedRegs at the start of allocation (framework) and by RegisterClassInfo to build allocation orders.

AArch64 splits the set in two. getStrictlyReservedRegs holds registers that are never usable at all:

  BitVector Reserved(getNumRegs());
  markSuperRegs(Reserved, AArch64::WSP);
  markSuperRegs(Reserved, AArch64::WZR);

  if (TFI->isFPReserved(MF))
    markSuperRegs(Reserved, AArch64::W29);
  ...
  if (hasBasePointer(MF))
    markSuperRegs(Reserved, AArch64::W19);

and getReservedRegs adds registers kept from the allocator only, such as lr while the function still has virtual registers:

  if (MF.getSubtarget<AArch64Subtarget>().isLRReservedForRA()) {
    // In order to prevent the register allocator from using LR, we need to
    // mark it as reserved. However we don't want to keep it reserved throughout
    // the pipeline since it prevents other infrastructure from reasoning about
    // it's liveness. We use the NoVRegs property instead of IsSSA because
    // IsSSA is removed before VirtRegRewriter runs.
    if (!MF.getProperties().hasNoVRegs())

Note markSuperRegs(Reserved, AArch64::WSP): reserving wsp also reserves sp. Reserve the smallest register and mark upwards.

Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:400-404, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:419-470, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:535-550

getCalleeSavedRegs

virtual const MCPhysReg*
getCalleeSavedRegs(const MachineFunction *MF) const = 0;

Return the null-terminated list of registers this function must preserve, normally a TableGen _SaveList. It may depend on the function's calling convention and attributes. AArch64 switches on both:

  if (TLI->supportSwiftError() &&
      F.getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
    if (Darwin)
      return CSR_Darwin_AArch64_AAPCS_SwiftError_SaveList;
    ...
  }

  switch (F.getCallingConv()) {
  case CallingConv::GHC:
    // GHC set of callee saved regs is empty as all those regs are
    // used for passing STG regs around
    return CSR_AArch64_NoRegs_SaveList;

Used by RegisterClassInfo (callee-saved registers go last in allocation orders), Greedy's callee-saved cost, and prologue/epilogue insertion (which saves the ones actually used).

Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:325-330, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:72-100

getCallPreservedMask

virtual const uint32_t *getCallPreservedMask(const MachineFunction &MF,
                                             CallingConv::ID) const {
  // The default mask clobbers everything.  All targets should override.
  return nullptr;
}

Return the register mask for calls with the given calling convention, normally a TableGen _RegMask. Your call lowering attaches it to each call instruction (DAG.getRegisterMask(Mask) in LowerCall), and LiveIntervals records where those masks are (liveness). This is how the allocator learns which registers a call destroys.

If you forget it, every value live across a call interferes with every register, and the allocator will spill everything around every call, or fail.

Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:355-364, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:271

getFrameRegister

virtual Register getFrameRegister(const MachineFunction &MF) const = 0;

The register that addresses the frame. AArch64:

  return TFI->hasFP(MF) ? AArch64::FP : AArch64::SP;

Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:1080-1082, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:753-756

eliminateFrameIndex

virtual bool eliminateFrameIndex(MachineBasicBlock::iterator MI,
                                 int SPAdj, unsigned FIOperandNum,
                                 RegScavenger *RS = nullptr) const = 0;

Called by prologue/epilogue insertion for every operand that is a frame index (every spill and reload, plus allocas). Replace operand FIOperandNum with the frame register and add the slot's offset to the instruction's immediate. Return true only if you erased MI.

The hard case: the offset does not fit the immediate. Then you need a scratch register to build the address, after allocation, when all registers may be in use. That is what the register scavenger is for (next section). Illustrative Toy sketch:

// ToyRegisterInfo.cpp (illustrative, not LLVM source)
bool ToyRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
                                          int SPAdj, unsigned FIOp,
                                          RegScavenger *RS) const {
  MachineInstr &MI = *II;
  MachineFunction &MF = *MI.getParent()->getParent();
  int FI = MI.getOperand(FIOp).getIndex();
  Register FrameReg;
  int64_t Off = getFrameLowering(MF)
                    ->getFrameIndexReference(MF, FI, FrameReg).getFixed() +
                MI.getOperand(FIOp + 1).getImm();
  if (isInt<12>(Off)) {                      // fits the immediate
    MI.getOperand(FIOp).ChangeToRegister(FrameReg, false);
    MI.getOperand(FIOp + 1).ChangeToImmediate(Off);
    return false;
  }
  // Too far: materialise FrameReg + Off in a scratch virtual register;
  // the scavenger (requiresFrameIndexScavenging) assigns it later.
  ...
}

AArch64's real implementation is at AArch64RegisterInfo.cpp:978.

Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:1015-1022, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:978

The Register Scavenger

After allocation there are no virtual registers, yet eliminateFrameIndex (and some pseudo expansions) may need a temporary register. Two hooks opt in:

virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
  return false;
}
...
virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
  return false;
}
Hook Effect when true
requiresRegisterScavenging Prologue/epilogue insertion creates a RegScavenger and passes it to eliminateFrameIndex. The scavenger finds a free physical register at a point, or spills one to an emergency slot
requiresFrameIndexScavenging After frame index elimination, any virtual registers you created there are assigned physical registers by the scavenger
useFPForScavengingIndex Place the emergency spill slot near the frame pointer (default true)

AArch64 returns true for both main hooks. A target whose immediates can reach any offset in practice can leave them false. If your frame can be larger than your immediate range, turn them on and make your frame lowering reserve an emergency slot (RS->addScavengingFrameIndex) in processFunctionBeforeFrameFinalized.

Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:882-898, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:758-790

Quality Hooks

Optional; defaults are safe.

getRegAllocationHints

virtual bool
getRegAllocationHints(Register VirtReg, ArrayRef<MCPhysReg> Order,
                      SmallVectorImpl<MCPhysReg> &Hints,
                      const MachineFunction &MF,
                      const VirtRegMap *VRM = nullptr,
                      const LiveRegMatrix *Matrix = nullptr) const;

Append preferred physical registers to Hints. They are tried first by every allocator that uses AllocationOrder (framework). Return true for hard hints: only those registers will be tried. The header advises: "Targets that override this function should typically call this default implementation as well and expect to see generic copy hints added."

Typical uses:

  • Register pairs. Instruction selection sets a target hint with MRI.setRegAllocationHint(Reg, ToyHint::EvenPart, PartnerVReg); the hook reads it, looks at where the partner was assigned (VRM->getPhys), and hints the matching even or odd register. When one half is coalesced, updateRegAllocHint lets you fix the other half's hint.
  • Short encodings. Hint the registers that allow a compact instruction form.

AArch64's override is at AArch64RegisterInfo.cpp:1191.

Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:835-853, llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp:1191

getLargestLegalSuperClass

virtual const TargetRegisterClass *
getLargestLegalSuperClass(const TargetRegisterClass *RC,
                          const MachineFunction &) const {
  /// The default implementation is very conservative and doesn't allow the
  /// register allocator to inflate register classes.
  return RC;
}

After splitting, a piece of a register may only have uses that accept a bigger class (for example gpr32all instead of gpr32common). Returning the largest legal super-class with the same spill size lets the allocator inflate the piece's class and choose from more registers. Implement this if your classes form a lattice.

Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:735-745

Other quality hooks

Hook Default Override when
getCSRFirstUseCost(MF) 0 (use a callee-saved register whenever free) Saving a callee-saved register is costly relative to spilling (Greedy)
shouldCoalesce(...) true Some merges create classes that are too constrained (coalescer)
shouldRegionSplitForVirtReg(MF, LI) true Region splitting is too slow for some huge intervals (splitting)
reverseLocalAssignment() false Many registers and huge blocks; allocate local intervals bottom-up (header warns this is "no longer guaranteed to optimally color")
regClassPriorityTrumpsGlobalness(MF) false Your AllocationPriority should outrank the global/local distinction
getRegPressureLimit(RC, MF) from TableGen Scheduler pressure tracking should assume fewer usable registers
getSpillWeightScaleFactor(RC) 1.0 Some classes are cheaper or dearer to spill (spill weights)
getCrossCopyRegClass(RC) RC Registers of RC cannot be copied directly and need an intermediate class
isConstantPhysReg(R) false Hardware zero registers (AArch64 xzr); lets liveness ignore them
isAsmClobberable(MF, R) true A reserved register must not appear in inline asm clobber lists

Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:418-431, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:731-753, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:855-873, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:1039-1073

Sub-register Liveness

TargetSubtargetInfo::enableSubRegLiveness() (default false) turns on per-lane liveness (liveness). Enable it if your registers are commonly built from or used as parts (vector lanes, register pairs, tuples); it lets the coalescer and allocator treat halves independently. Leave it off until your sub-register indices and lane masks are right, because it exposes every mistake in them.

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