Potential Compiler Optimization Issue with &Vec<*const T> vs &[*const T]

Thanks for your response.

Indeed, it is quite common for a function to indirectly have a signature &Vec<T> instead of &[T] through nested structure:

pub struct NestedVec{
    other_field:i32,
    arr:Vec<NestedVecInner>
}

pub struct NestedVecInner{
    other_field:&'static str,
    ptr:*const i32
}


#[no_mangle]
unsafe fn per_pos_add_2(nested:&NestedVec,b:&mut [*mut i32]){
    let a=&nested.arr;
    for i in 0..a.len(){
        for j in 0..b.len(){
            let v=a.get_unchecked(i).ptr.add(j);
            *b.get_unchecked_mut(i).add(j)+=*v;
        }
    }
}

Godbolt.

This situation is quite typical in daily work, and developers cannot optimize their code to adapt rustc without breaking changes. Moreover, Clang can vectorize this function call properly.


Update: core::hint::unreachable_unchecked() and is_aligned() did not work.

6 Likes