Loop-invariant code motion: Difference between revisions

Content deleted Content added
See also: add template
No edit summary
Line 34:
 
However, if too many variables are created, there will be high [[register pressure]], especially on processors with few registers, like the 32-bit [[x86]]. If the compiler runs out of registers, some variables will be [[register spilling|spilled]]. To counteract this, the inverse optimization can be performed, [[rematerialization]].
Loop-invariant expressions can be hoisted out of loops, thus improving run-time performance by executing the expression only once rather than at each iteration.
 
Example:
 
In the code fragment below, the expression (x + y) is loop invariant, and the addition can be hoisted out of the loop.
 
void f (int x, int y)
{
int i;
 
for (i = 0; i < 100; i++)
{
a[i] = x + y;
}
}
Below is the code fragment after the invariant expression has been hoisted out of the loop.
 
void f (int x, int y)
{
int i;
int t;
 
t = x + y;
for (i = 0; i < 100; i++)
{
a[i] = t;
}
}
Notes:
 
Some C compilers can hoist a subset of loop-invariant expressions (e.g. integer addition, subtraction, and multiplication), but few compilers can hoist a wide range of expressions (e.g. left shift, right shift, etc.).
 
Most compilers reduce expressions with sequence operators (i.e. &&, ||, and ?:) to if-then-else blocks early in the compiler, and most compilers fail to hoist loop-invariant expressions containing sequence operators.
 
 
 
http://www.compileroptimizations.com/category/hoisting.htm
 
==Further reading==