Sub topic 1
Where the time goes: rustc, LLVM, and the linker
A Rust build is a pipeline of several programs, and each stage has a different cost profile. A fix that helps one stage often does nothing for another. This chapter gives you a working model of the pipeline so that later chapters on profiles, linkers, and caching make sense.
Prerequisites
This chapter assumes you can:
- Read and write basic Rust, including ownership and generics.
- Run
cargo build,cargo run, andcargo teston a project. - Read a
Cargo.tomlfile and use a command line.
You do not need to know compiler internals. Each stage is explained as it appears.
The big picture
When you run cargo build, Cargo does not compile your code itself. It works out which crates need building, then starts one rustc process per crate. Build scripts and procedural macros add extra steps. The last step is a linker, which joins everything into one binary.
The three stages that usually matter most are the rustc front end, LLVM, and the linker. We cover each in turn.
Stage 1: Cargo plans the build
Cargo reads your manifests and resolves a dependency graph. It decides which crates are stale, then schedules rustc invocations in dependency order and in parallel where it can. Planning itself is quick. Its main effect on build time is the shape of the graph:
- A crate cannot start until the crates it depends on have produced their metadata.
- A long chain of dependencies limits parallelism, however many cores you have.
- One huge crate gets compiled mostly by a single process, so extra cores sit idle.
Cargo uses pipelining. A dependent crate can begin as soon as its dependency has emitted metadata (the .rmeta file with type and signature information). It does not have to wait for that dependency's machine code. This helps, but it does not remove the chain.
You can see the exact commands Cargo issues with the verbose flag:
cargo build -vEach Running line is one rustc call with its flags. This is useful when you later want to know which options a profile actually produces.
Stage 2: The rustc front end
The front end turns source text into a checked program. In order, it does roughly the following:
- Parses source into an abstract syntax tree (AST).
- Expands macros, including
macro_rules!and procedural macros, and resolves names. - Lowers the code to the high-level IR (HIR) and checks types, traits, and lifetimes.
- Lowers to MIR, a simplified control-flow representation, and runs the borrow checker on it.
- Runs some MIR optimizations.
This work is mostly single-threaded per crate on stable Rust. Heavy trait resolution, large macro expansions, and deeply nested generic code make this stage slow. Rust's type system is powerful, and that power has a cost: complex trait bounds and big derive-generated impls can add noticeable time.
The front end does not need LLVM. That is why cargo check is fast: it runs the front end, writes metadata, and stops. It never generates machine code or links. The cargo check chapter covers this in more detail.
Stage 3: LLVM code generation
After MIR, rustc translates each function into LLVM IR and hands it to LLVM. LLVM then runs its optimization passes and emits machine code in object files. For many projects, this stage takes the largest share of wall-clock time in a full build.
Three factors drive its cost.
Amount of IR. LLVM's work grows with the amount of code it receives. Generic functions are compiled once for each concrete type used, a process called monomorphization. A single generic function used with twenty types becomes twenty copies for LLVM to optimize. A later chapter covers how to tame this.
Optimization level. The opt-level setting controls how many passes run and how aggressive they are. A debug build uses opt-level = 0, which runs very little. A release build uses opt-level = 3 by default, which is much slower to compile but produces faster code.
Parallelism. rustc splits a crate's code into codegen units and gives LLVM one unit per thread. More units means more parallelism but fewer cross-unit optimizations. Debug builds use many units (256 by default with incremental compilation). Release builds default to 16.
You can look at the IR rustc produces for a crate:
cargo rustc --release -- --emit=llvm-irThe .ll files appear under target/release/deps/. They are plain text, so you can compare their sizes for different code shapes. The cargo llvm-lines tool, which later chapters use, summarizes this for you.
Stage 4: Linking
Once every crate has been compiled to object code or a library archive, the linker joins them into the final executable or shared library. The linker also resolves symbols, removes unused code, and lays out the binary.
Linking is a single step for each final artifact, and it cannot start until all its inputs exist. It runs after every other stage has finished for that artifact. Consequences:
- A one-line change to a leaf crate still requires a full link of the binary.
- Link time grows with binary size, which grows with debug info and with the number of dependencies.
- The default system linker on Linux (GNU
ld) is slower than newer alternatives such aslldandmold.
Link time matters most in the edit-compile-run loop. If you change one function and the compile takes half a second but the link takes five seconds, the linker is your bottleneck. A later chapter shows how to switch linkers.
Build scripts and procedural macros
Two kinds of code run during the build itself, so they add to build time before your own crate compiles.
- A build script (
build.rs) is compiled as its own program, then run. Its crate must finish before dependents start. Scripts that probe the system, compile C code, or generate sources can take seconds. - A procedural macro crate is compiled and then loaded into rustc as a plugin. Heavy macros (for example derives that generate large impls) slow the front end of every crate that uses them. The macro crate's own dependencies, often
synandquote, must also compile first.
Both are on the critical path of a clean build. They also run on the host machine, so they are compiled for the host even when you cross-compile.
Which stage is your bottleneck?
The answer depends on the build type. This table gives typical patterns, not guarantees.
| Situation | Usually dominant | Why |
|---|---|---|
| `cargo check` after an edit | rustc front end | No codegen or linking happens |
| Debug rebuild after a small edit | Linking, then LLVM | Incremental compilation reuses most work, but the link repeats fully |
| Clean debug build | Dependencies (front end plus LLVM) | Every crate compiles from scratch |
| Release build | LLVM | High `opt-level`, fewer codegen units, possibly LTO |
| Many small crates in a workspace | Critical path in the graph | Dependency chains limit parallelism |
Treat the table as a hypothesis to test. Measure before you change anything.
A first look with real measurements
The simplest comparison is how long each cargo command takes on the same project after a trivial edit. Run these in order and note the times:
touch src/main.rs
time cargo check
touch src/main.rs
time cargo build
touch src/main.rs
time cargo build --releaseThe gap between check and build is roughly the cost of LLVM plus linking for a debug build. The gap between build and build --release is mostly the cost of optimization. For a deeper per-stage view you can use nightly's -Z time-passes flag, which prints how long each rustc pass took:
cargo +nightly rustc -- -Z time-passesThe output is long and its names change between compiler versions. Use it to spot which broad pass, such as type checking or LLVM, is large. The next chapter introduces cargo build --timings, which is the better first tool because it shows the whole dependency graph.
Common mistakes
- Optimizing the wrong stage. Switching to a faster linker does nothing if the front end dominates. Enabling
cargo checkdoes nothing for a slow release build. - Judging by a clean build. Most of your day is incremental rebuilds. A clean build can be dominated by dependencies that you rarely recompile.
- Ignoring the graph. Eight cores do not help if one crate is on the critical path and everything waits for it.
- Measuring once. Disk cache and other load change timings. Repeat each measurement a few times and compare the typical value.
Exercise
You edit one line in a function in a leaf crate of a large workspace. cargo check takes 1 second, but cargo build takes 12 seconds. Which stages explain the 11-second difference, and which one is likely to grow most as the binary gets bigger?
Show answer
The difference comes from LLVM code generation (producing machine code for the changed code) and linking. cargo check stops after the front end and never runs either. Linking is likely to grow most with binary size, because it has to process the whole binary every time, even for a one-line change.
Exercise
A teammate says that adding more CPU cores will fix a slow clean build. Give one reason this might not help.
Show answer
A long dependency chain, or one very large crate, forces work to run mostly in sequence. A crate cannot start until its dependencies have produced metadata, and the front end of one crate is mostly single-threaded, so extra cores have little work to do.