如何自动矢量化基于范围的循环?

qua*_*ant 6 c++ vectorization visual-studio-2013

类似的问题发布在SO上,因为g ++相当模糊,所以我想我会发布一个VC++ 12/VS2013的具体示例,我们希望能够得到答案.

交叉链接: g ++,基于范围和矢量化

MSDN给出以下作为可以向量化的循环的示例:

for (int i=0; i<1000; ++i)
{       
    A[i] = A[i] + 1;
}
Run Code Online (Sandbox Code Playgroud)

(http://msdn.microsoft.com/en-us/library/vstudio/jj658585.aspx)

这是我对上面的基于范围的模拟的版本,c风格的怪物,以及类似的循环使用std::for_each.我用/ Qvec-report:2标志编译并添加编译器消息作为注释:

#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> vec(1000, 1);

    // simple range-based for loop
    {
        for (int& elem : vec)
        {
            elem = elem + 1;
        }
    } // info C5002 : loop not vectorized due to reason '1304'

    // c-style iteration
    {
        int * begin = vec.data();
        int * end = begin + vec.size();

        for (int* it = begin; it != end; ++it)
        {
            *it = *it + 1;
        }
    } // info C5001: loop vectorized

    // for_each iteration
    {
        std::for_each(vec.begin(), vec.end(), [](int& elem)
        {
            elem = elem + 1;
        });
    } // (no compiler message provided)

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

只有c风格的循环才能被矢量化.根据MSDN文档,原因1304如下:

1304:循环包括具有不同大小的分配.

它给出了以下作为触发1304消息的代码示例:

void code_1304(int *A, short *B)
{
    // Code 1304 is emitted when the compiler detects
    // different sized statements in the loop body.
    // In this case, there is an 32-bit statement and a
    // 16-bit statement.

    // In cases like this consider splitting the loop into loops to 
    // maximize vector register utilization.

    for (int i=0; i<1000; ++i)
    {
        A[i] = A[i] + 1;
        B[i] = B[i] + 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

我不是专家,但我看不出这种关系.这只是错误的报道吗?我注意到我的基于范围的循环都没有在我的实际程序中进行矢量化.是什么赋予了?

(如果这是有缺陷的行为我正在运行VS2013专业版12.0.21005.1 REL)

编辑:错误报告发布:https://connect.microsoft.com/VisualStudio/feedback/details/807826/range-based-for-loops-are-not-vectorized

qua*_*ant 7

在这里发布错误报告:

https://connect.microsoft.com/VisualStudio/feedback/details/807826/range-based-for-loops-are-not-vectorized

响应:

嗨,谢谢你的报道.

矢量化基于范围的循环代码是我们积极做得更好的事情.我们将解决这个问题,并在将来的编译器版本中为其他C++语言和库特性启用自动矢量化.

原因代码1304(在x64上)和原因代码1301(在x86上)的发射是编译器内部的伪像.对于这个特定代码,细节并不重要.

谢谢你的报道!我正在关闭此MSConnect项目.如果您还有其他需要,请随时回复.

Eric Brumer Microsoft Visual C++团队