Reading — step 1 of 5
Read
~1 min readCode Generation
Code Generation
Lower IR to assembly. For each IR instruction, emit corresponding asm.
Stack-based codegen (simplest):
- Every value lives on the stack initially.
- Operations pop operands, push results.
python
For a function:
python
Function calls:
gen_expr(arg1) -> push rax (etc., last)
mov rdi, [rsp+...] ; load args from stack into reg
mov rsi, [rsp+...]
call <func>
add rsp, <args*8> ; clean up
push rax ; result
Stack frame layout (x86-64 ABI):
[caller's frame]
[return address]
[old rbp] <- rbp
[local var 0] <- rbp-8
[local var 1] <- rbp-16
...
[temp slot] <- rsp
Naive stack-machine codegen is suboptimal: every operation hits memory. Real compilers use register allocation to keep values in regs as long as possible.
For our compiler:
- Skip register allocation.
- Stack everything.
- Resulting code is correct but slow.
- Modern compilers' optimization output is 5-10x faster.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…