Chapter 7: Symbol Table Management


6.12 EXAMPLES

Following are additional examples of syntax-directed definitions and translations.

EXAMPLE 6.3
start example

Generate the three-address code for the following C program:

 main() {  int i = 1;    int a[10];    while(i <= 10)    a[i] = ; } 
end example
 

The three-address code for the above C program is:

  1. i = 1

  2. if i <= 10 goto(4)

  3. goto(8)

  4. t 1 = i * width

  5. t 2 = addr( a ) ˆ’ width

  6. t 2[ t 1] = 0

  7. goto(2)

where width is the number of bytes required for each element.

EXAMPLE 6.4
start example

Generate the three-address code for the following program fragment:

 while (A < C and B > D) do   if A = 1 then C = C+1     else       while A <= D do                  A = A + 3 
end example
 

The three-address code is:

  1. if a < c goto(3)

  2. goto(16)

  3. if b > d goto(5)

  4. goto(16)

  5. if a = 1 goto(7)

  6. goto(10)

  7. t 1 = c +1

  8. c = t 1

  9. goto(1)

  10. if a <= d goto

  11. goto(1)

  12. t 2 = a +3

  13. a = t 2

  14. goto(10)

  15. goto(1)

EXAMPLE 6.5
start example

Generate the three-address code for the following program fragment, where a and b are arrays of size 20 — 20, and there are four bytes per word.

end example
 
 begin   add = 0;   i = 1;   j = 1;   do     begin       add = add + a[i,j] * b[j,i]       i = i + 1;       j = j + 1;     end   while i <= 20 and j <= 20; end 

The three-address code is:

  1. add = 0

  2. i = 1

  3. j = 1

  4. t 1 = i * 20

  5. t 1 = t 1 + j

  6. t 1 = t 1 * 4

  7. t 2 = addr( a ) ˆ’ 84

  8. t 3 = t 2[ t 1]

  9. t 4 = j * 20

  10. t 4 = t 4 + i

  11. t 4 = t 4 * 4

  12. t 5 = addr( b ) ˆ’ 84

  13. t 6 = t 5[ t 4]

  14. t 7 = t 3 * t 6

  15. t 7 = add + t 7

  16. t 8 = i + 1

  17. i = t 8

  18. t 9 = j + 1

  19. j = t 9

  20. if i <= 20 goto(22)

  21. goto NEXT

  22. if j <= 20 goto(4)

  23. goto NEXT

EXAMPLE 6.6
start example

Consider the program fragment:

 sum = 0 for(i = 1; i<= 20; i++)   sum = sum + a[i] + b[i]; 

and generate the three-address code for it. There are four bytes per word.

end example
 

The three address code is:

  1. sum = 0

  2. i = 1

  3. if i <= 20 goto(8)

  4. goto NEXT

  5. t 1 = i +1

  6. i = t 1

  7. goto(3)

  8. t 2 = i * 4

  9. t 3 = addr( a ) ˆ’ 4

  10. t 4 = t 3[ t 2]

  11. t 5 = i * 4

  12. t 6 = addr( b ) ˆ’ 4

  13. t 7 = t 6[ t 5]

  14. t 8 = sum + t 4

  15. t 8 = t 8 + t 7

  16. sum = t8

  17. goto(5)




Algorithms for Compiler Design
Algorithms for Compiler Design (Electrical and Computer Engineering Series)
ISBN: 1584501006
EAN: 2147483647
Year: 2005
Pages: 108
Authors: O G Kakde

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net