当前位置:文档之家› 编译器的设计与实现.ppt

编译器的设计与实现.ppt


1 语言
声明语句 简化的C 赋值语句 控制语句 If语句 While语句 函数调用 表达式 数组 …
1.1简单的C 语言的文法
1. 2. 3. 4. 5. 6.
7. 8.
9.
10.
program→ { var-declaration | fun-declaration } var-declaration→ int ID { , ID } //可以声明多个变量 fun-declaration→ ( int | void ) ID( params ) compound-stmt params → int ID { , int ID } | void | empty compound-stmt→ { { var-declaration } { statement } } statement→ expression-stmt∣compound-stmt ∣if-stmt ∣while-stmt | return-stmt expression-stmt→ [ expression ] ; if-stmt→ if( expression ) statement [ else statement ] while-stmt→ while( expression ) statement return-stmt→ return [ expression ] ;
}
大纲

语言 目标机器 编译器的实现
3 编译程序的实现

编译器的各个阶段的回顾 涉及的主要数据结构 具体实现
简单回顾-编译的各个阶段
源程序 字符流
单词流 语法单位 抽象语法树or 其它中间形式 目标代码 扫描器(词法分析) 分析器(语法分析)

语义分析和中间代码生成

优化器

目标代码生成
1.3进一步的扩展
简单的C 对象 简化的C++ 继承 多态 异常处理 垃圾回收
……
2 目标机器建模

处理器 存储器 指令系统
2.1 CPU的设计


ห้องสมุดไป่ตู้
数据结构如下: public struct processor { public int ax; public int bx; public int cx; public int pc; public int bp; public int sp; public int hp; public int zf; ……//其它 } 详细内容将会在以后解释
虚拟机执行
示例源代码
1. 2. 3. 4. 5. 6. 7.
8.
9. 10. 11. 12. 13. 14.
int f1(int x,int y) { if(x<y) x = x+y; x = x*2; return x; } void main() { int a; int b; a = 5; b = a + 2; a = f1(a,b); return; }
1.2程序举例
1. 2. 3. 4. 5. 6. 7.
8.
9. 10. 11. 12. 13. 14.
int f1(int x,int y) { if(x<y) x = x+y; x = x*2; return x; } void main() { int a; int b; a = 5; b = a + 2; a = f1(a,b); return; }
2.4指令系统

目标程序形式有以下几种:

绝对机器代码 可再定位机器代码 汇编语言程序

我们采用汇编语言的形式表示目标代码 格式如下: opcode oprand1 oprand2
指令集举例

MOV ax, bx MOV [addr], ax JMP 21 CMP ax, bx
11. 12.
13. 14.
15.
16. 17.
18.
expression→ ID = expression | simple-expression simple-expression→ additive-expression [ relop additiveexpression ] relop → < | <= | > | >= | == | != additive-expression→ term [( + | - ) term ] term→ factor [ ( * | / ) factor ] factor→ ( expression )| ID | call | NUM call→ ID( args ) args→ expression { , expression } | empty
// 累加器AX // BX
// 程序计数器 // 基址指针bp // 堆栈指针sp
//标志flag;
2.2存储器组织

线性组织, Mem[0]~Mem[maxAddr]
maxaddr

3 2 1 低
0

功能分区:



代码区 元数据区 栈(运行时存储空间) 堆

假定每一个功能存储区的地址都是由0开 始
寄存器
;bx ax ;ax addr所表示的地址空间中 ;无条件跳转指令 ;比较ax与bx寄存器的值,设置标

JZ 21 ……
;根据标志寄存器的值有条件跳转
目标代码数据结构


根据目标代码的结构,不难设计它的数据结构 如下: class Code { private string op; //操作码 private string arg1; //操作数 private string arg2; //操作数
编译器的设计与实现
ppt制作: 张 云 时间:2008-03
课程描述

目标:编译器的设计与实现 方法:


给定语言特性,限定目标机器模型,实现该 语言的编译器; 添加新的语言特性,对编译器做相应的修改。
一个简单的编译器的设计与实现

语言的设计 目标机器建模 编译器的实现
一个用于教学的编译运行环境
2.3目标机器模型
元数据 存放符号表等运行信息 堆 存储动态分配空间 栈 代码区 存储函数运行栈 存储代码 CPU(寄存器组)
简单的栈式存储分配
数据结构
class VM { processor cpu; //虚拟机的cpu symtable;//符号表 DataTable code; //代码存储空间 int[] stack = new int[STACKSIZE]; //栈 int[] heap = new int[HEAPSIZE]; //堆 }
相关主题