So I'm trying to learn a little bit of assembly, because I need it for Computer Architecture class. I wrote a few programs, like printing the Fibonacci sequence.
I recognized that whenever I write a function I use those 3 lines (as I learned from comparing assembly code generated from gcc
to its C
equivalent):
pushq %rbp
movq %rsp, %rbp
subq $16, %rsp
I have 2 questions about it:
%rbp
? Isn't it simpler to use %rsp
, as its contents are moved to %rbp
on the 2nd line?%rsp
? I mean it's not always 16
, when I was printf
ing like 7 or 8 variables, then I would subtract 24
or 28
.I use Manjaro 64 bit on a Virtual Machine (4 GB RAM), Intel 64 bit processor
rbp
is the frame pointer on x86_64. In your generated code, it gets a snapshot of the stack pointer (rsp
) so that when adjustments are made to rsp
(i.e. reserving space for local variables or push
ing values on to the stack), local variables and function parameters are still accessible from a constant offset from rbp
.
A lot of compilers offer frame pointer omission as an optimization option; this will make the generated assembly code access variables relative to rsp
instead and free up rbp
as another general purpose register for use in functions.
In the case of GCC, which I'm guessing you're using from the AT&T assembler syntax, that switch is -fomit-frame-pointer
. Try compiling your code with that switch and see what assembly code you get. You will probably notice that when accessing values relative to rsp
instead of rbp
, the offset from the pointer varies throughout the function.