Repository navigation
Closed
Labels
A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.Area: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.A-codegenArea: Code generationArea: Code generationC-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchCategory: An issue highlighting optimization opportunities or PRs implementing suchI-slowIssue: Problems and improvements with respect to performance of generated code.Issue: Problems and improvements with respect to performance of generated code.
Description
Indexing slice with (Bound<usize>, Bound<usize>) may not get optimized property even with inline attribute.
Full compiler explorer: https://godbolt.org/z/96eoPsaTj
Simplest case
pub mod bounds_indexer {
use std::collections::Bound;
pub fn test(buf: &[u8]) -> Option<&[u8]> {
if buf.len() < 4 {
None
} else {
Some(&buf[(Bound::Included(4), Bound::Unbounded)])
}
}
}Original case I initially working on, with impl RangeBounds
pub mod bounds_indexer_with_range_bounds {
// possible with stable
use std::ops::RangeBounds;
pub fn test(buf: &[u8]) -> Option<&[u8]> {
if buf.len() < 4 { None } else { Some(index(buf, 4..)) }
}
//#[inline(always)] // regardless. It looks rustc will inline this function without attribute
fn index(buf: &[u8], range: impl RangeBounds<usize>) -> &[u8] {
&buf[(range.start_bound().map(|x| *x), range.end_bound().map(|x| *x))]
}
}Other complex cases with several ways to construct (Bound, Bound)
#![cfg_attr(feature="nightly", feature(range_into_bounds))]
#[cfg(feature="nightly")]
pub mod bounds_indexer_with_into_range_bounds {
// nigltly only requires #![feature(range_into_bounds)]
use std::ops::IntoBounds;
pub fn test(buf: &[u8]) -> Option<&[u8]> {
if buf.len() < 4 { None } else { Some(index(buf, 4..)) }
}
//#[inline(always)] // regardless. It looks rustc will inline this function without attribute
fn index(buf: &[u8], range: impl IntoBounds<usize>) -> &[u8] {
&buf[range.into_bounds()]
}
}
// Following is optimized and does not introduce bounds check if none of above two are not compiled.
// If either or both of above cases are compiled, `<(Bound<usize>, Bound<usize>) as SliceIndex<[u8]>>::index`
// will be called and bounds check will be ran in `SliceIndex::index`
pub mod bounds_indexer {
use std::collections::Bound;
pub fn test(buf: &[u8]) -> Option<&[u8]> {
if buf.len() < 4 {
None
} else {
Some(&buf[(Bound::Included(4), Bound::Unbounded)])
}
}
}Following two cases get optimized out.
pub mod bounds_indexer_with_range_bounds_manually_mapped {
use std::collections::Bound;
use std::ops::RangeBounds;
pub fn test(buf: &[u8]) -> Option<&[u8]> {
if buf.len() < 4 { None } else { Some(index(buf, 4..)) }
}
fn index(buf: &[u8], range: impl RangeBounds<usize>) -> &[u8] {
&buf[match range.start_bound() {
Bound::Included(&i) => i,
Bound::Excluded(i) => i.checked_add(1).expect("overflow"),
Bound::Unbounded => 0,
}..match range.end_bound() {
Bound::Included(&i) => i,
Bound::Excluded(i) => i.checked_sub(1).expect("overflow"),
Bound::Unbounded => buf.len(),
}]
}
}much shorter case
pub mod raw_index {
pub fn test(buf: &[u8]) -> Option<&[u8]> {
if buf.len() < 4 { None } else { Some(&buf[4..]) }
}
}Surprisingly, Any of bad case will be optimized if only one of bad cases are compiled.
I think rustc can optimize indexing if there is only one <(Bound<usize>, Bound<usize>) as SliceIndex<[u8]>>::index invocation and can be inlined without almost no code size cost.
What's expected
I expected to see no bounds checks are emitted for all versions
Meta
rustc --version --verbose:
Basically testing with playground and compiler explorer
rustc 1.96.0 (ac68faa20 2026-05-25)
binary: rustc
commit-hash: ac68faa20c58cbccd01ee7208bf3b6e93a7d7f96
commit-date: 2026-05-25
host: x86_64-unknown-linux-gnu
release: 1.96.0
LLVM version: 22.1.2
Compiler returned: 0
Edit hisotry
- I found the Surprising part is not specific to the implementation, but for any implementation with
<(Bound<usize>, Bound<usize>) as SliceIndex<[u8]>>::indexso modified accordingly with new fact
Metadata
Metadata
Assignees
Labels
A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.Area: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.A-codegenArea: Code generationArea: Code generationC-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchCategory: An issue highlighting optimization opportunities or PRs implementing suchI-slowIssue: Problems and improvements with respect to performance of generated code.Issue: Problems and improvements with respect to performance of generated code.
Activity
anatawa12 commentedon Jun 15, 2026
@rustbot label +C-optimization
saethlin commentedon Jun 15, 2026
That's the LLVM pass IPSCCP kicking in, cc @nikic (I don't know how many people I've complained to about this pass, but I just think it's worth noting that though the pass is super cool it causes a lot of confusion when people report missed optimizations).
saethlin commentedon Jun 16, 2026
It looks like the problem is that
into_slice_rangeisn't inlined because it contains 4 separate calls to a#[inline(never)]function which cannot be merged together. The lazy way out of this is to just stick#[inline(always)]ontointo_slice_range, which does work but I always worry about collateral damage. And I think the panic messages from those calls are probably not that helpful anyway? It doesn't even have#[track_caller]so I doubt anyone is actually happy with its panic messages.nikic commentedon Jun 16, 2026
We could also try to make cost modelling for inlining smarter in LLVM, by trying to do constant folding for this kind of "memory stored directly before call and loaded directly at the start of the function" case.
[-]bounds check may not be properly elminated with (Bound<usize>, Bound<usize>) indexer but elminated with some cases[/-][+]bounds check may not be properly elminated with (Bound<usize>, Bound<usize>) indexer but eliminated with some cases[/+][-]bounds check may not be properly elminated with (Bound<usize>, Bound<usize>) indexer but eliminated with some cases[/-][+]bounds check may not be properly eliminated with (Bound<usize>, Bound<usize>) indexer but eliminated with some cases[/+][-]bounds check may not be properly eliminated with (Bound<usize>, Bound<usize>) indexer but eliminated with some cases[/-][+]Bounds check may not be properly eliminated with (Bound<usize>, Bound<usize>) indexer but eliminated with some cases[/+]Rollup merge of rust-lang#157947 - saethlin:into_slice_range, r=dingx…
Unrolled build for #157947 in rollup 162707