008chapter 8 - Code Optimization
008chapter 8 - Code Optimization
Code Optimization
Basic Topics to be covered
When to Optimize?
Code Optimization is the process of transforming a piece of code to make more efficient
Code Optimization is used to improve the intermediate code by making it consume fewer
resources (i.e. CPU, Memory) so that faster-running machine code will result.
Optimization of the code is often performed at the end of the development stage
since it reduces readability and adds code that is used to increase the performance.
Efforts for an optimized code can be made at various levels of compiling the
process.
– At the beginning, users can change/rearrange the code or use better algorithms to
write the code.
– After generating intermediate code, the compiler can modify the intermediate
code by address calculations and improving loops.
– While producing the target machine code, the compiler can make use of memory
hierarchy and CPU registers.
Code Optimization rule
Compiler optimizing process should meet the following rules given below:
– The optimization must be correct, it must not, in any way, change the meaning of
the program.
– (i.e. It is expected that the un-optimized and optimized variants give the same
output for all inputs.)
– The optimization process should not delay the overall compiling process.
Code Optimization: Example
Types of Code Optimization:
• The optimization process can be broadly classified into two types :
• One way we can begin to optimize our code is by using peephole technique.
• This is the idea of performing optimizations on small parts of the code, replacing sections
with shorter and faster code whilst still keeping the inputs consistent.
• This is a machine dependant optimization.
• Implement of peephole optimization, they are as follows:
– Redundant load/store elimination
– Common Sub-expression Elimination
– Constant folding
– Constant Propagation
– Strength reduction
– Null sequences
– Combining operators
Redundant load /store elimination
– Optimized code:
x = y+5
i=x
j = x*3
Copy Propagation
Common Sub-expression Elimination
Constant Folding
Simplification of constants
Input code:
Evaluate constant expressions at compile time.
x = 3*3
Only possible when side-effect freeness guaranteed.
Optimized code:
x=9
Constant Propagation
Combining operators
Multiple operations can be combined to a shorter equivilant expression
Input code:
i = j*(10+3)
Optimized code:
i = j*13