仅翻译部分常用,原文地址(Gcc手册)https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#Extended-Asm
0.格式asm [volatile] ( AssemblerTemplate
: OutputOperands
[ : InputOperands
[ : Clobbers ] ])
asm [volatile] goto ( AssemblerTemplate
:
: InputOperands
: Clobbers
: GotoLabels)
在使用-ansi或-std选项时,使用__asm__代替asm
1.参数介绍
AssemblerTemplate
汇编代码,是一系列汇编代码的文本
This is a literal string that is the template for the assembler code. It is a combination of fixed text and tokens that refer to the input, output, and goto parameters. See AssemblerTemplate.
OutputOperands
输出变量列表,为空时保留:,输出
A comma-separated list of the C variables modified by the instructions in the AssemblerTemplate. An empty list is permitted. See OutputOperands.
InputOperands
输入变量,可为空
A comma-separated list of C expressions read by the instructions in the AssemblerTemplate. An empty list is permitted. See InputOperands.
Clobbers
汇编代码使用到的寄存器列表,除了已经被列为输出的
A comma-separated list of registers or other values changed by the AssemblerTemplate, beyond those listed as outputs. An empty list is permitted. See Clobbers and Scratch Registers.
GotoLabels
Goto标志
When you are using the goto form of asm, this section contains the list of all C labels to which the code in the AssemblerTemplate may jump. See GotoLabels.
asm statements may not perform jumps into other asm statements, only to the listed GotoLabels. GCC’s optimizers do not know about other jumps; therefore they cannot take account of them when deciding how to optimize.
2.remarks
汇编代码中使用到的变量有两种表示方式
%n n为在变量列表中的位置(常用)
%[别名] 别名需要在变量前声明
举例
int src = 1;
int dst;
asm ("mov %1, %0\n\t"
"add $1, %0"
: "=r" (dst)
: "r" (src));
printf("%d\n", dst);
这段代码把src的值复制到dst
两种方式转换举例
uint32_t Mask = 1234;
uint32_t Index;
asm ("bsfl %1, %0"
: "=r" (Index)
: "r" (Mask)
: "cc");
另一种方式
uint32_t Mask = 1234;
uint32_t Index;
asm ("bsfl %[aMask], %[aIndex]"
: [aIndex] "=r" (Index)
: [aMask] "r" (Mask)
: "cc");
3.InputOperands和OutputOperands
OutputOperands必须以=或+开头,后接可能存放的位置和(变量名)
InputOperands只写可能存放的位置和(变量名)
=开头表示只输出(只写),+开头表示既输出也读取(读写)
常用的存放位置表示
r 寄存器
m 内存