使用内部函数时程序崩溃

Program crashes when using intrinsics

本文关键字:程序 崩溃 内部函数      更新时间:2023-10-16

我是使用内部函数的新手,所以我不知道我的程序为什么会崩溃。我可以构建程序,但当我运行它时,我只会看到"programname.exe已停止工作"窗口。

#include "stdafx.h"
#include <stdio.h>
#include <Windows.h>
#include <intrin.h>
int _tmain(int argc, _TCHAR* argv[])
{
    const int N = 128;
    float x[N], y[N];
    float sum = 0;
    for (int i = 0; i < N; i++)
    {
        x[i] = rand() >> 1;
        y[i] = rand() >> 1;
    }
    float* ptrx = x;
    float* ptry = y;
    __m128 x1;
    x1 = _mm_load_ps(ptrx);
    return 0;
}

如果我注释掉'x1=_mm_load_ps(ptrx);'行,程序能够运行,所以这就是导致崩溃的原因。

以下是构建解决方案时的输出。。。

1>------ Rebuild All started: Project: intrins2, Configuration: Debug Win32 ------
1>  stdafx.cpp
1>  intrins2.cpp
1>c:...visual studio 2013projectsintrins2intrins2intrins2.cpp(20): warning C4244: '=' : conversion from 'int' to 'float', possible loss of data
1>c:...visual studio 2013projectsintrins2intrins2intrins2.cpp(21): warning C4244: '=' : conversion from 'int' to 'float', possible loss of data
1>  intrins2.vcxproj -> c:...visual studio 2013Projectsintrins2Debugintrins2.exe
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

问题是您的"源"(数组x)没有与SSE指令所需的大小对齐。

您可以使用"未对齐"的加载指令来修复此问题,也可以使用__declspec(align(n))来修复,例如:

    float __declspec(align(16)) x[N];
    float __declspec(align(16)) y[N];

现在,您的xy数组已对齐到16个字节,并且可以从SSE指令访问[当然是4的倍数的索引]。请注意,对于采用内存参数的常规SSE指令,不允许进行未对齐的访问,因此例如_mm_max_ps要求第二个参数(按英特尔顺序,按AT&T顺序第一个)是对齐的内存位置。