Simple `Option` use, like in `checked_sub`, should optimize out fully in MIR
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Today, this bit of code: https://rust.godbolt.org/z/EfE68Meax
pub fn saturating_sub_at_home(lhs: u32, rhs: u32) -> u32 {
u32::checked_sub(lhs, rhs).unwrap_or(0)
}
Doesn't MIR-opt as well as it ought, because the Option isn't completely optimized out:
bb2: {
StorageLive(_5);
_5 = SubUnchecked(copy _1, copy _2);
_3 = Option::<u32>::Some(move _5);
StorageDead(_5);
StorageDead(_4);
StorageLive(_6);
_6 = move ((_3 as Some).0: u32);
_0 = move _6;
StorageDead(_6);
goto -> bb3;
}
Even though it's clearly unnecessary to build-then-unwrap the option here.
This isn't "just" a GVN bug, because when GVN sees it it's not all together in one BB like this, and IIRC the Option local is also not SSA at the time, so it's reasonable that GVN doesn't currently address it. Yay phase ordering :/
Once https://github.com/rust-lang/rust/pull/138545 lands, there will be tests in the repo further demonstrating this, at https://github.com/search?q=repo%3Arust-lang%2Frust%20138544%20%20path%3Atests%2Fmir-opt&type=code
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the MIR optimization tests added by pull request 138545 under tests/mir-opt, and compare them with the linked Godbolt example. The work is done when the checked_sub-style Option is fully optimized out in MIR; the issue does not name the compiler pass or implementation file to change.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100