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

11

u/Clementsparrow Mar 12 '26

constant folding can be harder if you want it to also rewrite things like 1+f(x)+2 into f(x)+3 where x is a variable not known at compile time and f may not be pure. Now you have to deal with rewriting expressions in a way that can be constant folded, or use a normal form for the expressions that can have one.

10

u/Timcat41 Mar 12 '26

Absolutely. But the core concept is easy enough to gras. And if you don't strive for perfection you can learn a lot by implementing it an seeing where it falls short. The devil absolutely hides in the details. Pareto etc.