# MIR optimizations
MIR optimizations are optimizations run on the [MIR][mir] to produce better MIR
before codegen. This is important for two reasons: first, it makes the final
generated executable code better, and second, it means that LLVM has less work
to do, so compilation is faster. Note that since MIR is generic (not
[monomorphized][monomorph] yet), these optimizations are particularly
effective; we can optimize the generic version, so all of the monomorphizations
are cheaper!
MIR optimizations run after borrow checking. We run a series of optimization
passes over the MIR to improve it. Some passes are required to run on all code,
some passes don't actually do optimizations but only check stuff, and some
passes are only turned on in `release` mode.
The [`optimized_mir`][optmir] [query] is called to produce the optimized MIR
for a given [`DefId`][defid]. This query makes sure that the borrow checker has
run and that some validation has occurred. Then, it [steals][steal] the MIR,
optimizes it, and returns the improved MIR.
## Quickstart for adding a new optimization
1. Make a Rust source file in `tests/mir-opt` that shows the code you want to
optimize. This should be kept simple, so avoid `println!` or other formatting
code if it's not necessary for the optimization. The reason for this is that
`println!`, `format!`, etc. generate a lot of MIR that can make it harder to
understand what the optimization does to the test.
2. Run `./x test --bless tests/mir-opt/<your-test>.rs` to generate a MIR
dump. Read [this README][mir-opt-test-readme] for instructions on how to dump
things.
3. Commit the current working directory state. The reason you should commit the
test output before you implement the optimization is so that you (and your
reviewers) can see a before/after diff of what the optimization changed.
4. Implement a new optimization in [`compiler/rustc_mir_transform/src`].
The fastest and easiest way to do this is to
1. pick a small optimization (such as [`remove_storage_markers`]) and copy it
to a new file,
2. add your optimization to one of the lists in the
[`run_optimization_passes()`] function,
3. and then start modifying the copied optimization.