unite
et code iets
Orbodu dion
code generation is the final
Ae a e adiuity of compiler
cally code generation 8 a process of Leads
ass
vo language [achive language stuperoents
pian Ibe operakcons spectfied by tbe souver
paograr when ne wun +
Properties of objeck code generation
1) corvechness - gt should produce a
and do not after the porpose- °F Kource Code
WoHigh Quality e Se should produ i
2 ce a high Qual’
object code 4 P . ‘ i t
Ci) BL ficient use. Of esources Of We Lovget machine:
while | the code Ge necessary |
Know the 7 anochine on which & & oT
‘to { enetabedl
exe
lod utilizalvon of abst
Performing tre arithmetic a
#% Quick tode . ¥
ge Wnecessory jak the code 4
chould alate the code. quickly of
Pp t
coszeck coda
the veg
Memo utilizakion while allocacting
thmette logit unb while
erations ©
enero!
phasecompiling Me Source progam
Object code forms:
The object of Ihe con yeni of ore
okjeck cade machine tode-This cede nosmalty
comes tr_-follow hg forms «
L-Absolule code
2. Relocale machine code
3.-Assembley code
LAbsolute codes
SE & a Machine code that contaths referer
to actual addvess with program's address space?
She quae code
sf we do
shuckion geleckon becomes
code then be in
skrotght _ fosward task.
-for examp lee
= ya
a=utt
“the code -for the above staitementr can be
aaa as follows
Mov fike
ADD z, Roi ee ee
voy %1Ro .
app 1 Ro
Mov Rov@ °
Hhe above generated code & a poor code becawr<
Mov Roa i® not used and statement Mov ajF
is sedundant « tence the efficient code can be
Mov yrRo
App ZiRo
App +) Ro
Mo Roe
“The quale of enevated code (8 decided by ee
speed and size. simply line by tine Banslatior
of three address code ‘hlo touget tone leads to
coneck code bub tt can enerake unacceptably:
non epfiaént tort cede
5) Register allecation:-
ister operarde
4 be tnsteuckior contains
becomes shoxter and qasten
vands in the a |
od code. efpicent|
then Such 2 Use
ban that of using opel
stlence toile
uitlizakon A
factor:
—SThere aye lwo
lohile sing registers *
tinpostant adivities done |@
i
a) tey allocation t- Dusting vegister allocakion_5
Sele appyoptiate set of variables that will noside
wn crea isbers .
Cb Register asstgnmenti- Durih nga a
ent pick Up Ibe Specific 7e is ia which-
vortable will westde *
obtaining the optimal actignment 4 cegtsters
to variables %s dif feeult °
machines Yequire veqistey pots SU
aor some —
LOVE spond n
— certain
as even odd numbered eer
operands and sesults -
—>foy examples ah 28M S
Acquites aceqictey pats ,
constdev the ‘three address code -
stems integer Multplicatio
44. =atb
Ere tee
ti tid -
he efpicient omachine
Mov ako
App by Ro
mur c, Ro
Dw ApReo
code sequence will be
mov RoytyOchoice of evaluation osdert-
tbe evaluation order f an important facts
fn generating oun. applacnt target code -
—>Some ovders vequite less number, af 7! 7
hold te tatermediate vesulls than the othere
> 7 up Ibe best order 1% one of the deffieuleg
wh cede evatcon -
> Mostly , we can avoid this problem ty opening
tthe ordey in which the three addvess code
enerated cementite. adil *
D Approaches to code ation t-
The most finpovtant fader a cede
\e that tt should produce the comect cod -
of toda. eneratton. vortous
cod: we designed:
bo
nevabort
voit this approach.
ee jo qed
“Ter ulin bape
arg wa esr ve
that lhe
Sp thie woe will assume
lke min —
machine code i a 7
computers Specifically following asscump
made 4p" code al
chwe will assume that 1 the tae conn ten.
fiven wy legtes and four bytes
ado vesses ave ¢
-form a voor «
ave; ©
tid There ate n-geneval puypase. registers Roy Rie Ryy
Zii) The two oda ess inseuction bs the foven
“Mov — awoves ee source source tb destinabton
App - add source to destinakon
0B — Subliact source from destinatfon
he source ang destination ave speed by
registers and memory inalions -
Sthe addsessing modes Ole used arte as follows -
Pudvessing Mode | form |Addwess fuel WHEL
| oe M | M
Oo
pei & eR
indexed 22) | ¢-4 contents (2) !
indirect” vegidi.| * ¥e contents (e> o
| eontenr(ct )
_indiveck indexed & oe) toot enke 8) | {
literal | He fee \
cost of the inshuclfonir
the tnskuthdn cose ca be computed Qu
one plus cosk asoctaked with the Sowce
and destination addvessing modes given by
added cost’sthkerpretalion,
Lost ok wegister mode
hs Ha eee b oe
use of amemoxy vasiah
(Bbc sek ee HR ESE PEER cmem seas HESSSESRERE stile ttifs a
Sub 5k 3 | Use of first constant
lo (RD -t use of Second
constant +1 =2
€xte Compute the cost of -followtng set of
instiucttons
Mov aio Mov a) Ro~>
ADD b) RO LW en
+
MOM Roe cont of cost Of
instiucliony)
“The cast of this sek of l Pee
a]
Mov ako (HY ee
App bRo = 2a (it)
Mov Roe —> LID
~fotal cost =O
DX Mov #R ,#RoW!
Mov # Rar ¥ RoW)
Q
> Mev Ba >> Cirtty)
mov aA —? 3 Cite
Total cost = C6)
SSP eee san= C)
ar igi allocakon and Assignment t-
—>Vartous stvabe gies used “4 registers allo
and asstgnament ove
\e Global req tster allcation
ae US count
a Register assignment for outer loop
q. Gyrcph. a for arogistes, assignment
Global register -Allocalzons
— While enerating the cede the seqistors ae.
used to hold the values $°% the duration of Sq
block:
L SAIL the (fe vartables ave ctoved at lhe end of-
oth block.-for the varibles that ee
consistently we can allocate specpe set 4
mecyisters ‘
Hence allocation oF vootbles +e speapte
+thak @ consistenk across Ie block boundarat
B éalled globe! — allocakon .
following we the shrakegiss adoptmed whit
deity tRe globo! megistey allocation
the global segister allocak’on has a stvateqy
ctoving the most frequently used varvablesur
fired req iaters Throughout the loop -lus count
he usuage counk the count for the Whe
Of some voyCoble ‘x in some ba nae used wa
baste block-
fves the tdea hew
the Usuage court
gelecting a. Specific
untls of cost Cane be saved
yastable jor qiebal regis allocaltzon -
> the approxtmake -fesrnulo -for uswage coun!
fox the loop ‘U' th come bast block 6! can bee
quer as
Ss (uses (x8) 42% Leve (x 8)
block Bunt
where use (x16) fk number of ones tet used a
block ts) potor to any deginitéon of & and
Live CriByet & UC & lve on exist 470M Bs
othe wise live (XY) =O -
eur constder a block Bi, Bo Bx By an
usuiage count for block ‘al in follows Loop
dg count Wey
ALToO
The usage county for Dhan. es uct TAbtie
tat
use (018i) =0 esa fs defined A B before!
alive (a) bi) =2 use +
a & lve on exter fe
tence leve (a, bD=/
Luse-(a)B) ta ¥ lve (a,Bi)) =2
“She usuage count {ov block Bg and Bs po%
yartable ‘a!
use (a1Ba) = Use (ab) = 2ak used wr By and 6
beore definiro°
live (a) B2) =O 4a. te Not 'Le OM extst of
2)Registe allocation fo ouker Loop
consider that there are two Loops L,@ oukee
Sal is came ep and allocation &
Lal & te be done te Sone ceases The.
approxemate ccenarto & 8 :- bela «
Loo} Ly
at
a
Pr
loo}
VastableIlow é t
ee critter , Should be adepted from the *
vegister aastpranient: -fos outer Loop - :
hy 44 (a! allocated in loop la then et should
hob be Allocated th Ly
Lit) Sp ale allocated tn 4 an
th ta then Stove ‘A’ On & entiane
la! while leaning lg -
in 94, 'o B allocated th lo and not
load sa’ on enhance a and stor tal on exitty
d th & not allocate
to ig and
th 2, her
fron lau
Stmple code ‘alton -Algorvttbm *
sda this we will deeuss the emethod of-
; eee | target code from three addve ss
shat ement >
this method comp uted
os jos thle
sn yesults car be kept
in registers 04 long
. yr ath 3
Exe
She cowses ponding
App bey Hera a hotds value 4 ‘4’
angel code is
Here cose =
Mov bik) ere Ry holds vale § \O!
ADD ee there cost =2-—y The code qa algostlhm uses descyiplows
Diecces
to keep track of vere contents and ad
for names -
Keep tack of-
b She Esq tel deseviplor 6 used te
what & zumently mn cach register. the register
descriptor show that tnitially all the reper
ave empty °
As the code ree fo Ihe block progresses
lL fold the values Of computations
lhe registers
ae using veqistors deseviptors we can Keep track
oh the ae which ave euaeenel occupied. -
Boolean TWpe which & used
qd with
the status field F
to check whether Ihe register @ occupies
come dala ©d not-
5 lelhen the status field holds the value ‘tsue?
zontains the
then operand descriptors field
the operand descriptor who & hawiha
pointer to
the latest value ta the register:
& The Addvess decertptor ° stoves the location whee
the cusvent value of the name can be jound
at wun time-
about locabions can be stoved|
—> The th-fomation
used te access the
an. the symbol table and
e
fs
variables—Sthe modes of opevand addvessibitity are as
ae belovo
S 1% used to indicate value C opaand wu
Stovage
£ & used bo indecate valle Ff operand re
Register
4s indicates that lhe addvess operand @
Stored in stoxage ie, thdévect accessing -
qr tndécates that the addyess of operand a
Stored th vegfsta Ce 5 indised” accessin
—> She ANddvess desereptor has
ees a storage locablonfe gies :
na
ea
5 the attribubes mean type of the operands The
enerally refers fo Me fname oF temporar
Variables
-fellourng fteid «
Ls the addvesst mode indicates Woheher the
addresses Ale Of type tg, Ros", “pele:
geld which tnde-
I> She third 4ield & location
i nm storage
zates whether the address
locakdn of in register +Algostthin -fow code genevalfon usifty geTREG-
head the exprestén ir the -foxm % operator operand)
and operand @ and gona code. using
follounng algortitary-
Gen- code (operator , operand | operand ®
{
tf Coperand 1. addvess mode = 'R')
if Coperand ='+')
Generabe (ADD opuard a)Ro )5
else & (operator = wey
Generate (‘sue operand a, Ro)5
alse ut (operator ~ ‘#)
Generate (‘Mur operand 21 Rolls
alse uf (operates = Y")
Genevabe (‘piv operand @.Rg)5
pase oth £
else ar (operand a. addvessmode ='R')
iy (opevakow = ta!)
Generate (‘ADD operand 1,00) 5
else vy (cpevator oe)
Generate (S08 qqerand L, R8)5
else a (operator =!)Generate (MUL operand 1, Rd)5
else. af (operator = ve
Genevate (DIV opevand |, Rol) 5
else
Generate (‘Mov operand a, Rod5
ef Copevator - 49)
Genevale CADD opevand Rod
else a Coperator ek
Generake (Sus operand a Ro!D5
alse wf (operator ote!)
Generate OMoe operand &, Rod
else i Coperatox sth)
Generake (‘DW operatora Rds
,;
Ext we will generare ‘the cede 407 folowing expression
rere (atby lend) + (C%p)* (o-+b))
[The covrespond ing athree address cede can be give.
i ty catbh
tg ed
tg = Sk
ty —tieta
ty =i * 4
4, = ty +t5Usthg the simple code eration. olgetitiyo the
Sequence tagged tode ~ be qe as
age FJorget code) Register “operand
yess .
Sequence. ptos d toy
code Sequence deserter fy
tyeatb } MaKe) Re empty
ADD b1RO Ry contains + LELLE
tg- ed = Mov Ri Ry contains ©
GuB dik Ry contam be
kant [ter erfs. | Ra contote TT Ta}
Div Fis Ry contains 8,
|
| ae
y= tit fe) Moe Roi Re Fo contales "4 (ea, z &|
| Ry contars 43
ta |R] fh
= |
tyatrt Mot Rat Ro Ra contain ba
Ry contains tl
R, contains ts
ts| R| Ro
|
| | i
te=tytts ADD Riko. Ry contains ty 4
| | Ro conta» be [ «| al &
| Ro contains te
code
expression
ELB* Geneate the code sequence ust?
ae eration eon 4or Ihe sellewng
w= (a-B4(a-9 t(A-9 :
|
Lcode haa
OF Rh ki < op
ae
regi 9) :
Example t
consider the expression
afiJz=b* —
The machine code &
Mov #Ha\Ro
ADD SP; Ro
App 1sp) Ro
Mov by &
Mut ¢a iki
Mov Ri) ¥Ro
Buffer matched templets -
Mov +thaiko me \
peg const a
AbD SP: Ro oes
/\
contke Reqsp
ADD (Sp) 1Ro J‘
tod
”\
const F “4p ‘“Mov b, Ry I
Veq. 4, memb -
MOL Bc,Ry :
;< *
3
i ki
Mov by, % Ry 2
OLN
ind Ri
be
code genevakion for DAGY
Generating code for dag & auch sinpler_
than the \hear Sequence o% three address code -
using DAg we can rearrange some gequente Of
cade
tnstuetions and qrciale an efficient
code ie ml from DAG -
Labellery
Rearrangit Heuxtlte
vad ordering ear ostthm -
| Reaw song i ade
“the onde of three address code afpect
| the cost of the object code being eneral-ed
>in Ine Cense by changihg the Osder th whch
Computations ave done »we ¢an obtaih the objet
code with minimum cost .
4—for example
+t, =atb
dg = e-d
tb, = eq ta >
ty > tits -fow Ihe expression
(a+b) + (et Ce-d)
Dag -for above Sequence *
oo
® B
7 e-
/\
The code can be generated b translating. he
three addvess code line by ine
Mov ajRo
Add by Ro
Mov <, Ry
Sop dR
Mov Rot (4:=0:+b)
Mov ki Ro
ADD Ry iki
Mov 41Ro
Ad) Ris Ro
Mov ky Ey
Rzetle-d)Now tf Wwe ch. lhe cai cequence. of Be
above three addsess code -
ta=c-d :
aes cinta tre irmproved
code as
tis ath ae
ty = titt pode
Mov 2 Ry
ADD Roi ky
Mov ajRo
ADD biRo
Abd RiiRo
Mov Roity .
Q.tteusidde ordering +
Algorithm a
ls obtain all the tnten’or nodes. Consider these
tntertos nodes as unlieted thterfos nodes
Q. while. Cunl&ted taterfor nodes remain)
{
ge Pick up an unksted node 1 whose parenle
have been lated
4, WE ar
5. IAlbele (tbe lept most child ‘mm! of \°
no unttted parent AND i nok leat) |
oe |
has& Lat =ms
Ae nem5
\
5
constdey DAG as
fie
“the seat is i numbered fiom top te bottom
and from left te vighe « ren consider the the unlisted
intertor nodes 1a3a4 Sf
ial the only nede with a pourent is
W moving sole ave Misted nodes
a Yass 6
Now we will find the left mest node of ‘I’ ist!
and pavent of \s' \ which. fs liked » Henee—
Vist 2LMlence the vesulung IE & 1 2 3 4
nen the oxdey of computations & deetded by
reversing thes list-
Now we will pad left mast node of 2 fs le! and
paren of 6 are a and 5. Buk 6 has unlisted
Povent ‘5's tence we can nok Selek c -
We therefore can swilh to 3
LS 4
Parent of 4 fs 1 whtch & ee ea S|
“Lise =3
The lest of 2 fe y.the pavent op 4 @ tg! when
listed Hence att =u ye yh © ©
Left of 4 is 's? which has Itsted paren Cie 2)
elise +5 [ytpas & <]
lek of 5 1 \6' which has a and 5 bolb an (sted
Liat =6 [vv yu ft vel
-As now only g is vernaining from tbe dnbiehed
intery nodes we will list. te
[ey pyvse
5 6 &
we get tre ovder of evaluation os
Cob ee he
shat also Means that we hove le per gos.
the Computations at these modes in the givennumber
t= dle
+, 2a-b
ts S46re
ty = bs ete
ty c ty-&
ty = tetty
t ata*t3
She ques the optewiized cede jor PAG:
S- Labelin Algosithm
The Labeling a ni perates the ophimal
code 4p" Gets expression fn. whitch. minimum
yegtsters ove sequired
= aa cel | algonthor the labelling ca” be
done to te hee at visiting nades tr "bottom - up
order
py he all he child nodes will he labelled
before its parint nodes:
fo computing Label at ‘n'uxth tbe label ly
to lept child and label fe fo le aight child
label (n= JMax (Ls 1 La) pu gee
nal if Ui<=la -Lowe stat ih bottom ~ Up -fashton and left left
lept as lL and tne leat ag Oo -
sdf Leads of the children of a node 'n! ave ugae
wegeclivelyy then -
label (n) = max (tril2) ho ufo
label (n) = Let
Al gedihimi
case 13 Yn & 0 lea node and tt 8 a leas node
4 Laila.
— lead- name tnlo vegistey
cose ay 4 node's atgnt child & a iD ng then
nt | (non)
Here ny iS -fivst evaluated in register on he
Top of the stack and the operation oh idenBipie
(nam! & perfowmed wilh the Same ar a
vohich & on top 4 the Stack °
gose2 Sf Lept child of © fe My Aequetes less
No Of vanishes than Ng then we Swap toptuo Registers on Stack:
ny no
|_J
Hee Ng ts fist evaluated and move to aegis
Then n, if evaluated and move te registers
[nally these two vegisters ave evaluated wilk
the operand -
case yt th the left child My te-quites more no-
On registers than the iy aaa child Ne -
The cae kk o posite to case 3
evaluated fist and then ng- nally evaluated
these tun using the opevatow on the lop of We
- tere n, &
Stack ‘
cose, 5 Both Ike childyen require equal @)
wane
eet %f wegtsteys than available no- of
veqisters then Tae subker 18 evaluated fast -we
and doved ih a aoe mae Then the evaluatton|
Of left subkee i donee And frally drook &
evaluated
CR
“Fy [|r
constr the labelled bee 407 astoronet 0
my 7 Sup RiiTo
you bo!
ap? 7
DADD Roi Ry
Pe Xe S|
wor oh ‘iol ey
Mov cio
Mov x Q
—
Mov bio ad
MUL cho
Mov aiki
ADD 8, Ro
Mov o,to
Mov d,k
MeML ek)
Mov Cc) Ro
ADD Ry iy
SoB R,,be-