I wrote a simple program containing inline assembly code. My code simply adds the variables a and b and returns the result in b.
What is confusing me is why the code below generates this instruction movl 28(%esp), %ecx.
I don't fully undertand the roles the modifiers + and = play in the input and output lists. So it would be appreciated if you could shed some light on this.
#include <cstdio>
int main( int argc , char ** argv )
{
int a = 2, b = 7;
__asm__
(
"addl %1,%0;"
:"+r"(b)
:"r"(a), "r"(b)
);
printf("b = %d\n",b);
return 0;
}
movl $2, 24(%esp) movl $7, 28(%esp) movl 24(%esp), %edx movl 28(%esp), %ecx movl 28(%esp), %eax addl %edx,%eax movl %eax, 28(%esp)
What I am going to show next is wrong. But it is for the sake of my better understanding about what is going on in GCC.
Ok, now I changed from +r to =r. And this is the assembly code GCC generates.
#include <cstdio>
int main( int argc , char ** argv )
{
int a = 2, b = 7;
__asm__
(
"addl %1,%0;"
:"=r"(b)
:"r"(a), "r"(b)
);
printf("b = %d\n",b);
return 0;
}
movl $2, 24(%esp) movl $7, 28(%esp) movl 24(%esp), %eax movl 28(%esp), %edx addl %eax,%eax; movl %eax, 28(%esp)
Now the output is 4, which is wrong. My question is why with "=r" GCC decided to reuse the register eax for b as shown in this instruction addl %eax,%eax;