rust-lang / rust-lang/rust

Bounds check eliminated only when array length is a constant

Open
#141,671 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

I tried this code (godbolt):

#[no_mangle]
pub fn shift_left(arr: &mut [u64], n: usize) {
    let len = arr.len();
    if n >= len {
        arr.fill(0);
    } else {
        let c = len - n;
        for i in 0..c {
            arr[i] = arr[i + n];
        }
        arr[c..].fill(0);
    }
}

#[no_mangle]
pub fn shift_left_4(arr: &mut [u64; 4], n: usize) {
    shift_left(arr, n);
}

I expected to see this happen: no bound checks in both functions

Instead, this happened: bounds check present in the generic shift_left (the arr[i + n])

Meta

rustc --version --verbose:

rustc 1.89.0-nightly (5e16c6620 2025-05-24)
binary: rustc
commit-hash: 5e16c662062fd6dee91f0fe2a1580483488d80cf
commit-date: 2025-05-24
host: x86_64-unknown-linux-gnu
release: 1.89.0-nightly
LLVM version: 20.1.5
Backtrace

<backtrace>

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

Reproduce the difference between shift_left and shift_left_4 using the linked Godbolt example and the reported rustc nightly version. Compare the generated code for the generic slice and fixed-size array cases, then trace the compiler optimization stage responsible for the remaining arr[i + n] bounds check. Done means the generic function no longer emits that check while preserving the demonstrated behavior.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.