What is an Intermediate Representation (IR)?
You'll learn why compilers don't translate source code directly to machine code, but use an intermediate step that makes everything easier.
The Bridge Between Two Worlds
When a compiler translates your source code (like Python or C) into machine code, it rarely goes directly from one to the other. Instead, it creates an intermediate representation (IR) — a form of code that sits between high-level source and low-level machine instructions.
Think of IR like a universal translator. If you have 5 programming languages and 3 different processor architectures, you'd need 15 different translators without IR. With IR, you need only 5 "language-to-IR" translators and 3 "IR-to-machine-code" translators — just 8 total.
Why Use IR?
Optimization becomes simpler: Once code is in IR form, the compiler can apply powerful optimizations (eliminating redundant calculations, reordering instructions, etc.) without worrying about the quirks of either the source language or the target machine.
Portability: The front-end of the compiler translates any source language to the same IR. Then different back-ends can translate that IR to different machine architectures (x86, ARM, etc.). Change the source language? Only rewrite the front-end. Add a new processor? Only write a new back-end.
Cleaner design: IR provides a clean separation of concerns. The parser and semantic analyzer produce IR. The optimizer works on IR. The code generator consumes IR.
Common IR forms include three-address code (each instruction has at most three operands) and control-flow graphs that represent program structure explicitly.
Key Takeaway: Intermediate Representation is a compiler's internal format that separates high-level language concerns from machine-specific details, enabling powerful optimizations and supporting multiple source languages and target platforms efficiently.