"Nate Denmark" <ndenmark@xxxxxxxxxxxxxx> writes: > I have a question about the optimiser in GCC. Take this bit of code: > > for(x = 0; x != 10; x++) > puts("Hello"); > > When compiled with full optimisations (-O3, -fexpensive-optimizations > etc.) it generates the following loop in assembly: > > .L2: > incl %ebx > movl $.LC0, (%esp) > call puts > cmpl $10, %ebx > jne .L2 > > .LC0 points to the "Hello" string. I'm wondering why GCC puts that > 'movl' line inside the loop, so that it's executed each time, when it > could go before the loop? As I understand it, 'puts' shouldn't do > anything to the stack, and the return value is passed back in eax, so > I'm not sure why it's doing the 'movl' each time. If I force loop > unrolling the same thing happens -- the 'movl' each iteration. Technically the parameters pushed on the stack become the property of the function being called. For example, code like this: int foo (int a) { int *p = &a; *p = 1; return *p; } could be compiled to change the value pushed on the stack. Since gcc doesn't know how puts is implemented, it can't assume that puts does not change the value on the stack. So it has to restore the value before each call, just in case. Ian