How a compiler turns code into machine code

· 2 min read

#how-it-works#apple-dev

A processor cannot run Swift or C source code; it runs machine instructions. A compiler translates one into the other in stages, and the idea to keep is that every stage hands a simpler form to the next.

The short version

A compiler is usually described in three parts. The front end reads your source, reports errors and builds a syntax tree (AST) for that language. The optimizer improves the code, mostly independent of the language and the machine. The back end maps the code to the instruction set of one processor. Between them sits a shared intermediate representation (IR): LLVM IR, for example, is a low-level, strongly typed virtual instruction set.

From source code to executable Source code goes to the front end, which produces the intermediate representation. The optimizer improves it, the back end produces machine code for one processor, and the linker combines the result into an executable. Source code Front end IR Optimizer Back end Executable 1 read 2 lower 3 improve 4 emit 5 link
Simplified: each arrow hands a simpler form to the next stage; the last one links the pieces into one file.

Step by step

  1. The front end parses the source, reports mistakes and builds the AST.
  2. The AST is lowered to the IR. Swift adds a layer here: its own IR, called SIL, comes first, then LLVM IR.
  3. The optimizer rewrites the IR to improve it.
  4. The back end turns the IR into machine code for one instruction set.
  5. The linker joins the pieces into one executable.

GCC can stop after each stage:

Flag Stops after You get
-E preprocessing preprocessed source on standard output
-S compiling an assembly file (.s)
-c assembling an object file (.o)
none linking an executable (a.out)

Why it matters

Because the IR is shared, a new language needs only a new front end and a new processor only a new back end. Without it, every pair of language and processor would need its own compiler.

Sources