Machine-Independent Optimization

  • Machine independent optimization attempts to improve the intermediate code to get a better target code. The part of the code which is transformed here does not involve any absolute memory location or any CPU registers.
  • The process of intermediate code generation introduces much inefficiency like: using variable instead of constants, extra copies of variable, repeated evaluation of expression. Through the code optimization, you can remove such efficiencies and improves code.
  • It can change the structure of program sometimes of beyond recognition like: unrolls loops, inline functions, eliminates some variables that are programmer defined.

Code Optimization can perform in the following different ways:

(1) Compile Time Evaluation:

(a) z = 5*(45.0/5.0)*r
     Perform 5*(45.0/5.0)*r at compile time.

(b) x = 5.7
     y = x/3.6
    Evaluate x/3.6 as 5.7/3.6 at compile time.

(2) Variable Propagation:

Before Optimization the code is:

  1. c = a * b                                                
  2. x = a                                                   
  3. till                                                            
  4. d = x * b + 4   

After Optimization the code is:

  1. c = a * b    
  2. x = a  
  3. till  
  4.     d = a * b + 4  

Here, after variable propagation a*b and x*b identified as common sub expression.

(3) Dead code elimination:

Before elimination the code is:

  1. c = a * b                                                  
  2. x = b                                                 
  3. till                                                          
  4. d = a * b + 4    

After elimination the code is:

  1. c = a * b  
  2. till  
  3. d = a * b + 4  

Here, x= b is a dead state because it will never subsequently used in the program. So, we can eliminate this state.

(4) Code Motion:

  • It reduces the evaluation frequency of expression.
  • It brings loop invariant statements out of the loop.
  1. do  
  2. {  
  3.    item = 10;  
  4.    valuevalue = value + item;   
  5. } while(value<100);  
  6.    
  7.    
  8. //This code can be further optimized as  
  9.   
  10. item = 10;  
  11. do  
  12. {  
  13.    valuevalue = value + item;   
  14. } while(value<100);  

(5) Induction Variable and Strength Reduction:

  • Strength reduction is used to replace the high strength operator by the low strength.
  • An induction variable is used in loop for the following kind of assignment like i = i + constant.

Before reduction the code is:

  1. i = 1;                                                    
  2. while(i<10)                                                
  3. {                                                        
  4.     y = i * 4;   
  5. }  

After Reduction the code is:

  1. i = 1  
  2. t = 4  
  3. {   
  4.    while( t<40)   
  5.   y = t;   
  6.   t = t + 4;  
  7. }