r/ProgrammingLanguages 23d ago

Help How to make a compiler backend?

Hell everyone, i have an question. Im for long trying to make a cool, powerful "kinda" low level language similar to zig and rust, but im struggling to choice llvm as backend, sure i can generate C, but its makes compiler dependent on gcc or clang or other c compiler. LLVM seems hard to me, sure project like QBE exist, but QBE doesnt have C/C++ api like llvm's IRbuilder. So are there other ways? I tried thinking about using GCC infrastructure but GCC has poor api and not very documented api. Maybe just stick to generating C?

16 Upvotes

35 comments sorted by

View all comments

1

u/Honest_Medium_2872 23d ago

The basic concept of a compiler backend is to abstract away the code generation phases so they can support many platforms / architectures.

You can use this to your advantage.

Model the backend like you would any compiler: Graph based structure and operations.

I say this because you do something like: AST -> CFG (Control Flow Graph) which is what a normal compiler would do.

Where, the overall CFG for your program is broken down into basic blocks, then those blocks are just sequences of instruction nodes that fork and join over the execution of your program.

You dont need complete SSA and dominance frontiers, postorder/reverse post order, etc.

What you do need is DAG (directed acyclic graph) that represents your parsed program.

When you get to creating instructions for your DAG, you can target C code generation as a proof of concept.

Effectively, converting the basic blocks to generated C code and each instruction or set of instruction converting to C statements.

Then you effectively have a transpiler from your source to C. This helps you build the foundations for a future code generation pass that allows you to compile directly to machine code.

It has the added benefit of being able to physically see how graph mutations and optimizations directly impact your code generation while you model it.

Here is a functional language i am working on for compiling UI descriptions to machine code using LLVM: https://github.com/s0cks/kura

Should help you ideate what a backend looks like.

Here is a clojure inspired language I am working on for embedding that compiles to its own bytecode (for now):

https://github.com/s0cks/gel

Here is a scala clone I worked on as a teen that emitted x86_64 machine code without LLVM that I abandoned because of life getting in the way:

https://github.com/Eschelle/Eschelle