实验:中间代码生成 (TAC Generation)
本实验演示如何将 C 语言源代码翻译为四元式 (Quadruples) 形式的中间代码。
核心考点:
- 数组引用翻译:演示如何将
a[i]展开为基址加偏移量的计算序列(width * i)。 - 控制流翻译:演示
while循环如何被翻译为if跳转和label。 - 临时变量:观察编译器自动生成的
t1,t2等临时变量。
1. C 源代码 (Source)
已支持:变量/数组声明、赋值、算术表达式、if/while 控制流。
2. 四元式序列 (Quadruples)
| ID | Op | Arg1 | Arg2 | Result | TAC | Desc |
|---|---|---|---|---|---|---|
| (100) | label | main | main: | Function Entry | ||
| (101) | = | 0 | i | i = 0 | Init var | |
| (102) | label | L1 | L1: | While Start | ||
| (103) | if< | i | 10 | L2 | if i < 10 goto L2 | Check loop cond |
| (104) | goto | L3 | goto L3 | Exit loop | ||
| (105) | label | L2 | L2: | Loop Body | ||
| (106) | * | i | 4 | t1 | t1 = i * 4 | Calc offset (int=4) |
| (107) | + | a | t1 | t2 | t2 = a + t1 | Calc addr &a[i] |
| (108) | * | i | 2 | t3 | t3 = i * 2 | Calc term |
| (109) | []= | t3 | t2 | *t2 = t3 | *t2 = t3 | |
| (110) | + | i | 1 | t4 | t4 = i + 1 | Calc expr |
| (111) | = | t4 | i | i = t4 | Assign | |
| (112) | goto | L1 | goto L1 | Loop back | ||
| (113) | label | L3 | L3: | Loop End |