r/Compilers • u/Potato871 • Sep 06 '26
Why not retain the AST?
I've been working on a compiler-like system for a while now, and it's gone through many stages of evolution.
A consistent pressure early on was away from multiple representations: I started with many switch statements and many kinds of representation for each stage, and ended up with one kind of node and handler based dispatch per stage.
Yet, when I look at (most) other compilers, their construction is far more static in nature, and far more varied in terms of the kinds of things presented. I've found forms like SSA impede my ability to reason about optimizations rather than aide them, and I've had enormous success from simply retaining and annotating one structure rather than continually converting.
A specific case, to provide one, is liveness propagation. Because values are already shared between their occurances (Nodes) and already have a system for acquiring properties (Quals), I can simply mint liveness tokens onto the children of expressions with output, and it automatically propagates.
Though I've not focused too much on codegen and optimization, my main goal with the compiler is extensibility and syntax flexibility.
So why not retain the AST? Turn it into a structure worth annotating and preserving from which optimizations and codegen can be performed more easily?
I wanted to get the opinions of others on this matter, I'm open to challenge.
Some more explanation can be found here: https://goldensystems.ca/GDSL_core
42
u/awoocent Sep 06 '26
The big issue with the AST is that control successors, and likely many data successors, are not easily traversible. If I have a source program like:
...how do I figure out where
xcomes from? If we look naively at the structure, an AST for the above will look a bit like this:To get from
(:= x 1)to the subsequent instruction, I need to reach up into my parent nodeif, and then its parent nodeblock, and then look at the next child. This is a nontrivial procedure, since I can't just look generically at the next child of the parent - it would be incorrect to pick the next child of theif, for example, since(:= x 2)does not execute after(:= x 1). So it's a bit nasty. Likewise for finding the predecessor. And I can make this arbitrarily complex if I wanted to nest the if statements.If we linearize this into SSA though, we get something like:
Now that there are no nested expressions, to get from any instruction to its predecessor or successor just requires finding the instruction before or after us in our block, or in a previous/subsequent block in the boundary case.
You might rebut this by saying, well, when do I need to actually traverse the tree like that? And it's true you can get pretty far by just walking the AST with a state, since the order you traverse the AST lines up with the linearized order of SSA instructions. But while this is pretty successful in simple cases, and works well for liveness, it becomes inconvenient in a couple optimizations.
Imagine you want to run something like strength reduction, pattern matching expressions and applying rules like reducing
x * 4intox << 2or so. For one, without SSA to make dataflow explicit, you have to be really conservative - in the above example, since we put it into SSA, we knowx1is always exactly equal to 2, but in the initial AST we don't distinguish betweenx0orx1orx2and need to consider the possibility of mutation - likely pessimizing the optimization.For two, we also usually want to run optimizations like this until fixpoint, since applying one optimization could allow another one to take place (imagine we have
x * 4 << 2, which reduces tox << 2 << 2, and thenx << 4). For efficiency's sake we might want to revisit only part of the graph, keeping a worklist of instructions we think still have optimization potential, or for whom at least one dependency changed in the last pass. In SSA, this is no biggie, since we structurally encode the dataflow, so we can just go to a given instruction and check out its uses and defs. But over an AST, since we need to walk the AST with a state in order to recover order-dependent information, to recover all the information for a node in the middle of a block, you'd need to either store the state at each node which is space inefficient, or you'd need to re-walk the state over the tree which is time inefficient. Probably you'd want to do a mix, and that can work - but it's hopefully clear how SSA or something with similar properties like Sea of Nodes makes this easier.In general, SSA is also just more efficient. To walk a tree with a state requires, well, a state. And without preprocessing, that state needs to be potentially pessimistically large. Like, in general, each node can potentially contain arbitrarily many expressions and state modifications and internal control changes, so the state probably needs to store some data for each variable - even if some variables are only ever defined and used once, which is really common. You can try some data compression tricks like having hierarchical states and storing difference lists and stuff, but I think you always have to be a little conservative. Whereas if you use an IR built for this purpose, the IR nodes themselves store exactly the data and control flow edges they need. It's hard to beat that. Note that you basically still have to do this once when you put the IR into SSA in the first place, so one way you can think of SSA is that you are basically caching the order you traversed your AST, so you don't need to repeat that whole traversal in later use.
But yeah, not everyone cares about efficiency, especially in the compiler itself. If anything I do think people tend to be a little too pessimistic about what ASTs are capable of. So if it works for you, I think it could be a very reasonable choice.
10
u/schungx Sep 07 '26
Unfortunately CPUs do not run trees. They run instruction streams.
Turning a tree (the AST) into a stream is what codegen is about.
It is ironic that source code also comes in a stream of characters. They got turned into a tree, then back to a stream.
9
u/AustinVelonaut Sep 06 '26
Others have discussed the tradeoffs in sticking with a single AST representation vs lowering it to simpler IRs, and eventually linearizing to SSA, bytecode, native code, etc.
But when you mention retaining the AST, I initially thought you meant something else: serializing the AST after all the parsing / desugaring / optimizations / inlining have been done on it, to allow it to be deserialized later, and avoiding replication of all that work.
This can be very useful in languages that support separate modules; simply check the relative modification dates of the source / serialized AST files when importing a module, and just deserialize if possible. It allows you to continue working on a collection of module ASTs and do things like support inter-module inlining and other optimizations, but still be very fast when recompiling.
8
u/beephod_zabblebrox Sep 06 '26
in the kotlin compiler, there are two main IRs: the FIR, which is a frontend AST representation, and the.. IR, which is kinda like a stripped down and simplified version of the language. FIR gets compiled down to IR, which then goes through a set of lowerings that change it and/or add attributes to nodes. in the end, each backend compiles the lowered IR into a target specific representation (llvm ir, a js ast, etc.)
for a lot of things, it's going to be simpler to have a tree-based IR that is similar to the source language
2
u/roeschinc Sep 06 '26
I commented above but generally smaller languages (or IRs) are easier to correctly analyze and lower. For example why do you need N control flow constructs when you can represent them all uniformly?
You can see Rustc MIR does this with a dataflow-y / block like IR where all loops, if, match, and so are on represented uniformly.
Languages like Lean does this via elaboration to a small core where everything happens, same with Haskell.
C compilers traditionally had less of this but changing with ClangIR and other projects.
35
u/jesseschalken Sep 06 '26
If, for your language and target, you haven't found a reason not to retain the AST, there may indeed not be one.
6
u/roeschinc Sep 06 '26
The idea is you keep around the information as long as you need it, and then remove it in order to simplify.
For example source languages have a ton of different constructs, once you have done what you need like type checking or loop validation you can lower the source IR into something that is easier to a) analyze or b) further lower.
For example one positive property of SSA is you have standardized all your control flow into a single form to simplify analysis. Functional languages do this with CPS or other transforms.
The reason you might not see the value of the transformation is that you might not be doing the types of analyses they are designed to simplify. For example SSA / ANF are both designed to simplify data flow analyses and make it easier to do forward / backward, construct def-use chains and so on.
One last thing is source syntax is the easiest part of compilation, that’s why all the intermediate representations ie (IRs) are designed for optimization and lowering.
1
u/Dusty_Coder Sep 08 '26
Is there a particular reason to believe that an AST is the best representation?
The thing about intermediate representations, is that they are not arbitrary. They are designed for purpose.
A tree can be good for finding satisfying global constraints efficiently.
However, Its straight forward to scan forward and backward through a sequence looking to find satisfying local constraints efficiently.
The presumption is that the AST has already been made well suited, before it is turned into an IR, which itself then needs to be made well suited.
There is no stage of this where optimizations are not performed. Even the parser might be folding some constants.
3
u/ZachVorhies Sep 07 '26
don’t listen to anybody else here that tells you that this is not a good idea… it is.
And it’s the backbone of all of the of the fastest compilers and linkers in existence.
Why is it mold or wild faster? Because they don’t retain the object tree in memory.
Why not?
Because daemons are client cli apps are freaking hard to get right.
specially, when you’re developing, and you want to iterate through multiple versions of the daemon while running the demons yourself for build operations.
however, if you get this right, your language compiler will scream.
3
u/grashalm01 Sep 07 '26
I think you want to look into futamura projections. I am generating compilers like this for the past 13 years.
3
u/ratchetfreak Sep 07 '26
you might want to look at Sea of Nodes then https://github.com/SeaOfNodes/Simple
That is essentially starting from the AST and then adding various ordering restrictions to each node in the tree, for example sequencing memory access for a variable such that loads and stores remain in the same order, phi nodes that connect to the condition that branched the control flow, masking memory accesses with those conditions,
after that you fully release the nodes from any other syntactic ordering constraint and can just manipulate them as if they are free-floating in a sea (of nodes)
Then later you schedule them again in some order
2
u/Inconstant_Moo Sep 10 '26
What is good engineering depends on your language and what you're trying to do and how the rest of your implementation works. Or to put it another way, your question has the exact same answer as every other really difficult question in tech:
The Koan
We made the long and lofty trek
to hear the Guru talk of Tech
and finding him atop his peak
implored him: "O great Guru, speak!
we beg you on our bended knees:
enlighten us, and tell us please
how not to make our programs crash,
how to invalidate a cache
and stop our data going stale,
and how to make our systems scale,
and how to name things (stating why)
and make a friendly API,
and how to manage memory
and not mess up with malloc/free
and say, what is the best defense
against a null dereference,
and how we ought to manage state,
and what and when we should mutate,
how FPLs should do IO,
and other things we need to know."
A minute's silence. Then he stirred
and said: "Now hearken to my word:
One koan answers all your woes
one mantra every Guru knows
the one true answer, deep and wise
to all the problems that arise
one secret only to be grasped."
"One answer only!" then we gasped,
"Oh, tell us what it is!", we cried,
and, smiling gently, he replied:
"Now learn from me, my simple friends,
the One True Answer: IT DEPENDS."
We kicked him 'til he begged us: "Stop!"
then flung him from the mountaintop.
1
u/VincentPepper Sep 08 '26
The later is close to the "Trees that Grow" paper: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/11/trees-that-grow.pdf
It's in haskell/about GHC so the framing is somewhat different but same idea really.
You define one basic AST that is shared between passes by extending/changing certain parts of it. I have mixed feelings about the approach tbh.
Sometimes it's just easier to understand a simpler AST with simpler types without having to think about what data sits in what node in what pass. But sometimes it's good for the ability to share functionality across multiple passes.
I think it's best when it's used sparingly, across passes that work on data that is mostly the same shape. If you push it beyond that it can make working on the code annoying imo.
I've skimmed your link and it feels like you are inventing a lot of your own nomenclature ("a traversal of a nodenet is called a program.") which makes it harder to get what's going on for people who worked on other compilers. Especially since it seems a large part of the description seems to paraphrase what's basically a visitor pattern.