提交 1df20569 编写于 作者: B bors

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.
......@@ -2204,6 +2204,8 @@ pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
} else if cmp == Greater {
right = mid;
} else {
// SAFETY: same as the `get_unchecked` above
unsafe { crate::intrinsics::assume(mid < self.len()) };
return Ok(mid);
}
......
// min-llvm-version: 11.0.0
// compile-flags: -O
// ignore-debug: the debug assertions get in the way
#![crate_type = "lib"]
// Make sure no bounds checks are emitted when slicing or indexing
// with an index from `binary_search`.
// CHECK-LABEL: @binary_search_index_no_bounds_check
#[no_mangle]
pub fn binary_search_index_no_bounds_check(s: &[u8]) -> u8 {
// CHECK-NOT: panic
// CHECK-NOT: slice_index_len_fail
if let Ok(idx) = s.binary_search(&b'\\') {
s[idx]
} else {
42
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册