[clang] c2c903c - [OpenMP] Build the metadirective AST node for runtime selection. (#236432)
via cfe-commits
cfe-commits at lists.llvm.org
Wed Nov 4 04:58:42 PST 2026
Author: Zahira Ammarguellat
Date: 2026-11-04T07:58:37-05:00
New Revision: c2c903c772c6b3326232215741b7a214cdc00c5a
URL: https://github.com/llvm/llvm-project/commit/c2c903c772c6b3326232215741b7a214cdc00c5a
DIFF: https://github.com/llvm/llvm-project/commit/c2c903c772c6b3326232215741b7a214cdc00c5a.diff
LOG: [OpenMP] Build the metadirective AST node for runtime selection. (#236432)
Follow-up to #192455 (Phase 3 of the agreed plan): with
`-fopenmp-metadirective-runtime-selection`, Sema now builds an
`OMPMetaDirective` holding every variant instead of returning the first
one.
**Known limitation**: the node has no associated statement, so
`-Wuninitialized` and `-Wunreachable-code` skip the variant bodies. This
is covered by `metadirective_runtime_flow_warnings.cpp` and will be
fixed in a follow-up.
Added:
clang/test/OpenMP/metadirective_runtime_ast_dump.cpp
clang/test/OpenMP/metadirective_runtime_ast_print.cpp
clang/test/OpenMP/metadirective_runtime_flow_warnings.cpp
clang/test/OpenMP/metadirective_runtime_implicit_map.cpp
clang/test/OpenMP/metadirective_runtime_simd_codegen.cpp
clang/test/OpenMP/metadirective_runtime_target_device_codegen.cpp
Modified:
clang/include/clang/AST/OpenMPClause.h
clang/include/clang/AST/StmtOpenMP.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/AST/StmtOpenMP.cpp
clang/lib/AST/StmtPrinter.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
clang/lib/CodeGen/CGStmtOpenMP.cpp
clang/lib/Parse/ParseOpenMP.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterStmt.cpp
Removed:
################################################################################
diff --git a/clang/include/clang/AST/OpenMPClause.h b/clang/include/clang/AST/OpenMPClause.h
index 960dcf65b2ca99..3fc2e696b1c2d0 100644
--- a/clang/include/clang/AST/OpenMPClause.h
+++ b/clang/include/clang/AST/OpenMPClause.h
@@ -10220,6 +10220,7 @@ class OMPChildren final
friend TrailingObjects;
friend class OMPClauseReader;
friend class OMPExecutableDirective;
+ friend class OMPMetaDirective;
template <typename T> friend class OMPDeclarativeDirective;
/// Numbers of clauses.
diff --git a/clang/include/clang/AST/StmtOpenMP.h b/clang/include/clang/AST/StmtOpenMP.h
index a070d97a6db1f3..1503147d55cc0b 100644
--- a/clang/include/clang/AST/StmtOpenMP.h
+++ b/clang/include/clang/AST/StmtOpenMP.h
@@ -6553,32 +6553,85 @@ class OMPMaskedDirective final : public OMPExecutableDirective {
/// #pragma omp metadirective when(user={condition(N>10)}: parallel for)
/// \endcode
/// In this example directive '#pragma omp metadirective' has clauses 'when'
-/// with a dynamic user condition to check if a variable 'N > 10'
+/// with a dynamic user condition to check if a variable 'N > 10'.
+/// The directive holds one variant per 'when' or 'otherwise' clause: the
+/// complete directive (or the plain associated statement), its condition and
+/// its context selectors.
///
class OMPMetaDirective final : public OMPExecutableDirective {
friend class ASTStmtReader;
friend class OMPExecutableDirective;
- Stmt *IfStmt;
+
+ /// True if the last variant is the implicit 'otherwise' added when the
+ /// directive has no 'otherwise' clause.
+ bool HasImplicitOtherwise = false;
OMPMetaDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(OMPMetaDirectiveClass,
llvm::omp::OMPD_metadirective, StartLoc,
EndLoc) {}
- explicit OMPMetaDirective()
- : OMPExecutableDirective(OMPMetaDirectiveClass,
- llvm::omp::OMPD_metadirective, SourceLocation(),
- SourceLocation()) {}
- void setIfStmt(Stmt *S) { IfStmt = S; }
+ /// Layout: the children hold the variants, then their conditions; the
+ /// trait infos follow the children.
+ static size_t getTraitInfosOffset(unsigned NumVariants) {
+ return llvm::alignTo(OMPChildren::size(/*NumClauses=*/0,
+ /*HasAssociatedStmt=*/false,
+ 2 * NumVariants),
+ alignof(OMPTraitInfo *));
+ }
+ static OMPMetaDirective *allocate(const ASTContext &C, unsigned NumVariants,
+ SourceLocation StartLoc,
+ SourceLocation EndLoc);
+
+ MutableArrayRef<Stmt *> getTrailingVariants() {
+ return Data->getChildren().take_front(getNumVariants());
+ }
+ MutableArrayRef<Expr *> getTrailingConditions() {
+ return {reinterpret_cast<Expr **>(Data->getChildren().data() +
+ getNumVariants()),
+ getNumVariants()};
+ }
+ MutableArrayRef<OMPTraitInfo *> getTrailingTraitInfos() {
+ return {reinterpret_cast<OMPTraitInfo **>(
+ reinterpret_cast<char *>(Data) +
+ getTraitInfosOffset(getNumVariants())),
+ getNumVariants()};
+ }
+ ArrayRef<Stmt *> getTrailingVariants() const {
+ return const_cast<OMPMetaDirective *>(this)->getTrailingVariants();
+ }
+ ArrayRef<Expr *> getTrailingConditions() const {
+ return const_cast<OMPMetaDirective *>(this)->getTrailingConditions();
+ }
+ ArrayRef<OMPTraitInfo *> getTrailingTraitInfos() const {
+ return const_cast<OMPMetaDirective *>(this)->getTrailingTraitInfos();
+ }
+
+ void setHasImplicitOtherwise(bool V) { HasImplicitOtherwise = V; }
public:
- static OMPMetaDirective *Create(const ASTContext &C, SourceLocation StartLoc,
- SourceLocation EndLoc,
- ArrayRef<OMPClause *> Clauses,
- Stmt *AssociatedStmt, Stmt *IfStmt);
- static OMPMetaDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses,
- EmptyShell);
- Stmt *getIfStmt() const { return IfStmt; }
+ static OMPMetaDirective *
+ Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
+ ArrayRef<Stmt *> Variants, ArrayRef<Expr *> Conditions,
+ ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise);
+ static OMPMetaDirective *CreateEmpty(const ASTContext &C,
+ unsigned NumVariants, EmptyShell);
+
+ unsigned getNumVariants() const { return Data->getChildren().size() / 2; }
+ bool hasImplicitOtherwise() const { return HasImplicitOtherwise; }
+ ArrayRef<Stmt *> variants() const { return getTrailingVariants(); }
+ ArrayRef<Expr *> conditions() const { return getTrailingConditions(); }
+ ArrayRef<OMPTraitInfo *> traitInfos() const {
+ return getTrailingTraitInfos();
+ }
+
+ child_range children() {
+ MutableArrayRef<Stmt *> Children = Data->getChildren();
+ return child_range(Children.begin(), Children.end());
+ }
+ const_child_range children() const {
+ return const_cast<OMPMetaDirective *>(this)->children();
+ }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPMetaDirectiveClass;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index a2fc0206c445be..941a58ae54a05e 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12881,8 +12881,6 @@ def err_omp_interchange_permutation_value_range : Error<
def err_omp_interchange_permutation_value_repeated : Error<
"index %0 must appear exactly once in the permutation clause">;
def note_omp_directive_here : Note<"'%0' directive found here">;
-def err_omp_instantiation_not_supported
- : Error<"instantiation of '%0' not supported yet">;
def err_omp_adjust_arg_multiple_clauses : Error<
"'adjust_arg' argument %0 used in multiple clauses">;
def err_omp_adjust_args_invalid_item : Error<
diff --git a/clang/lib/AST/StmtOpenMP.cpp b/clang/lib/AST/StmtOpenMP.cpp
index 5ba11b2d8c42fa..9a20b8273c3288 100644
--- a/clang/lib/AST/StmtOpenMP.cpp
+++ b/clang/lib/AST/StmtOpenMP.cpp
@@ -331,23 +331,41 @@ void OMPLoopDirective::setFinalsConditions(ArrayRef<Expr *> A) {
llvm::copy(A, getFinalsConditions().begin());
}
-OMPMetaDirective *OMPMetaDirective::Create(const ASTContext &C,
- SourceLocation StartLoc,
- SourceLocation EndLoc,
- ArrayRef<OMPClause *> Clauses,
- Stmt *AssociatedStmt, Stmt *IfStmt) {
- auto *Dir = createDirective<OMPMetaDirective>(
- C, Clauses, AssociatedStmt, /*NumChildren=*/1, StartLoc, EndLoc);
- Dir->setIfStmt(IfStmt);
+OMPMetaDirective *OMPMetaDirective::allocate(const ASTContext &C,
+ unsigned NumVariants,
+ SourceLocation StartLoc,
+ SourceLocation EndLoc) {
+ void *Mem =
+ C.Allocate(sizeof(OMPMetaDirective) + getTraitInfosOffset(NumVariants) +
+ NumVariants * sizeof(OMPTraitInfo *),
+ alignof(OMPMetaDirective));
+ auto *Data = OMPChildren::CreateEmpty(
+ reinterpret_cast<OMPMetaDirective *>(Mem) + 1, /*NumClauses=*/0,
+ /*HasAssociatedStmt=*/false, 2 * NumVariants);
+ auto *Dir = new (Mem) OMPMetaDirective(StartLoc, EndLoc);
+ Dir->Data = Data;
+ return Dir;
+}
+
+OMPMetaDirective *OMPMetaDirective::Create(
+ const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
+ ArrayRef<Stmt *> Variants, ArrayRef<Expr *> Conditions,
+ ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise) {
+ assert(Variants.size() == Conditions.size() &&
+ Variants.size() == TraitInfos.size() &&
+ "Expected one condition and one trait info 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);
return Dir;
}
OMPMetaDirective *OMPMetaDirective::CreateEmpty(const ASTContext &C,
- unsigned NumClauses,
+ unsigned NumVariants,
EmptyShell) {
- return createEmptyDirective<OMPMetaDirective>(C, NumClauses,
- /*HasAssociatedStmt=*/true,
- /*NumChildren=*/1);
+ return allocate(C, NumVariants, SourceLocation(), SourceLocation());
}
OMPParallelDirective *OMPParallelDirective::Create(
diff --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp
index 5e1d45e0f2ff02..bed934a70ab519 100644
--- a/clang/lib/AST/StmtPrinter.cpp
+++ b/clang/lib/AST/StmtPrinter.cpp
@@ -46,6 +46,7 @@
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Compiler.h"
@@ -796,7 +797,39 @@ void StmtPrinter::PrintOMPExecutableDirective(OMPExecutableDirective *S,
void StmtPrinter::VisitOMPMetaDirective(OMPMetaDirective *Node) {
Indent() << "#pragma omp metadirective";
- PrintOMPExecutableDirective(Node);
+ llvm::omp::Version OpenMPVersion =
+ Context ? Context->getLangOpts().getOpenMPVersion()
+ : llvm::omp::FallbackVersion;
+ OMPClausePrinter Printer(OS, Policy, OpenMPVersion);
+ ArrayRef<Stmt *> Variants = Node->variants();
+ ArrayRef<OMPTraitInfo *> TraitInfos = Node->traitInfos();
+ unsigned NumClauses =
+ Node->getNumVariants() - (Node->hasImplicitOtherwise() ? 1 : 0);
+ for (unsigned I : llvm::seq<unsigned>(NumClauses)) {
+ if (TraitInfos[I]->Sets.empty()) {
+ OS << (OpenMPVersion < 52 ? " default(" : " otherwise(");
+ } else {
+ OS << " when(";
+ TraitInfos[I]->print(OS, Policy);
+ OS << ": ";
+ }
+ if (auto *D = dyn_cast<OMPExecutableDirective>(Variants[I])) {
+ OS << getOpenMPDirectiveName(D->getDirectiveKind(), OpenMPVersion);
+ for (OMPClause *C : D->clauses()) {
+ if (C && !C->isImplicit()) {
+ OS << ' ';
+ Printer.Visit(C);
+ }
+ }
+ }
+ 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);
}
void StmtPrinter::VisitOMPParallelDirective(OMPParallelDirective *Node) {
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index d3a6ffee3ea748..4312c2d239a83c 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -11570,6 +11570,13 @@ void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
return;
}
+ // A metadirective has no associated statement; look into its variants.
+ if (const auto *MD = dyn_cast<OMPMetaDirective>(S)) {
+ for (const Stmt *V : MD->variants())
+ scanForTargetRegionsFunctions(V, ParentName);
+ return;
+ }
+
if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
return;
diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index f0e9bdf98485e8..4b9bf00ae5efe5 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -355,6 +355,9 @@ class CheckVarsEscapingDeclContext final
isOpenMPDistributeDirective(D->getDirectiveKind()));
}
}
+ // A metadirective has no associated statement; visit its variants and
+ // conditions.
+ void VisitOMPMetaDirective(const OMPMetaDirective *D) { VisitStmt(D); }
void VisitCapturedStmt(const CapturedStmt *S) {
if (!S)
return;
diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index e63957df3e4069..48c905cf8ad2b5 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -2398,7 +2398,8 @@ void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
}
void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) {
- EmitStmt(S.getIfStmt());
+ // TODO: Select the variant at runtime.
+ EmitStmt(S.variants().front());
}
namespace {
@@ -9103,6 +9104,11 @@ void CodeGenFunction::EmitSimpleOMPExecutableDirective(
EmitOMPScanDirective(*SD);
return;
}
+ // A metadirective has no associated statement; emit its variants.
+ if (const auto *MD = dyn_cast<OMPMetaDirective>(&D)) {
+ EmitOMPMetaDirective(*MD);
+ return;
+ }
if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
return;
auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp
index 8f384c3b888906..f6fab0b00b0b59 100644
--- a/clang/lib/Parse/ParseOpenMP.cpp
+++ b/clang/lib/Parse/ParseOpenMP.cpp
@@ -2736,10 +2736,9 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
// was specified without an associated directive variant. Only
// 'otherwise' (or the deprecated 'default') has no context selectors.
unsigned NumClauses = TraitInfos.size();
- if (llvm::none_of(TraitInfos, [](const OMPTraitInfo *TI) {
- return TI->Sets.empty();
- }))
- TraitInfos.push_back(&ASTContext.getNewOMPTraitInfo());
+ bool HasOtherwise = llvm::any_of(
+ TraitInfos, [](const OMPTraitInfo *TI) { return TI->Sets.empty(); });
+ unsigned NumVariants = NumClauses + (HasOtherwise ? 0 : 1);
// Reuse the normal metadirective variant parse per clause so every
// variant is a complete directive node with its own body and its own
@@ -2747,7 +2746,7 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
// reported once per variant.
SmallVector<Stmt *, 4> Variants;
bool HasError = false;
- for (unsigned I : llvm::seq<unsigned>(TraitInfos.size())) {
+ for (unsigned I : llvm::seq<unsigned>(NumVariants)) {
bool HasDirective = false;
if (I < NumClauses) {
OpenMPClauseKind CKind = getOpenMPClauseKind(PP.getSpelling(Tok));
@@ -2764,7 +2763,7 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
}
// Re-parse the directive and body for every variant but the last.
std::optional<TentativeParsingAction> VariantTPA;
- if (I + 1 < TraitInfos.size())
+ if (I + 1 < NumVariants)
VariantTPA.emplace(*this, /*Unannotated=*/true);
StmtResult Variant;
diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index 88217bd836edc5..d524a3dd183e56 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -3855,14 +3855,33 @@ StmtResult SemaOpenMP::ActOnOpenMPAssumeDirective(ArrayRef<OMPClause *> Clauses,
StmtResult SemaOpenMP::ActOnOpenMPMetaDirective(
SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPTraitInfo *> TraitInfos, ArrayRef<Stmt *> Variants) {
- assert(TraitInfos.size() == Variants.size() &&
+ // Without an 'otherwise' clause, the last variant is the implicit one.
+ bool HasImplicitOtherwise = Variants.size() == TraitInfos.size() + 1;
+ assert((HasImplicitOtherwise || Variants.size() == TraitInfos.size()) &&
"Expected one variant per metadirective clause");
- // TODO Phase 3: Build OMPMetaDirective AST node holding all variants.
- // TODO Phase 4: Codegen - generate runtime if-else chain.
- // Temporary stub: return the first variant until OMPMetaDirective exists.
- if (Variants.empty())
- return StmtError();
- return Variants.front();
+ SmallVector<OMPTraitInfo *, 4> AllTraitInfos(TraitInfos);
+ if (HasImplicitOtherwise)
+ AllTraitInfos.push_back(&getASTContext().getNewOMPTraitInfo());
+ // The user condition of each variant; null for 'otherwise'.
+ SmallVector<Expr *, 4> Conditions;
+ for (OMPTraitInfo *TI : AllTraitInfos) {
+ Expr *Cond = nullptr;
+ TI->anyScoreOrCondition([&](Expr *&E, bool IsScore) {
+ if (!IsScore)
+ Cond = E;
+ return !IsScore;
+ });
+ if (Cond) {
+ ExprResult Val = SemaRef.CheckBooleanCondition(Cond->getExprLoc(), Cond);
+ if (Val.isInvalid())
+ return StmtError();
+ Cond = SemaRef.MakeFullExpr(Val.get()).get();
+ }
+ Conditions.push_back(Cond);
+ }
+ return OMPMetaDirective::Create(getASTContext(), StartLoc, EndLoc, Variants,
+ Conditions, AllTraitInfos,
+ HasImplicitOtherwise);
}
OMPRequiresDecl *
@@ -4756,6 +4775,10 @@ class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
VisitStmt(S);
}
+ // A metadirective has no associated statement; visit its variants and
+ // conditions.
+ void VisitOMPMetaDirective(OMPMetaDirective *S) { VisitStmt(S); }
+
void VisitCallExpr(CallExpr *S) {
for (Stmt *C : S->arguments()) {
if (C) {
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index b56d00a65187f3..8dc79a88d19889 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -1704,6 +1704,18 @@ class TreeTransform {
Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
}
+ /// Build a new OpenMP metadirective.
+ ///
+ /// By default, performs semantic analysis to build the new statement.
+ /// Subclasses may override this routine to provide
diff erent behavior.
+ StmtResult RebuildOMPMetaDirective(SourceLocation StartLoc,
+ SourceLocation EndLoc,
+ ArrayRef<OMPTraitInfo *> TraitInfos,
+ ArrayRef<Stmt *> Variants) {
+ return getSema().OpenMP().ActOnOpenMPMetaDirective(StartLoc, EndLoc,
+ TraitInfos, Variants);
+ }
+
/// Build a new OpenMP informational directive.
StmtResult RebuildOMPInformationalDirective(OpenMPDirectiveKind Kind,
DeclarationNameInfo DirName,
@@ -10071,12 +10083,45 @@ StmtResult TreeTransform<Derived>::TransformOMPInformationalDirective(
template <typename Derived>
StmtResult
TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) {
- // TODO: Fix This
- llvm::omp::Version OMPVersion =
- getDerived().getSema().getLangOpts().getOpenMPVersion();
- SemaRef.Diag(D->getBeginLoc(), diag::err_omp_instantiation_not_supported)
- << getOpenMPDirectiveName(D->getDirectiveKind(), OMPVersion);
- return StmtError();
+ // Every variant is a complete directive (or the plain associated statement),
+ // so it is transformed on its own.
+ SmallVector<Stmt *, 4> Variants;
+ for (Stmt *V : D->variants()) {
+ StmtResult NewV = getDerived().TransformStmt(V);
+ if (NewV.isInvalid())
+ return StmtError();
+ Variants.push_back(NewV.get());
+ }
+
+ // Copy the trait infos and transform their score and condition expressions.
+ // The implicit 'otherwise' trait info is added back by Sema.
+ ArrayRef<OMPTraitInfo *> OldTraitInfos = D->traitInfos();
+ if (D->hasImplicitOtherwise())
+ OldTraitInfos = OldTraitInfos.drop_back();
+ SmallVector<OMPTraitInfo *, 4> TraitInfos;
+ for (const OMPTraitInfo *OldTI : OldTraitInfos) {
+ OMPTraitInfo &TI = getSema().getASTContext().getNewOMPTraitInfo();
+ TI = *OldTI;
+ auto TransformScoreOrCondition = [&](Expr *&E, bool IsScore) {
+ if (!E)
+ return false;
+ EnterExpressionEvaluationContext Ctx(
+ getSema(),
+ IsScore ? Sema::ExpressionEvaluationContext::ConstantEvaluated
+ : Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
+ ExprResult ER = getDerived().TransformExpr(E);
+ if (!ER.isUsable())
+ return true;
+ E = ER.get();
+ return false;
+ };
+ if (TI.anyScoreOrCondition(TransformScoreOrCondition))
+ return StmtError();
+ TraitInfos.push_back(&TI);
+ }
+
+ return getDerived().RebuildOMPMetaDirective(D->getBeginLoc(), D->getEndLoc(),
+ TraitInfos, Variants);
}
template <typename Derived>
diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp
index 26aee27c65e82f..b09471c13a48e2 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2541,9 +2541,12 @@ void ASTStmtReader::VisitOMPLoopDirective(OMPLoopDirective *D) {
void ASTStmtReader::VisitOMPMetaDirective(OMPMetaDirective *D) {
VisitStmt(D);
- // The NumClauses field was read in ReadStmtFromStream.
+ // The NumVariants field was read in ReadStmtFromStream.
Record.skipInts(1);
VisitOMPExecutableDirective(D);
+ D->setHasImplicitOtherwise(Record.readBool());
+ for (OMPTraitInfo *&TI : D->getTrailingTraitInfos())
+ TI = Record.readOMPTraitInfo();
}
void ASTStmtReader::VisitOMPParallelDirective(OMPParallelDirective *D) {
diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp
index c6e74fd19750a4..f91f318426290c 100644
--- a/clang/lib/Serialization/ASTWriterStmt.cpp
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp
@@ -2613,8 +2613,11 @@ void ASTStmtWriter::VisitOMPLoopDirective(OMPLoopDirective *D) {
void ASTStmtWriter::VisitOMPMetaDirective(OMPMetaDirective *D) {
VisitStmt(D);
- Record.push_back(D->getNumClauses());
+ Record.push_back(D->getNumVariants());
VisitOMPExecutableDirective(D);
+ Record.writeBool(D->hasImplicitOtherwise());
+ for (const OMPTraitInfo *TI : D->traitInfos())
+ Record.writeOMPTraitInfo(TI);
Code = serialization::STMT_OMP_META_DIRECTIVE;
}
diff --git a/clang/test/OpenMP/metadirective_runtime_ast_dump.cpp b/clang/test/OpenMP/metadirective_runtime_ast_dump.cpp
new file mode 100644
index 00000000000000..8de671834e1413
--- /dev/null
+++ b/clang/test/OpenMP/metadirective_runtime_ast_dump.cpp
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -std=c++11 \
+// RUN: -fopenmp-metadirective-runtime-selection -ast-dump %s | FileCheck %s
+
+// CHECK-LABEL: FunctionDecl {{.*}} when_otherwise
+// CHECK: OMPMetaDirective
+// CHECK-NEXT: OMPParallelDirective
+// CHECK: OMPSingleDirective
+// CHECK: ImplicitCastExpr {{.*}} 'bool' <IntegralToBoolean>
+// CHECK-NEXT: ImplicitCastExpr {{.*}} 'int' <LValueToRValue>
+// CHECK-NEXT: DeclRefExpr {{.*}} 'flag' 'int'
+// CHECK-NEXT: <<<NULL>>>
+void when_otherwise(int flag) {
+#pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single)
+ {
+ }
+}
+
+// A dependent condition is resolved when the template is instantiated.
+// CHECK-LABEL: FunctionTemplateDecl {{.*}} tmpl
+// CHECK: FunctionDecl {{.*}} tmpl 'void (T)'
+// CHECK: OMPMetaDirective
+// CHECK: FunctionDecl {{.*}} used tmpl 'void (int)' implicit_instantiation
+// CHECK: OMPMetaDirective
+// CHECK-NEXT: OMPParallelDirective
+// CHECK: OMPSingleDirective
+// CHECK: DeclRefExpr {{.*}} 'flag' 'int'
+template <typename T> void tmpl(T flag) {
+#pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single)
+ {
+ }
+}
+void inst() { tmpl(1); }
+
+// Without 'otherwise', the last variant is the plain associated statement.
+// CHECK-LABEL: FunctionDecl {{.*}} no_otherwise
+// CHECK: OMPMetaDirective
+// CHECK-NEXT: OMPParallelDirective
+// CHECK: {{^ *}}|-CompoundStmt
+// CHECK-NEXT: ImplicitCastExpr {{.*}} 'bool' <IntegralToBoolean>
+// CHECK: <<<NULL>>>
+void no_otherwise(int flag) {
+#pragma omp metadirective when(user={condition(flag)}: parallel)
+ {
+ }
+}
diff --git a/clang/test/OpenMP/metadirective_runtime_ast_print.cpp b/clang/test/OpenMP/metadirective_runtime_ast_print.cpp
new file mode 100644
index 00000000000000..9980b2df9defd4
--- /dev/null
+++ b/clang/test/OpenMP/metadirective_runtime_ast_print.cpp
@@ -0,0 +1,52 @@
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=52 -std=c++11 \
+// RUN: -fopenmp-metadirective-runtime-selection -ast-print %s \
+// RUN: | FileCheck %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -std=c++11 \
+// RUN: -fopenmp-metadirective-runtime-selection -x c++ -emit-pch -o %t %s
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=52 -std=c++11 \
+// RUN: -fopenmp-metadirective-runtime-selection -include-pch %t \
+// RUN: -ast-print %s | FileCheck %s
+
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+// CHECK-LABEL: void when_otherwise(int flag) {
+// CHECK-NEXT: #pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single)
+// CHECK-NEXT: {
+void when_otherwise(int flag) {
+#pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single)
+ {
+ }
+}
+
+// The implicit 'otherwise' is not printed.
+// CHECK-LABEL: void no_otherwise(int flag) {
+// CHECK-NEXT: #pragma omp metadirective when(user={condition(flag)}: parallel){{$}}
+void no_otherwise(int flag) {
+#pragma omp metadirective when(user={condition(flag)}: parallel)
+ {
+ }
+}
+
+// Variant clauses and an empty variant are printed as written.
+// CHECK-LABEL: void clauses(int flag) {
+// CHECK-NEXT: #pragma omp metadirective when(user={condition(flag)}: parallel num_threads(4)) when(user={condition(!flag)}: )
+void clauses(int flag) {
+#pragma omp metadirective when(user={condition(flag)}: parallel num_threads(4)) when(user={condition(!flag)}: )
+ {
+ }
+}
+
+// A loop variant prints its loop, not just the loop body.
+// CHECK-LABEL: void loop(int flag, int n) {
+// CHECK-NEXT: #pragma omp metadirective when(user={condition(flag)}: parallel for) otherwise(for)
+// CHECK-NEXT: for (int i = 0; i < n; ++i)
+void loop(int flag, int n) {
+#pragma omp metadirective when(user={condition(flag)}: parallel for) otherwise(for)
+ for (int i = 0; i < n; ++i)
+ ;
+}
+
+#endif
diff --git a/clang/test/OpenMP/metadirective_runtime_flow_warnings.cpp b/clang/test/OpenMP/metadirective_runtime_flow_warnings.cpp
new file mode 100644
index 00000000000000..a8cb07041fcacc
--- /dev/null
+++ b/clang/test/OpenMP/metadirective_runtime_flow_warnings.cpp
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=52 -std=c++11 \
+// RUN: -fopenmp-metadirective-runtime-selection -Wuninitialized \
+// RUN: -Wunreachable-code -fsyntax-only %s
+
+[[noreturn]] void stop();
+void use(int);
+
+void plain_parallel() {
+ int x; // expected-note {{initialize the variable 'x' to silence this warning}}
+#pragma omp parallel
+ {
+ use(x); // expected-warning {{variable 'x' is uninitialized when used here}}
+ }
+}
+
+// FIXME: Known limitation, to be fixed in a follow-up: CFG-based analyses
+// skip the variants, so this does not warn.
+void runtime_metadirective(int flag) {
+ int x;
+#pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single)
+ {
+ use(x);
+ }
+}
+
+void unreachable_parallel() {
+#pragma omp parallel
+ {
+ stop();
+ use(1); // expected-warning {{code will never be executed}}
+ }
+}
+
+// FIXME: Known limitation, to be fixed in a follow-up: CFG-based analyses
+// skip the variants, so this does not warn.
+void unreachable_metadirective(int flag) {
+#pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single)
+ {
+ stop();
+ use(1);
+ }
+}
diff --git a/clang/test/OpenMP/metadirective_runtime_implicit_map.cpp b/clang/test/OpenMP/metadirective_runtime_implicit_map.cpp
new file mode 100644
index 00000000000000..ee6ffcb3a5ef51
--- /dev/null
+++ b/clang/test/OpenMP/metadirective_runtime_implicit_map.cpp
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=52 \
+// RUN: -fopenmp-metadirective-runtime-selection \
+// RUN: -fopenmp-targets=x86_64-pc-linux-gnu -ast-dump %s | FileCheck %s
+// expected-no-diagnostics
+
+// A member used only inside a nested runtime metadirective is implicitly
+// mapped by the enclosing target region.
+struct S {
+ int a;
+ // CHECK-LABEL: CXXMethodDecl {{.*}} f_meta
+ // CHECK: OMPTargetDirective
+ // CHECK: OMPMapClause {{.*}} <implicit>
+ // CHECK-NEXT: MemberExpr {{.*}} ->a
+ void f_meta(int flag) {
+#pragma omp target
+ {
+#pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single)
+ a = 1;
+ }
+ }
+};
+
+void use(S &s) { s.f_meta(1); }
diff --git a/clang/test/OpenMP/metadirective_runtime_simd_codegen.cpp b/clang/test/OpenMP/metadirective_runtime_simd_codegen.cpp
new file mode 100644
index 00000000000000..b4e7582a20d56b
--- /dev/null
+++ b/clang/test/OpenMP/metadirective_runtime_simd_codegen.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -verify -fopenmp-simd -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();
+
+// With -fopenmp-simd, the body of a runtime metadirective is still emitted.
+// CHECK-LABEL: define {{.*}}void @_Z3fooi(
+// CHECK: call void @_Z3barv()
+// CHECK-NOT: __kmpc
+// CHECK: ret void
+void foo(int flag) {
+#pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single)
+ bar();
+}
diff --git a/clang/test/OpenMP/metadirective_runtime_target_device_codegen.cpp b/clang/test/OpenMP/metadirective_runtime_target_device_codegen.cpp
new file mode 100644
index 00000000000000..d58940f4e0d591
--- /dev/null
+++ b/clang/test/OpenMP/metadirective_runtime_target_device_codegen.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -x c++ \
+// RUN: -fopenmp-metadirective-runtime-selection \
+// RUN: -triple x86_64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN: -emit-llvm-bc %s -o %t-host.bc
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=52 -x c++ \
+// RUN: -fopenmp-metadirective-runtime-selection \
+// RUN: -triple nvptx64-nvidia-cuda -aux-triple x86_64-unknown-unknown \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s \
+// RUN: -fopenmp-is-target-device -fopenmp-host-ir-file-path %t-host.bc \
+// RUN: -o - | FileCheck %s
+// expected-no-diagnostics
+
+// A target region in a variant of a runtime metadirective gets a device
+// kernel.
+// CHECK: define {{.*}}void @__omp_offloading_{{.*}}_Z14target_varianti_l{{[0-9]+}}(
+void target_variant(int flag) {
+ int x = 0;
+#pragma omp metadirective when(user={condition(flag)}: target map(tofrom: x)) otherwise(parallel)
+ {
+ x = 1;
+ }
+}
More information about the cfe-commits
mailing list