[llvm] [GlobalOpt] Fix alignments of globals introduced for allocations (PR #216480)

Ömer Sinan Ağacan via llvm-commits llvm-commits at lists.llvm.org
Mon Aug 17 01:52:37 PDT 2026


================
@@ -944,15 +944,37 @@ OptimizeGlobalAddressOfAllocation(GlobalVariable *GV, CallInst *CI,
       UndefValue::get(GlobalType), GV->getName() + ".body", nullptr,
       GV->getThreadLocalMode());
 
+  // Alignment of the return value of the allocator call.
+  Align GVAlign = CI->getPointerAlignment(DL);
+
+  // If the allocation function has a valid constant `allocalign` argument
+  // that's larger, increase the alignment.
+  const Value *AllocAlign = getAllocAlignment(CI, TLI);
+  if (AllocAlign) {
+    const ConstantInt *AllocAlignC = dyn_cast<ConstantInt>(AllocAlign);
+    if (AllocAlignC &&
+        AllocAlignC->getValue().ult(llvm::Value::MaximumAlignment)) {
+      uint64_t AllocAlignVal = AllocAlignC->getZExtValue();
+      if (llvm::isPowerOf2_64(AllocAlignVal)) {
+        GVAlign = std::max(GVAlign, Align(AllocAlignC->getAlignValue()));
----------------
osa1 wrote:

Ah, I think I understand the concern now.

Say I have an allocation

```
%p = call noalias align 16 ptr ...
```

and a load or store

```
%x = load ptr, ptr %p, align 32
```

If we assume that the program is correct, then the allocation call must be returning 32-byte aligned. Therefore the global should be 32-byte aligned as well.

@efriedma-quic did I get this right or do you mean something else?

Re: `allocalign`, a similar argument applies. If we can't figure out the actual `allocalign` value then we don't know if the alignment needs to be increased and I guess there could be assumptions in the rest of the code about the alignment (i.e. the `allocalign` to return a more alignment pointer than what the call site declares)

If you confirm that my understanding is correct I'll update this to take the max. of load/store alignments, and to not do the transformation when there's an `allocalign` argument that's not a valid constant.

https://github.com/llvm/llvm-project/pull/216480


More information about the llvm-commits mailing list