Issue 234886
Summary [InstCombine] invariant.load dropped when unpacking array loads
Labels llvm:instcombine
Assignees
Reporter maleadt
    `unpackLoadToAggregate` copies `!invariant.load` to the per-element loads for structs (#152186), but the multi-element `ArrayType` path only copies AA metadata, so the metadata is lost when an array load is split:

```llvm
define void @f(ptr addrspace(1) %p, ptr addrspace(1) %q) {
  %v = load [2 x float], ptr addrspace(1) %p, align 8, !invariant.load !0
  store [2 x float] %v, ptr addrspace(1) %q, align 8
  ret void
}
!0 = !{}
```

`opt -passes=instcombine -S`:

```llvm
define void @f(ptr addrspace(1) %p, ptr addrspace(1) %q) {
  %v.unpack = load float, ptr addrspace(1) %p, align 8
 %v.elt1 = getelementptr inbounds nuw i8, ptr addrspace(1) %p, i64 4
 %v.unpack2 = load float, ptr addrspace(1) %v.elt1, align 4
  store float %v.unpack, ptr addrspace(1) %q, align 8
  %q.repack4 = getelementptr inbounds nuw i8, ptr addrspace(1) %q, i64 4
  store float %v.unpack2, ptr addrspace(1) %q.repack4, align 4
  ret void
}
```

(`[1 x T]` is fine: that path goes through `combineLoadToNewType`, which keeps the metadata.)

On NVPTX, `!invariant.load` is what selects the non-coherent read-only cache path, so after InstCombine the example above compiles (`llc -mtriple=nvptx64 -mcpu=sm_53`) to `ld.global.v2.b32` instead of `ld.global.nc.v2.b32`. Frontends that lower complex numbers to `[2 x float]` (e.g. Julia's `Complex{Float32}`) hit this; on a Maxwell GPU (Jetson Nano) the `ld.global.nc` versions of such loads measured 1.1-2.5x faster.

Proposed fix, mirroring the struct branch:

```diff
--- a/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp
@@ unpackLoadToAggregate
       auto *L = IC.Builder.CreateAlignedLoad(AT->getElementType(), Ptr,
 EltAlign, Name + ".unpack");
 L->setAAMetadata(LI.getAAMetadata());
+      L->copyMetadata(LI, LLVMContext::MD_invariant_load);
       V = IC.Builder.CreateInsertValue(V, L, i);
```

Two other places drop `!invariant.load` the same way when splitting a load:

- SROA `presplitLoadsAndStores` copies only `MD_mem_parallel_loop_access` / `MD_access_group` to the split loads (e.g. an `i64` invariant load stored to a `{ float, float }` alloca becomes two `i32` loads without it).
- VectorCombine `scalarizeLoadExtract` (a vector load whose only uses are `extractelement`s) sets only adjusted AA metadata on the scalar loads.

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to