Skip to content
systemcoding.dev
Toolchains

How Clang, LLVM IR and the LLVM Backend Fit Together

Follow one C function through Clang, LLVM IR, the optimizer and the code generator, and see what each stage produces and which tool lets you run it alone.

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.

People say "LLVM" and "Clang" as if they were one program, and the confusion causes real mistakes: someone installs clang and wonders why opt is missing, or reads that "LLVM optimized the loop" and cannot find where. They are separate pieces. Clang reads C and C++. LLVM is everything after that: an intermediate language called LLVM IR, an optimizer that rewrites it, and code generators for many CPUs. This post follows one small C function through all three, shows the output of each stage, and names the command that runs each one on its own. The examples use Clang 18 and LLVM 18 on x86-64 Linux, and the IR and assembly you see on your machine will differ in small details.

The three stages

A compiler built on LLVM is a pipeline with a typed interface in the middle:

  1. Front end. Reads source code, checks it and produces LLVM IR. Clang does this for C, C++ and Objective-C. Other languages have their own: rustc for Rust, swiftc for Swift, zig for Zig.

  2. Optimizer. Takes IR and returns better IR. It does not care which language produced it. Inlining, constant folding, loop vectorization and dead code removal all happen here, as passes over the IR.

  3. Back end. Takes optimized IR and turns it into machine instructions for one CPU family such as x86-64, AArch64, RISC-V or WebAssembly. The result is assembly text or an object file.

A linker, usually lld, then combines object files into an executable. The main idea is that the front end and back end never talk directly. Because both speak IR, a new language needs only a front end to get every CPU, and a new CPU needs only a back end to get every language. This is why LLVM supports more combinations than a compiler written as one program.

The program

Take a function that returns the larger of two integers:

max.cc
int max_of(int a, int b)
{
    return a > b ? a : b;
}

Stage 1: Clang produces IR

The flags -S -emit-llvm tell Clang to stop after the front end and write textual IR instead of assembly. Add -fno-discard-value-names so the IR keeps your variable names, which makes it readable, and use -O0 to see the front end's raw output without the optimizer:

Shell
clang -O0 -S -emit-llvm -fno-discard-value-names max.c -o max.ll
cat max.ll
Text
define dso_local i32 @max_of(i32 noundef %a, i32 noundef %b) #0 {
entry:
  %a.addr = alloca i32, align 4
  %b.addr = alloca i32, align 4
  store i32 %a, ptr %a.addr, align 4
  store i32 %b, ptr %b.addr, align 4
  %0 = load i32, ptr %a.addr, align 4
  %1 = load i32, ptr %b.addr, align 4
  %cmp = icmp sgt i32 %0, %1
  br i1 %cmp, label %cond.true, label %cond.false

cond.true:
  %2 = load i32, ptr %a.addr, align 4
  br label %cond.end

cond.false:
  %3 = load i32, ptr %b.addr, align 4
  br label %cond.end

cond.end:
  %cond = phi i32 [ %2, %cond.true ], [ %3, %cond.false ]
  ret i32 %cond
}

The listing leaves out the module header and the attribute block. Four things in it are worth knowing. Types are explicit: i32 is a 32-bit integer, and ptr is a pointer. Every value is assigned once and has a name starting with %, which is the single static assignment property. The function is divided into basic blocks, the labeled sections that end in a branch or a return. And the phi instruction in cond.end picks a value depending on which block control came from, which is how SSA form expresses "this variable has different values on different paths".

At -O0 Clang keeps every parameter in memory through an alloca, a store and load, because that is the simplest translation of C. The optimizer's first job is usually to clean that up.

Stage 2: the optimizer rewrites the IR

Run the same compile at -O1 or higher and the front end hands IR to the optimizer before you see it:

Shell
clang -O2 -S -emit-llvm -fno-discard-value-names max.c -o max_opt.ll
Text
define dso_local i32 @max_of(i32 noundef %a, i32 noundef %b) local_unnamed_addr #0 {
entry:
  %cond = tail call i32 @llvm.smax.i32(i32 %a, i32 %b)
  ret i32 %cond
}

Everything collapsed. The alloca memory traffic was removed by a pass called mem2reg, which promotes stack slots to SSA values. The comparison and the branch with its phi were recognized as a maximum, and replaced with a call to an LLVM intrinsic, llvm.smax.i32, which the back end knows how to lower to the best instruction for the CPU. local_unnamed_addr and tail call are extra facts the optimizer proved. You can run individual passes yourself with the opt tool, which the next posts in this series cover.

Stage 3: the back end emits machine code

The tool llc runs only the back end. Feed it the optimized IR and pick a target:

Shell
llc -O2 max_opt.ll -o max.s
cat max.s
Text
max_of:
	movl	%edi, %eax
	cmpl	%esi, %edi
	cmovgel	%esi, %eax
	retq

On x86-64, with the System V calling convention, the first argument arrives in %edi and the second in %esi, and the result leaves in %eax. The back end copied a into %eax, compared the two and used a conditional move to replace it with b if a was not greater. There is no branch. The listing omits assembler directives such as .globl and .cfi_startproc. For the same IR and a different target, you get different code, which shows the separation at work:

Shell
llc -O2 -mtriple=aarch64-linux-gnu max_opt.ll -o max_arm.s
Text
max_of:
	cmp	w0, w1
	csel	w0, w0, w1, gt
	ret

The comparison and the conditional select are the AArch64 forms of what the x86-64 listing did. The back end performed instruction selection, register allocation and scheduling for each target. The IR file did not change between the two runs.

Where each tool fits

StageInputOutputTool
Front endC or C++ sourceLLVM IRclang -S -emit-llvm
OptimizerLLVM IRLLVM IRopt
Back endLLVM IRassembly or objectllc
Assemblerassemblyobjectllvm-mc, or clang -c
Linkerobjectsexecutablelld

When you run clang -O2 max.c -o max, the driver runs the front end, the optimizer and the back end inside one process called cc1, then starts the linker. You can see the actual commands with -###:

Shell
clang -### -O2 max.c -o max 2>&1 | grep -c cc1
Text
1

One cc1 invocation does the compile. The linker line follows it. Clang keeps the stages inside one process for speed, which is why running clang -emit-llvm and then opt and llc is slower than a normal compile, though it gives you a chance to inspect or modify the IR between steps.

IR as a file format

Textual IR (.ll) is for people. The same module has a compact binary form, bitcode (.bc), that tools exchange and that link-time optimization uses to defer code generation until link time. llvm-as turns text into bitcode and llvm-dis turns it back:

Shell
llvm-as max_opt.ll -o max_opt.bc
llvm-dis max_opt.bc -o -

Because IR is a stable-enough format with a documented language reference, other tools read it too: analyzers, instrumentation passes such as the sanitizers, and just-in-time compilers. The sanitizers, for instance, are optimizer passes that insert checks into IR before the back end sees it.

Why this matters in practice

Knowing the stages answers common questions. If an optimization is missing, look at the IR after -O2 and see whether the optimizer saw the pattern; if the IR is good and the machine code is poor, the problem is in the back end for your target, and a different -mcpu or -march may help. If two languages produce different speed for the same algorithm, compare their IR. If a bug appears only with optimization, bisect which pass is responsible with -mllvm -opt-bisect-limit=N. If you work on a new CPU port, you only write the back end.

It also explains why other languages are "LLVM-based": Rust produces IR and uses the same optimizer and back ends as Clang, so a Rust program and a C program on the same target use the same instruction selector. The details differ by front end, because each language emits IR with its own conventions and metadata, which the optimizer uses to prove facts such as non-aliasing.

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.