Skip to content

ptr::read() is slower than directly dereferencing #73258

Closed
@jrmuizel

Description

@jrmuizel
#[derive(Clone, Copy)]
pub enum Foo {
    A, B, C, D,
}

pub fn foo(v: *const Foo) -> Foo {
    let k: Option<Foo> = unsafe { Some(*v) };
    return k.unwrap();
}

compiles to

example::foo:
        mov     al, byte ptr [rdi]
        ret

but replacing *v with v.read()

#[derive(Clone, Copy)]
pub enum Foo {
    A, B, C, D,
}

pub fn foo(v: *const Foo) -> Foo {
    let k: Option<Foo> = unsafe { Some(v.read()) };
    return k.unwrap();
}

compiles to:

example::foo:
        push    rax
        mov     al, byte ptr [rdi]
        cmp     al, 4
        je      .LBB0_1
        pop     rcx
        ret
.LBB0_1:
        lea     rdi, [rip + .L__unnamed_1]
        lea     rdx, [rip + .L__unnamed_2]
        mov     esi, 43
        call    qword ptr [rip + core::panicking::panic@GOTPCREL]
        ud2

This came up from #71257

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.A-codegenArea: Code generationC-bugCategory: This is a bug.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