- 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:
After Optimization the code is:
Here, after variable propagation a*b and x*b identified as common sub expression.
(3) Dead code elimination:
Before elimination the code is:
After elimination the code is:
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.
(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:
After Reduction the code is: