Calling assembly in GCC?
#include <stdlib.h>
static inline uint
xchg(volatile unsigned int *addr, unsigned int newval)
{
uint result;
asm volatile("lock; xchgl %0, %1" : "+m" (*addr), "=a" (result) : "1" (newval) : "cc");
return result;
}
Can some one tell me what this code does exactly? I 开发者_StackOverflowmean I have an idea or the parts of this command. "1" newval is the input, "=a" is to flush out its previous value and update it. "m" is for the memory operation but I am confused about the functionality of this function. What does the "+m" sign do? Does this function do something like m=a; m = newval; return a
=
and +
are constraint modifiers.
http://gcc.gnu.org/onlinedocs/gcc/Modifiers.html#Modifiers
`=' Means that this operand is write-only for this instruction: the previous value is discarded and replaced by output data.
`+' Means that this operand is both read and written by the instruction.
Basic constrains are here
http://gcc.gnu.org/onlinedocs/gcc/Simple-Constraints.html#Simple-Constraints
m
A memory operand is allowed, with any kind of address that the machine supports in general...
1
.. An operand that matches the specified operand number is allowed. If a digit is used together with letters within the same alternative, the digit should come last.
'a' is i386 specific
http://gcc.gnu.org/onlinedocs/gcc/Machine-Constraints.html#Machine-Constraints
a The a (eax) register.
there are constraints
. They are not variables, but modes, like the "w", "r", "r+" of fopen()
some of them are described here
http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html
part 6. More about constraints.
And the last "cc" is clobber.
If our instruction can alter the condition code register, we have to add
"cc"
to clobber list.
Full format of asm is
asm ( assembler template
: output operands /* optional */
: input operands /* optional */
: list of clobbered registers /* optional */
);
精彩评论