0 ratings0% found this document useful (0 votes) 42 views58 pagesCD Module 8 Print
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Module 8
‘Three address code — Types of Three address code —
Quadruples, Triples, Three-address code for Declarations,
Arrays, Loops, Backpatching
Dr.P. Mohamed Fathimal
AP,CEG campus
Anna University
Contents
+ Intermediate Code Generation
+ Intermediate Languages - prefix - postfix
+ Quadruple - triple - indirect triples Representation
+ Syntax tree- Evaluation of expression - three-address
code
+ Intermediate languages — Declarations
+ Assignment Statements
+ Boolean Expressions, Case Statements
+ Back patching — Procedure calls
11/22/2023What i:
termediate code?
During the translation of a source program into the object code for a target
machine, a compiler may generate a middle-level language code, which is
known as intermediate code
Intermediate code
The following are commonly used intermediate code representation
*Syntax ree
Postfix Notation
*"Three-Address Code
11/22/2023Forms of three address instructions
tx=y
+ goto L
+ if goto L and iffalse x goto L
+f x relop y goto L.
+ Procedure calls using:
+ call pin
syscall pa
[i] and xfi]=y
x= fy and x= ty and *x=y
Three-Address Code
“A statement involving no more than three references(two for operands and
‘one for result is known as three address statement.
+ A sequence of three address. statements is known as three address code.
Three address statement is of the form x= y op z, here x, y, z wil have
address (memory location),
+ Sometimes a. statement might contain less than three references but itis stil
called three address statement.
+ For Example :a=b+c*d;
* The intermediate code generator wil trytodvde tis expression into
sulb-expressions and hen generate the cortsponding code
risers
2
+n
11/22/2023Three-Address Code
+A three-address code has at most three address locations to
calculate the expression. A three- address code can be
represented in three forms :
© Quadrupies
© Triples
© Indirect Triples
Quadruples
+ Each instruction in quadruples presentation is divided into four
fields: operator, arg, arg2, and result. The example is
represented below in quadruples format:
} oP argi | arg? | result
< d 1
b A 2
R a
11/22/2023+ Each instruction in triples presentation has three fields: op, argt, and
‘arg2.The resuts of respective sub-expressions are denoted by the position
of expression.
[op | angi | argz
a © ¢
+ b Co}
a
Indirect Triples
+ This representation is an enhancement over triples.
representation.
+ Ituses pointers instead of position to store results,
+ This enables the optimizers to freely re-position the sub-
expression to produce an optimized code.
po op arg | arg |
iO} a € d
a
@ = a
11/22/2023Postfix Notation
+ The ordinary (infix) way of writing the sum of a and b is with
operator inthe middle: a + b
+The postfix notation for the same expression places the
operator at the right end as ab +
+ In general, i e1 and €2 are any postfix expressions, and + is
any binary ‘operator, the result of applying + to the values
donoted by &1 and e2 is postfix notation by e162 +.
+No_ parentheses are needed in postfix notation because the
position and. arity (number of arguments) of the operators permit
only one way to decode a postfix expression.
+ In postfix notation the operator follows. the operand.
Postfix Notation
+ Example — The postfix representation of the expression
(a-b)* (¢+d)+(a—b)is
ab - ed + ab-+"
11/22/2023Syntax tree
+ Syntax tree is more than condensed form of a parse tree.
+ The operator and keyword nodes of the parse tree are moved
to their parents and a chain of single productions is replaced by
single link in syntax tree.
+The — intemal nodes are operators and child nodes are
operands.
+ To form syntax tree put parentheses in the expression, this
way its easy to recognize which operand should come first.
Syntax tree
+ Example —
x=(a+b*c)/(a—b*c)
11/22/2023Variants of syntax trees
+ Itis sometimes beneficial to crate a DAG instead of tree for Expressions.
+ This way we can easily show the common sub-expressions and then use
that knowledge during code generation
+ Example: ata*(b-c)+(b-c)*d
L™.
CM/S
ZN ‘
Ko
SDD for creating DAG’s
Production Semantic Rules
1) E>ELT E.node= new Node(‘+’, E1 node, T.node)
2) E>ELT E,node= new Node('-", El node, T:node)
3) EST node
4) T>®) Exnode
5) Tid new Leaf{id, id.entry)
6) T>num new Leaf(num, num.val)
examale
1} ptsLeai, entry}
2} P2o.eali, entyralept
3) paeteatia entry)
4) pésteatia entry ¢
5) BS=Nadel! 3,4)
8) péeNodel™ ps5)
7} pT=Nodel "p16
11/22/2023Value-number method for constructing
DAG’s
AN tom
\ZN, tt
+ Algorithm,
+ Search the array for anode M with label op, lft child 1 and right eild r
+ If there is such a ode, return the value naraber M
+ not create inthe array a new node N with label op left child snd sight child r
and retum its value
+ We may use a hash table
Three address code
+ Ina three address code there is at most one operator at the right side of
an instruction
+ Example:
/
o™. /* o
\7\/7 4 Boore
JN
11/22/2023Example
+ doi= itl; while (afi] < v);
L: thsi¢l
i=tl
2=i"8
13 = alt2]
ift3 equivalence
constructor to structurally equivalent types. J
3.One is a type name that denotes the other. — poder
+ int a/2]/3] is not equivalent to int b/3]/2J; int ais not
+ equivalent to char [4];
+ struct fint, char} is not equivalent to struct {char, int};
+ int * is not equivalent to-void*:
11/22/2023
12Type Checking
Type expressions are checked for
-Correct code
“Ss
-Efficient code generation
Compiler determines that type expressions conform to
a collection of logical rules, called as the type system
of the source language.
‘Type synthesis: if fhas type s + t and x has type
s, then expression f(x) has type t.
Type inference: if f(x) is an expression, then for some
cand B, f has type a — B and x has type an.
Type System
* Potentially, everything can be checked dynamically...
— _iftype information is carried to execution time
A sound type system climinates the need for dynamic
* type checking.
A language implementation is strongly typed ifa
* compiler guarantees that the valid source programs
(it accepts) will run without type errors.
11/22/2023
13Type Conversions
int a= 10; float b= 2 * a;
Widening conversion are safe.
~int + long — float —> double.
~Automatically done by compiler, called coercion.
Narrowing conversions may not be safe.
~int — char.
Usually, enforced by the programmers, called casts.
-Sometimes, deferred until runtime, dyn_east<..>.
Declarations
When declarations are together, a single offset on
the stack pointer suffices.
int x, y, 75 fum1(; fun20;
Otherwise, the translator needs to keep track of the
current offset.
~int x; fun1(); int y, z; fun20;
A similar concept is applicable for fields in. structs.
Blocks and Nestings
~ Need to push the current environment and pop.
11/22/2023
14Declarations
D7 Tid; De
T -+ BC | record '{' D'}Y
B -» int | float
C + ¢| Cnumic
Storage Layout for Local
Names
+ Computing types and their widths
T+ 8B {t= Bulype; w = B.width; }
c
B > int { B.tyve = integer; B.width = 4; }
B > float { B.type = float; B.width = 8; }
Ca. { C.type = t; C.width =; }
CO > Cnum] C, { array(num-value, C; iype)
C.width = num. value Cy width; }
11/22/2023
45Storage Layout for Local
Names
© Syntax-directed translation of array types
Sequences of Declarations
Po { offset = 0; )
D
D+ Tid; { top-patlic.tereme, T.tupe, offset)
offect = offset + T.width; }
D
“De
P+ MD
Mo © { offset=0;)
11/22/2023
16Fields in Records and Classes
float x;
record { float x; float y; } p;
. record { int tag; float x; float y; } qi
T + record '{’ { Bnv.push(top); top = new Envi);
Stack push( offset); offset = 0; }
Dy { T.type = reeori(top); T-avidth = offset;
top = Enw.pop(); offset = Stack.pop(); }
Static Single Assignment
{some observations
L Definition of a variable killsits previous definition.
LA variable's use refers to its most recent definition
LA variable holds a register for a long time, if itis live
fonger.
11/22/2023
17SSA
* Static Single Assignment
- Each definition refers to a different variable (instance)
Language Constructs
+ Declarations
~Types (int, int [], struct, int *)
Storage qualifiers (array expressions, const, static)
+ Assignments Conditionals, switch
+ Loops
*+ Function calls, definitions
11/22/2023
18SDT Applications
+ Finding type expressions
~ int a[2)[3] is array of 2 arrays of 3 integers.
~ in functional style: array(2, array(3, int)
T+Bac Tt=ct
Cizat
Bint Bisin
Boat
C= Tnum 16,
cae
SDT Applications
+ Finding type expressions
~ int a[2J[3] is array of 2 arrays of 3 integers.
~ in functional style: array(2, array(3, int)
oe
Topic Tt
c.
Basin 8
Bo fost 8
C-[mumic, ©.
©.
«:
cue
12 Ci Csw=Ciw;
11/22/2023
19Translation of Expressions and Statements
Expressions
+ Wehave sued expression at eng
«To generate 3AC, we will use our grammar and its associated SDT to generate
IR,
For instance, a = b+ -¢ would be converted to
11 = minus ¢
2=bet
a2
Three-address code for expressions
Sweade = B.eod: I
gen(top-getid.eserns) "=! Badd)
B+ B+ R, | Bete = now Temn()
vente = Bcaly | B.code
igen(B.adds "=! Ey adde'4! Bgadé)
| =e, | Beatty = ew Teme)
Bacode = By-cote |
yen( Dudas ‘=! uusus! By uddr)
| CB) | Beatdr = Boar
Bucode = code
tep-gelGd.lereme)
11/22/2023
2011/22/2023
Incremental Translation
S + id =F; { gen(top.get{id.teceme) "=! F.adar); }
E> E+E: { B.addr— new Temp();
gen(E.addr '=' E) ,adir'+! Ep,addr}; }
| -B { B.addr = new Temp ();
gen(E.addr'=! ‘minus’ 2 .addr); }
| CB) { B.addr = By.addr; ]
| ia { B.addr = top.get{id leveme); }
ArrayExpressions
+ For instance, create IR for ¢ + afi].
+ This requires us to know the types of a and c. Say,
+ cis an integer (4 bytes) and a is int [2][3]. Then,
+ the IRis
21Addressing Array Elements
+ Layouts for a two-dimensional array:
Firat rome
Tangy | |e
[amar] Pe
[AEA eon tame
(aar] So?
Seoul row AS | ied ent
Bs ~J t
(@) Raw Major (b) Cotumn Major
Semantic actions for array reference
S A0= {gen tp ge eneme} =! Roady,
Le Ey (gpnloeddrdase Loadir' 1 Bade)
Byte | Badie= new Temp
sonar! Bodies! Bad); )
| ia { Buadde= tpt deem); )
be A Baadée ~ mw Teno 0
sen Evade’ Larroysaze'( Leader's}
i) MLE (Lemay = opsetiddezrne),
Like L-ermyype cer
Lede = or Tem
srk Ladde!= B nade! Lie with); )
[ty CET (Loesrap= army
Ti Dadar sem
ago ith)s }
en Fundy Cy td's ty)
11/22/2023
22Translation of Array References
Nonterminal L has three synthesized attributes:
*Laddr
+Larray
*Latype
Conversions between primitive
types in Java
double double
1 ’
‘float float
| 1
long long
conversions (b) Narrowing conversions
11/22/2023
23Introducing type conversions into
expression evaluation
E> By +B, { E.type = mac(Ey.type, Fa.type):
0, = widen(E.addr, Ey type, E.type);
= widen(#,.addr, E.typa, type);
E.addr = new Ternp ();
gen(B.addr'=! ay '+! ap); }
Abstract syntax tree for the
function definition
fun engto9
if ul) then O else lengeh(lex}= 1)"
mi “sgn
oe og
me
This is a polymorphic function w %
in ML language
11/22/2023
24Inferring a type for the function
length
“Tawa | BXPRSsIoN :_I'YPS
D| Teng = 8
2) 2.0
a) if: doclamxo:xa;—a: |
4) all stay) -> boolean
3 alls) + bwotewe ) tstfan) = 2
6) + integer (4 = integer
7 + integer ¥ énteger + integer
x) a> alg) —+ tata)
») Ha): Hist lista)
to) | tenyab(ee}) >
1s integer
a)}-41 + integer
) + atener
Boolean Expression
+ 1, The translation of if-else-statements and while-statements is tied to the
translation of boolean expressions,
+ In programming languages, boolean expressions are used to
+1. Alter the flow of control.
+ 2. Compute logical values.
Alter the low of contro,
* Boolean expressions are used as conditional expressions in statements that
alter the flow of control
‘The value of such boolean expressions is implicit in a position reached in a
program.
For example, in if (E) S, the expression E must be true if statement S is
reached.
+ 2, Compute logical values
* A boolean expression can represent true or false as values,
* Boolean expressions can be evaluated in analogy to arithmetic expressions
using three-address instructions with logical operators.
11/22/2023
25Boolean Expression
+ The intended use of boolean expressions is determined by its syntactic
context
+ For example, an expression following the keyword if's used to alter the
flow of control, while an expression on the right side of an assignment is
used to denote a logical value.
+ Such syntactic contexts ean be specified in a number of ways:
+ we may use two different nonterminals, use inherited attributes, or set
a flag during parsing.
+ Alternatively we may build a syntax troe and invoke different
procedures for the two different uses of boolean expressions,
Boolean expressions
+ Focus on the use of boolean expressions to alter the flove
of control
+ Boolean expressions are composed of the boolean operators
+&& - AND, II - OR, and ! - NOT
+ applied to elements that are boolean variables or
relational expressions
+Relational expressions are of the form El rel £2,
where E/ and E2 are arithmetic expressions
+ Grammar to gencrate Boolean expression:
BB) or B: |B» By and B: | B—»not By |B» (B))B > Firelop |
Bo false! Br true
11/22/2023
26Boolean expressions
lefntion ofthe programming language determines
whether all parts of a boolean expression must be
evaluated,
+ Ifthe language definition permits (or requires) portions of «boolean
expression to go unevaluaed
* the compiler can optimize the evaluation of boolean
expressions by compating only enough of an
expression to determine its valu
+ In an expression such as BI 11 B2, neither BI nor B2 is necessarily evaluated
rally
*If we determine that B1 is true, then we can conclude
that the entire expression is true without having to
evaluate B2.
+ Similarly, given B1&&B2, fB1 is als, then the entire expression is false
Short-Circuit Code
+ In short-circuit (or jumping) code, the boolean operators &&, I, and !
translate into jumps.
+ The operators themselves do not appear in the code
+ Instead, the value of a boolean expression is represented by a position in
the code sequence.
s8 (x €100 |] x> 200 bk x
+ The statement
peo;
if x ¢ 100 goto Le
stfniee = > 200 goto Ly
might t
+ Inthis translation, the Boolean expression is true if control reaches
label 12,
+ Ifthe expression is false, control goes immediately to L1, skipping \2
and the assignment x= 0.
11/22/2023
27Flow-of-Control Statements
+ Translation of boolean expressions into tarec-address code in the
context of statements generated using the following grammar
Sit si
S>if(B)SI else S2
S=> while(B) SI
+ Non terminal B represents a boolean expression and nonterminal S
represents a statement
Boolean Expression
+ Synthesized attributes associated with Boolean expression and Statement
+ B.code ,S.code- gives the translation into three-address instructions
+ Inherited attributes associated with Boolean expression and Statement
+ B.tmue-- label to which control flows if B is true
+ B,false ~ label to which control flows if B is false
Sinext - label attached tothe fist 3-address statement to be executed
immediately after the code for S.
+ Functions used in Syntax directed definitions
+ newlabel() creates @ new label each time itis called
+ label(L) attaches label L to the next three-address instruction to be
generated
11/22/2023
28Syntax directed definition for P > S
eh = wale)
Prod = See
3+ sign Se = asign le
> $ Program P consist of statement §
‘Snextis initialized to to 2 new label
Prcode consists of S.code followed by the new label S.next
assign isa placeholder for assignment statements
Syntax directed definition for S > S,S,
84+ SS Srnext = newlabel()
Sonext = S.next
Seode = Scone |\ label
+ SI followed by the code for $2
+ The first instruction aftr the code for SI is the beginning of the cade for $2
+The instruction aftr the code for S2 is also the instruction aftr the code for S.
ert) |) Se.coe
11/22/2023
29Control-Flow Translation of Boolean
Expressions
Propuction Semaxric RoLEs
B+ teue | Beale = gn’goto! Barve)
B+ tale | Basade= gen got! B fale)
The constants true and false translate into jumps to B.true and
Bialse, respectively
Syntax directed definition for Boolean Expression $ -> if (B) 1
10, Batrue Syntax-directed definition
Bucode lta Bfalse
— $4(8)8, |= wl
Btrwes) 5, code fds Sas St
ink = Bo BS ade
Bealse + |
(a) it
+ Create a new label Bru and aac it othe first three-addess instruction generated
forthe statement SI
+ Within 8. code are jumps based on the value of ®,
+ If Bs true, contral flows to the ist instruction of SI code, and
+ If 8's false, contro flows tothe instruction immediately following SI.cose.
+ By setting B false to Sinext, we ensure that control will skip the code for SI if
evaluates to false
11/22/2023
30Syntax directed definition for Boolean Expression
S-> if (B) SI else S2
|
Syntax-directed definition
—
+ Create 10 fits B.true and B false
+ ITB is true, B jumps tothe first instruction of the code for SI
IB is false, jumps to the first instruction of the code for S2
Control flows fiom both SI and S2 to the three-address instruction
immediately following the code for S ~ its label is given by the inherited
attribute next
An explicit goto S.next appears after the code for SI to skip over the code
for 82
No goto is needed after S2, sindé'S7“%2XU' the same as S. next.
Boolean Expression S > while (B) S1
Syntax-directed definition
sens Be nT
[Beate emjie —5-vncays Jug mat
— least
Biwe tT s code | | Since = Soe
ee eres
area eerte
jae (0 we
‘begin —local variable that holds anew label attached tothe first instruction for the
‘while-stalement, also the Gist instruction for B.
‘begin isa variable rather than an atibute, because begin is local to the semantic rules
for this production,
S.mext - marks the instruction that control must flow to if B is false; hence, B, false is set,
tobe S.next
B. true Code for B generates jump to this label ifB is rue and attached tothe fist
instruction fr S|
_goto begin ~ causes a jump back tthe Rezianing.of the code for the boolean expression
S1 next s set to this label begin, so jumps from within $1. code can go directly to begin
11/22/2023
31Control-Flow Translation of Boolean
Expressions
B+ BIB, | Brtrwe= Bite
nealael()
Batrue
B,false
code | label fase) || By-code
then mabe ste ae be ol othe ttn tea or
+ That arte ont of aretha same thereon ooo pct
Control-Flow Translation of Boolean
Expressions
PRODUCTION Senawrie Retes
B — By, && By | B,.true = newlabel{)
By false = B false
| Batrue = Batre
| By false = B.false
| Brecode
code || label(By true) || Ba.code
+ If.81 is tue, then 82 must be evaluated so make 81.17Ue is assigned as the label
‘of the fist instruction inthe code for &2
+ 1181 is false, then 8 itsel is false, s0 81 flses the same as B,folse
+ If2is true, then @ itself is true, so &2true is the same as .true
+ 1782s false, then 8 itself is false, s0 82 flses the same as B,folse
11/22/2023
32Control-Flow Translation of Boolean
Expressions
Probvcrion
SEMANTIC RULES
B+ Eyrel By | Booode = By.code || Ey code
| gen(it! Es.addr rel.op Fz.addr ‘goto’ true)
| gen( gota! B false)
+ Translated directly into a comparison three-address instruction with jumps to
the appropriate places
+ Forinstance, 8 ofthe form a 200 @ex !my) x= 0;
if x < 100 goto Ly
goto Le
if x > 200 goto Ly
goto Li
it x != y goto la
goto Li
11/22/2023
35Backpatching
+ Akkey problem when generating code for boolean expressions and flow-of control
statements is that of matching a jump instruction with the tanget of the jump.
+ For example, the translation of the boolean expression B in if (B) $ contains a
jump, for when B is false, to the instruction following the code for S.
+ Ing one-pass translation, B must be translated before S is examined.
+ What then is the target of the goto that jumps over the code for S?
For implementing syntax-directed definitions, the easiest way is to use two passes.
‘+ First syntax tee is constructed
+ Then traversed in depth-first order to compute the translations given in the
definition,
Problem in generating three address codes in a single pass for Boolean expressions
and flow of control statements is
We may not know the labels that control must go to at the time jump statements
are generated
Backpatching
+ This problem is solved by generating a series of branch statements with
the targets ofthe jumps temporarily left unspecified,
+ Each such statement will be put ona list of goto statements whose labels
will be filled in when the proper label ean be determined.
+ This subsequent filling of addresses forthe determined labels is called
BACKPATCIING,
+ For implementing Backpatching
+ Instructions are generated into an instruction array
+ Labels act as indices to this array.
+ To manipulate list of labels three fanetions are used
+ makelist( : creates a new list containing only i, an index into the array
of instructions and retums pointe to the list t bas made.
+ merge(i,) ~ concatenates the lists pointed to by i andj and returns @
pointer to the concatenated list,
+ backpatch(p,)— inserts asthe target label for each othe statements
con thelist pointed to by p.
11/22/2023
36Backpatching
+ The variable nextinstr holds the index of the next instruction to
follow.
+ This value will be backpatched onto B, truelist in case of B—> Br and
MB» where it contains the address of the first statement of B,.code.
+ This value will be backpatched onto By fascist in case of BB: or
‘MBs where it contains the address of the first statement of B,.code.
Backpatching-Boolean expressions
* We use the following semantic actions for the above grammar
+1)B—>B, or MB,
backpatch(B;.falselist, M.instr)
Btruclist = merge(B, truclst, B,.truclist)
B falselist = B, falselist
+ If B1 is true, then B is also true, so the jumps on BZ. truelist become part of|
Buaruelist.
+ IFBT is false, we must next test B2, so the target for the jumps BI falselist must
be the beginning of the code generated for B2.
+ This target is obtained using the marker nonterminal M.
‘+ M produces, as a synthesized attribute M.instr, the index of the next
instruction, just before B2 code starts being generated
‘+ The value M.instr will be backpatched onto the BI .falselist (ic., each
instruction on the list BZ. falselist will receive M.instr as its target label) when
‘we have seen the remainder of the production B -> BL or M B2.
11/22/2023
37Backpatching -Boolean expressions
2)B > B, and MB
backpatch(B, truelist, M.instr)
B.truelist = Bp truelist
B falselist = merge(B;.falselist, B,,falselist)
+ IFBL is true, we must next test B2, so the target forthe jumps BI. truest must be
the beginning ofthe code generated for B2.
+ This target is obvained using the marker nonterminal MLinstr, the index ofthe next
instruction, just before B2 code starts being generated
+ The value MLinstr wil be backpatched onto the Bt.truelist.
+ IPB is fase, then B is also false, 50 the jumps on BI. falselst become part of
Bfalselist,
Backpatching-Flow of control
{ backpatch(S: netlist, My-instr)
Dackpaten(s.truclist,” Ma instr):
Sincstlist — D-falaclist:
femat(igate! My 9m:
+ Inthe above production
+ Two occurrences ofthe marker nonteeminal MF
+ Used to record the instruction numbers ofthe beginning ofthe code for B and
the beginning ofthe code for St
+ Forthe ule M->€, semantic action is ( Minst = nextinst; }
+ After the body $1 ofthe while-satement is executed, control flows to the
beginning.
+ When the entire production is reduced to S, ST.nextlit is backpatched to make
all targets on that list be ML. instr
+ ‘An explicit jump tothe beginning ofthe code for Bis appended after the code for
$1 because control may also "fll out the bottom.”
+ Batruelstis backpatched to go tothe beginning of $1 by making jumps on B.
truest goto M2 . inst.
11/22/2023
38Backpatching-Flow of control
S > ACB) My SN elwe My Sa
{ backpateh(B.truclist, M; instr)
backpateh(B fatselist, Mz-instr)s
temp = merge(Si-neztlst, N-nextlist)
S.nezthist — ‘merge(temp, Sa.neztlist) }
+ Ifcontrl "falls out the bottoms” of SI, as when SI isan assignment
+ code has t be inchaded atthe end of SI to jump t9 $2.
+ Anew noaterminal N with production N > es introduced for this purpose
has attribute N.nextlst, which will be alist consisting ofthe instruction
numberof te jump goto -that is generated by the semantic action (7) for N
‘When B is true, jumps are backpatched to the instruction MLinste;
imilarly, when B is fase jumps are backpatched to the beginning ofthe code for
82
S.neatlis
fncludes al jumps out of SI and $2, a8 well as the jump generated by N,
temp isa temporary variable that is used only for merging lists,
Backpatching-Flow of control
TFTA MS —— { haekpateh( hy nextlist, M instr),
TE nestlise = 'Snertliet, }
ras { Fo noxthior — Snectl
oa
Above two productions handle sequences of statements,
InL->L,MS
+ Insituetion following the code for L1 in order of execution isthe Beginning of
8
+ Thus the L1 .nexlist lst is backpatched tothe beginning ofthe code for S,
which i given by M.
+ InL-> SL, nextlist ithe same as Snextlist
11/22/2023
39Backpatching for Boolean Expressions
Bo By VM Bo | By M8 AF By |! By | (By) | La vel By | true | false
Moe
1) Bo By I AEB) { bockpateh By falslist Mins)
Besrwelit = werye( Dy tela, By tru)
B felis = Be feochit |
2) BB Lk MB, { beckpateh(By.trwclist, Minute;
Btrelit = By truetist
cre fll, Ba fsa}
forcis
a) Ba 1D, t
) BU) ‘
Br fascists
5) BB relB, — { Butraclst = mabelit(nestinst);
DB falelst = maheise(nestinaty | 1);
formes iy addr eeh.op Bs adr 'goe0
amit’ goto}
©) Bs bene [ Dtewiot— small weatinati),
DB fates
s) M ve
BB)
Baruelis
Billi
5) Bid relop id sects mo nein,
Bacruelist= makelisinextinst) Sno pt nd arena
BB fulsclist= mukelist(nextinst+1 ) gts ve nite ages
«mit place relop id place got ‘Testis pt Ria
emi(goto _) ee Site Saar /
on =
Bruelst~ makelisi(nextinst)
emi(goto __)
7B false
E falslist~ makelist(nextint)
emi(goto_)
Moe
Minstr~ nextine;
11/22/2023Example-Backpatching for Boolean
Expressions
+ Annotated parse tree for x < 100 | x> 200 && x !=y.
Ba = {100,104}
Bf = (108, 105}
pres
ra
ar
bi p04 | a= (04)
Bj = {103} © ‘Bf = (105)
7iN 71\
= 5 Soo rey
Flow-of-Control Statements-
BackPatching
1) 8-408) AES {ino Arty Ms
Sinrtiat = race Sobek, Seat) }
2) S> MBM LS. oe Mh Sy
“lect li, Mite
Sect
‘oa = elon es ese
iat = men Seri}
Theoratt
© + while My (B) Mo S:
SCL (Sntlat — Lnetteh)
gona {Simei = na
OMe (aes a
nase CNnegtat = meeltvetnsts
Paltzeeo 1,
SELL MS — (Yedyusity att aut
Tat Seat |
9 oe Ueamstit = Seat)
11/22/2023
a1Translation of a switch-statement
be
switch CF) £ u
ease Vis 5
cease Vat So
Inet
cease Vint: Snot
default by
? test
code to evaluate B into t
goto test
code for S;
goto next
code for S
goto next
code for Sut
goto next
code for Sq
goto next
Vi goto ta
Vp goto Ls
aft
if
itt
goto
lo
coi to evauate Bato ©
set te Vi
toa foe 8
goto next
code for Ss
goto next
g0to Ly
At I+ Vy goto by
code fr 8,
gots next
fede for Sg
Control-Flow Translation of Boolean Expressions -Example
Consider the
‘S.noxt
u
11/22/2023
42ene
ire — sce
Baru
Bufflse
fie et
Dif Be
ate de
It condition goto L2
goto L3 B, true = B.true=
LS:TB2.condition goto L322 B, false = L3.
= gotoLt B,.tnie = B.true =
“12: x=0 L2 B, false:
u Bufalse= Lt
11/22/2023
43exe too goto 2
Er Baconaton goto 2
sul
11/22/2023E82 conden aot
Backpatching-Boolean expressions Example
Consider the
expression
838, orMa,
backpatch( 6, falselst, Mnstr)
Baruelst = merge(@, truest,
B,sruelist)
Bialselst = B, falselist
11/22/2023
45Backpatching-Boolean expressions Example
8 D
a =
/
8 > id elo de
Bisbee matcietmestnset) SB 100: Gf x < 100 goto -
emit. place rlop dy place goto) 101: goto
emitigoto
Backpatching-Boolean expressions Example
fren hh tie 302
8 > B,orMB, 7
backpatch(®, flselist, Mins)
Brruolist = merge(8, truest,
B,truelis)
Bialselist = 8, falselist
11/22/2023
46Backpatching-Boolean expressions Example
—
8 ld, reloo id i
Biruelist = makelist(nextinstr) mmmmp 102: if x > 200 goto -
8 falselist = makelist{nextinstr+1 ) 103: goto
cemit{if id, place relop id, place goto _)
femit(geto __)
Backpatching-Boolean expressions Example
et
“The arr nonterminal Min the
production records the value of
2)8 > 8, and MB,
backpatch{®.trulist, Mins)
Baruelist = 8, truest
B falselist « merge(B flselist, 8 falselist
11/22/2023
a7Backpatching-Boolean expressions Example
8 > id elope
Bruel ~makeli(nentinste 10
eit place rep place woto_) Ss
emitigoto
if x != y goto -
goto
Backpatching -Boolean expressions Example
——- e
cc) =
Inetruction in 02 ied with
Baruelst = 3, traelst
Bfalselst = merge(B;flselist, 8 falselst)
108: goto
10k Se x te y goto
105: goto
2)B28,and8e.8,—
ackpatch(6, truest, MiinsD ton 00: iz x'< 100 goto
11/22/2023
48Backpatching-Boolean expressions Example
Ly
fleet 103
+ aexpsth(103,202)—Instructon
b> Bonus. in 201s fle with 202
8 100: < 100 goto
Backpatch(s,falselist, MinsteD
Br TUT, 8 truelst) (01: goto 102
Bfalselst = 8, falselist 10 —IFF> 200 goto 104
103: goto
104: if x t+ y goto _
105: goto
Backpatching-Boolean expressions Example
caver ot kts)
Sevan
[wet tie
se itze age. | SEER iae )
OL, goto 102 es /
tna: Sty > 20 goxe IO
MOS goto
toe Se oy goto -
105: gee
11/22/2023
49Backpatching-Boolean expressions
Example
‘Annotated parse tree for $f( x © 100 (I-x > 200 8k x te) x= 0
Backpatching-Flow of control
+ Backpatching can be used to translate flow-of-control statements in
‘one pass.
+ Consider statements generated by the following grammar:
S++ if(B)S | if(B)S else | white(B)S | 03];
L+s|s
+S denotes a statement
+ L denotes statement list
+ B denotes boolean expression
11/22/2023
50Backpatching-Translation of Flow of
control statements
Avoiding Redundant Gotos
if x > 200 goto L4
+ Translated code of Boolean
goto L1 tresons are not
cptinited ores
L4: * Redundant gotos are
> rotieed
iffalse x>200 goto fiwougn
U1 La
(fall through)
11/22/2023
51