Skip to content

SelectionDAG 08 phi resolution

Mugundan edited this page Nov 27, 2026 · 1 revision

PHI Node Resolution

Relevant source files

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

SelectionDAG has no PHI node. A DAG describes one block, while a PHI chooses a value according to which edge was taken, so PHIs are handled across block boundaries with virtual registers in four hand-offs.

Purpose and Scope

This page follows an IR PHI from FunctionLoweringInfo through SelectionDAGBuilder and FinishBasicBlock to the PHIElimination pass, with a real loop example and its MIR at each stage. It touches DAG Construction and Scheduling and MIR Emission.

Overview of the Four Hand-Offs

sequenceDiagram
  participant FLI as FunctionLoweringInfo
  participant SDB as SelectionDAGBuilder
  participant ISEL as SelectionDAGISel
  participant PE as PHIElimination
  FLI->>FLI: set creates export vregs, MBBs, empty machine PHIs
  loop for each IR block, reverse post-order
    SDB->>SDB: HandlePHINodesInSuccessorBlocks before the terminator
    Note right of SDB: CopyToReg of incoming value into PHI operand vreg, record PHI and vreg pair
    ISEL->>ISEL: CodeGenAndEmitDAG for the block
    ISEL->>ISEL: FinishBasicBlock adds vreg and MBB operands to the PHIs
  end
  PE->>PE: LowerPHINode turns each PHI into COPYs, splits critical edges
Loading
  1. Before any DAG is built, empty machine PHIs and their registers are created.
  2. At the end of each predecessor's DAG, the incoming value is copied into a virtual register.
  3. After the predecessor is emitted, that register is attached as the PHI's operand for that edge.
  4. Much later, the PHIElimination pass turns every machine PHI into COPYs, and the register coalescer removes most of them.

Step 1: Set-Up Before Selection (FunctionLoweringInfo::set)

This runs once per function, before the first DAG is built:

  • Every IR value that is used outside its defining block, or by a PHI, gets one or more virtual registers (InitializeRegForValue, stored in FuncInfo.ValueMap). The number of registers follows the type: one for i32, two for i128. These are the export registers.
  • A MachineBasicBlock is created for every IR block, so successors already exist as targets.
  • For every live IR PHI (one that has users and a non-empty type), an empty machine PHI instruction is created at the top of its MBB, defining the PHI's registers: BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i). No operands yet.

Sources: llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:46-55, llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:231-235, llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:291-315

Step 2: At the End of Each Predecessor (HandlePHINodesInSuccessorBlocks)

Just before SelectionDAGBuilder::visit handles a block's terminator, it looks at every successor that begins with PHIs (each successor once, even if a switch reaches it through several edges). For each live PHI it takes the value this block contributes, PN.getIncomingValueForBlock(thisBlock), and:

  • If it is a constant: allocate (or reuse, via a per-block ConstantsOut map) a fresh virtual register and emit CopyToReg of the constant into it. Integer constants are sign- or zero-extended according to TLI.signExtendConstant, so later known-bits analysis of PHI results is valid.
  • If it is an instruction or argument: look up its export register in ValueMap. A CopyToReg into that register was already emitted right after the value was computed, by CopyToExportRegsIfNeeded.
  • Record the pair (machine PHI instruction, register) in FuncInfo.PHINodesToUpdate, once per register of the value.

The pair is only recorded here, not applied, because lowering the block can create several machine blocks, so the last one (the one that actually branches to the successor) is not known yet.

Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:12450-12523, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2384-2395, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:11860-11884

Step 3: Attaching Operands (FinishBasicBlock)

After the block's DAG has been emitted, SelectionDAGISel::FinishBasicBlock walks PHINodesToUpdate and, for each pair, appends the operands (register, FuncInfo->MBB) to the machine PHI. The condition FuncInfo->MBB->isSuccessor(PHI->getParent()) guards against stale entries. If the block was split (a jump table, bit tests, a stack-protector check), the code that creates the extra blocks fixes up the pairs so each PHI gets the right predecessor. PHINodesToUpdate is cleared before the next IR block.

Because blocks are selected in reverse post-order, the register for a value arriving on a loop back edge is still undefined when the loop header's PHI is created. That is fine: the register number was fixed in step 1, and the definition appears later in the MIR, which is still valid SSA.

Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1974-1992, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:2117-2126

Real Example: A Loop with Three PHIs

This function sums n integers. After the IR-level loop strength reduction pass, the IR that reaches instruction selection is:

entry:
  %c = icmp sgt i32 %n, 0
  br i1 %c, label %loop.preheader, label %exit
loop.preheader:
  br label %loop
loop:
  %lsr.iv1 = phi ptr [ %p, %loop.preheader ], [ %scevgep, %loop ]
  %lsr.iv  = phi i32 [ %n, %loop.preheader ], [ %lsr.iv.next, %loop ]
  %acc     = phi i32 [ %acc.next, %loop ], [ 0, %loop.preheader ]
  %v = load i32, ptr %lsr.iv1, align 4
  %acc.next = add i32 %acc, %v
  %lsr.iv.next = add i32 %lsr.iv, -1
  %scevgep = getelementptr i8, ptr %lsr.iv1, i64 4
  %done = icmp eq i32 %lsr.iv.next, 0
  br i1 %done, label %exit, label %loop
exit:
  %r = phi i32 [ 0, %entry ], [ %acc.next, %loop ]
  ret i32 %r

The real MIR straight out of instruction selection (llc -mtriple=aarch64 -O2 -stop-after=finalize-isel):

bb.0.entry:
  successors: %bb.1, %bb.3
  liveins: $x0, $w1
  %8:gpr32common = COPY $w1
  %7:gpr64 = COPY $x0
  %10:gpr32all = COPY $wzr            ; constant 0 flowing to %r's PHI, edge entry->exit
  %9:gpr32all = COPY %10
  %11:gpr32 = SUBSWri %8, 1, 0, implicit-def $nzcv
  Bcc 11, %bb.3, implicit $nzcv
  B %bb.1

bb.1.loop.preheader:
  %13:gpr32all = COPY $wzr            ; constant 0 flowing to %acc's PHI
  %12:gpr32all = COPY %13

bb.2.loop:
  %0:gpr64sp = PHI %7, %bb.1, %5, %bb.2       ; %lsr.iv1
  %1:gpr32sp = PHI %8, %bb.1, %4, %bb.2       ; %lsr.iv
  %2:gpr32   = PHI %12, %bb.1, %3, %bb.2      ; %acc
  early-clobber %14:gpr64sp, %15:gpr32 = LDRWpost %0, 4   ; load + pointer increment, one instruction
  %16:gpr32 = ADDWrr %2, killed %15           ; %acc.next
  %3:gpr32all = COPY %16                      ; export of %acc.next
  %17:gpr32 = SUBSWri %1, 1, 0, implicit-def dead $nzcv   ; %lsr.iv.next
  %4:gpr32all = COPY %17                      ; export of %lsr.iv.next
  %5:gpr64all = COPY %14                      ; export of %scevgep
  CBNZW %17, %bb.2
  B %bb.3

bb.3.exit:
  %6:gpr32all = PHI %9, %bb.0, %3, %bb.2      ; %r
  $w0 = COPY %6
  RET_ReallyLR implicit $w0
MIR Source
%0, %1, %2, %6 = PHI ... The empty machine PHIs from step 1, now with operand pairs from step 3
%7, %8 (COPY $x0, COPY $w1) Live-in copies of the arguments %p and %n, the incoming values from the preheader edge
%12 = COPY %13, %13 = COPY $wzr The constant 0 arriving at %acc from loop.preheader: step 2's constant path
%9 = COPY %10, %10 = COPY $wzr The constant 0 arriving at %r from entry
%3 = COPY %16, %4 = COPY %17, %5 = COPY %14 The CopyToReg exports of %acc.next, %lsr.iv.next, %scevgep, which feed the loop's own PHIs on the back edge and the exit PHI
LDRWpost load plus getelementptr i8, 4 merged by the combiner into one indexed load (see DAG Combiner and AArch64 Instruction Selection)

Step 4: PHI Elimination (PHIElimination)

The machine PHIs survive all the SSA-form machine passes (machine CSE, LICM, sinking, peepholes) and are removed just before register allocation, because PHIs cannot be allocated. For each %d = PHI [%a, bbA], [%b, bbB] the pass:

flowchart TD
  P["PHI: d = PHI a from bbA, b from bbB"] --> T["Create one fresh vreg t<br/>IncomingReg"]
  T --> D["At the PHI position:<br/>d = COPY t"]
  T --> A["At the end of bbA before terminators:<br/>t = COPY a"]
  T --> B["At the end of bbB before terminators:<br/>t = COPY b"]
  A --> CE{"Critical edge?<br/>pred has several successors<br/>and block has several preds"}
  B --> CE
  CE -- yes --> SP["Split the edge with a new block<br/>and put the copy there"]
  CE -- no --> OK["Copy stays in the predecessor"]
Loading

Using a fresh temporary that is read only at the top of the destination block avoids the classic lost-copy and swap problems of naive PHI lowering. Real output for the loop above (-stop-after=phi-node-elimination, trimmed):

bb.1:                                  ; NEW block: splits the critical edge entry -> exit
  %10:gpr32all = COPY $wzr
  %9:gpr32all = COPY killed %10
  %21:gpr32all = COPY killed %9        ; copy into the exit PHI's temporary
  B %bb.4

bb.2.loop.preheader:
  %13:gpr32all = COPY $wzr
  %12:gpr32all = COPY killed %13
  %18:gpr64sp = COPY killed %7         ; temporaries for the three loop PHIs,
  %19:gpr32sp = COPY killed %8         ; written on the preheader edge
  %20:gpr32 = COPY killed %12

bb.3.loop:
  %2:gpr32 = COPY killed %20           ; the PHIs themselves are now copies at the top
  %1:gpr32sp = COPY killed %19
  %0:gpr64sp = COPY killed %18
  early-clobber %14:gpr64sp, %15:gpr32 = LDRWpost killed %0, 4
  %16:gpr32 = ADDWrr killed %2, killed %15
  %3:gpr32all = COPY killed %16
  %17:gpr32 = SUBSWri killed %1, 1, 0, implicit-def $nzcv
  %4:gpr32all = COPY killed %17
  %5:gpr64all = COPY killed %14
  %18:gpr64sp = COPY killed %5         ; back-edge copies into the same temporaries
  %19:gpr32sp = COPY killed %4
  %20:gpr32 = COPY %3
  %21:gpr32all = COPY killed %3        ; value for the exit PHI
  Bcc 1, %bb.3, implicit killed $nzcv
  B %bb.4

bb.4.exit:
  %6:gpr32all = COPY killed %21        ; exit PHI is a copy from its temporary
  $w0 = COPY killed %6
  RET_ReallyLR implicit killed $w0

bb.1 did not exist in the IR: both ends of the entry -> exit edge have several neighbours, so PHI elimination inserted a block. PHIElimination may also reuse one incoming register across PHIs in the same block when it can (reusedIncoming).

Sources: llvm/lib/CodeGen/PHIElimination.cpp:365-420, llvm/lib/CodeGen/PHIElimination.cpp:860-880

Step 5: Copy Cleanup and the Final Code

TwoAddressInstruction handles tied operands, and the register coalescer merges registers joined by COPY whenever their live ranges do not interfere. After it, the loop is:

bb.3.loop:
  early-clobber %18:gpr64common, %15:gpr32 = LDRWpost %18, 4
  %21:gpr32 = ADDWrr %21, %15
  %19:gpr32common = SUBSWri %19, 1, 0, implicit-def $nzcv
  Bcc 1, %bb.3, implicit killed $nzcv
  B %bb.4

and the final assembly has no copies in the loop at all:

sum:
        cmp     w1, #1
        b.lt    .LBB0_4
        mov     w8, wzr              ; acc = 0 (constant from the preheader edge)
.LBB0_2:
        ldr     w9, [x0], #4         ; LDRWpost
        subs    w1, w1, #1
        add     w8, w8, w9
        b.ne    .LBB0_2
        mov     w0, w8               ; exit PHI, loop path
        ret
.LBB0_4:
        mov     w8, wzr              ; exit PHI, entry path (the constant 0)
        mov     w0, w8
        ret

Special Cases

  • Multi-register PHIs. A PHI of an illegal type that spans several registers (i128 on AArch64 is two i64) becomes one machine PHI per register, and PHINodesToUpdate gets one entry per register.
  • Dead PHIs (no users) and PHIs of empty types create nothing.
  • PHI of i1 or i8. The PHI's registers have the promoted type (a 32-bit register), and the exported value is extended with the node kind chosen by PreferredExtendType or any-extend.
  • undef incoming value. The CopyToReg source is IMPLICIT_DEF, and InstrEmitter emits an IMPLICIT_DEF instruction for the register instead of a COPY.
  • Switches that reach a PHI block through several edges are handled once per successor block.

Summary

When Where What
Before ISel FunctionLoweringInfo::set Allocate export vregs; create MBBs; create empty machine PHIs
End of each IR block's DAG SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks CopyToReg of constants and incoming values into PHI-operand vregs; record (PHI, vreg) pairs
After each block is emitted SelectionDAGISel::FinishBasicBlock Add (vreg, MBB) operands to the machine PHIs
Pre-register-allocation PHIElimination One temp vreg per PHI; copies in predecessors; critical-edge splitting
Register allocation register-coalescer, greedy Remove copies, assign physical registers

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