Repository navigation
IR 11 dataflow
Relevant source files
The following files were used as context for generating this wiki page:
Data-flow analysis computes facts that hold at each point of a program, such as "which variables may still be read later" or "which assignments may reach here", by propagating information along CFG edges until nothing changes. Classic compiler textbooks present it on non-SSA code. In LLVM IR, SSA makes several of these analyses almost free, but the framework is still the way to think about anything that involves memory or whole-block facts.
This page covers the general framework (direction, transfer function, meet, fixed point), three classic analyses (liveness, reaching definitions, available expressions), the worklist algorithm, and how SSA use-def chains replace much of this in LLVM. All examples are illustrative and worked by hand.
Every data-flow analysis is defined by four choices:
| Choice | Meaning | Options |
|---|---|---|
| Domain | What a fact is | Usually a set: of variables, definitions or expressions |
| Direction | Which way facts flow | Forward (from entry, along edges) or backward (from exits, against edges) |
| Transfer function | How a block changes the facts | Typically OUT = GEN ∪ (IN − KILL)
|
| Meet | How facts from several edges combine | Union ("may" analyses) or intersection ("must" analyses) |
For a forward analysis on block B:
IN[B] = meet of OUT[P] over all predecessors P
OUT[B] = GEN[B] ∪ (IN[B] − KILL[B])
For a backward analysis swap the roles: OUT[B] is the meet over successors, and IN[B] is computed from OUT[B].
Because loops make IN depend on OUT of later blocks, the equations are solved by iterating until no set changes: the fixed point. With finite sets and transfer functions that only ever grow (or only shrink) the sets, this always terminates.
| Analysis | Question | Direction | Meet | GEN[B] | KILL[B] |
|---|---|---|---|---|---|
| Liveness | Will this variable be read before being overwritten? | Backward | Union | Variables used in B before any assignment in B | Variables assigned in B |
| Reaching definitions | Which assignments may have produced the value here? | Forward | Union | Last assignment to each variable in B | Other assignments to the variables B assigns |
| Available expressions | Has a+b already been computed on every path, with a, b unchanged? |
Forward | Intersection | Expressions computed in B and not later invalidated in B | Expressions using a variable assigned in B |
Uses: liveness drives register allocation and dead store elimination; reaching definitions drives constant propagation on non-SSA code; available expressions drives common subexpression elimination.
Non-SSA pseudo-code (illustrative), a loop that sums i into s:
flowchart TD
B1["B1: s = 0; i = 0"] --> B2["B2: if i < n"]
B2 -->|true| B3["B3: s = s + i; i = i + 1"]
B3 --> B2
B2 -->|false| B4["B4: return s"]
| Block | USE (GEN) | DEF (KILL) |
|---|---|---|
| B1 | {} | {s, i} |
| B2 | {i, n} | {} |
| B3 | {s, i} | {s, i} |
| B4 | {s} | {} |
Equations: OUT[B] = ∪ IN[S] over successors S, IN[B] = USE[B] ∪ (OUT[B] − DEF[B]). Start with every set empty and process blocks in reverse order:
| Iteration | IN[B4] | IN[B3] | IN[B2] | IN[B1] |
|---|---|---|---|---|
| 1 | {s} | {s, i} (OUT = IN[B2] = {} so far) | {i, n, s} | {n} |
| 2 | {s} | {s, i, n} (OUT = {i, n, s}) | {i, n, s} | {n} |
| 3 | no change | no change | no change | no change |
Result: n is live into the function, as expected for a parameter, and s, i, n are all live around the loop. In iteration 2 only B3 changed, which is why a worklist (below) is better than sweeping every block each time.
Instead of re-sweeping all blocks, keep a worklist of blocks whose input may have changed:
for each block B: OUT[B] = {} (backward analysis shown)
worklist = all blocks
while worklist not empty:
B = worklist.pop()
OUT[B] = ∪ IN[S] for S in successors(B)
newIN = USE[B] ∪ (OUT[B] − DEF[B])
if newIN != IN[B]:
IN[B] = newIN
for P in predecessors(B): worklist.push(P) (their OUT depends on IN[B])
Order matters for speed, not for the answer: forward analyses converge fastest in reverse post-order, backward analyses in post-order.
mem2reg needs to know in which blocks a stack variable is live on entry, so it can avoid inserting dead phis. PromoteMem2Reg::ComputeLiveInBlocks is a small backward liveness analysis for one variable: it seeds a worklist with the blocks that load the variable before storing to it, then walks predecessors, adding each to the live-in set until it reaches a block that stores to the variable (a KILL).
DCE.cpp uses the same idea for a different fact, "this instruction is dead": eliminateDeadCode deletes trivially dead instructions, and each deletion pushes the instruction's operands onto a worklist because they may have just become dead.
Sources: llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:1039, llvm/lib/Transforms/Scalar/DCE.cpp:55-110
In SSA every value has exactly one definition, and that definition dominates its uses. So:
| Classic analysis | In LLVM SSA |
|---|---|
| Reaching definitions | Not needed for SSA values: the operand is the single reaching definition (a use-def chain) |
| Def-use chains | Stored directly: V->users() / V->uses()
|
| Liveness of a value | A value is live from its definition to its last use; computed from use lists and the dominator tree when needed (the back end does this for virtual registers) |
| Constant propagation | Sparse: propagate along def-use edges, not over every block (sccp) |
| Available expressions | Replaced by value numbering on SSA values (gvn, early-cse) |
These are called sparse analyses: information is attached to values and flows along def-use edges, instead of a set at every program point. They are much cheaper.
Classic dense data-flow is still needed for memory, which is not in SSA form: "has this location been written since?" depends on every store and call on every path. LLVM answers such questions with alias analysis and MemorySSA, which puts memory operations into an SSA-like form so the same sparse techniques work.
// Illustrative: walking use-def and def-use chains.
for (Use &U : I->operands()) // use-def: what I reads
errs() << "uses " << *U.get() << "\n";
for (User *Usr : I->users()) // def-use: who reads I
errs() << "used by " << *Usr << "\n";Sources: llvm/include/llvm/IR/Value.h:75, llvm/include/llvm/IR/Use.h:35
- A data-flow analysis is a domain, a direction, a transfer function and a meet; iterate to a fixed point.
- A worklist only revisits blocks whose inputs changed.
- SSA turns reaching definitions and def-use chains into pointers; dense analysis remains for memory.
- 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