Professional Documents
Culture Documents
Code Generation
Code Generation
• Our machine:
- Byte addressable machine
- Has n general purpose registers, R0, R1, …., Rn-1.
• Following kinds of instructions are available:
• Store operations:
ST x, r stores the value in register r into the location x.
(x = r).
• Computation operations:
OP dst, src1, src2
where Op is a operator like ADD or SUB.
SUB r1, r2, r3 computes r1 = r2 – r3.
• Unconditional Jumps:
BR L causes control to branch to the machine instruction with
label L.
• Conditional Jumps:
Bcond r, L where r is a register, L is a label.
BLTZ r, L causes a jump to label L if the value in register
r is less than zero.
x= y- z can be implemented by machine instructions:
LD R1, y
LD R2, z
SUB R1, R1, R2
ST x, R1
B = a[i]
LD R1, i // R1= i
MUL R1, R1, 8 // R1 = R1*8
LD R2, a(R1) // R2= contents(a + contents(R1))
ST b, R2 // b = R2
Optimization
• Optimization is the process of transforming a piece of code to
make more efficient(either in terms of time or space) without
changing its output or side-effects.
• It should not only save the CPU cycles, but can be used on any
processor.
Machine Dependant Optimization
• Machine-dependent optimization is done after the
target code has been generated and when the code is
transformed according to the target machine
architecture.
• It involves CPU registers and may have absolute
memory references rather than relative references.
• Machine dependent optimizers put efforts to take
maximum advantage of memory hierarchy.
A Simple Code generator
• It considers each three-address instruction in turn, and keeps track of
what values are in what registers so it can avoid generating
unnecessary loads and stores.
t=a–b
LD R1, a
LD R2, b
SUB R2, R1, R2
a tt a,R1 b c d R2
u=a–c
LD R3, c
SUB R1, R1, R3
u tt c a b c, R3 d R2 R1
.v = t + u
ADD R3, R2, R1
u tt v a b c d R2 R1 R3
a=d
LD R2, d
u Ta, d v R2 b c d,R2 R1 R3
d=v+u
ADD R1, R3, R1
d Ta v R2 b c R1 R3
Exit
ST a, R2
ST d, R1 d Ta v a,R2 b c d,R1 R3
Rules for picking Ry for y
Possibilities for value of R
Selection for Register Rx
Peephole optimization
Eliminating Redundant Loads and Stores
LD R0, a
ST a, R0
• We can delete the store instruction because whenever it is
executed, the first instruction will ensure that the value of a
has already been loaded into register R0.
Eliminating Unreachable Code
• An unlabeled instruction immediately following an
unconditional jump may be removed.
if debug == 1 goto LI
goto L2
LI: print debugging information
L2:
if 0 != 1 goto L2
print debugging information
L2:
1. IN[EXIT] = ᶲ;
2. for(each basic block B other than EXIT) IN[B] = ᶲ;
3. While( changes to any IN occur)
for(each basic block B other than EXIT)
{
OUT[B] = ᴜS a successor of B IN[S];
IN[B] = useB ᴜ (OUT[B] – defB);
}