Of The Text Book: Code Optimization
Of The Text Book: Code Optimization
source
Front End Intermediate Code Gen target
Code
Code Code
user Machine-
independent Machine-
Compiler dependent
optimizer Compiler
optimizer
• The technique consists of detecting
patterns and replacing them with efficient
constructs. The richest source of
optimization is the efficient usage of
registers and instruction set of a machine.
• After register utilization, the next important
one to consider towards optimization is
handling inner-loop
• Rule: 90 – 10 refers 90% of the time is
spent in 10% of the code
Optimization Techniques
1. Constant folding
A=I+J+B A = T1 + B
T1 = I + J
C= I+J+C C = T1 + C
2. Induction variables
For (i=0; I < 20; i++) A = 0;
{ For (i=0; I < 20; ++i)
{
A = I * 4; A = I + 4;
} }
Multiplication is replaced with less expensive addition
3. Repositioning Loop Variants
i = 0;
I = 0;
do { A = B;
P = P * I; do {
A = B; P = P * I;
I++; I++;
} while(I < 20);
} while(I < 20);
• If (debug) print …
• before after
• While ( I <= limit – 2). T = limit – 2
• While ( I <= t)
Induction-variable elimination &
Reduction in strength
• Look for induction variables for strength
reductions
• E.g. a pattern of changes in a lock step
B3: B3:
j = j - 1 j = j - 1
t4 = 4 *j t4 = t4 -4
t5 = a [ t4] t5 = a [ t4]
If t5 > v goto B3 If t5 > v goto B3
Loop Unrolling
Avoids a test at every iteration by recognizing that the
number of iterations is constant and replicating the body of
the loop. But NOT applicable to all.
J =0;
For (J=0; J < 100; ++J) while (J < 99)
{ {
A[J] = 5; A[J] = 5 ;
A[J+1] = 5 ;
} J+=2;
}
LOOP JAMMING
To merge body of two or more loops. Its necessary, each loop should be
executed the same number of tiems and that the indices are same.
Applicable to some indices of same value, NOT applicable to all