rust-lang / rust-lang/rust

Counter in slice iter fails to eliminate bounds check

Open
#132,557 1 comment 1 reaction 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

The following code (somewhat extracted from #126425) includes an unreachable bounds check panic

pub fn getnonzero(buf: &[u8; 128]) -> &[u8] {
    let mut curr = 0;
    for n in buf.iter() {
        if *n == 0 { break; }
        curr += 1;
    }
    &buf[..curr]
}

https://godbolt.org/z/vzooGexnj

This bounds check can be eliminated: Alive2

This also occurs with reverse iteration (like in the original) and iterating 0..buf.len() instead of direct slice iteration. Lowering the slice length to the point where the loop is fully unrolled does eliminate this, but the exact number depends on the specific code.

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

Compile the provided getnonzero reproducer and inspect its generated output through Godbolt, comparing direct, reverse, and range iteration variants. Trace the compiler optimization path responsible for the bounds check and validate changes against the Alive2 example. Done means the unreachable check is eliminated for the reported cases without regressing other cases.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.