Skip to content

Commit

Permalink
Auto merge of rust-lang#96596 - scottmcm:limited-calloc, r=Mark-Simul…
Browse files Browse the repository at this point in the history
…acrum

Tweak the vec-calloc runtime check to only apply to shortish-arrays

r? `@Mark-Simulacrum`

`@nbdd0121` pointed out in rust-lang#95362 (comment) that LLVM currently doesn't constant-fold the `IsZero` check for long arrays, so that seems like a reasonable justification for limiting it.

It appears that it's based on length, not byte size, (https://godbolt.org/z/4s48Y81dP), so that's what I used in the PR.  Maybe it's a ["the number of inlining shall be three"](https://youtu.be/s4wnuiCwTGU?t=320) sort of situation.

Certainly there's more that could be done here -- that generated code that checks long arrays byte-by-byte is highly suboptimal, for example -- but this is an easy, low-risk tweak.
  • Loading branch information
bors committed May 2, 2022
2 parents 905fd73 + 2830dbd commit 6b6c1ff
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
9 changes: 8 additions & 1 deletion library/alloc/src/vec/is_zero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,14 @@ unsafe impl<T> IsZero for *mut T {
unsafe impl<T: IsZero, const N: usize> IsZero for [T; N] {
#[inline]
fn is_zero(&self) -> bool {
self.iter().all(IsZero::is_zero)
// Because this is generated as a runtime check, it's not obvious that
// it's worth doing if the array is really long. The threshold here
// is largely arbitrary, but was picked because as of 2022-05-01 LLVM
// can const-fold the check in `vec![[0; 32]; n]` but not in
// `vec![[0; 64]; n]`: https://godbolt.org/z/WTzjzfs5b
// Feel free to tweak if you have better evidence.

N <= 32 && self.iter().all(IsZero::is_zero)
}
}

Expand Down
32 changes: 32 additions & 0 deletions src/test/codegen/vec-calloc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// compile-flags: -O
// only-x86_64
// ignore-debug

#![crate_type = "lib"]

// CHECK-LABEL: @vec_zero_scalar
#[no_mangle]
pub fn vec_zero_scalar(n: usize) -> Vec<i32> {
// CHECK-NOT: __rust_alloc(
// CHECK: __rust_alloc_zeroed(
// CHECK-NOT: __rust_alloc(
vec![0; n]
}

// CHECK-LABEL: @vec_zero_rgb48
#[no_mangle]
pub fn vec_zero_rgb48(n: usize) -> Vec<[u16; 3]> {
// CHECK-NOT: __rust_alloc(
// CHECK: __rust_alloc_zeroed(
// CHECK-NOT: __rust_alloc(
vec![[0, 0, 0]; n]
}

// CHECK-LABEL: @vec_zero_array_32
#[no_mangle]
pub fn vec_zero_array_32(n: usize) -> Vec<[i64; 32]> {
// CHECK-NOT: __rust_alloc(
// CHECK: __rust_alloc_zeroed(
// CHECK-NOT: __rust_alloc(
vec![[0_i64; 32]; n]
}

0 comments on commit 6b6c1ff

Please sign in to comment.