Skip to content

Missed Optimization for NonZeroU32 to NonZeroUsize Conversions #119422

Closed as not planned
@zmtaub

Description

@zmtaub

I tried this code:

use std::num::*;

pub fn f0(x: u32) -> u64 {
    x.try_into().unwrap()
}

pub fn f1(x: NonZeroU32) -> NonZeroU64 {
    x.try_into().unwrap()
}

pub fn f2(x: u32) -> usize {
    x.try_into().unwrap()
}

pub fn f3(x: NonZeroU32) -> NonZeroUsize {
    x.try_into().unwrap()
}

I expected to see this happen:

I expected equivalent assembly generated for each function on 64-bit platforms when compiling with -C opt-level=3.
Indeed, if f3 is removed, this assembly is generated according to Compiler Explorer:

example::f0:
        mov     eax, edi
        ret

Instead, this happened:

According to Compiler Explorer, this assembly is generated:

core::ptr::drop_in_place<core::num::error::TryFromIntError>:
        ret

example::f0:
        mov     eax, edi
        ret

example::f3:
        test    edi, edi
        je      .LBB2_1
        mov     eax, edi
        ret
.LBB2_1:
        push    rax
        lea     rdi, [rip + .L__unnamed_1]
        lea     rcx, [rip + .L__unnamed_2]
        lea     r8, [rip + .L__unnamed_3]
        lea     rdx, [rsp + 7]
        mov     esi, 43
        call    qword ptr [rip + core::result::unwrap_failed@GOTPCREL]
        ud2

.L__unnamed_1:
        .ascii  "called `Result::unwrap()` on an `Err` value"

.L__unnamed_2:
        .quad   core::ptr::drop_in_place<core::num::error::TryFromIntError>
        .asciz  "\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000"
        .quad   <core::num::error::TryFromIntError as core::fmt::Debug>::fmt

.L__unnamed_4:
        .ascii  "/app/example.rs"

.L__unnamed_3:
        .quad   .L__unnamed_4
        .asciz  "\017\000\000\000\000\000\000\000\020\000\000\000\022\000\000"

The try_into().unwrap() isn't optimized away for f3, unlike the other functions.

Compiler Explorer link

Meta

rustc --version --verbose:

rustc 1.74.0 (79e9716c9 2023-11-13)
binary: rustc
commit-hash: 79e9716c980570bfd1f666e3b16ac583f0168962
commit-date: 2023-11-13
host: x86_64-unknown-linux-gnu
release: 1.74.0
LLVM version: 17.0.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-bugCategory: This is a bug.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchI-heavyIssue: Problems and improvements with respect to binary size of generated code.I-slowIssue: Problems and improvements with respect to performance of generated code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions