Skip to content
systemcoding.dev
Toolchains

Run LLVM Optimisation Passes by Hand With opt

Run individual LLVM passes such as mem2reg and instcombine on IR with opt, build a pipeline, list the passes and print what each pass changed.

7 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the LLVM, GNU and C logos.

The optimizer in LLVM is a long list of small passes, each doing one thing: promote memory to registers, fold constants, remove dead code, simplify the control-flow graph. When you compile with -O2, Clang runs a fixed sequence of them. The opt tool runs any sequence you choose on an IR file and writes the result, which makes it the best way to learn what each pass does and to diagnose a bad optimization. This post covers the pass syntax used by LLVM 18's new pass manager, a worked example that takes -O0 IR to near--O2 IR one pass at a time, the options that list passes and report changes, and how to bisect a miscompile. The examples use opt from LLVM 18.

What opt does

opt reads IR, textual .ll or bitcode .bc, runs the passes you name and writes IR. It does not read C. You produce the input with Clang and read the output yourself:

Shell
opt -passes='<pipeline>' input.ll -S -o output.ll

-S writes text instead of bitcode. The -passes option takes a pipeline description in a small language. Pass names are separated by commas. Since LLVM 13 this "new pass manager" syntax is the default, and the older form where each pass had its own flag, such as -mem2reg, has been removed from opt in recent releases, so use -passes=.

Prepare input that the optimizer can touch

By default Clang marks every function at -O0 with the optnone attribute, which tells the optimizer to leave it alone. To experiment, drop it with a front-end option:

lerp.cc
int pick(int c, int a, int b)
{
    int r;
    if (c)
        r = a;
    else
        r = b;
    return r;
}
Shell
clang -O0 -Xclang -disable-O0-optnone -S -emit-llvm -fno-discard-value-names lerp.c -o lerp.ll

The resulting IR has alloca slots for c, a, b and r, loads and stores around them, and a diamond of basic blocks with a phi-free form, since variables live in memory.

One pass at a time

Run the first pass, mem2reg, which promotes alloca slots to SSA values:

Shell
opt -passes=mem2reg -S lerp.ll -o step1.ll
Text
define dso_local i32 @pick(i32 noundef %c, i32 noundef %a, i32 noundef %b) #0 {
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:
  %r.0 = phi i32 [ %a, %if.then ], [ %b, %if.else ]
  ret i32 %r.0
}

All alloca, store and load instructions are gone, replaced by a phi. The shape of the control flow is unchanged, and two blocks contain only a branch. Next, simplifycfg cleans up the control-flow graph:

Shell
opt -passes=simplifycfg -S step1.ll -o step2.ll
Text
define dso_local i32 @pick(i32 noundef %c, i32 noundef %a, i32 noundef %b) #0 {
entry:
  %tobool = icmp ne i32 %c, 0
  %r.0 = select i1 %tobool, i32 %a, i32 %b
  ret i32 %r.0
}

The empty blocks were removed, and the phi became a select, an instruction that picks one of two values without branching. A final instcombine would fold the comparison into the select, giving select i1 ... on a truncation or leaving the form unchanged on this input, since the semantics of a C if (c) over an int need the icmp ne. You can chain passes in one command, separated by commas, and they run in order:

Shell
opt -passes='mem2reg,simplifycfg,instcombine' -S lerp.ll -o lerp_opt.ll

That is a miniature pipeline; the real -O2 pipeline has dozens of passes in several rounds, and some run on whole modules, some on functions, some on loops.

Run a standard pipeline

You can ask for the default pipelines by name:

Shell
opt -passes='default<O2>' -S lerp.ll -o lerp_O2.ll
opt -passes='default<O1>' -S lerp.ll -o lerp_O1.ll
opt -passes='default<Os>' -S lerp.ll -o lerp_Os.ll

default<O2> is what Clang runs at -O2, and running it through opt on -O0 IR yields code very close to what clang -O2 produces, with some differences because the front end also records information such as TBAA metadata and function attributes. To see which passes the pipeline contains and in which order:

Shell
opt -passes='default<O2>' -print-pipeline-passes -disable-output lerp.ll
Text
annotation2metadata,forceattrs,inferattrs,function<eager-inv>(lower-expect,simplifycfg<bonus-inst-threshold=1;...>,sroa<modref-cfg>,early-cse<>),...

The line is very long, dozens of passes, and shows the nesting: function<...>(...) wraps passes that run per function, cgscc(...) per strongly connected component of the call graph, and loop(...) per loop. Reading it once is educational, and the exact content changes with each release.

List and describe passes

opt --print-passes prints every pass and analysis name that your build knows, grouped by kind, and is the index to use when you want to try something:

Shell
opt --print-passes | head -n 12
Text
Module passes:
  always-inline
  annotation2metadata
  attributor
  ...

Each pass has an entry in the LLVM documentation's "LLVM's Analysis and Transform Passes" page, with a description and an example, which is the place to read what sroa, gvn, licm, loop-unroll, inline, dce, adce, sccp and the rest do. A few passes worth trying early: instcombine for peephole simplification, sroa for scalar replacement of aggregates, gvn for redundant load and expression elimination, licm for loop-invariant code motion, loop-vectorize and slp-vectorizer for vectorization, and inline for inlining.

See what a pass changed

Two options show the change instead of leaving you to diff files. -print-changed prints the IR before and after every pass that modified it, which makes a long pipeline legible:

Shell
opt -passes='mem2reg,simplifycfg' -print-changed -disable-output lerp.ll 2>&1 | head -n 20
Text
*** IR Dump At Start ***
define dso_local i32 @pick(i32 noundef %c, i32 noundef %a, i32 noundef %b) #0 {
...
*** IR Dump After PromotePass on pick ***
define dso_local i32 @pick(i32 noundef %c, i32 noundef %a, i32 noundef %b) #0 {
...
*** IR Dump After SimplifyCFGPass on pick ***

The headings use the pass class names rather than the pipeline names; mem2reg is PromotePass. Add -print-after-all to dump after every pass, whether it changed anything or not, and -print-before=<pass> for one pass. -debug-pass-manager prints a line for each pass invocation, which shows the order and the unit it ran on. And -time-passes reports how long each pass took, which is how you find that a surprisingly slow compile spends its time in one pass.

Analyses

opt also runs analyses and prints their results using the print<...> passes. For example, the loop structure and the dominator tree:

Shell
opt -passes='print<loops>' -disable-output loop.ll
opt -passes='print<domtree>' -disable-output loop.ll
Text
Printing analysis 'Natural Loop Information' for function 'sum':
Loop at depth 1 containing: %for.cond<header><exiting>,%for.body,%for.inc<latch>

The block names depend on the input. These printouts are how compiler developers verify that an analysis sees what they expect, and how you can check whether the optimizer recognized your code as a loop at all before blaming a later pass.

Finding which pass caused a bug

When an optimized program misbehaves and the unoptimized one does not, the cause might be your code with undefined behavior, or a compiler bug. LLVM supports bisecting passes: -opt-bisect-limit=N runs only the first N pass invocations and skips the rest, which you use through Clang with -mllvm:

Shell
clang -O2 -mllvm -opt-bisect-limit=100 prog.c -o prog

Binary search on N finds the smallest limit at which the program breaks, and the compiler prints each pass it ran or skipped, such as BISECT: running pass (57) InstCombinePass on pick. The pass at that number is the one whose transformation exposes the bug. In most cases it turns out to expose undefined behavior in the program, such as a signed overflow or an out-of-bounds access, so run the sanitizers before you file a compiler bug. llvm-reduce and bugpoint shrink a failing input to a small test case, which is what the LLVM project needs in a report.

Use it to learn

Take a function you care about, produce -O0 IR, and apply passes one at a time as above, reading the diff each time. That is how the cost of a source-level pattern becomes concrete: you see that a local array is split into scalars by sroa, that a repeated load is removed by gvn, and that a loop-invariant computation is hoisted by licm. The same knowledge makes -Rpass remarks and -print-changed output easy to read when you tune a hot function.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.