Sub topic 8
Inlining, generics and mangled names
A flamegraph shows the functions in your compiled binary, which are not always the functions you wrote. This chapter covers three ways the two differ: the optimizer merges functions (inlining), the compiler copies generic code once per type (monomorphization), and symbol names are encoded (mangling). It assumes you can already produce a flamegraph from a release build with debug symbols, as covered in the earlier chapters, and that you know basic Rust generics and closures.
Why frames go missing: inlining
Inlining means the compiler copies the body of a called function into its caller. The call instruction disappears. At run time there is no new stack frame for the callee, so a sampling profiler that walks the stack never sees the callee as a separate frame.
Release builds inline aggressively. Small functions, iterator adapters, closures and trait methods are all candidates. A flamegraph can therefore show time in the caller when the work happens in a helper you wrote. It can also show an unfamiliar standard-library name where you expected your own function.
Debug symbols help. With debug = true, the binary carries DWARF information that records which source function each inlined instruction came from. A tool that reads it can reconstruct virtual frames for inlined code, so the graph still shows is_prime even though it has no real stack frame.
Inline frames in cargo flamegraph
cargo flamegraph asks perf script to expand inlined frames by default. This resolution is slow on large binaries, because every address is looked up in the DWARF data. The tool has a --no-inline flag that turns it off for speed. Check cargo flamegraph --help for your installed version. If your graph looks too flat, confirm that you did not turn expansion off.
# default: inlined frames are expanded
cargo flamegraph --bin myapp
# faster on huge binaries, but inlined functions disappear into their callers
cargo flamegraph --no-inline --bin myappWhen you run perf yourself, the same choice exists. perf script accepts --inline. The default pipeline from the previous chapter does not expand inlined frames unless you add it.
perf script --inline | inferno-collapse-perf | inferno-flamegraph > flame.svgForcing a frame to exist
Sometimes you want a function to show up as its own box while you investigate. Mark it #[inline(never)]. The compiler then keeps a real call, and the profiler sees a real frame with no reliance on DWARF reconstruction.
#[inline(never)]
fn hot_helper(x: u64) -> u64 {
x.wrapping_mul(2_654_435_761).rotate_left(13)
}
fn main() {
let mut acc = 0u64;
for i in 0..500_000_000u64 {
acc ^= hot_helper(i);
}
println!("{acc}");
}This is a diagnostic technique, not a free change. Forbidding inlining can make the program slower, and the profile you collect describes the modified program. Use it to answer "where is the time?" and remove the attribute before you measure the final result with a benchmark.
Generics: one function, many copies
Rust compiles generic code by monomorphization. For each concrete type a generic function is used with, the compiler emits a separate copy specialized for that type. The program below calls one generic function with two different element types.
use std::hint::black_box;
#[inline(never)]
fn sum_squares<T: Copy + Into<u64>>(items: &[T]) -> u64 {
items
.iter()
.map(|&x| {
let v: u64 = x.into();
v * v
})
.sum()
}
fn main() {
let small: Vec<u8> = (0..=255u8).cycle().take(10_000_000).collect();
let big: Vec<u32> = (0..1_000_000u32).collect();
let mut total = 0u64;
for _ in 0..50 {
total = total.wrapping_add(sum_squares(black_box(&small)));
total = total.wrapping_add(sum_squares(black_box(&big)));
}
println!("{total}");
}The binary contains two machine-code functions, sum_squares::<u8> and sum_squares::<u32>. They run different amounts of work. In the flamegraph they are two separate boxes, not one box named sum_squares. Three consequences follow:
- Time for one source function is split across several boxes. If a generic helper is used with ten types, each type may look small while the total is large.
- A box in the graph may belong to one instantiation only. Optimizing the generic source changes all copies, but your evidence came from one of them.
- Standard-library generics appear with concrete type arguments, such as
core::iter::adapters::map::map_foldinsideIterator::sum. These names are long, and the useful part is often your own frame just below them.
To total a generic function's cost, use the search box in the SVG (click "Search" or press Ctrl+F). It highlights every box whose name matches and reports the combined percentage of samples. Searching for sum_squares merges the cost of both instantiations.
Mangled names
Object files cannot store a name like sum_squares::<u8> directly, because the linker needs a flat string with limited characters. The compiler encodes the path, generic arguments and a disambiguating hash into a mangled symbol. Rust has two schemes:
| Scheme | Prefix | Example shape | Generic arguments visible after demangling |
|---|---|---|---|
| Legacy (default on stable) | `_ZN` | `_ZN5myapp11sum_squares17h0123456789abcdefE` | No, only a hash differs between instantiations |
| v0 | `_R` | `_RINvCs...5myapp11sum_squaresyEB2_` | Yes, for example `sum_squares::<u8>` |
Most profilers demangle names for you. With the legacy scheme the result looks like myapp::sum_squares::h0123456789abcdef. The trailing h followed by 16 hex digits is a hash, not part of your function name. Two instantiations then appear as identical names with different hashes, which is hard to tell apart.
You can opt in to the v0 scheme on a build. The demangled names then include type arguments. It does not change the generated code.
RUSTFLAGS="-C symbol-mangling-version=v0" cargo flamegraph --bin myappYour perf and inferno versions must understand v0. If boxes show raw _R... strings, upgrade them, or demangle the folded text with rustfilt.
cargo install rustfilt
perf script | inferno-collapse-perf | rustfilt > demangled.folded
inferno-flamegraph < demangled.folded > flame.svgReading names in practice
Use this table when a flamegraph name does not match your source.
| What you see | Likely cause | What to do |
|---|---|---|
| A caller is wide and has no children, but you expect a helper | The helper was inlined and expansion is off or unavailable | Build with `debug = true`, drop `--no-inline`, or use `#[inline(never)]` temporarily |
| Several boxes with the same name and different `h...` hashes | Different generic instantiations under legacy mangling | Search for the name to combine them, or build with v0 mangling |
| Raw `_ZN...` or `_R...` text | The tool could not demangle | Pipe through `rustfilt` or update the tool |
| `[unknown]` boxes | Missing symbols or broken stack walking | Revisit debug symbols and the unwinding method |
| Wide `core::` or `alloc::` boxes under your function | Standard-library code you called, such as iterator adapters, `Vec` growth or hashing | Look at the line numbers and parent frame to find the call in your code |
Common mistakes
- Concluding that a function is cheap because it is absent from the graph. It may have been inlined, and its cost may sit in the caller's self time.
- Adding
#[inline(never)]everywhere and trusting the new profile. The program you profiled is no longer the program you ship. - Optimizing the one instantiation you saw. Check whether other types hit the same generic code.
- Treating the hash in a legacy name as meaningful. It changes between builds and compiler versions, so do not use it to match frames across runs. Compare by the readable part of the path.
Exercise
A flamegraph of a release build shows myapp::parse with 40% of samples and no child frames. Your source has parse calling a small function read_digit in a loop. Name two possible explanations and one action for each.
Show answer
First, read_digit was inlined into parse and the profile is not expanding inline frames (for example because --no-inline was used, or debug info is missing). The action is to build with debug = true and run without --no-inline so the profiler reconstructs the read_digit frame from DWARF. Second, the time really is in parse itself, so there is no child to show. The action is to check the line numbers of the samples, or temporarily mark read_digit with #[inline(never)] and re-profile to see whether it takes a share of the time. Remove the attribute before benchmarking the final result.
Exercise
Two boxes in a flamegraph are both named myapp::sum_squares::h followed by different 16-digit hashes. What are they, and how can you see the total cost of the function?
Show answer
They are two monomorphized instantiations of the generic function sum_squares, each compiled for a different type. Under legacy mangling the demangled names differ only by hash. To get the total, search for sum_squares in the SVG, which highlights all matching boxes and shows their combined percentage. You can also rebuild with -C symbol-mangling-version=v0 so the type arguments appear in the names.