Zebrafish
Zebrafish

Reputation: 14314

Puzzling compiler optimisation result

If I try to run a loop like this:

int i;

for (i = 0; i < 1e9; i++)
{
    1 + 1;
}

The compiler optimises it out completely and doesn't even run it. But if I make the int i static, then it goes ahead and runs the loop, even when I went way higher iterations. This is in Visual Studio 2013 with optimisation turned on in release mode.

Upvotes: 0

Views: 80

Answers (2)

Hadi Brais
Hadi Brais

Reputation: 23719

When i is not static, this entire piece of code does not affect the observable state of the program. As you've noticed, the compiler optimizes away the loop. This is called dead-code elimination.

Now when i is static, the VC++ compiler immediately gives up and not optimize the code (most non-trivial optimizations will not be used whether they are applicable or not). If two or more threads are calling the function concurrently, then most optimizations including dead-code elimination might cause observable side effects on the state of the program rendering them illegal.

Of course, in this case, we are not using any threads. But VC++ will not analyze the code (for good reasons) and so, to be safe, it just gives up.

If it did analyze the code and discovered that only one thread is calling the function, then it's actually capable of optimizing it by replacing the loop with an addition statement if i was static.

Upvotes: 1

Adam
Adam

Reputation: 17389

It's obvious that the body of the loop is a no-op. The only effect that the loop has is to change the value of i. When i has automatic storage, the compiler can prove that the value of i is never read after the loop. Therefore, the entire loop has no effect and can be discarded.

However, when i is static then its lifetime extends beyond the single call of the function. Therefore, the value of i is a side effect and the loop cannot be discarded.

You could argue that the compiler could dig deeper and prove that even a static i is never read, but that's a much more difficult proof to do.

Upvotes: 2

Related Questions