Uncovering the Secrets of Rust Compilation
As a Rust developer, you might think that producing a binary from your code is a straightforward process. However, modern compilers are complex programs that can yield binaries with vastly different performance characteristics in response to minor changes in the source code. To diagnose performance issues, it’s essential to inspect the compiler’s output.
The Power of Assembly
Rust provides various types of output, including assembly code. This guide explores the tools and facilities available for extracting and embedding assembly code in your Rust projects.
Viewing Assembly Code
To view assembly output, we’ll use a simple example program. The quickest way to generate assembly is by using the Rust compiler itself, rustc
, with the --emit asm
option. You can also format the output with Intel syntax by passing the -C llvm-args=-x86-asm-syntax=intel
option.
Godbolt Compiler Explorer
A simpler way to examine short snippets of code is to run them through the Godbolt Compiler Explorer, a web application that compiles code to assembly and displays it in a side-by-side view. This tool allows you to easily identify the assembly corresponding to specific lines of code.
cargo-asm: A Cargo Subcommand
cargo-asm
is a Cargo subcommand that displays the assembly for a single function at a time. This tool resolves symbol names and displays the source code interleaved with the corresponding assembly, making it particularly useful for developers learning assembly.
Including Assembly in Your Code
Rust provides facilities for embedding assembly code into your projects. Until recently, the official method was the llvm_asm!
macro, which required Rust nightly. However, since rustc-nightly-2022-01-17
, the llvm_asm!
macro has been replaced by the new asm!
macro.
The New asm! Macro
The asm!
macro provides a more user-friendly syntax for using inline assembly than the deprecated llvm_asm!
macro. It allows you to specify the assembly template, input and output operands, clobbers, and options, making it easier to include assembly code in your projects.
Armed with the Right Tools
With the tools and facilities discussed above, you can explore the assembly code generated by your Rust projects. By combining these tools with a debugger, you’ll gain a deeper understanding of how your code manipulates the CPU directly.