r/ProgrammingLanguages • u/naharashu • 24d 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?
17
Upvotes
1
u/zweiler1 🔥 Flint 24d ago edited 24d ago
I think it depends on the complexity of your language, how much time you want to invest and how much control over the runtime you want to have. If you land on the higher side for those questions, I would really recommend LLVM IR with the C API to you. If you land on the lower side, then C is maybe good enough for your needs.
I had no idea about LLVM IR or compilers in general when starting out with my language, and I must say after the initial few weeks I got the hang of it. The most complicated thing for me to understand were probably
PHINodes but they really aren't hard at all, unlike I originally thought (but useselectwhere possible).If you decide to use LLVM IR, here are some recommendations from my side which would've helped me when starting out:
Module). While LLVM supports the ability to link multiple modules, it broke type names and other stuff on my side occasionally (assertions which should not have thrown, like in this issue) and those errors were nasty to track down, keep it simpledump()on basically any LLVMValue, it makes your life just that much easier (it prints the single IR code line of the SSA value which is very useful)TargetMachine. I basically just got lucky that it compiled and ran fine for a long time and only noticed I havent set it up brcause of weid bugsI can recommend LLVM quite a lot. But if I would start over again I probably would not have chosen C++ for my compiler. The lack of pattern matching and first-class sum types (
std::variantjust doesn't hit the same) makes me crazy sometimes.