← All writing

Engineering a Compiler

Reading notes on compiler structure, scanning, parsing and intermediate representations. Also covers symbol tables, namespaces, memory layout and syntax-driven translation.

Engineering a Compiler

Chapter 1 Overview of Compilation

A compiler is simply a computer program that translates other computer programs to prepare them for execution.

Fundamentally, a compiler must both understand the source program that it takes as input and map its functionality to the target machine. The distinct nature of these two tasks suggests a division of labor and leads to a design that decomposes compilation into two major pieces: a front end and a back end.

The front end must encode its knowledge of the source program in some structure, an intermediate representation (IR), for later use. The IR becomes the compiler’s definitive representation for the code it is compiling.

Chapter 2 Scanners

In a compiler, a scanner (also known as a lexical analyzer) is the first phase of the compilation process. Its main job is to read the source code and break it down into tokens, <lexeme, category>, which are the basic units of meaning in the programming language. E.g., <if, keyoword> , <x, identifier>

A DFA returns a binary answer: it either accepts or rejects the input.

So If we construct the DFA so that each final state maps to a single category, then the scanner can find the category with a simple table lookup (mapping relations).

Thus there is what table-driven scanner is:

  1. Define some token patterns using regular expressions, like: (int, int), (identifier, [a-zA-Z_][a-zA-Z0-9_]*)....
  2. For each token we convert its corresponding RE to NFA using Thompson’s construction.
  3. Combines all NFAs into a single NFA using ε-transitions and a new start state.
  4. Then use subset construction to convert it to DFA using subset construction and minimize it.
  5. Scanner repeatly reads a character from input stream, and input it to DFA to update current state.
  6. We should match the longest characters e.g. (>= but not just >). So we need to keep read characters and use a stack to remember accept states we have received.
  7. When meeting a error state (No transition), scanner will backtrack to the last accepting state (longest) and report a token. Or if there is no accept state at all, scanner report invalid input.

Direct-Coded Scanner Implements DFA using explicit logic (if-else, goto...). Like

Code
s0 : clear stack;
    push( bad );
    char ← NextChar();
    lexeme ← char;
    push( s0 );
    if (char = ‘r’)
    then goto s1;
    else goto sout;
s1 : char ← NextChar();
    lexeme ← lexeme + char;
    push( s1 );
    if (‘0’≤char ≤’9’)
    then goto s2;
    else goto sout;
s2 : char ← NextChar();
    lexeme ← lexeme + char;
    clear stack;
    push( s2 );
    if ‘0’ ≤char ≤ ‘9’
    	then goto s2;
    else goto sout;
sout : state ← se;
    while (state not in SA and state not equal bad ) do
    state ← pop();
    if state not equal bad then
    truncate lexeme;
    RollBack();
    end;
    if state ∈ SA
    then return Type[state];
    else return invalid;

No DFA tables needed — the DFA is hardcoded into control flow.

And and finite set of strings can be recognized be DFA, i.e., it is regular language. Since we can list them all and concatenate them by | (w_1 | w_2 | ...).

Chapter 3 Parsers

The parser’s task is to determine if the input program, represented by the stream of classified words produced by the scanner, is a valid sentence in the programming language

This chapter introduces context-free grammars to specify programming language syntax. (Refer to theory of computation)

Unlike scanners, where hand-coding is common, tool-generated parsers are more common than hand-coded parsers.

We abstract the programming language as a syntactic model. And the model is expressed by as a formal grammar GG. If some string of words ss is in the language defined by GG we say that GG derives ss.

For a stream of words ss and a grammar GG, the parser tries to build a constructive proof that ss can be derived in GG—a process called parsing.

Parsing algorithms fall into two general categories. LL(1) parsers (top-down parsers) and LR(1) parsers (bottom-up parsers ).

In fact, we cannot write an RE that will match all expressions with balanced parentheses. So we use CFG.

We have an input string and CFG. We want to find a derivation of such string. This is what parse does.

The process of constructing a derivation from a specific input sentence is called parsing.

The parser's job is to correctly find the derivation path (according to the CFG) for the input token stream — that is, to determine if and how the input string can be generated by the grammar.

The parser sees the program as it emerges incrementally from the scanner: a stream of words annotated with their syntactic categories. Thus, the parser would see a + b × c as <name,a> + <name,b> × <name,c> .

It is useful to visualize the parser as building a parse tree.

The parse tree and derivation are equivalent for an unambiguous grammar. root is known; it represents the grammar’s start symbol. The leaves of the parse tree are known; they match the stream of words returned by the scanner. The hard part of parsing lies in finding the connection between the leaves and the root. Two distinct and opposite approaches for constructing the tree suggest themselves:

  1. Top-Down Parsers begin with the root and grow the tree toward the leaves. At each step, a top-down parser selects a node for some nonterminal on the lower fringe of the partially built tree and extends it with a subtree that represents the right-hand side of a production that rewrites the nonterminal.

  2. Bottom-Up Parsers begin with the leaves and grow the tree toward the root. At each step, a bottom-up parser finds a substring of the partially built parse tree’s upper fringe that matches the right-hand side of some production; it then builds a node for the rule’s left-hand side and connects it into the tree.

3.3 TOP-DOWN PARSING

Code
root ← node for the start symbol, S
focus ← root
push null onto the stack
word ← NextWord( )
while (true) do
	if (focus is a nonterminal) then
        pick next rule to expand focus, say A → β1 β2 β3 ... βn
        build nodes for β1 β2 β3 ... βn as children of focus
        push βn , βn -1, βn -2,... β2 onto the stack
        focus ← β1
    else if (word matches focus) then
        word ← NextWord( )
	    focus ← pop from the stack
    else if (word = eof and focus = null)
        then accept the input and return root
    else backtrack

Note: we just search the correct rule, when fail, we will backtrack.

summary:

Top-down parsers are simple, compact, and efficient. They can be implemented in a number of ways, including hand-coded, recursive-descent parsers and generated LL(1) parsers. Because these parsers know, at each point in the parse, the set of words that can occur as the next symbol in a valid input string, they can produce accurate and useful error messages.

Most programming-language constructs can be expressed in a backtrack-free grammar. Thus, these techniques have widespread application. The restriction that alternate right-hand sides for a nonterminal have disjoint START sets does not seriously limit the utility of LL(1) grammars. The primary drawback of top-down, predictive parsers lies in their inability to handle left recursion.

3.4 BOTTOM-UP PARSING

To be learned.

Frontend Example

souce code:

c
x= a * 3 + b;

Generally speaking, many programming languages define their grammar (context-free grammer) in official documentation.

Thus we use it to parse. Suppose part of context-free grammer is like this:

Code
assign  → ident = expr;       
expr  → expr + term 
		| expr - term
		| term
term  → term * factor 
		| term \ factor
        | factor
factor  → (expr)
		| num
		| ident

After processing of front end, we will get the parse tree:

Code
assign
├── ident(x)
├── '='
├── expr
|    ├── expr
|    │   └── term
|    │       ├── term
|    │       │   └── factor ── ident(a)
|    │       ├── '*'
|    │       └── factor ── num(3)
|    ├── '+'
|    └── term ── factor ── indent(b)
└── ';'

Then we will simplify this parse tree to Abstract Syntax Tree(AST):

Code
       =
      / \
     x   +
        / \
      *    b
     / \
    a   3

Here's a clean tree that omits unnecessary grammar nodes (like term, factor).

Then we can use AST to generate linear IR like:

Code
load a → @r1
load 3 → @r2
mul @r1,@r2 → @r3
load @r4 → b
add @r3,@r4 → @r5
store r5 → x

Just using post-order DFS to walk through AST.

Chapter 4 Intermediate Representations

4.2 AN IR TAXONOMY

In general, these three attributes are independent; most combinations of organization, abstraction, and naming have been used in some compiler.

Structural Organization

Broadly speaking, IRs fall into three classes: Graphical IRs, Linear IRs, Hybrid IRs.

Level of Abstraction

high level, medium level, low level.

Mode of Use

The third axis relates to the way that the compiler uses an IR.

Definitive IR

A definitive IR is the primary representation for the code being compiled. The compiler does not refer back to the source code; instead, it analyzes, transforms, and translates one or more (successive) IR versions of the code. These IRs are definitive IRs.

Derivative IR

A derivative IR is one that the compiler builds for a specific, temporary purpose. The derivative IR may augment the definitive IR, as with a dependence graph for instruction scheduling (see Chapter 12). The compiler may translate the code into and out of the derivative IR to enable a specific optimization.

Naming

Using too few names can undermine optimization. Using too many can bloat some of the compile-time data structures and increase compile time without benefit.

4.3 GRAPHICAL IRS

Abstract Syntax Trees

The abstract syntax tree (AST) retains the structure and meaning of the parse tree but eliminates extraneous nodes.

ASTs have been used as the definitive IR in many practical compiler systems.

Directed Acyclic Graphs

A directed acyclic graph (DAG) is a contraction of the AST that avoids this duplication.

Control-Flow Graph

A Control Flow Graph (CFG) is a directed graph used to represent all paths that might be traversed through a program during execution.

The simplest unit of control flow is a basic block—a maximal length sequence of straight-line, or branch-free, code(i.e., there is no jump in such block).

A CFG is a directed graph, G=(N,E)G = (N, E). Each node n∈Nn \in N corresponds to a basic block. Each edge e=(ni,nj)∈Ee =(n_i, n_j) \in E corresponds to a possible transfer of control from block nin_i to block njn_j.

Dependence Graph

Compilers also use graphs to encode the flow of values from the point where a value is created, a definition, to any point where it is read, a use. A data dependence graph embodies this relationship.

The edges in the graph represent real constraints on the sequencing of operations—a value cannot be used until it has been defined. The dependence graph edges impose a partial order on execution (Topo order).

Call Graph

4.4 LINEAR IRS

4.4.1 Stack-Machine Code

Stack-machine code, a form of one-address code, assumes the presence of a stack of operands. It is easy to generate and to understand. Most operations read their operands from the stack and push their results onto the stack.

Stack-machine code for the expression a - 2 × b appears in the margin.

Code
push b
push 2
multiply
push a
subtract

4.4.2 Three-Address Code

In three-address code, most operations have the form i ← j op k, with an operator (op), two operands (j and k), and one result (i).

Code
t1 ← 2
t2 ← b
t3 ← t1 × t2
t4 ← a
t5 ← t4 - t3

4.4.3 Representing Linear Codes

Three-address codes are often implemented as a set of quadruples. Each quadruple is represented with four fields: an operator, two operands (or sources), and a destination.

4.4.4 Building the CFG (control-flow graph) from Linear Code

Compilers often must convert between different IRs, often different styles of IRs. One routine conversion is to build a CFG from a linear IR such as ILOC.

As a first step, the compiler must find the start and the end of each basic block in the linear IR. We will call the initial operation of a block a leader.

An operation is a leader if it is the first operation in the procedure, or if it has a label that is, potentially, the target of some branch (Since all linear IRs that represent control flow need branch labels or their equivalent) .

If the linear IR contains labels that are not used as branch targets, then treating labels as leaders may unnecessarily split blocks. The algorithm could track which labels are jump targets. However, ambiguous jumps may force it to treat all labeled statements as leaders. (We can optimize it when coding).

The second pass finds every block-ending operation. It assumes the ILOC model where every block, except the final block, ends with a branch or a jump and branches specify labels for both the taken and not-taken paths.

The operation immediately before next leader ends the current block.

4.5 SYMBOL TABLES

A symbol table is a data structure used by a compiler to store information about the symbols (names) in a program such as variables, arrays, records, structures, strings, and objects.

The compiler typically keeps a set of tables, often referred to as symbol tables. Conceptually, a symbol table has two principal components: a map from textual name to an index in a repository and a repository where that index leads to the name’s properties.

For literal constants, such as numbers, characters, and strings, the compiler will need to lay out a data area to hold these values, often called a constant pool.

4.6 NAME SPACES

4.6.1 Name Spaces in the IR

Implicit Versus Explicit Names

Tree-like IRs use implicit names for some values. By contrast, three-address code uses only explicit names.

Variables Versus Values

The temptation, of course, is to provide a unique name for each subexpression, so as to maximize the opportunities presented to the optimizer. However, not all subexpressions are of interest. A value that is only live in a single block does not need a name that persists through the entire procedure. Exposing such a value to procedure-wide analysis and optimization is unlikely to change the code.

4.6.2 Static Single-Assignment Form

Static single-assignment form (SSA) is an IR and a naming discipline that many modern compilers use to encode information about both the flow of control and the flow of values in the program.

A program is in SSA form when it meets two constraints:

(1) each definition has a distinct name;

(2) each use refers to a single definition.

I.e., each variable is assigned exactly once, and every variable is unique (versioned). Instead of reassigning a variable, we create a new version each time.

A ϕ\phi function is a special operator used in SSA form to merge values coming from different control-flow paths. It's not a real function call — it's a notation that says: "At this point, choose the right value based on the path taken to get here."

Why Is It Needed?

SSA requires each variable to be assigned only once.

But in real programs, we often write:

c
if (cond)
    x = 1;
else
    x = 2;
y = x + 3;

after the if, what is the value of x? It's either 1 or 2, depending on the condition.

SSA must rename each assignment, so it becomes:

x1
x1 = 1         ; in then branch
x2 = 2         ; in else branch
x3 = φ(x1, x2) ; merged value
y1 = x3 + 3

4.7 PLACEMENT OF VALUES IN MEMORY

4.7.1 Memory Models

Before the compiler can translate the source program into its IR form, the compiler must understand, for each value computed in the code, where that value will reside.

Three memory models are common:

Memory-to-Memory Model Values have their primary home in memory.Either the IR supports memory-to-memory operations, or the code moves active values into registers and inactive values back to memory.

Register-to-Register Model Whenever possible, values are kept in a virtual register; some local, scalar values have their only home in a virtual register. Global values have their homes in memory (see Section 4.7.2).

Stack Model Values have their primary home in memory. The compilermoves active values onto and off of the stack with explicit operations (e.g., push and pop). Stack-based IRs and ISAs often include operations to reorder the stack (e.g., swap).

4.7.3 Assigning Values to Data Areas

Chapter 5 Syntax-Driven Translation

5.3 SYNTAX-DRIVEN TRANSLATION

Its use in the initial translation of code from the source language to IR. For each rule of context-free grammer, it assign a snippet of code called action. When compiler reduce this rule (apply this rule), it will execute such action.

Syntax-driven translation lets the compiler writer specify the action and relies on the parser to decide when to apply that action.

This example shows a simple grammar that describes the set of positive integers.

Code
1 Number → DList
2 DList → DList digit
3 		| digit

For each rule we can add some snippet of code.

Code
Number : DList 		{ return $1; } ;
DList : DList digit { $$ = $1 * 10 + CToI($2); } ;
		| digit 	{ $$ = CToI($1); } ;

The symbols $$, $1, and $2 refer to values associated with grammar symbols in the production. $$ refers to the nonterminal symbol on the rule’s left-handside (LHS). The symbo $i refers to the value for the ith symbol on the rule’s right-hand side (RHS).

5.3.2 Translating Expressions

Example for building an Abstract Syntax Tree.

We can design each action such that it can construct a AST from grammer when execute action code.

Code
Expr → Expr + Term 		{ $$ ← MakeNode2( plus, $1, $3 ) ; };
	| Expr − Term 		{ $$ ← MakeNode2( minus, $1, $3 ) ; };
	| Term 				{ $$ ← $1 ; };
Term → Term × Factor 	{ $$ ← MakeNode2( times, $1, $3 ) ; };
	| Term ÷ Factor 	{ $$ ← MakeNode2( divide, $1, $3 ) ; };
	| Factor 			{ $$ ← $1 ; };
Factor → ( Expr ) 		{ $$ ← $2 ; };
	| number 			{ $$ ← MakeLeaf( number, lexeme ) ; };
	| indet 			{ $$ ← MakeLeaf( indet, lexeme ); };

Example for building an Abstract Syntax Tree.

Example for emitting Three-Address Code for Expressions.

For part of code (expression), we can elaborately design actions, so it can directly generate Three-Address Code (linear IR).

Code
Expr → Expr + Term 		{ $$ ← NextRegister() ;Emit( add, $1, $3, $$ ) ; };
	| Expr − Term 		{ $$ ← NextRegister() ; Emit( sub, $1, $3, $$ ) ; };
	| Term 				{ $$ ← $1 ; };
Term → Term × Factor 	{ $$ ← NextRegister() ; Emit( mult, $1, $3, $$ ) ; };
	| Term ÷ Factor 	{ $$ ← NextRegister() ;Emit( div, $1, $3, $$ ) ; };
	| Factor 			{ $$ ← $1 ; };
Factor → ( Expr ) 		{ $$ ← $2 ; };
		| number 		{ $$ ← NumberIntoReg( lexeme ) ; };
		| name 			{ entry ← STLookup( lexeme ); $$ ← ValueIntoReg( entry ) ; };

Chapter 7 Code Shape

To be learned.

← Back to ArchiveBack to top ↑

Comments

No approved comments yet.

Your display name and plain-text comment become public only after owner approval. No account or email is required.