rust-lang / rust-lang/rust

Indexing with `bool` generates suboptimal assembly

Open
#122,121 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-codegen C-optimization I-slow O-x86_64 S-has-mcve
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

fn f(a: &[u32; 2], c: bool) -> u32 {
    a[c as usize]
}

I expected to see this assembly:

f:
        mov     eax, dword ptr [rdi + 4*rsi]
        ret

Instead, I got this assembly:

f:
        mov     eax, esi ; zero-extend esi (bool param)
        mov     eax, dword ptr [rdi + 4*rax]
        ret

godbolt

I believe the ABI does not allow the upper 32 bits of rsi to be dirty when passing arguments smaller than 8 bytes, but I could be mistaken or otherwise misunderstanding the problem.

I could not find a workaround other than changing the type of c to usize and adding an unreachable_unchecked.

Meta

rustc --version --verbose:

rustc 1.78.0-nightly (d18480b84 2024-03-04)
binary: rustc
commit-hash: d18480b84fdbf1efc34f62070951334aa833d761
commit-date: 2024-03-04
host: x86_64-unknown-linux-gnu
release: 1.78.0-nightly
LLVM version: 18.1.0
Compiler returned: 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

Run the supplied Rust reproducer and compare its generated assembly with the Godbolt example. Trace rustc's code-generation and ABI handling for converting the bool index, then add regression coverage showing the expected indexing assembly and verify the compiler output no longer performs the unnecessary zero-extension.

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
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.