Rust segfaults while using SIMD

I'm new to simd in rust and while I'm trying to run below code, I get segfault.

# src/main.rs

use std::{arch::x86_64, mem::MaybeUninit};
fn main() {
    let mut f = MaybeUninit::uninit();
    unsafe {
        let a1 = x86_64::_mm256_set1_ps(10.1);
        x86_64::_mm256_store_ps(f.as_mut_ptr(), a1);
        println!("{}", f.assume_init());
        println!("Hello, world!");
    }
}

Below is how I'm running

cargo rustc -- -C target-feature=+avx -C target-feature=+sse -C target-cpu=x86-64
./target/debug/wisdom 

Running the binary on x86_64 GNU/Linux
Any help is greatly appreciated.

1 Like

Does your CPU support AVX? Try run cat /proc/cpuinfo | grep avx.

Your code doesn't include a type for f. Since the first argument of _mm256_store_ps is a *mut f32 I think the compiler deduces that f is a MaybeUninit<f32>. Not only does it not have enough space, it isn't aligned (and _mm256_store_ps needs an aligned address). Try

use std::{arch::x86_64, mem::MaybeUninit};
#[derive(Debug)]
#[repr(C, align(32))]
struct V8([f32; 8]);

fn main() {
    let mut f: MaybeUninit<V8> = MaybeUninit::uninit();
    unsafe {
        let a1 = x86_64::_mm256_set1_ps(10.1);
        x86_64::_mm256_store_ps(f.as_mut_ptr() as *mut f32, a1);
        println!("{:?}", f.assume_init());
        println!("Hello, world!");
    }
}
6 Likes