Intermediate Code Generation
Intermediate Code Generation
• Intermediate codes are machine independent codes, but they are close to
machine instructions.
• The given program in a source language is converted to an equivalent
program in an intermediate language by the intermediate code generator.
• Intermediate language can be many different languages, and the designer
of the compiler decides this intermediate language.
– syntax trees can be used as an intermediate language.
– postfix notation can be used as an intermediate language.
– three-address code (Quadraples) can be used as an intermediate language
• we will use quadraples to discuss intermediate code generation
• quadraples are close to machine instructions, but they are not actual machine instructions.
– some programming languages have well defined intermediate languages.
• java – java virtual machine
• prolog – warren abstract machine
• In fact, there are byte-code emulators to execute instructions in these intermediate languages.
• But we may also the following notation for quadraples (much better
notation because it looks like a machine code instruction)
op y,z,x
apply operator op to y and z, and store the result in x.
E → - { E1.inloc = E.inloc } E1
{ E.place = newtemp(); emit(E1.outloc ‘uminus’ E1.place ‘,,’ E.place); E.outloc=E1.outloc+1 }
A one-dimensional array A:
… …
• So, the intermediate code generator should produce the codes to evaluate
the following formula (to find the location of A[i1,i2,...,ik]) :
E → ( E1 ) { E.place = E1.place; }
L → Elist ]
{ L.place = newtemp(); L.offset = newtemp();
emit(‘mov’ c(Elist.array) ‘,,’ L.place);
emit(‘mult’ Elist.place ‘,’ width(Elist.array) ‘,’ L.offset) }
Elist → Elist1 , E
{ Elist.array = Elist1.array ; Elist.place = newtemp(); Elist.ndim = Elist1.ndim + 1;
emit(‘mult’ Elist1.place ‘,’ limit(Elist.array,Elist.ndim) ‘,’ Elist.place);
emit(‘add’ Elist.place ‘,’ E.place ‘,’ Elist.place); }
Elist → id [ E
{Elist.array = id.place ; Elist.place = E.place; Elist.ndim = 1; }
mult y,20,t1
add t1,z,t1
mov c,,t2 // where c=baseA-(1*20+1)*4
mult t1,4,t3
mov t2[t3],,t4
mov t4,,x
CS416 Compiler Design 24
Translation Scheme for Arrays – Example3
• A three-dimensional int array A : 0..9x0..19x0..29
n1=10 n2=20 n3=30 width=4 (integers) low1=0 low2=0 low3=0
• Intermediate codes corresponding to x := A[w,y,z]
mult w,20,t1
add t1,y,t1
mult t1,30,t2
add t2,z,t2
mov c,,t3 // where c=baseA-((0*20+0)*30+0)*4
mult t2,4,t4
mov t3[t4],,t5
mov t5,,x