What happens for each optimization level?

I have been curious about the optimization level in Rust for a long time. We can set the op-level to "0-3," "s," and "z." We know that most optimizations are closed when "opt-level=0". However, what happens with other options? For example, is "niche optimization" a default optimization? Or, we can close it by setting opt-level=0.

Remember that you can link together crates compiled with different optimization levels, so layout has to be independent of optimization levels.

For most of the differences between 1/2/3/s/z, look at LLVM's pass manager.

2 Likes

This argument doesn’t hold — if crate foo depends on crate bar, then when rustc is compiling foo, it has access to bar's crate metadata, which could contain layout decisions made when bar was compiled. (I don't know if it currently does.)

All that is required to be consistent is that when a generic type is monomorphized, the layout chosen for that depends solely on the types involved (which could have optimization-dependent information from the compilation of those types' crates) and not on any environment such as options to the current compilation.

That said, I’m not aware of any reason that layout should be made to depend on optimization settings, other than layout closely related to compilation such as that of futures/coroutines.

8 Likes

It does. -Zrandomize-layout is a per-crate flag and gets tracked in the type's repr metadata. Optimization fuel used to do that too, but it was removed.