Loop-invariant code motion moves expressions out of a loop if the expressions are not affected by the loop or the loop does not affect the expression. This optimization improves execution speed.
Controlling loop-invariant code motion explains how to control the optimization for loop-invariant code motion.
| Turn control this option from here... | use this setting |
|---|---|
| CodeWarrior IDE | Choose an Optimization Level value (3,4) from the Properties > C/C++ Build > Settings > Tool Settings > PowerPC Compiler > Optimization panel. |
| source code | #pragma opt_loop_invariants on | off | reset |
| command line | -opt [no]loop[invariants] |
For example, in Before loop-invariant code motion , the assignment to the variable circ does not refer to the counter variable of the for loop, i . But the assignment to circ will be executed at each loop iteration.
After loop-invariant code motion shows source code that is equivalent to how the compiler would rearrange instructions after applying this optimization. The compiler has moved the assignment to circ outside the for loop so that it is only executed once instead of each time the for loop iterates.
void func_from(float* vec, int max, float val)
{
float circ;
int i;
for (i = 0; i < max; ++i)
{
circ = val * 2 * PI;
vec[i] = circ;
}
}
void func_to(float* vec, int max, float val)
{
float circ;
int i;
circ = val * 2 * PI;
for (i = 0; i < max; ++i)
{
vec[i] = circ;
}
}