1 //===--- ParseOpenMP.cpp - OpenMP directives parsing ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements parsing of all OpenMP directives and clauses.
10 ///
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/StmtOpenMP.h"
15 #include "clang/Parse/ParseDiagnostic.h"
16 #include "clang/Parse/Parser.h"
17 #include "clang/Parse/RAIIObjectsForParser.h"
18 #include "clang/Sema/Scope.h"
19 #include "llvm/ADT/PointerIntPair.h"
20 
21 using namespace clang;
22 
23 //===----------------------------------------------------------------------===//
24 // OpenMP declarative directives.
25 //===----------------------------------------------------------------------===//
26 
27 namespace {
28 enum OpenMPDirectiveKindEx {
29   OMPD_cancellation = OMPD_unknown + 1,
30   OMPD_data,
31   OMPD_declare,
32   OMPD_end,
33   OMPD_end_declare,
34   OMPD_enter,
35   OMPD_exit,
36   OMPD_point,
37   OMPD_reduction,
38   OMPD_target_enter,
39   OMPD_target_exit,
40   OMPD_update,
41   OMPD_distribute_parallel,
42   OMPD_teams_distribute_parallel,
43   OMPD_target_teams_distribute_parallel,
44   OMPD_mapper,
45 };
46 
47 class ThreadprivateListParserHelper final {
48   SmallVector<Expr *, 4> Identifiers;
49   Parser *P;
50 
51 public:
52   ThreadprivateListParserHelper(Parser *P) : P(P) {}
53   void operator()(CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
54     ExprResult Res =
55         P->getActions().ActOnOpenMPIdExpression(P->getCurScope(), SS, NameInfo);
56     if (Res.isUsable())
57       Identifiers.push_back(Res.get());
58   }
59   llvm::ArrayRef<Expr *> getIdentifiers() const { return Identifiers; }
60 };
61 } // namespace
62 
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)
68     return DKind;
69 
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       .Case("mapper", OMPD_mapper)
81       .Default(OMPD_unknown);
82 }
83 
84 static OpenMPDirectiveKind parseOpenMPDirectiveKind(Parser &P) {
85   // Array of foldings: F[i][0] F[i][1] ===> F[i][2].
86   // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd
87   // TODO: add other combined directives in topological order.
88   static const unsigned F[][3] = {
89       {OMPD_cancellation, OMPD_point, OMPD_cancellation_point},
90       {OMPD_declare, OMPD_reduction, OMPD_declare_reduction},
91       {OMPD_declare, OMPD_mapper, OMPD_declare_mapper},
92       {OMPD_declare, OMPD_simd, OMPD_declare_simd},
93       {OMPD_declare, OMPD_target, OMPD_declare_target},
94       {OMPD_distribute, OMPD_parallel, OMPD_distribute_parallel},
95       {OMPD_distribute_parallel, OMPD_for, OMPD_distribute_parallel_for},
96       {OMPD_distribute_parallel_for, OMPD_simd,
97        OMPD_distribute_parallel_for_simd},
98       {OMPD_distribute, OMPD_simd, OMPD_distribute_simd},
99       {OMPD_end, OMPD_declare, OMPD_end_declare},
100       {OMPD_end_declare, OMPD_target, OMPD_end_declare_target},
101       {OMPD_target, OMPD_data, OMPD_target_data},
102       {OMPD_target, OMPD_enter, OMPD_target_enter},
103       {OMPD_target, OMPD_exit, OMPD_target_exit},
104       {OMPD_target, OMPD_update, OMPD_target_update},
105       {OMPD_target_enter, OMPD_data, OMPD_target_enter_data},
106       {OMPD_target_exit, OMPD_data, OMPD_target_exit_data},
107       {OMPD_for, OMPD_simd, OMPD_for_simd},
108       {OMPD_parallel, OMPD_for, OMPD_parallel_for},
109       {OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd},
110       {OMPD_parallel, OMPD_sections, OMPD_parallel_sections},
111       {OMPD_taskloop, OMPD_simd, OMPD_taskloop_simd},
112       {OMPD_target, OMPD_parallel, OMPD_target_parallel},
113       {OMPD_target, OMPD_simd, OMPD_target_simd},
114       {OMPD_target_parallel, OMPD_for, OMPD_target_parallel_for},
115       {OMPD_target_parallel_for, OMPD_simd, OMPD_target_parallel_for_simd},
116       {OMPD_teams, OMPD_distribute, OMPD_teams_distribute},
117       {OMPD_teams_distribute, OMPD_simd, OMPD_teams_distribute_simd},
118       {OMPD_teams_distribute, OMPD_parallel, OMPD_teams_distribute_parallel},
119       {OMPD_teams_distribute_parallel, OMPD_for,
120        OMPD_teams_distribute_parallel_for},
121       {OMPD_teams_distribute_parallel_for, OMPD_simd,
122        OMPD_teams_distribute_parallel_for_simd},
123       {OMPD_target, OMPD_teams, OMPD_target_teams},
124       {OMPD_target_teams, OMPD_distribute, OMPD_target_teams_distribute},
125       {OMPD_target_teams_distribute, OMPD_parallel,
126        OMPD_target_teams_distribute_parallel},
127       {OMPD_target_teams_distribute, OMPD_simd,
128        OMPD_target_teams_distribute_simd},
129       {OMPD_target_teams_distribute_parallel, OMPD_for,
130        OMPD_target_teams_distribute_parallel_for},
131       {OMPD_target_teams_distribute_parallel_for, OMPD_simd,
132        OMPD_target_teams_distribute_parallel_for_simd}};
133   enum { CancellationPoint = 0, DeclareReduction = 1, TargetData = 2 };
134   Token Tok = P.getCurToken();
135   unsigned DKind =
136       Tok.isAnnotation()
137           ? static_cast<unsigned>(OMPD_unknown)
138           : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
139   if (DKind == OMPD_unknown)
140     return OMPD_unknown;
141 
142   for (unsigned I = 0; I < llvm::array_lengthof(F); ++I) {
143     if (DKind != F[I][0])
144       continue;
145 
146     Tok = P.getPreprocessor().LookAhead(0);
147     unsigned SDKind =
148         Tok.isAnnotation()
149             ? static_cast<unsigned>(OMPD_unknown)
150             : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
151     if (SDKind == OMPD_unknown)
152       continue;
153 
154     if (SDKind == F[I][1]) {
155       P.ConsumeToken();
156       DKind = F[I][2];
157     }
158   }
159   return DKind < OMPD_unknown ? static_cast<OpenMPDirectiveKind>(DKind)
160                               : OMPD_unknown;
161 }
162 
163 static DeclarationName parseOpenMPReductionId(Parser &P) {
164   Token Tok = P.getCurToken();
165   Sema &Actions = P.getActions();
166   OverloadedOperatorKind OOK = OO_None;
167   // Allow to use 'operator' keyword for C++ operators
168   bool WithOperator = false;
169   if (Tok.is(tok::kw_operator)) {
170     P.ConsumeToken();
171     Tok = P.getCurToken();
172     WithOperator = true;
173   }
174   switch (Tok.getKind()) {
175   case tok::plus: // '+'
176     OOK = OO_Plus;
177     break;
178   case tok::minus: // '-'
179     OOK = OO_Minus;
180     break;
181   case tok::star: // '*'
182     OOK = OO_Star;
183     break;
184   case tok::amp: // '&'
185     OOK = OO_Amp;
186     break;
187   case tok::pipe: // '|'
188     OOK = OO_Pipe;
189     break;
190   case tok::caret: // '^'
191     OOK = OO_Caret;
192     break;
193   case tok::ampamp: // '&&'
194     OOK = OO_AmpAmp;
195     break;
196   case tok::pipepipe: // '||'
197     OOK = OO_PipePipe;
198     break;
199   case tok::identifier: // identifier
200     if (!WithOperator)
201       break;
202     LLVM_FALLTHROUGH;
203   default:
204     P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier);
205     P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
206                 Parser::StopBeforeMatch);
207     return DeclarationName();
208   }
209   P.ConsumeToken();
210   auto &DeclNames = Actions.getASTContext().DeclarationNames;
211   return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo())
212                         : DeclNames.getCXXOperatorName(OOK);
213 }
214 
215 /// Parse 'omp declare reduction' construct.
216 ///
217 ///       declare-reduction-directive:
218 ///        annot_pragma_openmp 'declare' 'reduction'
219 ///        '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')'
220 ///        ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')']
221 ///        annot_pragma_openmp_end
222 /// <reduction_id> is either a base language identifier or one of the following
223 /// operators: '+', '-', '*', '&', '|', '^', '&&' and '||'.
224 ///
225 Parser::DeclGroupPtrTy
226 Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) {
227   // Parse '('.
228   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
229   if (T.expectAndConsume(diag::err_expected_lparen_after,
230                          getOpenMPDirectiveName(OMPD_declare_reduction))) {
231     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
232     return DeclGroupPtrTy();
233   }
234 
235   DeclarationName Name = parseOpenMPReductionId(*this);
236   if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end))
237     return DeclGroupPtrTy();
238 
239   // Consume ':'.
240   bool IsCorrect = !ExpectAndConsume(tok::colon);
241 
242   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
243     return DeclGroupPtrTy();
244 
245   IsCorrect = IsCorrect && !Name.isEmpty();
246 
247   if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) {
248     Diag(Tok.getLocation(), diag::err_expected_type);
249     IsCorrect = false;
250   }
251 
252   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
253     return DeclGroupPtrTy();
254 
255   SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes;
256   // Parse list of types until ':' token.
257   do {
258     ColonProtectionRAIIObject ColonRAII(*this);
259     SourceRange Range;
260     TypeResult TR =
261         ParseTypeName(&Range, DeclaratorContext::PrototypeContext, AS);
262     if (TR.isUsable()) {
263       QualType ReductionType =
264           Actions.ActOnOpenMPDeclareReductionType(Range.getBegin(), TR);
265       if (!ReductionType.isNull()) {
266         ReductionTypes.push_back(
267             std::make_pair(ReductionType, Range.getBegin()));
268       }
269     } else {
270       SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end,
271                 StopBeforeMatch);
272     }
273 
274     if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end))
275       break;
276 
277     // Consume ','.
278     if (ExpectAndConsume(tok::comma)) {
279       IsCorrect = false;
280       if (Tok.is(tok::annot_pragma_openmp_end)) {
281         Diag(Tok.getLocation(), diag::err_expected_type);
282         return DeclGroupPtrTy();
283       }
284     }
285   } while (Tok.isNot(tok::annot_pragma_openmp_end));
286 
287   if (ReductionTypes.empty()) {
288     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
289     return DeclGroupPtrTy();
290   }
291 
292   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
293     return DeclGroupPtrTy();
294 
295   // Consume ':'.
296   if (ExpectAndConsume(tok::colon))
297     IsCorrect = false;
298 
299   if (Tok.is(tok::annot_pragma_openmp_end)) {
300     Diag(Tok.getLocation(), diag::err_expected_expression);
301     return DeclGroupPtrTy();
302   }
303 
304   DeclGroupPtrTy DRD = Actions.ActOnOpenMPDeclareReductionDirectiveStart(
305       getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes, AS);
306 
307   // Parse <combiner> expression and then parse initializer if any for each
308   // correct type.
309   unsigned I = 0, E = ReductionTypes.size();
310   for (Decl *D : DRD.get()) {
311     TentativeParsingAction TPA(*this);
312     ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
313                                     Scope::CompoundStmtScope |
314                                     Scope::OpenMPDirectiveScope);
315     // Parse <combiner> expression.
316     Actions.ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D);
317     ExprResult CombinerResult =
318         Actions.ActOnFinishFullExpr(ParseAssignmentExpression().get(),
319                                     D->getLocation(), /*DiscardedValue*/ false);
320     Actions.ActOnOpenMPDeclareReductionCombinerEnd(D, CombinerResult.get());
321 
322     if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
323         Tok.isNot(tok::annot_pragma_openmp_end)) {
324       TPA.Commit();
325       IsCorrect = false;
326       break;
327     }
328     IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable();
329     ExprResult InitializerResult;
330     if (Tok.isNot(tok::annot_pragma_openmp_end)) {
331       // Parse <initializer> expression.
332       if (Tok.is(tok::identifier) &&
333           Tok.getIdentifierInfo()->isStr("initializer")) {
334         ConsumeToken();
335       } else {
336         Diag(Tok.getLocation(), diag::err_expected) << "'initializer'";
337         TPA.Commit();
338         IsCorrect = false;
339         break;
340       }
341       // Parse '('.
342       BalancedDelimiterTracker T(*this, tok::l_paren,
343                                  tok::annot_pragma_openmp_end);
344       IsCorrect =
345           !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") &&
346           IsCorrect;
347       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
348         ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
349                                         Scope::CompoundStmtScope |
350                                         Scope::OpenMPDirectiveScope);
351         // Parse expression.
352         VarDecl *OmpPrivParm =
353             Actions.ActOnOpenMPDeclareReductionInitializerStart(getCurScope(),
354                                                                 D);
355         // Check if initializer is omp_priv <init_expr> or something else.
356         if (Tok.is(tok::identifier) &&
357             Tok.getIdentifierInfo()->isStr("omp_priv")) {
358           if (Actions.getLangOpts().CPlusPlus) {
359             InitializerResult = Actions.ActOnFinishFullExpr(
360                 ParseAssignmentExpression().get(), D->getLocation(),
361                 /*DiscardedValue*/ false);
362           } else {
363             ConsumeToken();
364             ParseOpenMPReductionInitializerForDecl(OmpPrivParm);
365           }
366         } else {
367           InitializerResult = Actions.ActOnFinishFullExpr(
368               ParseAssignmentExpression().get(), D->getLocation(),
369               /*DiscardedValue*/ false);
370         }
371         Actions.ActOnOpenMPDeclareReductionInitializerEnd(
372             D, InitializerResult.get(), OmpPrivParm);
373         if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
374             Tok.isNot(tok::annot_pragma_openmp_end)) {
375           TPA.Commit();
376           IsCorrect = false;
377           break;
378         }
379         IsCorrect =
380             !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid();
381       }
382     }
383 
384     ++I;
385     // Revert parsing if not the last type, otherwise accept it, we're done with
386     // parsing.
387     if (I != E)
388       TPA.Revert();
389     else
390       TPA.Commit();
391   }
392   return Actions.ActOnOpenMPDeclareReductionDirectiveEnd(getCurScope(), DRD,
393                                                          IsCorrect);
394 }
395 
396 void Parser::ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm) {
397   // Parse declarator '=' initializer.
398   // If a '==' or '+=' is found, suggest a fixit to '='.
399   if (isTokenEqualOrEqualTypo()) {
400     ConsumeToken();
401 
402     if (Tok.is(tok::code_completion)) {
403       Actions.CodeCompleteInitializer(getCurScope(), OmpPrivParm);
404       Actions.FinalizeDeclaration(OmpPrivParm);
405       cutOffParsing();
406       return;
407     }
408 
409     ExprResult Init(ParseInitializer());
410 
411     if (Init.isInvalid()) {
412       SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
413       Actions.ActOnInitializerError(OmpPrivParm);
414     } else {
415       Actions.AddInitializerToDecl(OmpPrivParm, Init.get(),
416                                    /*DirectInit=*/false);
417     }
418   } else if (Tok.is(tok::l_paren)) {
419     // Parse C++ direct initializer: '(' expression-list ')'
420     BalancedDelimiterTracker T(*this, tok::l_paren);
421     T.consumeOpen();
422 
423     ExprVector Exprs;
424     CommaLocsTy CommaLocs;
425 
426     SourceLocation LParLoc = T.getOpenLocation();
427     auto RunSignatureHelp = [this, OmpPrivParm, LParLoc, &Exprs]() {
428       QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
429           getCurScope(), OmpPrivParm->getType()->getCanonicalTypeInternal(),
430           OmpPrivParm->getLocation(), Exprs, LParLoc);
431       CalledSignatureHelp = true;
432       return PreferredType;
433     };
434     if (ParseExpressionList(Exprs, CommaLocs, [&] {
435           PreferredType.enterFunctionArgument(Tok.getLocation(),
436                                               RunSignatureHelp);
437         })) {
438       if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
439         RunSignatureHelp();
440       Actions.ActOnInitializerError(OmpPrivParm);
441       SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
442     } else {
443       // Match the ')'.
444       SourceLocation RLoc = Tok.getLocation();
445       if (!T.consumeClose())
446         RLoc = T.getCloseLocation();
447 
448       assert(!Exprs.empty() && Exprs.size() - 1 == CommaLocs.size() &&
449              "Unexpected number of commas!");
450 
451       ExprResult Initializer =
452           Actions.ActOnParenListExpr(T.getOpenLocation(), RLoc, Exprs);
453       Actions.AddInitializerToDecl(OmpPrivParm, Initializer.get(),
454                                    /*DirectInit=*/true);
455     }
456   } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
457     // Parse C++0x braced-init-list.
458     Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
459 
460     ExprResult Init(ParseBraceInitializer());
461 
462     if (Init.isInvalid()) {
463       Actions.ActOnInitializerError(OmpPrivParm);
464     } else {
465       Actions.AddInitializerToDecl(OmpPrivParm, Init.get(),
466                                    /*DirectInit=*/true);
467     }
468   } else {
469     Actions.ActOnUninitializedDecl(OmpPrivParm);
470   }
471 }
472 
473 /// Parses 'omp declare mapper' directive.
474 ///
475 ///       declare-mapper-directive:
476 ///         annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifier> ':']
477 ///         <type> <var> ')' [<clause>[[,] <clause>] ... ]
478 ///         annot_pragma_openmp_end
479 /// <mapper-identifier> and <var> are base language identifiers.
480 ///
481 Parser::DeclGroupPtrTy
482 Parser::ParseOpenMPDeclareMapperDirective(AccessSpecifier AS) {
483   bool IsCorrect = true;
484   // Parse '('
485   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
486   if (T.expectAndConsume(diag::err_expected_lparen_after,
487                          getOpenMPDirectiveName(OMPD_declare_mapper))) {
488     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
489     return DeclGroupPtrTy();
490   }
491 
492   // Parse <mapper-identifier>
493   auto &DeclNames = Actions.getASTContext().DeclarationNames;
494   DeclarationName MapperId;
495   if (PP.LookAhead(0).is(tok::colon)) {
496     if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
497       Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
498       IsCorrect = false;
499     } else {
500       MapperId = DeclNames.getIdentifier(Tok.getIdentifierInfo());
501     }
502     ConsumeToken();
503     // Consume ':'.
504     ExpectAndConsume(tok::colon);
505   } else {
506     // If no mapper identifier is provided, its name is "default" by default
507     MapperId =
508         DeclNames.getIdentifier(&Actions.getASTContext().Idents.get("default"));
509   }
510 
511   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
512     return DeclGroupPtrTy();
513 
514   // Parse <type> <var>
515   DeclarationName VName;
516   QualType MapperType;
517   SourceRange Range;
518   TypeResult ParsedType = parseOpenMPDeclareMapperVarDecl(Range, VName, AS);
519   if (ParsedType.isUsable())
520     MapperType =
521         Actions.ActOnOpenMPDeclareMapperType(Range.getBegin(), ParsedType);
522   if (MapperType.isNull())
523     IsCorrect = false;
524   if (!IsCorrect) {
525     SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch);
526     return DeclGroupPtrTy();
527   }
528 
529   // Consume ')'.
530   IsCorrect &= !T.consumeClose();
531   if (!IsCorrect) {
532     SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch);
533     return DeclGroupPtrTy();
534   }
535 
536   // Enter scope.
537   OMPDeclareMapperDecl *DMD = Actions.ActOnOpenMPDeclareMapperDirectiveStart(
538       getCurScope(), Actions.getCurLexicalContext(), MapperId, MapperType,
539       Range.getBegin(), VName, AS);
540   DeclarationNameInfo DirName;
541   SourceLocation Loc = Tok.getLocation();
542   unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
543                         Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope;
544   ParseScope OMPDirectiveScope(this, ScopeFlags);
545   Actions.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, getCurScope(), Loc);
546 
547   // Add the mapper variable declaration.
548   Actions.ActOnOpenMPDeclareMapperDirectiveVarDecl(
549       DMD, getCurScope(), MapperType, Range.getBegin(), VName);
550 
551   // Parse map clauses.
552   SmallVector<OMPClause *, 6> Clauses;
553   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
554     OpenMPClauseKind CKind = Tok.isAnnotation()
555                                  ? OMPC_unknown
556                                  : getOpenMPClauseKind(PP.getSpelling(Tok));
557     Actions.StartOpenMPClause(CKind);
558     OMPClause *Clause =
559         ParseOpenMPClause(OMPD_declare_mapper, CKind, Clauses.size() == 0);
560     if (Clause)
561       Clauses.push_back(Clause);
562     else
563       IsCorrect = false;
564     // Skip ',' if any.
565     if (Tok.is(tok::comma))
566       ConsumeToken();
567     Actions.EndOpenMPClause();
568   }
569   if (Clauses.empty()) {
570     Diag(Tok, diag::err_omp_expected_clause)
571         << getOpenMPDirectiveName(OMPD_declare_mapper);
572     IsCorrect = false;
573   }
574 
575   // Exit scope.
576   Actions.EndOpenMPDSABlock(nullptr);
577   OMPDirectiveScope.Exit();
578 
579   DeclGroupPtrTy DGP =
580       Actions.ActOnOpenMPDeclareMapperDirectiveEnd(DMD, getCurScope(), Clauses);
581   if (!IsCorrect)
582     return DeclGroupPtrTy();
583   return DGP;
584 }
585 
586 TypeResult Parser::parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
587                                                    DeclarationName &Name,
588                                                    AccessSpecifier AS) {
589   // Parse the common declaration-specifiers piece.
590   Parser::DeclSpecContext DSC = Parser::DeclSpecContext::DSC_type_specifier;
591   DeclSpec DS(AttrFactory);
592   ParseSpecifierQualifierList(DS, AS, DSC);
593 
594   // Parse the declarator.
595   DeclaratorContext Context = DeclaratorContext::PrototypeContext;
596   Declarator DeclaratorInfo(DS, Context);
597   ParseDeclarator(DeclaratorInfo);
598   Range = DeclaratorInfo.getSourceRange();
599   if (DeclaratorInfo.getIdentifier() == nullptr) {
600     Diag(Tok.getLocation(), diag::err_omp_mapper_expected_declarator);
601     return true;
602   }
603   Name = Actions.GetNameForDeclarator(DeclaratorInfo).getName();
604 
605   return Actions.ActOnOpenMPDeclareMapperVarDecl(getCurScope(), DeclaratorInfo);
606 }
607 
608 namespace {
609 /// RAII that recreates function context for correct parsing of clauses of
610 /// 'declare simd' construct.
611 /// OpenMP, 2.8.2 declare simd Construct
612 /// The expressions appearing in the clauses of this directive are evaluated in
613 /// the scope of the arguments of the function declaration or definition.
614 class FNContextRAII final {
615   Parser &P;
616   Sema::CXXThisScopeRAII *ThisScope;
617   Parser::ParseScope *TempScope;
618   Parser::ParseScope *FnScope;
619   bool HasTemplateScope = false;
620   bool HasFunScope = false;
621   FNContextRAII() = delete;
622   FNContextRAII(const FNContextRAII &) = delete;
623   FNContextRAII &operator=(const FNContextRAII &) = delete;
624 
625 public:
626   FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P) {
627     Decl *D = *Ptr.get().begin();
628     NamedDecl *ND = dyn_cast<NamedDecl>(D);
629     RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
630     Sema &Actions = P.getActions();
631 
632     // Allow 'this' within late-parsed attributes.
633     ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, Qualifiers(),
634                                            ND && ND->isCXXInstanceMember());
635 
636     // If the Decl is templatized, add template parameters to scope.
637     HasTemplateScope = D->isTemplateDecl();
638     TempScope =
639         new Parser::ParseScope(&P, Scope::TemplateParamScope, HasTemplateScope);
640     if (HasTemplateScope)
641       Actions.ActOnReenterTemplateScope(Actions.getCurScope(), D);
642 
643     // If the Decl is on a function, add function parameters to the scope.
644     HasFunScope = D->isFunctionOrFunctionTemplate();
645     FnScope = new Parser::ParseScope(
646         &P, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
647         HasFunScope);
648     if (HasFunScope)
649       Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D);
650   }
651   ~FNContextRAII() {
652     if (HasFunScope) {
653       P.getActions().ActOnExitFunctionContext();
654       FnScope->Exit(); // Pop scope, and remove Decls from IdResolver
655     }
656     if (HasTemplateScope)
657       TempScope->Exit();
658     delete FnScope;
659     delete TempScope;
660     delete ThisScope;
661   }
662 };
663 } // namespace
664 
665 /// Parses clauses for 'declare simd' directive.
666 ///    clause:
667 ///      'inbranch' | 'notinbranch'
668 ///      'simdlen' '(' <expr> ')'
669 ///      { 'uniform' '(' <argument_list> ')' }
670 ///      { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' }
671 ///      { 'linear '(' <argument_list> [ ':' <step> ] ')' }
672 static bool parseDeclareSimdClauses(
673     Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen,
674     SmallVectorImpl<Expr *> &Uniforms, SmallVectorImpl<Expr *> &Aligneds,
675     SmallVectorImpl<Expr *> &Alignments, SmallVectorImpl<Expr *> &Linears,
676     SmallVectorImpl<unsigned> &LinModifiers, SmallVectorImpl<Expr *> &Steps) {
677   SourceRange BSRange;
678   const Token &Tok = P.getCurToken();
679   bool IsError = false;
680   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
681     if (Tok.isNot(tok::identifier))
682       break;
683     OMPDeclareSimdDeclAttr::BranchStateTy Out;
684     IdentifierInfo *II = Tok.getIdentifierInfo();
685     StringRef ClauseName = II->getName();
686     // Parse 'inranch|notinbranch' clauses.
687     if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) {
688       if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) {
689         P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch)
690             << ClauseName
691             << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange;
692         IsError = true;
693       }
694       BS = Out;
695       BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc());
696       P.ConsumeToken();
697     } else if (ClauseName.equals("simdlen")) {
698       if (SimdLen.isUsable()) {
699         P.Diag(Tok, diag::err_omp_more_one_clause)
700             << getOpenMPDirectiveName(OMPD_declare_simd) << ClauseName << 0;
701         IsError = true;
702       }
703       P.ConsumeToken();
704       SourceLocation RLoc;
705       SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc);
706       if (SimdLen.isInvalid())
707         IsError = true;
708     } else {
709       OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName);
710       if (CKind == OMPC_uniform || CKind == OMPC_aligned ||
711           CKind == OMPC_linear) {
712         Parser::OpenMPVarListDataTy Data;
713         SmallVectorImpl<Expr *> *Vars = &Uniforms;
714         if (CKind == OMPC_aligned)
715           Vars = &Aligneds;
716         else if (CKind == OMPC_linear)
717           Vars = &Linears;
718 
719         P.ConsumeToken();
720         if (P.ParseOpenMPVarList(OMPD_declare_simd,
721                                  getOpenMPClauseKind(ClauseName), *Vars, Data))
722           IsError = true;
723         if (CKind == OMPC_aligned) {
724           Alignments.append(Aligneds.size() - Alignments.size(), Data.TailExpr);
725         } else if (CKind == OMPC_linear) {
726           if (P.getActions().CheckOpenMPLinearModifier(Data.LinKind,
727                                                        Data.DepLinMapLoc))
728             Data.LinKind = OMPC_LINEAR_val;
729           LinModifiers.append(Linears.size() - LinModifiers.size(),
730                               Data.LinKind);
731           Steps.append(Linears.size() - Steps.size(), Data.TailExpr);
732         }
733       } else
734         // TODO: add parsing of other clauses.
735         break;
736     }
737     // Skip ',' if any.
738     if (Tok.is(tok::comma))
739       P.ConsumeToken();
740   }
741   return IsError;
742 }
743 
744 /// Parse clauses for '#pragma omp declare simd'.
745 Parser::DeclGroupPtrTy
746 Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr,
747                                    CachedTokens &Toks, SourceLocation Loc) {
748   PP.EnterToken(Tok);
749   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
750   // Consume the previously pushed token.
751   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
752 
753   FNContextRAII FnContext(*this, Ptr);
754   OMPDeclareSimdDeclAttr::BranchStateTy BS =
755       OMPDeclareSimdDeclAttr::BS_Undefined;
756   ExprResult Simdlen;
757   SmallVector<Expr *, 4> Uniforms;
758   SmallVector<Expr *, 4> Aligneds;
759   SmallVector<Expr *, 4> Alignments;
760   SmallVector<Expr *, 4> Linears;
761   SmallVector<unsigned, 4> LinModifiers;
762   SmallVector<Expr *, 4> Steps;
763   bool IsError =
764       parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds,
765                               Alignments, Linears, LinModifiers, Steps);
766   // Need to check for extra tokens.
767   if (Tok.isNot(tok::annot_pragma_openmp_end)) {
768     Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
769         << getOpenMPDirectiveName(OMPD_declare_simd);
770     while (Tok.isNot(tok::annot_pragma_openmp_end))
771       ConsumeAnyToken();
772   }
773   // Skip the last annot_pragma_openmp_end.
774   SourceLocation EndLoc = ConsumeAnnotationToken();
775   if (IsError)
776     return Ptr;
777   return Actions.ActOnOpenMPDeclareSimdDirective(
778       Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears,
779       LinModifiers, Steps, SourceRange(Loc, EndLoc));
780 }
781 
782 Parser::DeclGroupPtrTy Parser::ParseOMPDeclareTargetClauses() {
783   // OpenMP 4.5 syntax with list of entities.
784   Sema::NamedDeclSetType SameDirectiveDecls;
785   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
786     OMPDeclareTargetDeclAttr::MapTypeTy MT = OMPDeclareTargetDeclAttr::MT_To;
787     if (Tok.is(tok::identifier)) {
788       IdentifierInfo *II = Tok.getIdentifierInfo();
789       StringRef ClauseName = II->getName();
790       // Parse 'to|link' clauses.
791       if (!OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName, MT)) {
792         Diag(Tok, diag::err_omp_declare_target_unexpected_clause) << ClauseName;
793         break;
794       }
795       ConsumeToken();
796     }
797     auto &&Callback = [this, MT, &SameDirectiveDecls](
798         CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
799       Actions.ActOnOpenMPDeclareTargetName(getCurScope(), SS, NameInfo, MT,
800                                            SameDirectiveDecls);
801     };
802     if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback,
803                                  /*AllowScopeSpecifier=*/true))
804       break;
805 
806     // Consume optional ','.
807     if (Tok.is(tok::comma))
808       ConsumeToken();
809   }
810   SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
811   ConsumeAnyToken();
812   SmallVector<Decl *, 4> Decls(SameDirectiveDecls.begin(),
813                                SameDirectiveDecls.end());
814   if (Decls.empty())
815     return DeclGroupPtrTy();
816   return Actions.BuildDeclaratorGroup(Decls);
817 }
818 
819 void Parser::ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind,
820                                                SourceLocation DTLoc) {
821   if (DKind != OMPD_end_declare_target) {
822     Diag(Tok, diag::err_expected_end_declare_target);
823     Diag(DTLoc, diag::note_matching) << "'#pragma omp declare target'";
824     return;
825   }
826   ConsumeAnyToken();
827   if (Tok.isNot(tok::annot_pragma_openmp_end)) {
828     Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
829         << getOpenMPDirectiveName(OMPD_end_declare_target);
830     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
831   }
832   // Skip the last annot_pragma_openmp_end.
833   ConsumeAnyToken();
834 }
835 
836 /// Parsing of declarative OpenMP directives.
837 ///
838 ///       threadprivate-directive:
839 ///         annot_pragma_openmp 'threadprivate' simple-variable-list
840 ///         annot_pragma_openmp_end
841 ///
842 ///       declare-reduction-directive:
843 ///        annot_pragma_openmp 'declare' 'reduction' [...]
844 ///        annot_pragma_openmp_end
845 ///
846 ///       declare-mapper-directive:
847 ///         annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
848 ///         <type> <var> ')' [<clause>[[,] <clause>] ... ]
849 ///         annot_pragma_openmp_end
850 ///
851 ///       declare-simd-directive:
852 ///         annot_pragma_openmp 'declare simd' {<clause> [,]}
853 ///         annot_pragma_openmp_end
854 ///         <function declaration/definition>
855 ///
856 ///       requires directive:
857 ///         annot_pragma_openmp 'requires' <clause> [[[,] <clause>] ... ]
858 ///         annot_pragma_openmp_end
859 ///
860 Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
861     AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
862     DeclSpec::TST TagType, Decl *Tag) {
863   assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
864   ParenBraceBracketBalancer BalancerRAIIObj(*this);
865 
866   SourceLocation Loc = ConsumeAnnotationToken();
867   OpenMPDirectiveKind DKind = parseOpenMPDirectiveKind(*this);
868 
869   switch (DKind) {
870   case OMPD_threadprivate: {
871     ConsumeToken();
872     ThreadprivateListParserHelper Helper(this);
873     if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Helper, true)) {
874       // The last seen token is annot_pragma_openmp_end - need to check for
875       // extra tokens.
876       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
877         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
878             << getOpenMPDirectiveName(OMPD_threadprivate);
879         SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
880       }
881       // Skip the last annot_pragma_openmp_end.
882       ConsumeAnnotationToken();
883       return Actions.ActOnOpenMPThreadprivateDirective(Loc,
884                                                        Helper.getIdentifiers());
885     }
886     break;
887   }
888   case OMPD_requires: {
889     SourceLocation StartLoc = ConsumeToken();
890     SmallVector<OMPClause *, 5> Clauses;
891     SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, OMPC_unknown + 1>
892     FirstClauses(OMPC_unknown + 1);
893     if (Tok.is(tok::annot_pragma_openmp_end)) {
894       Diag(Tok, diag::err_omp_expected_clause)
895           << getOpenMPDirectiveName(OMPD_requires);
896       break;
897     }
898     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
899       OpenMPClauseKind CKind = Tok.isAnnotation()
900                                    ? OMPC_unknown
901                                    : getOpenMPClauseKind(PP.getSpelling(Tok));
902       Actions.StartOpenMPClause(CKind);
903       OMPClause *Clause =
904           ParseOpenMPClause(OMPD_requires, CKind, !FirstClauses[CKind].getInt());
905       SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end, StopBeforeMatch);
906       FirstClauses[CKind].setInt(true);
907       if (Clause != nullptr)
908         Clauses.push_back(Clause);
909       if (Tok.is(tok::annot_pragma_openmp_end)) {
910         Actions.EndOpenMPClause();
911         break;
912       }
913       // Skip ',' if any.
914       if (Tok.is(tok::comma))
915         ConsumeToken();
916       Actions.EndOpenMPClause();
917     }
918     // Consume final annot_pragma_openmp_end
919     if (Clauses.size() == 0) {
920       Diag(Tok, diag::err_omp_expected_clause)
921           << getOpenMPDirectiveName(OMPD_requires);
922       ConsumeAnnotationToken();
923       return nullptr;
924     }
925     ConsumeAnnotationToken();
926     return Actions.ActOnOpenMPRequiresDirective(StartLoc, Clauses);
927   }
928   case OMPD_declare_reduction:
929     ConsumeToken();
930     if (DeclGroupPtrTy Res = ParseOpenMPDeclareReductionDirective(AS)) {
931       // The last seen token is annot_pragma_openmp_end - need to check for
932       // extra tokens.
933       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
934         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
935             << getOpenMPDirectiveName(OMPD_declare_reduction);
936         while (Tok.isNot(tok::annot_pragma_openmp_end))
937           ConsumeAnyToken();
938       }
939       // Skip the last annot_pragma_openmp_end.
940       ConsumeAnnotationToken();
941       return Res;
942     }
943     break;
944   case OMPD_declare_mapper: {
945     ConsumeToken();
946     if (DeclGroupPtrTy Res = ParseOpenMPDeclareMapperDirective(AS)) {
947       // Skip the last annot_pragma_openmp_end.
948       ConsumeAnnotationToken();
949       return Res;
950     }
951     break;
952   }
953   case OMPD_declare_simd: {
954     // The syntax is:
955     // { #pragma omp declare simd }
956     // <function-declaration-or-definition>
957     //
958     ConsumeToken();
959     CachedTokens Toks;
960     while(Tok.isNot(tok::annot_pragma_openmp_end)) {
961       Toks.push_back(Tok);
962       ConsumeAnyToken();
963     }
964     Toks.push_back(Tok);
965     ConsumeAnyToken();
966 
967     DeclGroupPtrTy Ptr;
968     if (Tok.is(tok::annot_pragma_openmp)) {
969       Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, TagType, Tag);
970     } else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
971       // Here we expect to see some function declaration.
972       if (AS == AS_none) {
973         assert(TagType == DeclSpec::TST_unspecified);
974         MaybeParseCXX11Attributes(Attrs);
975         ParsingDeclSpec PDS(*this);
976         Ptr = ParseExternalDeclaration(Attrs, &PDS);
977       } else {
978         Ptr =
979             ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag);
980       }
981     }
982     if (!Ptr) {
983       Diag(Loc, diag::err_omp_decl_in_declare_simd);
984       return DeclGroupPtrTy();
985     }
986     return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc);
987   }
988   case OMPD_declare_target: {
989     SourceLocation DTLoc = ConsumeAnyToken();
990     if (Tok.isNot(tok::annot_pragma_openmp_end)) {
991       return ParseOMPDeclareTargetClauses();
992     }
993 
994     // Skip the last annot_pragma_openmp_end.
995     ConsumeAnyToken();
996 
997     if (!Actions.ActOnStartOpenMPDeclareTargetDirective(DTLoc))
998       return DeclGroupPtrTy();
999 
1000     llvm::SmallVector<Decl *, 4>  Decls;
1001     DKind = parseOpenMPDirectiveKind(*this);
1002     while (DKind != OMPD_end_declare_target && Tok.isNot(tok::eof) &&
1003            Tok.isNot(tok::r_brace)) {
1004       DeclGroupPtrTy Ptr;
1005       // Here we expect to see some function declaration.
1006       if (AS == AS_none) {
1007         assert(TagType == DeclSpec::TST_unspecified);
1008         MaybeParseCXX11Attributes(Attrs);
1009         ParsingDeclSpec PDS(*this);
1010         Ptr = ParseExternalDeclaration(Attrs, &PDS);
1011       } else {
1012         Ptr =
1013             ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag);
1014       }
1015       if (Ptr) {
1016         DeclGroupRef Ref = Ptr.get();
1017         Decls.append(Ref.begin(), Ref.end());
1018       }
1019       if (Tok.isAnnotation() && Tok.is(tok::annot_pragma_openmp)) {
1020         TentativeParsingAction TPA(*this);
1021         ConsumeAnnotationToken();
1022         DKind = parseOpenMPDirectiveKind(*this);
1023         if (DKind != OMPD_end_declare_target)
1024           TPA.Revert();
1025         else
1026           TPA.Commit();
1027       }
1028     }
1029 
1030     ParseOMPEndDeclareTargetDirective(DKind, DTLoc);
1031     Actions.ActOnFinishOpenMPDeclareTargetDirective();
1032     return Actions.BuildDeclaratorGroup(Decls);
1033   }
1034   case OMPD_unknown:
1035     Diag(Tok, diag::err_omp_unknown_directive);
1036     break;
1037   case OMPD_parallel:
1038   case OMPD_simd:
1039   case OMPD_task:
1040   case OMPD_taskyield:
1041   case OMPD_barrier:
1042   case OMPD_taskwait:
1043   case OMPD_taskgroup:
1044   case OMPD_flush:
1045   case OMPD_for:
1046   case OMPD_for_simd:
1047   case OMPD_sections:
1048   case OMPD_section:
1049   case OMPD_single:
1050   case OMPD_master:
1051   case OMPD_ordered:
1052   case OMPD_critical:
1053   case OMPD_parallel_for:
1054   case OMPD_parallel_for_simd:
1055   case OMPD_parallel_sections:
1056   case OMPD_atomic:
1057   case OMPD_target:
1058   case OMPD_teams:
1059   case OMPD_cancellation_point:
1060   case OMPD_cancel:
1061   case OMPD_target_data:
1062   case OMPD_target_enter_data:
1063   case OMPD_target_exit_data:
1064   case OMPD_target_parallel:
1065   case OMPD_target_parallel_for:
1066   case OMPD_taskloop:
1067   case OMPD_taskloop_simd:
1068   case OMPD_distribute:
1069   case OMPD_end_declare_target:
1070   case OMPD_target_update:
1071   case OMPD_distribute_parallel_for:
1072   case OMPD_distribute_parallel_for_simd:
1073   case OMPD_distribute_simd:
1074   case OMPD_target_parallel_for_simd:
1075   case OMPD_target_simd:
1076   case OMPD_teams_distribute:
1077   case OMPD_teams_distribute_simd:
1078   case OMPD_teams_distribute_parallel_for_simd:
1079   case OMPD_teams_distribute_parallel_for:
1080   case OMPD_target_teams:
1081   case OMPD_target_teams_distribute:
1082   case OMPD_target_teams_distribute_parallel_for:
1083   case OMPD_target_teams_distribute_parallel_for_simd:
1084   case OMPD_target_teams_distribute_simd:
1085     Diag(Tok, diag::err_omp_unexpected_directive)
1086         << 1 << getOpenMPDirectiveName(DKind);
1087     break;
1088   }
1089   while (Tok.isNot(tok::annot_pragma_openmp_end))
1090     ConsumeAnyToken();
1091   ConsumeAnyToken();
1092   return nullptr;
1093 }
1094 
1095 /// Parsing of declarative or executable OpenMP directives.
1096 ///
1097 ///       threadprivate-directive:
1098 ///         annot_pragma_openmp 'threadprivate' simple-variable-list
1099 ///         annot_pragma_openmp_end
1100 ///
1101 ///       declare-reduction-directive:
1102 ///         annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':'
1103 ///         <type> {',' <type>} ':' <expression> ')' ['initializer' '('
1104 ///         ('omp_priv' '=' <expression>|<function_call>) ')']
1105 ///         annot_pragma_openmp_end
1106 ///
1107 ///       declare-mapper-directive:
1108 ///         annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
1109 ///         <type> <var> ')' [<clause>[[,] <clause>] ... ]
1110 ///         annot_pragma_openmp_end
1111 ///
1112 ///       executable-directive:
1113 ///         annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
1114 ///         'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
1115 ///         'parallel for' | 'parallel sections' | 'task' | 'taskyield' |
1116 ///         'barrier' | 'taskwait' | 'flush' | 'ordered' | 'atomic' |
1117 ///         'for simd' | 'parallel for simd' | 'target' | 'target data' |
1118 ///         'taskgroup' | 'teams' | 'taskloop' | 'taskloop simd' |
1119 ///         'distribute' | 'target enter data' | 'target exit data' |
1120 ///         'target parallel' | 'target parallel for' |
1121 ///         'target update' | 'distribute parallel for' |
1122 ///         'distribute paralle for simd' | 'distribute simd' |
1123 ///         'target parallel for simd' | 'target simd' |
1124 ///         'teams distribute' | 'teams distribute simd' |
1125 ///         'teams distribute parallel for simd' |
1126 ///         'teams distribute parallel for' | 'target teams' |
1127 ///         'target teams distribute' |
1128 ///         'target teams distribute parallel for' |
1129 ///         'target teams distribute parallel for simd' |
1130 ///         'target teams distribute simd' {clause}
1131 ///         annot_pragma_openmp_end
1132 ///
1133 StmtResult
1134 Parser::ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx) {
1135   assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
1136   ParenBraceBracketBalancer BalancerRAIIObj(*this);
1137   SmallVector<OMPClause *, 5> Clauses;
1138   SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, OMPC_unknown + 1>
1139   FirstClauses(OMPC_unknown + 1);
1140   unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
1141                         Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope;
1142   SourceLocation Loc = ConsumeAnnotationToken(), EndLoc;
1143   OpenMPDirectiveKind DKind = parseOpenMPDirectiveKind(*this);
1144   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
1145   // Name of critical directive.
1146   DeclarationNameInfo DirName;
1147   StmtResult Directive = StmtError();
1148   bool HasAssociatedStatement = true;
1149   bool FlushHasClause = false;
1150 
1151   switch (DKind) {
1152   case OMPD_threadprivate: {
1153     // FIXME: Should this be permitted in C++?
1154     if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
1155         ParsedStmtContext()) {
1156       Diag(Tok, diag::err_omp_immediate_directive)
1157           << getOpenMPDirectiveName(DKind) << 0;
1158     }
1159     ConsumeToken();
1160     ThreadprivateListParserHelper Helper(this);
1161     if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Helper, false)) {
1162       // The last seen token is annot_pragma_openmp_end - need to check for
1163       // extra tokens.
1164       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
1165         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
1166             << getOpenMPDirectiveName(OMPD_threadprivate);
1167         SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1168       }
1169       DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective(
1170           Loc, Helper.getIdentifiers());
1171       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
1172     }
1173     SkipUntil(tok::annot_pragma_openmp_end);
1174     break;
1175   }
1176   case OMPD_declare_reduction:
1177     ConsumeToken();
1178     if (DeclGroupPtrTy Res =
1179             ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) {
1180       // The last seen token is annot_pragma_openmp_end - need to check for
1181       // extra tokens.
1182       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
1183         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
1184             << getOpenMPDirectiveName(OMPD_declare_reduction);
1185         while (Tok.isNot(tok::annot_pragma_openmp_end))
1186           ConsumeAnyToken();
1187       }
1188       ConsumeAnyToken();
1189       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
1190     } else {
1191       SkipUntil(tok::annot_pragma_openmp_end);
1192     }
1193     break;
1194   case OMPD_declare_mapper: {
1195     ConsumeToken();
1196     if (DeclGroupPtrTy Res =
1197             ParseOpenMPDeclareMapperDirective(/*AS=*/AS_none)) {
1198       // Skip the last annot_pragma_openmp_end.
1199       ConsumeAnnotationToken();
1200       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
1201     } else {
1202       SkipUntil(tok::annot_pragma_openmp_end);
1203     }
1204     break;
1205   }
1206   case OMPD_flush:
1207     if (PP.LookAhead(0).is(tok::l_paren)) {
1208       FlushHasClause = true;
1209       // Push copy of the current token back to stream to properly parse
1210       // pseudo-clause OMPFlushClause.
1211       PP.EnterToken(Tok);
1212     }
1213     LLVM_FALLTHROUGH;
1214   case OMPD_taskyield:
1215   case OMPD_barrier:
1216   case OMPD_taskwait:
1217   case OMPD_cancellation_point:
1218   case OMPD_cancel:
1219   case OMPD_target_enter_data:
1220   case OMPD_target_exit_data:
1221   case OMPD_target_update:
1222     if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
1223         ParsedStmtContext()) {
1224       Diag(Tok, diag::err_omp_immediate_directive)
1225           << getOpenMPDirectiveName(DKind) << 0;
1226     }
1227     HasAssociatedStatement = false;
1228     // Fall through for further analysis.
1229     LLVM_FALLTHROUGH;
1230   case OMPD_parallel:
1231   case OMPD_simd:
1232   case OMPD_for:
1233   case OMPD_for_simd:
1234   case OMPD_sections:
1235   case OMPD_single:
1236   case OMPD_section:
1237   case OMPD_master:
1238   case OMPD_critical:
1239   case OMPD_parallel_for:
1240   case OMPD_parallel_for_simd:
1241   case OMPD_parallel_sections:
1242   case OMPD_task:
1243   case OMPD_ordered:
1244   case OMPD_atomic:
1245   case OMPD_target:
1246   case OMPD_teams:
1247   case OMPD_taskgroup:
1248   case OMPD_target_data:
1249   case OMPD_target_parallel:
1250   case OMPD_target_parallel_for:
1251   case OMPD_taskloop:
1252   case OMPD_taskloop_simd:
1253   case OMPD_distribute:
1254   case OMPD_distribute_parallel_for:
1255   case OMPD_distribute_parallel_for_simd:
1256   case OMPD_distribute_simd:
1257   case OMPD_target_parallel_for_simd:
1258   case OMPD_target_simd:
1259   case OMPD_teams_distribute:
1260   case OMPD_teams_distribute_simd:
1261   case OMPD_teams_distribute_parallel_for_simd:
1262   case OMPD_teams_distribute_parallel_for:
1263   case OMPD_target_teams:
1264   case OMPD_target_teams_distribute:
1265   case OMPD_target_teams_distribute_parallel_for:
1266   case OMPD_target_teams_distribute_parallel_for_simd:
1267   case OMPD_target_teams_distribute_simd: {
1268     ConsumeToken();
1269     // Parse directive name of the 'critical' directive if any.
1270     if (DKind == OMPD_critical) {
1271       BalancedDelimiterTracker T(*this, tok::l_paren,
1272                                  tok::annot_pragma_openmp_end);
1273       if (!T.consumeOpen()) {
1274         if (Tok.isAnyIdentifier()) {
1275           DirName =
1276               DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation());
1277           ConsumeAnyToken();
1278         } else {
1279           Diag(Tok, diag::err_omp_expected_identifier_for_critical);
1280         }
1281         T.consumeClose();
1282       }
1283     } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) {
1284       CancelRegion = parseOpenMPDirectiveKind(*this);
1285       if (Tok.isNot(tok::annot_pragma_openmp_end))
1286         ConsumeToken();
1287     }
1288 
1289     if (isOpenMPLoopDirective(DKind))
1290       ScopeFlags |= Scope::OpenMPLoopDirectiveScope;
1291     if (isOpenMPSimdDirective(DKind))
1292       ScopeFlags |= Scope::OpenMPSimdDirectiveScope;
1293     ParseScope OMPDirectiveScope(this, ScopeFlags);
1294     Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc);
1295 
1296     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1297       OpenMPClauseKind CKind =
1298           Tok.isAnnotation()
1299               ? OMPC_unknown
1300               : FlushHasClause ? OMPC_flush
1301                                : getOpenMPClauseKind(PP.getSpelling(Tok));
1302       Actions.StartOpenMPClause(CKind);
1303       FlushHasClause = false;
1304       OMPClause *Clause =
1305           ParseOpenMPClause(DKind, CKind, !FirstClauses[CKind].getInt());
1306       FirstClauses[CKind].setInt(true);
1307       if (Clause) {
1308         FirstClauses[CKind].setPointer(Clause);
1309         Clauses.push_back(Clause);
1310       }
1311 
1312       // Skip ',' if any.
1313       if (Tok.is(tok::comma))
1314         ConsumeToken();
1315       Actions.EndOpenMPClause();
1316     }
1317     // End location of the directive.
1318     EndLoc = Tok.getLocation();
1319     // Consume final annot_pragma_openmp_end.
1320     ConsumeAnnotationToken();
1321 
1322     // OpenMP [2.13.8, ordered Construct, Syntax]
1323     // If the depend clause is specified, the ordered construct is a stand-alone
1324     // directive.
1325     if (DKind == OMPD_ordered && FirstClauses[OMPC_depend].getInt()) {
1326       if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
1327           ParsedStmtContext()) {
1328         Diag(Loc, diag::err_omp_immediate_directive)
1329             << getOpenMPDirectiveName(DKind) << 1
1330             << getOpenMPClauseName(OMPC_depend);
1331       }
1332       HasAssociatedStatement = false;
1333     }
1334 
1335     StmtResult AssociatedStmt;
1336     if (HasAssociatedStatement) {
1337       // The body is a block scope like in Lambdas and Blocks.
1338       Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
1339       // FIXME: We create a bogus CompoundStmt scope to hold the contents of
1340       // the captured region. Code elsewhere assumes that any FunctionScopeInfo
1341       // should have at least one compound statement scope within it.
1342       AssociatedStmt = (Sema::CompoundScopeRAII(Actions), ParseStatement());
1343       AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
1344     } else if (DKind == OMPD_target_update || DKind == OMPD_target_enter_data ||
1345                DKind == OMPD_target_exit_data) {
1346       Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
1347       AssociatedStmt = (Sema::CompoundScopeRAII(Actions),
1348                         Actions.ActOnCompoundStmt(Loc, Loc, llvm::None,
1349                                                   /*isStmtExpr=*/false));
1350       AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
1351     }
1352     Directive = Actions.ActOnOpenMPExecutableDirective(
1353         DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc,
1354         EndLoc);
1355 
1356     // Exit scope.
1357     Actions.EndOpenMPDSABlock(Directive.get());
1358     OMPDirectiveScope.Exit();
1359     break;
1360   }
1361   case OMPD_declare_simd:
1362   case OMPD_declare_target:
1363   case OMPD_end_declare_target:
1364   case OMPD_requires:
1365     Diag(Tok, diag::err_omp_unexpected_directive)
1366         << 1 << getOpenMPDirectiveName(DKind);
1367     SkipUntil(tok::annot_pragma_openmp_end);
1368     break;
1369   case OMPD_unknown:
1370     Diag(Tok, diag::err_omp_unknown_directive);
1371     SkipUntil(tok::annot_pragma_openmp_end);
1372     break;
1373   }
1374   return Directive;
1375 }
1376 
1377 // Parses simple list:
1378 //   simple-variable-list:
1379 //         '(' id-expression {, id-expression} ')'
1380 //
1381 bool Parser::ParseOpenMPSimpleVarList(
1382     OpenMPDirectiveKind Kind,
1383     const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
1384         Callback,
1385     bool AllowScopeSpecifier) {
1386   // Parse '('.
1387   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1388   if (T.expectAndConsume(diag::err_expected_lparen_after,
1389                          getOpenMPDirectiveName(Kind)))
1390     return true;
1391   bool IsCorrect = true;
1392   bool NoIdentIsFound = true;
1393 
1394   // Read tokens while ')' or annot_pragma_openmp_end is not found.
1395   while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
1396     CXXScopeSpec SS;
1397     UnqualifiedId Name;
1398     // Read var name.
1399     Token PrevTok = Tok;
1400     NoIdentIsFound = false;
1401 
1402     if (AllowScopeSpecifier && getLangOpts().CPlusPlus &&
1403         ParseOptionalCXXScopeSpecifier(SS, nullptr, false)) {
1404       IsCorrect = false;
1405       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1406                 StopBeforeMatch);
1407     } else if (ParseUnqualifiedId(SS, false, false, false, false, nullptr,
1408                                   nullptr, Name)) {
1409       IsCorrect = false;
1410       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1411                 StopBeforeMatch);
1412     } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) &&
1413                Tok.isNot(tok::annot_pragma_openmp_end)) {
1414       IsCorrect = false;
1415       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1416                 StopBeforeMatch);
1417       Diag(PrevTok.getLocation(), diag::err_expected)
1418           << tok::identifier
1419           << SourceRange(PrevTok.getLocation(), PrevTokLocation);
1420     } else {
1421       Callback(SS, Actions.GetNameFromUnqualifiedId(Name));
1422     }
1423     // Consume ','.
1424     if (Tok.is(tok::comma)) {
1425       ConsumeToken();
1426     }
1427   }
1428 
1429   if (NoIdentIsFound) {
1430     Diag(Tok, diag::err_expected) << tok::identifier;
1431     IsCorrect = false;
1432   }
1433 
1434   // Parse ')'.
1435   IsCorrect = !T.consumeClose() && IsCorrect;
1436 
1437   return !IsCorrect;
1438 }
1439 
1440 /// Parsing of OpenMP clauses.
1441 ///
1442 ///    clause:
1443 ///       if-clause | final-clause | num_threads-clause | safelen-clause |
1444 ///       default-clause | private-clause | firstprivate-clause | shared-clause
1445 ///       | linear-clause | aligned-clause | collapse-clause |
1446 ///       lastprivate-clause | reduction-clause | proc_bind-clause |
1447 ///       schedule-clause | copyin-clause | copyprivate-clause | untied-clause |
1448 ///       mergeable-clause | flush-clause | read-clause | write-clause |
1449 ///       update-clause | capture-clause | seq_cst-clause | device-clause |
1450 ///       simdlen-clause | threads-clause | simd-clause | num_teams-clause |
1451 ///       thread_limit-clause | priority-clause | grainsize-clause |
1452 ///       nogroup-clause | num_tasks-clause | hint-clause | to-clause |
1453 ///       from-clause | is_device_ptr-clause | task_reduction-clause |
1454 ///       in_reduction-clause
1455 ///
1456 OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind,
1457                                      OpenMPClauseKind CKind, bool FirstClause) {
1458   OMPClause *Clause = nullptr;
1459   bool ErrorFound = false;
1460   bool WrongDirective = false;
1461   // Check if clause is allowed for the given directive.
1462   if (CKind != OMPC_unknown && !isAllowedClauseForDirective(DKind, CKind)) {
1463     Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind)
1464                                                << getOpenMPDirectiveName(DKind);
1465     ErrorFound = true;
1466     WrongDirective = true;
1467   }
1468 
1469   switch (CKind) {
1470   case OMPC_final:
1471   case OMPC_num_threads:
1472   case OMPC_safelen:
1473   case OMPC_simdlen:
1474   case OMPC_collapse:
1475   case OMPC_ordered:
1476   case OMPC_device:
1477   case OMPC_num_teams:
1478   case OMPC_thread_limit:
1479   case OMPC_priority:
1480   case OMPC_grainsize:
1481   case OMPC_num_tasks:
1482   case OMPC_hint:
1483     // OpenMP [2.5, Restrictions]
1484     //  At most one num_threads clause can appear on the directive.
1485     // OpenMP [2.8.1, simd construct, Restrictions]
1486     //  Only one safelen  clause can appear on a simd directive.
1487     //  Only one simdlen  clause can appear on a simd directive.
1488     //  Only one collapse clause can appear on a simd directive.
1489     // OpenMP [2.9.1, target data construct, Restrictions]
1490     //  At most one device clause can appear on the directive.
1491     // OpenMP [2.11.1, task Construct, Restrictions]
1492     //  At most one if clause can appear on the directive.
1493     //  At most one final clause can appear on the directive.
1494     // OpenMP [teams Construct, Restrictions]
1495     //  At most one num_teams clause can appear on the directive.
1496     //  At most one thread_limit clause can appear on the directive.
1497     // OpenMP [2.9.1, task Construct, Restrictions]
1498     // At most one priority clause can appear on the directive.
1499     // OpenMP [2.9.2, taskloop Construct, Restrictions]
1500     // At most one grainsize clause can appear on the directive.
1501     // OpenMP [2.9.2, taskloop Construct, Restrictions]
1502     // At most one num_tasks clause can appear on the directive.
1503     if (!FirstClause) {
1504       Diag(Tok, diag::err_omp_more_one_clause)
1505           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1506       ErrorFound = true;
1507     }
1508 
1509     if (CKind == OMPC_ordered && PP.LookAhead(/*N=*/0).isNot(tok::l_paren))
1510       Clause = ParseOpenMPClause(CKind, WrongDirective);
1511     else
1512       Clause = ParseOpenMPSingleExprClause(CKind, WrongDirective);
1513     break;
1514   case OMPC_default:
1515   case OMPC_proc_bind:
1516   case OMPC_atomic_default_mem_order:
1517     // OpenMP [2.14.3.1, Restrictions]
1518     //  Only a single default clause may be specified on a parallel, task or
1519     //  teams directive.
1520     // OpenMP [2.5, parallel Construct, Restrictions]
1521     //  At most one proc_bind clause can appear on the directive.
1522     // OpenMP [5.0, Requires directive, Restrictions]
1523     //  At most one atomic_default_mem_order clause can appear
1524     //  on the directive
1525     if (!FirstClause) {
1526       Diag(Tok, diag::err_omp_more_one_clause)
1527           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1528       ErrorFound = true;
1529     }
1530 
1531     Clause = ParseOpenMPSimpleClause(CKind, WrongDirective);
1532     break;
1533   case OMPC_schedule:
1534   case OMPC_dist_schedule:
1535   case OMPC_defaultmap:
1536     // OpenMP [2.7.1, Restrictions, p. 3]
1537     //  Only one schedule clause can appear on a loop directive.
1538     // OpenMP [2.10.4, Restrictions, p. 106]
1539     //  At most one defaultmap clause can appear on the directive.
1540     if (!FirstClause) {
1541       Diag(Tok, diag::err_omp_more_one_clause)
1542           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1543       ErrorFound = true;
1544     }
1545     LLVM_FALLTHROUGH;
1546 
1547   case OMPC_if:
1548     Clause = ParseOpenMPSingleExprWithArgClause(CKind, WrongDirective);
1549     break;
1550   case OMPC_nowait:
1551   case OMPC_untied:
1552   case OMPC_mergeable:
1553   case OMPC_read:
1554   case OMPC_write:
1555   case OMPC_update:
1556   case OMPC_capture:
1557   case OMPC_seq_cst:
1558   case OMPC_threads:
1559   case OMPC_simd:
1560   case OMPC_nogroup:
1561   case OMPC_unified_address:
1562   case OMPC_unified_shared_memory:
1563   case OMPC_reverse_offload:
1564   case OMPC_dynamic_allocators:
1565     // OpenMP [2.7.1, Restrictions, p. 9]
1566     //  Only one ordered clause can appear on a loop directive.
1567     // OpenMP [2.7.1, Restrictions, C/C++, p. 4]
1568     //  Only one nowait clause can appear on a for directive.
1569     // OpenMP [5.0, Requires directive, Restrictions]
1570     //   Each of the requires clauses can appear at most once on the directive.
1571     if (!FirstClause) {
1572       Diag(Tok, diag::err_omp_more_one_clause)
1573           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1574       ErrorFound = true;
1575     }
1576 
1577     Clause = ParseOpenMPClause(CKind, WrongDirective);
1578     break;
1579   case OMPC_private:
1580   case OMPC_firstprivate:
1581   case OMPC_lastprivate:
1582   case OMPC_shared:
1583   case OMPC_reduction:
1584   case OMPC_task_reduction:
1585   case OMPC_in_reduction:
1586   case OMPC_linear:
1587   case OMPC_aligned:
1588   case OMPC_copyin:
1589   case OMPC_copyprivate:
1590   case OMPC_flush:
1591   case OMPC_depend:
1592   case OMPC_map:
1593   case OMPC_to:
1594   case OMPC_from:
1595   case OMPC_use_device_ptr:
1596   case OMPC_is_device_ptr:
1597     Clause = ParseOpenMPVarListClause(DKind, CKind, WrongDirective);
1598     break;
1599   case OMPC_unknown:
1600     Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
1601         << getOpenMPDirectiveName(DKind);
1602     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1603     break;
1604   case OMPC_threadprivate:
1605   case OMPC_uniform:
1606     if (!WrongDirective)
1607       Diag(Tok, diag::err_omp_unexpected_clause)
1608           << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind);
1609     SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch);
1610     break;
1611   }
1612   return ErrorFound ? nullptr : Clause;
1613 }
1614 
1615 /// Parses simple expression in parens for single-expression clauses of OpenMP
1616 /// constructs.
1617 /// \param RLoc Returned location of right paren.
1618 ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName,
1619                                          SourceLocation &RLoc) {
1620   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1621   if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data()))
1622     return ExprError();
1623 
1624   SourceLocation ELoc = Tok.getLocation();
1625   ExprResult LHS(ParseCastExpression(
1626       /*isUnaryExpression=*/false, /*isAddressOfOperand=*/false, NotTypeCast));
1627   ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
1628   Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
1629 
1630   // Parse ')'.
1631   RLoc = Tok.getLocation();
1632   if (!T.consumeClose())
1633     RLoc = T.getCloseLocation();
1634 
1635   return Val;
1636 }
1637 
1638 /// Parsing of OpenMP clauses with single expressions like 'final',
1639 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
1640 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks' or 'hint'.
1641 ///
1642 ///    final-clause:
1643 ///      'final' '(' expression ')'
1644 ///
1645 ///    num_threads-clause:
1646 ///      'num_threads' '(' expression ')'
1647 ///
1648 ///    safelen-clause:
1649 ///      'safelen' '(' expression ')'
1650 ///
1651 ///    simdlen-clause:
1652 ///      'simdlen' '(' expression ')'
1653 ///
1654 ///    collapse-clause:
1655 ///      'collapse' '(' expression ')'
1656 ///
1657 ///    priority-clause:
1658 ///      'priority' '(' expression ')'
1659 ///
1660 ///    grainsize-clause:
1661 ///      'grainsize' '(' expression ')'
1662 ///
1663 ///    num_tasks-clause:
1664 ///      'num_tasks' '(' expression ')'
1665 ///
1666 ///    hint-clause:
1667 ///      'hint' '(' expression ')'
1668 ///
1669 OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
1670                                                bool ParseOnly) {
1671   SourceLocation Loc = ConsumeToken();
1672   SourceLocation LLoc = Tok.getLocation();
1673   SourceLocation RLoc;
1674 
1675   ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
1676 
1677   if (Val.isInvalid())
1678     return nullptr;
1679 
1680   if (ParseOnly)
1681     return nullptr;
1682   return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc);
1683 }
1684 
1685 /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
1686 ///
1687 ///    default-clause:
1688 ///         'default' '(' 'none' | 'shared' ')
1689 ///
1690 ///    proc_bind-clause:
1691 ///         'proc_bind' '(' 'master' | 'close' | 'spread' ')
1692 ///
1693 OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind,
1694                                            bool ParseOnly) {
1695   SourceLocation Loc = Tok.getLocation();
1696   SourceLocation LOpen = ConsumeToken();
1697   // Parse '('.
1698   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1699   if (T.expectAndConsume(diag::err_expected_lparen_after,
1700                          getOpenMPClauseName(Kind)))
1701     return nullptr;
1702 
1703   unsigned Type = getOpenMPSimpleClauseType(
1704       Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1705   SourceLocation TypeLoc = Tok.getLocation();
1706   if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1707       Tok.isNot(tok::annot_pragma_openmp_end))
1708     ConsumeAnyToken();
1709 
1710   // Parse ')'.
1711   SourceLocation RLoc = Tok.getLocation();
1712   if (!T.consumeClose())
1713     RLoc = T.getCloseLocation();
1714 
1715   if (ParseOnly)
1716     return nullptr;
1717   return Actions.ActOnOpenMPSimpleClause(Kind, Type, TypeLoc, LOpen, Loc, RLoc);
1718 }
1719 
1720 /// Parsing of OpenMP clauses like 'ordered'.
1721 ///
1722 ///    ordered-clause:
1723 ///         'ordered'
1724 ///
1725 ///    nowait-clause:
1726 ///         'nowait'
1727 ///
1728 ///    untied-clause:
1729 ///         'untied'
1730 ///
1731 ///    mergeable-clause:
1732 ///         'mergeable'
1733 ///
1734 ///    read-clause:
1735 ///         'read'
1736 ///
1737 ///    threads-clause:
1738 ///         'threads'
1739 ///
1740 ///    simd-clause:
1741 ///         'simd'
1742 ///
1743 ///    nogroup-clause:
1744 ///         'nogroup'
1745 ///
1746 OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly) {
1747   SourceLocation Loc = Tok.getLocation();
1748   ConsumeAnyToken();
1749 
1750   if (ParseOnly)
1751     return nullptr;
1752   return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation());
1753 }
1754 
1755 
1756 /// Parsing of OpenMP clauses with single expressions and some additional
1757 /// argument like 'schedule' or 'dist_schedule'.
1758 ///
1759 ///    schedule-clause:
1760 ///      'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
1761 ///      ')'
1762 ///
1763 ///    if-clause:
1764 ///      'if' '(' [ directive-name-modifier ':' ] expression ')'
1765 ///
1766 ///    defaultmap:
1767 ///      'defaultmap' '(' modifier ':' kind ')'
1768 ///
1769 OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
1770                                                       bool ParseOnly) {
1771   SourceLocation Loc = ConsumeToken();
1772   SourceLocation DelimLoc;
1773   // Parse '('.
1774   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1775   if (T.expectAndConsume(diag::err_expected_lparen_after,
1776                          getOpenMPClauseName(Kind)))
1777     return nullptr;
1778 
1779   ExprResult Val;
1780   SmallVector<unsigned, 4> Arg;
1781   SmallVector<SourceLocation, 4> KLoc;
1782   if (Kind == OMPC_schedule) {
1783     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
1784     Arg.resize(NumberOfElements);
1785     KLoc.resize(NumberOfElements);
1786     Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown;
1787     Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown;
1788     Arg[ScheduleKind] = OMPC_SCHEDULE_unknown;
1789     unsigned KindModifier = getOpenMPSimpleClauseType(
1790         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1791     if (KindModifier > OMPC_SCHEDULE_unknown) {
1792       // Parse 'modifier'
1793       Arg[Modifier1] = KindModifier;
1794       KLoc[Modifier1] = Tok.getLocation();
1795       if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1796           Tok.isNot(tok::annot_pragma_openmp_end))
1797         ConsumeAnyToken();
1798       if (Tok.is(tok::comma)) {
1799         // Parse ',' 'modifier'
1800         ConsumeAnyToken();
1801         KindModifier = getOpenMPSimpleClauseType(
1802             Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1803         Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown
1804                              ? KindModifier
1805                              : (unsigned)OMPC_SCHEDULE_unknown;
1806         KLoc[Modifier2] = Tok.getLocation();
1807         if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1808             Tok.isNot(tok::annot_pragma_openmp_end))
1809           ConsumeAnyToken();
1810       }
1811       // Parse ':'
1812       if (Tok.is(tok::colon))
1813         ConsumeAnyToken();
1814       else
1815         Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier";
1816       KindModifier = getOpenMPSimpleClauseType(
1817           Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1818     }
1819     Arg[ScheduleKind] = KindModifier;
1820     KLoc[ScheduleKind] = Tok.getLocation();
1821     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1822         Tok.isNot(tok::annot_pragma_openmp_end))
1823       ConsumeAnyToken();
1824     if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static ||
1825          Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic ||
1826          Arg[ScheduleKind] == OMPC_SCHEDULE_guided) &&
1827         Tok.is(tok::comma))
1828       DelimLoc = ConsumeAnyToken();
1829   } else if (Kind == OMPC_dist_schedule) {
1830     Arg.push_back(getOpenMPSimpleClauseType(
1831         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1832     KLoc.push_back(Tok.getLocation());
1833     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1834         Tok.isNot(tok::annot_pragma_openmp_end))
1835       ConsumeAnyToken();
1836     if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma))
1837       DelimLoc = ConsumeAnyToken();
1838   } else if (Kind == OMPC_defaultmap) {
1839     // Get a defaultmap modifier
1840     Arg.push_back(getOpenMPSimpleClauseType(
1841         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1842     KLoc.push_back(Tok.getLocation());
1843     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1844         Tok.isNot(tok::annot_pragma_openmp_end))
1845       ConsumeAnyToken();
1846     // Parse ':'
1847     if (Tok.is(tok::colon))
1848       ConsumeAnyToken();
1849     else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown)
1850       Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier";
1851     // Get a defaultmap kind
1852     Arg.push_back(getOpenMPSimpleClauseType(
1853         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1854     KLoc.push_back(Tok.getLocation());
1855     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1856         Tok.isNot(tok::annot_pragma_openmp_end))
1857       ConsumeAnyToken();
1858   } else {
1859     assert(Kind == OMPC_if);
1860     KLoc.push_back(Tok.getLocation());
1861     TentativeParsingAction TPA(*this);
1862     Arg.push_back(parseOpenMPDirectiveKind(*this));
1863     if (Arg.back() != OMPD_unknown) {
1864       ConsumeToken();
1865       if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) {
1866         TPA.Commit();
1867         DelimLoc = ConsumeToken();
1868       } else {
1869         TPA.Revert();
1870         Arg.back() = OMPD_unknown;
1871       }
1872     } else {
1873       TPA.Revert();
1874     }
1875   }
1876 
1877   bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) ||
1878                           (Kind == OMPC_dist_schedule && DelimLoc.isValid()) ||
1879                           Kind == OMPC_if;
1880   if (NeedAnExpression) {
1881     SourceLocation ELoc = Tok.getLocation();
1882     ExprResult LHS(ParseCastExpression(false, false, NotTypeCast));
1883     Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
1884     Val =
1885         Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
1886   }
1887 
1888   // Parse ')'.
1889   SourceLocation RLoc = Tok.getLocation();
1890   if (!T.consumeClose())
1891     RLoc = T.getCloseLocation();
1892 
1893   if (NeedAnExpression && Val.isInvalid())
1894     return nullptr;
1895 
1896   if (ParseOnly)
1897     return nullptr;
1898   return Actions.ActOnOpenMPSingleExprWithArgClause(
1899       Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc, RLoc);
1900 }
1901 
1902 static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec,
1903                              UnqualifiedId &ReductionId) {
1904   if (ReductionIdScopeSpec.isEmpty()) {
1905     auto OOK = OO_None;
1906     switch (P.getCurToken().getKind()) {
1907     case tok::plus:
1908       OOK = OO_Plus;
1909       break;
1910     case tok::minus:
1911       OOK = OO_Minus;
1912       break;
1913     case tok::star:
1914       OOK = OO_Star;
1915       break;
1916     case tok::amp:
1917       OOK = OO_Amp;
1918       break;
1919     case tok::pipe:
1920       OOK = OO_Pipe;
1921       break;
1922     case tok::caret:
1923       OOK = OO_Caret;
1924       break;
1925     case tok::ampamp:
1926       OOK = OO_AmpAmp;
1927       break;
1928     case tok::pipepipe:
1929       OOK = OO_PipePipe;
1930       break;
1931     default:
1932       break;
1933     }
1934     if (OOK != OO_None) {
1935       SourceLocation OpLoc = P.ConsumeToken();
1936       SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()};
1937       ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations);
1938       return false;
1939     }
1940   }
1941   return P.ParseUnqualifiedId(ReductionIdScopeSpec, /*EnteringContext*/ false,
1942                               /*AllowDestructorName*/ false,
1943                               /*AllowConstructorName*/ false,
1944                               /*AllowDeductionGuide*/ false,
1945                               nullptr, nullptr, ReductionId);
1946 }
1947 
1948 /// Checks if the token is a valid map-type-modifier.
1949 static OpenMPMapModifierKind isMapModifier(Parser &P) {
1950   Token Tok = P.getCurToken();
1951   if (!Tok.is(tok::identifier))
1952     return OMPC_MAP_MODIFIER_unknown;
1953 
1954   Preprocessor &PP = P.getPreprocessor();
1955   OpenMPMapModifierKind TypeModifier = static_cast<OpenMPMapModifierKind>(
1956       getOpenMPSimpleClauseType(OMPC_map, PP.getSpelling(Tok)));
1957   return TypeModifier;
1958 }
1959 
1960 /// Parse the mapper modifier in map, to, and from clauses.
1961 bool Parser::parseMapperModifier(OpenMPVarListDataTy &Data) {
1962   // Parse '('.
1963   BalancedDelimiterTracker T(*this, tok::l_paren, tok::colon);
1964   if (T.expectAndConsume(diag::err_expected_lparen_after, "mapper")) {
1965     SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
1966               StopBeforeMatch);
1967     return true;
1968   }
1969   // Parse mapper-identifier
1970   if (getLangOpts().CPlusPlus)
1971     ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
1972                                    /*ObjectType=*/nullptr,
1973                                    /*EnteringContext=*/false);
1974   if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
1975     Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
1976     SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
1977               StopBeforeMatch);
1978     return true;
1979   }
1980   auto &DeclNames = Actions.getASTContext().DeclarationNames;
1981   Data.ReductionOrMapperId = DeclarationNameInfo(
1982       DeclNames.getIdentifier(Tok.getIdentifierInfo()), Tok.getLocation());
1983   ConsumeToken();
1984   // Parse ')'.
1985   return T.consumeClose();
1986 }
1987 
1988 /// Parse map-type-modifiers in map clause.
1989 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
1990 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier)
1991 bool Parser::parseMapTypeModifiers(OpenMPVarListDataTy &Data) {
1992   while (getCurToken().isNot(tok::colon)) {
1993     OpenMPMapModifierKind TypeModifier = isMapModifier(*this);
1994     if (TypeModifier == OMPC_MAP_MODIFIER_always ||
1995         TypeModifier == OMPC_MAP_MODIFIER_close) {
1996       Data.MapTypeModifiers.push_back(TypeModifier);
1997       Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
1998       ConsumeToken();
1999     } else if (TypeModifier == OMPC_MAP_MODIFIER_mapper) {
2000       Data.MapTypeModifiers.push_back(TypeModifier);
2001       Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
2002       ConsumeToken();
2003       if (parseMapperModifier(Data))
2004         return true;
2005     } else {
2006       // For the case of unknown map-type-modifier or a map-type.
2007       // Map-type is followed by a colon; the function returns when it
2008       // encounters a token followed by a colon.
2009       if (Tok.is(tok::comma)) {
2010         Diag(Tok, diag::err_omp_map_type_modifier_missing);
2011         ConsumeToken();
2012         continue;
2013       }
2014       // Potential map-type token as it is followed by a colon.
2015       if (PP.LookAhead(0).is(tok::colon))
2016         return false;
2017       Diag(Tok, diag::err_omp_unknown_map_type_modifier);
2018       ConsumeToken();
2019     }
2020     if (getCurToken().is(tok::comma))
2021       ConsumeToken();
2022   }
2023   return false;
2024 }
2025 
2026 /// Checks if the token is a valid map-type.
2027 static OpenMPMapClauseKind isMapType(Parser &P) {
2028   Token Tok = P.getCurToken();
2029   // The map-type token can be either an identifier or the C++ delete keyword.
2030   if (!Tok.isOneOf(tok::identifier, tok::kw_delete))
2031     return OMPC_MAP_unknown;
2032   Preprocessor &PP = P.getPreprocessor();
2033   OpenMPMapClauseKind MapType = static_cast<OpenMPMapClauseKind>(
2034       getOpenMPSimpleClauseType(OMPC_map, PP.getSpelling(Tok)));
2035   return MapType;
2036 }
2037 
2038 /// Parse map-type in map clause.
2039 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
2040 /// where, map-type ::= to | from | tofrom | alloc | release | delete
2041 static void parseMapType(Parser &P, Parser::OpenMPVarListDataTy &Data) {
2042   Token Tok = P.getCurToken();
2043   if (Tok.is(tok::colon)) {
2044     P.Diag(Tok, diag::err_omp_map_type_missing);
2045     return;
2046   }
2047   Data.MapType = isMapType(P);
2048   if (Data.MapType == OMPC_MAP_unknown)
2049     P.Diag(Tok, diag::err_omp_unknown_map_type);
2050   P.ConsumeToken();
2051 }
2052 
2053 /// Parses clauses with list.
2054 bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind,
2055                                 OpenMPClauseKind Kind,
2056                                 SmallVectorImpl<Expr *> &Vars,
2057                                 OpenMPVarListDataTy &Data) {
2058   UnqualifiedId UnqualifiedReductionId;
2059   bool InvalidReductionId = false;
2060   bool IsInvalidMapperModifier = false;
2061 
2062   // Parse '('.
2063   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
2064   if (T.expectAndConsume(diag::err_expected_lparen_after,
2065                          getOpenMPClauseName(Kind)))
2066     return true;
2067 
2068   bool NeedRParenForLinear = false;
2069   BalancedDelimiterTracker LinearT(*this, tok::l_paren,
2070                                   tok::annot_pragma_openmp_end);
2071   // Handle reduction-identifier for reduction clause.
2072   if (Kind == OMPC_reduction || Kind == OMPC_task_reduction ||
2073       Kind == OMPC_in_reduction) {
2074     ColonProtectionRAIIObject ColonRAII(*this);
2075     if (getLangOpts().CPlusPlus)
2076       ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
2077                                      /*ObjectType=*/nullptr,
2078                                      /*EnteringContext=*/false);
2079     InvalidReductionId = ParseReductionId(
2080         *this, Data.ReductionOrMapperIdScopeSpec, UnqualifiedReductionId);
2081     if (InvalidReductionId) {
2082       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
2083                 StopBeforeMatch);
2084     }
2085     if (Tok.is(tok::colon))
2086       Data.ColonLoc = ConsumeToken();
2087     else
2088       Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier";
2089     if (!InvalidReductionId)
2090       Data.ReductionOrMapperId =
2091           Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId);
2092   } else if (Kind == OMPC_depend) {
2093   // Handle dependency type for depend clause.
2094     ColonProtectionRAIIObject ColonRAII(*this);
2095     Data.DepKind =
2096         static_cast<OpenMPDependClauseKind>(getOpenMPSimpleClauseType(
2097             Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : ""));
2098     Data.DepLinMapLoc = Tok.getLocation();
2099 
2100     if (Data.DepKind == OMPC_DEPEND_unknown) {
2101       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
2102                 StopBeforeMatch);
2103     } else {
2104       ConsumeToken();
2105       // Special processing for depend(source) clause.
2106       if (DKind == OMPD_ordered && Data.DepKind == OMPC_DEPEND_source) {
2107         // Parse ')'.
2108         T.consumeClose();
2109         return false;
2110       }
2111     }
2112     if (Tok.is(tok::colon)) {
2113       Data.ColonLoc = ConsumeToken();
2114     } else {
2115       Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren
2116                                       : diag::warn_pragma_expected_colon)
2117           << "dependency type";
2118     }
2119   } else if (Kind == OMPC_linear) {
2120     // Try to parse modifier if any.
2121     if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) {
2122       Data.LinKind = static_cast<OpenMPLinearClauseKind>(
2123           getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)));
2124       Data.DepLinMapLoc = ConsumeToken();
2125       LinearT.consumeOpen();
2126       NeedRParenForLinear = true;
2127     }
2128   } else if (Kind == OMPC_map) {
2129     // Handle map type for map clause.
2130     ColonProtectionRAIIObject ColonRAII(*this);
2131 
2132     // The first identifier may be a list item, a map-type or a
2133     // map-type-modifier. The map-type can also be delete which has the same
2134     // spelling of the C++ delete keyword.
2135     Data.DepLinMapLoc = Tok.getLocation();
2136 
2137     // Check for presence of a colon in the map clause.
2138     TentativeParsingAction TPA(*this);
2139     bool ColonPresent = false;
2140     if (SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
2141         StopBeforeMatch)) {
2142       if (Tok.is(tok::colon))
2143         ColonPresent = true;
2144     }
2145     TPA.Revert();
2146     // Only parse map-type-modifier[s] and map-type if a colon is present in
2147     // the map clause.
2148     if (ColonPresent) {
2149       IsInvalidMapperModifier = parseMapTypeModifiers(Data);
2150       if (!IsInvalidMapperModifier)
2151         parseMapType(*this, Data);
2152       else
2153         SkipUntil(tok::colon, tok::annot_pragma_openmp_end, StopBeforeMatch);
2154     }
2155     if (Data.MapType == OMPC_MAP_unknown) {
2156       Data.MapType = OMPC_MAP_tofrom;
2157       Data.IsMapTypeImplicit = true;
2158     }
2159 
2160     if (Tok.is(tok::colon))
2161       Data.ColonLoc = ConsumeToken();
2162   } else if (Kind == OMPC_to || Kind == OMPC_from) {
2163     if (Tok.is(tok::identifier)) {
2164       bool IsMapperModifier = false;
2165       if (Kind == OMPC_to) {
2166         auto Modifier = static_cast<OpenMPToModifierKind>(
2167             getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)));
2168         if (Modifier == OMPC_TO_MODIFIER_mapper)
2169           IsMapperModifier = true;
2170       } else {
2171         auto Modifier = static_cast<OpenMPFromModifierKind>(
2172             getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)));
2173         if (Modifier == OMPC_FROM_MODIFIER_mapper)
2174           IsMapperModifier = true;
2175       }
2176       if (IsMapperModifier) {
2177         // Parse the mapper modifier.
2178         ConsumeToken();
2179         IsInvalidMapperModifier = parseMapperModifier(Data);
2180         if (Tok.isNot(tok::colon)) {
2181           if (!IsInvalidMapperModifier)
2182             Diag(Tok, diag::warn_pragma_expected_colon) << ")";
2183           SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
2184                     StopBeforeMatch);
2185         }
2186         // Consume ':'.
2187         if (Tok.is(tok::colon))
2188           ConsumeToken();
2189       }
2190     }
2191   }
2192 
2193   bool IsComma =
2194       (Kind != OMPC_reduction && Kind != OMPC_task_reduction &&
2195        Kind != OMPC_in_reduction && Kind != OMPC_depend && Kind != OMPC_map) ||
2196       (Kind == OMPC_reduction && !InvalidReductionId) ||
2197       (Kind == OMPC_map && Data.MapType != OMPC_MAP_unknown) ||
2198       (Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown);
2199   const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned);
2200   while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) &&
2201                      Tok.isNot(tok::annot_pragma_openmp_end))) {
2202     ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
2203     // Parse variable
2204     ExprResult VarExpr =
2205         Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2206     if (VarExpr.isUsable()) {
2207       Vars.push_back(VarExpr.get());
2208     } else {
2209       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
2210                 StopBeforeMatch);
2211     }
2212     // Skip ',' if any
2213     IsComma = Tok.is(tok::comma);
2214     if (IsComma)
2215       ConsumeToken();
2216     else if (Tok.isNot(tok::r_paren) &&
2217              Tok.isNot(tok::annot_pragma_openmp_end) &&
2218              (!MayHaveTail || Tok.isNot(tok::colon)))
2219       Diag(Tok, diag::err_omp_expected_punc)
2220           << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush)
2221                                    : getOpenMPClauseName(Kind))
2222           << (Kind == OMPC_flush);
2223   }
2224 
2225   // Parse ')' for linear clause with modifier.
2226   if (NeedRParenForLinear)
2227     LinearT.consumeClose();
2228 
2229   // Parse ':' linear-step (or ':' alignment).
2230   const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon);
2231   if (MustHaveTail) {
2232     Data.ColonLoc = Tok.getLocation();
2233     SourceLocation ELoc = ConsumeToken();
2234     ExprResult Tail = ParseAssignmentExpression();
2235     Tail =
2236         Actions.ActOnFinishFullExpr(Tail.get(), ELoc, /*DiscardedValue*/ false);
2237     if (Tail.isUsable())
2238       Data.TailExpr = Tail.get();
2239     else
2240       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
2241                 StopBeforeMatch);
2242   }
2243 
2244   // Parse ')'.
2245   Data.RLoc = Tok.getLocation();
2246   if (!T.consumeClose())
2247     Data.RLoc = T.getCloseLocation();
2248   return (Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown &&
2249           Vars.empty()) ||
2250          (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) ||
2251          (MustHaveTail && !Data.TailExpr) || InvalidReductionId ||
2252          IsInvalidMapperModifier;
2253 }
2254 
2255 /// Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate',
2256 /// 'shared', 'copyin', 'copyprivate', 'flush', 'reduction', 'task_reduction' or
2257 /// 'in_reduction'.
2258 ///
2259 ///    private-clause:
2260 ///       'private' '(' list ')'
2261 ///    firstprivate-clause:
2262 ///       'firstprivate' '(' list ')'
2263 ///    lastprivate-clause:
2264 ///       'lastprivate' '(' list ')'
2265 ///    shared-clause:
2266 ///       'shared' '(' list ')'
2267 ///    linear-clause:
2268 ///       'linear' '(' linear-list [ ':' linear-step ] ')'
2269 ///    aligned-clause:
2270 ///       'aligned' '(' list [ ':' alignment ] ')'
2271 ///    reduction-clause:
2272 ///       'reduction' '(' reduction-identifier ':' list ')'
2273 ///    task_reduction-clause:
2274 ///       'task_reduction' '(' reduction-identifier ':' list ')'
2275 ///    in_reduction-clause:
2276 ///       'in_reduction' '(' reduction-identifier ':' list ')'
2277 ///    copyprivate-clause:
2278 ///       'copyprivate' '(' list ')'
2279 ///    flush-clause:
2280 ///       'flush' '(' list ')'
2281 ///    depend-clause:
2282 ///       'depend' '(' in | out | inout : list | source ')'
2283 ///    map-clause:
2284 ///       'map' '(' [ [ always [,] ] [ close [,] ]
2285 ///          [ mapper '(' mapper-identifier ')' [,] ]
2286 ///          to | from | tofrom | alloc | release | delete ':' ] list ')';
2287 ///    to-clause:
2288 ///       'to' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
2289 ///    from-clause:
2290 ///       'from' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
2291 ///    use_device_ptr-clause:
2292 ///       'use_device_ptr' '(' list ')'
2293 ///    is_device_ptr-clause:
2294 ///       'is_device_ptr' '(' list ')'
2295 ///
2296 /// For 'linear' clause linear-list may have the following forms:
2297 ///  list
2298 ///  modifier(list)
2299 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
2300 OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2301                                             OpenMPClauseKind Kind,
2302                                             bool ParseOnly) {
2303   SourceLocation Loc = Tok.getLocation();
2304   SourceLocation LOpen = ConsumeToken();
2305   SmallVector<Expr *, 4> Vars;
2306   OpenMPVarListDataTy Data;
2307 
2308   if (ParseOpenMPVarList(DKind, Kind, Vars, Data))
2309     return nullptr;
2310 
2311   if (ParseOnly)
2312     return nullptr;
2313   OMPVarListLocTy Locs(Loc, LOpen, Data.RLoc);
2314   return Actions.ActOnOpenMPVarListClause(
2315       Kind, Vars, Data.TailExpr, Locs, Data.ColonLoc,
2316       Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId, Data.DepKind,
2317       Data.LinKind, Data.MapTypeModifiers, Data.MapTypeModifiersLoc,
2318       Data.MapType, Data.IsMapTypeImplicit, Data.DepLinMapLoc);
2319 }
2320 
2321