Intermediate Code
Intermediate Code
Introduction
Intermediate code is the interface between front end
and back end in a compiler
Ideally the details of source language are confined to
the front end and the details of target machines to the
back end .
+ *
*
d
a -
b c
creating DAG’s
Production Semantic Rules
1) E -> E1+T E.node= new Node(‘+’, E1.node,T.node)
2) E -> E1-T E.node= new Node(‘-’, E1.node,T.node)
3) E -> T E.node = T.node
4) T -> (E) T.node = E.node
5) T -> id T.node = new Leaf(id, id.entry)
6) T -> num T.node = new Leaf(num, num.val)
Three address code
In a three address code there is at most one operator
at the right side of an instruction
Example:
+
t1 = b – c
+ * t2 = a * t1
t3 = a + t2
* t4 = t1 * d
d
t5 = t3 + t4
a -
b c
Forms of three address
instructions
x = y op z
x = op y
x = y
goto L
if x goto L and ifFalse x goto L
if x relop y goto L
Procedure calls using:
call p,n
y = call p,n
x = y[i] and x[i] = y
x = &y and x = *y and *x =y
Example
do i = i+1;
while (a[i] < v);
L: t1 = i + 1 100: t1 = i + 1
i = t1 101: i = t1
t2 = i * 8 102: t2 = i * 8
t3 = a[t2] 103: t3 = a[t2]
if t3 < v goto L 104: if t3 < v goto 100
Generating three-address code for booleans
Backpatching
Previous codes for Boolean expressions insert symbolic labels for
jumps
It therefore needs a separate pass to set them to appropriate addresses
We can use a technique named backpatching to avoid this
We assume we save instructions into an array and labels will be index
in the array
For nonterminal B we use two attributes B.truelist and B.falselist
together with following functions:
makelist(i): create a new list containing only I, an index into the array
of instructions
Merge(p1,p2): concatenates the lists pointed by p1 and p2 and returns a
pointer to the concatenated list
Backpatch(p,i): inserts i as the target label for each of the instruction
on the list pointed to by p
Translation of a switch-statement