[clang] [Clang][OpenMP] Emit device kernels for target regions in lambdas without an enclosing function (PR #240840)

Akash Manna via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 12 06:54:57 PST 2026


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

>From 254dc40e57086ee587183ee51e80f3ddab64f8d5 Mon Sep 17 00:00:00 2001
From: Akash Manna <akash.manna.mymail at gmail.com>
Date: Tue, 10 Nov 2026 11:10:59 +0530
Subject: [PATCH 1/5] [clang][OpenMP] Emit device kernels for target regions in
 lambdas without an enclosing function

Fixes #136652

A `target` region in a lambda at namespace scope no longer crashes the host after #226691, but with offloading the device still emitted no kernel for it. The device finds target regions by scanning function bodies, and a lambda in a global initializer, a default argument or a default member initializer is reached from none of them. The host registers the entry, the device image has nothing behind it.

The device scan now walks those initializers and names a region the way the host does: after the enclosing non-closure function, or after the call operator itself when there is none, through one helper shared by both sides.

AI Aided!
---
 clang/docs/ReleaseNotes.md                    |  2 +-
 clang/lib/CodeGen/CGOpenMPRuntime.cpp         | 84 +++++++++++++++----
 clang/lib/CodeGen/CGOpenMPRuntime.h           |  8 ++
 clang/lib/CodeGen/CGStmtOpenMP.cpp            | 18 ++--
 ...bal_ref_namespace_scope_lambda_codegen.cpp | 80 ++++++++++++++++--
 5 files changed, 155 insertions(+), 37 deletions(-)

diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 6d1dbbbb6eb77..f0b289f8fa5dc 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -807,7 +807,7 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
   (such as `std::map`) whose mapper lookup instantiates a class template specialization. (#GH154704)
 - Fixed a bug where repeated #imports of modular headers in non-modular compilation were translated to #pragma clang module import. (#GH216924)
 - Fixed an assertion when `#pragma omp declare simd` or `#pragma omp declare variant` is followed by another OpenMP declarative directive containing a qualified identifier. (#GH217204)
-- Fixed crashes on an OpenMP `target` region inside a lambda or block at namespace scope, including when the region used a global reference. (#GH223397)
+- Fixed crashes on an OpenMP `target` region inside a lambda or block at namespace scope, including when the region used a global reference; such a region in a lambda is now also emitted for the offloading device. (#GH223397, #GH136652)
 - Fixed a crash when an `asm` label names the register for a global variable of incomplete type. (#GH219746)
 - Fixed a crash when a local register variable bound to a pseudo or status register by an `asm` label,
   such as `register long double t __asm("17");` (the flags register), was used as an inline asm operand.
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index d3a6ffee3ea74..e362edba7f423 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -6482,6 +6482,15 @@ void CGOpenMPRuntime::emitHostKernelEnvironment(const OMPExecutableDirective &D,
   OMPBuilder.emitKernelEnvironment(CGF.Builder, Attrs);
 }
 
+StringRef
+CGOpenMPRuntime::getTargetRegionParentName(const FunctionDecl *FD) const {
+  if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD))
+    return CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
+  if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(FD))
+    return CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
+  return CGM.getMangledName(GlobalDecl(FD));
+}
+
 void CGOpenMPRuntime::emitTargetOutlinedFunction(
     const OMPExecutableDirective &D, StringRef ParentName,
     llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
@@ -11578,15 +11587,54 @@ void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
     return;
   }
 
-  // If this is a lambda function, look into its body.
-  if (const auto *L = dyn_cast<LambdaExpr>(S))
+  // Default arguments and member initializers are not children of their uses.
+  if (const auto *E = dyn_cast<CXXDefaultArgExpr>(S)) {
+    scanForTargetRegionsFunctions(E->getExpr(), ParentName);
+    return;
+  }
+  if (const auto *E = dyn_cast<CXXDefaultInitExpr>(S)) {
+    scanForTargetRegionsFunctions(E->getExpr(), ParentName);
+    return;
+  }
+
+  // An implicitly-defined constructor is only reachable from its uses.
+  if (const auto *E = dyn_cast<CXXConstructExpr>(S)) {
+    const CXXConstructorDecl *Ctor = E->getConstructor();
+    if (!Ctor->isUserProvided())
+      scanConstructorForTargetRegions(Ctor, ParentName);
+  }
+
+  // Regions in a lambda are named after its enclosing non-closure function
+  // (CurFuncDecl) or, when there is none, after the call operator itself.
+  if (const auto *L = dyn_cast<LambdaExpr>(S)) {
+    CXXMethodDecl *CallOp = L->getCallOperator();
+    if (const auto *Parent =
+            dyn_cast_or_null<FunctionDecl>(CallOp->getNonClosureContext())) {
+      ParentName = getTargetRegionParentName(Parent);
+    } else {
+      // Specializations of a generic lambda are scanned as top-level decls.
+      if (CallOp->isTemplated())
+        return;
+      ParentName = CGM.getMangledName(GlobalDecl(CallOp));
+    }
     S = L->getBody();
+  }
 
   // Keep looking for target regions recursively.
   for (const Stmt *II : S->children())
     scanForTargetRegionsFunctions(II, ParentName);
 }
 
+void CGOpenMPRuntime::scanConstructorForTargetRegions(
+    const CXXConstructorDecl *Ctor, StringRef ParentName) {
+  const auto *Def = dyn_cast_or_null<CXXConstructorDecl>(Ctor->getDefinition());
+  if (!Def)
+    return;
+  for (const CXXCtorInitializer *Init : Def->inits())
+    scanForTargetRegionsFunctions(Init->getInit(), ParentName);
+  scanForTargetRegionsFunctions(Def->getBody(), ParentName);
+}
+
 static bool isAssumedToBeNotEmitted(const ValueDecl *VD, bool IsDevice) {
   std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
       OMPDeclareTargetDeclAttr::getDeviceType(VD);
@@ -11616,7 +11664,10 @@ bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
   // Try to detect target regions in the function.
   if (const auto *FD = dyn_cast<FunctionDecl>(VD)) {
     StringRef Name = CGM.getMangledName(GD);
-    scanForTargetRegionsFunctions(FD->getBody(), Name);
+    if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD))
+      scanConstructorForTargetRegions(Ctor, Name);
+    else
+      scanForTargetRegionsFunctions(FD->getBody(), Name);
     if (isAssumedToBeNotEmitted(cast<ValueDecl>(FD),
                                 CGM.getLangOpts().OpenMPIsTargetDevice))
       return true;
@@ -11638,29 +11689,28 @@ bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
   // Check if there are Ctors/Dtors in this declaration and look for target
   // regions in it. We use the complete variant to produce the kernel name
   // mangling.
-  QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
+  const auto *VD = cast<VarDecl>(GD.getDecl());
+  QualType RDTy = VD->getType();
   if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
-    for (const CXXConstructorDecl *Ctor : RD->ctors()) {
-      StringRef ParentName =
-          CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
-      scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
-    }
-    if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
-      StringRef ParentName =
-          CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
-      scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
-    }
+    for (const CXXConstructorDecl *Ctor : RD->ctors())
+      scanConstructorForTargetRegions(Ctor, getTargetRegionParentName(Ctor));
+    if (const CXXDestructorDecl *Dtor = RD->getDestructor())
+      scanForTargetRegionsFunctions(Dtor->getBody(),
+                                    getTargetRegionParentName(Dtor));
   }
 
+  // Lambdas in the initializer are reached from nowhere else.
+  if (const Expr *Init = VD->getInit())
+    scanForTargetRegionsFunctions(Init, CGM.getMangledName(GD));
+
   // Do not emit variable if it is not marked as declare target.
   std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
-      OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
-          cast<VarDecl>(GD.getDecl()));
+      OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
   if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link ||
       ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
         *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
        HasRequiresUnifiedSharedMemory)) {
-    DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
+    DeferredGlobalVariables.insert(VD);
     return true;
   }
   return false;
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.h b/clang/lib/CodeGen/CGOpenMPRuntime.h
index ae55295cadc14..dcca166d4e887 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.h
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.h
@@ -523,6 +523,10 @@ class CGOpenMPRuntime {
   /// \param ParentName Name of the function declaration that is being scanned.
   void scanForTargetRegionsFunctions(const Stmt *S, StringRef ParentName);
 
+  /// Scans the mem-initializers and the body of \a Ctor for target regions.
+  void scanConstructorForTargetRegions(const CXXConstructorDecl *Ctor,
+                                       StringRef ParentName);
+
   /// Build type kmp_routine_entry_t (if not built yet).
   void emitKmpRoutineEntryT(QualType KmpInt32Ty);
 
@@ -1419,6 +1423,10 @@ class CGOpenMPRuntime {
                                           bool IsOffloadEntry,
                                           const RegionCodeGenTy &CodeGen);
 
+  /// Returns the parent name of the target regions in \a FD; constructors and
+  /// destructors use their complete variant.
+  StringRef getTargetRegionParentName(const FunctionDecl *FD) const;
+
   /// Emit the target offloading code associated with \a D. The emitted
   /// code attempts offloading the execution to the device, an the event of
   /// a failure it executes the host version outlined in \a OutlinedFn.
diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index e63957df3e406..68191a4030f35 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -7551,19 +7551,11 @@ static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
     CGM.getDiags().Report(diag::err_missing_mandatory_offloading);
   }
 
-  StringRef ParentName;
-  // In case we have Ctors/Dtors we use the complete type variant to produce
-  // the mangling of the device outlined kernel. Lambdas and blocks at
-  // namespace scope have no parent function.
-  if (!CGF.CurFuncDecl)
-    ParentName = CGF.CurFn->getName();
-  else if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
-    ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
-  else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
-    ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
-  else
-    ParentName =
-        CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
+  // Lambdas and blocks at namespace scope have no parent function.
+  StringRef ParentName = CGF.CurFuncDecl
+                             ? CGM.getOpenMPRuntime().getTargetRegionParentName(
+                                   cast<FunctionDecl>(CGF.CurFuncDecl))
+                             : CGF.CurFn->getName();
 
   // Emit target region as a standalone region.
   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
diff --git a/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp b/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
index 3ac1f55ca7a96..b441a92470435 100644
--- a/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
+++ b/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
@@ -1,40 +1,49 @@
 // RUN: %clang_cc1 -verify -fopenmp -fblocks -triple x86_64-unknown-linux-gnu -emit-llvm %s -o - | FileCheck %s
 // RUN: %clang_cc1 -verify -fopenmp-simd -fblocks -triple x86_64-unknown-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix=SIMD-ONLY
+// RUN: %clang_cc1 -verify -fopenmp -fblocks -triple x86_64-unknown-linux-gnu -fopenmp-targets=x86_64-unknown-linux-gnu -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -verify -fopenmp -fblocks -triple x86_64-unknown-linux-gnu -fopenmp-targets=x86_64-unknown-linux-gnu -emit-llvm-bc %s -o %t-host.bc
+// RUN: %clang_cc1 -verify -fopenmp -fblocks -triple x86_64-unknown-linux-gnu -emit-llvm %s -fopenmp-is-target-device -fopenmp-host-ir-file-path %t-host.bc -o - | FileCheck %s --check-prefix=DEVICE
 // expected-no-diagnostics
 
 // Target regions inside lambdas and blocks at namespace scope have no parent
 // function declaration, so they are named after the function being emitted.
+// The device compilation finds such lambdas through the declarations holding them.
 
 int x;
 int &ref = x;
 
 auto lambda = []() {
-// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
+// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+2]]{{"?}}(
+// DEVICE-DAG: define weak_odr protected void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
 #pragma omp target
   ref = 42;
 };
 
 auto nested_lambda = []() {
   return []() {
-// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
+// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+2]]{{"?}}(
+// DEVICE-DAG: define weak_odr protected void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
 #pragma omp target
     ref = 42;
   };
 };
 
 auto combined_directive = []() {
-// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
+// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+2]]{{"?}}(
+// DEVICE-DAG: define weak_odr protected void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
 #pragma omp target teams
   ref = 42;
 };
 
 auto static_local = []() {
   static int &local_ref = x;
-// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
+// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+2]]{{"?}}(
+// DEVICE-DAG: define weak_odr protected void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
 #pragma omp target
   local_ref = 42;
 };
 
+// The body of a block is not scanned for the device.
 void (^block)() = ^{
 // CHECK-DAG: define internal void @__omp_offloading_{{.*}}_block_block_invoke_l[[#@LINE+1]](
 #pragma omp target
@@ -42,26 +51,85 @@ void (^block)() = ^{
 };
 
 void default_argument(int = []() {
-// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
+// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+2]]{{"?}}(
+// DEVICE-DAG: define weak_odr protected void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
 #pragma omp target
   ref = 42;
   return 0;
 }());
 
 template <int N> int variable_template = []() {
-// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
+// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+2]]{{"?}}(
+// DEVICE-DAG: define weak_odr protected void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
 #pragma omp target
   ref = N;
   return 0;
 }();
 int instantiation = variable_template<1>;
 
+// Reproducer from GH136652.
+auto slice_work = [](__SIZE_TYPE__ device, float start, float end) {
+// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEmff_l[[#@LINE+2]]{{"?}}(
+// DEVICE-DAG: define weak_odr protected void @{{"?}}__omp_offloading_{{.*}}clEmff_l[[#@LINE+1]]{{"?}}(
+#pragma omp target teams device(device)
+  {
+  }
+};
+
+struct GlobalObject {
+  int member = [](int d) {
+// CHECK-DAG: define internal void @__omp_offloading_{{.*}}_ZNK12GlobalObject6memberMUliE_clEi_l[[#@LINE+2]](
+// DEVICE-DAG: define weak_odr protected void @__omp_offloading_{{.*}}_ZNK12GlobalObject6memberMUliE_clEi_l[[#@LINE+1]](
+#pragma omp target teams device(d)
+    {
+    }
+    return d;
+  }(0);
+};
+GlobalObject global_object;
+
+struct LocalObject {
+  int member = [](int d) {
+// CHECK-DAG: define internal void @__omp_offloading_{{.*}}_ZNK11LocalObject6memberMUliE_clEi_l[[#@LINE+2]](
+// DEVICE-DAG: define weak_odr protected void @__omp_offloading_{{.*}}_ZNK11LocalObject6memberMUliE_clEi_l[[#@LINE+1]](
+#pragma omp target teams device(d)
+    {
+    }
+    return d;
+  }(0);
+};
+
+template <class T> struct Holder {
+  static inline auto member = [](T d) {
+// CHECK-DAG: define internal void @__omp_offloading_{{.*}}_ZNK6HolderIiE6memberMUliE_clEi_l[[#@LINE+2]](
+// DEVICE-DAG: define weak_odr protected void @__omp_offloading_{{.*}}_ZNK6HolderIiE6memberMUliE_clEi_l[[#@LINE+1]](
+#pragma omp target teams device(d)
+    {
+    }
+  };
+};
+
+// Closures without a mangling number are named $_N in first-mangling order; the
+// device names those in initializers before any default argument. Keep this order.
 void use() {
   lambda();
   nested_lambda()();
   combined_directive();
   static_local();
+  slice_work(0, 0, 0);
   default_argument();
+  LocalObject local_object;
+  (void)local_object;
+  Holder<int>::member(0);
+  // Control: named after the enclosing function.
+  static auto static_local_lambda = [](__SIZE_TYPE__ device) {
+// CHECK-DAG: define internal void @__omp_offloading_{{.*}}_Z3usev_l[[#@LINE+2]](
+// DEVICE-DAG: define weak_odr protected void @__omp_offloading_{{.*}}_Z3usev_l[[#@LINE+1]](
+#pragma omp target teams device(device)
+    {
+    }
+  };
+  static_local_lambda(0);
 }
 
 // SIMD-ONLY-NOT: {{__kmpc|__tgt}}

>From 1d7ae7d13e6e1d6304e700f3890f6c503677b968 Mon Sep 17 00:00:00 2001
From: Akash Manna <akash.manna.mymail at gmail.com>
Date: Tue, 10 Nov 2026 23:18:45 +0530
Subject: [PATCH 2/5] [clang][OpenMP] Number namespace-scope closures under
 offloading and scan implicit constructors once

Lambdas with no enclosing function get a mangling number when offloading, so host and device name their target regions identically. Each implicitly-defined constructor is scanned for default member initializers only once.
---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp                     | 2 +-
 clang/lib/CodeGen/CGOpenMPRuntime.h                       | 3 +++
 clang/lib/Sema/SemaLambda.cpp                             | 8 +++++++-
 .../target_global_ref_namespace_scope_lambda_codegen.cpp  | 6 ++----
 4 files changed, 13 insertions(+), 6 deletions(-)

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index e362edba7f423..27dcb8011a3bd 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -11600,7 +11600,7 @@ void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
   // An implicitly-defined constructor is only reachable from its uses.
   if (const auto *E = dyn_cast<CXXConstructExpr>(S)) {
     const CXXConstructorDecl *Ctor = E->getConstructor();
-    if (!Ctor->isUserProvided())
+    if (!Ctor->isUserProvided() && ScannedImplicitCtors.insert(Ctor).second)
       scanConstructorForTargetRegions(Ctor, ParentName);
   }
 
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.h b/clang/lib/CodeGen/CGOpenMPRuntime.h
index dcca166d4e887..3742e3cd68680 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.h
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.h
@@ -480,6 +480,9 @@ class CGOpenMPRuntime {
   bool ShouldMarkAsGlobal = true;
   /// List of the emitted declarations.
   llvm::DenseSet<CanonicalDeclPtr<const Decl>> AlreadyEmittedTargetDecls;
+  /// Implicitly-defined constructors already scanned for target regions; only
+  /// lambdas can hold such regions there and they compute their own parent.
+  llvm::SmallPtrSet<const CXXConstructorDecl *, 8> ScannedImplicitCtors;
   /// List of the global variables with their addresses that should not be
   /// emitted for the target.
   llvm::StringMap<llvm::WeakTrackingVH> EmittedNonTargetVariables;
diff --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp
index 2a74f59a1d383..585122d43c489 100644
--- a/clang/lib/Sema/SemaLambda.cpp
+++ b/clang/lib/Sema/SemaLambda.cpp
@@ -518,8 +518,12 @@ void Sema::handleLambdaNumbering(
     Class->setLambdaContextDecl(ContextDecl);
 
   CXXRecordDecl::LambdaNumbering Numbering;
+  bool IsOpenMPOffload = getLangOpts().OpenMPIsTargetDevice ||
+                         !getLangOpts().OMPTargetTriples.empty();
   if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
-                getLangOpts().SYCLIsHost)) {
+                getLangOpts().SYCLIsHost ||
+                (IsOpenMPOffload &&
+                 !Class->getDeclContext()->getNonClosureAncestor()))) {
     // Force lambda numbering in CUDA/HIP as we need to name lambdas following
     // ODR. Both device- and host-compilation need to have a consistent naming
     // on kernel functions. As lambdas are potential part of these `__global__`
@@ -527,6 +531,8 @@ void Sema::handleLambdaNumbering(
     // Also force for SYCL, since we need this for the
     // __builtin_sycl_unique_stable_name implementation, which depends on lambda
     // mangling.
+    // Also force for OpenMP offloading outside of functions, where target
+    // regions are named after the closure on both host and device.
     MCtx = getMangleNumberingContext(Class, ContextDecl);
     assert(MCtx && "Retrieving mangle numbering context failed!");
     Numbering.HasKnownInternalLinkage = true;
diff --git a/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp b/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
index b441a92470435..a13aa139e08c7 100644
--- a/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
+++ b/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
@@ -70,7 +70,7 @@ int instantiation = variable_template<1>;
 // Reproducer from GH136652.
 auto slice_work = [](__SIZE_TYPE__ device, float start, float end) {
 // CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEmff_l[[#@LINE+2]]{{"?}}(
-// DEVICE-DAG: define weak_odr protected void @{{"?}}__omp_offloading_{{.*}}clEmff_l[[#@LINE+1]]{{"?}}(
+// DEVICE-DAG: define weak_odr protected void @__omp_offloading_{{.*}}_ZNKUlmffE_clEmff_l[[#@LINE+1]](
 #pragma omp target teams device(device)
   {
   }
@@ -109,15 +109,13 @@ template <class T> struct Holder {
   };
 };
 
-// Closures without a mangling number are named $_N in first-mangling order; the
-// device names those in initializers before any default argument. Keep this order.
 void use() {
   lambda();
   nested_lambda()();
   combined_directive();
   static_local();
-  slice_work(0, 0, 0);
   default_argument();
+  slice_work(0, 0, 0);
   LocalObject local_object;
   (void)local_object;
   Holder<int>::member(0);

>From ecde87b24b7a7d53284b44d9799c011e98988c58 Mon Sep 17 00:00:00 2001
From: Akash Manna <akash.manna.mymail at gmail.com>
Date: Wed, 11 Nov 2026 09:12:06 +0530
Subject: [PATCH 3/5] [clang][OpenMP] Name regions in constructs outlined from
 a namespace-scope lambda after its call operator

The host named such a region after the outlined function while the device used the call operator. Also skip implicit constructors without a body in the device scan.
---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp             |  5 +++--
 clang/lib/CodeGen/CGStmtOpenMP.cpp                | 15 ++++++++++-----
 clang/lib/Sema/SemaLambda.cpp                     |  6 +++---
 ..._global_ref_namespace_scope_lambda_codegen.cpp | 11 +++++++++++
 4 files changed, 27 insertions(+), 10 deletions(-)

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 27dcb8011a3bd..c16ad13254d82 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -11600,14 +11600,15 @@ void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
   // An implicitly-defined constructor is only reachable from its uses.
   if (const auto *E = dyn_cast<CXXConstructExpr>(S)) {
     const CXXConstructorDecl *Ctor = E->getConstructor();
-    if (!Ctor->isUserProvided() && ScannedImplicitCtors.insert(Ctor).second)
+    if (!Ctor->isUserProvided() && Ctor->hasBody() &&
+        ScannedImplicitCtors.insert(Ctor).second)
       scanConstructorForTargetRegions(Ctor, ParentName);
   }
 
   // Regions in a lambda are named after its enclosing non-closure function
   // (CurFuncDecl) or, when there is none, after the call operator itself.
   if (const auto *L = dyn_cast<LambdaExpr>(S)) {
-    CXXMethodDecl *CallOp = L->getCallOperator();
+    const CXXMethodDecl *CallOp = L->getCallOperator();
     if (const auto *Parent =
             dyn_cast_or_null<FunctionDecl>(CallOp->getNonClosureContext())) {
       ParentName = getTargetRegionParentName(Parent);
diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index 68191a4030f35..1a8e30f0cf1c8 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -7551,11 +7551,16 @@ static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
     CGM.getDiags().Report(diag::err_missing_mandatory_offloading);
   }
 
-  // Lambdas and blocks at namespace scope have no parent function.
-  StringRef ParentName = CGF.CurFuncDecl
-                             ? CGM.getOpenMPRuntime().getTargetRegionParentName(
-                                   cast<FunctionDecl>(CGF.CurFuncDecl))
-                             : CGF.CurFn->getName();
+  // Lambdas and blocks at namespace scope have no parent function. Regions in
+  // constructs outlined from such a lambda are named after its call operator,
+  // as the device names them.
+  const Decl *CodeDecl = CGF.CurFuncDecl ? CGF.CurFuncDecl : CGF.CurCodeDecl;
+  while (const auto *CD = dyn_cast_or_null<CapturedDecl>(CodeDecl))
+    CodeDecl = Decl::castFromDeclContext(CD->getParent());
+  const auto *ParentFD = dyn_cast_or_null<FunctionDecl>(CodeDecl);
+  StringRef ParentName =
+      ParentFD ? CGM.getOpenMPRuntime().getTargetRegionParentName(ParentFD)
+               : CGF.CurFn->getName();
 
   // Emit target region as a standalone region.
   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
diff --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp
index 585122d43c489..970591d480111 100644
--- a/clang/lib/Sema/SemaLambda.cpp
+++ b/clang/lib/Sema/SemaLambda.cpp
@@ -518,11 +518,11 @@ void Sema::handleLambdaNumbering(
     Class->setLambdaContextDecl(ContextDecl);
 
   CXXRecordDecl::LambdaNumbering Numbering;
-  bool IsOpenMPOffload = getLangOpts().OpenMPIsTargetDevice ||
-                         !getLangOpts().OMPTargetTriples.empty();
   if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
                 getLangOpts().SYCLIsHost ||
-                (IsOpenMPOffload &&
+                (getLangOpts().OpenMP &&
+                 (getLangOpts().OpenMPIsTargetDevice ||
+                  !getLangOpts().OMPTargetTriples.empty()) &&
                  !Class->getDeclContext()->getNonClosureAncestor()))) {
     // Force lambda numbering in CUDA/HIP as we need to name lambdas following
     // ODR. Both device- and host-compilation need to have a consistent naming
diff --git a/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp b/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
index a13aa139e08c7..6ce233635faad 100644
--- a/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
+++ b/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
@@ -35,6 +35,16 @@ auto combined_directive = []() {
   ref = 42;
 };
 
+auto nested_in_parallel = []() {
+#pragma omp parallel
+  {
+// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+2]]{{"?}}(
+// DEVICE-DAG: define weak_odr protected void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
+#pragma omp target
+    ref = 42;
+  }
+};
+
 auto static_local = []() {
   static int &local_ref = x;
 // CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+2]]{{"?}}(
@@ -113,6 +123,7 @@ void use() {
   lambda();
   nested_lambda()();
   combined_directive();
+  nested_in_parallel();
   static_local();
   default_argument();
   slice_work(0, 0, 0);

>From 00149e05f63f5b4efaad7bf68fd5fec339641a24 Mon Sep 17 00:00:00 2001
From: Akash Manna <akash.manna.mymail at gmail.com>
Date: Thu, 12 Nov 2026 09:36:59 +0530
Subject: [PATCH 4/5] [clang][OpenMP] Name regions in constructors by the
 complete variant in the device scan

A constructor of an abstract class is emitted only as its base variant, so the device scanned it under the C2 name while the host registers C1.
---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp             |  2 +-
 ..._global_ref_namespace_scope_lambda_codegen.cpp | 15 +++++++++++++++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index c16ad13254d82..83870e0631daf 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -11664,7 +11664,7 @@ bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
   const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
   // Try to detect target regions in the function.
   if (const auto *FD = dyn_cast<FunctionDecl>(VD)) {
-    StringRef Name = CGM.getMangledName(GD);
+    StringRef Name = getTargetRegionParentName(FD);
     if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD))
       scanConstructorForTargetRegions(Ctor, Name);
     else
diff --git a/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp b/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
index 6ce233635faad..bad35c0a526cf 100644
--- a/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
+++ b/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
@@ -119,6 +119,19 @@ template <class T> struct Holder {
   };
 };
 
+struct AbstractBase {
+  AbstractBase() {
+// CHECK-DAG: define internal void @__omp_offloading_{{.*}}_ZN12AbstractBaseC1Ev_l[[#@LINE+2]](
+// DEVICE-DAG: define weak_odr protected void @__omp_offloading_{{.*}}_ZN12AbstractBaseC1Ev_l[[#@LINE+1]](
+#pragma omp target
+    ref = 42;
+  }
+  virtual void f() = 0;
+};
+struct Derived : AbstractBase {
+  void f() override {}
+};
+
 void use() {
   lambda();
   nested_lambda()();
@@ -130,6 +143,8 @@ void use() {
   LocalObject local_object;
   (void)local_object;
   Holder<int>::member(0);
+  Derived derived;
+  (void)derived;
   // Control: named after the enclosing function.
   static auto static_local_lambda = [](__SIZE_TYPE__ device) {
 // CHECK-DAG: define internal void @__omp_offloading_{{.*}}_Z3usev_l[[#@LINE+2]](

>From 1f64fe76706e0f8027ec947d2eca6cc1f620ba2c Mon Sep 17 00:00:00 2001
From: Akash Manna <akash.manna.mymail at gmail.com>
Date: Thu, 12 Nov 2026 20:23:59 +0530
Subject: [PATCH 5/5] [clang][OpenMP] Scan inheriting constructors and
 host-only variables on the device, resolve closures in the parent-name helper

Default member initializers run by an inheriting constructor and lambdas in the initializer of a `device_type`(host) variable were not scanned for target regions. The parent-name helper now maps a closure to its enclosing non-closure function, so the device scan and the host share the whole rule.
---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp         | 47 ++++++++++---------
 clang/lib/CodeGen/CGOpenMPRuntime.h           |  5 +-
 ...bal_ref_namespace_scope_lambda_codegen.cpp | 28 +++++++++++
 3 files changed, 55 insertions(+), 25 deletions(-)

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 83870e0631daf..6a45938047998 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -6484,6 +6484,11 @@ void CGOpenMPRuntime::emitHostKernelEnvironment(const OMPExecutableDirective &D,
 
 StringRef
 CGOpenMPRuntime::getTargetRegionParentName(const FunctionDecl *FD) const {
+  // Regions in a closure are named after its enclosing non-closure function
+  // (CodeGenFunction::CurFuncDecl), if there is one.
+  if (const auto *Parent =
+          dyn_cast_or_null<FunctionDecl>(FD->getNonClosureContext()))
+    FD = Parent;
   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD))
     return CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(FD))
@@ -11597,27 +11602,23 @@ void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
     return;
   }
 
-  // An implicitly-defined constructor is only reachable from its uses.
-  if (const auto *E = dyn_cast<CXXConstructExpr>(S)) {
-    const CXXConstructorDecl *Ctor = E->getConstructor();
-    if (!Ctor->isUserProvided() && Ctor->hasBody() &&
-        ScannedImplicitCtors.insert(Ctor).second)
-      scanConstructorForTargetRegions(Ctor, ParentName);
-  }
+  // Implicit and inheriting constructors are only reachable from their uses.
+  const CXXConstructorDecl *Ctor = nullptr;
+  if (const auto *E = dyn_cast<CXXConstructExpr>(S))
+    Ctor = E->getConstructor();
+  else if (const auto *E = dyn_cast<CXXInheritedCtorInitExpr>(S))
+    Ctor = E->getConstructor();
+  if (Ctor && (!Ctor->isUserProvided() || Ctor->isInheritingConstructor()) &&
+      Ctor->hasBody() && ScannedImplicitCtors.insert(Ctor).second)
+    scanConstructorForTargetRegions(Ctor, ParentName);
 
-  // Regions in a lambda are named after its enclosing non-closure function
-  // (CurFuncDecl) or, when there is none, after the call operator itself.
+  // If this is a lambda function, look into its body.
   if (const auto *L = dyn_cast<LambdaExpr>(S)) {
     const CXXMethodDecl *CallOp = L->getCallOperator();
-    if (const auto *Parent =
-            dyn_cast_or_null<FunctionDecl>(CallOp->getNonClosureContext())) {
-      ParentName = getTargetRegionParentName(Parent);
-    } else {
-      // Specializations of a generic lambda are scanned as top-level decls.
-      if (CallOp->isTemplated())
-        return;
-      ParentName = CGM.getMangledName(GlobalDecl(CallOp));
-    }
+    // Specializations of a generic lambda are scanned as top-level decls.
+    if (CallOp->isTemplated())
+      return;
+    ParentName = getTargetRegionParentName(CallOp);
     S = L->getBody();
   }
 
@@ -11680,12 +11681,9 @@ bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
 }
 
 bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
-  if (isAssumedToBeNotEmitted(cast<ValueDecl>(GD.getDecl()),
-                              CGM.getLangOpts().OpenMPIsTargetDevice))
-    return true;
-
   if (!CGM.getLangOpts().OpenMPIsTargetDevice)
-    return false;
+    return isAssumedToBeNotEmitted(cast<ValueDecl>(GD.getDecl()),
+                                   /*IsDevice=*/false);
 
   // Check if there are Ctors/Dtors in this declaration and look for target
   // regions in it. We use the complete variant to produce the kernel name
@@ -11704,6 +11702,9 @@ bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
   if (const Expr *Init = VD->getInit())
     scanForTargetRegionsFunctions(Init, CGM.getMangledName(GD));
 
+  if (isAssumedToBeNotEmitted(VD, /*IsDevice=*/true))
+    return true;
+
   // Do not emit variable if it is not marked as declare target.
   std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.h b/clang/lib/CodeGen/CGOpenMPRuntime.h
index 3742e3cd68680..47c05d62a3b41 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.h
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.h
@@ -1426,8 +1426,9 @@ class CGOpenMPRuntime {
                                           bool IsOffloadEntry,
                                           const RegionCodeGenTy &CodeGen);
 
-  /// Returns the parent name of the target regions in \a FD; constructors and
-  /// destructors use their complete variant.
+  /// Returns the parent name of the target regions in \a FD: its enclosing
+  /// non-closure function if \a FD is a closure, otherwise \a FD itself;
+  /// constructors and destructors use their complete variant.
   StringRef getTargetRegionParentName(const FunctionDecl *FD) const;
 
   /// Emit the target offloading code associated with \a D. The emitted
diff --git a/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp b/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
index bad35c0a526cf..b9baeea8dc1cf 100644
--- a/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
+++ b/clang/test/OpenMP/target_global_ref_namespace_scope_lambda_codegen.cpp
@@ -77,6 +77,16 @@ template <int N> int variable_template = []() {
 }();
 int instantiation = variable_template<1>;
 
+#pragma omp begin declare target device_type(host)
+auto host_only = []() {
+  int v = 0;
+// CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+2]]{{"?}}(
+// DEVICE-DAG: define weak_odr protected void @{{"?}}__omp_offloading_{{.*}}clEv_l[[#@LINE+1]]{{"?}}(
+#pragma omp target
+  v = 42;
+};
+#pragma omp end declare target
+
 // Reproducer from GH136652.
 auto slice_work = [](__SIZE_TYPE__ device, float start, float end) {
 // CHECK-DAG: define internal void @{{"?}}__omp_offloading_{{.*}}clEmff_l[[#@LINE+2]]{{"?}}(
@@ -132,6 +142,21 @@ struct Derived : AbstractBase {
   void f() override {}
 };
 
+struct InheritedBase {
+  InheritedBase(int) {}
+};
+struct Inheriting : InheritedBase {
+  using InheritedBase::InheritedBase;
+  int member = [](int d) {
+// CHECK-DAG: define internal void @__omp_offloading_{{.*}}_ZNK10Inheriting6memberMUliE_clEi_l[[#@LINE+2]](
+// DEVICE-DAG: define weak_odr protected void @__omp_offloading_{{.*}}_ZNK10Inheriting6memberMUliE_clEi_l[[#@LINE+1]](
+#pragma omp target teams device(d)
+    {
+    }
+    return d;
+  }(0);
+};
+
 void use() {
   lambda();
   nested_lambda()();
@@ -139,12 +164,15 @@ void use() {
   nested_in_parallel();
   static_local();
   default_argument();
+  host_only();
   slice_work(0, 0, 0);
   LocalObject local_object;
   (void)local_object;
   Holder<int>::member(0);
   Derived derived;
   (void)derived;
+  Inheriting inheriting(1);
+  (void)inheriting;
   // Control: named after the enclosing function.
   static auto static_local_lambda = [](__SIZE_TYPE__ device) {
 // CHECK-DAG: define internal void @__omp_offloading_{{.*}}_Z3usev_l[[#@LINE+2]](



More information about the cfe-commits mailing list