[llvm] [NaryReassociate] Fix divide by zero crash in NaryReassociatePass (PR #202377)

via llvm-commits llvm-commits at lists.llvm.org
Mon Jun 8 09:01:31 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-transforms

Author: t-demchuk

<details>
<summary>Changes</summary>

Updates NaryReassociatePass with a safety check to guard against GEPs into arrays with zero sized element types (eg. [0 x ptr]) to prevent division by zero.

---
Full diff: https://github.com/llvm/llvm-project/pull/202377.diff


2 Files Affected:

- (modified) llvm/lib/Transforms/Scalar/NaryReassociate.cpp (+1-1) 
- (added) llvm/test/Transforms/NaryReassociate/nary-gep-zero-sized-element.ll (+22) 


``````````diff
diff --git a/llvm/lib/Transforms/Scalar/NaryReassociate.cpp b/llvm/lib/Transforms/Scalar/NaryReassociate.cpp
index cf0d77dc11116..5bdbd3e8b47cb 100644
--- a/llvm/lib/Transforms/Scalar/NaryReassociate.cpp
+++ b/llvm/lib/Transforms/Scalar/NaryReassociate.cpp
@@ -442,7 +442,7 @@ NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
   // sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
   //
   // TODO: bail out on this case for now. We could emit uglygep.
-  if (IndexedSize % ElementSize != 0)
+  if (ElementSize == 0 || IndexedSize % ElementSize != 0)
     return nullptr;
 
   // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
diff --git a/llvm/test/Transforms/NaryReassociate/nary-gep-zero-sized-element.ll b/llvm/test/Transforms/NaryReassociate/nary-gep-zero-sized-element.ll
new file mode 100644
index 0000000000000..04db4bf17b994
--- /dev/null
+++ b/llvm/test/Transforms/NaryReassociate/nary-gep-zero-sized-element.ll
@@ -0,0 +1,22 @@
+; RUN: opt < %s -passes=nary-reassociate -S | FileCheck %s
+
+; This test checks that NaryReassociate does not crash when a GEP's result
+; element type has a size of zero (eg. [0 x ptr] such as `%T` below).
+
+; CHECK-LABEL: define ptr @foo
+; CHECK-SAME: (ptr [[BASE:%.*]], i64 [[X:%.*]], i64 [[Y:%.*]]) {
+; CHECK-NEXT:    [[Z:%.*]] = add i64 [[X]], [[Y]]
+; CHECK-NEXT:    [[GEP1:%.*]] = getelementptr [[T:%.*]], ptr [[BASE]], i64 [[X]], i32 1
+; CHECK-NEXT:    [[GEP2:%.*]] = getelementptr inbounds [[T]], ptr [[BASE]], i64 [[Z]], i32 1
+; CHECK-NEXT:    ret ptr [[GEP2]]
+
+target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
+
+%T = type { [1 x ptr], [0 x ptr] }
+
+define ptr @foo(ptr %base, i64 %x, i64 %y) {
+  %z = add i64 %x, %y
+  %gep1 = getelementptr inbounds %T, ptr %base, i64 %x, i32 1
+  %gep2 = getelementptr inbounds %T, ptr %base, i64 %z, i32 1
+  ret ptr %gep2
+}

``````````

</details>


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


More information about the llvm-commits mailing list