What Are the Stages of Rust Compilation? (Parsing, HIR, MIR, LLVM IR)

Rust compiles code through Parsing, HIR, MIR, and LLVM IR stages to ensure safety and performance before generating machine code.

Rust compilation transforms source code into machine code through four distinct stages: Parsing, HIR, MIR, and LLVM IR. First, the compiler parses text into an Abstract Syntax Tree (AST), then expands macros and checks types to create the High-Level Intermediate Representation (HIR). Next, it lowers HIR into the Mid-Level Intermediate Representation (MIR) for borrow checking and optimization. Finally, MIR is translated into LLVM IR, which LLVM compiles into optimized machine code. You can inspect these stages using the rustc compiler with specific flags:

rustc --pretty=expanded src/main.rs
rustc -Z unpretty=hir src/main.rs
rustc -Z unpretty=mir src/main.rs
rustc -C llvm-args=-print-after-all src/main.rs

Note: The -Z flags require the nightly toolchain (rustup override set nightly).