简单了解C语言内嵌汇编

内嵌汇编有个固定格式

asm ( assembler template         /* 汇编语句 */
    : output operands                  /* 输出寄存器 */
    : input operands                   /* 输入寄存器 */
    : list of clobbered registers     //会被修改的寄存器 
    );

// 先输入  再汇编指令  再输出

cmpxchgl的描述

Compares the value in the AL, AX, EAX, or RAX register with the first operand (destination operand). If the twovalues are equal, the second operand (source operand) is loaded into the destination operand. Otherwise, thedestination operand is loaded into the AL, AX, EAX or RAX register. RAX register is available only in 64-bit mode.

(* Accumulator = AL, AX, EAX, or RAX depending on whether a byte, word, doubleword, or quadword comparison is being performed *)
TEMP ← DEST
IF accumulator = TEMP
THEN
ZF ← 1;
DEST ← SRC;
ELSE
ZF ← 0;
accumulator ← TEMP;
DEST ← TEMP;
FI;

cmpxchgl %0, %2为汇编语句,表示对第3个和第1个入参进行操作,即cmpxchgl *dest,exchange;
“=m” (dest), “=a” (old)为输出部分,将m内存的内容存到dest中,将a寄存器内容存到old;
“r” (exchange), “m” (dest), “a” (comperand)); 为输入部分,将exchange放入r寄存器,将dest放入m,将comperand放入a寄存器;

使用C语言翻译如下

int atomic_compare_and_exchange(int *dest, int exchange, int comperand) 
{
    
    
    int old = comperand;
    if ( comperand== *dest)
    {
    
    
        *dest = exchange;
    }
    else
    {
    
    
        old  = *dest;
    }
    return old;
}

常用的限制符

限制符 说明

r	通用寄存器
a	eax, ax, al
b	ebx, bx, bl
c	ecx, cx, cl
d	edx, dx, dl
S	esi, si
D	edi, di
q	寄存器:a、b、c、d
m	使用合法内存代表参数
g	任意寄存器、内存、立即数

cc  使用的指令会改变CPU的条件寄存器cc;
memory  使用的指令会修改内存

r:表示使用一个通用寄存器,由GCC在%eax/%ax/%al, %ebx/%bx/%bl, %ecx/%cx/%cl, %edx/%dx/%dl中选取一个GCC认为合适的。
a:表示使用%eax / %ax / %al
b:表示使用%ebx / %bx / %bl
c:表示使用%ecx / %cx / %cl
d:表示使用%edx / %dx / %dl
m: 表示内存地址

猜你喜欢

转载自blog.csdn.net/kq1983/article/details/114295316