[clang] [Clang][OpenMP] Fix crash on an `omp allocate` local in unreachable code (PR #242302)

Akash Manna via cfe-commits cfe-commits at lists.llvm.org
Sun Nov 15 22:39:16 PST 2026


https://github.com/akash-manna-sky updated https://github.com/llvm/llvm-project/pull/242302

>From 34fb37f610807cd9263533b26c28c0c245f01f3a Mon Sep 17 00:00:00 2001
From: Akash Manna <akash.manna.mymail at gmail.com>
Date: Sun, 8 Nov 2026 10:17:28 +0530
Subject: [PATCH 1/4] [Clang][OpenMP] Fix crash on an `omp allocate` local in
 unreachable code

Fixes #140336

CodeGen visits declarations even after the insertion point has been cleared, but the `omp allocate` path still emitted the `__kmpc_alloc` call there. For a declaration nothing can reach, such as a `switch` body before its first `case`, the call ended up outside any basic block and the verifier rejected the module.

Both allocation hooks now return early when there is no insertion point and the variable keeps its plain alloca. Jumping into the scope of such a variable is now an error, as for `__attribute__((cleanup))` and as GCC does: the allocation would be skipped but the `__kmpc_free` at scope exit would still run.

Assisted-by: LLMs!
---
 clang/docs/ReleaseNotes.md                    |   1 +
 .../clang/Basic/DiagnosticSemaKinds.td        |   4 +
 clang/lib/CodeGen/CGOpenMPRuntime.cpp         |   3 +
 clang/lib/CodeGen/CGStmtOpenMP.cpp            |   3 +
 clang/lib/Sema/JumpDiagnostics.cpp            |   5 +
 clang/test/OpenMP/GH140336.c                  | 104 ++++++++++++++++++
 clang/test/OpenMP/allocate_messages.cpp       |  23 ++++
 7 files changed, 143 insertions(+)
 create mode 100644 clang/test/OpenMP/GH140336.c

diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 6d1dbbbb6eb77b..0fbd3e5c4cc41a 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1471,6 +1471,7 @@ The `alpha.cplusplus.UseAfterLifetimeEnd` checker was renamed to `alpha.core.Use
 
 - Fixed an OpenMP `requires` directive read from a PCH or module losing its effect on
   semantic checks, which caused spurious `reverse_offload` errors.
+- Fixed a crash when a variable with `#pragma omp allocate` is declared in unreachable code; jumping into its scope is now an error. (#GH140336)
 - Added the OpenMP 6.1 `#pragma omp flatten` loop transformation and the
   `depth` clause. Flatten combines perfectly nested canonical loops into one
   loop. `depth(k)` selects how many outermost loops to combine (default 2).
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 56cc9721781063..fb5987b530642f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7024,6 +7024,8 @@ def note_protected_by_variable_non_pod : Note<
   "jump bypasses initialization of non-POD variable">;
 def note_protected_by_cleanup : Note<
   "jump bypasses initialization of variable with __attribute__((cleanup))">;
+def note_protected_by_omp_allocate : Note<
+  "jump bypasses allocation of variable with '#pragma omp allocate'">;
 def note_protected_by_vla_typedef : Note<
   "jump bypasses initialization of VLA typedef">;
 def note_protected_by_vla_type_alias : Note<
@@ -7084,6 +7086,8 @@ def note_enters_defer_stmt : Note<"jump enters a defer statement">;
 
 def note_exits_cleanup : Note<
   "jump exits scope of variable with __attribute__((cleanup))">;
+def note_exits_omp_allocate : Note<
+  "jump exits scope of variable with '#pragma omp allocate'">;
 def note_exits_dtor : Note<
   "jump exits scope of variable with non-trivial destructor">;
 def note_exits_temporary_dtor : Note<
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index d3a6ffee3ea748..591f1e8bcd2bec 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -12799,6 +12799,9 @@ Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
     // Use the default allocation.
     if (!isAllocatableDecl(VD))
       return UntiedAddr;
+    // Unreachable declaration: nothing can run the allocation.
+    if (!CGF.HaveInsertPoint())
+      return UntiedRealAddr.isValid() ? UntiedRealAddr : Address::invalid();
     llvm::Value *Size;
     CharUnits Align = CGM.getContext().getDeclAlign(CVD);
     if (CVD->getType()->isVariablyModifiedType()) {
diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index e63957df3e4069..97b845d6c6ab8d 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -2202,6 +2202,9 @@ Address CodeGenFunction::OMPBuilderCBHelpers::getAddressOfLocalVariable(
   const VarDecl *CVD = VD->getCanonicalDecl();
   if (!isAllocatableDecl(CVD))
     return Address::invalid();
+  // Unreachable declaration: nothing can run the allocation.
+  if (!CGF.HaveInsertPoint())
+    return Address::invalid();
   llvm::Value *Size;
   CharUnits Align = CGM.getContext().getDeclAlign(CVD);
   if (CVD->getType()->isVariablyModifiedType()) {
diff --git a/clang/lib/Sema/JumpDiagnostics.cpp b/clang/lib/Sema/JumpDiagnostics.cpp
index bbe6f644609bf8..7ef8ae07b346bc 100644
--- a/clang/lib/Sema/JumpDiagnostics.cpp
+++ b/clang/lib/Sema/JumpDiagnostics.cpp
@@ -157,6 +157,11 @@ static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) {
       return ScopePair(diag::note_protected_by_cleanup,
                        diag::note_exits_cleanup);
 
+    // Allocated at the declaration and freed at scope exit, like cleanup.
+    if (VD->hasLocalStorage() && VD->hasAttr<OMPAllocateDeclAttr>())
+      return ScopePair(diag::note_protected_by_omp_allocate,
+                       diag::note_exits_omp_allocate);
+
     if (VD->hasLocalStorage()) {
       switch (VD->getType().isDestructedType()) {
       case QualType::DK_objc_strong_lifetime:
diff --git a/clang/test/OpenMP/GH140336.c b/clang/test/OpenMP/GH140336.c
new file mode 100644
index 00000000000000..e9e0eb1bc6c7ed
--- /dev/null
+++ b/clang/test/OpenMP/GH140336.c
@@ -0,0 +1,104 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fopenmp -verify -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fopenmp -fopenmp-enable-irbuilder -verify -emit-llvm -o - %s | FileCheck %s --check-prefix=IRB
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fopenmp -x c++ -verify -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,CXX
+// expected-no-diagnostics
+
+typedef enum omp_allocator_handle_t {
+  omp_null_allocator = 0,
+  omp_default_mem_alloc = 1,
+  omp_large_cap_mem_alloc = 2,
+  omp_const_mem_alloc = 3,
+  omp_high_bw_mem_alloc = 4,
+  omp_low_lat_mem_alloc = 5,
+  omp_cgroup_mem_alloc = 6,
+  omp_pteam_mem_alloc = 7,
+  omp_thread_mem_alloc = 8,
+  KMP_ALLOCATOR_MAX_HANDLE = __UINTPTR_MAX__
+} omp_allocator_handle_t;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void stop(void) __attribute__((noreturn));
+
+// CHECK-LABEL: define {{.*}}void @gh140336(
+// CHECK-NOT: @__kmpc_
+// CHECK: switch i32
+// CHECK-NOT: @__kmpc_
+// CHECK: ret void
+// IRB-LABEL: define {{.*}}void @gh140336(
+// IRB-NOT: @__kmpc_
+// IRB: ret void
+void gh140336(int i) {
+  switch (i) {
+    int j;
+#pragma omp allocate(j)
+  }
+}
+
+// CHECK-LABEL: define {{.*}}void @after_return(
+// CHECK-NOT: @__kmpc_
+// CHECK: ret void
+// IRB-LABEL: define {{.*}}void @after_return(
+// IRB-NOT: @__kmpc_
+// IRB: ret void
+void after_return(int i) {
+  return;
+  int j;
+#pragma omp allocate(j) allocator(omp_large_cap_mem_alloc)
+  j = i;
+}
+
+// CHECK-LABEL: define {{.*}}void @after_noreturn(
+// CHECK-NOT: @__kmpc_
+// CHECK: unreachable
+// IRB-LABEL: define {{.*}}void @after_noreturn(
+// IRB-NOT: @__kmpc_
+// IRB: unreachable
+void after_noreturn(void) {
+  stop();
+  int j;
+#pragma omp allocate(j) align(32) allocator(omp_large_cap_mem_alloc)
+}
+
+// CHECK-LABEL: define {{.*}}void @reachable(
+// CHECK: [[TID:%.+]] = call i32 @__kmpc_global_thread_num(ptr @{{.+}})
+// CHECK: [[J:%.+]] = call ptr @__kmpc_alloc(i32 [[TID]], i64 4, ptr inttoptr (i64 2 to ptr))
+// CHECK: [[K:%.+]] = call ptr @__kmpc_alloc(i32 [[TID]], i64 4, ptr null)
+// CHECK: store i32 %{{.+}}, ptr [[J]],
+// CHECK: store i32 %{{.+}}, ptr [[K]],
+// CHECK: call void @__kmpc_free(i32 [[TID]], ptr [[K]], ptr null)
+// CHECK: call void @__kmpc_free(i32 [[TID]], ptr [[J]], ptr inttoptr (i64 2 to ptr))
+// CHECK: ret void
+// IRB-LABEL: define {{.*}}void @reachable(
+// IRB: [[J:%.+]] = call ptr @__kmpc_alloc(i32 %{{.+}}, i64 4, ptr inttoptr (i64 2 to ptr))
+// IRB: store i32 %{{.+}}, ptr [[J]],
+// IRB: call void @__kmpc_free(i32 %{{.+}}, ptr [[J]], ptr inttoptr (i64 2 to ptr))
+// IRB: ret void
+void reachable(int i) {
+  int j;
+#pragma omp allocate(j) allocator(omp_large_cap_mem_alloc)
+  int k;
+#pragma omp allocate(k)
+  j = i;
+  k = i;
+}
+
+#ifdef __cplusplus
+}
+
+struct S {
+  ~S();
+};
+
+// CXX-LABEL: define {{.*}}void @_Z17after_return_dtorv(
+// CXX-NOT: @__kmpc_
+// CXX-NOT: @_ZN1SD
+// CXX: ret void
+void after_return_dtor() {
+  return;
+  S s;
+#pragma omp allocate(s) allocator(omp_large_cap_mem_alloc)
+}
+#endif
diff --git a/clang/test/OpenMP/allocate_messages.cpp b/clang/test/OpenMP/allocate_messages.cpp
index cde714244c643b..ecda3aca98a424 100644
--- a/clang/test/OpenMP/allocate_messages.cpp
+++ b/clang/test/OpenMP/allocate_messages.cpp
@@ -149,3 +149,26 @@ int main(int argc, char **argv) {
 #pragma omp parallel allocate(d) // expected-error {{the referenced item is not found in any private clause on the same directive}}
   ;
 }
+
+void gh140336(int i) {
+  switch (i) {
+    int j; // expected-note {{jump bypasses allocation of variable with '#pragma omp allocate'}}
+#pragma omp allocate(j)
+  case 1: // expected-error {{cannot jump from switch statement to this case label}}
+    j = 3;
+    break;
+  }
+  goto label2; // expected-error {{cannot jump from this goto statement to its label}}
+  int k; // expected-note {{jump bypasses allocation of variable with '#pragma omp allocate'}}
+#pragma omp allocate(k)
+label2:
+  k = 4;
+  void *p = &&label3;
+  {
+    int l; // expected-note {{jump exits scope of variable with '#pragma omp allocate'}}
+#pragma omp allocate(l)
+    goto *p; // expected-error {{cannot jump from this indirect goto statement to one of its possible targets}}
+  }
+label3: // expected-note {{possible target of indirect goto statement}}
+  ;
+}

>From 08492c90b6b88d0df76d8f52672d117e1f4e26c5 Mon Sep 17 00:00:00 2001
From: Akash Manna <akash.manna.mymail at gmail.com>
Date: Fri, 13 Nov 2026 18:38:10 +0530
Subject: [PATCH 2/4] Reposition the release notes to avoid the conflicts!

---
 clang/docs/ReleaseNotes.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 0fbd3e5c4cc41a..704d997934057f 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1471,7 +1471,6 @@ The `alpha.cplusplus.UseAfterLifetimeEnd` checker was renamed to `alpha.core.Use
 
 - Fixed an OpenMP `requires` directive read from a PCH or module losing its effect on
   semantic checks, which caused spurious `reverse_offload` errors.
-- Fixed a crash when a variable with `#pragma omp allocate` is declared in unreachable code; jumping into its scope is now an error. (#GH140336)
 - Added the OpenMP 6.1 `#pragma omp flatten` loop transformation and the
   `depth` clause. Flatten combines perfectly nested canonical loops into one
   loop. `depth(k)` selects how many outermost loops to combine (default 2).
@@ -1534,6 +1533,7 @@ The `alpha.cplusplus.UseAfterLifetimeEnd` checker was renamed to `alpha.core.Use
   modifications to the bindings will not be reflected in the original variable.
   To ensure correct behavior, either use the original variable directly in the
   target region or map the bindings explicitly instead.
+- Fixed a crash when a variable with `#pragma omp allocate` is declared in unreachable code; jumping into its scope is now an error. (#GH140336)
 
 - Fixed `-fopenmp` and `-fopenmp-simd` host compilations dropping diagnostics when no
   offload target was configured, which accepted `try`/`throw` with exceptions disabled

>From d2db3c9434ec8e564db96b6f74cb61872ca0b9c0 Mon Sep 17 00:00:00 2001
From: Akash Manna <akash.manna.mymail at gmail.com>
Date: Sat, 14 Nov 2026 19:06:45 +0530
Subject: [PATCH 3/4] [Clang][OpenMP] Check the insertion point before the
 attribute lookup

---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp | 6 +++---
 clang/lib/CodeGen/CGStmtOpenMP.cpp    | 6 ++----
 2 files changed, 5 insertions(+), 7 deletions(-)

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 591f1e8bcd2bec..d85b20926e7580 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -12794,14 +12794,14 @@ Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
       UntiedRealAddr = I->second.second;
     }
   }
+  // Unreachable declaration: nothing can run the allocation.
+  if (!CGF.HaveInsertPoint())
+    return UntiedRealAddr.isValid() ? UntiedRealAddr : UntiedAddr;
   const VarDecl *CVD = VD->getCanonicalDecl();
   if (CVD->hasAttr<OMPAllocateDeclAttr>()) {
     // Use the default allocation.
     if (!isAllocatableDecl(VD))
       return UntiedAddr;
-    // Unreachable declaration: nothing can run the allocation.
-    if (!CGF.HaveInsertPoint())
-      return UntiedRealAddr.isValid() ? UntiedRealAddr : Address::invalid();
     llvm::Value *Size;
     CharUnits Align = CGM.getContext().getDeclAlign(CVD);
     if (CVD->getType()->isVariablyModifiedType()) {
diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index 97b845d6c6ab8d..d38300acb589ba 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -2197,14 +2197,12 @@ Address CodeGenFunction::OMPBuilderCBHelpers::getAddressOfLocalVariable(
   CodeGenModule &CGM = CGF.CGM;
   auto &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
 
-  if (!VD)
+  // Unreachable declaration: nothing can run the allocation.
+  if (!VD || !CGF.HaveInsertPoint())
     return Address::invalid();
   const VarDecl *CVD = VD->getCanonicalDecl();
   if (!isAllocatableDecl(CVD))
     return Address::invalid();
-  // Unreachable declaration: nothing can run the allocation.
-  if (!CGF.HaveInsertPoint())
-    return Address::invalid();
   llvm::Value *Size;
   CharUnits Align = CGM.getContext().getDeclAlign(CVD);
   if (CVD->getType()->isVariablyModifiedType()) {

>From ce7a43c9b1f01f1c7fc2c9fc3866c4bedeb622c0 Mon Sep 17 00:00:00 2001
From: Akash Manna <akash.manna.mymail at gmail.com>
Date: Mon, 16 Nov 2026 12:08:37 +0530
Subject: [PATCH 4/4] [Clang][OpenMP] Set the branch-protected scope flag for
 omp allocate locals

---
 clang/lib/Sema/SemaOpenMP.cpp           | 3 +++
 clang/test/OpenMP/allocate_messages.cpp | 3 +++
 2 files changed, 6 insertions(+)

diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index 257ee6e4d03898..782a2134445680 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -3767,6 +3767,9 @@ SemaOpenMP::DeclGroupPtrTy SemaOpenMP::ActOnOpenMPAllocateDirective(
     Vars.push_back(RefExpr);
     applyOMPAllocateAttribute(SemaRef, VD, AllocatorKind, Allocator, Alignment,
                               DE->getSourceRange());
+    // A jump over the allocation must be diagnosed, as for cleanup variables.
+    if (VD->hasLocalStorage())
+      SemaRef.setFunctionHasBranchProtectedScope();
   }
   if (Vars.empty())
     return nullptr;
diff --git a/clang/test/OpenMP/allocate_messages.cpp b/clang/test/OpenMP/allocate_messages.cpp
index ecda3aca98a424..f0b50e7f075cf1 100644
--- a/clang/test/OpenMP/allocate_messages.cpp
+++ b/clang/test/OpenMP/allocate_messages.cpp
@@ -163,6 +163,9 @@ void gh140336(int i) {
 #pragma omp allocate(k)
 label2:
   k = 4;
+}
+
+void gh140336_indirect() {
   void *p = &&label3;
   {
     int l; // expected-note {{jump exits scope of variable with '#pragma omp allocate'}}



More information about the cfe-commits mailing list