动态对齐的多维数组不被 GCC 编译器视为对齐

Dynamically aligned multi-dimensional array is not regarded as aligned by the GCC compiler

本文关键字:对齐 GCC 编译器 数组 动态      更新时间:2023-10-16

我是循环矢量化的新手。但是我无法通过搜索互联网几天来找到我简单任务的答案。

我有一个二维数组,它在第一维中有 4 个双精度。我想矢量化这 4 个元素。如果我在下面的代码中使用静态数组 gas[32768][4],并使用

g++ -O2 -ftree-vectorize -ftree-vectorizer-verbose=7 stack.cpp

它显示

vect_model_load_cost:对齐。

对于底部 K 循环。但是,如果我使用如下所示的动态数组,它会显示

矢量化未对齐的访问

但是,我认为我的动态数组确实是对齐的。我想知道如何强制编译器知道数组确实对齐了。

我也尝试了结构数组而不是二维数组。同样,如果它是一个静态数组,则可以。但是,如果它是使用>new 动态分配的结构数组,则编译器将无法识别对齐方式。

#include <iostream>
#include <time.h>
#include <new>
#include <malloc.h>
#include <stdio.h>
int main()
{
   clock_t t;
   double temp[4];
   int ng=32768;
   int i, j, k;
   double **gas;
   gas = (double **)memalign(__BIGGEST_ALIGNMENT__,32768*sizeof(double*));
   gas[0] = (double *)memalign(__BIGGEST_ALIGNMENT__,32768*4*sizeof(double));
   for (i=0; i<32768; i++){
     gas[i] = (double *)((unsigned char *)gas[0] + i*4*sizeof(double));
   }
/*
 replace above 7 lines with static assignment: double gas[32768][4]; then the compiler recoganize that the data are aligned
*/
   for (i=0; i<ng; i++){
     for (k=0; k<4; k++){
       gas[i][k]=i*1.0;
     }
   }
   for (j=0; j<10000; j++){
     for (k=0; k<4; k++){
        temp[k]=gas[j][k];
        temp[k]+=gas[j+1][k];
        temp[k]+=gas[j+2][k];
        temp[k]+=gas[j+13][k];
        temp[k]+=gas[j+14][k];
        temp[k]+=gas[j+15][k];
        temp[k]+=gas[j+16][k];
     }
   }
    std::cout<<temp[0]<<" "<<temp[1]<<" "<<temp[2]<<" "<<temp[3]<<std::endl;
}

如果你使用__builtin_assume_aligned它有效吗?请参阅 https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html 。您可以使用它来告诉编译器您的指针已充分对齐。例如类似的东西


double *tmp = memalign (16, some_size);
double *ptr = __builtin_assume_aligned(tmp, 16);
// Now *ptr points to tmp and the compiler should be able to assume that *ptr 
// is 16 byte aligned.