Intermediate Representation (IR) is like a translation of your code into a simpler, more structured version — just for the computer.
It’s not exactly the code you wrote, and it’s not machine code either. It’s in the middle, and it helps the compiler do its job: check, analyze, and make the code faster before it runs.
In short, It is the middle layer that helps compilers understand and improve your code.
🗂️ Are there different types of IR?
Yes! Most modern compilers break IR into multiple layers, going from high-level (close to your original code) down to low-level (closer to machine code):
1️⃣ HIR – High-level IR
Still looks a lot like your original code.
Keeps
if
,&&
,for
, and other logic.Easy for the compiler to analyze what the code means, but not ready for optimization.
Example:
if (user.isLoggedIn && user.hasRole("admin")) { ... }
2️⃣ MIR – Mid-level IR
Splits big expressions into simple steps.
Much easier for the compiler to optimize or rearrange.
t1 = user.isLoggedIn
t2 = user.hasRole("admin")
t3 = t1 && t2
if (t3) goto BLOCK_ADMIN
3️⃣ LIR – Low-level IR
Now the code looks like instructions for the machine.
You’ll see low-level operations like
LOAD
,CMP
,JUMP
,...
LOAD R1, user.isLoggedIn
LOAD R2, user.hasRole
CALL R2, "admin"
AND R3, R1, R2
CMP R3, 0
JZ END
⁉️ How Compilers Understand IR?
To make sense of your program, compilers don’t just read code line by line — they look at how the logic flows. That’s where Control-Flow Graphs (CFGs) come in.
- A CFG is like a roadmap that shows all the different routes your program might follow as it runs.
- It breaks your code into basic blocks — small, straight pieces of code with no jumps — and connects them based on decisions like
if
,else
, orloops
. - This helps the compiler understand your program's logic clearly, clean up unused code, and make everything run faster.
Example:
⚒️ Tools that use IR
Tool / Compiler | Note |
---|---|
LLVM (Clang, Swift) | Uses powerful LLVM IR |
Rust | Uses HIR → MIR → LLVM IR |
React Compiler | Uses HIR and reactive scopes |
V8 (Chrome JS engine) | Uses internal IR for JIT compilation |
🎯 Conclusion
IR is how your code becomes smarter before it runs.
It helps compilers understand, improve, and prepare your program step by step.
If you:
- Build developer tools.
- Work with performance-critical code.
- Want to dive deeper into how compilers think.
🔗 References
- Intermediate representation - wiki
- Introduction to Intermediate Representation(IR) - geeksforgeeks.org
- What is an Intermediate Representation? - piovezan blog
- CFG Basic - docs.washi.dev
- CFG - wiki