Skip to content

Missed optimization: computing smaller index than length does not elliminate bound check #80963

Closed

Description

@newpavlov

Code:

pub fn foo(buf: &[u8]) -> Option<&[u8]> {
    // guard against potential overflow
    if buf.len() > usize::MAX/3 {
        return None;
    }
    let n = (3*buf.len())/4;
    Some(&buf[..n])
}

godbolt

Even replacing usize::MAX/3 with any non-zero small number (even 1) does not result in removal of the bound check.

This behavior can be reproduced on current Nightly and previous stable compiler versions.

Activity

  1. added
    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.
    C-enhancementCategory: An issue proposing an enhancement or a PR with one.
    I-slowIssue: Problems and improvements with respect to performance of generated code.
    on Jan 13, 2021
  2. the8472 commented on Jan 13, 2021

    @the8472
    Member

    Workaround:

    pub fn foo(buf: &[u8]) -> Option<&[u8]> {
        if buf.len() > usize::MAX/3 {
            return None;
        }
        let n = (3*buf.len())/4;
        let n = std::cmp::min(n, buf.len());
        Some(&buf[..n])
    }
  3. nikic commented on Jan 13, 2021

    @nikic
    Contributor
  4. self-assigned this
    on Jan 18, 2021
  5. nikic commented on Jan 18, 2021

    @nikic
    Contributor
  6. MSxDOS commented on Mar 5, 2021

    @MSxDOS

    Fixed on the latest nightly by #81451

  7. newpavlov commented on Mar 5, 2021

    @newpavlov
    ContributorAuthor

    I confirm the fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-enhancementCategory: An issue proposing an enhancement or a PR with one.I-slowIssue: Problems and improvements with respect to performance of generated code.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions