2

I have been looking at disassembled c recently (all compiled with gcc). I noticed every function begins with

push rbp 
mov rbp, rsp

And ends with

pop rbp

Or the equivalent registers. I’ve heard this referee to as setting up a new stack for the function, but how does this actually benefit the code. Wouldn’t the code work exactly the same without it, as rbp can’t be accessed or chanced in c (without inline assembly) and pointers and variables are all offsets from rsp

brenden
  • 574
  • 3
  • 16
  • How does it benefit the code? It doesn't. That's why gcc only does it if you don't turn optimization on. – Petr Skocik May 28 '18 at 16:12
  • new stack FRAME for the function. – Martin James May 28 '18 at 16:12
  • Did you compile it without optimizations? If that is true the compiler tries to represent the code exactly the way you typed it in C. – Petar Velev May 28 '18 at 16:13
  • Does [this](https://stackoverflow.com/q/41912684/1971013) help? – meaning-matters May 28 '18 at 16:13
  • @PSkocik but if it has no benefit, it’s just extra instructions, so why would it ever need to be there – brenden May 28 '18 at 16:14
  • Debuggability, that's why. – n. m. could be an AI May 28 '18 at 16:15
  • @meaning-matters I swear I did google it, but maybe I’m just bad at formulating questions – brenden May 28 '18 at 16:16
  • @BElgy Take a look at https://stackoverflow.com/questions/14666665/trying-to-understand-gcc-option-fomit-frame-pointer or the gcc documentation ofthe `-fomit-frame-pointer` option. It looks like the answers is something along the lines: debuggers, weird machines, and histerical reasons. – Petr Skocik May 28 '18 at 16:17
  • I searched for "rbp register" and the above link was the top result. – meaning-matters May 28 '18 at 16:23
  • I think [this comment](https://stackoverflow.com/questions/14666665/trying-to-understand-gcc-option-fomit-frame-pointer#comment20499949_14666730) in @PSkocik 's reference is the best answer to when is a a new frame needed. There are only a few possibilities to make a function complex enough that a real benefit in the ease of compilation and code generated is preferred to performance. It doesn't answer this question though. – kabanus May 28 '18 at 16:23

1 Answers1

1

During the execution of the function, the stack pointer may vary as it is used for temporary storage during calculations. You must however still be able to access the function parameters, which are offsets from the base pointer (rbp).

Thomas Jager
  • 4,836
  • 2
  • 16
  • 30