Skip to content

Commit 1df2056

Browse files
committed
Auto merge of #81354 - SkiFire13:binary-search-assume, r=nagisa
Instruct LLVM that binary_search returns a valid index This allows removing bound checks when the return value of `binary_search` is used to index into the slice it was call on. I also added a codegen test for this, not sure if it's the right thing to do (I didn't find anything on the dev guide), but it felt so.
2 parents 3bfc851 + c9d04c2 commit 1df2056

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

library/core/src/slice/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -2204,6 +2204,8 @@ impl<T> [T] {
22042204
} else if cmp == Greater {
22052205
right = mid;
22062206
} else {
2207+
// SAFETY: same as the `get_unchecked` above
2208+
unsafe { crate::intrinsics::assume(mid < self.len()) };
22072209
return Ok(mid);
22082210
}
22092211

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// min-llvm-version: 11.0.0
2+
// compile-flags: -O
3+
// ignore-debug: the debug assertions get in the way
4+
#![crate_type = "lib"]
5+
6+
// Make sure no bounds checks are emitted when slicing or indexing
7+
// with an index from `binary_search`.
8+
9+
// CHECK-LABEL: @binary_search_index_no_bounds_check
10+
#[no_mangle]
11+
pub fn binary_search_index_no_bounds_check(s: &[u8]) -> u8 {
12+
// CHECK-NOT: panic
13+
// CHECK-NOT: slice_index_len_fail
14+
if let Ok(idx) = s.binary_search(&b'\\') {
15+
s[idx]
16+
} else {
17+
42
18+
}
19+
}

0 commit comments

Comments
 (0)