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, OMPD_simd, OMPD_target_teams_distribute_simd },
123 { OMPD_target_teams_distribute_parallel, OMPD_for, OMPD_target_teams_distribute_parallel_for },
124 { OMPD_target_teams_distribute_parallel_for, OMPD_simd, OMPD_target_teams_distribute_parallel_for_simd }
126 enum { CancellationPoint = 0, DeclareReduction = 1, TargetData = 2 };
127 auto Tok = P.getCurToken();
130 ? static_cast<unsigned>(OMPD_unknown)
131 : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
132 if (DKind == OMPD_unknown)
135 for (unsigned i = 0; i < llvm::array_lengthof(F); ++i) {
136 if (DKind != F[i][0])
139 Tok = P.getPreprocessor().LookAhead(0);
142 ? static_cast<unsigned>(OMPD_unknown)
143 : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
144 if (SDKind == OMPD_unknown)
147 if (SDKind == F[i][1]) {
152 return DKind < OMPD_unknown ? static_cast<OpenMPDirectiveKind>(DKind)
156 static DeclarationName parseOpenMPReductionId(Parser &P) {
157 Token Tok = P.getCurToken();
158 Sema &Actions = P.getActions();
159 OverloadedOperatorKind OOK = OO_None;
160 // Allow to use 'operator' keyword for C++ operators
161 bool WithOperator = false;
162 if (Tok.is(tok::kw_operator)) {
164 Tok = P.getCurToken();
167 switch (Tok.getKind()) {
168 case tok::plus: // '+'
171 case tok::minus: // '-'
174 case tok::star: // '*'
177 case tok::amp: // '&'
180 case tok::pipe: // '|'
183 case tok::caret: // '^'
186 case tok::ampamp: // '&&'
189 case tok::pipepipe: // '||'
192 case tok::identifier: // identifier
196 P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier);
197 P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
198 Parser::StopBeforeMatch);
199 return DeclarationName();
202 auto &DeclNames = Actions.getASTContext().DeclarationNames;
203 return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo())
204 : DeclNames.getCXXOperatorName(OOK);
207 /// \brief Parse 'omp declare reduction' construct.
209 /// declare-reduction-directive:
210 /// annot_pragma_openmp 'declare' 'reduction'
211 /// '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')'
212 /// ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')']
213 /// annot_pragma_openmp_end
214 /// <reduction_id> is either a base language identifier or one of the following
215 /// operators: '+', '-', '*', '&', '|', '^', '&&' and '||'.
217 Parser::DeclGroupPtrTy
218 Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) {
220 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
221 if (T.expectAndConsume(diag::err_expected_lparen_after,
222 getOpenMPDirectiveName(OMPD_declare_reduction))) {
223 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
224 return DeclGroupPtrTy();
227 DeclarationName Name = parseOpenMPReductionId(*this);
228 if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end))
229 return DeclGroupPtrTy();
232 bool IsCorrect = !ExpectAndConsume(tok::colon);
234 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
235 return DeclGroupPtrTy();
237 IsCorrect = IsCorrect && !Name.isEmpty();
239 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) {
240 Diag(Tok.getLocation(), diag::err_expected_type);
244 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
245 return DeclGroupPtrTy();
247 SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes;
248 // Parse list of types until ':' token.
250 ColonProtectionRAIIObject ColonRAII(*this);
252 TypeResult TR = ParseTypeName(&Range, Declarator::PrototypeContext, AS);
255 Actions.ActOnOpenMPDeclareReductionType(Range.getBegin(), TR);
256 if (!ReductionType.isNull()) {
257 ReductionTypes.push_back(
258 std::make_pair(ReductionType, Range.getBegin()));
261 SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end,
265 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end))
269 if (ExpectAndConsume(tok::comma)) {
271 if (Tok.is(tok::annot_pragma_openmp_end)) {
272 Diag(Tok.getLocation(), diag::err_expected_type);
273 return DeclGroupPtrTy();
276 } while (Tok.isNot(tok::annot_pragma_openmp_end));
278 if (ReductionTypes.empty()) {
279 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
280 return DeclGroupPtrTy();
283 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
284 return DeclGroupPtrTy();
287 if (ExpectAndConsume(tok::colon))
290 if (Tok.is(tok::annot_pragma_openmp_end)) {
291 Diag(Tok.getLocation(), diag::err_expected_expression);
292 return DeclGroupPtrTy();
295 DeclGroupPtrTy DRD = Actions.ActOnOpenMPDeclareReductionDirectiveStart(
296 getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes, AS);
298 // Parse <combiner> expression and then parse initializer if any for each
300 unsigned I = 0, E = ReductionTypes.size();
301 for (auto *D : DRD.get()) {
302 TentativeParsingAction TPA(*this);
303 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
304 Scope::OpenMPDirectiveScope);
305 // Parse <combiner> expression.
306 Actions.ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D);
307 ExprResult CombinerResult =
308 Actions.ActOnFinishFullExpr(ParseAssignmentExpression().get(),
309 D->getLocation(), /*DiscardedValue=*/true);
310 Actions.ActOnOpenMPDeclareReductionCombinerEnd(D, CombinerResult.get());
312 if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
313 Tok.isNot(tok::annot_pragma_openmp_end)) {
318 IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable();
319 ExprResult InitializerResult;
320 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
321 // Parse <initializer> expression.
322 if (Tok.is(tok::identifier) &&
323 Tok.getIdentifierInfo()->isStr("initializer"))
326 Diag(Tok.getLocation(), diag::err_expected) << "'initializer'";
332 BalancedDelimiterTracker T(*this, tok::l_paren,
333 tok::annot_pragma_openmp_end);
335 !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") &&
337 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
338 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
339 Scope::OpenMPDirectiveScope);
341 Actions.ActOnOpenMPDeclareReductionInitializerStart(getCurScope(), D);
342 InitializerResult = Actions.ActOnFinishFullExpr(
343 ParseAssignmentExpression().get(), D->getLocation(),
344 /*DiscardedValue=*/true);
345 Actions.ActOnOpenMPDeclareReductionInitializerEnd(
346 D, InitializerResult.get());
347 if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
348 Tok.isNot(tok::annot_pragma_openmp_end)) {
354 !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid();
359 // Revert parsing if not the last type, otherwise accept it, we're done with
366 return Actions.ActOnOpenMPDeclareReductionDirectiveEnd(getCurScope(), DRD,
371 /// RAII that recreates function context for correct parsing of clauses of
372 /// 'declare simd' construct.
373 /// OpenMP, 2.8.2 declare simd Construct
374 /// The expressions appearing in the clauses of this directive are evaluated in
375 /// the scope of the arguments of the function declaration or definition.
376 class FNContextRAII final {
378 Sema::CXXThisScopeRAII *ThisScope;
379 Parser::ParseScope *TempScope;
380 Parser::ParseScope *FnScope;
381 bool HasTemplateScope = false;
382 bool HasFunScope = false;
383 FNContextRAII() = delete;
384 FNContextRAII(const FNContextRAII &) = delete;
385 FNContextRAII &operator=(const FNContextRAII &) = delete;
388 FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P) {
389 Decl *D = *Ptr.get().begin();
390 NamedDecl *ND = dyn_cast<NamedDecl>(D);
391 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
392 Sema &Actions = P.getActions();
394 // Allow 'this' within late-parsed attributes.
395 ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, /*TypeQuals=*/0,
396 ND && ND->isCXXInstanceMember());
398 // If the Decl is templatized, add template parameters to scope.
399 HasTemplateScope = D->isTemplateDecl();
401 new Parser::ParseScope(&P, Scope::TemplateParamScope, HasTemplateScope);
402 if (HasTemplateScope)
403 Actions.ActOnReenterTemplateScope(Actions.getCurScope(), D);
405 // If the Decl is on a function, add function parameters to the scope.
406 HasFunScope = D->isFunctionOrFunctionTemplate();
407 FnScope = new Parser::ParseScope(&P, Scope::FnScope | Scope::DeclScope,
410 Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D);
414 P.getActions().ActOnExitFunctionContext();
415 FnScope->Exit(); // Pop scope, and remove Decls from IdResolver
417 if (HasTemplateScope)
426 /// Parses clauses for 'declare simd' directive.
428 /// 'inbranch' | 'notinbranch'
429 /// 'simdlen' '(' <expr> ')'
430 /// { 'uniform' '(' <argument_list> ')' }
431 /// { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' }
432 /// { 'linear '(' <argument_list> [ ':' <step> ] ')' }
433 static bool parseDeclareSimdClauses(
434 Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen,
435 SmallVectorImpl<Expr *> &Uniforms, SmallVectorImpl<Expr *> &Aligneds,
436 SmallVectorImpl<Expr *> &Alignments, SmallVectorImpl<Expr *> &Linears,
437 SmallVectorImpl<unsigned> &LinModifiers, SmallVectorImpl<Expr *> &Steps) {
439 const Token &Tok = P.getCurToken();
440 bool IsError = false;
441 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
442 if (Tok.isNot(tok::identifier))
444 OMPDeclareSimdDeclAttr::BranchStateTy Out;
445 IdentifierInfo *II = Tok.getIdentifierInfo();
446 StringRef ClauseName = II->getName();
447 // Parse 'inranch|notinbranch' clauses.
448 if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) {
449 if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) {
450 P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch)
452 << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange;
456 BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc());
458 } else if (ClauseName.equals("simdlen")) {
459 if (SimdLen.isUsable()) {
460 P.Diag(Tok, diag::err_omp_more_one_clause)
461 << getOpenMPDirectiveName(OMPD_declare_simd) << ClauseName << 0;
466 SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc);
467 if (SimdLen.isInvalid())
470 OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName);
471 if (CKind == OMPC_uniform || CKind == OMPC_aligned ||
472 CKind == OMPC_linear) {
473 Parser::OpenMPVarListDataTy Data;
474 auto *Vars = &Uniforms;
475 if (CKind == OMPC_aligned)
477 else if (CKind == OMPC_linear)
481 if (P.ParseOpenMPVarList(OMPD_declare_simd,
482 getOpenMPClauseKind(ClauseName), *Vars, Data))
484 if (CKind == OMPC_aligned)
485 Alignments.append(Aligneds.size() - Alignments.size(), Data.TailExpr);
486 else if (CKind == OMPC_linear) {
487 if (P.getActions().CheckOpenMPLinearModifier(Data.LinKind,
489 Data.LinKind = OMPC_LINEAR_val;
490 LinModifiers.append(Linears.size() - LinModifiers.size(),
492 Steps.append(Linears.size() - Steps.size(), Data.TailExpr);
495 // TODO: add parsing of other clauses.
499 if (Tok.is(tok::comma))
505 /// Parse clauses for '#pragma omp declare simd'.
506 Parser::DeclGroupPtrTy
507 Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr,
508 CachedTokens &Toks, SourceLocation Loc) {
510 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
511 // Consume the previously pushed token.
512 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
514 FNContextRAII FnContext(*this, Ptr);
515 OMPDeclareSimdDeclAttr::BranchStateTy BS =
516 OMPDeclareSimdDeclAttr::BS_Undefined;
518 SmallVector<Expr *, 4> Uniforms;
519 SmallVector<Expr *, 4> Aligneds;
520 SmallVector<Expr *, 4> Alignments;
521 SmallVector<Expr *, 4> Linears;
522 SmallVector<unsigned, 4> LinModifiers;
523 SmallVector<Expr *, 4> Steps;
525 parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds,
526 Alignments, Linears, LinModifiers, Steps);
527 // Need to check for extra tokens.
528 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
529 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
530 << getOpenMPDirectiveName(OMPD_declare_simd);
531 while (Tok.isNot(tok::annot_pragma_openmp_end))
534 // Skip the last annot_pragma_openmp_end.
535 SourceLocation EndLoc = ConsumeToken();
537 return Actions.ActOnOpenMPDeclareSimdDirective(
538 Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears,
539 LinModifiers, Steps, SourceRange(Loc, EndLoc));
544 /// \brief Parsing of declarative OpenMP directives.
546 /// threadprivate-directive:
547 /// annot_pragma_openmp 'threadprivate' simple-variable-list
548 /// annot_pragma_openmp_end
550 /// declare-reduction-directive:
551 /// annot_pragma_openmp 'declare' 'reduction' [...]
552 /// annot_pragma_openmp_end
554 /// declare-simd-directive:
555 /// annot_pragma_openmp 'declare simd' {<clause> [,]}
556 /// annot_pragma_openmp_end
557 /// <function declaration/definition>
559 Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
560 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
561 DeclSpec::TST TagType, Decl *Tag) {
562 assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
563 ParenBraceBracketBalancer BalancerRAIIObj(*this);
565 SourceLocation Loc = ConsumeToken();
566 auto DKind = ParseOpenMPDirectiveKind(*this);
569 case OMPD_threadprivate: {
571 ThreadprivateListParserHelper Helper(this);
572 if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Helper, true)) {
573 // The last seen token is annot_pragma_openmp_end - need to check for
575 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
576 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
577 << getOpenMPDirectiveName(OMPD_threadprivate);
578 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
580 // Skip the last annot_pragma_openmp_end.
582 return Actions.ActOnOpenMPThreadprivateDirective(Loc,
583 Helper.getIdentifiers());
587 case OMPD_declare_reduction:
589 if (auto Res = ParseOpenMPDeclareReductionDirective(AS)) {
590 // The last seen token is annot_pragma_openmp_end - need to check for
592 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
593 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
594 << getOpenMPDirectiveName(OMPD_declare_reduction);
595 while (Tok.isNot(tok::annot_pragma_openmp_end))
598 // Skip the last annot_pragma_openmp_end.
603 case OMPD_declare_simd: {
605 // { #pragma omp declare simd }
606 // <function-declaration-or-definition>
610 while(Tok.isNot(tok::annot_pragma_openmp_end)) {
618 if (Tok.is(tok::annot_pragma_openmp))
619 Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, TagType, Tag);
620 else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
621 // Here we expect to see some function declaration.
623 assert(TagType == DeclSpec::TST_unspecified);
624 MaybeParseCXX11Attributes(Attrs);
625 ParsingDeclSpec PDS(*this);
626 Ptr = ParseExternalDeclaration(Attrs, &PDS);
629 ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag);
633 Diag(Loc, diag::err_omp_decl_in_declare_simd);
634 return DeclGroupPtrTy();
636 return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc);
638 case OMPD_declare_target: {
639 SourceLocation DTLoc = ConsumeAnyToken();
640 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
641 // OpenMP 4.5 syntax with list of entities.
642 llvm::SmallSetVector<const NamedDecl*, 16> SameDirectiveDecls;
643 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
644 OMPDeclareTargetDeclAttr::MapTypeTy MT =
645 OMPDeclareTargetDeclAttr::MT_To;
646 if (Tok.is(tok::identifier)) {
647 IdentifierInfo *II = Tok.getIdentifierInfo();
648 StringRef ClauseName = II->getName();
649 // Parse 'to|link' clauses.
650 if (!OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName,
652 Diag(Tok, diag::err_omp_declare_target_unexpected_clause)
658 auto Callback = [this, MT, &SameDirectiveDecls](
659 CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
660 Actions.ActOnOpenMPDeclareTargetName(getCurScope(), SS, NameInfo, MT,
663 if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback, true))
666 // Consume optional ','.
667 if (Tok.is(tok::comma))
670 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
672 return DeclGroupPtrTy();
675 // Skip the last annot_pragma_openmp_end.
678 if (!Actions.ActOnStartOpenMPDeclareTargetDirective(DTLoc))
679 return DeclGroupPtrTy();
681 DKind = ParseOpenMPDirectiveKind(*this);
682 while (DKind != OMPD_end_declare_target && DKind != OMPD_declare_target &&
683 Tok.isNot(tok::eof) && Tok.isNot(tok::r_brace)) {
684 ParsedAttributesWithRange attrs(AttrFactory);
685 MaybeParseCXX11Attributes(attrs);
686 ParseExternalDeclaration(attrs);
687 if (Tok.isAnnotation() && Tok.is(tok::annot_pragma_openmp)) {
688 TentativeParsingAction TPA(*this);
690 DKind = ParseOpenMPDirectiveKind(*this);
691 if (DKind != OMPD_end_declare_target)
698 if (DKind == OMPD_end_declare_target) {
700 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
701 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
702 << getOpenMPDirectiveName(OMPD_end_declare_target);
703 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
705 // Skip the last annot_pragma_openmp_end.
708 Diag(Tok, diag::err_expected_end_declare_target);
709 Diag(DTLoc, diag::note_matching) << "'#pragma omp declare target'";
711 Actions.ActOnFinishOpenMPDeclareTargetDirective();
712 return DeclGroupPtrTy();
715 Diag(Tok, diag::err_omp_unknown_directive);
733 case OMPD_parallel_for:
734 case OMPD_parallel_for_simd:
735 case OMPD_parallel_sections:
739 case OMPD_cancellation_point:
741 case OMPD_target_data:
742 case OMPD_target_enter_data:
743 case OMPD_target_exit_data:
744 case OMPD_target_parallel:
745 case OMPD_target_parallel_for:
747 case OMPD_taskloop_simd:
748 case OMPD_distribute:
749 case OMPD_end_declare_target:
750 case OMPD_target_update:
751 case OMPD_distribute_parallel_for:
752 case OMPD_distribute_parallel_for_simd:
753 case OMPD_distribute_simd:
754 case OMPD_target_parallel_for_simd:
755 case OMPD_target_simd:
756 case OMPD_teams_distribute:
757 case OMPD_teams_distribute_simd:
758 case OMPD_teams_distribute_parallel_for_simd:
759 case OMPD_teams_distribute_parallel_for:
760 case OMPD_target_teams:
761 case OMPD_target_teams_distribute:
762 case OMPD_target_teams_distribute_parallel_for:
763 case OMPD_target_teams_distribute_parallel_for_simd:
764 case OMPD_target_teams_distribute_simd:
765 Diag(Tok, diag::err_omp_unexpected_directive)
766 << getOpenMPDirectiveName(DKind);
769 while (Tok.isNot(tok::annot_pragma_openmp_end))
775 /// \brief Parsing of declarative or executable OpenMP directives.
777 /// threadprivate-directive:
778 /// annot_pragma_openmp 'threadprivate' simple-variable-list
779 /// annot_pragma_openmp_end
781 /// declare-reduction-directive:
782 /// annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':'
783 /// <type> {',' <type>} ':' <expression> ')' ['initializer' '('
784 /// ('omp_priv' '=' <expression>|<function_call>) ')']
785 /// annot_pragma_openmp_end
787 /// executable-directive:
788 /// annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
789 /// 'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
790 /// 'parallel for' | 'parallel sections' | 'task' | 'taskyield' |
791 /// 'barrier' | 'taskwait' | 'flush' | 'ordered' | 'atomic' |
792 /// 'for simd' | 'parallel for simd' | 'target' | 'target data' |
793 /// 'taskgroup' | 'teams' | 'taskloop' | 'taskloop simd' |
794 /// 'distribute' | 'target enter data' | 'target exit data' |
795 /// 'target parallel' | 'target parallel for' |
796 /// 'target update' | 'distribute parallel for' |
797 /// 'distribute paralle for simd' | 'distribute simd' |
798 /// 'target parallel for simd' | 'target simd' |
799 /// 'teams distribute' | 'teams distribute simd' |
800 /// 'teams distribute parallel for simd' |
801 /// 'teams distribute parallel for' | 'target teams' |
802 /// 'target teams distribute' |
803 /// 'target teams distribute parallel for' |
804 /// 'target teams distribute parallel for simd' |
805 /// 'target teams distribute simd' {clause}
806 /// annot_pragma_openmp_end
808 StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
809 AllowedContsructsKind Allowed) {
810 assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
811 ParenBraceBracketBalancer BalancerRAIIObj(*this);
812 SmallVector<OMPClause *, 5> Clauses;
813 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, OMPC_unknown + 1>
814 FirstClauses(OMPC_unknown + 1);
815 unsigned ScopeFlags =
816 Scope::FnScope | Scope::DeclScope | Scope::OpenMPDirectiveScope;
817 SourceLocation Loc = ConsumeToken(), EndLoc;
818 auto DKind = ParseOpenMPDirectiveKind(*this);
819 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
820 // Name of critical directive.
821 DeclarationNameInfo DirName;
822 StmtResult Directive = StmtError();
823 bool HasAssociatedStatement = true;
824 bool FlushHasClause = false;
827 case OMPD_threadprivate: {
828 if (Allowed != ACK_Any) {
829 Diag(Tok, diag::err_omp_immediate_directive)
830 << getOpenMPDirectiveName(DKind) << 0;
833 ThreadprivateListParserHelper Helper(this);
834 if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Helper, false)) {
835 // The last seen token is annot_pragma_openmp_end - need to check for
837 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
838 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
839 << getOpenMPDirectiveName(OMPD_threadprivate);
840 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
842 DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective(
843 Loc, Helper.getIdentifiers());
844 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
846 SkipUntil(tok::annot_pragma_openmp_end);
849 case OMPD_declare_reduction:
851 if (auto Res = ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) {
852 // The last seen token is annot_pragma_openmp_end - need to check for
854 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
855 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
856 << getOpenMPDirectiveName(OMPD_declare_reduction);
857 while (Tok.isNot(tok::annot_pragma_openmp_end))
861 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
863 SkipUntil(tok::annot_pragma_openmp_end);
866 if (PP.LookAhead(0).is(tok::l_paren)) {
867 FlushHasClause = true;
868 // Push copy of the current token back to stream to properly parse
869 // pseudo-clause OMPFlushClause.
875 case OMPD_cancellation_point:
877 case OMPD_target_enter_data:
878 case OMPD_target_exit_data:
879 case OMPD_target_update:
880 if (Allowed == ACK_StatementsOpenMPNonStandalone) {
881 Diag(Tok, diag::err_omp_immediate_directive)
882 << getOpenMPDirectiveName(DKind) << 0;
884 HasAssociatedStatement = false;
885 // Fall through for further analysis.
895 case OMPD_parallel_for:
896 case OMPD_parallel_for_simd:
897 case OMPD_parallel_sections:
904 case OMPD_target_data:
905 case OMPD_target_parallel:
906 case OMPD_target_parallel_for:
908 case OMPD_taskloop_simd:
909 case OMPD_distribute:
910 case OMPD_distribute_parallel_for:
911 case OMPD_distribute_parallel_for_simd:
912 case OMPD_distribute_simd:
913 case OMPD_target_parallel_for_simd:
914 case OMPD_target_simd:
915 case OMPD_teams_distribute:
916 case OMPD_teams_distribute_simd:
917 case OMPD_teams_distribute_parallel_for_simd:
918 case OMPD_teams_distribute_parallel_for:
919 case OMPD_target_teams:
920 case OMPD_target_teams_distribute:
921 case OMPD_target_teams_distribute_parallel_for:
922 case OMPD_target_teams_distribute_parallel_for_simd:
923 case OMPD_target_teams_distribute_simd: {
925 // Parse directive name of the 'critical' directive if any.
926 if (DKind == OMPD_critical) {
927 BalancedDelimiterTracker T(*this, tok::l_paren,
928 tok::annot_pragma_openmp_end);
929 if (!T.consumeOpen()) {
930 if (Tok.isAnyIdentifier()) {
932 DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation());
935 Diag(Tok, diag::err_omp_expected_identifier_for_critical);
939 } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) {
940 CancelRegion = ParseOpenMPDirectiveKind(*this);
941 if (Tok.isNot(tok::annot_pragma_openmp_end))
945 if (isOpenMPLoopDirective(DKind))
946 ScopeFlags |= Scope::OpenMPLoopDirectiveScope;
947 if (isOpenMPSimdDirective(DKind))
948 ScopeFlags |= Scope::OpenMPSimdDirectiveScope;
949 ParseScope OMPDirectiveScope(this, ScopeFlags);
950 Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc);
952 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
953 OpenMPClauseKind CKind =
956 : FlushHasClause ? OMPC_flush
957 : getOpenMPClauseKind(PP.getSpelling(Tok));
958 Actions.StartOpenMPClause(CKind);
959 FlushHasClause = false;
961 ParseOpenMPClause(DKind, CKind, !FirstClauses[CKind].getInt());
962 FirstClauses[CKind].setInt(true);
964 FirstClauses[CKind].setPointer(Clause);
965 Clauses.push_back(Clause);
969 if (Tok.is(tok::comma))
971 Actions.EndOpenMPClause();
973 // End location of the directive.
974 EndLoc = Tok.getLocation();
975 // Consume final annot_pragma_openmp_end.
978 // OpenMP [2.13.8, ordered Construct, Syntax]
979 // If the depend clause is specified, the ordered construct is a stand-alone
981 if (DKind == OMPD_ordered && FirstClauses[OMPC_depend].getInt()) {
982 if (Allowed == ACK_StatementsOpenMPNonStandalone) {
983 Diag(Loc, diag::err_omp_immediate_directive)
984 << getOpenMPDirectiveName(DKind) << 1
985 << getOpenMPClauseName(OMPC_depend);
987 HasAssociatedStatement = false;
990 StmtResult AssociatedStmt;
991 if (HasAssociatedStatement) {
992 // The body is a block scope like in Lambdas and Blocks.
993 Sema::CompoundScopeRAII CompoundScope(Actions);
994 Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
995 Actions.ActOnStartOfCompoundStmt();
997 AssociatedStmt = ParseStatement();
998 Actions.ActOnFinishOfCompoundStmt();
999 AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
1001 Directive = Actions.ActOnOpenMPExecutableDirective(
1002 DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc,
1006 Actions.EndOpenMPDSABlock(Directive.get());
1007 OMPDirectiveScope.Exit();
1010 case OMPD_declare_simd:
1011 case OMPD_declare_target:
1012 case OMPD_end_declare_target:
1013 Diag(Tok, diag::err_omp_unexpected_directive)
1014 << getOpenMPDirectiveName(DKind);
1015 SkipUntil(tok::annot_pragma_openmp_end);
1018 Diag(Tok, diag::err_omp_unknown_directive);
1019 SkipUntil(tok::annot_pragma_openmp_end);
1025 // Parses simple list:
1026 // simple-variable-list:
1027 // '(' id-expression {, id-expression} ')'
1029 bool Parser::ParseOpenMPSimpleVarList(
1030 OpenMPDirectiveKind Kind,
1031 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
1033 bool AllowScopeSpecifier) {
1035 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1036 if (T.expectAndConsume(diag::err_expected_lparen_after,
1037 getOpenMPDirectiveName(Kind)))
1039 bool IsCorrect = true;
1040 bool NoIdentIsFound = true;
1042 // Read tokens while ')' or annot_pragma_openmp_end is not found.
1043 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
1045 SourceLocation TemplateKWLoc;
1048 Token PrevTok = Tok;
1049 NoIdentIsFound = false;
1051 if (AllowScopeSpecifier && getLangOpts().CPlusPlus &&
1052 ParseOptionalCXXScopeSpecifier(SS, nullptr, false)) {
1054 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1056 } else if (ParseUnqualifiedId(SS, false, false, false, nullptr,
1057 TemplateKWLoc, Name)) {
1059 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1061 } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) &&
1062 Tok.isNot(tok::annot_pragma_openmp_end)) {
1064 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1066 Diag(PrevTok.getLocation(), diag::err_expected)
1068 << SourceRange(PrevTok.getLocation(), PrevTokLocation);
1070 Callback(SS, Actions.GetNameFromUnqualifiedId(Name));
1073 if (Tok.is(tok::comma)) {
1078 if (NoIdentIsFound) {
1079 Diag(Tok, diag::err_expected) << tok::identifier;
1084 IsCorrect = !T.consumeClose() && IsCorrect;
1089 /// \brief Parsing of OpenMP clauses.
1092 /// if-clause | final-clause | num_threads-clause | safelen-clause |
1093 /// default-clause | private-clause | firstprivate-clause | shared-clause
1094 /// | linear-clause | aligned-clause | collapse-clause |
1095 /// lastprivate-clause | reduction-clause | proc_bind-clause |
1096 /// schedule-clause | copyin-clause | copyprivate-clause | untied-clause |
1097 /// mergeable-clause | flush-clause | read-clause | write-clause |
1098 /// update-clause | capture-clause | seq_cst-clause | device-clause |
1099 /// simdlen-clause | threads-clause | simd-clause | num_teams-clause |
1100 /// thread_limit-clause | priority-clause | grainsize-clause |
1101 /// nogroup-clause | num_tasks-clause | hint-clause | to-clause |
1102 /// from-clause | is_device_ptr-clause
1104 OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind,
1105 OpenMPClauseKind CKind, bool FirstClause) {
1106 OMPClause *Clause = nullptr;
1107 bool ErrorFound = false;
1108 // Check if clause is allowed for the given directive.
1109 if (CKind != OMPC_unknown && !isAllowedClauseForDirective(DKind, CKind)) {
1110 Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind)
1111 << getOpenMPDirectiveName(DKind);
1117 case OMPC_num_threads:
1123 case OMPC_num_teams:
1124 case OMPC_thread_limit:
1126 case OMPC_grainsize:
1127 case OMPC_num_tasks:
1129 // OpenMP [2.5, Restrictions]
1130 // At most one num_threads clause can appear on the directive.
1131 // OpenMP [2.8.1, simd construct, Restrictions]
1132 // Only one safelen clause can appear on a simd directive.
1133 // Only one simdlen clause can appear on a simd directive.
1134 // Only one collapse clause can appear on a simd directive.
1135 // OpenMP [2.9.1, target data construct, Restrictions]
1136 // At most one device clause can appear on the directive.
1137 // OpenMP [2.11.1, task Construct, Restrictions]
1138 // At most one if clause can appear on the directive.
1139 // At most one final clause can appear on the directive.
1140 // OpenMP [teams Construct, Restrictions]
1141 // At most one num_teams clause can appear on the directive.
1142 // At most one thread_limit clause can appear on the directive.
1143 // OpenMP [2.9.1, task Construct, Restrictions]
1144 // At most one priority clause can appear on the directive.
1145 // OpenMP [2.9.2, taskloop Construct, Restrictions]
1146 // At most one grainsize clause can appear on the directive.
1147 // OpenMP [2.9.2, taskloop Construct, Restrictions]
1148 // At most one num_tasks clause can appear on the directive.
1150 Diag(Tok, diag::err_omp_more_one_clause)
1151 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1155 if (CKind == OMPC_ordered && PP.LookAhead(/*N=*/0).isNot(tok::l_paren))
1156 Clause = ParseOpenMPClause(CKind);
1158 Clause = ParseOpenMPSingleExprClause(CKind);
1161 case OMPC_proc_bind:
1162 // OpenMP [2.14.3.1, Restrictions]
1163 // Only a single default clause may be specified on a parallel, task or
1165 // OpenMP [2.5, parallel Construct, Restrictions]
1166 // At most one proc_bind clause can appear on the directive.
1168 Diag(Tok, diag::err_omp_more_one_clause)
1169 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1173 Clause = ParseOpenMPSimpleClause(CKind);
1176 case OMPC_dist_schedule:
1177 case OMPC_defaultmap:
1178 // OpenMP [2.7.1, Restrictions, p. 3]
1179 // Only one schedule clause can appear on a loop directive.
1180 // OpenMP [2.10.4, Restrictions, p. 106]
1181 // At most one defaultmap clause can appear on the directive.
1183 Diag(Tok, diag::err_omp_more_one_clause)
1184 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1189 Clause = ParseOpenMPSingleExprWithArgClause(CKind);
1193 case OMPC_mergeable:
1202 // OpenMP [2.7.1, Restrictions, p. 9]
1203 // Only one ordered clause can appear on a loop directive.
1204 // OpenMP [2.7.1, Restrictions, C/C++, p. 4]
1205 // Only one nowait clause can appear on a for directive.
1207 Diag(Tok, diag::err_omp_more_one_clause)
1208 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1212 Clause = ParseOpenMPClause(CKind);
1215 case OMPC_firstprivate:
1216 case OMPC_lastprivate:
1218 case OMPC_reduction:
1222 case OMPC_copyprivate:
1228 case OMPC_use_device_ptr:
1229 case OMPC_is_device_ptr:
1230 Clause = ParseOpenMPVarListClause(DKind, CKind);
1233 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
1234 << getOpenMPDirectiveName(DKind);
1235 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1237 case OMPC_threadprivate:
1239 Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind)
1240 << getOpenMPDirectiveName(DKind);
1241 SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch);
1244 return ErrorFound ? nullptr : Clause;
1247 /// Parses simple expression in parens for single-expression clauses of OpenMP
1249 /// \param RLoc Returned location of right paren.
1250 ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName,
1251 SourceLocation &RLoc) {
1252 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1253 if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data()))
1256 SourceLocation ELoc = Tok.getLocation();
1257 ExprResult LHS(ParseCastExpression(
1258 /*isUnaryExpression=*/false, /*isAddressOfOperand=*/false, NotTypeCast));
1259 ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
1260 Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc);
1265 RLoc = T.getCloseLocation();
1269 /// \brief Parsing of OpenMP clauses with single expressions like 'final',
1270 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
1271 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks' or 'hint'.
1274 /// 'final' '(' expression ')'
1276 /// num_threads-clause:
1277 /// 'num_threads' '(' expression ')'
1280 /// 'safelen' '(' expression ')'
1283 /// 'simdlen' '(' expression ')'
1285 /// collapse-clause:
1286 /// 'collapse' '(' expression ')'
1288 /// priority-clause:
1289 /// 'priority' '(' expression ')'
1291 /// grainsize-clause:
1292 /// 'grainsize' '(' expression ')'
1294 /// num_tasks-clause:
1295 /// 'num_tasks' '(' expression ')'
1298 /// 'hint' '(' expression ')'
1300 OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind) {
1301 SourceLocation Loc = ConsumeToken();
1302 SourceLocation LLoc = Tok.getLocation();
1303 SourceLocation RLoc;
1305 ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
1307 if (Val.isInvalid())
1310 return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc);
1313 /// \brief Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
1316 /// 'default' '(' 'none' | 'shared' ')
1318 /// proc_bind-clause:
1319 /// 'proc_bind' '(' 'master' | 'close' | 'spread' ')
1321 OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind) {
1322 SourceLocation Loc = Tok.getLocation();
1323 SourceLocation LOpen = ConsumeToken();
1325 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1326 if (T.expectAndConsume(diag::err_expected_lparen_after,
1327 getOpenMPClauseName(Kind)))
1330 unsigned Type = getOpenMPSimpleClauseType(
1331 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1332 SourceLocation TypeLoc = Tok.getLocation();
1333 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1334 Tok.isNot(tok::annot_pragma_openmp_end))
1340 return Actions.ActOnOpenMPSimpleClause(Kind, Type, TypeLoc, LOpen, Loc,
1344 /// \brief Parsing of OpenMP clauses like 'ordered'.
1355 /// mergeable-clause:
1370 OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind) {
1371 SourceLocation Loc = Tok.getLocation();
1374 return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation());
1378 /// \brief Parsing of OpenMP clauses with single expressions and some additional
1379 /// argument like 'schedule' or 'dist_schedule'.
1381 /// schedule-clause:
1382 /// 'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
1386 /// 'if' '(' [ directive-name-modifier ':' ] expression ')'
1389 /// 'defaultmap' '(' modifier ':' kind ')'
1391 OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind) {
1392 SourceLocation Loc = ConsumeToken();
1393 SourceLocation DelimLoc;
1395 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1396 if (T.expectAndConsume(diag::err_expected_lparen_after,
1397 getOpenMPClauseName(Kind)))
1401 SmallVector<unsigned, 4> Arg;
1402 SmallVector<SourceLocation, 4> KLoc;
1403 if (Kind == OMPC_schedule) {
1404 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
1405 Arg.resize(NumberOfElements);
1406 KLoc.resize(NumberOfElements);
1407 Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown;
1408 Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown;
1409 Arg[ScheduleKind] = OMPC_SCHEDULE_unknown;
1410 auto KindModifier = getOpenMPSimpleClauseType(
1411 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1412 if (KindModifier > OMPC_SCHEDULE_unknown) {
1414 Arg[Modifier1] = KindModifier;
1415 KLoc[Modifier1] = Tok.getLocation();
1416 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1417 Tok.isNot(tok::annot_pragma_openmp_end))
1419 if (Tok.is(tok::comma)) {
1420 // Parse ',' 'modifier'
1422 KindModifier = getOpenMPSimpleClauseType(
1423 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1424 Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown
1426 : (unsigned)OMPC_SCHEDULE_unknown;
1427 KLoc[Modifier2] = Tok.getLocation();
1428 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1429 Tok.isNot(tok::annot_pragma_openmp_end))
1433 if (Tok.is(tok::colon))
1436 Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier";
1437 KindModifier = getOpenMPSimpleClauseType(
1438 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1440 Arg[ScheduleKind] = KindModifier;
1441 KLoc[ScheduleKind] = Tok.getLocation();
1442 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1443 Tok.isNot(tok::annot_pragma_openmp_end))
1445 if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static ||
1446 Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic ||
1447 Arg[ScheduleKind] == OMPC_SCHEDULE_guided) &&
1449 DelimLoc = ConsumeAnyToken();
1450 } else if (Kind == OMPC_dist_schedule) {
1451 Arg.push_back(getOpenMPSimpleClauseType(
1452 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1453 KLoc.push_back(Tok.getLocation());
1454 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1455 Tok.isNot(tok::annot_pragma_openmp_end))
1457 if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma))
1458 DelimLoc = ConsumeAnyToken();
1459 } else if (Kind == OMPC_defaultmap) {
1460 // Get a defaultmap modifier
1461 Arg.push_back(getOpenMPSimpleClauseType(
1462 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1463 KLoc.push_back(Tok.getLocation());
1464 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1465 Tok.isNot(tok::annot_pragma_openmp_end))
1468 if (Tok.is(tok::colon))
1470 else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown)
1471 Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier";
1472 // Get a defaultmap kind
1473 Arg.push_back(getOpenMPSimpleClauseType(
1474 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1475 KLoc.push_back(Tok.getLocation());
1476 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1477 Tok.isNot(tok::annot_pragma_openmp_end))
1480 assert(Kind == OMPC_if);
1481 KLoc.push_back(Tok.getLocation());
1482 TentativeParsingAction TPA(*this);
1483 Arg.push_back(ParseOpenMPDirectiveKind(*this));
1484 if (Arg.back() != OMPD_unknown) {
1486 if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) {
1488 DelimLoc = ConsumeToken();
1491 Arg.back() = OMPD_unknown;
1497 bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) ||
1498 (Kind == OMPC_dist_schedule && DelimLoc.isValid()) ||
1500 if (NeedAnExpression) {
1501 SourceLocation ELoc = Tok.getLocation();
1502 ExprResult LHS(ParseCastExpression(false, false, NotTypeCast));
1503 Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
1504 Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc);
1510 if (NeedAnExpression && Val.isInvalid())
1513 return Actions.ActOnOpenMPSingleExprWithArgClause(
1514 Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc,
1515 T.getCloseLocation());
1518 static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec,
1519 UnqualifiedId &ReductionId) {
1520 SourceLocation TemplateKWLoc;
1521 if (ReductionIdScopeSpec.isEmpty()) {
1523 switch (P.getCurToken().getKind()) {
1551 if (OOK != OO_None) {
1552 SourceLocation OpLoc = P.ConsumeToken();
1553 SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()};
1554 ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations);
1558 return P.ParseUnqualifiedId(ReductionIdScopeSpec, /*EnteringContext*/ false,
1559 /*AllowDestructorName*/ false,
1560 /*AllowConstructorName*/ false, nullptr,
1561 TemplateKWLoc, ReductionId);
1564 /// Parses clauses with list.
1565 bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind,
1566 OpenMPClauseKind Kind,
1567 SmallVectorImpl<Expr *> &Vars,
1568 OpenMPVarListDataTy &Data) {
1569 UnqualifiedId UnqualifiedReductionId;
1570 bool InvalidReductionId = false;
1571 bool MapTypeModifierSpecified = false;
1574 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1575 if (T.expectAndConsume(diag::err_expected_lparen_after,
1576 getOpenMPClauseName(Kind)))
1579 bool NeedRParenForLinear = false;
1580 BalancedDelimiterTracker LinearT(*this, tok::l_paren,
1581 tok::annot_pragma_openmp_end);
1582 // Handle reduction-identifier for reduction clause.
1583 if (Kind == OMPC_reduction) {
1584 ColonProtectionRAIIObject ColonRAII(*this);
1585 if (getLangOpts().CPlusPlus)
1586 ParseOptionalCXXScopeSpecifier(Data.ReductionIdScopeSpec,
1587 /*ObjectType=*/nullptr,
1588 /*EnteringContext=*/false);
1589 InvalidReductionId = ParseReductionId(*this, Data.ReductionIdScopeSpec,
1590 UnqualifiedReductionId);
1591 if (InvalidReductionId) {
1592 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
1595 if (Tok.is(tok::colon))
1596 Data.ColonLoc = ConsumeToken();
1598 Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier";
1599 if (!InvalidReductionId)
1601 Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId);
1602 } else if (Kind == OMPC_depend) {
1603 // Handle dependency type for depend clause.
1604 ColonProtectionRAIIObject ColonRAII(*this);
1606 static_cast<OpenMPDependClauseKind>(getOpenMPSimpleClauseType(
1607 Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : ""));
1608 Data.DepLinMapLoc = Tok.getLocation();
1610 if (Data.DepKind == OMPC_DEPEND_unknown) {
1611 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
1615 // Special processing for depend(source) clause.
1616 if (DKind == OMPD_ordered && Data.DepKind == OMPC_DEPEND_source) {
1622 if (Tok.is(tok::colon))
1623 Data.ColonLoc = ConsumeToken();
1625 Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren
1626 : diag::warn_pragma_expected_colon)
1627 << "dependency type";
1629 } else if (Kind == OMPC_linear) {
1630 // Try to parse modifier if any.
1631 if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) {
1632 Data.LinKind = static_cast<OpenMPLinearClauseKind>(
1633 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)));
1634 Data.DepLinMapLoc = ConsumeToken();
1635 LinearT.consumeOpen();
1636 NeedRParenForLinear = true;
1638 } else if (Kind == OMPC_map) {
1639 // Handle map type for map clause.
1640 ColonProtectionRAIIObject ColonRAII(*this);
1642 /// The map clause modifier token can be either a identifier or the C++
1644 auto &&IsMapClauseModifierToken = [](const Token &Tok) -> bool {
1645 return Tok.isOneOf(tok::identifier, tok::kw_delete);
1648 // The first identifier may be a list item, a map-type or a
1649 // map-type-modifier. The map modifier can also be delete which has the same
1650 // spelling of the C++ delete keyword.
1652 IsMapClauseModifierToken(Tok)
1653 ? static_cast<OpenMPMapClauseKind>(
1654 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)))
1656 Data.DepLinMapLoc = Tok.getLocation();
1657 bool ColonExpected = false;
1659 if (IsMapClauseModifierToken(Tok)) {
1660 if (PP.LookAhead(0).is(tok::colon)) {
1661 if (Data.MapType == OMPC_MAP_unknown)
1662 Diag(Tok, diag::err_omp_unknown_map_type);
1663 else if (Data.MapType == OMPC_MAP_always)
1664 Diag(Tok, diag::err_omp_map_type_missing);
1666 } else if (PP.LookAhead(0).is(tok::comma)) {
1667 if (IsMapClauseModifierToken(PP.LookAhead(1)) &&
1668 PP.LookAhead(2).is(tok::colon)) {
1669 Data.MapTypeModifier = Data.MapType;
1670 if (Data.MapTypeModifier != OMPC_MAP_always) {
1671 Diag(Tok, diag::err_omp_unknown_map_type_modifier);
1672 Data.MapTypeModifier = OMPC_MAP_unknown;
1674 MapTypeModifierSpecified = true;
1680 IsMapClauseModifierToken(Tok)
1681 ? static_cast<OpenMPMapClauseKind>(
1682 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)))
1684 if (Data.MapType == OMPC_MAP_unknown ||
1685 Data.MapType == OMPC_MAP_always)
1686 Diag(Tok, diag::err_omp_unknown_map_type);
1689 Data.MapType = OMPC_MAP_tofrom;
1690 Data.IsMapTypeImplicit = true;
1693 Data.MapType = OMPC_MAP_tofrom;
1694 Data.IsMapTypeImplicit = true;
1697 Data.MapType = OMPC_MAP_tofrom;
1698 Data.IsMapTypeImplicit = true;
1701 if (Tok.is(tok::colon))
1702 Data.ColonLoc = ConsumeToken();
1703 else if (ColonExpected)
1704 Diag(Tok, diag::warn_pragma_expected_colon) << "map type";
1708 (Kind != OMPC_reduction && Kind != OMPC_depend && Kind != OMPC_map) ||
1709 (Kind == OMPC_reduction && !InvalidReductionId) ||
1710 (Kind == OMPC_map && Data.MapType != OMPC_MAP_unknown &&
1711 (!MapTypeModifierSpecified ||
1712 Data.MapTypeModifier == OMPC_MAP_always)) ||
1713 (Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown);
1714 const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned);
1715 while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) &&
1716 Tok.isNot(tok::annot_pragma_openmp_end))) {
1717 ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
1719 ExprResult VarExpr =
1720 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
1721 if (VarExpr.isUsable())
1722 Vars.push_back(VarExpr.get());
1724 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1728 IsComma = Tok.is(tok::comma);
1731 else if (Tok.isNot(tok::r_paren) &&
1732 Tok.isNot(tok::annot_pragma_openmp_end) &&
1733 (!MayHaveTail || Tok.isNot(tok::colon)))
1734 Diag(Tok, diag::err_omp_expected_punc)
1735 << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush)
1736 : getOpenMPClauseName(Kind))
1737 << (Kind == OMPC_flush);
1740 // Parse ')' for linear clause with modifier.
1741 if (NeedRParenForLinear)
1742 LinearT.consumeClose();
1744 // Parse ':' linear-step (or ':' alignment).
1745 const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon);
1747 Data.ColonLoc = Tok.getLocation();
1748 SourceLocation ELoc = ConsumeToken();
1749 ExprResult Tail = ParseAssignmentExpression();
1750 Tail = Actions.ActOnFinishFullExpr(Tail.get(), ELoc);
1751 if (Tail.isUsable())
1752 Data.TailExpr = Tail.get();
1754 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1760 if ((Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown &&
1762 (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) ||
1763 (MustHaveTail && !Data.TailExpr) || InvalidReductionId)
1768 /// \brief Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate',
1769 /// 'shared', 'copyin', 'copyprivate', 'flush' or 'reduction'.
1772 /// 'private' '(' list ')'
1773 /// firstprivate-clause:
1774 /// 'firstprivate' '(' list ')'
1775 /// lastprivate-clause:
1776 /// 'lastprivate' '(' list ')'
1778 /// 'shared' '(' list ')'
1780 /// 'linear' '(' linear-list [ ':' linear-step ] ')'
1782 /// 'aligned' '(' list [ ':' alignment ] ')'
1783 /// reduction-clause:
1784 /// 'reduction' '(' reduction-identifier ':' list ')'
1785 /// copyprivate-clause:
1786 /// 'copyprivate' '(' list ')'
1788 /// 'flush' '(' list ')'
1790 /// 'depend' '(' in | out | inout : list | source ')'
1792 /// 'map' '(' [ [ always , ]
1793 /// to | from | tofrom | alloc | release | delete ':' ] list ')';
1795 /// 'to' '(' list ')'
1797 /// 'from' '(' list ')'
1798 /// use_device_ptr-clause:
1799 /// 'use_device_ptr' '(' list ')'
1800 /// is_device_ptr-clause:
1801 /// 'is_device_ptr' '(' list ')'
1803 /// For 'linear' clause linear-list may have the following forms:
1806 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
1807 OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
1808 OpenMPClauseKind Kind) {
1809 SourceLocation Loc = Tok.getLocation();
1810 SourceLocation LOpen = ConsumeToken();
1811 SmallVector<Expr *, 4> Vars;
1812 OpenMPVarListDataTy Data;
1814 if (ParseOpenMPVarList(DKind, Kind, Vars, Data))
1817 return Actions.ActOnOpenMPVarListClause(
1818 Kind, Vars, Data.TailExpr, Loc, LOpen, Data.ColonLoc, Tok.getLocation(),
1819 Data.ReductionIdScopeSpec, Data.ReductionId, Data.DepKind, Data.LinKind,
1820 Data.MapTypeModifier, Data.MapType, Data.IsMapTypeImplicit,