Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Phases of a compiler

Clear, exam-focused notes on the standard phases of a compiler: what each phase does, precise definitions, inputs/outputs, algorithms used, worked traces (lexing → parsing → AST → three-address code), common mistakes, and exam tips.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

A compiler converts human-readable source code into machine code that runs on hardware. Engineers design, debug and optimise compilers when building language tools, improving program performance, or implementing new languages and hardware targets — so you must know what every phase does, what errors each phase finds, and what input and output each phase produces.

Key ideas

Start simple: a program written by a programmer is a sequence of characters. A compiler works in stages to turn that sequence into machine instructions.

  • Definition: Compiler — a program that translates source code written in one programming language (the source language) into another language (the target language), typically machine code or an intermediate code. It must preserve the meaning (semantics) of the source program.

  • Definition: Phase — a logical unit of work inside a compiler that takes a specific kind of input and produces a specific kind of output. Phases are ordered; outputs of earlier phases are inputs to later phases.

Standard phases (each defined and with exact I/O):

  1. Lexical analysis (Scanner) — input: sequence of characters; output: sequence of tokens (token = pair (token-type, attribute)). The scanner groups characters into lexemes and returns token types like IDENTIFIER, NUMBER, KEYWORD, OPERATOR. It also removes whitespace and comments. If the scanner uses buffering, it may use limited lookahead to implement maximal munch; DFA-based scanners typically avoid backtracking.

  2. Syntax analysis (Parser) — input: tokens; output: parse tree or concrete syntax tree and possibly an abstract syntax tree (AST) depending on design. The parser checks that tokens follow the grammar (a context-free grammar) of the language. If grammar is ambiguous, parser design must choose a disambiguation (e.g., precedence rules) or use an unambiguous grammar.

    • Exact statement: Given a context-free grammar G and a sequence of tokens w, the parser must decide whether w ∈ L(G) and produce a parse tree corresponding to a leftmost (or rightmost) derivation. Assumption: grammar G describes the syntactic structure of the source language.
  3. Semantic analysis — input: parse tree/AST; output: annotated AST and symbol table entries with types, scopes, and other semantic information. This phase performs type checking, scope resolution, and other language-specific checks (e.g., definite assignment). Errors here are semantic errors (type mismatch, undeclared identifier).

    • Definition: Type checking — verifying that operations in the program are applied to operands of compatible types according to language rules. Exact statement: For every expression E with operator op and operands of types T1, T2, ... the semantic rules must prove op is defined for (T1, T2, ...) or raise an error.
  4. Intermediate code generation (IR generation) — input: annotated AST; output: an intermediate representation (IR) such as three-address code, syntax trees, or postfix. The IR is machine-independent and easier to analyse and transform.

    • Definition: Three-address code (TAC) — each instruction has at most three addresses (operands), typically of the form x = y op z or x = op y, where x, y, z are names, temporaries, or constants.
  5. Code optimisation (opt) — input: IR; output: optimized IR. Optimisations are either machine-independent (performed on IR) or machine-dependent (during or after code generation). They aim to reduce runtime, memory, or code size while preserving semantics.

    • Exact statement: An optimisation is semantics-preserving transformation T on IR such that for all programs P, T(P) has the same observable behaviour as P and meets some resource objective (e.g., reduce number of instructions).
  6. Code generation — input: (optimized) IR; output: target code (assembly/machine code). It maps IR operations to target machine instructions, assigns registers, and manages data layout and calling conventions.

  7. Assembly and linking (sometimes outside the core compiler) — Assembler input: generated assembly; output: object code. Linker input: object code and libraries; output: executable image. The loader places the executable into memory for running.

Other exact definitions:

  • Front end — the part of the compiler that handles language-specific analysis (lexical, syntax, semantic analysis, and IR generation). It is language dependent but machine independent.
  • Back end — the part that handles machine-specific tasks (optimisation for target, code generation). It is machine dependent but language independent.
  • Pass — a complete traversal of the program representation (e.g., parse tree or IR) during which certain analyses or transformations are performed.

What each phase reports and typical algorithms used (summary):

  • Lexical analysis: finite automata, regular expressions, maximal-munch rule, input buffering; typical errors: illegal characters, unterminated strings/comments, malformed numeric literals.
  • Syntax analysis: LL(1), LR(0), SLR, LALR(1), Canonical LR(1) (CLR(1)) parsers; recursive descent for predictive parsing; typical errors: unexpected or missing tokens (syntax errors), mismatched parentheses/brackets.
  • Semantic analysis: symbol table (hash table), type inference rules, attribute grammars (S-attributed, L-attributed); typical errors: type mismatch, undeclared or multiply declared identifiers, incompatible assignments, wrong number/types of arguments, use-before-definition where applicable.
  • IR: syntax-directed translation to produce TAC, DAGs for basic blocks; reports: internal representation for later phases (normally no new user-visible errors).
  • Optimisation: data-flow analysis, basic-block and global optimisations, loop optimisations.
  • Code generation: tree-walking, register allocation (graph colouring), instruction selection and scheduling; notes: may trigger register spilling due to limited registers, with target-specific diagnostics issued by the assembler/linker.

Diagram to draw for exams: draw a left-to-right pipeline with boxes labelled: Source code → [Lexical analysis] → Tokens → [Syntax analysis] → Parse tree / AST → [Semantic analysis] → Annotated AST & Symbol Table → [IR generation] → IR → [Optimisation] → Optimized IR → [Code generation] → Target code → [Assembler & Linker] → Executable. Label arrows with input/output names and add a top label: Front end covers up to IR generation; Back end covers optimisation and code generation. Optionally show a 'middle end' performing machine-independent optimisations.

Formulas

Source_code --(Lexical_analysis)--> Tokens — Source_code: sequence of characters; Tokens: sequence of (token-type, attribute) pairs; applies for any textual language. Tokens --(Syntax_analysis)--> Parse_Tree / AST — Tokens: from scanner; Parse_Tree: concrete derivation tree. AST --(Semantic_analysis)--> Annotated_AST + Symbol_Table — Annotated_AST: nodes with types and attributes; Symbol_Table: mapping (name → attributes). Annotated_AST --(IR_generation)--> IR (e.g., Three_Address_Code) — IR: machine-independent instructions. IR --(Optimisation)--> Optimized_IR — Optimisation preserves semantics. Optimized_IR --(Code_generation)--> Target_code — Target_code: assembly or machine code for the target machine.

For syntax to remember (small): common three-address code patterns: t1 = b * c, t2 = a + t1, x = t2.

Worked examples

Example 1 — Full trace for a simple assignment expression Source statement: a = b + c * d; Step 1: Lexical analysis (list tokens with lexemes):

  1. IDENTIFIER (lexeme: "a")
  2. ASSIGN (lexeme: "=")
  3. IDENTIFIER (lexeme: "b")
  4. PLUS (lexeme: "+")
  5. IDENTIFIER (lexeme: "c")
  6. TIMES (lexeme: "*")
  7. IDENTIFIER (lexeme: "d")
  8. SEMICOLON (lexeme: ";") Step 2: Syntax analysis (assume grammar for expressions with precedence): Grammar rules (informal): E → E + T | T; T → T * F | F; F → id Leftmost derivation for tokens b + c * d: E ⇒ E + T ⇒ T + T ⇒ F + T ⇒ id + T ⇒ id + T * F ⇒ id + F * F ⇒ id + id * id Parse tree: internal nodes are nonterminals (E, T, F) and leaves are terminals (ids and operators). For b + c * d with T having higher precedence than E, the tree reflects E → E + T and T → T * F: the '+' combines the left E subtree (yielding id b) with the right T subtree, which in turn has '' combining id c and id d. Draw '+' above '', showing '' nested within the right T. Step 3: Build AST (remove grammar noise): AST structure: assignment node '=' with left child id(a) and right child '+'; '+' node has left id(b) and right '' node; '' node has children id(c) and id(d). Step 4: Semantic analysis: check symbol table for types of a,b,c,d. If all int, type check passes (operator semantics valid for int). Step 5: IR generation (three-address code) — produce temporaries and linear code: t1 = c * d t2 = b + t1 a = t2 (Each line is a TAC instruction.) Step 6: Simple code generation to a hypothetical assembly (assume registers R1,R2,R3): LOAD R1, c MUL R1, d ; R1 = c * d LOAD R2, b ADD R2, R1 ; R2 = b + (cd) STORE a, R2 This is a straight mapping from TAC to instructions. Final answer (bold for exam): TAC lines are t1 = c * d; t2 = b + t1; a = t2.

Example 2 — Error detection and recovery (missing semicolon) Source fragment: x = y + z (semicolon omitted) next token starts a new statement w = 1; Phase and behaviour:

  • Parser reading tokens expects SEMICOLON after expression. When it sees IDENTIFIER w instead, parser reports a syntax error.
  • Recovery strategy (panic mode): discard tokens until a synchronising token is found, e.g., SEMICOLON or NEWLINE. If we use SEMICOLON as a sync token, the parser discards tokens until it finds ';' (here it discards w, =, and 1), thereby losing the entire w = 1; statement. Better: use single-token insertion: insert SEMICOLON at error point and continue; then w = 1; parses normally. Model answer: describe both detection (parser can't match grammar) and two recovery strategies (panic-mode discard to next SEMICOLON and single-token insertion), and show consequences on subsequent statements. State which strategy you choose and why.

Common mistakes

  • Confusing lexeme (actual character sequence) and token (type plus attribute). Define both before use.
  • Mis-ordering phases (e.g., performing optimisation before semantic checks). Semantic checks must happen before transforming code in ways that could hide errors.
  • Thinking optimisations can change program meaning — they must be semantics-preserving; if unsafe optimisations are allowed, the requirements must be stated.
  • Mixing up parse tree and AST: parse tree contains all grammar nodes; AST is compact and used for later phases.
  • Forgetting that front end is language-dependent and back end is machine-dependent.

For your exam

Question types:

  • Definitions: define compiler, lexeme, token, parse tree, AST, IR, front end, back end, pass.
  • Short notes: explain the role of lexical analysis; list errors detected by each phase.
  • Derivations/diagrams: draw the compiler pipeline; show parse tree for given expression; show AST.
  • Algorithm traces: run a scanner on a small input; show LR parsing steps for a small grammar and input.
  • Programs: simple translator producing TAC for an expression.
  • Error recovery: explain strategies and consequences.

What full-marks answers include:

  • Precise definitions for terms used and clear input/output for each phase.
  • For diagrams: labelled boxes left-to-right, arrow labels, front end/back end boundaries.
  • For algorithm traces: step-by-step token lists, parser stack contents or derivation steps, produced TAC lines with temporaries named and explained.
  • State assumptions (e.g., language grammar or operator precedence) before starting a derivation.

Quick check

  1. What is the output of lexical analysis?
  2. Which phase builds the symbol table?
  3. Give one property an optimisation must satisfy. Answers: Tokens (token-type + attribute); Semantic analysis (and front end) builds and fills the symbol table; It must preserve program semantics (observable behaviour) while improving some resource metric.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?