Skip to content

Register Allocation 08 rewriting post ra

Mugundan edited this page Nov 27, 2026 · 1 revision

Rewriting and Post-RA Passes

Relevant source files

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

Basic, Greedy and PBQP only record their decisions in `VirtRegMap`. `VirtRegRewriter` is the pass that applies them: it replaces every virtual register operand with its physical register, deletes copies that became no-ops, and fills in block live-in lists. After it, the function contains no virtual registers. A few cleanup passes then run before the frame is laid out.

Purpose and Scope

This page covers VirtRegRewriter in detail and the passes between it and prologue/epilogue insertion. The Fast allocator rewrites operands itself and does not use this pass.

VirtRegRewriter::run

bool VirtRegRewriter::run(MachineFunction &fn) {
  ...
  // Add kill flags while we still have virtual registers.
  LIS->addKillFlags(VRM);

  // Live-in lists on basic blocks are required for physregs.
  addMBBLiveIns();

  // Rewrite virtual registers.
  rewrite();

  if (ClearVirtRegs) {
    // Write out new DBG_VALUE instructions.
    ...
    DebugVars->emitDebugValues(VRM);

    // All machine operands and other references to virtual registers have been
    // replaced. Remove the virtual registers and release all the transient data.
    VRM->clearAllVirt();
    MRI->clearVirtRegs();
  }
  return true;
}
Step Why
addKillFlags Liveness is about to be thrown away; killed flags on physical registers are what later passes (and the register scavenger) rely on
addMBBLiveIns After allocation, each block must list the physical registers live on entry (liveins: in MIR). That is computed from each virtual register's interval and its assignment, per lane when sub-register liveness is on (addLiveInsForSubRanges)
rewrite The actual operand replacement
emitDebugValues LiveDebugVariables put back DBG_VALUEs that point at the final registers or stack slots
clearVirtRegs No virtual registers remain; the function gets the NoVRegs property

ClearVirtRegs is false when a target runs the allocator in several rounds (with filters) and only the last round's rewriter should clear everything.

Sources: llvm/lib/CodeGen/VirtRegMap.cpp:343-376, llvm/lib/CodeGen/VirtRegMap.cpp:378-424

rewrite(): Operand by Operand

    for (MachineInstr &MI : llvm::make_early_inc_range(MBBI->instrs())) {
      for (MachineOperand &MO : MI.operands()) {
        // Make sure MRI knows about registers clobbered by regmasks.
        if (MO.isRegMask())
          MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());

        if (!MO.isReg() || !MO.getReg().isVirtual())
          continue;
        Register VirtReg = MO.getReg();
        MCRegister PhysReg = VRM->getPhys(VirtReg);
        ...
        RewriteRegs.insert(PhysReg);
        assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");

        // Preserve semantics of sub-register operands.
        unsigned SubReg = MO.getSubReg();
        if (SubReg != 0) {
          ...

For each virtual register operand:

  1. Look up its physical register in VirtRegMap. It is a bug (assertion) if the allocator assigned a reserved register.
  2. If the operand has a sub-register index, the result is the matching sub-register of the physical register. %15.sub_32 with %15 → $x9 becomes $w9, as in the loop example. When sub-register liveness is not tracked, implicit operands are added for the full register so that writing half a register still counts as touching the whole of it.
  3. Replace the operand. The rewritten operand is marked renamable, which tells later passes (copy propagation, post-RA scheduling) that the allocator chose this register freely and it may be renamed.
  4. Record the physical register as used (RewriteRegs, and regmask clobbers via addPhysRegsUsedFromRegMask). Prologue/epilogue insertion uses the "used physical registers" set to decide which callee-saved registers to save.

Sources: llvm/lib/CodeGen/VirtRegMap.cpp:654-693

Identity Copies

Once operands are rewritten, many COPYs have the same register on both sides. handleIdentityCopy deals with them:

void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) {
  if (!MI.isIdentityCopy())
    return;
  ...
  // Copies like:
  //    %r0 = COPY undef %r0
  //    %al = COPY %al, implicit-def %eax
  // give us additional liveness information: The target (super-)register
  // must not be valid before this point. Replace the COPY with a KILL
  // instruction to maintain this information.
  if (MI.getOperand(1).isUndef() || MI.getNumOperands() > 2) {
    MI.setDesc(TII->get(TargetOpcode::KILL));
    return;
  }

  if (Indexes)
    Indexes->removeSingleMachineInstrFromMaps(MI);
  MI.eraseFromBundle();
}

This is where all the hint work pays off. In the first example the COPYs %0 = COPY $w0, %1 = COPY $w1, %2 = COPY $w2 and $w0 = COPY %4 all became $wN = COPY $wN and were erased, leaving the single MADDWrrr.

Copy bundles created by splitting with sub-registers are expanded into separate copies (expandCopyBundle).

Sources: llvm/lib/CodeGen/VirtRegMap.cpp:492-528, llvm/lib/CodeGen/VirtRegMap.cpp:529

Before and After, Side by Side

The call example (-stop-before=greedy versus -stop-after=virtregrewriter):

%1:gpr32 = COPY $w1                          renamable $w19 = COPY $w1
%0:gpr32 = COPY $w0                          (deleted: identity copy $w0 = COPY $w0)
ADJCALLSTACKDOWN 0, 0, ...                   ADJCALLSTACKDOWN 0, 0, ...
$w0 = COPY %0                                (deleted: identity copy)
BL @g, csr_aarch64_aapcs, ...                BL @g, csr_aarch64_aapcs, ...
ADJCALLSTACKUP 0, 0, ...                     ADJCALLSTACKUP 0, 0, ...
%2:gpr32 = COPY $w0                          (deleted: identity copy)
$w0 = ADDWrr %2, %1                          $w0 = ADDWrr killed renamable $w0, killed renamable $w19
RET_ReallyLR implicit $w0                    RET_ReallyLR implicit $w0

%1 crosses the call, so it got callee-saved $w19, and its copy from $w1 remains as a real move (mov w19, w1). %0 and %2 got $w0 and their copies disappeared.

The Passes After the Rewriter

From the observed AArch64 -O2 pipeline (Pipeline):

Pass What it does for allocated code
Stack Slot Coloring (stack-slot-coloring) Spill slots whose live ranges (from LiveStacks) do not overlap are merged, so the frame is smaller. It also removes load/store pairs made redundant by the merge
addPostRewrite() Target hook; AArch64 adds a sub-register mitigation pass when enabled
Machine Copy Propagation (machine-cp) Forwards the source of remaining physical-register copies into later uses and deletes copies that become dead
Machine LICM (machinelicm, post-RA) Hoists loop-invariant reloads and rematerialised instructions out of loops
addPostRegAlloc() Target hook; AArch64 runs redundant copy elimination and A57 FP load balancing
PostRA Machine Sinking, Shrink Wrapping (optimised builds only) Sink copies toward their uses; choose where the prologue and epilogue go so cold paths avoid saving callee-saved registers
Prologue/Epilogue Insertion (prologepilog) Saves and restores the callee-saved registers that were used, lays out the frame, and turns every frame index (%stack.N) into a concrete address by calling TargetRegisterInfo::eliminateFrameIndex
Post-RA pseudo expansion (ExpandPostRAPseudos) Lowers COPY to real instructions via TargetInstrInfo::copyPhysReg; target-specific pseudos via expandPostRAPseudo

Sources: llvm/lib/CodeGen/TargetPassConfig.cpp:1532-1548, llvm/lib/CodeGen/TargetPassConfig.cpp:1176-1206, llvm/lib/CodeGen/VirtRegMap.cpp:754

Frame Indexes Become Addresses

After the rewriter, a spill looks like STRWui killed renamable $w8, %stack.11, 0. The slot still has offset: 0 in the MIR stack: section. Prologue/epilogue insertion assigns each slot an offset from sp or the frame pointer and calls eliminateFrameIndex on every instruction that names a frame index. In the 24-load test, the final assembly shows the result: str w8, [sp, #32]. Later the AArch64 load/store optimiser paired neighbouring accesses into stp w8, w10, [sp, #48], which is why some spills print as "8-byte Folded Spill".

If the offset does not fit in the instruction's immediate, eliminateFrameIndex needs a scratch register. That is what the register scavenger provides after allocation; see TargetRegisterInfo Hooks.

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