Optimisation: What is Loop-Invariant Code Motion?

Loop-Invariant Code Motion (LICM) is the optimisation which detects code within a loop which is constant for each iteration of the loop and could be placed outside of the loop to save instructions.

Consider the example:
for( int i = 0; i < n; i++)
{
int K = X + Y;
arr[i] = K + i;
}

In this example “X + Y” is being evaluated each step of the loop but is constant. So this could be transformed to be:

int K = X * Y;
for( int i = 0; i < n; i++)
arr[i] = K + i;

This saved on “n” number of add operations. However, this is not a valid transform. Because the creation of variable K was inside the loop, there are values for “n” which would never enter the loop - in which case we have moved some code which should never be executed into a position where it can be executed.

To perform this transform in a way that does not break this rule we must do:

if(n >= 0)
{
int K = X * Y
for(int i = 0; i < n; i++)
arr[i] = K + i
}