cgccoptimization

Is dereferencing a member from a struct pointer in loop optimized as loop invariant?


Suppose I have, in C99, for(int j=0; j < t->k; j++), t->k does not change throughout the loop iteration. Does the compiler optimize this line, or there will be one dereferencing operation per loop iteration?

In other words, would

tmpk = t->k;
for(int j = 0; j < tmpk; j++)

be better for a large number of iterations?


Solution

  • In the general case this depends on whether t is declared restrict; in the absence of an explicit aliasing restriction the compiler cannot assume that no other pointer provides a path to modify k.

    Of course, if the compiler can prove that t->k is invariant by inspection of the loop body, it may choose to move the dereference out of the loop body, or do so incorrectly if the optimizer is buggy.

    Explicitly caching the value of t->k in a local variable would rather reliably force the issue. :-)