Lec 12 - Code Generator
Lec 12 - Code Generator
Lec 12 - Code Generator
An Overview !!
Phases of a compiler
Program (character stream)
Lexical Analyzer (Scanner)
Token
Stream
Syntax Analyzer (Parser)
Parse Tree
Semantic Analyzer
Intermediate Representation
Intermediate Code Optimizer
Optimized Intermediate Representation
Code Generator
Assembly code
2
OR
Program (character stream)
Lexical Analyzer (Scanner)
Token
Stream
Syntax Analyzer (Parser)
Parse Tree
Semantic Analyzer
High-level IR
Low-level IR
Intermediate Representation
Code Generator
Assembly code
3
Position of Code Generator
4
Role of a Code Generator
Severe requirements imposed
– Output must be correct and high quality, means it should make
effective use of the resources of the target machine
– Code generator should run efficiently
Certain generic issues are inherent in the design of basically all code
generators
5
Issues in the Design of Code Generator
6
Input to Code Generator
The input to the code generator consists of:
Intermediate code produced by the front end
9
Instruction Selection
Depends on the nature of the instruction set
11
Generating Assembly Code
Learn by Examples !!
Points to Remember
Assembly Instructions are of the form
OP Source , Destination
For example
MOV Source , Destination
13
Example 1 (a = b + c)
Three Address Code Assembly Code
MOV b, R0;
t1 = b + c ADD c, R0;
a = t1 MOV R0, a
14
Example 2 ( a = a + 1)
Three Address Code Assembly Code
MOV a, R0;
t1 = a + 1 ADD #1, R0;
a = t1 MOV R0, a
15
Example 3 (a := b * -c + b * -c;)
( Consider optimization not done)
Three Address Code Assembly Code
t1 := -c MOV c, R0;
t2 := b * t1 MUL #-1,R0;
t3 := -c MUL b,R0;
t4 := b * t3 MOV c, R1;
t5 := t2 + t4 MUL #-1,R1;
a := t5 MUL b,R1;
ADD R1,R0;
MOV R0,a;
16
Example 4 (a := b * -c + b * -c;)
( Consider optimization done)
Three Address Code Assembly Code
t1 := -c MOV c, R0;
t2 := b * t1 MUL #-1,R0;
t3 := t2 + t2 MUL b,R0;
a := t3 ADD R0,R0;
MOV R0, a;
17
Example 5 d:=(a-b) + (a-c) + (a-c)
(Consider optimization not done)
t1 := a – b;
mov a, r0
t2 := a – c;
sub b,r0
t3 := t1 + t2;
mov a,r1
t4 := a – c;
sub c,r1
t5 := t3 + t4;
add r1,r0
d := t5;
mov a,r2
sub c,r2
add r2,r0 ;
mov r0,d
Example 5 d:=(a-b) + (a-c) + (a-c)
(Consider optimization done)
t1 := a – b;
mov a, r0
t2 := a – c;
sub b,r0
t3 := t1 + t2;
mov a,r1
t4 := t3 + t2;
sub c,r1
d := t4;
add r1,r0
add r1,r0 ;
mov r0,d
Let’s Revise
Position of Code Generator
21
Issues in the Design of Code Generator
22
Generating Assembly Language