rust-lang / rust-lang/rust

Possibly Missed Optimization

Open
#150,690 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-LLVM C-optimization I-slow T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

This generates the following ASM. Godbolt

fn foo(i: i32) -> i64 {
    let i = i.abs() as i64;
    i + i
}
foo:
        mov     eax, edi
        neg     eax
        cmovs   eax, edi
        cdqe
        add     rax, rax
        ret

But, this generates the following ASM. Godbolt

fn foo(i: i32) -> i64 {
    i.abs() as i64 + i.abs() as i64
}
foo:
        mov     eax, edi
        neg     eax
        mov     ecx, edi
        cmovns  ecx, eax
        test    edi, edi
        cdqe
        mov     edx, edi
        cmovs   rdx, rax
        movsxd  rax, ecx
        add     rax, rdx
        ret

Doing a small reordering makes sure they compile down to same ASM. Godbolt

fn foo(i: i32) -> i64 {
    let i = i.abs() as i64;
    i + i
}

fn foo_other(i: i32) -> i64 {
    let i = i.abs();
    i as i64 + i as i64
}
foo:
        mov     eax, edi
        neg     eax
        cmovs   eax, edi
        cdqe
        add     rax, rax
        ret

foo_other = foo
Meta

rustc --version --verbose:

1.92.0

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the two Rust snippets with rustc 1.92.0 using the provided Godbolt links and compare their generated ASM. Investigate why repeating i.abs() as i64 prevents the optimization seen after introducing a local variable. Done means the equivalent expressions generate the same optimized code, with the behavior covered by an appropriate compiler test.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers, performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.