Section 12.18

LLVM

Full name: LLVM, a name that began as an abbreviation of Low Level Virtual Machine; the project now uses LLVM as its full name.

Definition

LLVM is an open-source collection of reusable compiler parts: a common intermediate representation §3.37 (IR) of programs, the form a compiler holds a program in between source and machine code; a library of optimization passes, steps that each transform the IR; code generators for many processor families; and tools built on them, such as a linker §12.4. A language front end, such as Clang §12.17 for C and C++, translates source code into LLVM IR. The name began as Low Level Virtual Machine; the project now treats LLVM as a plain name.

The idea

Without shared parts, a compiler is written for each pair of language and processor family: LL languages and PP processor families need up to L×PL \times P translators. LLVM puts one representation in the middle. Each language needs one front end into the IR, each processor family one back end out of it, L+PL + P parts in all, and an optimization written once for the IR serves every pair. With 5 languages and 10 processor families that is 5+10=155 + 10 = 15 parts instead of 5×10=505 \times 10 = 50. Clang, the Rust and Swift compilers, and the code generator for eBPF §2.1 (extended Berkeley Packet Filter) bytecode §2.4, the instruction format of a small virtual machine §2.3, all share LLVM’s optimizer. LLVM began in 2000 as a research project of Vikram Adve and Chris Lattner at the University of Illinois at Urbana-Champaign.

The same design explains why “LLVM changed my function” is not an answer. A compiled function results from dozens of independently written passes run one after another, with a front end before them and a code generator after them. The picture is an assembly line with a window between every two stations: anyone can look at the IR after each pass and see which station made a change. The picture fails in two places: some stations run several times, and the last stations, inside the code generator, work on a lower-level form that the IR windows do not show.

How it works

From source code to object file, a program passes through these parts in this order.

  1. Front end. Clang parses C, checks it, and emits LLVM IR. It applies the language’s rules and the target’s ABI §12.47 (application binary interface), the rules for calls and data layout. Language facts become IR facts: an addition of two int values becomes add nsw, where nsw (no signed wrap) records that C leaves signed overflow §4.15 undefined. clang -S -emit-llvm writes the IR as text.

  2. Middle end, the optimizer. A pass manager runs a fixed list of passes, which an option such as -O2 or -Os selects. Examples: SROA (scalar replacement of aggregates) turns local variables and structures held in memory into plain values; InstCombine simplifies and merges instructions; GVN (global value numbering) removes repeated computations; the inliner copies called functions into their callers; loop passes such as IndVarSimplify (induction variable simplification; an induction variable is one that changes by a fixed rule on each loop iteration, such as a counter) and LoopDeletion rewrite and remove loops. Passes rely on analyses, such as scalar evolution, which describes how a value changes from one loop iteration to the next. The tool opt runs chosen passes on an IR file.

  3. Back end, the code generator. Instruction selection replaces IR operations by the target processor’s instructions; register allocation assigns the processor’s registers; scheduling orders the instructions; further passes build the stack frame and make target-specific improvements. The tool llc runs this stage alone.

  4. Machine-code layer. LLVM’s built-in assembler encodes each instruction as bytes, choosing among the encodings the processor offers, and writes the object file, for example in ELF §12.6 (Executable and Linking Format).

  5. Link time. The linker lld joins object files. With link-time optimization §12.10 (LTO), the object files hold IR, and the optimizer runs again over the whole program, so a function in one file can be inlined into another.

The project also holds compiler-rt, with helper routines for operations the processor cannot do in one instruction and the run-time parts of the sanitizers §10.21, tools that check a program for errors while it runs; the C++ library libc++; and a back end for eBPF, selected with --target=bpf.

Four switches show which part did what.

The option -mllvm hands the option after it from Clang to LLVM.

Worked example

The C function unsigned sum(unsigned n) adds 0+1+…+(n−1)0 + 1 + \dots + (n - 1) in a loop and returns the total. Clang 18.1.8 compiled it with -O2 --target=thumbv7em-none-eabi -mcpu=cortex-m4 for an Arm Cortex-M4 §6.3 processor. The IR module records target triple = "thumbv7em-none-unknown-eabi", the target’s name in LLVM’s normalized form. The finished code contains no loop: it computes the total with one multiplication, as the entry comparing the two major C compilers shows instruction by instruction. Three parts of LLVM made that happen.

With -mllvm -opt-bisect-limit=-1, which sets no limit, the compiler runs every pass and numbers the optional ones from 1 to 145. Three of the lines it prints are:

BISECT: running pass (46) IndVarSimplifyPass on <unnamed loop>
BISECT: running pass (47) LoopDeletionPass on <unnamed loop>
BISECT: running pass (113) ARM Instruction Selection on function (sum)

With the limit 45, the Arm code still contains a four-instruction loop (add, adds, cmp, blo). With the limit 46, a multiplication computes the total instead, so pass 46, IndVarSimplify, made the change. Searching by halving the range needs at most ⌈log2146⌉=8\lceil \log_2 146 \rceil = 8 compilations for the 146 possible limits 0 to 145, where ⌈x⌉\lceil x \rceil means xx rounded up to a whole number.

-mllvm -print-changed shows what pass 46 did. Before it, the loop adds the counter to a running total. After it, the IR computes the total before the loop starts:

%4 = add i32 %0, -1
%5 = zext i32 %4 to i33
%6 = add i32 %0, -2
%7 = zext i32 %6 to i33
%8 = mul i33 %5, %7
%9 = lshr i33 %8, 1
%10 = trunc i33 %9 to i32
%11 = add i32 %0, %10

and, where the loop exits, %13 = add i32 %11, -1. Here %0 is nn. i32 and i33 are integer types of 32 and 33 bits, since LLVM IR allows any width. zext widens a value with zero bits, mul multiplies, lshr shifts right and fills with zeros, and trunc drops the high bits. The loop is left with a branch condition that is always false, so its body runs once; pass 47, LoopDeletion, then removes the loop.

Check with n=4n = 4, where the answer is 0+1+2+3=60 + 1 + 2 + 3 = 6: %4 is 33, %6 is 22, %8 is 3×2=63 \times 2 = 6, %9 is 6/2=36 / 2 = 3, %11 is 4+3=74 + 3 = 7, and %13 is 7−1=67 - 1 = 6. The 33-bit product keeps bit 32, which the halving moves into the result. For n=100,000n = 100{,}000 the product 99,999×99,998=9,999,700,00299{,}999 \times 99{,}998 = 9{,}999{,}700{,}002 needs 34 bits. Modulo 233=8,589,934,5922^{33} = 8{,}589{,}934{,}592 it is 1,409,765,4101{,}409{,}765{,}410; half of that is 704,882,705704{,}882{,}705; and 100,000+704,882,705−1=704,982,704100{,}000 + 704{,}882{,}705 - 1 = 704{,}982{,}704. That equals the exact sum 100,000×99,999/2=4,999,950,000100{,}000 \times 99{,}999 / 2 = 4{,}999{,}950{,}000 reduced modulo 2322^{32}, which is what the C loop returns with 32-bit unsigned arithmetic.

Pass 113, Arm instruction selection in the back end, chose how to compute a 33-bit product on a 32-bit processor: umull forms the full 64-bit product in two registers, and and, lsrs and rrx shift bit 32 into the result. The front end produced the loop, the middle end replaced it, and the back end chose the instructions: three different parts of LLVM.

Stated precisely

Each LLVM IR instruction has a meaning defined by the LLVM Language Reference Manual, together with the module’s data layout, a string that gives the sizes and alignments §4.22 of types for the target. Some operations produce a poison value, a special value that marks a result the program must not rely on, instead of immediate undefined behavior §4.12: add nsw gives poison if the signed result overflows. Only certain uses of poison, such as branching on it, are undefined behavior.

A pass is correct when the IR it produces refines the IR it receives: for every input, every behavior of the new IR is a behavior that the old IR allows. A whole compilation is correct when each stage refines the one before: C to IR in the front end, IR to IR in every pass, and IR to machine code in the back end. The argument that one transformation is correct therefore belongs to one stage and rests on that stage’s premises, such as the absence of signed overflow that nsw records.

Attribution can be stated exactly. Number the passes 1,2,…,K1, 2, \dots, K in the order they run, let R0R_0 be the front end’s IR and RiR_i the program after pass ii, and let φ\varphi be a property of the program, such as “contains a multiplication of 33-bit values”. The pass responsible for φ\varphi is the smallest ii for which φ(Ri)\varphi(R_i) holds and φ(Ri−1)\varphi(R_{i-1}) does not. Bisection with -opt-bisect-limit finds that ii when φ\varphi, once true, stays true for every larger limit. If a later pass removes φ\varphi again, bisection can miss the first pass. Only optional passes are numbered; the others always run.

Limits and common mistakes

LLVM IR is neither C nor machine code. It has its own types, such as 33-bit integers; an unlimited supply of virtual registers in static single assignment §3.38 (SSA) form, in which every value is assigned exactly once; and its own rules for poison. Reading IR shows the middle end’s decisions, not instruction selection, register allocation or stack layout. For those, read the output of llc -print-after-all or the final assembly.

LLVM IR is not eBPF bytecode. For an eBPF program, the BPF back end turns the IR into eBPF instructions, and the eBPF verifier §3.3, the checker that decides whether a program may run (in Linux, part of the kernel), examines that bytecode, not the IR. A property seen in the IR may not survive code generation.

Pass names, pass lists, pass numbers and the textual IR change between LLVM versions and with options. Record the exact version and the full command with any finding; pass 46 of this example is pass 46 only for this file, this version and these options.

“LLVM” names the whole project, so “LLVM did it” identifies no part. Not every change comes from an optimization pass: the front end evaluates constant expressions and lays out structures, the assembler picks instruction encodings §2.7, and with LTO the linker stage inlines across files.

Finding the pass explains a mechanism. It does not show that the transformation is correct for every program; that is the question of compiler correctness §3.40.

Questions answered

Which part of LLVM is responsible for a particular transformation?

The responsible part is the first stage whose output shows the transformation while its input does not: the front end (such as Clang), one named pass of the middle-end optimizer, one pass of the back end (the code generator), the machine-code layer that encodes instructions, or the linker stage during link-time optimization. LLVM is a set of compiler parts that hand a program along in an intermediate representation (IR); the question asks which of them made a given change. Find it in three ways.

For example, when Clang 18.1.8 compiles a loop that sums 00 to n−1n - 1 for an Arm Cortex-M4 at -O2, pass 46, IndVarSimplify, replaces the loop’s result by an expression equal to n(n−1)/2n(n-1)/2; pass 47, LoopDeletion, removes the loop; and pass 113, Arm instruction selection, picks the multiply instruction. State the LLVM version and the full command with the answer, because pass lists change between versions.

Related entries: GCC and Clang (§12.17), Link-time optimization (LTO) (§12.10), Compiler correctness (§3.40), Classic BPF (cBPF) (§2.2), Intermediate representation (IR) (§3.37), Static single assignment (SSA) (§3.38), Compiler optimization (§3.39), eBPF (§2.1). Further reading: [114, 186].