Repository navigation
SelectionDAG 08 phi resolution
Relevant source files
The following files were used as context for generating this wiki page:
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.
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
-
Before any DAG is built, empty machine
PHIs and their registers are created. - At the end of each predecessor's DAG, the incoming value is copied into a virtual register.
- After the predecessor is emitted, that register is attached as the PHI's operand for that edge.
-
Much later, the
PHIEliminationpass turns every machine PHI intoCOPYs, and the register coalescer removes most of them.
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 inFuncInfo.ValueMap). The number of registers follows the type: one fori32, two fori128. These are the export registers. - A
MachineBasicBlockis 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
PHIinstruction 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
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
ConstantsOutmap) a fresh virtual register and emitCopyToRegof the constant into it. Integer constants are sign- or zero-extended according toTLI.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. ACopyToReginto that register was already emitted right after the value was computed, byCopyToExportRegsIfNeeded. - 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
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
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 %rThe 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) |
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"]
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
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-
Multi-register PHIs. A PHI of an illegal type that spans several registers (
i128on AArch64 is twoi64) becomes one machine PHI per register, andPHINodesToUpdategets one entry per register. - Dead PHIs (no users) and PHIs of empty types create nothing.
-
PHI of
i1ori8. The PHI's registers have the promoted type (a 32-bit register), and the exported value is extended with the node kind chosen byPreferredExtendTypeor any-extend. -
undefincoming value. TheCopyToRegsource isIMPLICIT_DEF, andInstrEmitteremits anIMPLICIT_DEFinstruction for the register instead of aCOPY. - Switches that reach a PHI block through several edges are handled once per successor block.
| 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 |
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look