Skip to content

Add unreachable hints for length getters? #106737

Open
@newpavlov

Description

@newpavlov

As discussed in this thread, Rust does not provide LLVM any information about possible lengths of slices, vectors, and other types. In some cases it prevents LLVM from applying optimizations since it has to account for invalid lengths.

I suggest updating length getters of slice-like types to something like this:

#[inline]
pub const fn len(&self) -> usize {
    let len = ...;
    let size = core::mem::size_of::<T>();
    // on most arches we can use `isize::MAX as usize`
    // instead of `usize::MAX`, but IIRC not everywhere
    if size != 0 && len > usize::MAX / size {
        unsafe { core::hint::unreachable_unchecked() }
    }
    len
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchT-libsRelevant to the library 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