https://github.com/akash-manna-sky created https://github.com/llvm/llvm-project/pull/240840
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 Assisted! >From 254dc40e57086ee587183ee51e80f3ddab64f8d5 Mon Sep 17 00:00:00 2001 From: Akash Manna <[email protected]> Date: Tue, 10 Nov 2026 11:10:59 +0530 Subject: [PATCH] [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 6d1dbbbb6eb77b..f0b289f8fa5dc4 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 d3a6ffee3ea748..e362edba7f4239 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 ae55295cadc14f..dcca166d4e8872 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 e63957df3e4069..68191a4030f353 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 3ac1f55ca7a960..b441a924704356 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}} _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
