问题
I'm still uncertain how registers are being used by the assembler
say I have a program:
int main(int rdi, int rsi, int rdx) {
rdx = rdi;
return 0;
}
Would this in assembly be translated into:
movq %rdx, %rdi
ret rax;
I'm new to AT&T and have hard time predicting when a certain register will be used. Looking at this chart from Computer Systems - A programmer's perspective, third edition, R.E. Bryant and D. R. O'Hallaron:
charter
回答1:
Is it certain in which register arguments and variables are stored?
Only at entry and exit of a function.
There is no guarantee as to what registers will be used within a function, even for variables which are parameters to the function. Compilers can (and often will) move variables around between registers to optimize register/stack usage, especially on register-starved architectures like x86.
In this case, a simple assignment operation like rdx = rdi may not compile to any assembly code at all, because the compiler will simply recognize that both values can now be found in the register %rdi. Even for a more complex operation like rdx = rdi + 1, the compiler has the freedom to store the value in any register, not specifically in %rdx. (It may even store the value back to %rdi, e.g. inc %rdi, if it recognizes that the original value is never used afterwards.)
回答2:
No, it would be translated into:
mov %rdi, %rdx # move %rdi into %rdx
xor %eax, %eax # zero return value
ret # return
Of course, it's more than likely that rdx = rdi (and therefore mov %rdi, %rdx) will be removed by the compiler, because rdx is not used again.
Credit to @Jester for finding this out before me.
来源:https://stackoverflow.com/questions/57982674/is-it-certain-in-which-register-arguments-and-variables-are-stored