Bounds check eliminated only when array length is a constant
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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