问题描述
我正在为 x64 和 neon 开发 C++ 内在包装器。我希望我的函数是 constexpr。我的动机类似于 Constexpr and SSE intrinsics,但 #pragma omp simd 和内在函数在 constexpr 函数中可能不受编译器 (GCC) 的支持。下面的代码只是一个演示(自动矢量化对于加法来说已经足够了)。
struct FA{
float c[4];
};
inline constexpr FA add(FA a,FA b){
FA result{};
#pragma omp simd // clang error: statement not allowed in constexpr function
for(int i = 0; i < 4; i++){ // GCC error: uninitialized variable 'i' in 'constexpr' function
result.c[i] = b.c[i] + a.c[i];
}
return result;
}
struct FA2{
__m128 c;
};
inline constexpr FA2 add2(FA2 a,FA2 b){
FA2 result{};
result.c = _mm_add_ps(a.c,b.c); // GCC error: call to non-'constexpr' function '__m128 _mm_add_ps(__m128,__m128)'
return result; // fine with clang
}
无论如何,我必须提供参考 C++ 代码以实现可移植性。有没有一种代码高效的方式让编译器在编译时使用参考代码?
f(){
if(){
// constexpr version
}else{
// intrinsic version
}
}
它应该适用于所有支持 omp、内部函数和 C++20 的编译器。
解决方法
使用 std::is_constant_evaluated,您可以得到您想要的:
#include <type_traits>
struct FA{
float c[4];
};
// Just for the sake of the example. Makes for nice-looking assembly.
extern FA add_parallel(FA a,FA b);
constexpr FA add(FA a,FA b) {
if (std::is_constant_evaluated()) {
// do it in a constexpr-friendly manner
FA result{};
for(int i = 0; i < 4; i++) {
result.c[i] = b.c[i] + a.c[i];
}
return result;
} else {
// can be anything that's not constexpr-friendly.
return add_parallel(a,b);
}
}
constexpr FA at_compile_time = add(FA{1,2,3,4},FA{5,6,7,8});
FA at_runtime(FA a) {
return add(a,at_compile_time);
}
在 Godbolt 上看到:https://gcc.godbolt.org/z/szhWKs3ec