Skip to content

Missed optimization with Option #149970

@theemathas

Description

@theemathas

I tried this code:

#[unsafe(no_mangle)]
pub fn f(x: &mut Option<u32>) {
    let mut y = *x;
    y = y.map(|a| a + 1);
    *x = y;
}

#[unsafe(no_mangle)]
pub fn g(x: &mut Option<u32>) {
    let mut y = *x;
    if let Some(a) = &mut y {
        *a += 1;
    }
    *x = y;
}

I expected both code to generate the same assembly, but instead I got the following with -Copt-level=3 (Godbolt):

f:
        inc     dword ptr [rdi + 4]
        ret

g:
        mov     eax, dword ptr [rdi]
        add     dword ptr [rdi + 4], eax
        ret

Since both functions are unconditionally doing a typed copy to *x, the compiler should be free to mutate the uninitialized bytes in a None value.

Meta

Godbolt compiler version:

rustc 1.94.0-nightly (fa5eda19b 2025-12-12)
binary: rustc
commit-hash: fa5eda19b95201468f5b1c5c035ec2fc06fccd66
commit-date: 2025-12-12
host: x86_64-unknown-linux-gnu
release: 1.94.0-nightly
LLVM version: 21.1.5
Internal compiler ID: nightly

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions