[clang] [OpenMP] Emit the metadirective runtime selection (PR #239292)

Zahira Ammarguellat via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 5 12:54:21 PST 2026


https://github.com/zahiraam updated https://github.com/llvm/llvm-project/pull/239292

>From 20affab97a5f6b7e758675b11ec1f4f045911989 Mon Sep 17 00:00:00 2001
From: Zahira Ammarguellat <zahira.ammarguellat at intel.com>
Date: Thu, 5 Nov 2026 09:00:04 -0800
Subject: [PATCH 1/3] [OpenMP] Emit the metadirective runtime selection

---
 clang/lib/CodeGen/CGStmtOpenMP.cpp            |  54 ++++++-
 .../OpenMP/metadirective_runtime_codegen.cpp  | 138 ++++++++++++++++++
 2 files changed, 190 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/OpenMP/metadirective_runtime_codegen.cpp

diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index b00894c85fd67..e2ecdf7d6f45b 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -2398,8 +2398,58 @@ void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
 }
 
 void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) {
-  // TODO: Select the variant at runtime.
-  EmitStmt(S.variants().front());
+  // Try variants from best to worst match; 'otherwise' runs if none applies.
+  TargetOMPContext OMPCtx(
+      getContext(), /*DiagUnknownTrait=*/[](StringRef) {},
+      /*CurrentFunctionDecl=*/nullptr,
+      /*ConstructTraits=*/{}, /*DeviceNum=*/-1);
+  ArrayRef<Stmt *> Variants = S.variants();
+  ArrayRef<Expr *> Conditions = S.conditions();
+  SmallVector<llvm::omp::VariantMatchInfo, 4> VMIs;
+  SmallVector<unsigned, 4> VariantIdx;
+  const Stmt *Fallback = nullptr;
+  for (auto [I, TI] : llvm::enumerate(S.traitInfos())) {
+    if (TI->Sets.empty()) {
+      Fallback = Variants[I];
+      continue;
+    }
+    llvm::omp::VariantMatchInfo &VMI = VMIs.emplace_back();
+    TI->getAsVariantMatchInfo(getContext(), VMI);
+    // Treat the condition as true here; it is checked at runtime.
+    if (Conditions[I]) {
+      VMI.RequiredTraits.reset(
+          unsigned(llvm::omp::TraitProperty::user_condition_false));
+      VMI.RequiredTraits.set(
+          unsigned(llvm::omp::TraitProperty::user_condition_true));
+    }
+    VariantIdx.push_back(I);
+  }
+
+  llvm::BasicBlock *EndBB = createBasicBlock("omp.metadirective.end");
+  while (!VMIs.empty()) {
+    int Best = llvm::omp::getBestVariantMatchForContext(VMIs, OMPCtx);
+    if (Best < 0)
+      break;
+    unsigned I = VariantIdx[Best];
+    VMIs.erase(VMIs.begin() + Best);
+    VariantIdx.erase(VariantIdx.begin() + Best);
+    // Without a condition the variant always applies; later ones are unused.
+    const Expr *Cond = Conditions[I];
+    if (!Cond) {
+      Fallback = Variants[I];
+      break;
+    }
+    llvm::BasicBlock *WhenBB = createBasicBlock("omp.metadirective.when");
+    llvm::BasicBlock *ElseBB = createBasicBlock("omp.metadirective.else");
+    EmitBranchOnBoolExpr(Cond, WhenBB, ElseBB, /*TrueCount=*/0);
+    EmitBlock(WhenBB);
+    EmitStmt(Variants[I]);
+    EmitBranch(EndBB);
+    EmitBlock(ElseBB);
+  }
+  if (Fallback)
+    EmitStmt(Fallback);
+  EmitBlock(EndBB, /*IsFinished=*/true);
 }
 
 namespace {
diff --git a/clang/test/OpenMP/metadirective_runtime_codegen.cpp b/clang/test/OpenMP/metadirective_runtime_codegen.cpp
new file mode 100644
index 0000000000000..26de70ff9cd27
--- /dev/null
+++ b/clang/test/OpenMP/metadirective_runtime_codegen.cpp
@@ -0,0 +1,138 @@
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=52 \
+// RUN:   -fopenmp-metadirective-runtime-selection -x c++ \
+// RUN:   -triple x86_64-unknown-linux -emit-llvm %s -o - | FileCheck %s
+// expected-no-diagnostics
+
+void bar();
+
+// The condition selects the 'when' variant; otherwise the 'otherwise' variant
+// runs.
+// CHECK-LABEL: define {{.*}}void @_Z14when_otherwisei(
+// CHECK:       [[FLAG:%.*]] = load i32, ptr %flag.addr
+// CHECK-NEXT:  [[COND:%.*]] = icmp ne i32 [[FLAG]], 0
+// CHECK-NEXT:  br i1 [[COND]], label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]]
+// CHECK:       [[WHEN]]:
+// CHECK:       call {{.*}}@__kmpc_fork_call(
+// CHECK:       br label %[[END:omp.metadirective.end[0-9]*]]
+// CHECK:       [[ELSE]]:
+// CHECK:       call i32 @__kmpc_single(
+// CHECK:       br label %[[END]]
+// CHECK:       [[END]]:
+// CHECK-NEXT:  ret void
+void when_otherwise(int flag) {
+#pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single)
+  bar();
+}
+
+// 'when' clauses are tried in order; the first true condition wins.
+// CHECK-LABEL: define {{.*}}void @_Z9two_whensii(
+// CHECK:       [[A:%.*]] = load i32, ptr %a.addr
+// CHECK-NEXT:  [[CONDA:%.*]] = icmp ne i32 [[A]], 0
+// CHECK-NEXT:  br i1 [[CONDA]], label %[[WHEN0:omp.metadirective.when[0-9]*]], label %[[ELSE0:omp.metadirective.else[0-9]*]]
+// CHECK:       [[WHEN0]]:
+// CHECK:       call {{.*}}@__kmpc_fork_call(
+// CHECK:       br label %[[END:omp.metadirective.end[0-9]*]]
+// CHECK:       [[ELSE0]]:
+// CHECK:       [[B:%.*]] = load i32, ptr %b.addr
+// CHECK-NEXT:  [[CONDB:%.*]] = icmp ne i32 [[B]], 0
+// CHECK-NEXT:  br i1 [[CONDB]], label %[[WHEN1:omp.metadirective.when[0-9]*]], label %[[ELSE1:omp.metadirective.else[0-9]*]]
+// CHECK:       [[WHEN1]]:
+// CHECK:       call i32 @__kmpc_single(
+// CHECK:       br label %[[END]]
+// CHECK:       [[ELSE1]]:
+// CHECK-NEXT:  call void @_Z3barv()
+// CHECK-NEXT:  br label %[[END]]
+// CHECK:       [[END]]:
+// CHECK-NEXT:  ret void
+void two_whens(int a, int b) {
+#pragma omp metadirective when(user={condition(a)}: parallel) \
+                          when(user={condition(b)}: single) otherwise()
+  bar();
+}
+
+// Without 'otherwise', the associated statement runs when no condition holds.
+// CHECK-LABEL: define {{.*}}void @_Z12no_otherwisei(
+// CHECK:       br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]]
+// CHECK:       [[WHEN]]:
+// CHECK:       call {{.*}}@__kmpc_fork_call(
+// CHECK:       [[ELSE]]:
+// CHECK-NEXT:  call void @_Z3barv()
+// CHECK-NEXT:  br label %[[END:omp.metadirective.end[0-9]*]]
+// CHECK:       [[END]]:
+// CHECK-NEXT:  ret void
+void no_otherwise(int flag) {
+#pragma omp metadirective when(user={condition(flag)}: parallel)
+  bar();
+}
+
+// vendor(llvm) always matches, so 'parallel' is always selected.
+// CHECK-LABEL: define {{.*}}void @_Z18static_match_firsti(
+// CHECK-NOT:   icmp
+// CHECK:       call {{.*}}@__kmpc_fork_call(
+// CHECK-NOT:   __kmpc_single
+// CHECK:       ret void
+void static_match_first(int flag) {
+#pragma omp metadirective when(implementation={vendor(llvm)}: parallel) \
+                          when(user={condition(flag)}: single) otherwise()
+  bar();
+}
+
+// vendor(amd) never matches, so its variant is not emitted.
+// CHECK-LABEL: define {{.*}}void @_Z14static_nomatchi(
+// CHECK-NOT:   __kmpc_fork_call
+// CHECK:       br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]]
+// CHECK:       [[WHEN]]:
+// CHECK:       call i32 @__kmpc_single(
+// CHECK:       [[ELSE]]:
+// CHECK-NEXT:  call void @_Z3barv()
+// CHECK-NOT:   __kmpc_fork_call
+// CHECK:       ret void
+void static_nomatch(int flag) {
+#pragma omp metadirective when(implementation={vendor(amd)}: parallel) \
+                          when(user={condition(flag)}: single) otherwise()
+  bar();
+}
+
+// vendor(llvm) runs when the condition fails; plain bar() is never called.
+// CHECK-LABEL: define {{.*}}void @_Z17static_match_lasti(
+// CHECK:       br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]]
+// CHECK:       [[WHEN]]:
+// CHECK:       call i32 @__kmpc_single(
+// CHECK:       [[ELSE]]:
+// CHECK-NEXT:  call {{.*}}@__kmpc_fork_call(
+// CHECK-NEXT:  br label %[[END:omp.metadirective.end[0-9]*]]
+// CHECK:       [[END]]:
+// CHECK-NEXT:  ret void
+void static_match_last(int flag) {
+#pragma omp metadirective when(user={condition(flag)}: single) \
+                          when(implementation={vendor(llvm)}: parallel)
+  bar();
+}
+
+// kind(host) scores higher than the condition, so 'parallel' always wins.
+// CHECK-LABEL: define {{.*}}void @_Z18device_kind_secondi(
+// CHECK-NOT:   icmp
+// CHECK:       call {{.*}}@__kmpc_fork_call(
+// CHECK-NOT:   __kmpc_single
+// CHECK:       ret void
+void device_kind_second(int flag) {
+#pragma omp metadirective when(user={condition(flag)}: single) \
+                          when(device={kind(host)}: parallel)
+  bar();
+}
+
+// score(5) makes the second variant the first one tried.
+// CHECK-LABEL: define {{.*}}void @_Z14score_reordersi(
+// CHECK:       br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]]
+// CHECK:       [[WHEN]]:
+// CHECK:       call i32 @__kmpc_single(
+// CHECK:       [[ELSE]]:
+// CHECK-NEXT:  call {{.*}}@__kmpc_fork_call(
+// CHECK-NEXT:  br label %[[END:omp.metadirective.end[0-9]*]]
+// CHECK:       [[END]]:
+// CHECK-NEXT:  ret void
+void score_reorders(int flag) {
+#pragma omp metadirective when(implementation={vendor(llvm)}: parallel) \
+    when(user={condition(flag)}, implementation={vendor(score(5): llvm)}: single)
+  bar();
+}

>From f05ebf1db3a06e2836d3589ce3909f4c192a1b78 Mon Sep 17 00:00:00 2001
From: Zahira Ammarguellat <zahira.ammarguellat at intel.com>
Date: Thu, 5 Nov 2026 09:54:02 -0800
Subject: [PATCH 2/3] match construct selectors

---
 clang/include/clang/AST/StmtOpenMP.h          | 11 ++-
 clang/include/clang/Sema/SemaOpenMP.h         |  3 +
 clang/lib/AST/StmtOpenMP.cpp                  | 11 ++-
 clang/lib/CodeGen/CGStmtOpenMP.cpp            |  3 +-
 clang/lib/Parse/ParseOpenMP.cpp               |  2 +-
 clang/lib/Sema/SemaOpenMP.cpp                 |  6 +-
 clang/lib/Serialization/ASTReaderStmt.cpp     |  4 +
 clang/lib/Serialization/ASTWriterStmt.cpp     |  3 +
 .../metadirective_construct_codegen.cpp       | 29 +++++++
 .../OpenMP/metadirective_runtime_codegen.cpp  | 80 +++++++++++++++++++
 10 files changed, 146 insertions(+), 6 deletions(-)
 create mode 100644 clang/test/OpenMP/metadirective_construct_codegen.cpp

diff --git a/clang/include/clang/AST/StmtOpenMP.h b/clang/include/clang/AST/StmtOpenMP.h
index a990de6d04f74..b7b2b2498a061 100644
--- a/clang/include/clang/AST/StmtOpenMP.h
+++ b/clang/include/clang/AST/StmtOpenMP.h
@@ -6627,6 +6627,9 @@ class OMPMetaDirective final : public OMPExecutableDirective {
   /// directive has no 'otherwise' clause.
   bool HasImplicitOtherwise = false;
 
+  /// The OpenMP constructs that enclose the directive.
+  ArrayRef<llvm::omp::TraitProperty> ConstructTraits;
+
   OMPMetaDirective(SourceLocation StartLoc, SourceLocation EndLoc)
       : OMPExecutableDirective(OMPMetaDirectiveClass,
                                llvm::omp::OMPD_metadirective, StartLoc,
@@ -6669,12 +6672,15 @@ class OMPMetaDirective final : public OMPExecutableDirective {
   }
 
   void setHasImplicitOtherwise(bool V) { HasImplicitOtherwise = V; }
+  void setConstructTraits(const ASTContext &C,
+                          ArrayRef<llvm::omp::TraitProperty> Traits);
 
 public:
   static OMPMetaDirective *
   Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
          ArrayRef<Stmt *> Variants, ArrayRef<Expr *> Conditions,
-         ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise);
+         ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise,
+         ArrayRef<llvm::omp::TraitProperty> ConstructTraits);
   static OMPMetaDirective *CreateEmpty(const ASTContext &C,
                                        unsigned NumVariants, EmptyShell);
 
@@ -6685,6 +6691,9 @@ class OMPMetaDirective final : public OMPExecutableDirective {
   ArrayRef<OMPTraitInfo *> traitInfos() const {
     return getTrailingTraitInfos();
   }
+  ArrayRef<llvm::omp::TraitProperty> constructTraits() const {
+    return ConstructTraits;
+  }
 
   child_range children() {
     MutableArrayRef<Stmt *> Children = Data->getChildren();
diff --git a/clang/include/clang/Sema/SemaOpenMP.h b/clang/include/clang/Sema/SemaOpenMP.h
index 6750f6a9ce4c2..b5c5c3f9a4acd 100644
--- a/clang/include/clang/Sema/SemaOpenMP.h
+++ b/clang/include/clang/Sema/SemaOpenMP.h
@@ -1525,6 +1525,9 @@ class SemaOpenMP : public SemaBase {
 
   int getOpenMPDeviceNum() const;
 
+  /// Return the OpenMP constructs enclosing the current location.
+  ArrayRef<llvm::omp::TraitProperty> getConstructTraits();
+
   void setOpenMPDeviceNumID(StringRef ID);
 
   enum class OpenMPImpexType {
diff --git a/clang/lib/AST/StmtOpenMP.cpp b/clang/lib/AST/StmtOpenMP.cpp
index 3812b4a060240..6e7ccf5360518 100644
--- a/clang/lib/AST/StmtOpenMP.cpp
+++ b/clang/lib/AST/StmtOpenMP.cpp
@@ -350,7 +350,8 @@ OMPMetaDirective *OMPMetaDirective::allocate(const ASTContext &C,
 OMPMetaDirective *OMPMetaDirective::Create(
     const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
     ArrayRef<Stmt *> Variants, ArrayRef<Expr *> Conditions,
-    ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise) {
+    ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise,
+    ArrayRef<llvm::omp::TraitProperty> ConstructTraits) {
   assert(Variants.size() == Conditions.size() &&
          Variants.size() == TraitInfos.size() &&
          "Expected one condition and one trait info per variant");
@@ -359,9 +360,17 @@ OMPMetaDirective *OMPMetaDirective::Create(
   llvm::copy(Conditions, Dir->getTrailingConditions().begin());
   llvm::copy(TraitInfos, Dir->getTrailingTraitInfos().begin());
   Dir->setHasImplicitOtherwise(HasImplicitOtherwise);
+  Dir->setConstructTraits(C, ConstructTraits);
   return Dir;
 }
 
+void OMPMetaDirective::setConstructTraits(
+    const ASTContext &C, ArrayRef<llvm::omp::TraitProperty> Traits) {
+  auto *Mem = C.Allocate<llvm::omp::TraitProperty>(Traits.size());
+  llvm::copy(Traits, Mem);
+  ConstructTraits = {Mem, Traits.size()};
+}
+
 OMPMetaDirective *OMPMetaDirective::CreateEmpty(const ASTContext &C,
                                                 unsigned NumVariants,
                                                 EmptyShell) {
diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index e2ecdf7d6f45b..bcfddd7fec95e 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -2401,8 +2401,7 @@ void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) {
   // Try variants from best to worst match; 'otherwise' runs if none applies.
   TargetOMPContext OMPCtx(
       getContext(), /*DiagUnknownTrait=*/[](StringRef) {},
-      /*CurrentFunctionDecl=*/nullptr,
-      /*ConstructTraits=*/{}, /*DeviceNum=*/-1);
+      /*CurrentFunctionDecl=*/nullptr, S.constructTraits(), /*DeviceNum=*/-1);
   ArrayRef<Stmt *> Variants = S.variants();
   ArrayRef<Expr *> Conditions = S.conditions();
   SmallVector<llvm::omp::VariantMatchInfo, 4> VMIs;
diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp
index f6fab0b00b0b5..00b3b39ff42e6 100644
--- a/clang/lib/Parse/ParseOpenMP.cpp
+++ b/clang/lib/Parse/ParseOpenMP.cpp
@@ -2715,7 +2715,7 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
         };
     TargetOMPContext OMPCtx(ASTContext, std::move(DiagUnknownTrait),
                             /* CurrentFunctionDecl */ nullptr,
-                            ArrayRef<llvm::omp::TraitProperty>(),
+                            Actions.OpenMP().getConstructTraits(),
                             Actions.OpenMP().getOpenMPDeviceNum());
 
     // A single match is returned for OpenMP 5.0
diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index 607ca7a554462..c37926f9f59e7 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -3881,7 +3881,7 @@ StmtResult SemaOpenMP::ActOnOpenMPMetaDirective(
   }
   return OMPMetaDirective::Create(getASTContext(), StartLoc, EndLoc, Variants,
                                   Conditions, AllTraitInfos,
-                                  HasImplicitOtherwise);
+                                  HasImplicitOtherwise, getConstructTraits());
 }
 
 OMPRequiresDecl *
@@ -19195,6 +19195,10 @@ void SemaOpenMP::setOpenMPDeviceNumID(StringRef ID) { DeviceNumID = ID; }
 
 int SemaOpenMP::getOpenMPDeviceNum() const { return DeviceNum; }
 
+ArrayRef<llvm::omp::TraitProperty> SemaOpenMP::getConstructTraits() {
+  return DSAStack->getConstructTraits();
+}
+
 void SemaOpenMP::ActOnOpenMPDeviceNum(Expr *DeviceNumExpr) {
   llvm::APSInt Result;
   Expr::EvalResult EvalResult;
diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp
index b09471c13a48e..6cd9b5c8f91c0 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2547,6 +2547,10 @@ void ASTStmtReader::VisitOMPMetaDirective(OMPMetaDirective *D) {
   D->setHasImplicitOtherwise(Record.readBool());
   for (OMPTraitInfo *&TI : D->getTrailingTraitInfos())
     TI = Record.readOMPTraitInfo();
+  SmallVector<llvm::omp::TraitProperty, 4> ConstructTraits(Record.readInt());
+  for (llvm::omp::TraitProperty &Trait : ConstructTraits)
+    Trait = llvm::omp::TraitProperty(Record.readInt());
+  D->setConstructTraits(Record.getContext(), ConstructTraits);
 }
 
 void ASTStmtReader::VisitOMPParallelDirective(OMPParallelDirective *D) {
diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp
index f91f318426290..1ab9c55d90956 100644
--- a/clang/lib/Serialization/ASTWriterStmt.cpp
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp
@@ -2618,6 +2618,9 @@ void ASTStmtWriter::VisitOMPMetaDirective(OMPMetaDirective *D) {
   Record.writeBool(D->hasImplicitOtherwise());
   for (const OMPTraitInfo *TI : D->traitInfos())
     Record.writeOMPTraitInfo(TI);
+  Record.push_back(D->constructTraits().size());
+  for (llvm::omp::TraitProperty Trait : D->constructTraits())
+    Record.push_back(unsigned(Trait));
   Code = serialization::STMT_OMP_META_DIRECTIVE;
 }
 
diff --git a/clang/test/OpenMP/metadirective_construct_codegen.cpp b/clang/test/OpenMP/metadirective_construct_codegen.cpp
new file mode 100644
index 0000000000000..7707780b01078
--- /dev/null
+++ b/clang/test/OpenMP/metadirective_construct_codegen.cpp
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=52 -x c++ \
+// RUN:   -triple x86_64-unknown-linux -emit-llvm %s -o - | FileCheck %s
+// expected-no-diagnostics
+
+void bar();
+
+// construct={parallel} matches inside the parallel region.
+// CHECK-LABEL: define internal void @_Z17compile_time_pathv.omp_outlined(
+// CHECK-NOT:   __kmpc_masked
+// CHECK:       call i32 @__kmpc_single(
+// CHECK-NOT:   __kmpc_masked
+// CHECK:       ret void
+void compile_time_path() {
+#pragma omp parallel
+  {
+#pragma omp metadirective when(construct={parallel}: single) otherwise(masked)
+    bar();
+  }
+}
+
+// Outside a parallel region, construct={parallel} does not match.
+// CHECK-LABEL: define {{.*}}void @_Z9no_regionv(
+// CHECK-NOT:   __kmpc_single
+// CHECK:       call i32 @__kmpc_masked(
+// CHECK:       ret void
+void no_region() {
+#pragma omp metadirective when(construct={parallel}: single) otherwise(masked)
+  bar();
+}
diff --git a/clang/test/OpenMP/metadirective_runtime_codegen.cpp b/clang/test/OpenMP/metadirective_runtime_codegen.cpp
index 26de70ff9cd27..f7ab66ed8d27a 100644
--- a/clang/test/OpenMP/metadirective_runtime_codegen.cpp
+++ b/clang/test/OpenMP/metadirective_runtime_codegen.cpp
@@ -136,3 +136,83 @@ void score_reorders(int flag) {
     when(user={condition(flag)}, implementation={vendor(score(5): llvm)}: single)
   bar();
 }
+
+void baz(int);
+
+// Loop variants: each one runs its own loop.
+// CHECK-LABEL: define {{.*}}void @_Z13loop_variantsii(
+// CHECK:       br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]]
+// CHECK:       [[WHEN]]:
+// CHECK-NEXT:  call {{.*}}@__kmpc_fork_call({{.*}}@_Z13loop_variantsii.omp_outlined
+// CHECK:       [[ELSE]]:
+// CHECK:       call void @__kmpc_for_static_init_4(
+// CHECK:       call void @_Z3bazi(
+// CHECK:       call void @__kmpc_for_static_fini(
+// CHECK:       call void @__kmpc_barrier(
+// CHECK:       define internal void @_Z13loop_variantsii.omp_outlined(
+// CHECK:       call void @__kmpc_for_static_init_4(
+// CHECK:       call void @_Z3bazi(
+// CHECK:       call void @__kmpc_for_static_fini(
+void loop_variants(int flag, int n) {
+#pragma omp metadirective when(user={condition(flag)}: parallel for) otherwise(for)
+  for (int i = 0; i < n; ++i)
+    baz(i);
+}
+
+// A metadirective inside a variant of another one. The empty 'otherwise()'
+// runs the block, so the inner metadirective runs on both paths.
+// CHECK-LABEL: define {{.*}}void @_Z6nestedii(
+// CHECK:       br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]]
+// CHECK:       [[WHEN]]:
+// CHECK-NEXT:  call {{.*}}@__kmpc_fork_call({{.*}}@_Z6nestedii.omp_outlined, ptr %b.addr)
+// CHECK:       [[ELSE]]:
+// CHECK-NEXT:  {{%.*}} = load i32, ptr %b.addr
+// CHECK-NEXT:  {{%.*}} = icmp ne i32
+// CHECK-NEXT:  br i1 {{.*}}, label %[[IWHEN:omp.metadirective.when[0-9]*]], label %[[IELSE:omp.metadirective.else[0-9]*]]
+// CHECK:       [[IWHEN]]:
+// CHECK-NEXT:  call i32 @__kmpc_single(
+// CHECK:       [[IELSE]]:
+// CHECK-NEXT:  call i32 @__kmpc_masked(
+// CHECK:       define internal void @_Z6nestedii.omp_outlined(
+// CHECK:       br i1 {{.*}}, label %[[OWHEN:omp.metadirective.when[0-9]*]], label %[[OELSE:omp.metadirective.else[0-9]*]]
+// CHECK:       [[OWHEN]]:
+// CHECK:       call i32 @__kmpc_single(
+// CHECK:       [[OELSE]]:
+// CHECK:       call i32 @__kmpc_masked(
+void nested(int a, int b) {
+#pragma omp metadirective when(user={condition(a)}: parallel) otherwise()
+  {
+#pragma omp metadirective when(user={condition(b)}: single) otherwise(masked)
+    bar();
+  }
+}
+
+// construct={parallel} matches inside the parallel region and scores higher,
+// so 'single' is always selected.
+// CHECK-LABEL: define internal void @_Z12runtime_pathi.omp_outlined(
+// CHECK-NOT:   __kmpc_masked
+// CHECK:       call i32 @__kmpc_single(
+// CHECK-NOT:   __kmpc_masked
+// CHECK:       ret void
+void runtime_path(int flag) {
+#pragma omp parallel
+  {
+#pragma omp metadirective when(construct={parallel}: single) \
+                          when(user={condition(flag)}: masked)
+    bar();
+  }
+}
+
+// Instantiated template. Kept last: the instantiation may be emitted at the
+// end of the file.
+// CHECK-LABEL: define {{.*}}void @_Z4tmplIiEvT_(
+// CHECK:       br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]]
+// CHECK:       [[WHEN]]:
+// CHECK-NEXT:  call {{.*}}@__kmpc_fork_call({{.*}}@_Z4tmplIiEvT_.omp_outlined
+// CHECK:       [[ELSE]]:
+// CHECK-NEXT:  call i32 @__kmpc_single(
+template <typename T> void tmpl(T flag) {
+#pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single)
+  bar();
+}
+void inst() { tmpl(1); }

>From dca28af84b8608685d8783efc26b2822d8019fd6 Mon Sep 17 00:00:00 2001
From: Zahira Ammarguellat <zahira.ammarguellat at intel.com>
Date: Thu, 5 Nov 2026 12:53:59 -0800
Subject: [PATCH 3/3] Added standalone variant support

---
 clang/include/clang/AST/StmtOpenMP.h          |  9 +++-
 .../clang/Basic/DiagnosticParseKinds.td       |  3 --
 clang/include/clang/Sema/SemaOpenMP.h         |  5 +-
 clang/lib/AST/StmtOpenMP.cpp                  | 16 ++++--
 clang/lib/AST/StmtPrinter.cpp                 | 20 +++++---
 clang/lib/Parse/ParseOpenMP.cpp               | 50 +++++++++++++------
 clang/lib/Sema/SemaOpenMP.cpp                 |  9 ++--
 clang/lib/Sema/TreeTransform.h                | 10 ++--
 clang/lib/Serialization/ASTReaderStmt.cpp     |  4 ++
 clang/lib/Serialization/ASTWriterStmt.cpp     |  2 +
 .../metadirective_runtime_ast_print.cpp       | 20 ++++++++
 .../OpenMP/metadirective_runtime_codegen.cpp  | 39 +++++++++++++++
 .../OpenMP/metadirective_runtime_messages.cpp | 10 ----
 13 files changed, 149 insertions(+), 48 deletions(-)

diff --git a/clang/include/clang/AST/StmtOpenMP.h b/clang/include/clang/AST/StmtOpenMP.h
index b7b2b2498a061..46e35d4b48470 100644
--- a/clang/include/clang/AST/StmtOpenMP.h
+++ b/clang/include/clang/AST/StmtOpenMP.h
@@ -6630,6 +6630,10 @@ class OMPMetaDirective final : public OMPExecutableDirective {
   /// The OpenMP constructs that enclose the directive.
   ArrayRef<llvm::omp::TraitProperty> ConstructTraits;
 
+  /// For each variant, true if it is a standalone directive followed by the
+  /// statement, stored together as a compound statement.
+  ArrayRef<bool> DirectiveThenStmt;
+
   OMPMetaDirective(SourceLocation StartLoc, SourceLocation EndLoc)
       : OMPExecutableDirective(OMPMetaDirectiveClass,
                                llvm::omp::OMPD_metadirective, StartLoc,
@@ -6674,13 +6678,15 @@ class OMPMetaDirective final : public OMPExecutableDirective {
   void setHasImplicitOtherwise(bool V) { HasImplicitOtherwise = V; }
   void setConstructTraits(const ASTContext &C,
                           ArrayRef<llvm::omp::TraitProperty> Traits);
+  void setDirectiveThenStmt(const ASTContext &C, ArrayRef<bool> Flags);
 
 public:
   static OMPMetaDirective *
   Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
          ArrayRef<Stmt *> Variants, ArrayRef<Expr *> Conditions,
          ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise,
-         ArrayRef<llvm::omp::TraitProperty> ConstructTraits);
+         ArrayRef<llvm::omp::TraitProperty> ConstructTraits,
+         ArrayRef<bool> DirectiveThenStmt);
   static OMPMetaDirective *CreateEmpty(const ASTContext &C,
                                        unsigned NumVariants, EmptyShell);
 
@@ -6694,6 +6700,7 @@ class OMPMetaDirective final : public OMPExecutableDirective {
   ArrayRef<llvm::omp::TraitProperty> constructTraits() const {
     return ConstructTraits;
   }
+  ArrayRef<bool> directiveThenStmt() const { return DirectiveThenStmt; }
 
   child_range children() {
     MutableArrayRef<Stmt *> Children = Data->getChildren();
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 2be6ff8344cd6..82aec8b4eb714 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1568,9 +1568,6 @@ def err_omp_expected_context_selector
     : Error<"expected valid context selector in %0">;
 def warn_omp_default_deprecated : Warning<"'default' clause for"
   " 'metadirective' is deprecated; use 'otherwise' instead">, InGroup<Deprecated>;
-def err_omp_metadirective_standalone_variant : Error<
-  "standalone directive variants are not supported in a 'metadirective' "
-  "with non-constant user conditions">;
 def err_omp_requires_out_inout_depend_type : Error<
   "reserved locator 'omp_all_memory' requires 'out' or 'inout' "
   "dependency types">;
diff --git a/clang/include/clang/Sema/SemaOpenMP.h b/clang/include/clang/Sema/SemaOpenMP.h
index b5c5c3f9a4acd..174a7caafa6e4 100644
--- a/clang/include/clang/Sema/SemaOpenMP.h
+++ b/clang/include/clang/Sema/SemaOpenMP.h
@@ -214,10 +214,13 @@ class SemaOpenMP : public SemaBase {
   /// Called for metadirectives with user conditions that require runtime
   /// selection. \p Variants holds one complete directive (or the plain
   /// associated statement) per entry of \p TraitInfos.
+  /// \p DirectiveThenStmt marks the variants that are a standalone directive
+  /// followed by the statement.
   StmtResult ActOnOpenMPMetaDirective(SourceLocation StartLoc,
                                       SourceLocation EndLoc,
                                       ArrayRef<OMPTraitInfo *> TraitInfos,
-                                      ArrayRef<Stmt *> Variants);
+                                      ArrayRef<Stmt *> Variants,
+                                      ArrayRef<bool> DirectiveThenStmt);
 
   // OpenMP directives and clauses.
   /// Called on correct id-expression from the '#pragma omp
diff --git a/clang/lib/AST/StmtOpenMP.cpp b/clang/lib/AST/StmtOpenMP.cpp
index 6e7ccf5360518..71c992b717b25 100644
--- a/clang/lib/AST/StmtOpenMP.cpp
+++ b/clang/lib/AST/StmtOpenMP.cpp
@@ -351,24 +351,30 @@ OMPMetaDirective *OMPMetaDirective::Create(
     const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
     ArrayRef<Stmt *> Variants, ArrayRef<Expr *> Conditions,
     ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise,
-    ArrayRef<llvm::omp::TraitProperty> ConstructTraits) {
+    ArrayRef<llvm::omp::TraitProperty> ConstructTraits,
+    ArrayRef<bool> DirectiveThenStmt) {
   assert(Variants.size() == Conditions.size() &&
          Variants.size() == TraitInfos.size() &&
-         "Expected one condition and one trait info per variant");
+         Variants.size() == DirectiveThenStmt.size() &&
+         "Expected one condition, trait info and flag per variant");
   OMPMetaDirective *Dir = allocate(C, Variants.size(), StartLoc, EndLoc);
   llvm::copy(Variants, Dir->getTrailingVariants().begin());
   llvm::copy(Conditions, Dir->getTrailingConditions().begin());
   llvm::copy(TraitInfos, Dir->getTrailingTraitInfos().begin());
   Dir->setHasImplicitOtherwise(HasImplicitOtherwise);
   Dir->setConstructTraits(C, ConstructTraits);
+  Dir->setDirectiveThenStmt(C, DirectiveThenStmt);
   return Dir;
 }
 
+void OMPMetaDirective::setDirectiveThenStmt(const ASTContext &C,
+                                            ArrayRef<bool> Flags) {
+  DirectiveThenStmt = Flags.copy(C);
+}
+
 void OMPMetaDirective::setConstructTraits(
     const ASTContext &C, ArrayRef<llvm::omp::TraitProperty> Traits) {
-  auto *Mem = C.Allocate<llvm::omp::TraitProperty>(Traits.size());
-  llvm::copy(Traits, Mem);
-  ConstructTraits = {Mem, Traits.size()};
+  ConstructTraits = Traits.copy(C);
 }
 
 OMPMetaDirective *OMPMetaDirective::CreateEmpty(const ASTContext &C,
diff --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp
index bed934a70ab51..030985f62280f 100644
--- a/clang/lib/AST/StmtPrinter.cpp
+++ b/clang/lib/AST/StmtPrinter.cpp
@@ -813,7 +813,11 @@ void StmtPrinter::VisitOMPMetaDirective(OMPMetaDirective *Node) {
       TraitInfos[I]->print(OS, Policy);
       OS << ": ";
     }
-    if (auto *D = dyn_cast<OMPExecutableDirective>(Variants[I])) {
+    Stmt *V = Variants[I];
+    // A standalone directive is stored together with the statement.
+    if (Node->directiveThenStmt()[I])
+      V = cast<CompoundStmt>(V)->body_front();
+    if (auto *D = dyn_cast<OMPExecutableDirective>(V)) {
       OS << getOpenMPDirectiveName(D->getDirectiveKind(), OpenMPVersion);
       for (OMPClause *C : D->clauses()) {
         if (C && !C->isImplicit()) {
@@ -825,11 +829,15 @@ void StmtPrinter::VisitOMPMetaDirective(OMPMetaDirective *Node) {
     OS << ')';
   }
   OS << NL;
-  // Every variant has the same associated statement; print it once.
-  Stmt *Body = Variants.front();
-  if (auto *D = dyn_cast<OMPExecutableDirective>(Body))
-    Body = D->getRawStmt();
-  PrintStmt(Body);
+  // Print the statement once, from a variant that has it. If none has it,
+  // the statement follows the metadirective.
+  for (Stmt *V : Variants) {
+    auto *D = dyn_cast<OMPExecutableDirective>(V);
+    if (D && D->hasAssociatedStmt()) {
+      PrintStmt(D->getRawStmt());
+      break;
+    }
+  }
 }
 
 void StmtPrinter::VisitOMPParallelDirective(OMPParallelDirective *Node) {
diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp
index 00b3b39ff42e6..3ca165bcd9536 100644
--- a/clang/lib/Parse/ParseOpenMP.cpp
+++ b/clang/lib/Parse/ParseOpenMP.cpp
@@ -2621,6 +2621,7 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
     ConsumeToken();
     SmallVector<VariantMatchInfo, 4> VMIs;
     SmallVector<OMPTraitInfo *, 4> TraitInfos;
+    bool AnyVariantTakesStmt = false;
 
     // First iteration of parsing all clauses of metadirective.
     // This iteration only parses and collects all context selectors ignoring
@@ -2677,6 +2678,14 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
         }
       }
 
+      // Note if a variant uses the statement after the pragma.
+      if (Tok.isNot(tok::r_paren)) {
+        OpenMPDirectiveKind DKind = parseOpenMPDirectiveKind(*this);
+        if (DKind != OMPD_unknown &&
+            getDirectiveAssociation(DKind) != Association::None)
+          AnyVariantTakesStmt = true;
+      }
+
       // Skip Directive for now. We will parse directive in the second iteration
       int paren = 0;
       while (Tok.isNot(tok::r_paren) || paren != 0) {
@@ -2745,9 +2754,11 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
       // data-sharing context. Diagnostics in the associated statement are
       // reported once per variant.
       SmallVector<Stmt *, 4> Variants;
+      SmallVector<bool, 4> DirectiveThenStmt;
       bool HasError = false;
       for (unsigned I : llvm::seq<unsigned>(NumVariants)) {
         bool HasDirective = false;
+        bool IsDirectiveThenStmt = false;
         if (I < NumClauses) {
           OpenMPClauseKind CKind = getOpenMPClauseKind(PP.getSpelling(Tok));
           ConsumeToken();
@@ -2776,33 +2787,44 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
             ConsumeAnyToken();
           ConsumeAnnotationToken();
         }
-        // No directive or 'nothing': the variant is the associated statement.
-        if (!Variant.isInvalid() && !Variant.isUsable()) {
+        // If any variant uses the statement, the others run a copy of it.
+        auto *D = dyn_cast_or_null<OMPExecutableDirective>(Variant.get());
+        if (!Variant.isInvalid() && !(D && D->hasAssociatedStmt()) &&
+            AnyVariantTakesStmt) {
           ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
-          Variant = ParseStatement();
-        }
-        // A standalone variant does not take the associated statement while
-        // the others do; reject the mix until Sema models it.
-        if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(Variant.get());
-            D && !D->hasAssociatedStmt()) {
-          Diag(Loc, diag::err_omp_metadirective_standalone_variant);
-          Variant = StmtError();
+          StmtResult Body = ParseStatement();
+          if (Body.isInvalid()) {
+            Variant = StmtError();
+          } else if (Variant.isUsable()) {
+            Variant = CompoundStmt::Create(
+                Actions.getASTContext(), {Variant.get(), Body.get()},
+                FPOptionsOverride(), Variant.get()->getBeginLoc(),
+                Body.get()->getEndLoc());
+            IsDirectiveThenStmt = true;
+          } else {
+            Variant = Body;
+          }
         }
+        // Nothing to run for this variant.
+        if (!Variant.isInvalid() && !Variant.isUsable())
+          Variant = Actions.ActOnNullStmt(Loc);
 
         if (VariantTPA) {
           VariantTPA->Revert();
           SkipUntil(tok::r_paren, StopBeforeMatch);
           T.consumeClose();
         }
-        if (Variant.isInvalid())
+        if (Variant.isInvalid()) {
           HasError = true;
-        else
+        } else {
           Variants.push_back(Variant.get());
+          DirectiveThenStmt.push_back(IsDirectiveThenStmt);
+        }
       }
       if (HasError)
         return StmtError();
-      return Actions.OpenMP().ActOnOpenMPMetaDirective(Loc, EndLoc, TraitInfos,
-                                                       Variants);
+      return Actions.OpenMP().ActOnOpenMPMetaDirective(
+          Loc, EndLoc, TraitInfos, Variants, DirectiveThenStmt);
     }
 
     int Idx = 0;
diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index c37926f9f59e7..d29637de012b8 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -3854,7 +3854,8 @@ StmtResult SemaOpenMP::ActOnOpenMPAssumeDirective(ArrayRef<OMPClause *> Clauses,
 
 StmtResult SemaOpenMP::ActOnOpenMPMetaDirective(
     SourceLocation StartLoc, SourceLocation EndLoc,
-    ArrayRef<OMPTraitInfo *> TraitInfos, ArrayRef<Stmt *> Variants) {
+    ArrayRef<OMPTraitInfo *> TraitInfos, ArrayRef<Stmt *> Variants,
+    ArrayRef<bool> DirectiveThenStmt) {
   // Without an 'otherwise' clause, the last variant is the implicit one.
   bool HasImplicitOtherwise = Variants.size() == TraitInfos.size() + 1;
   assert((HasImplicitOtherwise || Variants.size() == TraitInfos.size()) &&
@@ -3879,9 +3880,9 @@ StmtResult SemaOpenMP::ActOnOpenMPMetaDirective(
     }
     Conditions.push_back(Cond);
   }
-  return OMPMetaDirective::Create(getASTContext(), StartLoc, EndLoc, Variants,
-                                  Conditions, AllTraitInfos,
-                                  HasImplicitOtherwise, getConstructTraits());
+  return OMPMetaDirective::Create(
+      getASTContext(), StartLoc, EndLoc, Variants, Conditions, AllTraitInfos,
+      HasImplicitOtherwise, getConstructTraits(), DirectiveThenStmt);
 }
 
 OMPRequiresDecl *
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 8dc79a88d1988..d82b11bdf43f3 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -1711,9 +1711,10 @@ class TreeTransform {
   StmtResult RebuildOMPMetaDirective(SourceLocation StartLoc,
                                      SourceLocation EndLoc,
                                      ArrayRef<OMPTraitInfo *> TraitInfos,
-                                     ArrayRef<Stmt *> Variants) {
-    return getSema().OpenMP().ActOnOpenMPMetaDirective(StartLoc, EndLoc,
-                                                       TraitInfos, Variants);
+                                     ArrayRef<Stmt *> Variants,
+                                     ArrayRef<bool> DirectiveThenStmt) {
+    return getSema().OpenMP().ActOnOpenMPMetaDirective(
+        StartLoc, EndLoc, TraitInfos, Variants, DirectiveThenStmt);
   }
 
   /// Build a new OpenMP informational directive.
@@ -10121,7 +10122,8 @@ TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) {
   }
 
   return getDerived().RebuildOMPMetaDirective(D->getBeginLoc(), D->getEndLoc(),
-                                              TraitInfos, Variants);
+                                              TraitInfos, Variants,
+                                              D->directiveThenStmt());
 }
 
 template <typename Derived>
diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp
index 6cd9b5c8f91c0..12752c988f837 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2551,6 +2551,10 @@ void ASTStmtReader::VisitOMPMetaDirective(OMPMetaDirective *D) {
   for (llvm::omp::TraitProperty &Trait : ConstructTraits)
     Trait = llvm::omp::TraitProperty(Record.readInt());
   D->setConstructTraits(Record.getContext(), ConstructTraits);
+  SmallVector<bool, 4> DirectiveThenStmt(D->getNumVariants());
+  for (bool &Flag : DirectiveThenStmt)
+    Flag = Record.readBool();
+  D->setDirectiveThenStmt(Record.getContext(), DirectiveThenStmt);
 }
 
 void ASTStmtReader::VisitOMPParallelDirective(OMPParallelDirective *D) {
diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp
index 1ab9c55d90956..c417d855d00e1 100644
--- a/clang/lib/Serialization/ASTWriterStmt.cpp
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp
@@ -2621,6 +2621,8 @@ void ASTStmtWriter::VisitOMPMetaDirective(OMPMetaDirective *D) {
   Record.push_back(D->constructTraits().size());
   for (llvm::omp::TraitProperty Trait : D->constructTraits())
     Record.push_back(unsigned(Trait));
+  for (bool Flag : D->directiveThenStmt())
+    Record.writeBool(Flag);
   Code = serialization::STMT_OMP_META_DIRECTIVE;
 }
 
diff --git a/clang/test/OpenMP/metadirective_runtime_ast_print.cpp b/clang/test/OpenMP/metadirective_runtime_ast_print.cpp
index 9980b2df9defd..013add05fa52a 100644
--- a/clang/test/OpenMP/metadirective_runtime_ast_print.cpp
+++ b/clang/test/OpenMP/metadirective_runtime_ast_print.cpp
@@ -49,4 +49,24 @@ void loop(int flag, int n) {
     ;
 }
 
+// A standalone variant is printed in its clause; the statement once.
+// CHECK-LABEL: void standalone(int flag, int n) {
+// CHECK-NEXT: #pragma omp metadirective when(user={condition(flag)}: barrier) otherwise(single)
+// CHECK-NEXT: n = 1;
+// CHECK-NEXT: }
+void standalone(int flag, int n) {
+#pragma omp metadirective when(user={condition(flag)}: barrier) otherwise(single)
+  n = 1;
+}
+
+// All variants are standalone: the statement follows the metadirective.
+// CHECK-LABEL: void all_standalone(int flag, int n) {
+// CHECK-NEXT: #pragma omp metadirective when(user={condition(flag)}: barrier) otherwise(taskyield)
+// CHECK-NEXT: n = 1;
+// CHECK-NEXT: }
+void all_standalone(int flag, int n) {
+#pragma omp metadirective when(user={condition(flag)}: barrier) otherwise(taskyield)
+  n = 1;
+}
+
 #endif
diff --git a/clang/test/OpenMP/metadirective_runtime_codegen.cpp b/clang/test/OpenMP/metadirective_runtime_codegen.cpp
index f7ab66ed8d27a..6e1ccfc7dd7cd 100644
--- a/clang/test/OpenMP/metadirective_runtime_codegen.cpp
+++ b/clang/test/OpenMP/metadirective_runtime_codegen.cpp
@@ -203,6 +203,45 @@ void runtime_path(int flag) {
   }
 }
 
+// A standalone variant runs its directive and then the statement.
+// CHECK-LABEL: define internal void @_Z5mixedi.omp_outlined(
+// CHECK:       br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]]
+// CHECK:       [[WHEN]]:
+// CHECK:       call void @__kmpc_barrier(
+// CHECK-NEXT:  call void @_Z3barv()
+// CHECK-NEXT:  br label %[[END:omp.metadirective.end[0-9]*]]
+// CHECK:       [[ELSE]]:
+// CHECK:       call i32 @__kmpc_single(
+// CHECK:       [[END]]:
+// CHECK-NEXT:  ret void
+void mixed(int flag) {
+#pragma omp parallel
+  {
+#pragma omp metadirective when(user={condition(flag)}: barrier) otherwise(single)
+    bar();
+  }
+}
+
+// All variants are standalone: the statement runs once, after the selection.
+// CHECK-LABEL: define internal void @_Z14all_standalonei.omp_outlined(
+// CHECK:       br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]]
+// CHECK:       [[WHEN]]:
+// CHECK:       call void @__kmpc_barrier(
+// CHECK-NEXT:  br label %[[END:omp.metadirective.end[0-9]*]]
+// CHECK:       [[ELSE]]:
+// CHECK:       call i32 @__kmpc_omp_taskyield(
+// CHECK-NEXT:  br label %[[END]]
+// CHECK:       [[END]]:
+// CHECK-NEXT:  call void @_Z3barv()
+// CHECK-NEXT:  ret void
+void all_standalone(int flag) {
+#pragma omp parallel
+  {
+#pragma omp metadirective when(user={condition(flag)}: barrier) otherwise(taskyield)
+    bar();
+  }
+}
+
 // Instantiated template. Kept last: the instantiation may be emitted at the
 // end of the file.
 // CHECK-LABEL: define {{.*}}void @_Z4tmplIiEvT_(
diff --git a/clang/test/OpenMP/metadirective_runtime_messages.cpp b/clang/test/OpenMP/metadirective_runtime_messages.cpp
index 7419fbe010e19..f394d46eeddf6 100644
--- a/clang/test/OpenMP/metadirective_runtime_messages.cpp
+++ b/clang/test/OpenMP/metadirective_runtime_messages.cpp
@@ -60,13 +60,3 @@ void local_decl(int flag) {
     l.v = 1;
   }
 }
-
-// Standalone directive variants are rejected for now.
-void standalone_variant(int flag) {
-  // expected-error at +1 {{standalone directive variants are not supported in a 'metadirective' with non-constant user conditions}}
-#pragma omp metadirective \
-  when(user={condition(flag)}: barrier) \
-  otherwise(single)
-  {
-  }
-}



More information about the cfe-commits mailing list