Because we use a "dumb" Code Generator that blindly translates lines 1-to-1 into assembly, we have to make our code "smart" during the IR phase. Optimization passes analyze the IR instructions and rewrite them to be more efficient without changing the final output of the program.
Our Optimization Passes
Constant Propagation: If a variable is assigned a constant number (x = 5), the optimizer replaces all future uses of x with the number 5.
Constant Folding: If an instruction does math with two raw numbers (t0 = 5 + 10), the compiler just does the math immediately and replaces the instruction with the result (t0 = 15).
Strength Reduction: Replaces "expensive" CPU operations with cheaper ones. For example, replacing a multiplication by a power of two (x * 4) with a hyper-fast bitwise shift (x << 2).
Dead Code Elimination: Scans the IR for variables or temporaries that are created but never actually used later in the program. It deletes these instructions entirely to save memory and CPU cycles.
Interactive Optimizer Simulator
Click through the optimization passes below. Notice how propagation and folding have a cascading effect, creating unused "dead code" that we can delete at the very end!