1

I am using the compiler explorer (https://godbolt.org/) with default compiler settings (x86-64 gcc 6.3). The following code

int foo(int num) {
    int a, b, c;
    a = 1;
    b = 2; 
    c = 3;
}

generates the assembly

foo(int):
            push    rbp
            mov     rbp, rsp
            mov     DWORD PTR [rbp-20], edi
            mov     DWORD PTR [rbp-4], 1
            mov     DWORD PTR [rbp-8], 2
            mov     DWORD PTR [rbp-12], 3
            nop
            pop     rbp
            ret

It appears the stack pointer register rsp is never modified. Why is this? I thought local variables were pushed onto the stack, and that rsp would subsequently be modified (e.g. https://en.wikibooks.org/wiki/X86_Disassembly/Functions_and_Stack_Frames).

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
Colin
  • 101
  • 1
  • 5
  • 3
    That's using the so-called red zone (128 bytes you can use without allocation) – Jester Apr 15 '17 at 19:02
  • 2
    This is because you are likely on Linux. On 64-bit Linux there is a [RED ZONE](https://en.wikipedia.org/wiki/Red_zone_(computing)) in user space code that protects the 128 bytes under the current value from _RSP_ from modification by asynchronous events (signals etc). Because of that you don't need to allocate space if you need <= 128 bytes AND your function doesn't call other functions. Calling another function puts the return address on the stack and that would potentially clobber data stored in the red zone. – Michael Petch Apr 15 '17 at 19:03
  • Ah, ok. Thank you! – Colin Apr 15 '17 at 19:04
  • You might also want to keep in mind that there are situations where the stack might not be used for locals: optimizations might keep locals in registers or even omit them altogether (which would happen in this case if the function is compiled with optimization enabled). An interesting example is the ia64 which has a register architecture designed to keep locals in registers, spilling them to memory only when the stack frames get too deep. See https://blogs.msdn.microsoft.com/oldnewthing/20050421-28/?p=35833 – Michael Burr Apr 15 '17 at 19:14

0 Answers0