Loop-Invariant Computations and Code Motion

Induction Variable Detection and Elimination

Strength Reduction

Loop Unrolling

Loop Jamming (Fusion)

Counting up to Zero

Unswitching

Loop Collapse

10.2.4 Loop Unrolling

Loop unrolling decreases the number of iterations of a loop. Consider the following loop:

    LOOP I = 1 to 10000 by 1


      A(I) := A(I) + B(I)

    ENDLOOP

Unrolling by 2 gives

    LOOP I = 1 to 9999 by 2


      A(I) = A(I) + B(I)
      A(I + 1) = A(I + 1) + B(I + 1)

The number of instructions executed is reduced because the number of increments and tests is halved.

Another example of loop unrolling is:

      WHILE Condition                  WHILE Condition
          A                              A
       ENDWHILE                           IF NOT Condition THEN Exit
                                             A
                                        ENDLOOP
 

Loop unrolling also exposes instructions for parallel execution since the two statements can be executed at the same time if they are independent (see Chapter 13).

The disadvantage here is that increased instruction space is required.