Presentation is loading. Please wait.

Presentation is loading. Please wait.

Translation to Intermediate Code Chapter 7 Cheng-Chia Chen.

Similar presentations


Presentation on theme: "Translation to Intermediate Code Chapter 7 Cheng-Chia Chen."— Presentation transcript:

1 Translation to Intermediate Code Chapter 7 Cheng-Chia Chen

2 2 Intermediate Representation (IR) A kind of abstract machine language Express target machine operations without machine specific detail independent of the details of the source language compiler front-end: –lexical analysis  parsing  semantic analysis  translation to IR back-end –optimization on IR  code generation

3 3 Compiler for several languages and machines Good IR –must be convenient for semantic analysis –must be convenient to translate into real machine code –has clear and simple meaning –ie., SIMPLE but GENERAL! Java ML Pascal C C++ Sparc MIPS Pentinum Itanium Java ML Pascal C C++ IR #Transformations:MxN M+N

4 4 Intermediate Representation Tree package tree; // IR tree abstract class Exp –computation of some value (with side-Effect) CONST(int value) –integer constant value NAME(Label label) –symbolic constant label ( corresponding to assembly language label, i.e., a program loc ) reference. TEMP(temp.Temp temp) –a temporary (i.e., a loc for storing data); like registers in real machine but the abstract machine has infinitely many temporaries. BINOP(int binop, Exp left, Exp right) – (left +/* right)

5 5 tree.Exp (continued) MEM(Exp exp) –the content of wordsize bytes of memory at address exp. –means “store” when at left child of MOVE and means “fetch” otherwise. CALL(Exp func, ExpList args) –procedure call func(args) –func is evaluated before args, which is evaluated left to right. ESEQ(Stm stm, Exp exp) –evaluate stm with side effect, then return exp.

6 6 abstract class tree.Stm perform side effect and control flow. MOVE(Exp dst, Exp src) // two forms – MOVE(Temp t, e) – evaluate e and move it to temporary t – MOVE(MEM(e1), e2) – evaluate e1 to get an address a, store the result of e2 into wordsize – bytes of memory at address a. EXP(Exp exp) // ExpStm(Exp exp) –evaluate exp and discard the result LABEL(Label label) –Define the constant label “label” to be the current machine code address. –like a label definition in assembly. –can use NAME(label) as the target of jumps, calls,etc.

7 7 abstract class tree.Stm JUMP(Exp exp, temp.LabelList targets) –transfer control to address exp, where exp must be one value in targets. –exp may be a label reference i.e., NAME(lb) or may be an address that can be calculated by other Exp. –to jump to known label lb, use JUMP(NAME lb, new LabelList(lb,null)) CJUMP(int relop, Exp left, Exp right, Label iftrue, Label iffalse) –evaluate left, right; compare left and right using relop relation; –if result true goto iftrue else goto iffalse. –possible relop: EQ,NE for integer. signed integer: LT,GT,LE,GE. – unsigned: ULT,ULE,UGT,UGE. SEQ(Stm left, Stm right) –execute left and then execute right.

8 8 Intermediate Representation Tree (cont’d) other classes ExpList(Exp head, ExpList tail) StmList(Stm head, StmList tail) Other constants: public class BINOP { final static int PLUS, MINUS, MUL, DIV, AND, OR, LSHIFT, RSHIFT,ARSHIFT,XOR; … } pubilc class CJUMP { final static int EQ, NE, LT, GT, LE,GE, ULT, ULE, UGT,UGE; …}

9 9 Translate into Tree syntaxtree.Exp  translate.Exp  tree.Exp Ex(),Nx(),Cx() Exp(),Stm() IdentifierExp() -> Ex.unEx() -> tree.MEM() Assign() -> Nx.unNx() -> tree.MOVE() Plus() -> Ex.unEx() -> tree.BINOP() Plus() -> Ex.unCx() -> tree.CJUMP() LessThan() -> Cx.unCx() -> tree.CJUMP() LessThan() -> Cx.unEx() -> tree.ESEQ() And() -> Cx.unCx() -> tree.CJUNP()

10 10 The Idea How might an expression be used ? –Every expression will be used differently. –some return value, some return non, some will transfer control. Need to define methods for an Object-oriented interface to expressions. package translate; pubic abstract class Exp { abstract tree.Exp unEx(); //Exp2Exp abstract tree.Stm unNx(); // Exp2Non abstract tree.Stm unCx(temp.Label t, temp.Label f); //Exp2ConditionalJump …}

11 11 Ex : expression represented as a tree.Exp Nx: expression represented as a tree.Stm Cx: expression represented as a function f from label pris to statements. –e.g;: relative operations –If you pass it two labels: say, t for ture and f for false, then it will return you a tree.Stm that will jump to t if Exp is evaluted to true and jump to f if Exp is evaluted to false. e.g: a > b || c < d

12 12 Example: a > b || c < d tree.Stm unCx(Label tt, Label ft) { Label zz = new Label(); return new SEQ ( new CJUMP(CJUMP.GT, a, b, tt, zz), new SEQ ( new LABEL(zz), new SEQ ( new CJUMP(CJUMP.GT, c, d, tt, ff ))) a>b c<d zz: true false true false tt : ff: CJUMP(>,a,b, tt, zz) LABEL(zz:) CJUMP(<,c,d, tt, ff)

13 13 Conversion rules Ex(Exp) Nx(Stm)Cx  ReCx(op,Exp,Exp) tree.Exp unEx() eESEQ(s, CONST(0)) ESEQ(r  1, c(t,f), f: r  0, go t t: r) tree.Stm unNx() ExpStm(e) (evaluate e, disgard result) sSEQ(c(j,j), j: ) Stm unCx(t,f) e != 0 =>goto t e==0 => goto f never happenCJUMP(op, left,right,t,f)

14 14 Ex: subclass of translate.Exp an ordinary expression yielding a single value class Ex extends Exp { tree.Exp exp; Ex(tree.Exp e) {exp=e;} tree.Exp unEx() {return exp;} // if(exp!=0)goto t else goto f tree.Stm unCx(Label t, Label f) { if (exp instanceof CONST) if (((CONST)exp).value!=0) return new JUMP(t); else return new JUMP(f); else return new CJUMP(CJUMP.NE,exp, new CONST(0),t,f); } tree.Stm unNx() {return new tree.ExpStm(exp);} }

15 15 Expression that yields no value Nx: subclass of Translate.Exp class Nx extends Exp { tree.Stm stm; Nx(tree.Stm s) {stm=s;} tree.Exp unEx(){return new tree.ESEQ(stm, new CONST(0));} //-> never happen Tree.Stm unCx(Label t, Label f) { throw new Error("Nx.unCx"); //Never happen } Tree.Stm unNx() {return stm;} }

16 16 Cx: subclass of Translate.Exp A “conditional” expression that jumps to either t or f: eg: flag := (a<b && c<d) Cx_Obj(a<b && c<d).unEx() = 1 if true, 0 if false abstract class Cx extends Exp { abstract Tree.Stm unCx(Label t, Label f); Tree.Stm unNx() { Label tf = new Label(); return new Tree.SEQ( unCx(tf,tf), new Tree.LABEL(tf)); }

17 17 tree.Exp unEx() { Temp r = new Temp(); Label t = new Label(); Label f = new Label(); return new ESEQ( new SEQ( MOVE(new TEMP(r), new CONST(1)), new SEQ(unCx(t,f), new SEQ(new LABEL(f), new SEQ(new MOVE(new TEMP(r), new CONST(0)), new LABEL(t))))), new TEMP(r)); }

18 18 Translate Simple Variables A simple v declared in the current stack frame will be MEM(BINOP(PLUS, TEMP fp, CONST k)) where k is the offset of v within the frame TEMP fp is the frame pointer register

19 19 Frame class : all machine-dependent stuff Package frame; public class Frame { … abstract public TEMP FP(); abstract public int wordSize(); } public abstract class Access{ public abstract tree.Exp exp (tree.Exp framePtr) } The exp method of f rame.Access is used by Translate to turn a f rame.Access into the Tree expression.

20 20 Tree to access the local variable in Frame The tree.Exp argument of exp is the address of the stack frame that the Access lives in. Eg. frame.Access a such as InFrame(k), a.exp(new TEMP(frame.FP())) = MEM(BINOP(PLUS,TEMP(frame.FP()), CONST(k))) The reason why the argument of exp is tree.Exp: It is the code to access the fp from register or static links.

21 21 Ex: program public class Access { Level home; Frame.Access acc; Access(Level h, Frame.Access a) {home=h; acc=a;} } public class Level { public Level parent; Frame.Frame frame;// not public! public Level(Level p, Symbol name, BoolList escapes) { parent = p; frame = parent.frame.newFrame(name, escapes); } Level(Frame.Frame f) { frame = f; } public Temp.Label name() { return frame.name; } public Access allocLocal(boolean escape) { return new Access(this, frame.allocLocal(escape)); }

22 22 Array Variables In MiniJava array variables behave like pointers –new array values are created and initialized by the constructor new int[n], where n is the number of elements and 0 is the initial value of each element. MiniJava objects are also pointers –object assignment is the pointer assignment. –Cf: Records of C, Pascal –Cf: Array of C, Pascal

23 23 Structured L-values l-value : left of assignment -> location –eg. x, p.y, a[i+2] r-value : right of assignment -> contents –eg. a+3 f(x) All the variables and l-values in MiniJava are scalar –no case like A := B // copy B array into A array –if not, we need size of variables in Access –We need to modify MEM(Exp) to MEM(Exp, Size) –C struct, PASCAL array and record are structured l-value. –we are lucky!

24 24 Subscripting and field selection a[i] (i-low) x s + a a.f a+ offset(f) if a is global constant addr, a – low x s con be precomputed. if low = 0 and a = MEM(e) => a[i] = MEM(+(MEM(e), BONOP(MUL, i,CONST(W)); Technically, l-value should be represented as an address. –as r-value ==> use MEM[addr]. –In the book, l-value is represented as MEM[addr] with the knowing that – MEM means both store(in lhs) and fetch(elsewhere).

25 25 A sermon on safety Compiler need to emit code to check array boundary. but if it can guarantee the safety, it may omit the checking code.

26 26 Arithmetic AST operator  IR Tree operator no unary arithmetic operator – e.g. – 4 ==> 0 – 4. – ~ n ==> 0 XOR n

27 27

28 28 Conditionals The result of a comparison operator will be a Cx expression. –A statement that will JUMP to any true-or-false destination Simple Cx expression from AST comparison operator –CJUMP operator. x CX(s) where s(tt,ff) = CJUMP(LT, TEMP(x), CONST(5), tt,ff)

29 29 Relative Operator: RelCx() package translate; import temp.Label; public class RelCx extends Cx { int op; tree.Exp left, right; RelCx(int o, Tree.Exp l, Tree.Exp r) { op = o;left = l; right = r; } Tree.Stm unCx(Label t, Label f) { return new tree.CJUMP(op, left, right, t, f); }

30 30 For relational operator, we have seen RelCx class, which has relop, left Exp and right Exp. & and | are translated into If-Then-Else AST. –(A & B)  A? B: false –(A | B )  A? : true:B If e1 then e2 else e3, where –e1 is an Cx, e2 and e3 are Ex.

31 31 IfThenElse 1.Make two labels t and f to which conditional will branch. e1.unCx(t,f) 2.Allocate temp r, and after label t, move e2 to r. Jump to label join. SEQ(Label(t),Move(Temp(r), e2.unEx()), JUMP(join)) 3.After label f, move e3 to r. Jump to label join. SEQ(Label(f), Move(Temp(r), e3.unEx(),JUMP(join)) 4.If e2 and e3 are statements, replace unEx() by unNx().

32 32 If Then Else Exp class IfThenElseExp extends Exp { Exp cond, a, b; Label t = new Label(); Label f = new Label(); Label join = new Label(); IfThenElseExp(Exp cc, Exp aa, Exp bb) { cond=cc; a=aa; b=bb;} Tree.Stm unCx(Label tt, Label ff) { return new Tree.SEQ(cond.unCx(t,f), new Tree.SEQ(new Tree.LABEL(t), new Tree.SEQ(a.unCx(tt,ff), new Tree.SEQ(new Tree.LABEL(f), b.unCx(tt,ff))))); }

33 33 Exp unEx() { Temp r = new Temp(); return new ESEQ( new SEQ(cond.unCx(t,f), new SEQ(new Tree.LABEL(t), new SEQ(new MOVE(new TEMP(r), a.unEx()), new SEQ(new JUMP(join), new SEQ(new LABEL(f), new SEQ(new MOVE(new TEMP(r), b.unEx()), new LABEL(join))))))), new TEMP(r)); }

34 34 Stm unNx() { return new SEQ(cond.unCx(t,f), new SEQ(new LABEL(t), new SEQ(a.unNx(), new SEQ(new JUMP(join), new SEQ(new LABEL(f), new SEQ(b.unNx(), new LABEL(join))))))); }

35 35 String For String literal, make a new Label lab, and return the tree tree.NAME(lab). String needs special handling depending on machine architecture.

36 36 Record and Array construction a { f1 =e1,f2=e2,…,fn=en } –create and initialize n-element record. –records may outlive the procedure activation – => allocate space at heap area. – => no freeing action, delegating to GC. create n-word memory by calling external function and get a pointer TEMP(r) to the heap area. Then move n values e1,…en to location 0, 1w, 2w, …,(n-1)w relative to r. ESEQ ( TEMP(r)  CALL(NAME(malloc), CONST(n*w)) M(TEMP(r) + 0W)  e1; … M(TEMP(r) + (n-1)W)  en; TEMP(r) )

37 37 Array Allocation : new int [exp] 1.Determine how much space is needed for the array: -- = ((length of array +1) x (size of integer)) -- keep the length of array with array itself. 2.Call an external function to allocate on the heap. 3.Generate code for saving the length of the array at offset 0. 4.Generate the code for initializing each of the values in the array to zero starting at the 1 st element.

38 38 while loop while (condition) do exp test: if not condition go done exp go test done: if break appear within the body(exp), the translation is JUMP(done).

39 39 While Loop public Exp whileExp(Exp cond, Exp body, BreakScope done) { Label test = new Label(); Label top = new Label(); return new Nx(new Tree.SEQ(new Tree.JUMP(test), new Tree.SEQ(new Tree.LABEL(top), new Tree.SEQ(body.unNx(), new Tree.SEQ(new Tree.LABEL(test), new Tree.SEQ(cond.unCx(top,done.label), new Tree.LABEL(done.label))))))); }

40 40 Function Call Function call f(a 1, …, a n ) CALL(NAME l f, [e 1,e 2,…,e n ]) where l f : label for f –In general, add static link as an extra argument –In an OOP language, we need this (current object pointer) as an argument. –For a static method p.m(a 1, …, a n ): CALL(NAME l c$m, [p,e 1,e 2,…,e n ]) –For dynamic methods, we need dipatch tables….

41 41 Static Links When a variable x is declared at an outer level of static scope, the static link must be used. MEM(+(CONST k n, MEM(+(CONST k n-1, …. MEM(+(CONST k 1, TEMP FP))…)))) where k 1, ….k n-1 are the static link offsets k n is the offset of var x in local frame exp() method in Frame.Access need to calculate the chain of static links to dereference.

42 42 Function call with Static Links function call f(a1,a2,…,an) –add static link as an extra parameter –CALL(NAME(lab f, [sl, a1,a2,…,an]).

43 43 Declarations For each variable declaration within function body (including parameters) –Allocate additional space in the current frame (of the current level) For each function declaration –Keep a new “fragment” of Tree code for function’s body

44 44 Variable Definition Translator should return an augmented type environment: update symbol table Initializing variables: translated into a Tree exp that must be put just before the body of function: return a Translate.Exp containing assignment expressions. Translator will return “no-op” (eg. Ex(CONST(0)) if applied to function and type declarations.

45 45 Fragment package Translate; public class Frag { public Frag next; }

46 46 ProgFrag and DataFrag public class ProcFrag extends Frag { public Tree.Stm body; public Frame.Frame frame; ProcFrag(Tree.Stm b, Frame.Frame fr) { body=b; frame=fr; } public class DataFrag extends Frag { public String data; DataFrag(String d) { data=d; } public String toString(){return data;} }

47 47 Class Translate public class Translate extends ??visitor { ………… private Frags frags; //linked list of accumulated fragments public void procEntryExit(Exp body) { Frame.Frame myframe = level.frame; Tree.Exp bodyExp = body.unEx(); Tree.Stm bodyStm; if (bodyExp != null) bodyStm = MOVE(TEMP(myframe.RV()), bodyExp); else bodyStm = body.unNx(); ProcFrag frag = new ProcFrag(bodyStm, myframe); frags.add(frag); } public Frag getResults() { return frags.get();}

48 48 class Frags { private Frag first; void put(Frag f) { f.next=first; first=f; } Frag get() { Frag accum=null, f; while (first!=null) {f=first; first=f.next; f.next=accum; accum=f;} return accum; }

49 49 Classes and Objects We can create multiple objects for a class. Each object will have its own instance variables. Two objects can have different instances of local variables. Methods of an object can access the variables of that object. We need “this” pointer in the method to access the local variables : similar to accessing record fields -> need to lookup symbol table of the class.

50 50 Creating new Objects 1.Generate code for allocating heap space for all the instance variables; we need the number of variables declared in the class. (Object size?) 2.Iterate through the memory locations for those variables and initialize them: (In our case, all variables should be initialized to “0”. – Don’t forget!) 3.How about the nested object? - “extends”

51 51 Example: Program 7.5 class Vehicle { int position; int gas; int move (int x) { position = position + x; return position; } int fill (int y) { gas = gas +y; return gas; } …… Vehicle v; v.move(); variable in the object variable in the stack need initialization code stack variable this: value of v


Download ppt "Translation to Intermediate Code Chapter 7 Cheng-Chia Chen."

Similar presentations


Ads by Google