Loop Invariant Code Motion

From emmtrix Wiki
Jump to navigation Jump to search

Loop invariant code motion is an optimization technique that moves computations outside of a loop if they do not depend on the loop iterator. By extracting such invariant expressions, this transformation reduces redundant calculations and improves runtime efficiency. It minimizes unnecessary operations within loops, leading to faster execution and better performance. This technique is particularly useful in optimizing complex loops, reducing computation overhead, and enabling further compiler optimizations.

Loop Invariant Code Motion Transformation in emmtrix Studio

emmtrix Studio implements loop invariant code motion using #pragma directives or via the GUI. Loop invariant code motion is a transformation that moves code that is invariant from the loop iterator in front of the loop.

Typical Usage and Benefits

Loop invariant code motion is typically used to improve the runtime of an application by moving loop invariant parts out of loops in order to reduce the number of times they are executed.

Example

/* The following code tests loop invariant code motion transformation applied to a for loop: */   

int main(void) {
    #pragma EMX_TRANSFORMATION LoopInvariantCodeMotion
    for (int i = 0; i < 10; ++i) {
        int inv = 10;
        int inv2 = inv * inv;
        printf( % d\ n, inv2);
    }
    return 0
}
/* The generated code: */

int main(void) {
    int inv = 10;
    int inv2 = inv * inv;
    for (int i = 0; i < 10; ++i) {
        printf( % d\ n, inv2);
    }
    return 0;
}

Parameters

Following parameters can be set (each description is followed by keyword in pragma-syntax and default value):

Id Default Value Description
subExprs false Move sub-expressions by creating temporary variables - move expressions that require the insertion of temporary variables in order to make the code more efficient
reorderInvExprs false Reorder invariant expressions by applying the commutative and associative laws - enables reordering of moved expressions that allows more optimizations for better efficiency
xpectedMovedExpr -1 Expected moved expressions - can be used for testing purposes by inserting the number of expected moved expressions. Creates an error if the numbers differ, does nothing when set to -1

Note

  • To move functions from math.h, use the idiom recognizer transformation to identify the functions and apply the code sinking transformation afterwards.