Skip to content

Intermediate Code

:material-circle-edit-outline: 约 382 个字 :material-clock-time-two-outline: 预计阅读时间 1 分钟

Three-Address Code

用来表示算术表达式求值,形如 x = y op z,只有一个操作符

保存三地址码信息需要 3 个地址以及 1 个操作符,我们用 四元式 quadruple 的方式来存储三地址码

image-20250414195352560

Intermediate Representation Trees

表达式

image-20250414205537869

  • evaluate 即求值
  • ESEQ 是连接,先执行 statement 得到副作用(环境 B),再计算 e 得到结果作为表达式的返回

语句

image-20250414205550127

  • EXP(e) 会计算表达式然后将结果丢掉,用来将表达式转化为语句(只需要表达式的副作用,不管其返回值)
  • JUMP 指跳转到 e 的地址继续执行,注意这里 e 不一定是表达式
  • CJUMP 为条件跳转,t 和 f 是两个地址
  • SEQ 就是把两个语句连起来,功能类似 C 语言的分号
  • LABEL 将当前机器码的地址存入符号 n

Translate AST into IR Trees

Expressions

image-20250414221405963

NULLt 指 true 时跳转的位置,因为此时还不知道具体地址就记成 null,会通过 patchList 替换为正确的地址

Simple Variables

image-20250414222547764

  • k 是变量再栈帧中的偏移

Array Variables

In the Tiger language, all record and array values are really pointers to record and array structures.

compute the address of a [i]: (i −l) × s + a

  • a: the base address of the array elements
  • l: the lower bound of the index range
  • s: the size (in bytes) of each array element

image-20250415121857053

Arithmetic

Tiger 没有一元操作符,负数用 0-x 运算表示,Tiger 不支持浮点数

Conditionals

an expression such as x < 5 will be translated as a Cx with:

image-20250415123143098

Translation of Declarations

Variable Definition

Function Definition