diff options
| author | bors <bors@rust-lang.org> | 2021-03-28 03:51:22 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2021-03-28 03:51:22 +0000 |
| commit | 1df20569dd07d91ed270ea9cfc2dbb9f56700703 (patch) | |
| tree | 7bfa02c3ae5addd0148397f4ff82bdab22d91ef1 | |
| parent | 3bfc85149e9620b029fd5c85b02abcbf7ab1a64e (diff) | |
| parent | c9d04c2b238dc5ab51bd8a92c41ba17bb5b00ed7 (diff) | |
| download | rust-1df20569dd07d91ed270ea9cfc2dbb9f56700703.tar.gz rust-1df20569dd07d91ed270ea9cfc2dbb9f56700703.zip | |
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.
| -rw-r--r-- | library/core/src/slice/mod.rs | 2 | ||||
| -rw-r--r-- | src/test/codegen/binary-search-index-no-bound-check.rs | 19 |
2 files changed, 21 insertions, 0 deletions
diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 1e9e9c24a45..d7a28c8d08f 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -2204,6 +2204,8 @@ impl<T> [T] { } else if cmp == Greater { right = mid; } else { + // SAFETY: same as the `get_unchecked` above + unsafe { crate::intrinsics::assume(mid < self.len()) }; return Ok(mid); } diff --git a/src/test/codegen/binary-search-index-no-bound-check.rs b/src/test/codegen/binary-search-index-no-bound-check.rs new file mode 100644 index 00000000000..110d1d55626 --- /dev/null +++ b/src/test/codegen/binary-search-index-no-bound-check.rs @@ -0,0 +1,19 @@ +// 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 + } +} |
