How Compilers Work

The phases of a compiler — lexing, parsing, semantic analysis, IR, optimisation and code generation — front end vs back end, compilers vs interpreters vs JITs, and how real toolchains like GCC, LLVM, javac and V8 fit the model.

Intermediate 4 min readLesson 1 of 8 Interview Q&A

A compiler translates a program from one language (the source) into another (the target) — usually from a high-level language into machine code or bytecode — while preserving its meaning. It is one of the best-studied pieces of software in CS, and its structure reappears everywhere: SQL engines, template languages, regex engines, linters, bundlers and config parsers are all small compilers.

The pipeline

Front end (language-specific)Middle + back endSource codetextLexertokensParserASTSemantic analysistyped ASTIR generationIROptimiserbetter IRCode generationassemblyMachine codeobject file
PhaseInput → OutputCatches
Lexical analysisCharacters → tokensIllegal characters, unterminated strings
ParsingTokens → abstract syntax tree (AST)Syntax errors (missing ), misplaced keywords)
Semantic analysisAST → annotated AST + symbol tablesType errors, undeclared names, wrong argument counts
IR generation and optimisationAST → intermediate representation → better IR— (transformations must preserve meaning)
Code generationIR → target code—

A concrete trace of x = a + b * 2;:

Tokens:  IDENT(x) ASSIGN IDENT(a) PLUS IDENT(b) STAR INT(2) SEMI

AST:        Assign
           /      \
         x        Add
                 /    \
                a     Mul
                     /   \
                    b     2

IR (three-address code):
    t1 = b * 2
    t2 = a + t1
    x  = t2

x86-64:
    mov  eax, DWORD PTR [b]
    add  eax, eax              ; b * 2 strength-reduced to b + b
    add  eax, DWORD PTR [a]
    mov  DWORD PTR [x], eax

Front end, middle end, back end

The key architectural idea: a shared intermediate representation (IR) decouples languages from machines.

  • Front end: understands the source language (lexer, parser, type checker). One per language.
  • Middle end: language- and machine-independent optimisation on the IR.
  • Back end: instruction selection, register allocation and scheduling for one target (x86-64, ARM64, RISC-V, WebAssembly).

Without an IR, M languages × N targets need M×N compilers; with one, you need M front ends + N back ends. This is exactly how LLVM works: Clang (C/C++), rustc, Swift, Zig and Julia all emit LLVM IR and share its optimiser and back ends.

Compilers, interpreters and JITs

StrategyHow it runsExamplesTrade-off
Ahead-of-time (AOT) compilerTranslate to machine code before runningC, C++, Rust, Go, SwiftFast execution, slower builds, per-platform binaries
Tree-walking interpreterWalk the AST and execute each nodeEarly Ruby, many toy languagesSimple; slow
Bytecode VMCompile to compact bytecode, interpret thatCPython, Lua, early JVMPortable, faster than AST walking
JIT compilerInterpret first, compile hot code to machine code at runtimeJVM HotSpot, V8, .NET, PyPy, LuaJITFast steady state, uses runtime profiles; warm-up cost
TranspilerSource → another high-level languageTypeScript → JS, Babel, Sass → CSSReuses an existing platform

The lines blur: Java is compiled AOT to bytecode by javac, then interpreted and JIT-compiled by the JVM (JIT compilation); V8 parses JS to bytecode, interprets it in Ignition, and optimises hot functions with TurboFan (V8 internals). See Interpreters and VMs.

Real toolchains

gcc main.c  →  preprocessor → compiler (cc1) → assembler (as) → linker (ld) → a.out

clang -O2 -S -emit-llvm main.c     # see LLVM IR
clang -O2 -S main.c                # see assembly
gcc -O2 -fdump-tree-all main.c     # dump every GCC pass
  • Preprocessor (C/C++): textual #include and macro expansion before lexing.
  • Assembler: assembly → object file with machine code and relocations.
  • Linker: combines object files and libraries, resolves symbols, produces the executable. Link-time optimisation (LTO) delays optimisation so it can see across files.

Godbolt's Compiler Explorer (godbolt.org) shows the assembly any compiler produces for your code in real time — the best way to build intuition.

Why learn this

  • Better code: knowing what the optimiser can and can't do (inlining, vectorisation, escape analysis) tells you when to write things differently and when not to bother.
  • Reading errors: parse errors, type inference failures and borrow-checker messages make more sense.
  • Building tools: DSLs, query languages, linters, formatters and code generators use the same techniques.
  • Interviews: "What happens when you compile a program?" and "Compiled vs interpreted?" are common.
Key takeaways
  • A compiler is a pipeline: lex → parse → semantic analysis → IR → optimise → generate code.
  • The front end understands the language; the back end understands the machine; the IR connects them (LLVM's M + N design).
  • AOT compilers, interpreters, bytecode VMs and JITs trade start-up time, peak speed and portability.
  • Real toolchains add a preprocessor, assembler and linker; LTO optimises across files.
Interview questions
QWhat is the difference between a compiler and an interpreter?easy

A compiler translates the whole program into another form (usually machine code) before it runs, so execution is fast and errors like type errors are found early. An interpreter executes the program directly, statement by statement or from bytecode, which starts faster and is more portable but runs slower. Most modern systems mix the two: Java and C# compile to bytecode then JIT-compile hot code; V8 interprets bytecode and optimises hot functions.

QWhy do compilers use an intermediate representation?medium

An IR separates language concerns from machine concerns. Front ends for many languages produce the same IR; optimisations are written once against the IR; back ends turn IR into code for each target. This cuts M×N compilers to M+N components, which is how LLVM supports many languages and architectures. IRs are also designed to make analysis easy (e.g. SSA form).