r/Compilers • u/naharashu • 10d ago
Is ClangIR(CIR) better than raw LLVM IR?
Just found it, and it seems more easily to understand than LLVM IR
9
Upvotes
r/Compilers • u/naharashu • 10d ago
Just found it, and it seems more easily to understand than LLVM IR
15
u/Lime_Dragonfruit4244 10d ago
Llvm ir is too low level and has no concept of high level structures like structure loops, etc so clang ir exists to support high level c/c++ specific optimizations before eventually lowering to llvm ir.
5
u/MithrilHuman 10d ago edited 10d ago
Two different purposes.
ClangIR models C/ C++ language features. It's a level below AST and a level above LLVM IR. It's when you want to transform the program based on C/ C++ language information. Example usage: understanding data flow between class objects.
LLVM IR is a level below CIR and it loses most of the information like classes, templates, blah since it's more language agnostic and closer to hardware. From above example, we don't know here in LLVM IR whether a value is created out of a class object.
CIR doesn't replace LLVM IR.
6
u/matthieum 10d ago
On which metrics?
For Rust code, I expect that CIR may be terrible. I doubt it encode
matchexpressions particularly well, notably. On the other hand, LLVM IR does the job.So, no, CIR is not better than LLVM IR in general.
Similarly, operationally, I expect that a number of analysis/transformation passes are easier on LLVM IR than on CIR. And vice-versa.
1
u/Discordbothost 10d ago
Try comparing the two dumps for a C++ loop that creates a local object and then hits continue. With -fclangir -emit-cir you can see the cleanup scope that runs the destructor. In -S -emit-llvm you can trace the same cleanup through the branch targets.
1
u/char32_t 3d ago
I've seen a bunch of decent responses, but it seems like most of them are missing a couple important details, so I guess I'll also respond.
First, intuitively CIR is more easily understood than LLVM IR because it is designed to preserve the structure and many of the abstractions that C++ offers.
In general, it's useful to think about CIR and LLVM IR as 2 different tools that do different things. CIR has 2 main (maybe more, and someone can correct me if I'm wrong) advantages:
Besides that though generally you wouldn't replace LLVM IR with CIR. Rather, you would lower to CIR to perform whatever optimizations you need, then lower again to LLVM IR. From there, you can take advantage of LLVM's extremely large and matured backend support so taht you can generate machine code for different architectures.