Skip to content

match-then-remake Result doesn't optimize away for some payload widths #101210

Closed
@scottmcm

Description

@scottmcm

As the new codegen test confirms, matching and rebuilding a Result<i32, u32> optimizes away now (on x64).

However, it seemingly doesn't optimize away if the ok and error types are 64 bits:

pub fn result_nop_match_64(x: Result<i64, u64>) -> Result<i64, u64> {
    match x {
        Ok(x) => Ok(x),
        Err(x) => Err(x),
    }
}

https://rust.godbolt.org/z/fMn6aqWG8

result_nop_match_64:
        mov     rax, rdi
        cmp     qword ptr [rsi], 0
        je      .LBB0_1
        mov     rcx, qword ptr [rsi + 8]
        mov     qword ptr [rax + 8], rcx
        mov     ecx, 1
        mov     qword ptr [rax], rcx
        ret
.LBB0_1:
        mov     rcx, qword ptr [rsi + 8]
        mov     qword ptr [rax + 8], rcx
        xor     ecx, ecx
        mov     qword ptr [rax], rcx
        ret

Interestingly, it does optimize away when there's another enum in the middle, like happens in the ? desugaring. From that same godbolt,

pub fn result_nop_traits_64(x: Result<i64, u64>) -> Result<i64, u64> {
    try {
        x?
    }
}

gives

result_nop_traits_64:
        mov     rax, rdi
        movups  xmm0, xmmword ptr [rsi]
        movups  xmmword ptr [rdi], xmm0
        ret

Metadata

Metadata

Assignees

Labels

A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchE-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.E-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.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