LLVM IR Overview
Relevant source files
The following files were used as context for generating this wiki page:
LLVM IR (intermediate representation) is the language that sits between a front end such as Clang and a back end such as the AArch64 code generator. A front end translates source code into IR, the optimizer rewrites IR into faster IR, and a back end translates IR into machine code. This wiki explains IR from the ground up: what it looks like, what each instruction does, and the analyses (CFG, dominance, data flow) that passes use to transform it.
> Note on examples. Every IR listing in this wiki is illustrative: hand-written to match what LLVM produces, but not captured from a tool run. The local build at the time of writing had no clang or opt. Line-numbered source citations were checked against the LLVM checkout at commit a2171756.
Purpose and Scope
This wiki is for readers who have never worked with LLVM IR. It covers:
| Topic | Page |
|---|---|
| How a module is organised | Structure |
| Types | Type System |
| The instruction set | Arithmetic, Compare and Select, Memory, Control Flow |
SSA form and phi | SSA and Phi |
| Program analysis | CFG and Loops, Dominance, Data-flow Analysis |
| Writing and using passes | Writing a Pass, Common Passes |
| Practice | Exercises, Tooling and Glossary |
What happens after the optimizer, when IR becomes machine instructions, is covered by the SelectionDAG wiki and the Target Bring-up wiki.
Why an IR Exists
Without a shared IR, every language would need its own optimizer and its own back end for every processor: N languages times M targets. With one IR in the middle, each front end only emits IR and each back end only consumes it, so the work is N + M, and every optimization written once on IR benefits every language and every target.
flowchart LR
C["C / C++ (Clang)"] --> IR["LLVM IR"]
R["Rust (rustc)"] --> IR
S["Swift"] --> IR
IR --> OPT["Optimizer (opt passes)"]
OPT --> IR2["Optimized IR"]
IR2 --> A64["AArch64 back end"]
IR2 --> X86["X86 back end"]
IR2 --> GPU["GPU back ends"]
LLVM IR has three properties that make it convenient to optimize:
| Property | Meaning | Why it helps |
|---|---|---|
| Typed | Every value has a type such as i32, double or ptr | Passes can check that a rewrite keeps types consistent; the verifier rejects ill-typed IR |
| SSA (static single assignment) | Each value is assigned exactly once | The definition of a value is a single instruction, so "where did this come from?" is a pointer lookup, see SSA and Phi |
| Low level but target independent | Instructions are close to machine operations (add, load, branch) but there are unlimited virtual registers and no fixed calling convention | Optimizations can reason about real costs without knowing the target |
A First Look
This C function:
int add(int a, int b) { return a + b; }
becomes, after optimization, roughly this IR (illustrative):
define i32 @add(i32 %a, i32 %b) {
entry:
%sum = add nsw i32 %a, %b
ret i32 %sum
}
Reading it line by line:
define i32 @add(i32 %a, i32 %b)defines a function named@addthat returns ani32(32-bit integer). Names starting with@are global (functions and global variables); names starting with%are local to the function.entry:is the label of a basic block, a straight-line list of instructions.%sum = add nsw i32 %a, %badds twoi32values.nsw("no signed wrap") records that C signed overflow is undefined, see Arithmetic.ret i32 %sumreturns the result. Every basic block ends with exactly one such terminator instruction.
The Three Forms
The same IR exists in three interchangeable forms:
| Form | File | Produced by | Read by |
|---|---|---|---|
| Text assembly | .ll | clang -S -emit-llvm, llvm-dis, opt -S | Humans, llvm-as, opt, llc |
| Bitcode | .bc | clang -c -emit-llvm, llvm-as, opt | opt, llc, llvm-dis, the linker for LTO |
| In memory | C++ objects | The IR parser or bitcode reader | Passes |
flowchart LR
LL[".ll text"] -->|llvm-as| BC[".bc bitcode"]
BC -->|llvm-dis| LL
LL -->|parse| MEM["In-memory Module<br/>(Function, BasicBlock, Instruction)"]
BC -->|read| MEM
MEM -->|print| LL
MEM -->|write| BC
The text and bitcode forms are lossless encodings of the in-memory form. Passes only ever see the in-memory form: a Module containing Functions, each containing BasicBlocks, each containing Instructions, all of which derive from Value.
Sources: llvm/include/llvm/IR/Value.h:75, llvm/include/llvm/IR/Function.h:65
The Instruction Set at a Glance
All IR opcodes are listed in one file, Instruction.def, grouped by kind:
| Group | Lines | Examples | Page |
|---|---|---|---|
| Terminators | 126-139 | ret, br, switch, invoke, unreachable | Control Flow |
| Unary | 142-144 | fneg | Arithmetic |
| Binary | 147-168 | add, fmul, sdiv, shl, xor | Arithmetic |
| Memory | 171-179 | alloca, load, store, getelementptr, atomics | Memory |
| Casts | 184-199 | trunc, zext, sext, sitofp, bitcast | Arithmetic |
| Other | 207-223 | icmp, fcmp, phi, call, select, freeze | Compare, SSA and Phi |
Sources: llvm/include/llvm/IR/Instruction.def:126-223
Where Passes Fit
The optimizer is a sequence of passes. Each pass either analyses IR (computing facts such as the dominator tree) or transforms it (for example promoting stack variables to registers). opt runs passes by name; the names are registered in PassRegistry.def, for example mem2reg at line 491 and print<domtree> at line 522.
opt -S -passes=mem2reg in.ll -o out.ll
opt -disable-output -passes='print<domtree>' in.ll
Sources: llvm/lib/Passes/PassRegistry.def:491, llvm/lib/Passes/PassRegistry.def:522
How to Read This Wiki
- Overview (this page).
- Structure: modules, functions, blocks, instructions, values and uses.
- Type System.
- Arithmetic, Bitwise and Casts.
- Compare and Select.
- Memory.
- Control Flow.
- SSA and Phi.
- CFG and Loops.
- Dominance.
- Data-flow Analysis.
- Writing a Pass.
- Common Passes.
- Exercises, Tooling and Glossary.
Structure: Modules, Functions, Blocks and Values
Relevant source files
The following files were used as context for generating this wiki page:
An LLVM IR program is a tree of containers: a module holds functions and globals, a function holds basic blocks, and a basic block holds instructions. On top of that tree sits a graph: every instruction that uses a value points to it, and every value keeps a list of its uses. This page explains both.
Purpose and Scope
This page covers the containers (Module, Function, BasicBlock, Instruction), the value hierarchy (Value, User, Use), globals, attributes and metadata. Instruction semantics are on the following pages, starting with Arithmetic.
The Containment Tree
flowchart TD
M["Module (one .ll file)"] --> G["GlobalVariable @counter"]
M --> F1["Function @main"]
M --> F2["Function @helper (declaration only)"]
F1 --> A["Argument %argc"]
F1 --> B1["BasicBlock entry"]
F1 --> B2["BasicBlock loop"]
B1 --> I1["Instruction %x = add ..."]
B1 --> I2["Terminator br label %loop"]
A complete module (illustrative):
; ModuleID = 'example.c'
source_filename = "example.c"
target datalayout = "e-m:e-i64:64-i128:128-n32:64-S128"
target triple = "aarch64-unknown-linux-gnu"
@counter = global i32 0, align 4 ; a global variable
declare i32 @puts(ptr) ; a declaration: no body
define i32 @bump(i32 %by) #0 { ; a definition: has blocks
entry:
%old = load i32, ptr @counter, align 4
%new = add i32 %old, %by
store i32 %new, ptr @counter, align 4
ret i32 %new
}
attributes #0 = { nounwind }
| Level | Class | What it holds |
|---|---|---|
| Module | Module | Globals, functions, the target triple and data layout, named metadata |
| Function | Function | Arguments, a list of basic blocks (none for a declare), attributes |
| Basic block | BasicBlock | A list of instructions; the last one is a terminator |
| Instruction | Instruction | An opcode, a type and operands |
Function derives from GlobalObject: a function is a global value, and its name @bump is its address. BasicBlock derives from Value, which is why a block label such as label %loop can be an operand of a branch.
Sources: llvm/include/llvm/IR/Function.h:65, llvm/include/llvm/IR/BasicBlock.h:61
Basic Blocks and Terminators
A basic block is a sequence of instructions with one entry (the top) and one exit (the terminator at the bottom). Control never jumps into the middle of a block. Two rules follow:
- Every block ends in exactly one terminator (
ret,br,switch,unreachable, ...).BasicBlock::getTerminator()returns it, or null if the block is malformed. phiinstructions, if any, must come first in the block, see SSA and Phi.
The first block of a function is its entry block. It has no predecessors, and it is where allocas for local variables are conventionally placed.
Sources: llvm/include/llvm/IR/BasicBlock.h:237
Values, Users and Uses
Almost everything in IR is a Value: arguments, instructions, basic blocks, functions, globals and constants. A User is a value that has operands, which includes every instruction. Each operand slot is a Use, which links the user to the value it uses.
classDiagram
Value <|-- Argument
Value <|-- BasicBlock
Value <|-- User
User <|-- Instruction
User <|-- Constant
Constant <|-- GlobalValue
GlobalValue <|-- GlobalObject
GlobalObject <|-- Function
GlobalObject <|-- GlobalVariable
class Value { type, name, use list }
class User { operand list of Use }
class Use { Val, Parent user }
For %new = add i32 %old, %by:
- The
addinstruction is aUserwith twoUses. - Use 0 points to
%old(theload), use 1 points to%by(anArgument). %oldkeeps theaddon its use list, so%old->users()finds it.
Because SSA gives each value exactly one definition, the def-use graph is just these pointers. V->replaceAllUsesWith(W) walks V's use list and redirects every Use to W; this is the basic move of most transformations.
// Illustrative: print every instruction that uses value V.
for (User *U : V->users())
if (auto *I = dyn_cast<Instruction>(U))
errs() << *I << "\n";
Sources: llvm/include/llvm/IR/Value.h:75, llvm/include/llvm/IR/User.h:44, llvm/include/llvm/IR/Use.h:35
Names and Numbering
| Prefix | Scope | Examples |
|---|---|---|
@ | Module (global) | @main, @counter, @puts |
% | Function (local) | %a, %sum, %entry |
! | Metadata | !0, !dbg, !tbaa |
# | Attribute group | #0 |
Names are optional. An unnamed value is printed with a number, %0, %1, ..., assigned in order through the function, which is why Clang output is full of %0, %1. Names are only for humans; passes compare Value* pointers, never names.
Attributes and Metadata
Attributes are facts attached to functions, parameters or return values that passes may rely on:
| Attribute | Meaning |
|---|---|
nounwind | The function never throws an exception |
readnone / memory(none) | The function does not touch memory |
noalias on a ptr parameter | No other pointer visible to the function aliases it (like C restrict) |
nonnull, dereferenceable(N) | Pointer facts |
noinline, alwaysinline, optnone | Inliner and optimizer controls |
Metadata is extra information that may be dropped without changing the meaning of the program: debug locations (!dbg), type-based alias info (!tbaa), loop hints (!llvm.loop), branch weights (!prof). It is written after the instruction:
%v = load i32, ptr %p, align 4, !tbaa !5 ; illustrative
Key Points
- Module, function, block, instruction is a strict containment tree.
- Every block ends in exactly one terminator.
- Everything is a
Value; operands areUses; use lists give def-use chains for free.
Type System
Relevant source files
The following files were used as context for generating this wiki page:
Every value in LLVM IR has a type, and every instruction states the types it works on. Types are simple and structural: there are no classes, no signed versus unsigned integers, and only one kind of pointer. This page lists the types a beginner meets and how they are written.
Purpose and Scope
This page covers integer, floating-point, pointer, vector, array, struct, function, void and label types, and how they are represented in C++ by Type and its subclasses. How instructions use these types is covered in Arithmetic and Memory.
The Type Kinds
Each Type object has a TypeID that says which kind it is. The enum is in Type.h:
| Kind | Written as | TypeID |
C++ class |
|---|---|---|---|
| Integer | i1, i8, i32, i64, any iN | IntegerTyID | IntegerType |
| Floating point | half, bfloat, float, double, fp128 | HalfTyID, FloatTyID, DoubleTyID, ... | Type |
| Pointer | ptr, ptr addrspace(N) | PointerTyID | PointerType |
| Fixed vector | <4 x i32>, <2 x double> | FixedVectorTyID | FixedVectorType |
| Scalable vector | <vscale x 4 x i32> | ScalableVectorTyID | ScalableVectorType |
| Array | [10 x i32] | ArrayTyID | ArrayType |
| Struct | { i32, ptr }, %struct.Point | StructTyID | StructType |
| Function | i32 (i32, ptr) | FunctionTyID | FunctionType |
| Void | void | VoidTyID | Type |
| Label | label (a basic block) | LabelTyID | Type |
Type provides predicates such as isIntegerTy(), isPointerTy(), isStructTy() and isArrayTy() that test the TypeID.
Sources: llvm/include/llvm/IR/Type.h:46-79, llvm/include/llvm/IR/Type.h:257-282
Integers Have No Sign
i32 is just 32 bits. Whether those bits are signed is decided by the instruction: sdiv versus udiv, icmp slt versus icmp ult, sext versus zext. C int and unsigned both become i32.
i1 is the boolean type: comparisons produce it and conditional branches consume it.
; illustrative
%q1 = sdiv i32 %a, %b ; signed division
%q2 = udiv i32 %a, %b ; unsigned division of the same bits
%lt = icmp slt i32 %a, %b ; i1 result
Sources: llvm/include/llvm/IR/DerivedTypes.h:42
Pointers Are Opaque
Older LLVM had typed pointers such as i32*. Current LLVM has one pointer type, ptr, that says nothing about what it points to. The type of the data comes from the instruction that accesses it:
; illustrative
%x = load i32, ptr %p ; read 4 bytes as i32
%y = load double, ptr %p ; read 8 bytes as double from the same pointer
Only the address space can differ (ptr addrspace(1) is common on GPUs). If you read old tutorials, mentally replace every T* with ptr and remove the bitcasts between pointer types.
Sources: llvm/include/llvm/IR/DerivedTypes.h:758
Aggregates: Arrays and Structs
| Type | Example | Element access |
|---|---|---|
| Array | [4 x float] | Same type for every element; index can be a variable in getelementptr |
| Struct (literal) | { i32, double } | Fields can differ; field index must be a constant |
| Struct (identified) | %struct.Point = type { i32, i32 } | Same, but has a name and can be recursive through ptr |
| Packed struct | <{ i8, i32 }> | No padding between fields |
; illustrative
%struct.Node = type { i32, ptr } ; int value; struct Node *next
@table = global [3 x i32] [i32 1, i32 2, i32 3]
How these map to byte offsets (alignment and padding) is decided by the module's target datalayout string. See Memory for the getelementptr arithmetic.
Sources: llvm/include/llvm/IR/DerivedTypes.h:278, llvm/include/llvm/IR/DerivedTypes.h:458
Vectors
A vector type holds a fixed number of scalars that one instruction processes together, for SIMD:
; illustrative
%s = add <4 x i32> %a, %b ; four adds at once
%e = extractelement <4 x i32> %s, i32 0 ; take lane 0
Scalable vectors, <vscale x 4 x i32>, have a length that is a multiple of a runtime constant vscale; they model AArch64 SVE and RISC-V V.
Sources: llvm/include/llvm/IR/DerivedTypes.h:490, llvm/include/llvm/IR/DerivedTypes.h:650
Function Types
A function type is a return type and a list of parameter types, optionally variadic:
; illustrative
declare i32 @printf(ptr, ...) ; type: i32 (ptr, ...)
declare void @free(ptr) ; type: void (ptr)
Functions themselves are values of type ptr; the function type is stored separately and used by call.
Sources: llvm/include/llvm/IR/DerivedTypes.h:165
Types Are Unique
Types are created once per LLVMContext and shared: there is exactly one i32 object, so passes compare types by pointer, A->getType() == B->getType(). In C++ you get them with calls such as Type::getInt32Ty(Ctx), PointerType::getUnqual(Ctx) and ArrayType::get(Elt, N).
Key Points
- Integers carry no sign; instructions decide signedness.
- There is one pointer type,
ptr; loads and stores state the accessed type. - Struct and array layout comes from the data layout string.
Arithmetic, Bitwise and Cast Instructions
Relevant source files
The following files were used as context for generating this wiki page:
Arithmetic instructions take two operands of the same type and produce a result of that type. Cast instructions change a value from one type to another. Both groups also carry optional flags (nsw, nuw, exact, fast-math flags) that record extra facts the optimizer may use.
Purpose and Scope
This page covers the binary operators (integer, floating point, shifts and bitwise), the unary fneg, the poison-generating flags, fast-math flags and the cast instructions. Comparisons are on Compare and Select.
Binary Operators
Every binary operator has the form %r = <op> [flags] <type> %a, %b. Both operands and the result have the same type, which may be a scalar or a vector.
| Integer | Floating point | Meaning |
|---|---|---|
add | fadd | Addition |
sub | fsub | Subtraction |
mul | fmul | Multiplication |
udiv, sdiv | fdiv | Division (unsigned, signed) |
urem, srem | frem | Remainder |
shl | Shift left | |
lshr, ashr | Shift right: logical (fill with 0) or arithmetic (copy sign bit) | |
and, or, xor | Bitwise operations |
The unary fneg negates a floating-point value. In C++ all of these are BinaryOperator (or UnaryOperator for fneg), and I->getOpcode() tells them apart.
; illustrative: (a * 4 + b) >> 1, all unsigned 32-bit
%m = mul i32 %a, 4
%s = add i32 %m, %b
%r = lshr i32 %s, 1
There is no neg or not instruction: -x is sub i32 0, %x and ~x is xor i32 %x, -1.
Sources: llvm/include/llvm/IR/Instruction.def:142-168, llvm/include/llvm/IR/InstrTypes.h:206
Undefined Behaviour: Poison and the Wrap Flags
Integer add, sub, mul and shl wrap around by default (modulo 2^N), like C unsigned arithmetic. Flags add a promise:
| Flag | Applies to | Promise | If broken |
|---|---|---|---|
nuw | add, sub, mul, shl | No unsigned overflow | Result is poison |
nsw | add, sub, mul, shl | No signed overflow | Result is poison |
exact | udiv, sdiv, lshr, ashr | No non-zero remainder / no bits shifted out | Result is poison |
disjoint | or | No bit is set in both operands | Result is poison |
Clang puts nsw on signed int arithmetic because signed overflow is undefined in C. That lets passes reason like a mathematician: with nsw, (x + 1) > x folds to true; without it, it does not, because INT_MAX + 1 wraps to INT_MIN.
Poison is a special value meaning "this computation went wrong". It is not immediate undefined behaviour: it spreads through later arithmetic, and only becomes undefined behaviour when it reaches something with a side effect, such as a branch condition or a store address. freeze turns poison into an arbitrary but fixed value.
Division by zero is immediate undefined behaviour, not poison, which is why passes are careful about moving udiv and sdiv.
In C++, OverflowingBinaryOperator exposes hasNoUnsignedWrap() and hasNoSignedWrap(), and PossiblyExactOperator exposes isExact().
Sources: llvm/include/llvm/IR/Operator.h:78-84, llvm/include/llvm/IR/Operator.h:156
Fast-Math Flags
Floating-point instructions follow IEEE-754 by default, so (a + b) + c cannot be reassociated. Fast-math flags relax that per instruction:
| Flag | Allows |
|---|---|
reassoc | Reassociation, (a+b)+c to a+(b+c) |
nnan | Assume no NaN inputs or results |
ninf | Assume no infinities |
nsz | Ignore the sign of zero |
arcp | Use a * (1/b) for a / b |
contract | Fuse a*b + c into a fused multiply-add |
afn | Use approximate math library functions |
fast | All of the above |
%s = fadd fast float %a, %b ; illustrative, from -ffast-math
These flags live in FastMathFlags and are reached through FPMathOperator.
Sources: llvm/include/llvm/IR/FMF.h:23-33, llvm/include/llvm/IR/Operator.h:202
Casts
A cast is written %r = <cast> <srcty> %v to <dstty>.
| Cast | From | To | Example C source |
|---|---|---|---|
trunc | wider integer | narrower integer | (char)i |
zext | narrower integer | wider, filling with zeros | (unsigned long)u |
sext | narrower integer | wider, copying the sign bit | (long)i |
fptrunc, fpext | float type | smaller / larger float type | (float)d, (double)f |
fptoui, fptosi | float | integer | (int)f |
uitofp, sitofp | integer | float | (double)i |
ptrtoint, inttoptr | pointer / integer | integer / pointer | (uintptr_t)p |
ptrtoaddr | pointer | integer address only | (new in this LLVM version) |
bitcast | any | same size, reinterpret the bits | memcpy type punning |
addrspacecast | pointer | pointer in another address space | GPU code |
; illustrative: long f(char c) { return c; }
%w = sext i8 %c to i64
zext can carry nneg (the input is non-negative) and trunc can carry nuw/nsw (no bits lost); breaking these promises gives poison.
All casts derive from CastInst.
Sources: llvm/include/llvm/IR/Instruction.def:184-199, llvm/include/llvm/IR/InstrTypes.h:512
Key Points
- Binary operators require matching operand and result types; signedness is in the opcode.
nsw,nuwandexactare promises; breaking one gives poison, not a wrong number.- Fast-math flags are per instruction, so one function can mix strict and fast code.
Compare and Select
Relevant source files
The following files were used as context for generating this wiki page:
Comparisons produce an i1 (true or false). icmp compares integers and pointers, fcmp compares floating-point values, and select picks one of two values based on an i1. Together they express every if, ?:, min and max in a program.
Purpose and Scope
This page covers icmp and its ten predicates, fcmp and its sixteen predicates (including what "ordered" means), and select. Using an i1 to branch is on Control Flow.
icmp
The form is %c = icmp <pred> <type> %a, %b. Because integers carry no sign (see Type System), the predicate says whether to compare as signed or unsigned:
| Predicate | Meaning | C example (int a, b) |
C example (unsigned a, b) |
|---|---|---|---|
eq | equal | a == b | a == b |
ne | not equal | a != b | a != b |
sgt / ugt | greater than | a > b | a > b |
sge / uge | greater or equal | a >= b | a >= b |
slt / ult | less than | a < b | a < b |
sle / ule | less or equal | a <= b | a <= b |
; illustrative: int is_neg(int x) { return x < 0; }
%c = icmp slt i32 %x, 0
%r = zext i1 %c to i32
ret i32 %r
The same bits give different answers: for %x = -1 (all ones), icmp slt i32 %x, 0 is true but icmp ult i32 %x, 0 is false, because unsigned all-ones is the largest value.
icmp also works on vectors, giving a vector of i1, and on ptr, comparing addresses.
In C++ the predicates are the CmpInst::Predicate enum; ICMP_EQ is 32 through ICMP_SLE at 41.
Sources: llvm/include/llvm/IR/InstrTypes.h:728, llvm/include/llvm/IR/InstrTypes.h:761-773, llvm/include/llvm/IR/Instructions.h:1262
fcmp and NaN
Floating-point comparison has a complication: NaN (not a number) is unordered, it is neither less than, equal to nor greater than anything, including itself. Every fcmp predicate therefore states what to return when either operand is NaN:
- Ordered predicates (
oprefix) return false if either operand is NaN. - Unordered predicates (
uprefix) return true if either operand is NaN.
| Ordered | Unordered | Relation |
|---|---|---|
oeq | ueq | equal |
one | une | not equal |
ogt | ugt | greater than |
oge | uge | greater or equal |
olt | ult | less than |
ole | ule | less or equal |
ord | uno | "neither is NaN" / "at least one is NaN" |
false | true | always false / always true |
C's a == b on doubles is fcmp oeq; C's a != b is fcmp une, because NaN != NaN is true in C. isnan(x) can be written fcmp uno double %x, %x.
The enum comment in InstrTypes.h shows the encoding: four bits U, L, G, E (unordered, less, greater, equal), and each predicate is the set of outcomes for which it is true. For example FCMP_OEQ = 1 is just E and FCMP_UNO = 8 is just U.
Sources: llvm/include/llvm/IR/InstrTypes.h:740-760, llvm/include/llvm/IR/Instructions.h:1495
select
%r = select i1 %c, <type> %t, <type> %f is c ? t : f without a branch. Both %t and %f are already computed; select only chooses.
; illustrative: int max(int a, int b) { return a > b ? a : b; }
define i32 @max(i32 %a, i32 %b) {
entry:
%gt = icmp sgt i32 %a, %b
%r = select i1 %gt, i32 %a, i32 %b
ret i32 %r
}
The optimizer turns small if/else diamonds into select when both sides are cheap and safe to compute (simplifycfg does this, see Common Passes), because a select avoids a branch that may be mispredicted. The back end can lower select to a conditional move such as AArch64 csel.
A vector select takes a vector of i1 and picks per lane. Recognised select shapes such as min/max are often rewritten to intrinsics such as llvm.smax.i32.
Sources: llvm/include/llvm/IR/Instructions.h:1776, llvm/include/llvm/IR/Instruction.def:207-212
Key Points
icmppredicates pick signed or unsigned;fcmppredicates pick what NaN means.- Results are
i1; usezextto turn one into a Cint. selectchooses between two already computed values without branching.
Memory: alloca, load, store and getelementptr
Relevant source files
The following files were used as context for generating this wiki page:
SSA values live in unlimited virtual registers, but programs also need memory: stack variables, globals, the heap and anything reached through a pointer. LLVM IR touches memory only through a few explicit instructions. alloca reserves stack space, load reads, store writes, and getelementptr computes addresses without touching memory at all.
Purpose and Scope
This page covers alloca, load, store, getelementptr (with worked offset calculations), and gives a short introduction to atomics and fences. How mem2reg removes most allocas is on SSA and Phi.
The Memory Instructions
| Opcode | C++ class | Purpose |
|---|---|---|
alloca | AllocaInst | Reserve space in the current function's stack frame |
load | LoadInst | Read a value of a stated type from an address |
store | StoreInst | Write a value to an address |
getelementptr | GetElementPtrInst | Compute an address from a base pointer and indices |
fence | FenceInst | Order memory operations between threads |
cmpxchg | AtomicCmpXchgInst | Atomic compare and exchange |
atomicrmw | AtomicRMWInst | Atomic read-modify-write (add, xchg, max, ...) |
Sources: llvm/include/llvm/IR/Instruction.def:171-179
alloca
%x = alloca i32, align 4 ; illustrative: int x;
%buf = alloca [16 x i8], align 1 ; char buf[16];
alloca returns a ptr to fresh stack memory that is freed automatically when the function returns. The memory starts uninitialised. Clang puts every local variable, and every parameter, in an alloca in the entry block, because that is easy to generate; mem2reg later turns most of them into SSA values.
Sources: llvm/include/llvm/IR/Instructions.h:65
load and store
; illustrative: x = x + 1;
%old = load i32, ptr %x, align 4
%new = add nsw i32 %old, 1
store i32 %new, ptr %x, align 4
load <type>, ptr <addr>reads. Because pointers are opaque, the type is written on the instruction.store <type> <value>, ptr <addr>writes. The value comes first, then the address.storeproduces no value.align Npromises that the address is a multiple of N. Lying about alignment is undefined behaviour.volatile(load volatile i32, ...) forbids the optimizer from removing or merging the access, for memory-mapped hardware.
Sources: llvm/include/llvm/IR/Instructions.h:197, llvm/include/llvm/IR/Instructions.h:338
getelementptr
getelementptr (GEP) computes base + offset, where the offset comes from walking a type with a list of indices. It never reads memory; it only does arithmetic. Its form is:
%p = getelementptr [inbounds] <source element type>, ptr %base, <idx0>, <idx1>, ...
The rules:
- The first index steps over whole copies of the source element type, as in C pointer arithmetic
base + idx0. - Each later index steps into the current type: an array index picks an element, a struct index (always a constant
i32) picks a field.
Worked Examples
These assume the AArch64 data layout: i32 is 4 bytes, ptr and i64 are 8 bytes, aligned to their size.
Array element. int a[10]; ... &a[i]
; illustrative
@a = global [10 x i32] zeroinitializer
%p = getelementptr inbounds [10 x i32], ptr @a, i64 0, i64 %i
Index 0 steps over 0 whole arrays, index %i picks element i: offset = 0 * 40 + i * 4.
The same address can be written with a simpler source type, and newer Clang usually emits this form:
%p = getelementptr inbounds i32, ptr @a, i64 %i ; offset = i * 4
Struct field. struct Point { int x; int y; }; ... &pts[1].y
; illustrative
%struct.Point = type { i32, i32 }
%q = getelementptr inbounds %struct.Point, ptr %pts, i64 1, i32 1
Index 1 steps over one whole Point (8 bytes); field index 1 picks y at offset 4 within it. Total offset 12.
Struct with padding. struct Node { int v; struct Node *next; }; ... &n->next
; illustrative
%struct.Node = type { i32, ptr }
%nx = getelementptr inbounds %struct.Node, ptr %n, i64 0, i32 1
ptr is 8-byte aligned, so there are 4 padding bytes after v and next is at offset 8, not 4. The data layout decides this, not the GEP.
| Example | Indices | Offset in bytes |
|---|---|---|
&a[i] | 0, %i on [10 x i32] | 4*i |
&pts[1].y | 1, 1 on {i32, i32} | 8 + 4 = 12 |
&n->next | 0, 1 on {i32, ptr} | 8 |
inbounds
inbounds promises that the base and the result point into the same allocated object (or one past its end). If that is false the result is poison. It lets alias analysis assume that &a[i] cannot point into some other variable.
A common beginner mistake is to think GEP dereferences a pointer. p->next->v needs two GEPs with a load between them, because following next reads memory:
; illustrative: p->next->v
%nextaddr = getelementptr inbounds %struct.Node, ptr %p, i64 0, i32 1
%next = load ptr, ptr %nextaddr, align 8
%vaddr = getelementptr inbounds %struct.Node, ptr %next, i64 0, i32 0
%v = load i32, ptr %vaddr, align 4
Sources: llvm/include/llvm/IR/Instructions.h:1034
Atomics, Briefly
For multi-threaded code, loads and stores can be atomic with an ordering, and there are three extra instructions:
; illustrative
%v = load atomic i32, ptr %p acquire, align 4
store atomic i32 1, ptr %p release, align 4
%old = atomicrmw add ptr %counter, i32 1 seq_cst
%pair = cmpxchg ptr %p, i32 %expected, i32 %new seq_cst seq_cst
fence seq_cst
The orderings (monotonic, acquire, release, acq_rel, seq_cst) follow the C++11 memory model. cmpxchg returns a { i32, i1 } struct: the old value and whether the exchange happened. Most optimizations leave atomics alone.
Key Points
- Only
load,store, atomics and calls touch memory;getelementptris pure arithmetic. - The first GEP index steps over whole objects; later indices step into arrays and structs.
- Clang emits an
allocaper local variable;mem2regremoves most of them.
Control Flow: br, switch, ret and call
Relevant source files
The following files were used as context for generating this wiki page:
Inside a basic block, instructions run top to bottom. Between blocks, control moves only through the terminator at the end of each block. A terminator either jumps to other blocks (br, switch), leaves the function (ret), or states that control can never reach that point (unreachable). call is not a terminator: execution comes back to the next instruction after the call.
Purpose and Scope
This page covers ret, unconditional and conditional br, switch, unreachable and call, and gives a short introduction to invoke and exceptions. How terminators form a graph is on CFG and Loops.
The Terminators
Instruction.def lists the terminators first, in lines 126-139:
| Opcode (text) | C++ class | Successors | Purpose |
|---|---|---|---|
ret | ReturnInst | none | Return from the function |
br label %d | UncondBrInst | 1 | Unconditional jump |
br i1 %c, label %t, label %f | CondBrInst | 2 | Two-way conditional jump |
switch | SwitchInst | many | Multi-way jump on an integer |
indirectbr | IndirectBrInst | many | Jump to a computed block address |
invoke | InvokeInst | 2 | Call that may throw |
resume, cleanupret, catchret, catchswitch | ... | Exception handling | |
unreachable | UnreachableInst | none | Control never gets here |
callbr | CallBrInst | many | asm goto |
> Version note. Older LLVM releases, and most tutorials, use a single BranchInst class for both kinds of br. In this checkout it is split into UncondBrInst and CondBrInst. The text syntax is unchanged: the parser reads br and creates one class or the other depending on whether a condition is present.
Sources: llvm/include/llvm/IR/Instruction.def:126-139, llvm/lib/AsmParser/LLParser.cpp:8050-8071
ret
ret i32 %v ; illustrative: return a value
ret void ; return from a void function
The type must match the function's return type. A function may contain several ret instructions, one in each exit block.
Sources: llvm/include/llvm/IR/Instructions.h:3065
br
; illustrative: int abs(int x) { if (x < 0) x = -x; return x; }
define i32 @abs(i32 %x) {
entry:
%neg = icmp slt i32 %x, 0
br i1 %neg, label %then, label %done ; conditional: CondBrInst
then:
%nx = sub nsw i32 0, %x
br label %done ; unconditional: UncondBrInst
done:
%r = phi i32 [ %nx, %then ], [ %x, %entry ]
ret i32 %r
}
- The condition of a conditional
brmust be ani1, usually fromicmporfcmp. - Targets are written
label %name. A label is aBasicBlockvalue used as an operand. - If the condition is poison, the behaviour is undefined (see Arithmetic).
- The
phiindonechooses%xor%nxdepending on which block came before; this is explained on SSA and Phi.
Sources: llvm/include/llvm/IR/Instructions.h:3151, llvm/include/llvm/IR/Instructions.h:3217
switch
; illustrative: switch (op) { case 0: ...; case 1: ...; default: ... }
switch i32 %op, label %default [
i32 0, label %case0
i32 1, label %case1
]
A switch names a default target, then a list of constant values and their targets. The back end lowers it to a jump table, a binary search of compares, or a bit test, whichever is cheaper. simplifycfg may turn a short chain of icmp/br into a switch, or the reverse.
Sources: llvm/include/llvm/IR/Instructions.h:3296
unreachable
unreachable says that execution can never get here. Clang emits it after a call to a noreturn function such as abort(), and at the end of a non-void function that falls off its end. Optimizers treat reaching it as undefined behaviour, so they may delete any code path that must lead to it.
call void @abort() ; illustrative
unreachable
Sources: llvm/include/llvm/IR/Instructions.h:4662
call
; illustrative
%r = call i32 @add(i32 %a, i32 %b)
call void @free(ptr %p)
%r2 = tail call i32 %fnptr(i32 1) ; indirect call through a pointer
%m = call i32 @llvm.smax.i32(i32 %a, i32 %b) ; an intrinsic
- The callee is a
ptr: either a function name (direct call) or any pointer value (indirect call). - The function type is written on the call, so with opaque pointers the call itself states the parameter types.
tailis a hint that the call can reuse the caller's stack frame;musttailmakes that required.- Functions whose names start with
llvm.are intrinsics: built-in operations such asllvm.memcpy,llvm.smaxorllvm.dbg.valuethat passes and back ends understand directly.
How a call becomes argument registers and a branch-and-link instruction is covered by the Calling Conventions wiki.
Sources: llvm/include/llvm/IR/Instructions.h:1597, llvm/include/llvm/IR/Instruction.def:211
invoke and landingpad, Briefly
In C++, a call that may throw must say where to go if it does. invoke is a call that is also a terminator with two successors:
; illustrative
%r = invoke i32 @may_throw()
to label %ok unwind label %lpad
ok:
ret i32 %r
lpad:
%ex = landingpad { ptr, i32 } cleanup
; run destructors, then:
resume { ptr, i32 } %ex
}
On a normal return control goes to %ok. If an exception is thrown it goes to %lpad, whose first instruction must be a landingpad. A plain call inside a function compiled with exceptions enabled is allowed only if the callee is nounwind, or if an exception may simply propagate out of the caller.
Key Points
- Every block ends in exactly one terminator, and only terminators move control between blocks.
- In this checkout
bris two classes,UncondBrInstandCondBrInst; the text form is stillbr. callreturns to the next instruction;invokeis a call that is also a terminator.
SSA and 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.
Purpose and Scope
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.
The SSA Rule
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 %x2
Because 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.
Why phi Is Needed
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
phi Rules
| 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.
Clang Does Not Emit SSA for Variables
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.
Before mem2reg
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
}
After opt -S -passes=mem2reg
(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
How mem2reg Works
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 Example
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.
Key Points
- 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.
Control Flow Graph and Loops
Relevant source files
The following files were used as context for generating this wiki page:
The control flow graph (CFG) of a function has one node per basic block and one edge for each way a terminator can jump. LLVM does not store the CFG as a separate data structure: successors are read from the terminator's operands, and predecessors are found by walking the block's use list. Loops are found from the CFG by the LoopInfo analysis.
Purpose and Scope
This page covers predecessors and successors, the entry and exit blocks, critical edges, and natural loops with their header, preheader, latch and exits. The dominance theory that loop detection relies on is on Dominance.
Successors and Predecessors
| Query | How LLVM answers it | Cost |
|---|---|---|
successors(BB) | The block operands of BB's terminator | Constant per successor |
predecessors(BB) | Users of BB (as a Value) that are terminators | Walks the use list |
pred_empty(BB) | No predecessors (entry block, or unreachable) | |
BB->getSinglePredecessor() | The one predecessor, or null |
// Illustrative: print the CFG edges of a function.
for (BasicBlock &BB : F)
for (BasicBlock *Succ : successors(&BB))
errs() << BB.getName() << " -> " << Succ->getName() << "\n";
Because a block is a Value and every branch uses it as an operand, the predecessor list is just the block's use list filtered to terminators. That is why pred_begin is an iterator over uses.
Sources: llvm/include/llvm/IR/CFG.h:99-119, llvm/include/llvm/IR/CFG.h:147, llvm/include/llvm/IR/CFG.h:170
A Worked CFG
Using @sum from SSA and Phi:
flowchart TD
E["entry"] --> C["for.cond<br/>(phis, icmp, br)"]
C -->|true| B["for.body"]
C -->|false| X["for.end<br/>ret"]
B -->|back edge| C
| Block | Predecessors | Successors |
|---|---|---|
entry | none | for.cond |
for.cond | entry, for.body | for.body, for.end |
for.body | for.cond | for.cond |
for.end | for.cond | none (returns) |
opt -passes=dot-cfg in.ll writes one Graphviz .dot file per function (.sum.dot here), which dot -Tpng turns into a picture. The pass is registered as FUNCTION_PASS("dot-cfg", CFGPrinterPass()).
Sources: llvm/lib/Passes/PassRegistry.def:436
Unreachable Blocks
A block with no path from the entry block is unreachable. It is valid IR, but analyses such as the dominator tree treat it specially and most passes skip it. simplifycfg deletes such blocks.
Critical Edges
An edge A → B is critical if A has more than one successor and B has more than one predecessor. In the diamond below, the edge entry → join is critical:
flowchart TD
E["entry: br %c, %then, %join"] --> T["then"]
E -->|critical| J["join"]
T --> J
There is nowhere to put code that should run only on that edge: putting it at the end of entry also runs it on the way to then, and putting it at the start of join also runs it when coming from then. Passes that need to insert code on edges, such as PHI elimination or partial redundancy elimination, split the edge by inserting a new empty block between A and B. isCriticalEdge(TI, SuccNum) tests an edge, and SplitCriticalEdge in BasicBlockUtils splits it.
Sources: llvm/lib/Analysis/CFG.cpp:106-112
Natural Loops
A back edge is an edge whose target dominates its source (the target is always reached before the source). Each back edge defines a natural loop: the target is the loop header, and the loop body is every block that can reach the back edge's source without going through the header.
| Part | Definition | In @sum |
|---|---|---|
| Header | The single entry block of the loop; dominates every block in it | for.cond |
| Latch | A block with a back edge to the header | for.body |
| Preheader | The single block outside the loop that branches to the header, and only to it | entry |
| Exiting block | A loop block with a successor outside the loop | for.cond |
| Exit block | A block outside the loop reached from an exiting block | for.end |
Loops nest: an inner loop's blocks are a subset of the outer loop's. LoopInfo builds a forest of Loop objects, each with its blocks and its sub-loops. The accessors are on LoopBase: getHeader() returns the first block, getLoopPreheader() and getLoopLatch() return null if there is no unique one.
Many loop passes need a preheader (a place to hoist code into) and a single latch. The loop-simplify pass creates them, which is why it runs before licm and other loop passes.
Sources: llvm/include/llvm/Support/GenericLoopInfo.h:59, llvm/include/llvm/Support/GenericLoopInfo.h:105, llvm/include/llvm/Support/GenericLoopInfo.h:310-320, llvm/include/llvm/Analysis/LoopInfo.h:40, llvm/include/llvm/Analysis/LoopInfo.h:433
Printing Loops
opt -disable-output -passes='print<loops>' sum.ll prints the loop forest. For @sum the output has this shape (illustrative):
Loop info for function 'sum':
Loop at depth 1 containing: %for.cond<header><exiting>,%for.body<latch>
The printer is LoopPrinterPass, registered as print<loops>; the analysis it prints is LoopAnalysis.
Sources: llvm/include/llvm/Analysis/LoopInfo.h:594-605, llvm/lib/Passes/PassRegistry.def:526
Key Points
- The CFG is implicit: successors come from terminators, predecessors from use lists.
- A critical edge goes from a multi-successor block to a multi-predecessor block; split it to insert code on it.
- A natural loop has one header;
loop-simplifygives it a preheader and a single latch.
Dominance, Dominator Tree and Dominance Frontier
Relevant source files
The following files were used as context for generating this wiki page:
Block A dominates block B if every path from the entry block to B passes through A. Dominance answers "is this value guaranteed to have been computed here?", which is what SSA, loop detection, code motion and phi placement all need. LLVM computes it once per function as a dominator tree and keeps it up to date as passes change the CFG.
Purpose and Scope
This page defines dominance, immediate dominators, the dominator tree, the dominance frontier and post-dominance, works through an example, and shows the LLVM classes and printer passes. Use of these in mem2reg is on SSA and Phi.
Definitions
| Term | Definition |
|---|---|
| A dominates B | Every path from entry to B goes through A. Every block dominates itself. |
| A strictly (properly) dominates B | A dominates B and A ≠ B |
| Immediate dominator idom(B) | The strict dominator of B closest to B. Every block except entry has exactly one. |
| Dominator tree | Tree with an edge idom(B) → B for every B. The entry block is the root. |
| Dominance frontier DF(A) | Blocks B such that A dominates a predecessor of B but does not strictly dominate B: where A's dominance "ends" |
| A post-dominates B | Every path from B to a function exit goes through A |
A Worked Example
(illustrative CFG)
flowchart TD
E["entry"] --> A["A"]
A --> B["B"]
A --> C["C"]
B --> D["D"]
C --> D
D --> A
D --> X["exit"]
| Block | Dominators | idom | Dominance frontier |
|---|---|---|---|
| entry | entry | none | {} |
| A | entry, A | entry | {A} (via the back edge from D) |
| B | entry, A, B | A | {D} |
| C | entry, A, C | A | {D} |
| D | entry, A, D | A | {A} |
| exit | entry, A, D, exit | D | {} |
Neither B nor C dominates D, because D can be reached through the other one. So D's idom is A. The dominator tree is:
flowchart TD
E["entry"] --> A["A"]
A --> B["B"]
A --> C["C"]
A --> D["D"]
D --> X["exit"]
Reading the frontier: a variable assigned in B needs a phi in D, where B's value meets C's. A variable assigned in D needs a phi in A, where the value from the previous iteration meets the value from entry. That is exactly the rule mem2reg uses, with the frontier iterated because each new phi is itself a definition.
Since D → A goes to a block that dominates its source, it is a back edge, and A is a loop header; see CFG and Loops.
The Dominator Tree in LLVM
DominatorTree is a DominatorTreeBase<BasicBlock, false> (the false means "not post-dominators"). Each node is a DomTreeNode with getIDom() and its children. The main queries:
| Call | Answers |
|---|---|
DT.dominates(A, B) on blocks | Does block A dominate block B |
DT.dominates(Def, UseInst) | Is Def available at instruction UseInst (handles instructions in the same block by order) |
DT.dominates(Def, U) on a Use | Is Def available at this use; for a phi use, checks the end of the incoming block |
DT.properlyDominates(A, B) | Strict dominance |
DT.getNode(BB)->getIDom() | Immediate dominator |
DT.findNearestCommonDominator(A, B) | Lowest block dominating both |
A pass obtains it from the analysis manager:
// Illustrative
DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
if (DT.dominates(Def, UserInst)) { /* safe to use Def here */ }
LLVM builds the tree with the Semi-NCA algorithm and can update it incrementally (DomTreeUpdater) when a pass adds or removes edges, rather than recomputing.
Sources: llvm/include/llvm/IR/Dominators.h:122, llvm/include/llvm/IR/Dominators.h:140-175, llvm/include/llvm/IR/Dominators.h:241, llvm/include/llvm/Support/GenericDomTree.h:112, llvm/include/llvm/Support/GenericDomTree.h:440-449
Printing the Tree
opt -disable-output -passes='print<domtree>' example.ll
The output lists the tree with indentation by depth and DFS numbers in braces. For the example above it has this shape (illustrative):
DominatorTree for function: example
=============================--------------------------------
Inorder Dominator Tree: DFSNumbers invalid: 0 slow queries.
[1] %entry {4294967295,4294967295} [0]
[2] %A {4294967295,4294967295} [1]
[3] %B {4294967295,4294967295} [2]
[3] %C {4294967295,4294967295} [2]
[3] %D {4294967295,4294967295} [2]
[4] %exit {4294967295,4294967295} [3]
Roots: %entry
The number in the first brackets is the depth. print<postdomtree> prints the post-dominator tree the same way.
Sources: llvm/include/llvm/IR/Dominators.h:254, llvm/lib/Passes/PassRegistry.def:522, llvm/lib/Passes/PassRegistry.def:530
Dominance Frontier
DominanceFrontier stores DF(B) for every block. Most passes do not need the full table: mem2reg and SSA updating use IDFCalculator, which computes the iterated frontier of a set of blocks directly from the dominator tree (see SSA and Phi).
Sources: llvm/include/llvm/Analysis/DominanceFrontier.h:43, llvm/include/llvm/Analysis/DominanceFrontier.h:94, llvm/include/llvm/Analysis/DominanceFrontier.h:134
Post-Dominance
Post-dominance is dominance on the reversed CFG, with the function exits as roots. In the example, D post-dominates B and C (both must pass through D to exit), and exit post-dominates everything.
It answers "if B runs, is A certain to run afterwards?". Uses include:
- Control dependence: B is control dependent on a branch if B post-dominates one successor of the branch but not the branch itself. Aggressive dead code elimination (
adce) uses this to delete branches whose outcome does not matter. - Sinking code to a point that is executed whenever the original was.
PostDominatorTree and PostDominatorTreeAnalysis are in PostDominators.h.
Sources: llvm/include/llvm/Analysis/PostDominators.h:29, llvm/include/llvm/Analysis/PostDominators.h:48-64
Key Points
- A dominates B if every entry-to-B path goes through A; idom links form the dominator tree.
- The dominance frontier is where a block's dominance ends;
phis go at the iterated frontier of definitions. - Post-dominance is dominance on the reversed CFG and gives control dependence.
Data-flow Analysis
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.
Purpose and Scope
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.
The Framework
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.
The Three Classic Analyses
| 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.
Worked Example: Liveness
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.
The Worklist Algorithm
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.
A Real Worklist in LLVM
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
What SSA Changes
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
Key Points
- 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.
Writing an IR Pass
Relevant source files
The following files were used as context for generating this wiki page:
A pass is a C++ class with a run method that the pass manager calls on a module, function or loop. LLVM's current ("new") pass manager has no base class with virtual methods: a pass is any type with the right run signature, plus a mixin that supplies its name. This page builds three passes: a function pass that counts instructions, an analysis that other passes can query, and a small peephole transformation. It then loads them into opt as a plugin.
> All C++ on this page is illustrative: written against the headers at commit a2171756 but not compiled or run for this wiki, because the local build had no opt.
Purpose and Scope
This page covers the pass interface (run, PreservedAnalyses, the info mixins), analyses and the analysis manager, registering passes through a plugin, and running them with opt -load-pass-plugin. Passes already in LLVM are described on Common Passes.
The Smallest Pass: HelloWorld
LLVM ships a minimal pass. The header declares it:
class HelloWorldPass : public OptionalPassInfoMixin<HelloWorldPass> {
public:
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
};
and the implementation prints the function name and changes nothing:
PreservedAnalyses HelloWorldPass::run(Function &F,
FunctionAnalysisManager &AM) {
errs() << F.getName() << "\n";
return PreservedAnalyses::all();
}
It is built into opt and registered as helloworld, so opt -disable-output -passes=helloworld in.ll prints every function name.
Sources: llvm/include/llvm/Transforms/Utils/HelloWorld.h:16-19, llvm/lib/Transforms/Utils/HelloWorld.cpp:14-18, llvm/lib/Passes/PassRegistry.def:456
The Pass Interface
| Piece | Meaning |
|---|---|
run(IRUnit &, AnalysisManager &) | Called once per unit: Module, Function, Loop or call-graph SCC |
PreservedAnalyses return value | Tells the manager which cached analyses are still valid. all() if nothing changed, none() if you are unsure |
OptionalPassInfoMixin<T> | Supplies name(). The pass may be skipped, for example for optnone functions |
RequiredPassInfoMixin<T> | Same, but the pass always runs (verifiers, printers) |
AnalysisInfoMixin<T> | For analyses; also supplies the unique Key |
PassManager.h notes that real passes should inherit from RequiredPassInfoMixin or OptionalPassInfoMixin rather than PassInfoMixin directly.
Returning the wrong PreservedAnalyses is the most common bug: if a pass changes the CFG but claims everything is preserved, later passes will use a stale dominator tree.
Sources: llvm/include/llvm/IR/PassManager.h:75-90, llvm/include/llvm/IR/PassManager.h:117
Pass 1: Count Instructions
// CountInsts.cpp (illustrative)
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
struct CountInstsPass : OptionalPassInfoMixin<CountInstsPass> {
PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
unsigned N = 0, Loads = 0;
for (Instruction &I : instructions(F)) {
++N;
if (isa<LoadInst>(I)) ++Loads;
}
errs() << F.getName() << ": " << N << " instructions, "
<< Loads << " loads\n";
return PreservedAnalyses::all(); // read-only
}
};
} // namespace
instructions(F) iterates over every instruction in every block. isa<>, dyn_cast<> and cast<> are LLVM's type tests for the Value hierarchy.
Pass 2: An Analysis
An analysis computes a result that the manager caches until a pass invalidates it.
// illustrative
struct BlockCountAnalysis : AnalysisInfoMixin<BlockCountAnalysis> {
using Result = unsigned;
Result run(Function &F, FunctionAnalysisManager &) { return F.size(); }
private:
friend AnalysisInfoMixin<BlockCountAnalysis>;
static AnalysisKey Key;
};
AnalysisKey BlockCountAnalysis::Key;
// A pass that uses it, and the dominator tree:
struct ReportPass : OptionalPassInfoMixin<ReportPass> {
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM) {
unsigned Blocks = AM.getResult<BlockCountAnalysis>(F);
DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
errs() << F.getName() << ": " << Blocks << " blocks, root "
<< DT.getRoot()->getName() << "\n";
return PreservedAnalyses::all();
}
};
AM.getResult<X>(F) runs X if no valid result is cached. AM.getCachedResult<X>(F) returns null instead of computing.
Pass 3: A Peephole Transformation
This pass rewrites x * 2^k into x << k, an instcombine-style rewrite.
// illustrative
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/IRBuilder.h"
using namespace llvm::PatternMatch;
struct MulToShiftPass : OptionalPassInfoMixin<MulToShiftPass> {
PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
bool Changed = false;
for (Instruction &I : make_early_inc_range(instructions(F))) {
Value *X; const APInt *C;
if (!match(&I, m_Mul(m_Value(X), m_APInt(C))) || !C->isPowerOf2())
continue;
IRBuilder<> B(&I);
Value *Shl = B.CreateShl(X, C->logBase2(), I.getName());
I.replaceAllUsesWith(Shl);
I.eraseFromParent();
Changed = true;
}
if (!Changed) return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>(); // no blocks or edges changed
return PA;
}
};
Points to notice:
make_early_inc_rangelets the loop erase the current instruction safely.match(..., m_Mul(m_Value(X), m_APInt(C)))is thePatternMatchlibrary, whichinstcombineuses throughout.IRBuilderinserts new instructions before&I.replaceAllUsesWiththeneraseFromParentis the standard replace-and-delete pattern.- The CFG is unchanged, so CFG analyses such as the dominator tree are preserved. The pass drops
nsw/nuwbecause it does not copy them, which is always safe.
Before and after (illustrative):
%y = mul i32 %x, 8 ; before
%y = shl i32 %x, 3 ; after
Registering as a Plugin
A plugin is a shared library exporting llvmGetPassPluginInfo, which returns a PassPluginLibraryInfo: an API version, a name, a version string and a callback that registers passes with the PassBuilder.
// illustrative
#include "llvm/Plugins/PassPlugin.h"
#include "llvm/Passes/PassBuilder.h"
extern "C" LLVM_ATTRIBUTE_WEAK ::llvm::PassPluginLibraryInfo
llvmGetPassPluginInfo() {
return {LLVM_PLUGIN_API_VERSION, "IRWikiPasses", "v0.1",
[](PassBuilder &PB) {
PB.registerAnalysisRegistrationCallback(
[](FunctionAnalysisManager &FAM) {
FAM.registerPass([] { return BlockCountAnalysis(); });
});
PB.registerPipelineParsingCallback(
[](StringRef Name, FunctionPassManager &FPM,
ArrayRef<PassBuilder::PipelineElement>) {
if (Name == "count-insts") { FPM.addPass(CountInstsPass()); return true; }
if (Name == "report") { FPM.addPass(ReportPass()); return true; }
if (Name == "mul-to-shift"){ FPM.addPass(MulToShiftPass()); return true; }
return false;
});
}};
}
In this checkout the header is llvm/Plugins/PassPlugin.h; older tutorials use llvm/Passes/PassPlugin.h. LLVM_PLUGIN_API_VERSION is 2 here.
Sources: llvm/include/llvm/Plugins/PassPlugin.h:36, llvm/include/llvm/Plugins/PassPlugin.h:45-56, llvm/include/llvm/Plugins/PassPlugin.h:125-138, llvm/include/llvm/Passes/PassBuilder.h:586-610
Building and Running
A minimal out-of-tree CMake file (illustrative):
cmake_minimum_required(VERSION 3.20)
project(IRWikiPasses)
find_package(LLVM REQUIRED CONFIG)
include_directories(${LLVM_INCLUDE_DIRS})
add_definitions(${LLVM_DEFINITIONS})
add_library(IRWikiPasses MODULE CountInsts.cpp)
Then:
opt -load-pass-plugin=./libIRWikiPasses.so -disable-output -passes=count-insts in.ll
opt -load-pass-plugin=./libIRWikiPasses.so -S -passes='mem2reg,mul-to-shift' in.ll
On Windows, plugins need an LLVM built with plugin support (LLVM_ENABLE_PLUGINS) and the .dll must link against the same LLVM. If that is not available, an alternative is to add the pass to LLVM itself: put it in lib/Transforms/Utils/, add a FUNCTION_PASS("count-insts", CountInstsPass()) line to PassRegistry.def next to helloworld, and rebuild opt.
Always run -passes='your-pass,verify' while developing: the verifier catches broken SSA, missing terminators and type errors right after your pass.
Key Points
- A pass is a class with
run(Unit&, AnalysisManager&)returningPreservedAnalyses. - Analyses use
AnalysisInfoMixinand a staticAnalysisKey, and are fetched withAM.getResult<>. - A plugin exports
llvmGetPassPluginInfoand registers names withregisterPipelineParsingCallback.
Common Passes
Relevant source files
The following files were used as context for generating this wiki page:
A handful of passes do most of the work in every optimization pipeline. Each is simple to describe in terms of the ideas from earlier pages: mem2reg builds SSA, instcombine rewrites instruction patterns, simplifycfg cleans up the CFG, gvn removes redundant computations, licm moves work out of loops, and dce deletes unused code. This page shows what each one does with a small before/after example.
> All before/after IR on this page is illustrative, written by hand to show the typical effect of each pass. It was not produced by running opt.
Purpose and Scope
This page covers six passes, the analyses each relies on, and the source location of each run method. It is not a full description of any of them: instcombine alone has thousands of rewrite rules. Writing your own pass is on Writing a Pass.
Summary
| Pass name | What it does | Relies on | Entry point |
|---|---|---|---|
mem2reg | Promote allocas to SSA values, insert phis | Dominator tree | PromoteMemToReg |
instcombine | Local algebraic rewrites and canonicalisation | Known bits, simplify queries | InstCombinePass::run |
simplifycfg | Merge, remove and simplify blocks and branches | CFG only | SimplifyCFGPass::run |
gvn | Remove redundant computations and loads | Dominator tree, memory dependence, alias analysis | GVNPass::run |
licm | Hoist loop-invariant code out of loops, sink code below them | Loop info, dominator tree, MemorySSA | LICMPass::run |
dce / adce | Delete instructions whose results are unused | Use lists; adce also post-dominators | DCEPass::run |
Sources: llvm/lib/Passes/PassRegistry.def:410, llvm/lib/Passes/PassRegistry.def:432, llvm/lib/Passes/PassRegistry.def:491, llvm/lib/Passes/PassRegistry.def:609-621
mem2reg
Covered in detail on SSA and Phi.
; before ; after
%x = alloca i32 ;
store i32 %a, ptr %x ;
%v = load i32, ptr %x ;
%r = add i32 %v, 1 %r = add i32 %a, 1
In the standard -O pipelines its job is done by sroa, which also splits structs and arrays into separate scalars first.
Sources: llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:1259
instcombine
instcombine visits instructions one at a time and replaces each with a simpler or more canonical equivalent. It keeps a worklist: whenever it changes an instruction, that instruction's users go back on the list, and it runs until the worklist is empty.
; before
%a = add i32 %x, 0 ; x + 0
%b = mul i32 %a, 8 ; x * 8
%c = sub i32 0, %b
%d = sub i32 %y, %c ; y - (0 - b)
; after
%b = shl i32 %x, 3
%d = add i32 %y, %b
Typical rules: identities (x+0, x*1, x&x), strength reduction (mul by a power of two to shl), constant folding, removing double negation, and putting constants on the right (add 1, %x becomes add %x, 1) so that other rules only need to match one form.
Canonicalisation matters as much as simplification: if every pass can rely on one shape for an idiom, each pass needs fewer patterns.
Sources: llvm/lib/Transforms/InstCombine/InstructionCombining.cpp:5777, llvm/lib/Transforms/InstCombine/InstructionCombining.cpp:6255
simplifycfg
simplifycfg cleans up the CFG: it deletes unreachable blocks, merges a block into its only predecessor, removes empty forwarding blocks, folds branches on constants, and turns small if/else diamonds into select.
Continuing the @pick example from SSA and Phi:
; before (after mem2reg)
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
; after
entry:
%tobool = icmp ne i32 %c, 0
%x.0 = select i1 %tobool, i32 1, i32 2
ret i32 %x.0
Three blocks and two branches became one block. instcombine might then simplify the select further.
Sources: llvm/lib/Transforms/Scalar/SimplifyCFGPass.cpp:378
gvn
Global value numbering gives every computed value a number such that two instructions get the same number when they are certain to compute the same result. If an instruction's number was already computed by an instruction that dominates it, the second one is replaced by the first.
; before
%a1 = add i32 %x, %y
%v1 = load i32, ptr %p
call void @use(i32 %a1, i32 %v1)
%a2 = add i32 %x, %y ; same as %a1
%v2 = load i32, ptr %p ; same as %v1 if nothing wrote *p in between
call void @use(i32 %a2, i32 %v2)
; after (assuming @use cannot write *p, e.g. it is memory(none))
%a1 = add i32 %x, %y
%v1 = load i32, ptr %p
call void @use(i32 %a1, i32 %v1)
call void @use(i32 %a1, i32 %v1)
The arithmetic part needs only SSA and dominance. The load part needs memory dependence and alias analysis: GVN must prove that no store or call in between could have changed *p. This is the "available expressions" idea from Data-flow Analysis, done sparsely on SSA values.
Sources: llvm/lib/Transforms/Scalar/GVN.cpp:892, llvm/lib/Transforms/Scalar/GVN.cpp:3315
licm
Loop-invariant code motion moves computations whose operands do not change inside a loop out to the loop's preheader (see CFG and Loops), so they run once instead of every iteration.
; before
loop:
%i = phi i64 [ 0, %entry ], [ %i.next, %loop ]
%scale = mul i64 %n, 4 ; %n is defined outside the loop
%off = add i64 %i, %scale
...
br i1 %done, label %exit, label %loop
; after
entry: ; the preheader
%scale = mul i64 %n, 4
br label %loop
loop:
%i = phi i64 [ 0, %entry ], [ %i.next, %loop ]
%off = add i64 %i, %scale
...
hoistRegion walks the loop's blocks in dominator-tree order and hoists an instruction when all its operands are defined outside the loop and moving it is safe: it must not trap (a division might, if the loop could run zero times) and, for loads, nothing in the loop may write that memory. sinkRegion does the reverse, moving code that is only needed after the loop into the exit blocks. LICM is a loop pass: LICMPass::run takes a Loop &.
Sources: llvm/lib/Transforms/Scalar/LICM.cpp:311, llvm/lib/Transforms/Scalar/LICM.cpp:567, llvm/lib/Transforms/Scalar/LICM.cpp:896
dce and adce
dce deletes instructions that have no uses and no side effects, using the worklist described on Data-flow Analysis:
; before
%a = add i32 %x, 1
%b = mul i32 %a, 2 ; %b is never used
ret i32 %x
; after
ret i32 %x
Deleting %b makes %a unused too, so it is deleted next. Stores and calls with side effects are kept even if they produce no used value.
adce (aggressive DCE) works the other way: it assumes everything is dead, marks as live only instructions with side effects and whatever they transitively use, and deletes the rest. With post-dominance (see Dominance) it can also delete branches whose outcome does not affect any live instruction, and so remove whole loops that compute nothing.
Sources: llvm/lib/Transforms/Scalar/DCE.cpp:89-110
How They Work Together
No single pass does much alone; each one creates opportunities for the others. A typical sequence on Clang output:
flowchart LR
S["sroa / mem2reg<br/>SSA from allocas"] --> I1["instcombine<br/>simplify"]
I1 --> C["simplifycfg<br/>clean CFG"]
C --> L["licm<br/>hoist from loops"]
L --> G["gvn<br/>remove redundancy"]
G --> I2["instcombine"]
I2 --> D["dce / adce"]
Try it on a file of your own:
opt -S -passes='mem2reg,instcombine,simplifycfg' in.ll
opt -S -passes='mem2reg,loop-simplify,licm,gvn,dce' in.ll
opt -S -O2 in.ll ; the full default pipeline
opt -S -O2 -print-after-all in.ll 2> trace.txt ; IR after every pass
Key Points
mem2regbuilds SSA;instcombineandsimplifycfgclean up locally and in the CFG.gvnremoves redundant values and loads;licmmoves invariant work to the preheader.dce/adceremove what other passes left unused; passes are run repeatedly because each enables the others.
Exercises, Tooling and Glossary
Relevant source files
The following files were used as context for generating this wiki page:
This page collects the command-line tools for working with IR, a set of exercises that follow the order of the wiki, and a glossary of the terms used on earlier pages.
Purpose and Scope
This page covers the IR tools (clang, opt, llvm-as, llvm-dis, llc, lli), the most useful opt options, exercises with hints, and a glossary. All command lines are illustrative; the expected results in the exercises were worked out by hand, not captured from a tool run.
Tools
| Tool | Input | Output | Typical use |
|---|---|---|---|
clang -S -emit-llvm | C/C++ | .ll | See what IR a C function becomes |
clang -c -emit-llvm | C/C++ | .bc | Bitcode for LTO or opt |
opt | .ll / .bc | .ll / .bc / analysis printouts | Run passes |
llvm-as | .ll | .bc | Assemble text to bitcode |
llvm-dis | .bc | .ll | Disassemble bitcode to text |
llc | .ll / .bc | .s / .o | Run the back end |
lli | .ll / .bc | program output | Execute IR directly with the JIT |
llvm-link | several .bc | one .bc | Merge modules |
Useful Commands
# Unoptimised IR, but still optimisable by opt (no optnone attribute):
clang -O0 -Xclang -disable-O0-optnone -S -emit-llvm f.c -o f.ll
# Optimised IR, without the names Clang would discard in release builds kept:
clang -O2 -S -emit-llvm -fno-discard-value-names f.c -o f.O2.ll
# Run single passes, check the result:
opt -S -passes='mem2reg,verify' f.ll -o f.m2r.ll
# Analyses:
opt -disable-output -passes='print<domtree>' f.m2r.ll
opt -disable-output -passes='print<postdomtree>' f.m2r.ll
opt -disable-output -passes='print<loops>' f.m2r.ll
opt -disable-output -passes=dot-cfg f.m2r.ll # writes .<fn>.dot files
# See what each pass in -O2 does:
opt -S -O2 -print-after-all f.ll 2> trace.txt
opt -S -O2 -print-changed f.ll 2> changes.txt # only passes that changed IR
opt -disable-output -O2 -debug-pass-manager f.ll # pass and analysis order
The names after -passes= come from PassRegistry.def, for example verify (line 564), dot-cfg (line 436) and the printers at lines 522-530.
Sources: llvm/lib/Passes/PassRegistry.def:436, llvm/lib/Passes/PassRegistry.def:522-530, llvm/lib/Passes/PassRegistry.def:564
Exercises
Each exercise names the page it practises.
- Read IR (Overview, Structure). Compile
int sq(int x) { return x * x; }with-O2 -S -emit-llvm. Identify the function definition, the block label, the terminator and every attribute group. Expected core:%mul = mul nsw i32 %x, %xthenret i32 %mul. - Signedness (Type System, Compare). Compile
int lt(int a, int b){return a<b;}and the same withunsigned. Whichicmppredicate changes? (Hint:sltvsult; nothing else changes.) - Flags (Arithmetic). Why does
int f(int x){return x+1 > x;}fold toreturn 1at-O2, but theunsignedversion does not? (Hint:nsw.) - GEP by hand (Memory). For
struct S { char c; int i; long l; }on AArch64, give the byte offsets ofc,i,l, and write the GEP for&s[2].l. (Answer: 0, 4, 8; size 16; offset 2*16+8 = 40;getelementptr inbounds %struct.S, ptr %s, i64 2, i32 2.) - Control flow (Control Flow). Compile a
switchwith four cases. Find theswitchinstruction and its default target. Then compile at-O2and see whether it stays aswitchor becomes a table lookup. - mem2reg (SSA and Phi). Take
max(a,b)written withif/elseand a local variable. Runopt -passes=mem2regand find thephi. Then addsimplifycfgand confirm it becomes aselect. - Escaping alloca (SSA and Phi). Add
foo(&x);to exercise 6. Why doesmem2regnow leavexin memory? (Hint:isAllocaPromotable.) - CFG and loops (CFG and Loops). For a nested
forloop, runprint<loops>and identify each loop's header, latch and depth. Draw the CFG withdot-cfg. - Dominance by hand (Dominance). For the CFG
entry→A, A→B, A→C, B→D, C→D, D→E, E→A, E→exit, compute the idom of each block and DF(B), DF(D), DF(E). Check withprint<domtree>. (Answer: idom(A)=entry, idom(B)=idom(C)=idom(D)=A, idom(E)=D, idom(exit)=E; DF(B)=DF(C)={D}, DF(D)=DF(E)={A}.) - Liveness (Data-flow Analysis). Run the worklist algorithm by hand on
B1: a=1; b=2 → B2: c=a+b; if c<10 → (B3: a=c → B2) | B4: return b. Which variables are live into B2? (Answer: {a, b}.) - Your first pass (Writing a Pass). Build
CountInstsPassand print, per function, the count of each opcode name (I.getOpcodeName()). Compare before and after-O2. - Transformation (Writing a Pass). Extend
MulToShiftPassto rewriteudiv x, 2^kintolshr x, k. Why is the same rewrite wrong forsdiv? (Hint: try-1 / 2.) - Pipeline (Common Passes). Write a loop with an invariant multiply. Run
mem2reg,loop-simplify,licmand find where the multiply moved.
Glossary
| Term | Meaning | Page |
|---|---|---|
| Alloca | Stack allocation instruction; returns a ptr | Memory |
| Analysis | A pass that computes a cached result without changing IR | Writing a Pass |
| Back edge | A CFG edge whose target dominates its source | CFG and Loops |
| Basic block | Straight-line instructions ending in one terminator | Structure |
| Bitcode | The binary .bc form of IR | Overview |
| Canonical form | The one shape passes agree to use for an idiom | Common Passes |
| CFG | Control flow graph of blocks and terminator edges | CFG and Loops |
| Critical edge | Edge from a multi-successor block to a multi-predecessor block | CFG and Loops |
| Data layout | Module string that fixes sizes, alignment and endianness | Type System |
| Dominance frontier | Blocks where a block's dominance ends; where phis go | Dominance |
| Dominator tree | Tree of immediate dominators | Dominance |
| Fast-math flags | Per-instruction permission to relax IEEE floating-point rules | Arithmetic |
| GEP | getelementptr, address arithmetic without memory access | Memory |
| Header | The entry block of a natural loop | CFG and Loops |
| Intrinsic | Built-in function named llvm.* | Control Flow |
| Latch | Loop block with a back edge to the header | CFG and Loops |
| Liveness | Whether a value may be read later | Data-flow Analysis |
| Metadata | Optional extra information (!dbg, !tbaa) | Structure |
| Module | The top-level container: one .ll file | Structure |
nsw / nuw | No signed / unsigned wrap promise | Arithmetic |
| Opaque pointer | The single ptr type, with no pointee type | Type System |
| Phi | Instruction choosing a value by incoming edge | SSA and Phi |
| Poison | Value from a broken promise; UB only when it reaches a side effect | Arithmetic |
| Post-dominance | Dominance on the reversed CFG | Dominance |
| Preheader | Unique block outside a loop that enters the header | CFG and Loops |
PreservedAnalyses | What a pass returns to say which analyses are still valid | Writing a Pass |
| SSA | Static single assignment: one definition per value | SSA and Phi |
| Terminator | Last instruction of a block (br, ret, switch, ...) | Control Flow |
| Use | One operand slot linking a user to a value | Structure |
| Value | Base class of almost everything in IR | Structure |
| Worklist | Queue of items to revisit until a fixed point | Data-flow Analysis |
Sources: llvm/include/llvm/IR/Instruction.def:126-223
Where to Go Next
- How IR becomes machine instructions: SelectionDAG wiki.
- How a new target plugs into that: Target Bring-up wiki.