问题
For writing a compiler, what are the advantages and disadvantages of using LLVM IR vs C for a target language? I know both are used, and I imagine that the final machine code would be similar if I were to use clang to compile the C. So what are other things to consider?
回答1:
I've used LLVM IR for a few compiler back ends and have worked with compilers that use C as a back end. One thing that I found that gave the LLVM IR an advantage is that it is typed. It is hard to make completely ill-formed output without getting errors from the LLVM libraries.
It is also easier to keep a close correlation between the source code and the IR for debugging, in my opinion.
Plus, you get all the cool LLVM command line tools to analyse and process the IR your front end emits.
回答2:
LLVM advantages:
- JIT - you can compile and run your code dynamically. Sure the same is possible with C (e.g., using an embedded
tcc
), but it is a much less robust and portable option. - You can run your own optimisation passes over the generated IR.
- Reflection for free - inspecting the generated code is much easier with LLVM.
- LLVM library is not as big as most of the C compilers (not counting
tcc
, of course).
LLVM drawbacks:
- Code is not portable, you have to change it slightly depending on your target. There is a somewhat portable subset of LLVM, but it is still a dodgy practice.
- Runtime dependency on the C++ libraries, might be a bit of an issue.
回答3:
I doubt you can implement proper debugging support for your language when targeting C.
回答4:
Architectures and OSes for which there is no CLANG obviously, or for which it is in an experimental state.
C is more widely accepted, but LLVM IR allows you to spoon feed the LLVM engine. Not all paths to IR are equal.
来源:https://stackoverflow.com/questions/10264635/compiler-output-language-llvm-ir-vs-c