Unit VI Code Generation
Unit VI Code Generation
Manisha Mali
[email protected]
Unit VI
3
Index
• Issues in code generation
• Register allocation and assignment
• Code generator concept
4
Introduction
Manisha Mali, Department 26-Oct-20
of Computer Engineering,
VIIT , Pune-48
Source
Intermediate Intermediate
program Front code Code code Code target
program
end Optimizer generator
Symbol
table
VIIT , Pune-48
MOVE id2,R1
MULT id3,R1
ADD #1,R1
MOVE R1,id1
Manisha Mali
6
Manisha Mali
7
Target Programs
• The output of the code generator is the target
program.
• Target program may be
▫ Absolute machine language
It can be placed in a fixed location of memory and
immediately executed
▫ Re-locatable machine language
Subprograms to be compiled separately
A set of re-locatable object modules can be linked
together and loaded for execution by a linker
▫ Assembly language
Easier
10
Instruction Selection
Manisha Mali, Department 26-Oct-20
of Computer Engineering,
VIIT , Pune-48
a=b+c
d=a+e
MOV b, R0
ADD c, R0
MOV R0,
MOV R0, aa If a is subsequently
used
MOV a,
MOV a, R0
R0
ADD e, R0
MOV R0, d
12
Register Allocation
• Instructions involving register operands are usually
shorter and faster than those involving operands in
memory.
• Efficient utilization of register is particularly
important in code generation.
• The use of register is subdivided into two sub
problems
▫ During register allocation, we select the set of
variables that will reside in register at a point in the
program.
▫ During a subsequent register allocation phase, we pick
the specific register that a variable will reside in.
14
Tree-
rewriting
for some
target-
machine
instructi
on
17
constructed
18
Exercise (Contd)
MOV MEM, REG /* load data in memory Mem
to register Reg
MOV REG, MEM /* store data in register Reg to
memory Mem
SUB REG1, REG2 /* Reg2 – Reg1 Reg2
SUB MEM,REG /* Reg – Mem Reg
MOV REG1,REG2 /* Move data in register Reg1 to
register Reg2
22
Exercise (Contd)
Manisha Mali, Department 26-Oct-20
of Computer Engineering,
VIIT , Pune-48
Generated code
VIIT , Pune-48
• MOV a, R0
• SUB b, R0
• MOV c, R1
• SUB d, R1
• SUB R1, R0
• MOV f, R2
• MOV g, R1
• SUB h, R1
• SUB R1, R2
• MOV e, R1
• SUB R2, R1
• SUB R1, R0
24
Exercise
• given the code fragment
x := a*a + 2*a*b + b*b;
y := a*a – 2*a*b + b*b;
+ +
+ * - *
* * b b * * b b
a a * b a a * b
2 a 2 a
26
Answers
dependency graph after CSE
x y
+ +
+ * - *
* * b * * b b
a * a a * b
2 2 a
27
Answers
Manisha Mali, Department 26-Oct-20
of Computer Engineering,
VIIT , Pune-48
x y
+ +
+ * -
* * b
a *
2
26-Oct-20
References
28
26-Oct-20
Manisha Mali, Department of Computer Engineering, VIIT , Pune-48
29