Course contentsShow
← Computer Science
Lesson 2049 of 2,87246. Compilation and InterpretationFree lesson

Introduction to Code Generation

Code generation transforms intermediate representation into target machine or bytecode instructions.

Introduction to Code Generation

You'll learn: How compilers turn your program's intermediate representation into actual machine instructions or bytecode that a computer can execute.

What Is Code Generation?

Code generation is the final translation step in a compiler. After parsing your source code, building an abstract syntax tree, and converting it into an intermediate representation (IR), the compiler must produce target code — the actual instructions that will run on hardware or a virtual machine.

Think of it like translating a recipe (your IR) into specific cooking actions. The IR says "combine ingredients," but code generation produces the exact movements: "pick up bowl with left hand, pour 2 cups flour, stir clockwise 10 times."

From IR to Executable Code

The code generator takes structured IR — whether that's three-address code, SSA form, or another representation you've learned — and maps it to:

  • Machine code: Native CPU instructions (x86, ARM, etc.)
  • Bytecode: Virtual machine instructions (like Java bytecode or Python bytecode)

The generator must handle:

  • Instruction selection: Choosing which target instructions implement each IR operation
  • Register allocation: Deciding which variables live in fast CPU registers vs slower memory
  • Instruction ordering: Arranging operations to follow target platform rules

For example, an IR instruction like t1 = a + b might become the x86 assembly ADD EAX, EBX or the JVM bytecode iadd, depending on your target platform.

Why It Matters

Code generation bridges the gap between high-level program meaning (captured in IR) and low-level execution. It's where compiler optimizations meet hardware reality, and where your abstract computations become concrete instructions.

Key Takeaway: Code generation transforms intermediate representation into executable target instructions, translating platform-independent program structure into platform-specific machine code or bytecode.