2

When compiling a simple function that does not even alter the ebp register GCC still saves the value at the start of the function and then restores the same value at the end:

#add.c
int add( int a, int b )
{
  return ( a + b );
}

gcc -c -S -m32 -O3 add.c -o add.S

#add.S
    .file   "add.c"
    .text
    .p2align 4,,15
.globl add
    .type   add, @function
add:
    pushl   %ebp
    movl    %esp, %ebp
    movl    12(%ebp), %eax
    addl    8(%ebp), %eax
    popl    %ebp
    ret
    .size   add, .-add
    .ident  "GCC: (GNU) 4.4.6"
    .section        .note.GNU-stack,"",@progbits

It would seem like a simple optimisation to leave ebp untouched, calculate offsets relative to esp and save 3 instructions.

Why does GCC not do this?

Thanks,

Andrew

andypea
  • 1,343
  • 11
  • 22
  • The answers to http://stackoverflow.com/questions/5086230/is-the-gcc-insane-optimisation-level-o3-not-insane-enough?rq=1 (which popped up in the "related" list beside your question) may answer your question as well. – Dmitri Feb 07 '14 at 05:58
  • When I do this with gcc 4.8.1, I does optimize away the prologue/epilogue – twin Feb 07 '14 at 06:03
  • Hi, that question does answer mine. Is there some way to point mine over there? – andypea Feb 07 '14 at 07:00

1 Answers1

4

Tools such as debuggers and stack walkers used to expect code to have a prologue that constructed a frame pointer, and couldn't understand code that didn't have it. Over time, the restriction has been removed.

The compiler itself has no difficulty generating code without a frame pointer, and you can ask for it to be removed with -fomit-frame-pointer. I believe that recent versions of gcc (~4.8) and gcc on x86-64 omit the frame pointer by default.

gsg
  • 9,167
  • 1
  • 21
  • 23