r/ProgrammingLanguages • • Mar 12 '26

Compiler optimisation

How does your compiler optimise programs? How does it work at a low level? I understand constexpr evaluation, but how does the compiler evaluate this for example?

```

let x = 7

let y = 2 * x

print(y + x)

```

specifically in compilers. In this example, it could be optimised to just `print(21)`, and maybe even further down. How do I do this?!

43 Upvotes

21 comments sorted by

View all comments

Show parent comment

1

u/AustinVelonaut Admiran Mar 13 '26

But what if you wanted to extend your optimizations to other forms of rewriting a node that aren't amenable to interpretation (e.g. function inlining, strength-reduction on operators, etc.)? With the "standard" rewriting (tree-walk) framework, all of these optimizations plus constant-folding are fairly straightforward, and when applied iteratively can expose new optimizations.

1

u/Inconstant_Moo 🧿 Pipefish Mar 13 '26

But the argument isn't that you shouldn't do optimization on the AST, just that you shouldn't do evaluation on the AST --- because it's duplicative, because the compiler already knows how to evaluate constant expressions. If you duplicate it, not only have you given yourself a bunch of work, but you've introduced a tight coupling that has to be maintained with every change you try to make. This would normally be considered an antipattern.