1 //===--- ParseOpenMP.cpp - OpenMP directives parsing ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// \brief This file implements parsing of all OpenMP directives and clauses.
12 //===----------------------------------------------------------------------===//
14 #include "RAIIObjectsForParser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/StmtOpenMP.h"
17 #include "clang/Parse/ParseDiagnostic.h"
18 #include "clang/Parse/Parser.h"
19 #include "clang/Sema/Scope.h"
20 #include "llvm/ADT/PointerIntPair.h"
22 using namespace clang;
24 //===----------------------------------------------------------------------===//
25 // OpenMP declarative directives.
26 //===----------------------------------------------------------------------===//
29 enum OpenMPDirectiveKindEx {
30 OMPD_cancellation = OMPD_unknown + 1,
42 OMPD_distribute_parallel,
43 OMPD_teams_distribute_parallel,
44 OMPD_target_teams_distribute_parallel
47 class ThreadprivateListParserHelper final {
48 SmallVector<Expr *, 4> Identifiers;
52 ThreadprivateListParserHelper(Parser *P) : P(P) {}
53 void operator()(CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
55 P->getActions().ActOnOpenMPIdExpression(P->getCurScope(), SS, NameInfo);
57 Identifiers.push_back(Res.get());
59 llvm::ArrayRef<Expr *> getIdentifiers() const { return Identifiers; }
63 // Map token string to extended OMP token kind that are
64 // OpenMPDirectiveKind + OpenMPDirectiveKindEx.
65 static unsigned getOpenMPDirectiveKindEx(StringRef S) {
66 auto DKind = getOpenMPDirectiveKind(S);
67 if (DKind != OMPD_unknown)
70 return llvm::StringSwitch<unsigned>(S)
71 .Case("cancellation", OMPD_cancellation)
72 .Case("data", OMPD_data)
73 .Case("declare", OMPD_declare)
74 .Case("end", OMPD_end)
75 .Case("enter", OMPD_enter)
76 .Case("exit", OMPD_exit)
77 .Case("point", OMPD_point)
78 .Case("reduction", OMPD_reduction)
79 .Case("update", OMPD_update)
80 .Default(OMPD_unknown);
83 static OpenMPDirectiveKind ParseOpenMPDirectiveKind(Parser &P) {
84 // Array of foldings: F[i][0] F[i][1] ===> F[i][2].
85 // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd
86 // TODO: add other combined directives in topological order.
87 static const unsigned F[][3] = {
88 { OMPD_cancellation, OMPD_point, OMPD_cancellation_point },
89 { OMPD_declare, OMPD_reduction, OMPD_declare_reduction },
90 { OMPD_declare, OMPD_simd, OMPD_declare_simd },
91 { OMPD_declare, OMPD_target, OMPD_declare_target },
92 { OMPD_distribute, OMPD_parallel, OMPD_distribute_parallel },
93 { OMPD_distribute_parallel, OMPD_for, OMPD_distribute_parallel_for },
94 { OMPD_distribute_parallel_for, OMPD_simd,
95 OMPD_distribute_parallel_for_simd },
96 { OMPD_distribute, OMPD_simd, OMPD_distribute_simd },
97 { OMPD_end, OMPD_declare, OMPD_end_declare },
98 { OMPD_end_declare, OMPD_target, OMPD_end_declare_target },
99 { OMPD_target, OMPD_data, OMPD_target_data },
100 { OMPD_target, OMPD_enter, OMPD_target_enter },
101 { OMPD_target, OMPD_exit, OMPD_target_exit },
102 { OMPD_target, OMPD_update, OMPD_target_update },
103 { OMPD_target_enter, OMPD_data, OMPD_target_enter_data },
104 { OMPD_target_exit, OMPD_data, OMPD_target_exit_data },
105 { OMPD_for, OMPD_simd, OMPD_for_simd },
106 { OMPD_parallel, OMPD_for, OMPD_parallel_for },
107 { OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd },
108 { OMPD_parallel, OMPD_sections, OMPD_parallel_sections },
109 { OMPD_taskloop, OMPD_simd, OMPD_taskloop_simd },
110 { OMPD_target, OMPD_parallel, OMPD_target_parallel },
111 { OMPD_target, OMPD_simd, OMPD_target_simd },
112 { OMPD_target_parallel, OMPD_for, OMPD_target_parallel_for },
113 { OMPD_target_parallel_for, OMPD_simd, OMPD_target_parallel_for_simd },
114 { OMPD_teams, OMPD_distribute, OMPD_teams_distribute },
115 { OMPD_teams_distribute, OMPD_simd, OMPD_teams_distribute_simd },
116 { OMPD_teams_distribute, OMPD_parallel, OMPD_teams_distribute_parallel },
117 { OMPD_teams_distribute_parallel, OMPD_for, OMPD_teams_distribute_parallel_for },
118 { OMPD_teams_distribute_parallel_for, OMPD_simd, OMPD_teams_distribute_parallel_for_simd },
119 { OMPD_target, OMPD_teams, OMPD_target_teams },
120 { OMPD_target_teams, OMPD_distribute, OMPD_target_teams_distribute },
121 { OMPD_target_teams_distribute, OMPD_parallel, OMPD_target_teams_distribute_parallel },
122 { OMPD_target_teams_distribute_parallel, OMPD_for, OMPD_target_teams_distribute_parallel_for }
124 enum { CancellationPoint = 0, DeclareReduction = 1, TargetData = 2 };
125 auto Tok = P.getCurToken();
128 ? static_cast<unsigned>(OMPD_unknown)
129 : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
130 if (DKind == OMPD_unknown)
133 for (unsigned i = 0; i < llvm::array_lengthof(F); ++i) {
134 if (DKind != F[i][0])
137 Tok = P.getPreprocessor().LookAhead(0);
140 ? static_cast<unsigned>(OMPD_unknown)
141 : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
142 if (SDKind == OMPD_unknown)
145 if (SDKind == F[i][1]) {
150 return DKind < OMPD_unknown ? static_cast<OpenMPDirectiveKind>(DKind)
154 static DeclarationName parseOpenMPReductionId(Parser &P) {
155 Token Tok = P.getCurToken();
156 Sema &Actions = P.getActions();
157 OverloadedOperatorKind OOK = OO_None;
158 // Allow to use 'operator' keyword for C++ operators
159 bool WithOperator = false;
160 if (Tok.is(tok::kw_operator)) {
162 Tok = P.getCurToken();
165 switch (Tok.getKind()) {
166 case tok::plus: // '+'
169 case tok::minus: // '-'
172 case tok::star: // '*'
175 case tok::amp: // '&'
178 case tok::pipe: // '|'
181 case tok::caret: // '^'
184 case tok::ampamp: // '&&'
187 case tok::pipepipe: // '||'
190 case tok::identifier: // identifier
194 P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier);
195 P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
196 Parser::StopBeforeMatch);
197 return DeclarationName();
200 auto &DeclNames = Actions.getASTContext().DeclarationNames;
201 return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo())
202 : DeclNames.getCXXOperatorName(OOK);
205 /// \brief Parse 'omp declare reduction' construct.
207 /// declare-reduction-directive:
208 /// annot_pragma_openmp 'declare' 'reduction'
209 /// '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')'
210 /// ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')']
211 /// annot_pragma_openmp_end
212 /// <reduction_id> is either a base language identifier or one of the following
213 /// operators: '+', '-', '*', '&', '|', '^', '&&' and '||'.
215 Parser::DeclGroupPtrTy
216 Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) {
218 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
219 if (T.expectAndConsume(diag::err_expected_lparen_after,
220 getOpenMPDirectiveName(OMPD_declare_reduction))) {
221 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
222 return DeclGroupPtrTy();
225 DeclarationName Name = parseOpenMPReductionId(*this);
226 if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end))
227 return DeclGroupPtrTy();
230 bool IsCorrect = !ExpectAndConsume(tok::colon);
232 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
233 return DeclGroupPtrTy();
235 IsCorrect = IsCorrect && !Name.isEmpty();
237 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) {
238 Diag(Tok.getLocation(), diag::err_expected_type);
242 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
243 return DeclGroupPtrTy();
245 SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes;
246 // Parse list of types until ':' token.
248 ColonProtectionRAIIObject ColonRAII(*this);
250 TypeResult TR = ParseTypeName(&Range, Declarator::PrototypeContext, AS);
253 Actions.ActOnOpenMPDeclareReductionType(Range.getBegin(), TR);
254 if (!ReductionType.isNull()) {
255 ReductionTypes.push_back(
256 std::make_pair(ReductionType, Range.getBegin()));
259 SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end,
263 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end))
267 if (ExpectAndConsume(tok::comma)) {
269 if (Tok.is(tok::annot_pragma_openmp_end)) {
270 Diag(Tok.getLocation(), diag::err_expected_type);
271 return DeclGroupPtrTy();
274 } while (Tok.isNot(tok::annot_pragma_openmp_end));
276 if (ReductionTypes.empty()) {
277 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
278 return DeclGroupPtrTy();
281 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
282 return DeclGroupPtrTy();
285 if (ExpectAndConsume(tok::colon))
288 if (Tok.is(tok::annot_pragma_openmp_end)) {
289 Diag(Tok.getLocation(), diag::err_expected_expression);
290 return DeclGroupPtrTy();
293 DeclGroupPtrTy DRD = Actions.ActOnOpenMPDeclareReductionDirectiveStart(
294 getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes, AS);
296 // Parse <combiner> expression and then parse initializer if any for each
298 unsigned I = 0, E = ReductionTypes.size();
299 for (auto *D : DRD.get()) {
300 TentativeParsingAction TPA(*this);
301 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
302 Scope::OpenMPDirectiveScope);
303 // Parse <combiner> expression.
304 Actions.ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D);
305 ExprResult CombinerResult =
306 Actions.ActOnFinishFullExpr(ParseAssignmentExpression().get(),
307 D->getLocation(), /*DiscardedValue=*/true);
308 Actions.ActOnOpenMPDeclareReductionCombinerEnd(D, CombinerResult.get());
310 if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
311 Tok.isNot(tok::annot_pragma_openmp_end)) {
316 IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable();
317 ExprResult InitializerResult;
318 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
319 // Parse <initializer> expression.
320 if (Tok.is(tok::identifier) &&
321 Tok.getIdentifierInfo()->isStr("initializer"))
324 Diag(Tok.getLocation(), diag::err_expected) << "'initializer'";
330 BalancedDelimiterTracker T(*this, tok::l_paren,
331 tok::annot_pragma_openmp_end);
333 !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") &&
335 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
336 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
337 Scope::OpenMPDirectiveScope);
339 Actions.ActOnOpenMPDeclareReductionInitializerStart(getCurScope(), D);
340 InitializerResult = Actions.ActOnFinishFullExpr(
341 ParseAssignmentExpression().get(), D->getLocation(),
342 /*DiscardedValue=*/true);
343 Actions.ActOnOpenMPDeclareReductionInitializerEnd(
344 D, InitializerResult.get());
345 if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
346 Tok.isNot(tok::annot_pragma_openmp_end)) {
352 !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid();
357 // Revert parsing if not the last type, otherwise accept it, we're done with
364 return Actions.ActOnOpenMPDeclareReductionDirectiveEnd(getCurScope(), DRD,
369 /// RAII that recreates function context for correct parsing of clauses of
370 /// 'declare simd' construct.
371 /// OpenMP, 2.8.2 declare simd Construct
372 /// The expressions appearing in the clauses of this directive are evaluated in
373 /// the scope of the arguments of the function declaration or definition.
374 class FNContextRAII final {
376 Sema::CXXThisScopeRAII *ThisScope;
377 Parser::ParseScope *TempScope;
378 Parser::ParseScope *FnScope;
379 bool HasTemplateScope = false;
380 bool HasFunScope = false;
381 FNContextRAII() = delete;
382 FNContextRAII(const FNContextRAII &) = delete;
383 FNContextRAII &operator=(const FNContextRAII &) = delete;
386 FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P) {
387 Decl *D = *Ptr.get().begin();
388 NamedDecl *ND = dyn_cast<NamedDecl>(D);
389 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
390 Sema &Actions = P.getActions();
392 // Allow 'this' within late-parsed attributes.
393 ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, /*TypeQuals=*/0,
394 ND && ND->isCXXInstanceMember());
396 // If the Decl is templatized, add template parameters to scope.
397 HasTemplateScope = D->isTemplateDecl();
399 new Parser::ParseScope(&P, Scope::TemplateParamScope, HasTemplateScope);
400 if (HasTemplateScope)
401 Actions.ActOnReenterTemplateScope(Actions.getCurScope(), D);
403 // If the Decl is on a function, add function parameters to the scope.
404 HasFunScope = D->isFunctionOrFunctionTemplate();
405 FnScope = new Parser::ParseScope(&P, Scope::FnScope | Scope::DeclScope,
408 Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D);
412 P.getActions().ActOnExitFunctionContext();
413 FnScope->Exit(); // Pop scope, and remove Decls from IdResolver
415 if (HasTemplateScope)
424 /// Parses clauses for 'declare simd' directive.
426 /// 'inbranch' | 'notinbranch'
427 /// 'simdlen' '(' <expr> ')'
428 /// { 'uniform' '(' <argument_list> ')' }
429 /// { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' }
430 /// { 'linear '(' <argument_list> [ ':' <step> ] ')' }
431 static bool parseDeclareSimdClauses(
432 Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen,
433 SmallVectorImpl<Expr *> &Uniforms, SmallVectorImpl<Expr *> &Aligneds,
434 SmallVectorImpl<Expr *> &Alignments, SmallVectorImpl<Expr *> &Linears,
435 SmallVectorImpl<unsigned> &LinModifiers, SmallVectorImpl<Expr *> &Steps) {
437 const Token &Tok = P.getCurToken();
438 bool IsError = false;
439 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
440 if (Tok.isNot(tok::identifier))
442 OMPDeclareSimdDeclAttr::BranchStateTy Out;
443 IdentifierInfo *II = Tok.getIdentifierInfo();
444 StringRef ClauseName = II->getName();
445 // Parse 'inranch|notinbranch' clauses.
446 if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) {
447 if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) {
448 P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch)
450 << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange;
454 BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc());
456 } else if (ClauseName.equals("simdlen")) {
457 if (SimdLen.isUsable()) {
458 P.Diag(Tok, diag::err_omp_more_one_clause)
459 << getOpenMPDirectiveName(OMPD_declare_simd) << ClauseName << 0;
464 SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc);
465 if (SimdLen.isInvalid())
468 OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName);
469 if (CKind == OMPC_uniform || CKind == OMPC_aligned ||
470 CKind == OMPC_linear) {
471 Parser::OpenMPVarListDataTy Data;
472 auto *Vars = &Uniforms;
473 if (CKind == OMPC_aligned)
475 else if (CKind == OMPC_linear)
479 if (P.ParseOpenMPVarList(OMPD_declare_simd,
480 getOpenMPClauseKind(ClauseName), *Vars, Data))
482 if (CKind == OMPC_aligned)
483 Alignments.append(Aligneds.size() - Alignments.size(), Data.TailExpr);
484 else if (CKind == OMPC_linear) {
485 if (P.getActions().CheckOpenMPLinearModifier(Data.LinKind,
487 Data.LinKind = OMPC_LINEAR_val;
488 LinModifiers.append(Linears.size() - LinModifiers.size(),
490 Steps.append(Linears.size() - Steps.size(), Data.TailExpr);
493 // TODO: add parsing of other clauses.
497 if (Tok.is(tok::comma))
503 /// Parse clauses for '#pragma omp declare simd'.
504 Parser::DeclGroupPtrTy
505 Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr,
506 CachedTokens &Toks, SourceLocation Loc) {
508 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
509 // Consume the previously pushed token.
510 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
512 FNContextRAII FnContext(*this, Ptr);
513 OMPDeclareSimdDeclAttr::BranchStateTy BS =
514 OMPDeclareSimdDeclAttr::BS_Undefined;
516 SmallVector<Expr *, 4> Uniforms;
517 SmallVector<Expr *, 4> Aligneds;
518 SmallVector<Expr *, 4> Alignments;
519 SmallVector<Expr *, 4> Linears;
520 SmallVector<unsigned, 4> LinModifiers;
521 SmallVector<Expr *, 4> Steps;
523 parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds,
524 Alignments, Linears, LinModifiers, Steps);
525 // Need to check for extra tokens.
526 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
527 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
528 << getOpenMPDirectiveName(OMPD_declare_simd);
529 while (Tok.isNot(tok::annot_pragma_openmp_end))
532 // Skip the last annot_pragma_openmp_end.
533 SourceLocation EndLoc = ConsumeToken();
535 return Actions.ActOnOpenMPDeclareSimdDirective(
536 Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears,
537 LinModifiers, Steps, SourceRange(Loc, EndLoc));
542 /// \brief Parsing of declarative OpenMP directives.
544 /// threadprivate-directive:
545 /// annot_pragma_openmp 'threadprivate' simple-variable-list
546 /// annot_pragma_openmp_end
548 /// declare-reduction-directive:
549 /// annot_pragma_openmp 'declare' 'reduction' [...]
550 /// annot_pragma_openmp_end
552 /// declare-simd-directive:
553 /// annot_pragma_openmp 'declare simd' {<clause> [,]}
554 /// annot_pragma_openmp_end
555 /// <function declaration/definition>
557 Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
558 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
559 DeclSpec::TST TagType, Decl *Tag) {
560 assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
561 ParenBraceBracketBalancer BalancerRAIIObj(*this);
563 SourceLocation Loc = ConsumeToken();
564 auto DKind = ParseOpenMPDirectiveKind(*this);
567 case OMPD_threadprivate: {
569 ThreadprivateListParserHelper Helper(this);
570 if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Helper, true)) {
571 // The last seen token is annot_pragma_openmp_end - need to check for
573 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
574 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
575 << getOpenMPDirectiveName(OMPD_threadprivate);
576 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
578 // Skip the last annot_pragma_openmp_end.
580 return Actions.ActOnOpenMPThreadprivateDirective(Loc,
581 Helper.getIdentifiers());
585 case OMPD_declare_reduction:
587 if (auto Res = ParseOpenMPDeclareReductionDirective(AS)) {
588 // The last seen token is annot_pragma_openmp_end - need to check for
590 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
591 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
592 << getOpenMPDirectiveName(OMPD_declare_reduction);
593 while (Tok.isNot(tok::annot_pragma_openmp_end))
596 // Skip the last annot_pragma_openmp_end.
601 case OMPD_declare_simd: {
603 // { #pragma omp declare simd }
604 // <function-declaration-or-definition>
608 while(Tok.isNot(tok::annot_pragma_openmp_end)) {
616 if (Tok.is(tok::annot_pragma_openmp))
617 Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, TagType, Tag);
618 else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
619 // Here we expect to see some function declaration.
621 assert(TagType == DeclSpec::TST_unspecified);
622 MaybeParseCXX11Attributes(Attrs);
623 ParsingDeclSpec PDS(*this);
624 Ptr = ParseExternalDeclaration(Attrs, &PDS);
627 ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag);
631 Diag(Loc, diag::err_omp_decl_in_declare_simd);
632 return DeclGroupPtrTy();
634 return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc);
636 case OMPD_declare_target: {
637 SourceLocation DTLoc = ConsumeAnyToken();
638 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
639 // OpenMP 4.5 syntax with list of entities.
640 llvm::SmallSetVector<const NamedDecl*, 16> SameDirectiveDecls;
641 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
642 OMPDeclareTargetDeclAttr::MapTypeTy MT =
643 OMPDeclareTargetDeclAttr::MT_To;
644 if (Tok.is(tok::identifier)) {
645 IdentifierInfo *II = Tok.getIdentifierInfo();
646 StringRef ClauseName = II->getName();
647 // Parse 'to|link' clauses.
648 if (!OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName,
650 Diag(Tok, diag::err_omp_declare_target_unexpected_clause)
656 auto Callback = [this, MT, &SameDirectiveDecls](
657 CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
658 Actions.ActOnOpenMPDeclareTargetName(getCurScope(), SS, NameInfo, MT,
661 if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback, true))
664 // Consume optional ','.
665 if (Tok.is(tok::comma))
668 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
670 return DeclGroupPtrTy();
673 // Skip the last annot_pragma_openmp_end.
676 if (!Actions.ActOnStartOpenMPDeclareTargetDirective(DTLoc))
677 return DeclGroupPtrTy();
679 DKind = ParseOpenMPDirectiveKind(*this);
680 while (DKind != OMPD_end_declare_target && DKind != OMPD_declare_target &&
681 Tok.isNot(tok::eof) && Tok.isNot(tok::r_brace)) {
682 ParsedAttributesWithRange attrs(AttrFactory);
683 MaybeParseCXX11Attributes(attrs);
684 ParseExternalDeclaration(attrs);
685 if (Tok.isAnnotation() && Tok.is(tok::annot_pragma_openmp)) {
686 TentativeParsingAction TPA(*this);
688 DKind = ParseOpenMPDirectiveKind(*this);
689 if (DKind != OMPD_end_declare_target)
696 if (DKind == OMPD_end_declare_target) {
698 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
699 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
700 << getOpenMPDirectiveName(OMPD_end_declare_target);
701 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
703 // Skip the last annot_pragma_openmp_end.
706 Diag(Tok, diag::err_expected_end_declare_target);
707 Diag(DTLoc, diag::note_matching) << "'#pragma omp declare target'";
709 Actions.ActOnFinishOpenMPDeclareTargetDirective();
710 return DeclGroupPtrTy();
713 Diag(Tok, diag::err_omp_unknown_directive);
731 case OMPD_parallel_for:
732 case OMPD_parallel_for_simd:
733 case OMPD_parallel_sections:
737 case OMPD_cancellation_point:
739 case OMPD_target_data:
740 case OMPD_target_enter_data:
741 case OMPD_target_exit_data:
742 case OMPD_target_parallel:
743 case OMPD_target_parallel_for:
745 case OMPD_taskloop_simd:
746 case OMPD_distribute:
747 case OMPD_end_declare_target:
748 case OMPD_target_update:
749 case OMPD_distribute_parallel_for:
750 case OMPD_distribute_parallel_for_simd:
751 case OMPD_distribute_simd:
752 case OMPD_target_parallel_for_simd:
753 case OMPD_target_simd:
754 case OMPD_teams_distribute:
755 case OMPD_teams_distribute_simd:
756 case OMPD_teams_distribute_parallel_for_simd:
757 case OMPD_teams_distribute_parallel_for:
758 case OMPD_target_teams:
759 case OMPD_target_teams_distribute:
760 case OMPD_target_teams_distribute_parallel_for:
761 Diag(Tok, diag::err_omp_unexpected_directive)
762 << getOpenMPDirectiveName(DKind);
765 while (Tok.isNot(tok::annot_pragma_openmp_end))
771 /// \brief Parsing of declarative or executable OpenMP directives.
773 /// threadprivate-directive:
774 /// annot_pragma_openmp 'threadprivate' simple-variable-list
775 /// annot_pragma_openmp_end
777 /// declare-reduction-directive:
778 /// annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':'
779 /// <type> {',' <type>} ':' <expression> ')' ['initializer' '('
780 /// ('omp_priv' '=' <expression>|<function_call>) ')']
781 /// annot_pragma_openmp_end
783 /// executable-directive:
784 /// annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
785 /// 'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
786 /// 'parallel for' | 'parallel sections' | 'task' | 'taskyield' |
787 /// 'barrier' | 'taskwait' | 'flush' | 'ordered' | 'atomic' |
788 /// 'for simd' | 'parallel for simd' | 'target' | 'target data' |
789 /// 'taskgroup' | 'teams' | 'taskloop' | 'taskloop simd' |
790 /// 'distribute' | 'target enter data' | 'target exit data' |
791 /// 'target parallel' | 'target parallel for' |
792 /// 'target update' | 'distribute parallel for' |
793 /// 'distribute paralle for simd' | 'distribute simd' |
794 /// 'target parallel for simd' | 'target simd' |
795 /// 'teams distribute' | 'teams distribute simd' |
796 /// 'teams distribute parallel for simd' |
797 /// 'teams distribute parallel for' | 'target teams' |
798 /// 'target teams distribute' |
799 /// 'target teams distribute parallel for' {clause}
800 /// annot_pragma_openmp_end
802 StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
803 AllowedContsructsKind Allowed) {
804 assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
805 ParenBraceBracketBalancer BalancerRAIIObj(*this);
806 SmallVector<OMPClause *, 5> Clauses;
807 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, OMPC_unknown + 1>
808 FirstClauses(OMPC_unknown + 1);
809 unsigned ScopeFlags =
810 Scope::FnScope | Scope::DeclScope | Scope::OpenMPDirectiveScope;
811 SourceLocation Loc = ConsumeToken(), EndLoc;
812 auto DKind = ParseOpenMPDirectiveKind(*this);
813 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
814 // Name of critical directive.
815 DeclarationNameInfo DirName;
816 StmtResult Directive = StmtError();
817 bool HasAssociatedStatement = true;
818 bool FlushHasClause = false;
821 case OMPD_threadprivate: {
822 if (Allowed != ACK_Any) {
823 Diag(Tok, diag::err_omp_immediate_directive)
824 << getOpenMPDirectiveName(DKind) << 0;
827 ThreadprivateListParserHelper Helper(this);
828 if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Helper, false)) {
829 // The last seen token is annot_pragma_openmp_end - need to check for
831 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
832 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
833 << getOpenMPDirectiveName(OMPD_threadprivate);
834 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
836 DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective(
837 Loc, Helper.getIdentifiers());
838 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
840 SkipUntil(tok::annot_pragma_openmp_end);
843 case OMPD_declare_reduction:
845 if (auto Res = ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) {
846 // The last seen token is annot_pragma_openmp_end - need to check for
848 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
849 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
850 << getOpenMPDirectiveName(OMPD_declare_reduction);
851 while (Tok.isNot(tok::annot_pragma_openmp_end))
855 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
857 SkipUntil(tok::annot_pragma_openmp_end);
860 if (PP.LookAhead(0).is(tok::l_paren)) {
861 FlushHasClause = true;
862 // Push copy of the current token back to stream to properly parse
863 // pseudo-clause OMPFlushClause.
869 case OMPD_cancellation_point:
871 case OMPD_target_enter_data:
872 case OMPD_target_exit_data:
873 case OMPD_target_update:
874 if (Allowed == ACK_StatementsOpenMPNonStandalone) {
875 Diag(Tok, diag::err_omp_immediate_directive)
876 << getOpenMPDirectiveName(DKind) << 0;
878 HasAssociatedStatement = false;
879 // Fall through for further analysis.
889 case OMPD_parallel_for:
890 case OMPD_parallel_for_simd:
891 case OMPD_parallel_sections:
898 case OMPD_target_data:
899 case OMPD_target_parallel:
900 case OMPD_target_parallel_for:
902 case OMPD_taskloop_simd:
903 case OMPD_distribute:
904 case OMPD_distribute_parallel_for:
905 case OMPD_distribute_parallel_for_simd:
906 case OMPD_distribute_simd:
907 case OMPD_target_parallel_for_simd:
908 case OMPD_target_simd:
909 case OMPD_teams_distribute:
910 case OMPD_teams_distribute_simd:
911 case OMPD_teams_distribute_parallel_for_simd:
912 case OMPD_teams_distribute_parallel_for:
913 case OMPD_target_teams:
914 case OMPD_target_teams_distribute:
915 case OMPD_target_teams_distribute_parallel_for: {
917 // Parse directive name of the 'critical' directive if any.
918 if (DKind == OMPD_critical) {
919 BalancedDelimiterTracker T(*this, tok::l_paren,
920 tok::annot_pragma_openmp_end);
921 if (!T.consumeOpen()) {
922 if (Tok.isAnyIdentifier()) {
924 DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation());
927 Diag(Tok, diag::err_omp_expected_identifier_for_critical);
931 } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) {
932 CancelRegion = ParseOpenMPDirectiveKind(*this);
933 if (Tok.isNot(tok::annot_pragma_openmp_end))
937 if (isOpenMPLoopDirective(DKind))
938 ScopeFlags |= Scope::OpenMPLoopDirectiveScope;
939 if (isOpenMPSimdDirective(DKind))
940 ScopeFlags |= Scope::OpenMPSimdDirectiveScope;
941 ParseScope OMPDirectiveScope(this, ScopeFlags);
942 Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc);
944 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
945 OpenMPClauseKind CKind =
948 : FlushHasClause ? OMPC_flush
949 : getOpenMPClauseKind(PP.getSpelling(Tok));
950 Actions.StartOpenMPClause(CKind);
951 FlushHasClause = false;
953 ParseOpenMPClause(DKind, CKind, !FirstClauses[CKind].getInt());
954 FirstClauses[CKind].setInt(true);
956 FirstClauses[CKind].setPointer(Clause);
957 Clauses.push_back(Clause);
961 if (Tok.is(tok::comma))
963 Actions.EndOpenMPClause();
965 // End location of the directive.
966 EndLoc = Tok.getLocation();
967 // Consume final annot_pragma_openmp_end.
970 // OpenMP [2.13.8, ordered Construct, Syntax]
971 // If the depend clause is specified, the ordered construct is a stand-alone
973 if (DKind == OMPD_ordered && FirstClauses[OMPC_depend].getInt()) {
974 if (Allowed == ACK_StatementsOpenMPNonStandalone) {
975 Diag(Loc, diag::err_omp_immediate_directive)
976 << getOpenMPDirectiveName(DKind) << 1
977 << getOpenMPClauseName(OMPC_depend);
979 HasAssociatedStatement = false;
982 StmtResult AssociatedStmt;
983 if (HasAssociatedStatement) {
984 // The body is a block scope like in Lambdas and Blocks.
985 Sema::CompoundScopeRAII CompoundScope(Actions);
986 Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
987 Actions.ActOnStartOfCompoundStmt();
989 AssociatedStmt = ParseStatement();
990 Actions.ActOnFinishOfCompoundStmt();
991 AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
993 Directive = Actions.ActOnOpenMPExecutableDirective(
994 DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc,
998 Actions.EndOpenMPDSABlock(Directive.get());
999 OMPDirectiveScope.Exit();
1002 case OMPD_declare_simd:
1003 case OMPD_declare_target:
1004 case OMPD_end_declare_target:
1005 Diag(Tok, diag::err_omp_unexpected_directive)
1006 << getOpenMPDirectiveName(DKind);
1007 SkipUntil(tok::annot_pragma_openmp_end);
1010 Diag(Tok, diag::err_omp_unknown_directive);
1011 SkipUntil(tok::annot_pragma_openmp_end);
1017 // Parses simple list:
1018 // simple-variable-list:
1019 // '(' id-expression {, id-expression} ')'
1021 bool Parser::ParseOpenMPSimpleVarList(
1022 OpenMPDirectiveKind Kind,
1023 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
1025 bool AllowScopeSpecifier) {
1027 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1028 if (T.expectAndConsume(diag::err_expected_lparen_after,
1029 getOpenMPDirectiveName(Kind)))
1031 bool IsCorrect = true;
1032 bool NoIdentIsFound = true;
1034 // Read tokens while ')' or annot_pragma_openmp_end is not found.
1035 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
1037 SourceLocation TemplateKWLoc;
1040 Token PrevTok = Tok;
1041 NoIdentIsFound = false;
1043 if (AllowScopeSpecifier && getLangOpts().CPlusPlus &&
1044 ParseOptionalCXXScopeSpecifier(SS, nullptr, false)) {
1046 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1048 } else if (ParseUnqualifiedId(SS, false, false, false, nullptr,
1049 TemplateKWLoc, Name)) {
1051 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1053 } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) &&
1054 Tok.isNot(tok::annot_pragma_openmp_end)) {
1056 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1058 Diag(PrevTok.getLocation(), diag::err_expected)
1060 << SourceRange(PrevTok.getLocation(), PrevTokLocation);
1062 Callback(SS, Actions.GetNameFromUnqualifiedId(Name));
1065 if (Tok.is(tok::comma)) {
1070 if (NoIdentIsFound) {
1071 Diag(Tok, diag::err_expected) << tok::identifier;
1076 IsCorrect = !T.consumeClose() && IsCorrect;
1081 /// \brief Parsing of OpenMP clauses.
1084 /// if-clause | final-clause | num_threads-clause | safelen-clause |
1085 /// default-clause | private-clause | firstprivate-clause | shared-clause
1086 /// | linear-clause | aligned-clause | collapse-clause |
1087 /// lastprivate-clause | reduction-clause | proc_bind-clause |
1088 /// schedule-clause | copyin-clause | copyprivate-clause | untied-clause |
1089 /// mergeable-clause | flush-clause | read-clause | write-clause |
1090 /// update-clause | capture-clause | seq_cst-clause | device-clause |
1091 /// simdlen-clause | threads-clause | simd-clause | num_teams-clause |
1092 /// thread_limit-clause | priority-clause | grainsize-clause |
1093 /// nogroup-clause | num_tasks-clause | hint-clause | to-clause |
1094 /// from-clause | is_device_ptr-clause
1096 OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind,
1097 OpenMPClauseKind CKind, bool FirstClause) {
1098 OMPClause *Clause = nullptr;
1099 bool ErrorFound = false;
1100 // Check if clause is allowed for the given directive.
1101 if (CKind != OMPC_unknown && !isAllowedClauseForDirective(DKind, CKind)) {
1102 Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind)
1103 << getOpenMPDirectiveName(DKind);
1109 case OMPC_num_threads:
1115 case OMPC_num_teams:
1116 case OMPC_thread_limit:
1118 case OMPC_grainsize:
1119 case OMPC_num_tasks:
1121 // OpenMP [2.5, Restrictions]
1122 // At most one num_threads clause can appear on the directive.
1123 // OpenMP [2.8.1, simd construct, Restrictions]
1124 // Only one safelen clause can appear on a simd directive.
1125 // Only one simdlen clause can appear on a simd directive.
1126 // Only one collapse clause can appear on a simd directive.
1127 // OpenMP [2.9.1, target data construct, Restrictions]
1128 // At most one device clause can appear on the directive.
1129 // OpenMP [2.11.1, task Construct, Restrictions]
1130 // At most one if clause can appear on the directive.
1131 // At most one final clause can appear on the directive.
1132 // OpenMP [teams Construct, Restrictions]
1133 // At most one num_teams clause can appear on the directive.
1134 // At most one thread_limit clause can appear on the directive.
1135 // OpenMP [2.9.1, task Construct, Restrictions]
1136 // At most one priority clause can appear on the directive.
1137 // OpenMP [2.9.2, taskloop Construct, Restrictions]
1138 // At most one grainsize clause can appear on the directive.
1139 // OpenMP [2.9.2, taskloop Construct, Restrictions]
1140 // At most one num_tasks clause can appear on the directive.
1142 Diag(Tok, diag::err_omp_more_one_clause)
1143 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1147 if (CKind == OMPC_ordered && PP.LookAhead(/*N=*/0).isNot(tok::l_paren))
1148 Clause = ParseOpenMPClause(CKind);
1150 Clause = ParseOpenMPSingleExprClause(CKind);
1153 case OMPC_proc_bind:
1154 // OpenMP [2.14.3.1, Restrictions]
1155 // Only a single default clause may be specified on a parallel, task or
1157 // OpenMP [2.5, parallel Construct, Restrictions]
1158 // At most one proc_bind clause can appear on the directive.
1160 Diag(Tok, diag::err_omp_more_one_clause)
1161 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1165 Clause = ParseOpenMPSimpleClause(CKind);
1168 case OMPC_dist_schedule:
1169 case OMPC_defaultmap:
1170 // OpenMP [2.7.1, Restrictions, p. 3]
1171 // Only one schedule clause can appear on a loop directive.
1172 // OpenMP [2.10.4, Restrictions, p. 106]
1173 // At most one defaultmap clause can appear on the directive.
1175 Diag(Tok, diag::err_omp_more_one_clause)
1176 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1181 Clause = ParseOpenMPSingleExprWithArgClause(CKind);
1185 case OMPC_mergeable:
1194 // OpenMP [2.7.1, Restrictions, p. 9]
1195 // Only one ordered clause can appear on a loop directive.
1196 // OpenMP [2.7.1, Restrictions, C/C++, p. 4]
1197 // Only one nowait clause can appear on a for directive.
1199 Diag(Tok, diag::err_omp_more_one_clause)
1200 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1204 Clause = ParseOpenMPClause(CKind);
1207 case OMPC_firstprivate:
1208 case OMPC_lastprivate:
1210 case OMPC_reduction:
1214 case OMPC_copyprivate:
1220 case OMPC_use_device_ptr:
1221 case OMPC_is_device_ptr:
1222 Clause = ParseOpenMPVarListClause(DKind, CKind);
1225 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
1226 << getOpenMPDirectiveName(DKind);
1227 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1229 case OMPC_threadprivate:
1231 Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind)
1232 << getOpenMPDirectiveName(DKind);
1233 SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch);
1236 return ErrorFound ? nullptr : Clause;
1239 /// Parses simple expression in parens for single-expression clauses of OpenMP
1241 /// \param RLoc Returned location of right paren.
1242 ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName,
1243 SourceLocation &RLoc) {
1244 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1245 if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data()))
1248 SourceLocation ELoc = Tok.getLocation();
1249 ExprResult LHS(ParseCastExpression(
1250 /*isUnaryExpression=*/false, /*isAddressOfOperand=*/false, NotTypeCast));
1251 ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
1252 Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc);
1257 RLoc = T.getCloseLocation();
1261 /// \brief Parsing of OpenMP clauses with single expressions like 'final',
1262 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
1263 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks' or 'hint'.
1266 /// 'final' '(' expression ')'
1268 /// num_threads-clause:
1269 /// 'num_threads' '(' expression ')'
1272 /// 'safelen' '(' expression ')'
1275 /// 'simdlen' '(' expression ')'
1277 /// collapse-clause:
1278 /// 'collapse' '(' expression ')'
1280 /// priority-clause:
1281 /// 'priority' '(' expression ')'
1283 /// grainsize-clause:
1284 /// 'grainsize' '(' expression ')'
1286 /// num_tasks-clause:
1287 /// 'num_tasks' '(' expression ')'
1290 /// 'hint' '(' expression ')'
1292 OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind) {
1293 SourceLocation Loc = ConsumeToken();
1294 SourceLocation LLoc = Tok.getLocation();
1295 SourceLocation RLoc;
1297 ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
1299 if (Val.isInvalid())
1302 return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc);
1305 /// \brief Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
1308 /// 'default' '(' 'none' | 'shared' ')
1310 /// proc_bind-clause:
1311 /// 'proc_bind' '(' 'master' | 'close' | 'spread' ')
1313 OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind) {
1314 SourceLocation Loc = Tok.getLocation();
1315 SourceLocation LOpen = ConsumeToken();
1317 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1318 if (T.expectAndConsume(diag::err_expected_lparen_after,
1319 getOpenMPClauseName(Kind)))
1322 unsigned Type = getOpenMPSimpleClauseType(
1323 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1324 SourceLocation TypeLoc = Tok.getLocation();
1325 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1326 Tok.isNot(tok::annot_pragma_openmp_end))
1332 return Actions.ActOnOpenMPSimpleClause(Kind, Type, TypeLoc, LOpen, Loc,
1336 /// \brief Parsing of OpenMP clauses like 'ordered'.
1347 /// mergeable-clause:
1362 OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind) {
1363 SourceLocation Loc = Tok.getLocation();
1366 return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation());
1370 /// \brief Parsing of OpenMP clauses with single expressions and some additional
1371 /// argument like 'schedule' or 'dist_schedule'.
1373 /// schedule-clause:
1374 /// 'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
1378 /// 'if' '(' [ directive-name-modifier ':' ] expression ')'
1381 /// 'defaultmap' '(' modifier ':' kind ')'
1383 OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind) {
1384 SourceLocation Loc = ConsumeToken();
1385 SourceLocation DelimLoc;
1387 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1388 if (T.expectAndConsume(diag::err_expected_lparen_after,
1389 getOpenMPClauseName(Kind)))
1393 SmallVector<unsigned, 4> Arg;
1394 SmallVector<SourceLocation, 4> KLoc;
1395 if (Kind == OMPC_schedule) {
1396 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
1397 Arg.resize(NumberOfElements);
1398 KLoc.resize(NumberOfElements);
1399 Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown;
1400 Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown;
1401 Arg[ScheduleKind] = OMPC_SCHEDULE_unknown;
1402 auto KindModifier = getOpenMPSimpleClauseType(
1403 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1404 if (KindModifier > OMPC_SCHEDULE_unknown) {
1406 Arg[Modifier1] = KindModifier;
1407 KLoc[Modifier1] = Tok.getLocation();
1408 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1409 Tok.isNot(tok::annot_pragma_openmp_end))
1411 if (Tok.is(tok::comma)) {
1412 // Parse ',' 'modifier'
1414 KindModifier = getOpenMPSimpleClauseType(
1415 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1416 Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown
1418 : (unsigned)OMPC_SCHEDULE_unknown;
1419 KLoc[Modifier2] = Tok.getLocation();
1420 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1421 Tok.isNot(tok::annot_pragma_openmp_end))
1425 if (Tok.is(tok::colon))
1428 Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier";
1429 KindModifier = getOpenMPSimpleClauseType(
1430 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1432 Arg[ScheduleKind] = KindModifier;
1433 KLoc[ScheduleKind] = Tok.getLocation();
1434 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1435 Tok.isNot(tok::annot_pragma_openmp_end))
1437 if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static ||
1438 Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic ||
1439 Arg[ScheduleKind] == OMPC_SCHEDULE_guided) &&
1441 DelimLoc = ConsumeAnyToken();
1442 } else if (Kind == OMPC_dist_schedule) {
1443 Arg.push_back(getOpenMPSimpleClauseType(
1444 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1445 KLoc.push_back(Tok.getLocation());
1446 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1447 Tok.isNot(tok::annot_pragma_openmp_end))
1449 if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma))
1450 DelimLoc = ConsumeAnyToken();
1451 } else if (Kind == OMPC_defaultmap) {
1452 // Get a defaultmap modifier
1453 Arg.push_back(getOpenMPSimpleClauseType(
1454 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1455 KLoc.push_back(Tok.getLocation());
1456 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1457 Tok.isNot(tok::annot_pragma_openmp_end))
1460 if (Tok.is(tok::colon))
1462 else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown)
1463 Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier";
1464 // Get a defaultmap kind
1465 Arg.push_back(getOpenMPSimpleClauseType(
1466 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1467 KLoc.push_back(Tok.getLocation());
1468 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1469 Tok.isNot(tok::annot_pragma_openmp_end))
1472 assert(Kind == OMPC_if);
1473 KLoc.push_back(Tok.getLocation());
1474 TentativeParsingAction TPA(*this);
1475 Arg.push_back(ParseOpenMPDirectiveKind(*this));
1476 if (Arg.back() != OMPD_unknown) {
1478 if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) {
1480 DelimLoc = ConsumeToken();
1483 Arg.back() = OMPD_unknown;
1489 bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) ||
1490 (Kind == OMPC_dist_schedule && DelimLoc.isValid()) ||
1492 if (NeedAnExpression) {
1493 SourceLocation ELoc = Tok.getLocation();
1494 ExprResult LHS(ParseCastExpression(false, false, NotTypeCast));
1495 Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
1496 Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc);
1502 if (NeedAnExpression && Val.isInvalid())
1505 return Actions.ActOnOpenMPSingleExprWithArgClause(
1506 Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc,
1507 T.getCloseLocation());
1510 static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec,
1511 UnqualifiedId &ReductionId) {
1512 SourceLocation TemplateKWLoc;
1513 if (ReductionIdScopeSpec.isEmpty()) {
1515 switch (P.getCurToken().getKind()) {
1543 if (OOK != OO_None) {
1544 SourceLocation OpLoc = P.ConsumeToken();
1545 SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()};
1546 ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations);
1550 return P.ParseUnqualifiedId(ReductionIdScopeSpec, /*EnteringContext*/ false,
1551 /*AllowDestructorName*/ false,
1552 /*AllowConstructorName*/ false, nullptr,
1553 TemplateKWLoc, ReductionId);
1556 /// Parses clauses with list.
1557 bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind,
1558 OpenMPClauseKind Kind,
1559 SmallVectorImpl<Expr *> &Vars,
1560 OpenMPVarListDataTy &Data) {
1561 UnqualifiedId UnqualifiedReductionId;
1562 bool InvalidReductionId = false;
1563 bool MapTypeModifierSpecified = false;
1566 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1567 if (T.expectAndConsume(diag::err_expected_lparen_after,
1568 getOpenMPClauseName(Kind)))
1571 bool NeedRParenForLinear = false;
1572 BalancedDelimiterTracker LinearT(*this, tok::l_paren,
1573 tok::annot_pragma_openmp_end);
1574 // Handle reduction-identifier for reduction clause.
1575 if (Kind == OMPC_reduction) {
1576 ColonProtectionRAIIObject ColonRAII(*this);
1577 if (getLangOpts().CPlusPlus)
1578 ParseOptionalCXXScopeSpecifier(Data.ReductionIdScopeSpec,
1579 /*ObjectType=*/nullptr,
1580 /*EnteringContext=*/false);
1581 InvalidReductionId = ParseReductionId(*this, Data.ReductionIdScopeSpec,
1582 UnqualifiedReductionId);
1583 if (InvalidReductionId) {
1584 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
1587 if (Tok.is(tok::colon))
1588 Data.ColonLoc = ConsumeToken();
1590 Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier";
1591 if (!InvalidReductionId)
1593 Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId);
1594 } else if (Kind == OMPC_depend) {
1595 // Handle dependency type for depend clause.
1596 ColonProtectionRAIIObject ColonRAII(*this);
1598 static_cast<OpenMPDependClauseKind>(getOpenMPSimpleClauseType(
1599 Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : ""));
1600 Data.DepLinMapLoc = Tok.getLocation();
1602 if (Data.DepKind == OMPC_DEPEND_unknown) {
1603 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
1607 // Special processing for depend(source) clause.
1608 if (DKind == OMPD_ordered && Data.DepKind == OMPC_DEPEND_source) {
1614 if (Tok.is(tok::colon))
1615 Data.ColonLoc = ConsumeToken();
1617 Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren
1618 : diag::warn_pragma_expected_colon)
1619 << "dependency type";
1621 } else if (Kind == OMPC_linear) {
1622 // Try to parse modifier if any.
1623 if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) {
1624 Data.LinKind = static_cast<OpenMPLinearClauseKind>(
1625 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)));
1626 Data.DepLinMapLoc = ConsumeToken();
1627 LinearT.consumeOpen();
1628 NeedRParenForLinear = true;
1630 } else if (Kind == OMPC_map) {
1631 // Handle map type for map clause.
1632 ColonProtectionRAIIObject ColonRAII(*this);
1634 /// The map clause modifier token can be either a identifier or the C++
1636 auto &&IsMapClauseModifierToken = [](const Token &Tok) -> bool {
1637 return Tok.isOneOf(tok::identifier, tok::kw_delete);
1640 // The first identifier may be a list item, a map-type or a
1641 // map-type-modifier. The map modifier can also be delete which has the same
1642 // spelling of the C++ delete keyword.
1644 IsMapClauseModifierToken(Tok)
1645 ? static_cast<OpenMPMapClauseKind>(
1646 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)))
1648 Data.DepLinMapLoc = Tok.getLocation();
1649 bool ColonExpected = false;
1651 if (IsMapClauseModifierToken(Tok)) {
1652 if (PP.LookAhead(0).is(tok::colon)) {
1653 if (Data.MapType == OMPC_MAP_unknown)
1654 Diag(Tok, diag::err_omp_unknown_map_type);
1655 else if (Data.MapType == OMPC_MAP_always)
1656 Diag(Tok, diag::err_omp_map_type_missing);
1658 } else if (PP.LookAhead(0).is(tok::comma)) {
1659 if (IsMapClauseModifierToken(PP.LookAhead(1)) &&
1660 PP.LookAhead(2).is(tok::colon)) {
1661 Data.MapTypeModifier = Data.MapType;
1662 if (Data.MapTypeModifier != OMPC_MAP_always) {
1663 Diag(Tok, diag::err_omp_unknown_map_type_modifier);
1664 Data.MapTypeModifier = OMPC_MAP_unknown;
1666 MapTypeModifierSpecified = true;
1672 IsMapClauseModifierToken(Tok)
1673 ? static_cast<OpenMPMapClauseKind>(
1674 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)))
1676 if (Data.MapType == OMPC_MAP_unknown ||
1677 Data.MapType == OMPC_MAP_always)
1678 Diag(Tok, diag::err_omp_unknown_map_type);
1681 Data.MapType = OMPC_MAP_tofrom;
1682 Data.IsMapTypeImplicit = true;
1685 Data.MapType = OMPC_MAP_tofrom;
1686 Data.IsMapTypeImplicit = true;
1689 Data.MapType = OMPC_MAP_tofrom;
1690 Data.IsMapTypeImplicit = true;
1693 if (Tok.is(tok::colon))
1694 Data.ColonLoc = ConsumeToken();
1695 else if (ColonExpected)
1696 Diag(Tok, diag::warn_pragma_expected_colon) << "map type";
1700 (Kind != OMPC_reduction && Kind != OMPC_depend && Kind != OMPC_map) ||
1701 (Kind == OMPC_reduction && !InvalidReductionId) ||
1702 (Kind == OMPC_map && Data.MapType != OMPC_MAP_unknown &&
1703 (!MapTypeModifierSpecified ||
1704 Data.MapTypeModifier == OMPC_MAP_always)) ||
1705 (Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown);
1706 const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned);
1707 while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) &&
1708 Tok.isNot(tok::annot_pragma_openmp_end))) {
1709 ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
1711 ExprResult VarExpr =
1712 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
1713 if (VarExpr.isUsable())
1714 Vars.push_back(VarExpr.get());
1716 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1720 IsComma = Tok.is(tok::comma);
1723 else if (Tok.isNot(tok::r_paren) &&
1724 Tok.isNot(tok::annot_pragma_openmp_end) &&
1725 (!MayHaveTail || Tok.isNot(tok::colon)))
1726 Diag(Tok, diag::err_omp_expected_punc)
1727 << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush)
1728 : getOpenMPClauseName(Kind))
1729 << (Kind == OMPC_flush);
1732 // Parse ')' for linear clause with modifier.
1733 if (NeedRParenForLinear)
1734 LinearT.consumeClose();
1736 // Parse ':' linear-step (or ':' alignment).
1737 const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon);
1739 Data.ColonLoc = Tok.getLocation();
1740 SourceLocation ELoc = ConsumeToken();
1741 ExprResult Tail = ParseAssignmentExpression();
1742 Tail = Actions.ActOnFinishFullExpr(Tail.get(), ELoc);
1743 if (Tail.isUsable())
1744 Data.TailExpr = Tail.get();
1746 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1752 if ((Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown &&
1754 (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) ||
1755 (MustHaveTail && !Data.TailExpr) || InvalidReductionId)
1760 /// \brief Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate',
1761 /// 'shared', 'copyin', 'copyprivate', 'flush' or 'reduction'.
1764 /// 'private' '(' list ')'
1765 /// firstprivate-clause:
1766 /// 'firstprivate' '(' list ')'
1767 /// lastprivate-clause:
1768 /// 'lastprivate' '(' list ')'
1770 /// 'shared' '(' list ')'
1772 /// 'linear' '(' linear-list [ ':' linear-step ] ')'
1774 /// 'aligned' '(' list [ ':' alignment ] ')'
1775 /// reduction-clause:
1776 /// 'reduction' '(' reduction-identifier ':' list ')'
1777 /// copyprivate-clause:
1778 /// 'copyprivate' '(' list ')'
1780 /// 'flush' '(' list ')'
1782 /// 'depend' '(' in | out | inout : list | source ')'
1784 /// 'map' '(' [ [ always , ]
1785 /// to | from | tofrom | alloc | release | delete ':' ] list ')';
1787 /// 'to' '(' list ')'
1789 /// 'from' '(' list ')'
1790 /// use_device_ptr-clause:
1791 /// 'use_device_ptr' '(' list ')'
1792 /// is_device_ptr-clause:
1793 /// 'is_device_ptr' '(' list ')'
1795 /// For 'linear' clause linear-list may have the following forms:
1798 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
1799 OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
1800 OpenMPClauseKind Kind) {
1801 SourceLocation Loc = Tok.getLocation();
1802 SourceLocation LOpen = ConsumeToken();
1803 SmallVector<Expr *, 4> Vars;
1804 OpenMPVarListDataTy Data;
1806 if (ParseOpenMPVarList(DKind, Kind, Vars, Data))
1809 return Actions.ActOnOpenMPVarListClause(
1810 Kind, Vars, Data.TailExpr, Loc, LOpen, Data.ColonLoc, Tok.getLocation(),
1811 Data.ReductionIdScopeSpec, Data.ReductionId, Data.DepKind, Data.LinKind,
1812 Data.MapTypeModifier, Data.MapType, Data.IsMapTypeImplicit,