title: Is the gcc insane optimisation level (-O3) not insane enough?
body: <p>As part of answering another question, I wanted to show that the insane level of optimisation of <code>gcc</code> (<code>-O3</code>) would basically strip out any variables that weren't used in main. The code was:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  int main (void) {
     char bing[71];
     int x = 7;
     bing[0] = 11;
     return 0;
  }
  </code></pre>
  
  <p>and the <code>gcc -O3</code> output was:</p>
  
  <pre><code>    .file "qq.c"
      .text
      .p2align 4,,15
  .globl main
      .type main, @function
  main:
      pushl %ebp
      xorl %eax, %eax
      movl %esp, %ebp
      popl %ebp
      ret
      .size main, .-main
      .ident "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
      .section .note.GNU-stack,"",@progbits
  </code></pre>
  
  <p>Now I can see it's removed the local variables but there's still quite a bit of wastage in there. It seems to me that the entire:</p>
  
  <pre><code>    pushl %ebp
      xorl %eax, %eax
      movl %esp, %ebp
      popl %ebp
      ret
  </code></pre>
  
  <p>section could be replaced with the simpler:</p>
  
  <pre><code>    xorl %eax, %eax
      ret
  </code></pre>
  
  <p>Does anyone have any idea why <code>gcc</code> does not perform this optimisation? I know that would save very little for <code>main</code> itself but, if this were done with normal functions as well, the effect of unnecessarily adjusting the stack pointer in a massive loop would be considerable.</p>
  
  <p>The command used to generate the assembly was:</p>
  
  <pre><code>gcc -O3 -std=c99 -S qq.c
  </code></pre>