mirror of
https://github.com/allankoechke/rust.git
synced 2026-12-02 09:47:57 +00:00
simplify slice::Iter[Mut]::next_chunk implementation
I verified that this doesn't pessimize codegen using the example from the
PR that inroduced the optimization of `next_chunk` (# 149131):
```rust
#![feature(iter_next_chunk)]
#[no_mangle]
pub fn simd_sum_slow(arr: &[u32]) -> u32 {
const STEP_SIZE: usize = 16;
let mut result = [0; STEP_SIZE];
let mut iter = arr.iter();
while let Ok(c) = iter.next_chunk::<STEP_SIZE>() {
for (&n, r) in c.iter().zip(result.iter_mut()) {
*r += n;
}
}
result.iter().sum()
}
```
I compiled this example with
```shell
./build/host/stage1/bin/rustc t.rs --emit=asm -O --crate-type=lib
```
Before and after this change; the only difference is the choice of the
jump instruction, which I think shouldn't make any difference:
```diff
28,29c28,29
< cmpq $64, %rsi
< jae .LBB0_2
---
> cmpq $60, %rsi
> ja .LBB0_2
```
This commit is contained in:
@@ -192,25 +192,20 @@ macro_rules! iterator {
|
||||
}
|
||||
|
||||
fn next_chunk<const N:usize>(&mut self) -> Result<[$elem; N], crate::array::IntoIter<$elem, N>> {
|
||||
if T::IS_ZST {
|
||||
if T::IS_ZST || len!(self) < N {
|
||||
return crate::array::iter_next_chunk(self);
|
||||
}
|
||||
let len = len!(self);
|
||||
if len >= N {
|
||||
// SAFETY: we are just getting an array of [T; N] and moving the pointer over a little
|
||||
let r = unsafe { self.post_inc_start(N).cast_array().$into_ref() }
|
||||
.$array_ref(); // must convert &[T; N] to [&T; N]
|
||||
|
||||
// SAFETY: the check above ensures len >= N
|
||||
unsafe {
|
||||
let r = self
|
||||
.post_inc_start(N)
|
||||
.cast_array() // NonNull<T> -> NonNull<[T; N]>
|
||||
// SAFETY: post_inc_start(N) insures we don't return overlapping `&mut`s
|
||||
.$into_ref() // NonNull<[T; N]> -> &{mut} [T; N]
|
||||
.$array_ref(); // must convert &{mut} [T; N] to [&{mut} T; N]
|
||||
|
||||
Ok(r)
|
||||
} else {
|
||||
// cant use $array_ref because theres no builtin for &mut [MU<T>; N] -> [&mut MU<T>; N]
|
||||
// cant use copy_nonoverlapping as the $elem is of type &{mut} T instead of T
|
||||
let mut a = [const { crate::mem::MaybeUninit::<$elem>::uninit() }; N];
|
||||
for into in (&mut a).into_iter().take(len) {
|
||||
// SAFETY: take(n) limits to remainder (slice produces worse codegen)
|
||||
into.write(unsafe { self.post_inc_start(1).$into_ref() });
|
||||
}
|
||||
// SAFETY: we just initialized elements 0..len
|
||||
unsafe { Err(crate::array::IntoIter::new_unchecked(a, 0..len)) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user