Code Generation
Code Generation
op source, destination
◦ Op – op-code
◦ Source, destination – data fields
6
The Target Machine: Op-
codes
Op-codes (op), for example
MOV (move content of source to
destination)
ADD (add content of source to destination)
SUB (subtract content of source from
destination)
7
The Target Machine: Address
modes
Added
Mode Form Address
Cost
Absolute M M 1
Register R R 0
Indexed c(R) c+contents(R) 1
Literal #c N/A 1
Instruction Costs
Machine is a simple processor with fixed
instruction costs
Define the cost of instruction
= 1 + cost(source-mode) + cost(destination-
mode)
9
Examples
10
Instruction Selection
Instruction selection is important to obtain
efficient code
Suppose we translate three-address code
x:= y + z
to: MOVy,R0
ADD z,R0
MOV R0,x
a:=a+1 MOV a,R0
ADD #1,R0
MOV R0,a
Cost = 6
Better Best
12
Need for Global Machine-
Specific Code Optimizations
Suppose we translate three-address code
x:=y+z
to: MOVy,R0
ADD z,R0
MOV R0,x
Then, we translate
a:=b+c
d:=a+e
to: MOV a,R0
ADD b,R0
MOV R0,a
MOV a,R0 Redundant
ADD e,R0
MOV R0,d
13
Register Allocation and
Assignment
Efficient utilization of the limited set of
registers is important to generate good
code
Registers are assigned by
◦ Register allocation to select the set of variables
that will reside in registers at a point in the code
◦ Register assignment to pick the specific register
that a variable will reside in
Finding an optimal register assignment in
general is NP-complete
14
Example
t:=a*b t:=a*b
t:=t+a t:=t+a
t:=t/d t:=t/d
MOV a,R0
ADD b,R0
MOV R0,t1
t1:=a+b MOV c,R1
t2:=c+d ADD d,R1
a+b-(c+d)*e t3:=e*t2 MOV e,R0
t4:=t1-t3 MUL R1,R0 MOV c,R0
MOV t1,R1 ADD d,R0
reorder SUB R0,R1 MOV e,R1
MOV R1,t4 MUL R0,R1
t2:=c+d MOV a,R0
t3:=e*t2 ADD b,R0
t1:=a+b SUB R1,R0
t4:=t1-t3 MOV R0,t4 16
Two Classes of Storage in
Processor
Registers
◦ Fast access, but only a few of them
◦ Address space not visible to programmer
Doesn’t support pointer access!
Memory
◦ Slow access, but large
◦ Supports pointers
4 Distinct Regions of Memory
Code space – Instructions to be
executed
◦ Best if read-only
Static (or Global) – Variables that retain
their value over the lifetime of the
program
Stack – Variables that is only as long as
the block within which they are defined
(local)
Heap – Variables that are defined by
calls to the system storage allocator
Memory Organization
int a;
float j;