Repository navigation
IR 08 ssa phi
Relevant source files
The following files were used as context for generating this wiki page:
SSA (static single assignment) form means every value is assigned exactly once in the program text. A C variable that is assigned in several places becomes several IR values. Where control paths join and different paths carry different values, a phi instruction picks the right one. This page explains why LLVM uses SSA, how phi works, and how the mem2reg pass builds SSA from the simpler code Clang emits.
This page covers the SSA rule, the phi instruction and its placement rules, and the mem2reg pass with a before/after example. Dominance, which decides where phis are needed, is explained in depth on Dominance.
In this C code x is assigned twice:
int x = a;
x = x + 1;
return x * 2;In SSA each assignment creates a new name (illustrative):
%x1 = add i32 %a, 1
%x2 = mul i32 %x1, 2
ret i32 %x2Because every value has one definition:
- "Which definition reaches this use?" has one answer: the operand pointer itself.
- A value can be replaced everywhere with
replaceAllUsesWith, with no need to check for other assignments. - Many analyses (constant propagation, dead code, value numbering) become simple walks over def-use chains.
A second rule goes with it: a definition must dominate all its uses. Every path from the entry block to a use must pass through the definition, so the value always exists when it is used. The verifier checks this.
Straight-line code is easy. The problem is a join point:
int x;
if (c) x = 1; else x = 2;
return x;After the if, x is 1 or 2 depending on which branch ran. Neither definition dominates the return. A phi creates a new value that is selected by the edge control arrived on (illustrative):
define i32 @pick(i1 %c) {
entry:
br i1 %c, label %then, label %else
then:
br label %join
else:
br label %join
join:
%x = phi i32 [ 1, %then ], [ 2, %else ]
ret i32 %x
}phi i32 [ 1, %then ], [ 2, %else ] means "1 if we came from %then, 2 if we came from %else".
flowchart TD
E["entry: br %c"] --> T["then"]
E --> F["else"]
T -->|"x = 1"| J["join: %x = phi [1,%then],[2,%else]"]
F -->|"x = 2"| J
Sources: llvm/include/llvm/IR/Instructions.h:2727
| Rule | Reason |
|---|---|
phis must be at the top of a block, before any other instruction |
They conceptually run "on the edge", all at once, as control enters |
| One incoming entry per predecessor edge | Each way in must say what value it brings |
Every incoming value has the same type as the phi
|
Same as any other instruction |
An incoming value only needs to be available at the end of its predecessor, not in the phi's block |
The value travels along the edge |
All phis at the top of a block are evaluated together, so in a loop this swap is correct (illustrative):
loop:
%a = phi i32 [ 0, %entry ], [ %b, %loop ]
%b = phi i32 [ 1, %entry ], [ %a, %loop ]phi is not a real machine instruction. Before register allocation the back end replaces each phi with copies at the end of the predecessor blocks; see the Register Allocation wiki.
In C++, PHINode has getNumIncomingValues(), getIncomingValue(i), getIncomingBlock(i) and addIncoming(V, BB). BasicBlock::phis() iterates over the phis at the top of a block.
Building SSA directly is fiddly, so Clang does something simpler. At -O0, and as the first step at higher levels, every local variable gets an alloca, every read is a load, and every write is a store. Memory is not subject to the single-assignment rule, so this is valid IR. Then the mem2reg pass (or the more general sroa) promotes those stack slots to SSA values and inserts the phis.
int pick(int c) { int x; if (c) x = 1; else x = 2; return x; }(illustrative, shaped like clang -O0 -Xclang -disable-O0-optnone -S -emit-llvm)
define i32 @pick(i32 %c) {
entry:
%c.addr = alloca i32, align 4
%x = alloca i32, align 4
store i32 %c, ptr %c.addr, align 4
%0 = load i32, ptr %c.addr, align 4
%tobool = icmp ne i32 %0, 0
br i1 %tobool, label %if.then, label %if.else
if.then:
store i32 1, ptr %x, align 4
br label %if.end
if.else:
store i32 2, ptr %x, align 4
br label %if.end
if.end:
%1 = load i32, ptr %x, align 4
ret i32 %1
}(illustrative)
define i32 @pick(i32 %c) {
entry:
%tobool = icmp ne i32 %c, 0
br i1 %tobool, label %if.then, label %if.else
if.then:
br label %if.end
if.else:
br label %if.end
if.end:
%x.0 = phi i32 [ 1, %if.then ], [ 2, %if.else ]
ret i32 %x.0
}The allocas, loads and stores are gone. The load of %c.addr was replaced by %c directly, because only one store reached it. The load of %x became a phi, because two different stores reached it. simplifycfg would then turn the empty diamond into a select, see Common Passes.
mem2reg is registered in PassRegistry.def as FUNCTION_PASS("mem2reg", PromotePass()).
Sources: llvm/lib/Passes/PassRegistry.def:491
PromoteMemoryToRegister.cpp implements the classic algorithm (Cytron et al., 1991) in four steps:
-
Pick promotable allocas.
isAllocaPromotableaccepts anallocaonly if it is used just by simpleloads andstores (and a few harmless intrinsics). If its address escapes, for example by being passed to a call, it must stay in memory. -
Find where the variable is live.
ComputeLiveInBlocksfinds the blocks where the variable's value is needed on entry. Aphiin a block where it is not live would be dead, so these blocks restrict placement. -
Place phis at the iterated dominance frontier. The blocks containing
stores are the definition blocks. Aphiis needed exactly where two different definitions first meet, which is the dominance frontier of the definition blocks, and repeated because each newphiis itself a definition.ForwardIDFCalculatorcomputes this set, andQueuePhiNodeinserts an emptyphiin each block. -
Rename. A walk over the CFG in dominator-tree order keeps the "current value" of each variable. A
storeupdates it, aloadis replaced by it, and on each edge the current value is added as an incoming value of the successor'sphis. Finally theallocas andstores are deleted.
flowchart LR
A["Promotable allocas<br/>isAllocaPromotable"] --> L["Live-in blocks<br/>ComputeLiveInBlocks"]
L --> P["Insert phis at IDF<br/>ForwardIDFCalculator, QueuePhiNode"]
P --> R["Rename loads/stores<br/>along dominator tree"]
R --> D["Delete allocas"]
The public entry point used by passes is PromoteMemToReg(Allocas, DT, ...), which needs a dominator tree.
Sources: llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:66, llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:809, llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:879-895, llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:1039, llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:1108, llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:1259, llvm/include/llvm/Analysis/IteratedDominanceFrontier.h:39-55
A loop always needs a phi in its header, because the header is reached both from before the loop and from the end of the previous iteration (illustrative, after mem2reg):
int sum(int n) { int s = 0; for (int i = 0; i < n; i++) s += i; return s; }define i32 @sum(i32 %n) {
entry:
br label %for.cond
for.cond:
%s.0 = phi i32 [ 0, %entry ], [ %add, %for.body ]
%i.0 = phi i32 [ 0, %entry ], [ %inc, %for.body ]
%cmp = icmp slt i32 %i.0, %n
br i1 %cmp, label %for.body, label %for.end
for.body:
%add = add nsw i32 %s.0, %i.0
%inc = add nsw i32 %i.0, 1
br label %for.cond
for.end:
ret i32 %s.0
}Here %add is used by a phi in %for.cond even though %for.body comes "later" in the text. That is allowed: the use is on the edge from %for.body, and %add dominates the end of %for.body.
- SSA: one definition per value, and the definition dominates every use.
-
phipicks a value by incoming edge;phis sit at the top of a block. - Clang emits
alloca/load/store;mem2reginsertsphis at the iterated dominance frontier and renames.
- 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