[clang] [CIR] Handle proper hoisting of const variables with InvariantGroupOp (PR #175037)
Sirui Mu via cfe-commits
cfe-commits at lists.llvm.org
Fri Jan 9 23:10:17 PST 2026
Lancern wrote:
> @Lancern Have you seen any significant benefits from the invariant handling? In general, the LLVM optimizer is very good at detecting when alloca loads are redundant, and it seems to me that this might be introducing more fragility than benefit.
The initial motivation is to optimize for code like this:
```cpp
int g();
void use(int);
void h(const int *); // <-- The body of h is external.
void f() {
const int x = g();
h(&x);
use(x);
}
```
Since `h` is external, LLVM cannot take the risk to eliminate the reload from alloca before calling `use`, despite that the reload is indeed unnecessary according to the C++ standard. One hope of CIR was (and I believe it still is) to enable language-specific optimizations like this.
To enable such optimizations we had two choices:
1. Implement some kind of const-propagation pass directly in CIR.
2. Teach LLVM to optimize this by emitting better LLVM IR or attaching more metadata to the IR.
It was decided that 1 would probably be an overkill. Since LLVM already has something like invariant group (although it's experimental and it has caveats as @andykaylor pointed out), 2 would seem like a more reasonable approach back then.
https://github.com/llvm/llvm-project/pull/175037
More information about the cfe-commits
mailing list