Compiler Phases
Follow a statement through scanning, parsing, type checking, three-address code, optimization, and code generation.
- Lecture reference: Intro (cont’d): Compiler architecture
- Lecture reference: Intro (cont’d): Compiler structure with examples
- Lecture reference: Lexical Analysis
Source
Grammar
program -> stmt*
stmt -> ID = expr ;
| if cond then stmt [ else stmt ]
cond -> expr relop expr relop: == != < <= > >=
expr -> term ( ( + | - ) term )*
term -> factor ( ( * | / ) factor )*
factor -> ID | NUM | FNUM | ( expr ) ID is a letter followed by letters or digits; NUM is an int literal (1), FNUM a float
literal (2.3). An else belongs to the nearest if.
Declarations
7 Phases of a Compiler
Seven phases; each one turns the output of the phase before it into a new form.
| Group | Phase | Output | Sample | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Programmer (source code producer) | Source string | A= B1 +C; | |||||||||||||||||
| 1 | Scanner (performs lexical analysis) | Tokens and their attributes (lexemes) |
| ||||||||||||||||
| 2 | Parser (performs syntax analysis based on the grammar of the programming language) | Abstract syntax tree | |||||||||||||||||
| 3 | Semantic analyzer (type checking, etc.) | Annotated abstract syntax tree |
| ||||||||||||||||
| 4 | Intermediate code generator | Three-address code, P-code, or RTL |
| ||||||||||||||||
| 5 | Optimizer | Three-address code, P-code, or RTL |
| ||||||||||||||||
| 6 | Code generator | Assembly code |
| ||||||||||||||||
| 7 | Peephole optimizer | Assembly code |
|
* The slide assumes r2 already holds B1 as a float; CVTLF performs that conversion.
The C- Compiler runs these phases on a whole program.
Preprocessors, Compilers, Assemblers, and Linkers
- Source Program w/preprocessor directives
- Preprocessor
- produces Source Program
- Compiler
- produces Target Assembly Program
- Assembler
- produces Relocatable Object Code
- Linker, which also takes Libraries and Relocatable Object Files
- Absolute Machine Code
Try, e.g.,
gcc -v Prog.c With -v, gcc prints the command it runs for each step.
Code generation produces assembly code (usually), which is then assembled into an object module. What next to obtain an executable object?
Show answer
Linking: the linker combines the relocatable object code with libraries and other relocatable object files into absolute machine code.