Presentation is loading. Please wait.

Presentation is loading. Please wait.

 www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Optimization & Code Generation.

Similar presentations


Presentation on theme: " www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Optimization & Code Generation."— Presentation transcript:

1  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Optimization & Code Generation

2 Objectives  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers To learn about 1. Issues In The Design Of Code Generators 2. Basic Blocks And Flow Graphs 3. Next-use Information 4. A Simple Code Generator 5. Register Allocation & Assignment 6. The Dag Representation Of Basic Blocks

3 Code Generator  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers The final phase of the compiler Code Optimization is the optional preceding phase Code generator should Effectively use the features of target machine and Itself should run efficiently Front End Source Code IR Code Generator Target Code Symbol Table Code Optimizer IR Code

4 Optimization versus Generation  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Code generation: usually transforms from one representation to another However, in as much as a code generator selects among possibilities, it is also doing a restricted form of optimization. Optimization: transforms a computation to an equivalent but ‘‘better’’ computation in the same representation language or annotates the representation with additional information about the computation.

5 Optimization through Transformation  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Optimization process must have following properties It must preserve the meaning of programs Must improve the performance by measurable amount It must be worth the effort spent by compiler 1. Best program transformation must yield the most benefit for the least effort 2. A fast and non-optimizing compiler may be more useful during the debugging phase and optimized one at the actual runtime. Available options include: Improving loops Improving Procedure calls Instruction selection Efficient use of registers Address calculations Control Flow Analysis Data Flow Analysis

6 Organization of Optimizing Compiler  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1. Intermediate code can be relatively independent of the target machine, 2. So the optimizer can perform freely and does not have to change even if code generator is changed Code Optimizer Control Flow Analysis Data Flow Analysis Transformations

7 Basic Blocks  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers A sequence of consecutive intermediate language statements in which flow of control can only enter at the beginning and leave at the end. A maximal length segment of straight-line code (i.e., no branches) Basic Block terminology 1. The first statement in the block is a LABEL / LEADER. 2. The last statement in the block is a JUMP or a CJUMP. 3. There are no other LABELs, JUMPs, or CJUMPs in the block. Question : Why do we need to look at Blocks ?

8 Basic Block  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Significance If any statement executes, they all execute Barring exceptions or other unusual circumstances Execution totally ordered Many techniques for improving basic blocks – simplest and strongest methods How to partition the IR code into Basic blocks ? 1. Identify LEADER statements 2. The basic block corresponding to a leader consists of the leader, plus all statements up to but not including the next leader or up to the end of the program

9 How to Identify the leader ?  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Using the following rules 1. The first statement in the program is a leader 2. Any statement that is the target of a branch statement is a leader (for most intermediate languages these are statements with an associated label) 3. Any statement that immediately follows a branch or return statement is a leader

10 Example: Finding Leaders  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers The following Code computes the product of a matrix begin prod := 0; i := 1; do begin prod := prod + a[i] * b[i]; i = i+ 1; end while i <= 20 end Source Code (1) prod := 0 (2) i := 1 (3) t1 := 4 * i (4) t2 := a[t1] (5) t3 := 4 * i (6) t4 := b[t3] (7) t5 := t2 * t4 (8) t6 := prod + t5 (9) prod := t6 (10) t7 := i + 1 (11) i := t7 (12)if i <= 20 goto (3) (13)………. Three Addr Code 1.The first statement in the program is a leader 2.Any statement that is the target of a branch statement is a leader 3.Any statement that immediately follows a branch or return statement is a leader RULES

11 Example : Forming Basic Blocks  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers The basic block corresponding to a leader consists of the leader, plus all statements up to but not including the next leader or up to the end of the program. (1) prod := 0 (2) i := 1 B1 (3) t1 := 4 * i (4) t2 := a[t1] (5) t3 := 4 * i (6) t4 := b[t3] (7) t5 := t2 * t4 (8) t6 := prod + t5 (9) prod := t6 (10) t7 := i + 1 (11) i := t7 (12) if i <= 20 goto (3) B2 (13) … B3

12 Flow Analysis  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Blocks are used as basic units in Flow Analysis Control Flow Analysis: determine the control structure of a program and build a Control Flow Graph. Data Flow Analysis: determine the flow of scalar values and build Data Flow Graphs. Basic block Program Procedure Inter-procedural Intra-procedural Local Flow analysis Data flow analysis Control flow analysis

13 Building CFG  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers There is a directed edge from basic block B x to basic block B y in the CFG if: (1) There is a branch from the last statement of B x to the first statement of B y, or (2) Control flow can fall through from B x to B y because: (i) B y immediately follows B x, and (ii) B x does not end with an unconditional branch ( 1) prod := 0 (2) i := 1 B1 (3) t1 := 4 * i (4) t2 := a[t1] (5) t3 := 4 * i (6) t4 := b[t3] (7) t5 := t2 * t4 (8) t6 := prod + t5 (9) prod := t6 (10) t7 := i + 1 (11) i := t7 (12) if i <= 20 goto (3) B2 ( 13) … B3 Rule (2 i ) Rule (2 ii ) B1 B2 B3 Rule (1)

14 Control Flow Graph  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers A control flow graph (CFG), or simply a flow graph, is a directed multi-graph in which: (i) the nodes are basic blocks; and (ii) the edges represent flow of control (branches/ fall-through ) The basic block whose leader is the first intermediate language statement is called the start node No information about the data; Therefore an edge in the CFG means that the program may take that path How to build CFG ?

15 Use of CFG’s  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Used to identify loops in code with several blocks, with two concepts Strongly Connected nodes a collection of N nodes where there is a path ( of length one or more ) from any node in N to any ther node in N Dominance A node a in a CFG dominates a node b if every path from the start node to node b goes through a. We say that node a is a dominator of node b Motivation: Programs spend most of the execution time in loops, therefore there is a larger payoff for optimizations that exploit loop structure

16 Basic Block Transformations  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Basic Block Computes a set of expressions Number of transformations can be applied to a basic block without changing the expressions computed by the block Such transformations are useful in Code optimization since they can help in Improving the running time and Saving the memory occupied by the block ( program) Two types of transformations are possible 1. Structure preserving & 2. Algebraic Transformations

17 Quick Sort  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers v oid quicksort (m,n) int m,n; { int i, j; int v, z; if ( n <= m ) return; /* fragment begins here */ i := m-1; j := n; v := a [n] ; while (1) { do i := I + 1; while ( a[ i ] < v ); do j := j - 1; while ( a[ j ] > v ); if ( I >= j) break; x := a[ i ]; a[ i ] = a[ j ]; a[ j ] := x; } x := a[ i ]; a[ i ] := a[n]; a[n] := x; quicksort (m,j); quicksort ( i +1,n); }

18 Corr. Three address code  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1. i := n-1 2. j := n 3. t1 := 4*n 4. v := a[t1] 5. i := i + 1 6. t2 := 4* i 7. t3 := a[ t2] 8. if t1 < v goto(5) 9. j := j-1 10. t4 := 4 *j 11. t5 := a [t4] 12. if t5 > v goto (9) 13. if i >= j goto (23) 14. t6 := 4 * i 15. x := a [t6[ 16.t7 := 4 * i 17. t8 := 4* j 18.T9 := a [ t8 ] 19. a[t7] := t9 20. t10 := 4 * j 21. a[t10] :=x 22. goto (5) 23. t11 := 4 * i 24. x := a[t11] 25. t12 := 4 * i 26. t13 := 4 * n 27. t14 := a[t13] 28. a[t11] := t14 29. t15 := 4 * n 30. a[t13] := x

19 Three address code  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 14. t6 := 4 * i 15. x := a [t6] 16. t7 := 4 * i 17. t8 := 4* j 18. t9 := a [ t8 ] 19. a[t7] := t9 20. t10 := 4 * j 21. a[t10] :=x 22. goto (5) 23. t11 := 4 * i 24. x := a[t11] 25. t12 := 4 * i 26. t13 := 4 * n 27. t14 := a[t13] 28. a[t11] := t14 29. t15 := 4 * n 30. a[t13] := x 1.i := n-1 2. j := n 3. t1 := 4*n 4. v := a[t1] 5.i := i + 1 6. t2 := 4* i 7. t3 := a[ t2] 8. if t1 < v goto(5) 9.j := j-1 10. t4 := 4 *j 11. t5 := a [t4] 12. if t5 > v goto (9) 13.if i >= j goto (23) B1 B2 B3 B4 B5 B6

20 FLOW GRAPH  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers if i >= j goto B6 t11 := 4 * i x := a[t11] t12 := 4 * i t13 := 4 * n t14 := a[t13] a[t12] := t14 t15 := 4 * n a[t15] := x i := n-1 j := n t1 := 4*n v := a[t1] i := i + 1 t2 := 4* i t3 := a[ t2] if t1 < v gotoB2 j := j-1 t4 := 4 *j t5 := a [t4] if t5 > v goto B3 t6 := 4 * i x := a [t6] t7 := 4 * i t8 := 4* j T9 := a [ t8 ] a[t7] := t9 t10 := 4 * j a[t10] :=x goto B2 B1 B2 B3B3 B4 B5 B6 Loops Try Transformations on this as an exercise

21 Principal Sources of Code Optimization  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1. Function Preserving Transformations 2. Common Sub-expressions 3. Copy Propagation 4. Dead Code Elimination 5. Loop Optimization i. Code Motion ii. Induction Variables & iii. reduction in Strength

22 1. Structure Preserving Transformations  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1.1 Common Sub-expression Elimination Consider the code block The 2 nd & 4 th statement compute the same expression b + c - d Hence it can be replaced by a := b + c b := a – d c := b + c d := a – d a := b + c b := a – d c := b + c d := b

23 Elimination of Common Sub- ex  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers if i >= j goto B6 t11 := 4 * i x := a[t11] t12 := 4 * i t13 := 4 * n t14 := a[t13] a[t11] := t14 t15 := 4 * n a[t13] := x i := n-1 j := n t1 := 4*n v := a[t1] i := i + 1 t2 := 4* i t3 := a[ t2] if t1 < v gotoB2 j := j-1 t4 := 4 *j t5 := a [t4] if t5 > v goto B3 t6 := 4 * i x := a [t6] t7 := 4 * i t8 := 4* j T9 := a [ t8 ] a[t7] := t9 t10 := 4 * j a[t10] :=x goto B2 B1 B2 B3B3 B4 B5 B6 x := t3 a[t7] := t5 a[t4] := x x := t3 2] ] ] t2 := 4* i t3 := a[ t2] t2 := 4* i t4 := 4 *j t5 := a [t4] t1 := 4 *n

24 1. Structure Preserving Transformations  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1.2 Dead Code Elimination Eliminating code that computes a value which is never used later ! Can be identified through: 1. Liveness analysis & 2. Def-Use Chains If ( debug ) print is usually preceded by an assignment debug := false. If copy propagation replaces debug by false, then the print statement is dead since it can’t be reached. We can eliminate both test and print statements More generally, deducing at compile time that the value of an expression is a constant and using the constant instead is known as constant folding.

25 Copy Propagation  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers f := g is copy statement or simply a copy. In fact, elimination of common sub-expressions introduces some of these copy statements. It would be incorrect to replace c:= d+e with c := a or c := b as one does not know the flow of control at the run time. The idea is to use g for f wherever possible after the copy statement f := g in B5 of the example, x := t3 a[t2] := t5 a[t4] := x goto B2 which can be replaced by x := t3 a[t2] := t5 a[t4] := t3 goto B2 This may not appear to be an improvement, but it gives an opportunity to eliminate the assignment to x

26 1. Structure Preserving Transformations  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1.3 Constant propagation ( Constant folding) Constant expressions are calculated and used Consider the following Code: const NN = 4; …. i:=2+NN; j:=i*5+a; 1.4 Loop Optimization Aims to minimise the time spent in the loop, often by reducing the number of operations in the loop Can be done in several ways i := 6 j := 30 + a

27 1. Structure Preserving Transformations  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1.4.1 Code Motion Moving the invariant code out of the loop: The following Code: Taking an expression and placing it outside the loop that yields the result independent of the number of times a loop is executed. while ( j < limit-2 ) do … can be written as t := limit-2; while j < t do… – Can be rewritten as t := b/c; for i := 1 to 10 do begin z := i + t;. end: for i := 1 to 10 do begin z := i + b/c. end;

28 1. Structure Preserving Transformations  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1.4.2 Loop Unrolling Reducing number of iterations –The following Code: i:=1; while (i<=50) do begin a[i]:= b[i]; i:= i + 1 end; Can be rewritten as i:=1; while (i<=50) do begin a[i]:= b[i]; i:= i + 1; end;

29 Strength Reduction  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers if i >= j goto B6 i := n-1 j := n t1 := 4*n v := a[t1]; ; i := i + 1 t2 := 4* i t3 := a[ t2] if t1 < v gotoB2 j := j-1 t4 := 4 *j t5 := a [t4] if t5 > v goto B3 B1 B2 B3B3 B4 B5 B6 j := j-1 t4 := 4 *j j := j-1 t4 := 4 *j The variables j and t4 in B3 are in the lock- step, in each iteration, j is decremented by 1 and t4 by 4. t4 := t4 - 4 t4 := 4 *j

30 1. Structure Preserving Transformations  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1.4.3 Induction variable Elimination Certain variables, in a loop derive their values from the looping variable ( i or j ) and hence their values form an arithmetic progression as we go around the loop. All such induction variables must be related by a linear function at each point in the loop. The calculation of each induction variable, frequently involving multiplication, may be replaced by addition to its former value. Such improvements, replacing an expensive operation by a cheaper one, are called reduction in strength. 1.j := j-1 2. t4 := 4 *j 3. t5 := a [t4] 4. if t5 > v goto (1) Consider the Following Code; It can be replaced by 1. t4 := t4 - 4 2. t5 := a [t4] 3. if t5 > v goto (1)

31 FLOW GRAPH AFTER LOOP OPTIMIZATION  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers if t2 >= t4 goto B6 t14 := a[t1] a[t2] := t14 a[t1] := t3 i := n-1 j := n t1 := 4*n v := a[t1]; t4 := 4 *j ; t2 := 4*i t2 := t2 + 4 t3 := a[ t2] if t1 < v gotoB2 t4 := t4 - 4 t5 := a [t4] if t5 > v goto B3 a[t2] := t5 a[t4] := t3 goto B2 B1 B2 B3B3 B4 B5 B6

32 2. Algebraic Transformation  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Can be used to change the set of expressions by its algebraic equivalent For Example statements like  x := x = 0 or  x := X * 1 can be eliminated. Statement  x := y ** 2 can be changed to cheaper x := y * y  X := y * 2 can be changed to cheaper x := y + y ( Strength Reduction )

33 Data Flow Analysis  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers A collection of techniques for compile-time reasoning about the run-time flow of values Almost always involves building a graph Usually formulated as a set of simultaneous equations attached to nodes and edges Useful in code optimization tasks like dead-code elimination redundant computation elimination code motion etc… One such technique is Liveness Analysis

34 Liveness Analysis – Another use of FG  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Consider the following code : a := 0; L1: b := a +1; c := c + b; a := b * 2; if a < N go to L1; return c Corresponding CFG Would be: a := 0; b := a +1; c := c + b; a := b * 2; a < N return c 1 2 3 4 5 6 A variable is live if its current value will be used in future. So we analyze live-ness from future to present to past

35 Liveness Analysis  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers The variable b is used in statement 4 & is therefore live at 4. It is automatically live from 3 to 4 and since 3 does not assign a value to b it is also live from 2 to 3. But 2 assigns b; Further, b is not needed by anyone from 1 to 2 and is therefore dead from 1 to 2, but live from 2 to 3 a := 0; b := a +1; c := c + b; a := b * 2; a < N return c 1 2 3 4 5 6 and 3 to 4.

36 Liveness Analysis  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers The variable a is live from 1 to 2 and again is live from 4 to 5 to 2 but not live from 2 to 3 to 4. The variable c is live on entry. If it is a parameter then it is live throughout this segment. If it is a local variable, then the compiler would detect an un-initialized variable and give a warning signal ! a := 0; b := a +1; c := c + b; a := b * 2; a < N return c 1 2 3 4 5 6

37 Predecessor & Successor  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers A flow graph node has out-edges that lead to successor nodes, and in-edges that come from predecessor nodes. The set pred [n] is all the predecessors of node n and succ [n] is the set of successors a := 0; b := a +1; c := c + b; a := b * 2; a < N return c 1 2 3 4 5 6 –T–The out-edges of (5) are 6 and 2. therefore, the succ [5] is {2,6}. –S–Similarly the in-edges of 2 are1 and 5 therefore pred [ 2 ] are {1,5}

38 def & uses of Variables in FG  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers An assignment to a variable or a temporary defines it. An occurrence of a variable on RHS of an assignment or inany other expression uses the variable. def [ 3 ] is {c} & uses [ 3 ] = {b,c} a := 0; b := a +1; c := c + b; a := b * 2; a < N return c 1 2 3 4 5 6

39 Live-in, Live-out & Live -on  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers A variable is : 1. live-in at a node if it is live on any of the in-edges of that node 2. live-out at a node if it is live on any of the out-edges of that node 3. live on an edge if there is a directed path from the edge to a use of the variable that does not go through any def. a := 0; b := a +1; c := c + b; a := b * 2; a < N return c 1 2 3 4 5 6

40 Liveness – Observations & equations  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1. If a variable is in Use [n] then it is live at node n (i.e. if a statement uses a variable, then the variable is live on entry to that statement) 2. If a variable is live-in at a node n then it is live-out at all nodes in pred [n]. 3. If a variable is live-out at node n, and not def [n] then the variable is also live-in at n.( i.e. if someone needs the value a at the end of the statement n and n does not provide that value, then a’s value is needed on entry to n) In [n] = use [n] (out [n] – def [n]) Out [n] = s Є succ [n] in [s] a := 0; b := a +1; c := c + b; a := b * 2; a < N return c 1 2 3 4 5 6 ∩ ∩

41 Liveness Computation Algorithm  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers for each n in [n] ← ( ) out [n] ← ( ) ; repeat for each n in’ [n] ← in [n] out’ [n] ← out [n] in [n] ← use [n] (out [n] – def [n]) out [n] ← s Є succ [n] in [s] Until in’ [n] = in [n] and out’ [n ] = out [n] a := 0; b := a +1; c := c + b; a := b * 2; a < N return c 1 2 3 4 5 6 ∩ ∩

42 Liveness Computation Algorithm a := 0; b := a +1; c := c + b; a := b * 2; a < N return c 1 2 3 4 5 6 c ac bc ac c I bc ac c bc ac c O Second I ac bc ac c a bcba c acab ca cc O Third I Odefuse First 1 2 3 4 5 6

43 Live-in and live-out of Basic Blocks  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers a:= b + c d:= d – b e := a + f f := a - d b := d + f e := a –c b := d + c a c d e a c d f c d e f b, c, d, e, f are live c, d, e, f are live a, c, d, e, f are live B1B1 B2B2 B3B3 B4B4 Variables in the module are a, b, c, d, e, f b, c, d, e, f b, c, d, f b, c, f b, c, d, f

44 Live-in and live-out of Basic Blocks  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers a:= b + c d:= d – b e := a + f f := a - d b := d + f e := a –c b := d + c b c d f a c d e a c d f c d e f b, c, d, e, f are live c, d, e, f are live a, c, d, e, f are live B1B1 B2B2 B3B3 B4B4  Variables in the module are a, b, c, d, e, f

45 Usage of live-ness property  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Live-ness property is useful in usage counts which is useful for Register allocation Live-ness property helps to determine sharing of registers by variables which are not live at the same time. Give warning message for uninitialized variables. Helps in data flow analysis.

46  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers

47 Code Generator Issues  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1. Input to code generator –Intermediate Representations Several choices including graphical ones Assumption is prior stage has done type checking & job to be done is allocating the target machine variable types Further assumption is error checking is done thing 2. Target Code Could be absolute machine code or relocatable code or assembly language code 3. Memory management Mapping of variables to memory locations ( absolutely or relatively

48 Code Generator Issues (Contd.)  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 4. Instruction Selection Decided by the nature of the instruction set, supported data types, instruction speeds machine idioms etc.... of the target machine Each three address code line can be individually translated into target machine code ; but this could result in poor code 5. Register Allocation Instructions involving registers (RR) tend to go fast Effective use of variables in registers speeds up the program execution Limited number of registers in the system calls for efficient use of these register locations

49  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers

50 Code Generation – Phases  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Instruction Selection Mapping IR into assembly code Assumes a fixed storage mapping & code shape Combining operations, using address modes Instruction scheduling Reordering operations to hide latencies Assumes a fixed program (set of operations) Changes demand for registers Register allocation Deciding which values will reside in registers Changes the storage mapping, may add false sharing Concerns about placement of data & memory operations

51 Code Generation – Step by Step  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1. Study the target machine registers, data formats, addressing modes, instructions, instruction formats,... 2. Design the run-time data structures layout of stack frames, layout of the global data area, layout of heap objects, layout of the constant pool,... 3. Implement the code buffer instruction encoding, instruction patching,... 4. Implement register allocation Optimal use of register speeds up execution

52 Code Generation – Step by Step (Contd.)  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 5. Implement code generation routines (in the following order) 1. Load values and addresses into registers (or onto the stack) 2. Process designators (x.y, a[i],...) 3. Translate expressions 4. Manage labels and jumps 5. Translate statements 6. Translate methods and parameter passing

53 Code generation methods  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Several Alternatives exist: ( We look at Four of them ) 1. Macro-expansion of internal form Each quadruple is translated to one or more instructions very simple but poor quality code (slow & needs much memory) poor use of registers 2. "A simple code generation algorithm” using address and register descriptors Uses following: 1. reg(R): register descriptor, specifies the content of register R 2. adr(A): address descriptor, specifies where the value of A is (possibly in both register and memory)

54 "A simple code generation algorithm”  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Code for quadruple: x:= y op z is generated using the following algorithm: 1. Invoke a function getreg to determine the location L where the result of computation will be stored 2. Consult address descriptor for y to locate Y’ – one of the current location (s) of Y – preferably a register. If y is ot in a register generate instruction MOV y’, L to put Y in L 3. Generate instruction OP Z’ L where Z’ is the current location of Z (again preferably a register) and update the address descriptor of X to indicate that x is in Location L. If L is a register update its descriptor to indicate that it contains the value of x and remove X from all other register descriptors 4. If the current value of Y and Z have no next uses and are in registers, alter the register descriptor to indicate that y and z are no longer in register

55 Function getreg  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Used for getting a register for use ( returns the location of register L to hold the result); Involves: if a register holds y and no other value, then update the address descriptor of y to indicate Y is no longer in L and that register as L elseif an empty register is available return it as L elseif X is used in next block find an occupied register, save it into memory and return as L else select a memory location and return it as L …………………………..

56 Codegen Example  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Generate code for the following quadruples. Assumptions: Only two registers, R0 and R1 are available All variables are live at the end of the block but not the temps Show the contents of registers and finally the cost 1.t1 := m + n 2.t2 := a + b 3.t3 := k + t2 4.z := t1 - t3 MOV m, R0 m ← R0 ADD n, R0 t1 ← in R0 MOV a, R1 a ← R1 ADD b, R1 t2 in R1 MOV R0, t1 ; empty R0, it is needed for something else now! MOV k, R0 ; t3 will be in R0 after next add ADD R1, R0 ; free R1, as it is not used again in the block MOV t1, R1 ; t1 is in memory, load it into a register SUB R0, R1 ; calculated t1-t3, the result is in R1 MOV R1, z ; end of block=> save R1 in z’s memory address Total cost of the block = 10 instructions

57 3. Code generation using AST  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Involves 2 phases : 1. Calculate the need for registers for each sub-tree 2. Traverse the tree and generate code. (The register need guides the traversal.) Register needs using syntax directed translation with bottom-up parsing (postorder traversal). Code gen proceeds depending on 5 possible options we encounter in traversal. ( Details not covered)

58 4. Codegen with Pattern matching  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers The target machine is described using a set of code templates. Corresponding instructions are attached to each code template. The tree is matched with the code templates top down. If there is a ’’complicated’’ code template which corresponds to the whole tree, write the corresponding instructions. Otherwise match with the children of the node. 1. IF (A - B)=0 THEN …..A:=B {CMP A,B} Test 2. D:=(A-B)*C { MOV A,R0 ; SUB B,R0 } Value

59 Exercise  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Void main() { int fahr, celsius, lower = 0, upper = 300, step = 20; fahr=lower; while(fahr <=upper) { celsius =5 *(fahr –32) / 9; printf(“%d %d”,fahr,Celsius); fahr + = step; }

60 Three address code  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1 lower=0 2 upper =300 3 step = 20 4 fahr = lower 5 t1 = fahr – 32 6 t2 = 5 * t1 7 t3 = t2/9 8 fahr = farh + step 9 if (fahr < = upper) goto 5 10 exit(0)

61 Quadruple  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers oppArg1Arg2result 1=0lower 2=300upper 3=20step 4=Lowerfahr 5- 32t1 6*5 t2 7/ 9t3 8+fahrStepfahr

62 Example 2  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers  1. Write the three code for the following program begin Prod:=0; i:=1; j:=1; do begin prod:=prod+a[i][j]* b[i][j]; i++; j++; end while (i& j) <=10; end

63 Three address code  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers 1. prod=0 2. i=1 3. j=1 4. t1= 2*i 5. t2= 2*j 6. t3= a[t1][t2] * b[t1][t2] 7. prod= prod+t3 8. i=i+1 9. j=j+1 10. If(I&j < 10) goto 4

64 Quadruple  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers oppArg1Arg2result 1=0Prod 2=1I 3=1J 4= i* 2t1 5=j*2t2 6*t1t2t3 7+prodt3prod 8+I1i 9+j1j

65 Sample Code Templates  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers

66 Any Questions ????  www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Thank you


Download ppt " www.Bookspar.com | Website for Students | VTU - Notes - Question Papers Optimization & Code Generation."

Similar presentations


Ads by Google