Compilers Principles, Techniques, & Tools (purple dragon book) second edition exercise answers

Exercises for Section 8.3

8.3.1

Generate code for the following three-address statements assuming stack allocation where register SP points to the top of the stack.

call p
call q
return
call r
return
return

Answer

100:  LD SP, #stackStart
108: ADD SP, SP, #psize
116:  ST *SP, #132
124:  BR pStart
132:  SUB SP, SP, #psize
140:  ADD SP, SP, #qsize
148:  ST *SP, #164
156:  BR qStart
164:  SUB SP, SP, #qsize
172:  BR **SP

8.3.2

Generate code for the following three-address statements assuming stack allocation where register SP points to the top of the stack.

  1. x = 1
  2. x=a
  3. x = a + 1
  4. x = a+b
  5. The two statements
    • x = b * c
    • y = a + x

8.3.3

Generate code for the following three-address statements again assuming stack allocation and assuming a and b are arrays whose elements are 4-byte values.

  1. The four-statement sequence

     x = a[i]
     y = b[j]
     a[i] = y
     b[j] = x
    
  2. The three-statement sequence

     x = a[i]
     y = b[i]
     z = x * y
    
  3. The three-statement sequence

     x = a[i]
     y = b[x]
     a[i] = y
    

Note

1. 指令长度

120:  ST 364, #140
132:  BR 200
140:  ACTION2

图 8-4 部分代码

  • 每行指令前面的标号代表了这行代码的起始位置(即偏移量),和下一行指令的标号差代表这行指令的长度。
  • 第一行有 1 个指令和 2 个常量,所以指令长度是 12,同理第二行有 1 个指令和 1 个常量,所以长度为 8.
100:  LD, SP, #600
108:  ACTION1
128:  ADD SP, SP, #msize
136:  ST *SP, #152

图 8-6 部分代码

  • 由于 SP 不占空间,所以上图中的几行指令长度均为 8。