如何用普通的 cpp 文件编译 Linux 和 link 中的 ISPC 代码?

How can I compile ISPC code in Linux and link it with normal cpp file?

我想编译一个ispc程序。我正在尝试为他们的示例程序之一生成可执行文件。

我有 simple.cpp 以下内容

#include <stdio.h>
#include <stdlib.h>

// Include the header file that the ispc compiler generates
#include "simple_ispc.h"
using namespace ispc;

int main() {
    float vin[16], vout[16];

    // Initialize input buffer
    for (int i = 0; i < 16; ++i)
        vin[i] = (float)i;

    // Call simple() function from simple.ispc file
    simple(vin, vout, 16);

    // Print results
    for (int i = 0; i < 16; ++i)
        printf("%d: simple(%f) = %f\n", i, vin[i], vout[i]);

    return 0;
}

我有 simple.ispc 以下内容

export void simple(uniform float vin[], uniform float vout[],
                   uniform int count) {
    foreach (index = 0 ... count) {
        // Load the appropriate input value for this program instance.
        float v = vin[index];

        // Do an arbitrary little computation, but at least make the
        // computation dependent on the value being processed
        if (v < 3.)
            v = v * v;
        else
            v = sqrt(v);

        // And write the result to the output array.
        vout[index] = v;
    }
}

我可以使用 cmake https://github.com/ispc/ispc/tree/main/examples/cpu/simple 来获取可执行文件,但我想知道我需要对 运行 simple.cpp 文件执行的原始命令。有人可以告诉我如何用 ispc 编译和 运行 simple.cpp 文件吗?

根据 the ISPC User's guide,您可以在终端中使用 ispc 作为命令:

ispc simple.ispc -o simple.o

这会生成一个目标文件 simple.o,您可以使用 g++ 等常规 C++ 编译器将其 link 到您的 simple.cpp 文件。

编辑:

编译为simple_ispc.h:

The -h flag can also be used to direct ispc to generate a C/C++ header file that includes C/C++ declarations of the C-callable ispc functions and the types passed to it.

所以你可以做类似的事情

ispc simple.ispc -h simple_ispc.h

然后

g++ simple.cpp -o executable

获取可执行文件。

首先,使用ispc编译器创建ispc头文件和目标文件

ispc --target=avx2-i32x8 simple.ispc -h simple_ispc.h -o simple_ispc.o

然后创建cpp的目标文件和link一起创建2个目标文件

g++ -c simple.cpp -o simple.o
g++ simple.o simple_ispc.o -o executable

或者在创建ispc头文件和obj文件后,在一条命令中创建可执行文件

g++ simple.cpp simple_ispc.o -o executable

此外,如果你有clang/llvm,你也可以使用它们进行编译。以下是步骤:https://ispc.github.io/faq.html#is-it-possible-to-inline-ispc-functions-in-c-c-code

// emit llvm IR
ispc --emit-llvm --target=avx2-i32x8 -h simple_ispc.h -o simple_ispc.bc simple.ispc
clang -O2 -c -emit-llvm -o simple.bc simple.cpp

// link the two IR files into a single file and run the LLVM optimizer on the result
llvm-link simple.bc simple_ispc.bc -o - | opt -O3 -o simple_opt.bc

// generate the native object file
llc -filetype=obj simple_opt.bc -o simple.o

// generate the executable
clang -o simple simple.o