3 ms·
Hand-rolling is unnecessary and error-prone. It is better to leverage the compiler. There are a couple relevant GCC flags: -mcpu and -mtune. The -mcpu flag wil
by klodolph 7y ago
Hand-rolling is unnecessary and error-prone. It is better to leverage the compiler.
There are a couple relevant GCC flags: -mcpu and -mtune. The -mcpu flag will specify which features it is allowed to assume are present. The blog post is using SSE instructions, I’m thinking SSE2 but that’s just from memory, and these days most people consider it eccentric to try and support CPUs without SSE2.
There are a couple ways you can do the feature testing in your own program. You can make multiple copies of the function and compile them with different CPU targets, and then use something like
void xor512a_avx(...) __attribute__((target("avx"))) { ... }
if (__builtin_cpu_supports("avx")) {
xor512a_avx(dst, src);
}
Alternatively, you can use something called function multiversioning, which will write the branch for you. I think this feature is present in both GCC and Clang.
Also note that there are some unusual edge cases you may not have considered with feature detection. There’s a strong case to say that instructions like CPUID are the wrong way to go about it, and you should do things like use sysctl() on macOS. The risks in using CPUID are a bit esoteric in my opinion, though.