我正在为 x64 和 neon 开发 C++ 内在包装器。我希望我的函数是 constexpr。我的动机类似于Constexpr 和 SSE 内在函数 https://stackoverflow.com/questions/51880079/constexpr-and-sse-intrinsics,但 constexpr 函数中的编译器 (GCC) 可能不支持 #pragma omp simd 和内在函数。以下代码只是一个演示(自动矢量化足以进行加法)。
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 的编译器。
Using std::is_constant_evaluated https://en.cppreference.com/w/cpp/types/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 https://gcc.godbolt.org/z/szhWKs3ec
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)