Skip to content

Register Allocation 09.3 tii hooks

Mugundan edited this page Nov 27, 2026 · 1 revision

TargetInstrInfo Hooks

Relevant source files

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

`InstrInfo` tells the allocator how to *move* values: copy one register to another, store a register to a stack slot, load it back, recompute it, or read it straight from memory. Three of these hooks are mandatory. Without them the default implementations call `llvm_unreachable`, and compilation stops with "Target didn't implement ...".

Purpose and Scope

Declarations at the pinned commit, who calls each hook, what AArch64 does, and illustrative sketches for the made-up "Toy" target (not LLVM source).

Required Hooks

copyPhysReg

virtual void copyPhysReg(MachineBasicBlock &MBB,
                         MachineBasicBlock::iterator MI, const DebugLoc &DL,
                         Register DestReg, Register SrcReg, bool KillSrc,
                         bool RenamableDest = false,
                         bool RenamableSrc = false) const {
  llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg!");
}

Emit an instruction (or a sequence) that copies SrcReg to DestReg. Both are physical registers. It is called after allocation, when ExpandPostRAPseudos lowers each remaining COPY, and by the Fast allocator and frame lowering.

Handle every pair of register classes that can appear in a COPY:

  • same class (GPR to GPR);
  • across classes (GPR to FPR, if your ISA has a move for it);
  • register pairs and tuples (copy each sub-register; take care with overlapping source and destination, copy in the right direction);
  • special registers (flags, if a COPY of them can occur).

If a pair is impossible, make sure it never reaches COPY: use getCrossCopyRegClass or CopyCost = -1 on the class.

AArch64 forwards to copyPhysRegImpl, a large function that covers GPR, FPR, SVE, tuples and flag registers.

// ToyInstrInfo.cpp (illustrative, not LLVM source)
void ToyInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
                               MachineBasicBlock::iterator I,
                               const DebugLoc &DL, Register Dst, Register Src,
                               bool KillSrc, bool, bool) const {
  if (Toy::GPRRegClass.contains(Dst, Src)) {
    BuildMI(MBB, I, DL, get(Toy::MOVrr), Dst)
        .addReg(Src, getKillRegState(KillSrc));
    return;
  }
  if (Toy::GPRPairRegClass.contains(Dst, Src)) {
    // Copy halves; if they overlap, copy the high half first.
    Register DLo = RI.getSubReg(Dst, Toy::sub_lo), DHi = RI.getSubReg(Dst, Toy::sub_hi);
    Register SLo = RI.getSubReg(Src, Toy::sub_lo), SHi = RI.getSubReg(Src, Toy::sub_hi);
    bool HiFirst = DLo == SHi;
    auto Copy = [&](Register D, Register S) {
      BuildMI(MBB, I, DL, get(Toy::MOVrr), D).addReg(S, getKillRegState(KillSrc));
    };
    if (HiFirst) { Copy(DHi, SHi); Copy(DLo, SLo); }
    else         { Copy(DLo, SLo); Copy(DHi, SHi); }
    return;
  }
  llvm_unreachable("Impossible register copy");
}

Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:1083-1093, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:6365-6375

storeRegToStackSlot and loadRegFromStackSlot

virtual void storeRegToStackSlot(
    MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
    bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
    MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const;

virtual void loadRegFromStackSlot(
    MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg,
    int FrameIndex, const TargetRegisterClass *RC, Register VReg,
    unsigned SubReg = 0,
    MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const;

Insert, before MI, a store of SrcReg (or a load into DestReg) to frame index FrameIndex, using an instruction suitable for class RC.

Callers and what they pass:

Caller Register passed Notes
InlineSpiller (Greedy, Basic, PBQP) A virtual register Your instruction must accept a virtual register of class RC. You may constrain its class (AArch64 does)
RegAllocFast A physical register; VReg is the virtual register being spilled
Prologue/epilogue insertion (callee-saved saves) A physical register; Flags is FrameSetup / FrameDestroy Pass the flag through to the instructions you create

The AArch64 version chooses the opcode by spill size and class:

  MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
  MachineMemOperand *MMO =
      MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
                              MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
  ...
  switch (RI.getSpillSize(*RC)) {
  ...
  case 4:
    if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
      Opc = AArch64::STRWui;
      if (SrcReg.isVirtual())
        MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR32RegClass);

That is the STRWui ... %stack.N, 0 seen in the spill example. Three things to copy from it:

  1. Always attach a MachineMemOperand for the fixed stack slot. Alias analysis, the scheduler and the load/store optimiser rely on it.
  2. Pick by spill size and class, and cover every allocatable class. A missing case is a crash under register pressure, which may not show up until a big test.
  3. Use the frame index as the address operand (.addFrameIndex(FI).addImm(0)); eliminateFrameIndex fixes it later.
// ToyInstrInfo.cpp (illustrative, not LLVM source)
void ToyInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
    MachineBasicBlock::iterator I, Register Src, bool IsKill, int FI,
    const TargetRegisterClass *RC, Register, MachineInstr::MIFlag Flags) const {
  MachineFunction &MF = *MBB.getParent();
  MachineFrameInfo &MFI = MF.getFrameInfo();
  auto *MMO = MF.getMachineMemOperand(
      MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
      MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
  unsigned Opc = Toy::GPRRegClass.hasSubClassEq(RC)     ? Toy::STW
               : Toy::GPRPairRegClass.hasSubClassEq(RC) ? Toy::STD
               : 0;
  assert(Opc && "Cannot store this register class to a stack slot");
  BuildMI(MBB, I, DebugLoc(), get(Opc))
      .addReg(Src, getKillRegState(IsKill))
      .addFrameIndex(FI).addImm(0)
      .addMemOperand(MMO)
      .setMIFlag(Flags);
}

loadRegFromStackSlot mirrors it with MOLoad and a load opcode.

Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:1195-1226, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:6400-6440, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:6580

Strongly Recommended

isLoadFromStackSlot and isStoreToStackSlot

virtual Register isLoadFromStackSlot(const MachineInstr &MI,
                                     int &FrameIndex) const {
  return 0;
}
virtual Register isStoreToStackSlot(const MachineInstr &MI,
                                    int &FrameIndex) const {
  return 0;
}

Recognise your own spill and reload instructions: return the register and set FrameIndex, or return 0. The header requires returning 0 "if the instruction has any side effects other than loading from the stack slot". The spiller uses them to delete redundant spills and reloads (coalesceStackAccess, eliminateRedundantSpills), Stack Slot Coloring uses them, and the AsmPrinter uses them to print the // 4-byte Spill comments. With the defaults, everything still works but spill code is worse.

Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:320-365, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:2852-2881

Rematerialisation

Mark instructions isReMaterializable = 1 in TableGen (and usually isAsCheapAsAMove = 1). That is often enough: the generic check accepts an instruction whose uses are only constants or unallocatable physical registers:

  /// Return true if the instruction is trivially rematerializable, meaning it
  /// has no side effects and requires no operands that aren't always available.
  /// This means the only allowed uses are constants and unallocatable physical
  /// registers so that the instructions result is independent of the place
  /// in the function.
  bool isTriviallyReMaterializable(const MachineInstr &MI) const {
Hook Override when
isReMaterializableImpl(MI) The flag is set but some forms of the instruction are not safe to recompute (e.g. a load that is only safe from invariant memory). Must return false if the instruction has any side effects other than producing a value
reMaterialize(MBB, MI, DestReg, SubIdx, Orig, UsedLanes) The copy needs adjusting (e.g. a different opcode when DestReg is a sub-register)

Effects: the coalescer can duplicate the definition instead of keeping a copy (coalescer), the spill weight is halved (spill weights), and the spiller recomputes instead of reloading (inline spiller).

Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:171-218, llvm/include/llvm/CodeGen/TargetInstrInfo.h:488-495

isCopyInstrImpl

virtual std::optional<DestSourcePair>
isCopyInstrImpl(const MachineInstr &MI) const {
  return std::nullopt;
}

If your target has move instructions that survive until allocation (for example a MOVrr emitted by ISel instead of a COPY), report them here so copy hints, sibling-copy detection in the spiller and copy propagation treat them as copies. AArch64's is at AArch64InstrInfo.cpp:11511.

Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:1112-1120, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:11511

Optional

foldMemoryOperandImpl

virtual MachineInstr *
foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,
                      ArrayRef<unsigned> Ops, int FrameIndex,
                      MachineInstr *&CopyMI, LiveIntervals *LIS = nullptr,
                      VirtRegMap *VRM = nullptr) const {
  return nullptr;
}

Ops are the operand indices of MI that refer to the register being spilled. If MI has a form that reads (or writes) memory directly, build it with the frame index instead and return it; return nullptr otherwise. The generic foldMemoryOperand wrapper adds the memory operand. Worth doing for CISC-style ISAs; load/store ISAs can skip it.

Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:1450-1475, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:7154

expandPostRAPseudo

virtual bool expandPostRAPseudo(MachineInstr &MI) const { return false; }

Called on pseudo instructions that remain after allocation. A useful pattern: during ISel, emit a pseudo with simple register constraints (so allocation is easy), and expand it here into the real sequence once registers are known. AArch64's MOVi32imm is an example: it is selected as a rematerialisable pseudo and expanded later.

Sources: llvm/include/llvm/CodeGen/TargetInstrInfo.h:1228-1234, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:2559

Two-address helpers

findCommutedOpIndices, commuteInstructionImpl, convertToThreeAddress: see PHI Elimination and Two-Address Lowering.

Summary

Hook Status Missing it causes
copyPhysReg Required llvm_unreachable on the first COPY
storeRegToStackSlot, loadRegFromStackSlot Required llvm_unreachable the first time anything spills
isLoadFromStackSlot, isStoreToStackSlot Recommended Redundant spill code; no spill comments
isReMaterializable / isReMaterializableImpl Recommended Constants spilled instead of recomputed
isCopyInstrImpl Recommended if target moves survive ISel Missed hints and copy propagation
foldMemoryOperandImpl Optional Extra loads on CISC targets
expandPostRAPseudo As needed Pseudos reach the AsmPrinter

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