WIPIVERSE All articles

Loop inversion

Loop inversion is a compiler optimization and loop transformation in computer science in which a while loop (a pre-test loop) is replaced by an if block containing a do..while loop (a post-test loop). The transformation preserves the original semantics of the loop while potentially improving performance.

Overview

In a standard while loop, the loop condition is evaluated at the beginning of each iteration. When the condition becomes false, execution exits the loop. In the inverted form, the condition is first checked in an if statement; if it is true, the loop body is entered via a do..while construct that evaluates the condition at the end of each iteration. This rearrangement eliminates the unconditional jump at the end of the loop body that would otherwise be required to return to the condition check at the top.

Performance Implications

The primary benefit of loop inversion is the reduction of jump instructions. On modern CPUs that use instruction pipelining, any jump can cause a pipeline stall, degrading performance. The inverted loop removes two jump instructions on the final iteration when the loop is entered:

  • The unconditional jump from the end of the loop body back to the condition check is eliminated.
  • The conditional jump that exits the loop is moved to the end of the body.

For the initial and all non-final iterations, the number of instructions executed is unchanged. When the loop condition is initially false, the if block is skipped entirely, incurring only the cost of a single conditional jump — the same as the original while loop.

Additional Benefits

Loop inversion also enables safe loop-invariant code motion. Because the condition check is separated from the loop body, code that does not change between iterations can be moved outside the loop more easily, further improving performance.

Example (C)

Original while loop:

int i, a[100];
i = 0;
while (i < 100) {
    a[i] = 0;
    i++;
}

After loop inversion:

int i, a[100];
i = 0;
if (i < 100) {
    do {
        a[i] = 0;
        i++;
    } while (i < 100);
}

Example (Three-Address Code)

Original:

      i := 0
 L1:  if i >= 100 goto L2
      a[i] := 0
      i := i + 1
      goto L1
 L2:

After inversion:

      i := 0
      if i >= 100 goto L2
 L1:  a[i] := 0
      i := i + 1
      if i < 100 goto L1
 L2:

In the inverted version, two goto instructions (and thus two potential pipeline stalls) are eliminated during execution when the loop is entered.

References

  • Wikipedia, Loop inversion (https://en.wikipedia.org/wiki/Loop_inversion)
  • Jubb, Chae, Loop Optimizations in Modern C Compilers
Browse

More topics to explore

    Browse all articles