我正在尝试使用需要特定处理器架构的 x86 ASM 功能。我了解调用“ CPUID 标准函数 01H ”后需要检查特定位。下面是来自CPUID Wikipedia页面的用于调用 CPUID的C实现:
#include <stdio.h>
int main() {
int i;
unsigned int index = 0;
unsigned int regs[4];
int sum;
__asm__ __volatile__(
#if defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64)
"pushq %%rbx \n\t" /* save %rbx */
#else
"pushl %%ebx \n\t" /* save %ebx */
#endif
"cpuid \n\t"
"movl %%ebx ,%[ebx] \n\t" /* write the result into output var */
#if defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64)
"popq %%rbx \n\t"
#else
"popl %%ebx \n\t"
#endif
: "=a"(regs[0]), [ebx] "=r"(regs[1]), "=c"(regs[2]), "=d"(regs[3])
: "a"(index));
for (i=4; i<8; i++) {
printf("%c" ,((char *)regs)[i]);
}
for (i=12; i<16; i++) {
printf("%c" ,((char *)regs)[i]);
}
for (i=8; i<12; i++) {
printf("%c" ,((char *)regs)[i]);
}
printf("\n");
}
虽然Linux 内核使用以下函数:
static inline void native_cpuid(unsigned int *eax, unsigned int *ebx,
unsigned int *ecx, unsigned int *edx)
{
/* ecx is often an input as well as an output. */
asm volatile("cpuid"
: "=a" (*eax),
"=b" (*ebx),
"=c" (*ecx),
"=d" (*edx)
: "0" (*eax), "2" (*ecx));
}
哪一个更好?其他他们本质上是等价的?