为了检测指令集功能,我参考了两个源文件:
- 神秘的cpu_x86.cpp
- 阿格纳·福格指令集检测.cpp
如果您的操作系统支持 AVX 和其他功能,这两个文件都会告诉您如何通过 AVX2 以及 XOP、FMA3、FMA4 检测 SSE。
我习惯了 Agner 的代码(MSVC、GCC、Clang、ICC 的一个源文件),所以让我们先看一下。
以下是相关代码片段instrset_detect.cpp
用于检测 AVX:
iset = 0; // default value
int abcd[4] = {0,0,0,0}; // cpuid results
cpuid(abcd, 0); // call cpuid function 0
//....
iset = 6; // 6: SSE4.2 supported
if ((abcd[2] & (1 << 27)) == 0) return iset; // no OSXSAVE
if ((xgetbv(0) & 6) != 6) return iset; // AVX not enabled in O.S.
if ((abcd[2] & (1 << 28)) == 0) return iset; // no AVX
iset = 7; // 7: AVX supported
with xgetbv
定义为
// Define interface to xgetbv instruction
static inline int64_t xgetbv (int ctr) {
#if (defined (_MSC_FULL_VER) && _MSC_FULL_VER >= 160040000) || (defined (__INTEL_COMPILER) && __INTEL_COMPILER >= 1200) // Microsoft or Intel compiler supporting _xgetbv intrinsic
return _xgetbv(ctr); // intrinsic function for XGETBV
#elif defined(__GNUC__) // use inline assembly, Gnu/AT&T syntax
uint32_t a, d;
__asm("xgetbv" : "=a"(a),"=d"(d) : "c"(ctr) : );
return a | (uint64_t(d) << 32);
#else // #elif defined (_WIN32) // other compiler. try inline assembly with masm/intel/MS syntax
//see the source file
}
我没有包括cpuid
函数(参见源代码),我从中删除了非 GCC 内联汇编xgetbv
使答案更短。
这里是detect_OS_AVX()
来自神秘的cpu_x86.cpp
用于检测 AVX:
bool cpu_x86::detect_OS_AVX(){
// Copied from: http://stackoverflow.com/a/22521619/922184
bool avxSupported = false;
int cpuInfo[4];
cpuid(cpuInfo, 1);
bool osUsesXSAVE_XRSTORE = (cpuInfo[2] & (1 << 27)) != 0;
bool cpuAVXSuport = (cpuInfo[2] & (1 << 28)) != 0;
if (osUsesXSAVE_XRSTORE && cpuAVXSuport)
{
uint64_t xcrFeatureMask = xgetbv(_XCR_XFEATURE_ENABLED_MASK);
avxSupported = (xcrFeatureMask & 0x6) == 0x6;
}
return avxSupported;
}
神秘显然是从这个答案.
请注意,两个源文件基本上执行相同的操作:检查 OSXSAVE 位 27,检查 CPUID 中的 AVX 位 28,检查来自xgetbv
.