用SIMD命令编程时出现分段错误

segmentation fault in programm with SIMD commands

本文关键字:分段 错误 SIMD 命令 编程      更新时间:2023-10-16

这是怎么回事?当我运行程序时,它说,Segmentation Fault (Core Dumped)。我使用了一些SIMD命令。

float function ( Point p1, Point p2, int dim )
{
      int k;
      float result=0.0;
      float *p3;
      p3 = (float*) malloc (16);
      k=dim%4;
      __m128 *v_p1 = (__m128*)p1.coord;
      __m128 *v_p2 = (__m128*)p2.coord;
      __m128 *v_p3 = (__m128*)p3;
      for (int i=0; i<dim/4; i++){
             *v_p3= _mm_sub_ps(*v_p1,*v_p2);
      }
      for(int i=0; i<dim; i++){
             result+=p3[i];
      }
      return(result);
}

任何SIMD _ps指令都需要16字节对齐的数据。从我可以告诉至少p3没有正确对齐,所以你肯定会得到一个seg fault,如果你不使用正确对齐的数据。我不能自己运行这段代码,但如果你按值分配给__m128变量,你应该没问题,因为它们应该正确对齐:

  __m128 v_p1 = _mm_set_ps( ... ); // not sure of the argument 
  __m128 v_p2 = _mm_set_ps( ... ); // not sure of the argument 
  __m128 v_p3 = _mm_set_ps1(p3) ;

正如注释所说,当使用SIMD intrinsic时,内存中的数据必须对齐(在此特殊情况下,16字节对齐),如果您在UNIX系统中尝试使用posix_memalign()分配数据:

http://pubs.opengroup.org/onlinepubs/009695399/functions/posix_memalign.html