Rust
LLVM IR
Learn the LLVM backend and code generation pipeline.
LLVM IR
MIR is translated to LLVM's intermediate representation, where LLVM optimizations (inlining, constant folding, loop unrolling, vectorization) are applied; then machine code for the target processor is generated. The optimization level is chosen with opt-level: 0 in debug builds, 3 in release.
fn kare_toplam(n: u64) -> u64 {
(1..=n).map(|i| i * i).sum()
}
// in release, LLVM may turn this loop into the n(n+1)(2n+1)/6 formula
To see the output: cargo rustc --release -- --emit=llvm-ir or Compiler Explorer (godbolt.org).
Debug versus release
In debug builds overflow checks and debug info are on and there's no optimization; in release it's the opposite. Performance must always be measured in a release build: the same code can be 10–100 times slower in debug. Intermediate options are set in Cargo.toml:
[profile.dev]
opt-level = 1 # a little optimization in debug
[profile.release]
debug = true # symbol info for profiling
codegen-units = 1 # better optimization, slower compile
Exercise Sum of squares
Write the kare_toplam function above. Print the result, passing the input through std::hint::black_box(10u64).
Show example solution
fn kare_toplam(n: u64) -> u64 {
(1..=n).map(|i| i * i).sum()
}
fn main() {
let n = std::hint::black_box(10u64);
println!("{}", kare_toplam(n));
}
Test yourself
-
Why is <code>std::hint::black_box</code> used when writing benchmarks?
- To allocate memory
- For debugging
- To stop the compiler from treating the value as a known constant and deleting the computation
- To speed the program up
Show answer
To stop the compiler from treating the value as a known constant and deleting the computation — A pure function called with a constant input may be computed at compile time; the measured time wouldn't reflect reality.
-
Block the optimization
let n = std::hint::____(10u64);
println!("{}", kare_toplam(n));
Show answer
let n = std::hint::black_box(10u64);
println!("{}", kare_toplam(n));
-
Setting and effect
- opt-level = 0
- No optimization
- opt-level = 3
- Full optimization
- --emit=llvm-ir
- LLVM IR output
- black_box
- Prevents folding
Next lesson: Borrow checker