Professional Documents
Culture Documents
1.2 Phases of A Compiler
1.2 Phases of A Compiler
Phases of a Compiler
• Compiler operates in phases
• Each phase transforms source program
from one representation to another
The Structure of a Modern Compiler
Lexical Analysis
Source Code
Syntax Analysis
Semantic Analysis
IR Generation
IR Optimization
Code Generation
Syntax Analysis
while (y < z) {
Semantic Analysis
int x = a + b;
y += x; IR Generation
} IR Optimization
Code Generation
Code Optimization
Reads the characters in the source program
and groups them into tokens.
•Eg: TAC
•Improve the Intermediate Code so that
the ultimate object program runs faster
and or takes less space.
It involves:
- Detection and removal of dead code.
-Calculation of constant expressions and terms.
-Moving code outside of loops.
-Removal of unnecessary temporary variables.
Machine code is generated. This involves:
1
Lexical Analyzer
2
Syntax Analyzer
3
Semantic Analyzer
5
Code Optimizer
6
Code Generator
Target Program
Find the Answer?
Consider the following statement
position=initial + rate*60
Show the output of each phase.
Example
position := initial + rate * 60
lexical analyzer
id1 := id2 + id3 * 60
syntax analyzer
:=
id1 +
id2 *
id3 60
semantic analyzer
:=
Symbol + E
Table
id1 r
id2l *
r
position .... id3 inttoreal o
60 r
initial …. s
intermediate code generator
rate….
Example
Symbol Table E
r
position ....
r
initial …. o
intermediate code generator r
rate…. s
temp1 := inttoreal(60)
temp2 := id3 * temp1
temp3 := id2 + temp2 3 address code
id1 := temp3
code optimizer
temp1 := id3 * 50.0
id1 := id2 + temp1
final code generator
MOVF id3, R2
MULF #60.0, R2
MOVF id2, R1
ADDF R2, R1
MOVF R1, id1