Skip to content

Counter in slice iter fails to eliminate bounds check #132557

Open
@clubby789

Description

@clubby789

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchI-slowIssue: Problems and improvements with respect to performance of generated code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions