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/OpenMPClause.h"
15 #include "clang/AST/StmtOpenMP.h"
16 #include "clang/Basic/OpenMPKinds.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Basic/TokenKinds.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Parse/Parser.h"
21 #include "clang/Parse/RAIIObjectsForParser.h"
22 #include "clang/Sema/Scope.h"
23 #include "llvm/ADT/PointerIntPair.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/UniqueVector.h"
26 #include "llvm/Frontend/OpenMP/OMPAssume.h"
27 #include "llvm/Frontend/OpenMP/OMPContext.h"
28 
29 using namespace clang;
30 using namespace llvm::omp;
31 
32 //===----------------------------------------------------------------------===//
33 // OpenMP declarative directives.
34 //===----------------------------------------------------------------------===//
35 
36 namespace {
37 enum OpenMPDirectiveKindEx {
38   OMPD_cancellation = llvm::omp::Directive_enumSize + 1,
39   OMPD_data,
40   OMPD_declare,
41   OMPD_end,
42   OMPD_end_declare,
43   OMPD_enter,
44   OMPD_exit,
45   OMPD_point,
46   OMPD_reduction,
47   OMPD_target_enter,
48   OMPD_target_exit,
49   OMPD_update,
50   OMPD_distribute_parallel,
51   OMPD_teams_distribute_parallel,
52   OMPD_target_teams_distribute_parallel,
53   OMPD_mapper,
54   OMPD_variant,
55   OMPD_begin,
56   OMPD_begin_declare,
57 };
58 
59 // Helper to unify the enum class OpenMPDirectiveKind with its extension
60 // the OpenMPDirectiveKindEx enum which allows to use them together as if they
61 // are unsigned values.
62 struct OpenMPDirectiveKindExWrapper {
63   OpenMPDirectiveKindExWrapper(unsigned Value) : Value(Value) {}
64   OpenMPDirectiveKindExWrapper(OpenMPDirectiveKind DK) : Value(unsigned(DK)) {}
65   bool operator==(OpenMPDirectiveKindExWrapper V) const {
66     return Value == V.Value;
67   }
68   bool operator!=(OpenMPDirectiveKindExWrapper V) const {
69     return Value != V.Value;
70   }
71   bool operator==(OpenMPDirectiveKind V) const { return Value == unsigned(V); }
72   bool operator!=(OpenMPDirectiveKind V) const { return Value != unsigned(V); }
73   bool operator<(OpenMPDirectiveKind V) const { return Value < unsigned(V); }
74   operator unsigned() const { return Value; }
75   operator OpenMPDirectiveKind() const { return OpenMPDirectiveKind(Value); }
76   unsigned Value;
77 };
78 
79 class DeclDirectiveListParserHelper final {
80   SmallVector<Expr *, 4> Identifiers;
81   Parser *P;
82   OpenMPDirectiveKind Kind;
83 
84 public:
85   DeclDirectiveListParserHelper(Parser *P, OpenMPDirectiveKind Kind)
86       : P(P), Kind(Kind) {}
87   void operator()(CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
88     ExprResult Res = P->getActions().ActOnOpenMPIdExpression(
89         P->getCurScope(), SS, NameInfo, Kind);
90     if (Res.isUsable())
91       Identifiers.push_back(Res.get());
92   }
93   llvm::ArrayRef<Expr *> getIdentifiers() const { return Identifiers; }
94 };
95 } // namespace
96 
97 // Map token string to extended OMP token kind that are
98 // OpenMPDirectiveKind + OpenMPDirectiveKindEx.
99 static unsigned getOpenMPDirectiveKindEx(StringRef S) {
100   OpenMPDirectiveKindExWrapper DKind = getOpenMPDirectiveKind(S);
101   if (DKind != OMPD_unknown)
102     return DKind;
103 
104   return llvm::StringSwitch<OpenMPDirectiveKindExWrapper>(S)
105       .Case("cancellation", OMPD_cancellation)
106       .Case("data", OMPD_data)
107       .Case("declare", OMPD_declare)
108       .Case("end", OMPD_end)
109       .Case("enter", OMPD_enter)
110       .Case("exit", OMPD_exit)
111       .Case("point", OMPD_point)
112       .Case("reduction", OMPD_reduction)
113       .Case("update", OMPD_update)
114       .Case("mapper", OMPD_mapper)
115       .Case("variant", OMPD_variant)
116       .Case("begin", OMPD_begin)
117       .Default(OMPD_unknown);
118 }
119 
120 static OpenMPDirectiveKindExWrapper parseOpenMPDirectiveKind(Parser &P) {
121   // Array of foldings: F[i][0] F[i][1] ===> F[i][2].
122   // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd
123   // TODO: add other combined directives in topological order.
124   static const OpenMPDirectiveKindExWrapper F[][3] = {
125       {OMPD_begin, OMPD_declare, OMPD_begin_declare},
126       {OMPD_begin, OMPD_assumes, OMPD_begin_assumes},
127       {OMPD_end, OMPD_declare, OMPD_end_declare},
128       {OMPD_end, OMPD_assumes, OMPD_end_assumes},
129       {OMPD_cancellation, OMPD_point, OMPD_cancellation_point},
130       {OMPD_declare, OMPD_reduction, OMPD_declare_reduction},
131       {OMPD_declare, OMPD_mapper, OMPD_declare_mapper},
132       {OMPD_declare, OMPD_simd, OMPD_declare_simd},
133       {OMPD_declare, OMPD_target, OMPD_declare_target},
134       {OMPD_declare, OMPD_variant, OMPD_declare_variant},
135       {OMPD_begin_declare, OMPD_target, OMPD_begin_declare_target},
136       {OMPD_begin_declare, OMPD_variant, OMPD_begin_declare_variant},
137       {OMPD_end_declare, OMPD_variant, OMPD_end_declare_variant},
138       {OMPD_distribute, OMPD_parallel, OMPD_distribute_parallel},
139       {OMPD_distribute_parallel, OMPD_for, OMPD_distribute_parallel_for},
140       {OMPD_distribute_parallel_for, OMPD_simd,
141        OMPD_distribute_parallel_for_simd},
142       {OMPD_distribute, OMPD_simd, OMPD_distribute_simd},
143       {OMPD_end_declare, OMPD_target, OMPD_end_declare_target},
144       {OMPD_target, OMPD_data, OMPD_target_data},
145       {OMPD_target, OMPD_enter, OMPD_target_enter},
146       {OMPD_target, OMPD_exit, OMPD_target_exit},
147       {OMPD_target, OMPD_update, OMPD_target_update},
148       {OMPD_target_enter, OMPD_data, OMPD_target_enter_data},
149       {OMPD_target_exit, OMPD_data, OMPD_target_exit_data},
150       {OMPD_for, OMPD_simd, OMPD_for_simd},
151       {OMPD_parallel, OMPD_for, OMPD_parallel_for},
152       {OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd},
153       {OMPD_parallel, OMPD_loop, OMPD_parallel_loop},
154       {OMPD_parallel, OMPD_sections, OMPD_parallel_sections},
155       {OMPD_taskloop, OMPD_simd, OMPD_taskloop_simd},
156       {OMPD_target, OMPD_parallel, OMPD_target_parallel},
157       {OMPD_target, OMPD_simd, OMPD_target_simd},
158       {OMPD_target_parallel, OMPD_loop, OMPD_target_parallel_loop},
159       {OMPD_target_parallel, OMPD_for, OMPD_target_parallel_for},
160       {OMPD_target_parallel_for, OMPD_simd, OMPD_target_parallel_for_simd},
161       {OMPD_teams, OMPD_distribute, OMPD_teams_distribute},
162       {OMPD_teams_distribute, OMPD_simd, OMPD_teams_distribute_simd},
163       {OMPD_teams_distribute, OMPD_parallel, OMPD_teams_distribute_parallel},
164       {OMPD_teams_distribute_parallel, OMPD_for,
165        OMPD_teams_distribute_parallel_for},
166       {OMPD_teams_distribute_parallel_for, OMPD_simd,
167        OMPD_teams_distribute_parallel_for_simd},
168       {OMPD_teams, OMPD_loop, OMPD_teams_loop},
169       {OMPD_target, OMPD_teams, OMPD_target_teams},
170       {OMPD_target_teams, OMPD_distribute, OMPD_target_teams_distribute},
171       {OMPD_target_teams, OMPD_loop, OMPD_target_teams_loop},
172       {OMPD_target_teams_distribute, OMPD_parallel,
173        OMPD_target_teams_distribute_parallel},
174       {OMPD_target_teams_distribute, OMPD_simd,
175        OMPD_target_teams_distribute_simd},
176       {OMPD_target_teams_distribute_parallel, OMPD_for,
177        OMPD_target_teams_distribute_parallel_for},
178       {OMPD_target_teams_distribute_parallel_for, OMPD_simd,
179        OMPD_target_teams_distribute_parallel_for_simd},
180       {OMPD_master, OMPD_taskloop, OMPD_master_taskloop},
181       {OMPD_master_taskloop, OMPD_simd, OMPD_master_taskloop_simd},
182       {OMPD_parallel, OMPD_master, OMPD_parallel_master},
183       {OMPD_parallel_master, OMPD_taskloop, OMPD_parallel_master_taskloop},
184       {OMPD_parallel_master_taskloop, OMPD_simd,
185        OMPD_parallel_master_taskloop_simd}};
186   enum { CancellationPoint = 0, DeclareReduction = 1, TargetData = 2 };
187   Token Tok = P.getCurToken();
188   OpenMPDirectiveKindExWrapper DKind =
189       Tok.isAnnotation()
190           ? static_cast<unsigned>(OMPD_unknown)
191           : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
192   if (DKind == OMPD_unknown)
193     return OMPD_unknown;
194 
195   for (unsigned I = 0; I < llvm::array_lengthof(F); ++I) {
196     if (DKind != F[I][0])
197       continue;
198 
199     Tok = P.getPreprocessor().LookAhead(0);
200     OpenMPDirectiveKindExWrapper SDKind =
201         Tok.isAnnotation()
202             ? static_cast<unsigned>(OMPD_unknown)
203             : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
204     if (SDKind == OMPD_unknown)
205       continue;
206 
207     if (SDKind == F[I][1]) {
208       P.ConsumeToken();
209       DKind = F[I][2];
210     }
211   }
212   return unsigned(DKind) < llvm::omp::Directive_enumSize
213              ? static_cast<OpenMPDirectiveKind>(DKind)
214              : OMPD_unknown;
215 }
216 
217 static DeclarationName parseOpenMPReductionId(Parser &P) {
218   Token Tok = P.getCurToken();
219   Sema &Actions = P.getActions();
220   OverloadedOperatorKind OOK = OO_None;
221   // Allow to use 'operator' keyword for C++ operators
222   bool WithOperator = false;
223   if (Tok.is(tok::kw_operator)) {
224     P.ConsumeToken();
225     Tok = P.getCurToken();
226     WithOperator = true;
227   }
228   switch (Tok.getKind()) {
229   case tok::plus: // '+'
230     OOK = OO_Plus;
231     break;
232   case tok::minus: // '-'
233     OOK = OO_Minus;
234     break;
235   case tok::star: // '*'
236     OOK = OO_Star;
237     break;
238   case tok::amp: // '&'
239     OOK = OO_Amp;
240     break;
241   case tok::pipe: // '|'
242     OOK = OO_Pipe;
243     break;
244   case tok::caret: // '^'
245     OOK = OO_Caret;
246     break;
247   case tok::ampamp: // '&&'
248     OOK = OO_AmpAmp;
249     break;
250   case tok::pipepipe: // '||'
251     OOK = OO_PipePipe;
252     break;
253   case tok::identifier: // identifier
254     if (!WithOperator)
255       break;
256     LLVM_FALLTHROUGH;
257   default:
258     P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier);
259     P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
260                 Parser::StopBeforeMatch);
261     return DeclarationName();
262   }
263   P.ConsumeToken();
264   auto &DeclNames = Actions.getASTContext().DeclarationNames;
265   return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo())
266                         : DeclNames.getCXXOperatorName(OOK);
267 }
268 
269 /// Parse 'omp declare reduction' construct.
270 ///
271 ///       declare-reduction-directive:
272 ///        annot_pragma_openmp 'declare' 'reduction'
273 ///        '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')'
274 ///        ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')']
275 ///        annot_pragma_openmp_end
276 /// <reduction_id> is either a base language identifier or one of the following
277 /// operators: '+', '-', '*', '&', '|', '^', '&&' and '||'.
278 ///
279 Parser::DeclGroupPtrTy
280 Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) {
281   // Parse '('.
282   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
283   if (T.expectAndConsume(
284           diag::err_expected_lparen_after,
285           getOpenMPDirectiveName(OMPD_declare_reduction).data())) {
286     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
287     return DeclGroupPtrTy();
288   }
289 
290   DeclarationName Name = parseOpenMPReductionId(*this);
291   if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end))
292     return DeclGroupPtrTy();
293 
294   // Consume ':'.
295   bool IsCorrect = !ExpectAndConsume(tok::colon);
296 
297   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
298     return DeclGroupPtrTy();
299 
300   IsCorrect = IsCorrect && !Name.isEmpty();
301 
302   if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) {
303     Diag(Tok.getLocation(), diag::err_expected_type);
304     IsCorrect = false;
305   }
306 
307   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
308     return DeclGroupPtrTy();
309 
310   SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes;
311   // Parse list of types until ':' token.
312   do {
313     ColonProtectionRAIIObject ColonRAII(*this);
314     SourceRange Range;
315     TypeResult TR = ParseTypeName(&Range, DeclaratorContext::Prototype, AS);
316     if (TR.isUsable()) {
317       QualType ReductionType =
318           Actions.ActOnOpenMPDeclareReductionType(Range.getBegin(), TR);
319       if (!ReductionType.isNull()) {
320         ReductionTypes.push_back(
321             std::make_pair(ReductionType, Range.getBegin()));
322       }
323     } else {
324       SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end,
325                 StopBeforeMatch);
326     }
327 
328     if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end))
329       break;
330 
331     // Consume ','.
332     if (ExpectAndConsume(tok::comma)) {
333       IsCorrect = false;
334       if (Tok.is(tok::annot_pragma_openmp_end)) {
335         Diag(Tok.getLocation(), diag::err_expected_type);
336         return DeclGroupPtrTy();
337       }
338     }
339   } while (Tok.isNot(tok::annot_pragma_openmp_end));
340 
341   if (ReductionTypes.empty()) {
342     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
343     return DeclGroupPtrTy();
344   }
345 
346   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
347     return DeclGroupPtrTy();
348 
349   // Consume ':'.
350   if (ExpectAndConsume(tok::colon))
351     IsCorrect = false;
352 
353   if (Tok.is(tok::annot_pragma_openmp_end)) {
354     Diag(Tok.getLocation(), diag::err_expected_expression);
355     return DeclGroupPtrTy();
356   }
357 
358   DeclGroupPtrTy DRD = Actions.ActOnOpenMPDeclareReductionDirectiveStart(
359       getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes, AS);
360 
361   // Parse <combiner> expression and then parse initializer if any for each
362   // correct type.
363   unsigned I = 0, E = ReductionTypes.size();
364   for (Decl *D : DRD.get()) {
365     TentativeParsingAction TPA(*this);
366     ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
367                                     Scope::CompoundStmtScope |
368                                     Scope::OpenMPDirectiveScope);
369     // Parse <combiner> expression.
370     Actions.ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D);
371     ExprResult CombinerResult = Actions.ActOnFinishFullExpr(
372         ParseExpression().get(), D->getLocation(), /*DiscardedValue*/ false);
373     Actions.ActOnOpenMPDeclareReductionCombinerEnd(D, CombinerResult.get());
374 
375     if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
376         Tok.isNot(tok::annot_pragma_openmp_end)) {
377       TPA.Commit();
378       IsCorrect = false;
379       break;
380     }
381     IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable();
382     ExprResult InitializerResult;
383     if (Tok.isNot(tok::annot_pragma_openmp_end)) {
384       // Parse <initializer> expression.
385       if (Tok.is(tok::identifier) &&
386           Tok.getIdentifierInfo()->isStr("initializer")) {
387         ConsumeToken();
388       } else {
389         Diag(Tok.getLocation(), diag::err_expected) << "'initializer'";
390         TPA.Commit();
391         IsCorrect = false;
392         break;
393       }
394       // Parse '('.
395       BalancedDelimiterTracker T(*this, tok::l_paren,
396                                  tok::annot_pragma_openmp_end);
397       IsCorrect =
398           !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") &&
399           IsCorrect;
400       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
401         ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
402                                         Scope::CompoundStmtScope |
403                                         Scope::OpenMPDirectiveScope);
404         // Parse expression.
405         VarDecl *OmpPrivParm =
406             Actions.ActOnOpenMPDeclareReductionInitializerStart(getCurScope(),
407                                                                 D);
408         // Check if initializer is omp_priv <init_expr> or something else.
409         if (Tok.is(tok::identifier) &&
410             Tok.getIdentifierInfo()->isStr("omp_priv")) {
411           ConsumeToken();
412           ParseOpenMPReductionInitializerForDecl(OmpPrivParm);
413         } else {
414           InitializerResult = Actions.ActOnFinishFullExpr(
415               ParseAssignmentExpression().get(), D->getLocation(),
416               /*DiscardedValue*/ false);
417         }
418         Actions.ActOnOpenMPDeclareReductionInitializerEnd(
419             D, InitializerResult.get(), OmpPrivParm);
420         if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
421             Tok.isNot(tok::annot_pragma_openmp_end)) {
422           TPA.Commit();
423           IsCorrect = false;
424           break;
425         }
426         IsCorrect =
427             !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid();
428       }
429     }
430 
431     ++I;
432     // Revert parsing if not the last type, otherwise accept it, we're done with
433     // parsing.
434     if (I != E)
435       TPA.Revert();
436     else
437       TPA.Commit();
438   }
439   return Actions.ActOnOpenMPDeclareReductionDirectiveEnd(getCurScope(), DRD,
440                                                          IsCorrect);
441 }
442 
443 void Parser::ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm) {
444   // Parse declarator '=' initializer.
445   // If a '==' or '+=' is found, suggest a fixit to '='.
446   if (isTokenEqualOrEqualTypo()) {
447     ConsumeToken();
448 
449     if (Tok.is(tok::code_completion)) {
450       cutOffParsing();
451       Actions.CodeCompleteInitializer(getCurScope(), OmpPrivParm);
452       Actions.FinalizeDeclaration(OmpPrivParm);
453       return;
454     }
455 
456     PreferredType.enterVariableInit(Tok.getLocation(), OmpPrivParm);
457     ExprResult Init = ParseInitializer();
458 
459     if (Init.isInvalid()) {
460       SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
461       Actions.ActOnInitializerError(OmpPrivParm);
462     } else {
463       Actions.AddInitializerToDecl(OmpPrivParm, Init.get(),
464                                    /*DirectInit=*/false);
465     }
466   } else if (Tok.is(tok::l_paren)) {
467     // Parse C++ direct initializer: '(' expression-list ')'
468     BalancedDelimiterTracker T(*this, tok::l_paren);
469     T.consumeOpen();
470 
471     ExprVector Exprs;
472     CommaLocsTy CommaLocs;
473 
474     SourceLocation LParLoc = T.getOpenLocation();
475     auto RunSignatureHelp = [this, OmpPrivParm, LParLoc, &Exprs]() {
476       QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
477           OmpPrivParm->getType()->getCanonicalTypeInternal(),
478           OmpPrivParm->getLocation(), Exprs, LParLoc, /*Braced=*/false);
479       CalledSignatureHelp = true;
480       return PreferredType;
481     };
482     if (ParseExpressionList(Exprs, CommaLocs, [&] {
483           PreferredType.enterFunctionArgument(Tok.getLocation(),
484                                               RunSignatureHelp);
485         })) {
486       if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
487         RunSignatureHelp();
488       Actions.ActOnInitializerError(OmpPrivParm);
489       SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
490     } else {
491       // Match the ')'.
492       SourceLocation RLoc = Tok.getLocation();
493       if (!T.consumeClose())
494         RLoc = T.getCloseLocation();
495 
496       assert(!Exprs.empty() && Exprs.size() - 1 == CommaLocs.size() &&
497              "Unexpected number of commas!");
498 
499       ExprResult Initializer =
500           Actions.ActOnParenListExpr(T.getOpenLocation(), RLoc, Exprs);
501       Actions.AddInitializerToDecl(OmpPrivParm, Initializer.get(),
502                                    /*DirectInit=*/true);
503     }
504   } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
505     // Parse C++0x braced-init-list.
506     Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
507 
508     ExprResult Init(ParseBraceInitializer());
509 
510     if (Init.isInvalid()) {
511       Actions.ActOnInitializerError(OmpPrivParm);
512     } else {
513       Actions.AddInitializerToDecl(OmpPrivParm, Init.get(),
514                                    /*DirectInit=*/true);
515     }
516   } else {
517     Actions.ActOnUninitializedDecl(OmpPrivParm);
518   }
519 }
520 
521 /// Parses 'omp declare mapper' directive.
522 ///
523 ///       declare-mapper-directive:
524 ///         annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifier> ':']
525 ///         <type> <var> ')' [<clause>[[,] <clause>] ... ]
526 ///         annot_pragma_openmp_end
527 /// <mapper-identifier> and <var> are base language identifiers.
528 ///
529 Parser::DeclGroupPtrTy
530 Parser::ParseOpenMPDeclareMapperDirective(AccessSpecifier AS) {
531   bool IsCorrect = true;
532   // Parse '('
533   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
534   if (T.expectAndConsume(diag::err_expected_lparen_after,
535                          getOpenMPDirectiveName(OMPD_declare_mapper).data())) {
536     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
537     return DeclGroupPtrTy();
538   }
539 
540   // Parse <mapper-identifier>
541   auto &DeclNames = Actions.getASTContext().DeclarationNames;
542   DeclarationName MapperId;
543   if (PP.LookAhead(0).is(tok::colon)) {
544     if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
545       Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
546       IsCorrect = false;
547     } else {
548       MapperId = DeclNames.getIdentifier(Tok.getIdentifierInfo());
549     }
550     ConsumeToken();
551     // Consume ':'.
552     ExpectAndConsume(tok::colon);
553   } else {
554     // If no mapper identifier is provided, its name is "default" by default
555     MapperId =
556         DeclNames.getIdentifier(&Actions.getASTContext().Idents.get("default"));
557   }
558 
559   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
560     return DeclGroupPtrTy();
561 
562   // Parse <type> <var>
563   DeclarationName VName;
564   QualType MapperType;
565   SourceRange Range;
566   TypeResult ParsedType = parseOpenMPDeclareMapperVarDecl(Range, VName, AS);
567   if (ParsedType.isUsable())
568     MapperType =
569         Actions.ActOnOpenMPDeclareMapperType(Range.getBegin(), ParsedType);
570   if (MapperType.isNull())
571     IsCorrect = false;
572   if (!IsCorrect) {
573     SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch);
574     return DeclGroupPtrTy();
575   }
576 
577   // Consume ')'.
578   IsCorrect &= !T.consumeClose();
579   if (!IsCorrect) {
580     SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch);
581     return DeclGroupPtrTy();
582   }
583 
584   // Enter scope.
585   DeclarationNameInfo DirName;
586   SourceLocation Loc = Tok.getLocation();
587   unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
588                         Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope;
589   ParseScope OMPDirectiveScope(this, ScopeFlags);
590   Actions.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, getCurScope(), Loc);
591 
592   // Add the mapper variable declaration.
593   ExprResult MapperVarRef = Actions.ActOnOpenMPDeclareMapperDirectiveVarDecl(
594       getCurScope(), MapperType, Range.getBegin(), VName);
595 
596   // Parse map clauses.
597   SmallVector<OMPClause *, 6> Clauses;
598   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
599     OpenMPClauseKind CKind = Tok.isAnnotation()
600                                  ? OMPC_unknown
601                                  : getOpenMPClauseKind(PP.getSpelling(Tok));
602     Actions.StartOpenMPClause(CKind);
603     OMPClause *Clause =
604         ParseOpenMPClause(OMPD_declare_mapper, CKind, Clauses.empty());
605     if (Clause)
606       Clauses.push_back(Clause);
607     else
608       IsCorrect = false;
609     // Skip ',' if any.
610     if (Tok.is(tok::comma))
611       ConsumeToken();
612     Actions.EndOpenMPClause();
613   }
614   if (Clauses.empty()) {
615     Diag(Tok, diag::err_omp_expected_clause)
616         << getOpenMPDirectiveName(OMPD_declare_mapper);
617     IsCorrect = false;
618   }
619 
620   // Exit scope.
621   Actions.EndOpenMPDSABlock(nullptr);
622   OMPDirectiveScope.Exit();
623   DeclGroupPtrTy DG = Actions.ActOnOpenMPDeclareMapperDirective(
624       getCurScope(), Actions.getCurLexicalContext(), MapperId, MapperType,
625       Range.getBegin(), VName, AS, MapperVarRef.get(), Clauses);
626   if (!IsCorrect)
627     return DeclGroupPtrTy();
628 
629   return DG;
630 }
631 
632 TypeResult Parser::parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
633                                                    DeclarationName &Name,
634                                                    AccessSpecifier AS) {
635   // Parse the common declaration-specifiers piece.
636   Parser::DeclSpecContext DSC = Parser::DeclSpecContext::DSC_type_specifier;
637   DeclSpec DS(AttrFactory);
638   ParseSpecifierQualifierList(DS, AS, DSC);
639 
640   // Parse the declarator.
641   DeclaratorContext Context = DeclaratorContext::Prototype;
642   Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
643   ParseDeclarator(DeclaratorInfo);
644   Range = DeclaratorInfo.getSourceRange();
645   if (DeclaratorInfo.getIdentifier() == nullptr) {
646     Diag(Tok.getLocation(), diag::err_omp_mapper_expected_declarator);
647     return true;
648   }
649   Name = Actions.GetNameForDeclarator(DeclaratorInfo).getName();
650 
651   return Actions.ActOnOpenMPDeclareMapperVarDecl(getCurScope(), DeclaratorInfo);
652 }
653 
654 namespace {
655 /// RAII that recreates function context for correct parsing of clauses of
656 /// 'declare simd' construct.
657 /// OpenMP, 2.8.2 declare simd Construct
658 /// The expressions appearing in the clauses of this directive are evaluated in
659 /// the scope of the arguments of the function declaration or definition.
660 class FNContextRAII final {
661   Parser &P;
662   Sema::CXXThisScopeRAII *ThisScope;
663   Parser::MultiParseScope Scopes;
664   bool HasFunScope = false;
665   FNContextRAII() = delete;
666   FNContextRAII(const FNContextRAII &) = delete;
667   FNContextRAII &operator=(const FNContextRAII &) = delete;
668 
669 public:
670   FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P), Scopes(P) {
671     Decl *D = *Ptr.get().begin();
672     NamedDecl *ND = dyn_cast<NamedDecl>(D);
673     RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
674     Sema &Actions = P.getActions();
675 
676     // Allow 'this' within late-parsed attributes.
677     ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, Qualifiers(),
678                                            ND && ND->isCXXInstanceMember());
679 
680     // If the Decl is templatized, add template parameters to scope.
681     // FIXME: Track CurTemplateDepth?
682     P.ReenterTemplateScopes(Scopes, D);
683 
684     // If the Decl is on a function, add function parameters to the scope.
685     if (D->isFunctionOrFunctionTemplate()) {
686       HasFunScope = true;
687       Scopes.Enter(Scope::FnScope | Scope::DeclScope |
688                    Scope::CompoundStmtScope);
689       Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D);
690     }
691   }
692   ~FNContextRAII() {
693     if (HasFunScope)
694       P.getActions().ActOnExitFunctionContext();
695     delete ThisScope;
696   }
697 };
698 } // namespace
699 
700 /// Parses clauses for 'declare simd' directive.
701 ///    clause:
702 ///      'inbranch' | 'notinbranch'
703 ///      'simdlen' '(' <expr> ')'
704 ///      { 'uniform' '(' <argument_list> ')' }
705 ///      { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' }
706 ///      { 'linear '(' <argument_list> [ ':' <step> ] ')' }
707 static bool parseDeclareSimdClauses(
708     Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen,
709     SmallVectorImpl<Expr *> &Uniforms, SmallVectorImpl<Expr *> &Aligneds,
710     SmallVectorImpl<Expr *> &Alignments, SmallVectorImpl<Expr *> &Linears,
711     SmallVectorImpl<unsigned> &LinModifiers, SmallVectorImpl<Expr *> &Steps) {
712   SourceRange BSRange;
713   const Token &Tok = P.getCurToken();
714   bool IsError = false;
715   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
716     if (Tok.isNot(tok::identifier))
717       break;
718     OMPDeclareSimdDeclAttr::BranchStateTy Out;
719     IdentifierInfo *II = Tok.getIdentifierInfo();
720     StringRef ClauseName = II->getName();
721     // Parse 'inranch|notinbranch' clauses.
722     if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) {
723       if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) {
724         P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch)
725             << ClauseName
726             << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange;
727         IsError = true;
728       }
729       BS = Out;
730       BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc());
731       P.ConsumeToken();
732     } else if (ClauseName.equals("simdlen")) {
733       if (SimdLen.isUsable()) {
734         P.Diag(Tok, diag::err_omp_more_one_clause)
735             << getOpenMPDirectiveName(OMPD_declare_simd) << ClauseName << 0;
736         IsError = true;
737       }
738       P.ConsumeToken();
739       SourceLocation RLoc;
740       SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc);
741       if (SimdLen.isInvalid())
742         IsError = true;
743     } else {
744       OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName);
745       if (CKind == OMPC_uniform || CKind == OMPC_aligned ||
746           CKind == OMPC_linear) {
747         Sema::OpenMPVarListDataTy Data;
748         SmallVectorImpl<Expr *> *Vars = &Uniforms;
749         if (CKind == OMPC_aligned) {
750           Vars = &Aligneds;
751         } else if (CKind == OMPC_linear) {
752           Data.ExtraModifier = OMPC_LINEAR_val;
753           Vars = &Linears;
754         }
755 
756         P.ConsumeToken();
757         if (P.ParseOpenMPVarList(OMPD_declare_simd,
758                                  getOpenMPClauseKind(ClauseName), *Vars, Data))
759           IsError = true;
760         if (CKind == OMPC_aligned) {
761           Alignments.append(Aligneds.size() - Alignments.size(),
762                             Data.DepModOrTailExpr);
763         } else if (CKind == OMPC_linear) {
764           assert(0 <= Data.ExtraModifier &&
765                  Data.ExtraModifier <= OMPC_LINEAR_unknown &&
766                  "Unexpected linear modifier.");
767           if (P.getActions().CheckOpenMPLinearModifier(
768                   static_cast<OpenMPLinearClauseKind>(Data.ExtraModifier),
769                   Data.ExtraModifierLoc))
770             Data.ExtraModifier = OMPC_LINEAR_val;
771           LinModifiers.append(Linears.size() - LinModifiers.size(),
772                               Data.ExtraModifier);
773           Steps.append(Linears.size() - Steps.size(), Data.DepModOrTailExpr);
774         }
775       } else
776         // TODO: add parsing of other clauses.
777         break;
778     }
779     // Skip ',' if any.
780     if (Tok.is(tok::comma))
781       P.ConsumeToken();
782   }
783   return IsError;
784 }
785 
786 /// Parse clauses for '#pragma omp declare simd'.
787 Parser::DeclGroupPtrTy
788 Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr,
789                                    CachedTokens &Toks, SourceLocation Loc) {
790   PP.EnterToken(Tok, /*IsReinject*/ true);
791   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
792                       /*IsReinject*/ true);
793   // Consume the previously pushed token.
794   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
795   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
796 
797   FNContextRAII FnContext(*this, Ptr);
798   OMPDeclareSimdDeclAttr::BranchStateTy BS =
799       OMPDeclareSimdDeclAttr::BS_Undefined;
800   ExprResult Simdlen;
801   SmallVector<Expr *, 4> Uniforms;
802   SmallVector<Expr *, 4> Aligneds;
803   SmallVector<Expr *, 4> Alignments;
804   SmallVector<Expr *, 4> Linears;
805   SmallVector<unsigned, 4> LinModifiers;
806   SmallVector<Expr *, 4> Steps;
807   bool IsError =
808       parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds,
809                               Alignments, Linears, LinModifiers, Steps);
810   skipUntilPragmaOpenMPEnd(OMPD_declare_simd);
811   // Skip the last annot_pragma_openmp_end.
812   SourceLocation EndLoc = ConsumeAnnotationToken();
813   if (IsError)
814     return Ptr;
815   return Actions.ActOnOpenMPDeclareSimdDirective(
816       Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears,
817       LinModifiers, Steps, SourceRange(Loc, EndLoc));
818 }
819 
820 namespace {
821 /// Constant used in the diagnostics to distinguish the levels in an OpenMP
822 /// contexts: selector-set={selector(trait, ...), ...}, ....
823 enum OMPContextLvl {
824   CONTEXT_SELECTOR_SET_LVL = 0,
825   CONTEXT_SELECTOR_LVL = 1,
826   CONTEXT_TRAIT_LVL = 2,
827 };
828 
829 static StringRef stringLiteralParser(Parser &P) {
830   ExprResult Res = P.ParseStringLiteralExpression(true);
831   return Res.isUsable() ? Res.getAs<StringLiteral>()->getString() : "";
832 }
833 
834 static StringRef getNameFromIdOrString(Parser &P, Token &Tok,
835                                        OMPContextLvl Lvl) {
836   if (Tok.is(tok::identifier) || Tok.is(tok::kw_for)) {
837     llvm::SmallString<16> Buffer;
838     StringRef Name = P.getPreprocessor().getSpelling(Tok, Buffer);
839     (void)P.ConsumeToken();
840     return Name;
841   }
842 
843   if (tok::isStringLiteral(Tok.getKind()))
844     return stringLiteralParser(P);
845 
846   P.Diag(Tok.getLocation(),
847          diag::warn_omp_declare_variant_string_literal_or_identifier)
848       << Lvl;
849   return "";
850 }
851 
852 static bool checkForDuplicates(Parser &P, StringRef Name,
853                                SourceLocation NameLoc,
854                                llvm::StringMap<SourceLocation> &Seen,
855                                OMPContextLvl Lvl) {
856   auto Res = Seen.try_emplace(Name, NameLoc);
857   if (Res.second)
858     return false;
859 
860   // Each trait-set-selector-name, trait-selector-name and trait-name can
861   // only be specified once.
862   P.Diag(NameLoc, diag::warn_omp_declare_variant_ctx_mutiple_use)
863       << Lvl << Name;
864   P.Diag(Res.first->getValue(), diag::note_omp_declare_variant_ctx_used_here)
865       << Lvl << Name;
866   return true;
867 }
868 } // namespace
869 
870 void Parser::parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
871                                        llvm::omp::TraitSet Set,
872                                        llvm::omp::TraitSelector Selector,
873                                        llvm::StringMap<SourceLocation> &Seen) {
874   TIProperty.Kind = TraitProperty::invalid;
875 
876   SourceLocation NameLoc = Tok.getLocation();
877   StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_TRAIT_LVL);
878   if (Name.empty()) {
879     Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
880         << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector);
881     return;
882   }
883 
884   TIProperty.RawString = Name;
885   TIProperty.Kind = getOpenMPContextTraitPropertyKind(Set, Selector, Name);
886   if (TIProperty.Kind != TraitProperty::invalid) {
887     if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_TRAIT_LVL))
888       TIProperty.Kind = TraitProperty::invalid;
889     return;
890   }
891 
892   // It follows diagnosis and helping notes.
893   // FIXME: We should move the diagnosis string generation into libFrontend.
894   Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_property)
895       << Name << getOpenMPContextTraitSelectorName(Selector)
896       << getOpenMPContextTraitSetName(Set);
897 
898   TraitSet SetForName = getOpenMPContextTraitSetKind(Name);
899   if (SetForName != TraitSet::invalid) {
900     Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
901         << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_TRAIT_LVL;
902     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
903         << Name << "<selector-name>"
904         << "(<property-name>)";
905     return;
906   }
907   TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name);
908   if (SelectorForName != TraitSelector::invalid) {
909     Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
910         << Name << CONTEXT_SELECTOR_LVL << CONTEXT_TRAIT_LVL;
911     bool AllowsTraitScore = false;
912     bool RequiresProperty = false;
913     isValidTraitSelectorForTraitSet(
914         SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName),
915         AllowsTraitScore, RequiresProperty);
916     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
917         << getOpenMPContextTraitSetName(
918                getOpenMPContextTraitSetForSelector(SelectorForName))
919         << Name << (RequiresProperty ? "(<property-name>)" : "");
920     return;
921   }
922   for (const auto &PotentialSet :
923        {TraitSet::construct, TraitSet::user, TraitSet::implementation,
924         TraitSet::device}) {
925     TraitProperty PropertyForName =
926         getOpenMPContextTraitPropertyKind(PotentialSet, Selector, Name);
927     if (PropertyForName == TraitProperty::invalid)
928       continue;
929     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
930         << getOpenMPContextTraitSetName(
931                getOpenMPContextTraitSetForProperty(PropertyForName))
932         << getOpenMPContextTraitSelectorName(
933                getOpenMPContextTraitSelectorForProperty(PropertyForName))
934         << ("(" + Name + ")").str();
935     return;
936   }
937   Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
938       << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector);
939 }
940 
941 static bool checkExtensionProperty(Parser &P, SourceLocation Loc,
942                                    OMPTraitProperty &TIProperty,
943                                    OMPTraitSelector &TISelector,
944                                    llvm::StringMap<SourceLocation> &Seen) {
945   assert(TISelector.Kind ==
946              llvm::omp::TraitSelector::implementation_extension &&
947          "Only for extension properties, e.g., "
948          "`implementation={extension(PROPERTY)}`");
949   if (TIProperty.Kind == TraitProperty::invalid)
950     return false;
951 
952   if (TIProperty.Kind ==
953       TraitProperty::implementation_extension_disable_implicit_base)
954     return true;
955 
956   if (TIProperty.Kind ==
957       TraitProperty::implementation_extension_allow_templates)
958     return true;
959 
960   auto IsMatchExtension = [](OMPTraitProperty &TP) {
961     return (TP.Kind ==
962                 llvm::omp::TraitProperty::implementation_extension_match_all ||
963             TP.Kind ==
964                 llvm::omp::TraitProperty::implementation_extension_match_any ||
965             TP.Kind ==
966                 llvm::omp::TraitProperty::implementation_extension_match_none);
967   };
968 
969   if (IsMatchExtension(TIProperty)) {
970     for (OMPTraitProperty &SeenProp : TISelector.Properties)
971       if (IsMatchExtension(SeenProp)) {
972         P.Diag(Loc, diag::err_omp_variant_ctx_second_match_extension);
973         StringRef SeenName = llvm::omp::getOpenMPContextTraitPropertyName(
974             SeenProp.Kind, SeenProp.RawString);
975         SourceLocation SeenLoc = Seen[SeenName];
976         P.Diag(SeenLoc, diag::note_omp_declare_variant_ctx_used_here)
977             << CONTEXT_TRAIT_LVL << SeenName;
978         return false;
979       }
980     return true;
981   }
982 
983   llvm_unreachable("Unknown extension property!");
984 }
985 
986 void Parser::parseOMPContextProperty(OMPTraitSelector &TISelector,
987                                      llvm::omp::TraitSet Set,
988                                      llvm::StringMap<SourceLocation> &Seen) {
989   assert(TISelector.Kind != TraitSelector::user_condition &&
990          "User conditions are special properties not handled here!");
991 
992   SourceLocation PropertyLoc = Tok.getLocation();
993   OMPTraitProperty TIProperty;
994   parseOMPTraitPropertyKind(TIProperty, Set, TISelector.Kind, Seen);
995 
996   if (TISelector.Kind == llvm::omp::TraitSelector::implementation_extension)
997     if (!checkExtensionProperty(*this, Tok.getLocation(), TIProperty,
998                                 TISelector, Seen))
999       TIProperty.Kind = TraitProperty::invalid;
1000 
1001   // If we have an invalid property here we already issued a warning.
1002   if (TIProperty.Kind == TraitProperty::invalid) {
1003     if (PropertyLoc != Tok.getLocation())
1004       Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1005           << CONTEXT_TRAIT_LVL;
1006     return;
1007   }
1008 
1009   if (isValidTraitPropertyForTraitSetAndSelector(TIProperty.Kind,
1010                                                  TISelector.Kind, Set)) {
1011 
1012     // If we make it here the property, selector, set, score, condition, ... are
1013     // all valid (or have been corrected). Thus we can record the property.
1014     TISelector.Properties.push_back(TIProperty);
1015     return;
1016   }
1017 
1018   Diag(PropertyLoc, diag::warn_omp_ctx_incompatible_property_for_selector)
1019       << getOpenMPContextTraitPropertyName(TIProperty.Kind,
1020                                            TIProperty.RawString)
1021       << getOpenMPContextTraitSelectorName(TISelector.Kind)
1022       << getOpenMPContextTraitSetName(Set);
1023   Diag(PropertyLoc, diag::note_omp_ctx_compatible_set_and_selector_for_property)
1024       << getOpenMPContextTraitPropertyName(TIProperty.Kind,
1025                                            TIProperty.RawString)
1026       << getOpenMPContextTraitSelectorName(
1027              getOpenMPContextTraitSelectorForProperty(TIProperty.Kind))
1028       << getOpenMPContextTraitSetName(
1029              getOpenMPContextTraitSetForProperty(TIProperty.Kind));
1030   Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1031       << CONTEXT_TRAIT_LVL;
1032 }
1033 
1034 void Parser::parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
1035                                        llvm::omp::TraitSet Set,
1036                                        llvm::StringMap<SourceLocation> &Seen) {
1037   TISelector.Kind = TraitSelector::invalid;
1038 
1039   SourceLocation NameLoc = Tok.getLocation();
1040   StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_LVL);
1041   if (Name.empty()) {
1042     Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
1043         << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set);
1044     return;
1045   }
1046 
1047   TISelector.Kind = getOpenMPContextTraitSelectorKind(Name);
1048   if (TISelector.Kind != TraitSelector::invalid) {
1049     if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_SELECTOR_LVL))
1050       TISelector.Kind = TraitSelector::invalid;
1051     return;
1052   }
1053 
1054   // It follows diagnosis and helping notes.
1055   Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_selector)
1056       << Name << getOpenMPContextTraitSetName(Set);
1057 
1058   TraitSet SetForName = getOpenMPContextTraitSetKind(Name);
1059   if (SetForName != TraitSet::invalid) {
1060     Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1061         << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_SELECTOR_LVL;
1062     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1063         << Name << "<selector-name>"
1064         << "<property-name>";
1065     return;
1066   }
1067   for (const auto &PotentialSet :
1068        {TraitSet::construct, TraitSet::user, TraitSet::implementation,
1069         TraitSet::device}) {
1070     TraitProperty PropertyForName = getOpenMPContextTraitPropertyKind(
1071         PotentialSet, TraitSelector::invalid, Name);
1072     if (PropertyForName == TraitProperty::invalid)
1073       continue;
1074     Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1075         << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_LVL;
1076     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1077         << getOpenMPContextTraitSetName(
1078                getOpenMPContextTraitSetForProperty(PropertyForName))
1079         << getOpenMPContextTraitSelectorName(
1080                getOpenMPContextTraitSelectorForProperty(PropertyForName))
1081         << ("(" + Name + ")").str();
1082     return;
1083   }
1084   Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
1085       << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set);
1086 }
1087 
1088 /// Parse optional 'score' '(' <expr> ')' ':'.
1089 static ExprResult parseContextScore(Parser &P) {
1090   ExprResult ScoreExpr;
1091   llvm::SmallString<16> Buffer;
1092   StringRef SelectorName =
1093       P.getPreprocessor().getSpelling(P.getCurToken(), Buffer);
1094   if (!SelectorName.equals("score"))
1095     return ScoreExpr;
1096   (void)P.ConsumeToken();
1097   SourceLocation RLoc;
1098   ScoreExpr = P.ParseOpenMPParensExpr(SelectorName, RLoc);
1099   // Parse ':'
1100   if (P.getCurToken().is(tok::colon))
1101     (void)P.ConsumeAnyToken();
1102   else
1103     P.Diag(P.getCurToken(), diag::warn_omp_declare_variant_expected)
1104         << "':'"
1105         << "score expression";
1106   return ScoreExpr;
1107 }
1108 
1109 /// Parses an OpenMP context selector.
1110 ///
1111 /// <trait-selector-name> ['('[<trait-score>] <trait-property> [, <t-p>]* ')']
1112 void Parser::parseOMPContextSelector(
1113     OMPTraitSelector &TISelector, llvm::omp::TraitSet Set,
1114     llvm::StringMap<SourceLocation> &SeenSelectors) {
1115   unsigned short OuterPC = ParenCount;
1116 
1117   // If anything went wrong we issue an error or warning and then skip the rest
1118   // of the selector. However, commas are ambiguous so we look for the nesting
1119   // of parentheses here as well.
1120   auto FinishSelector = [OuterPC, this]() -> void {
1121     bool Done = false;
1122     while (!Done) {
1123       while (!SkipUntil({tok::r_brace, tok::r_paren, tok::comma,
1124                          tok::annot_pragma_openmp_end},
1125                         StopBeforeMatch))
1126         ;
1127       if (Tok.is(tok::r_paren) && OuterPC > ParenCount)
1128         (void)ConsumeParen();
1129       if (OuterPC <= ParenCount) {
1130         Done = true;
1131         break;
1132       }
1133       if (!Tok.is(tok::comma) && !Tok.is(tok::r_paren)) {
1134         Done = true;
1135         break;
1136       }
1137       (void)ConsumeAnyToken();
1138     }
1139     Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1140         << CONTEXT_SELECTOR_LVL;
1141   };
1142 
1143   SourceLocation SelectorLoc = Tok.getLocation();
1144   parseOMPTraitSelectorKind(TISelector, Set, SeenSelectors);
1145   if (TISelector.Kind == TraitSelector::invalid)
1146     return FinishSelector();
1147 
1148   bool AllowsTraitScore = false;
1149   bool RequiresProperty = false;
1150   if (!isValidTraitSelectorForTraitSet(TISelector.Kind, Set, AllowsTraitScore,
1151                                        RequiresProperty)) {
1152     Diag(SelectorLoc, diag::warn_omp_ctx_incompatible_selector_for_set)
1153         << getOpenMPContextTraitSelectorName(TISelector.Kind)
1154         << getOpenMPContextTraitSetName(Set);
1155     Diag(SelectorLoc, diag::note_omp_ctx_compatible_set_for_selector)
1156         << getOpenMPContextTraitSelectorName(TISelector.Kind)
1157         << getOpenMPContextTraitSetName(
1158                getOpenMPContextTraitSetForSelector(TISelector.Kind))
1159         << RequiresProperty;
1160     return FinishSelector();
1161   }
1162 
1163   if (!RequiresProperty) {
1164     TISelector.Properties.push_back(
1165         {getOpenMPContextTraitPropertyForSelector(TISelector.Kind),
1166          getOpenMPContextTraitSelectorName(TISelector.Kind)});
1167     return;
1168   }
1169 
1170   if (!Tok.is(tok::l_paren)) {
1171     Diag(SelectorLoc, diag::warn_omp_ctx_selector_without_properties)
1172         << getOpenMPContextTraitSelectorName(TISelector.Kind)
1173         << getOpenMPContextTraitSetName(Set);
1174     return FinishSelector();
1175   }
1176 
1177   if (TISelector.Kind == TraitSelector::user_condition) {
1178     SourceLocation RLoc;
1179     ExprResult Condition = ParseOpenMPParensExpr("user condition", RLoc);
1180     if (!Condition.isUsable())
1181       return FinishSelector();
1182     TISelector.ScoreOrCondition = Condition.get();
1183     TISelector.Properties.push_back(
1184         {TraitProperty::user_condition_unknown, "<condition>"});
1185     return;
1186   }
1187 
1188   BalancedDelimiterTracker BDT(*this, tok::l_paren,
1189                                tok::annot_pragma_openmp_end);
1190   // Parse '('.
1191   (void)BDT.consumeOpen();
1192 
1193   SourceLocation ScoreLoc = Tok.getLocation();
1194   ExprResult Score = parseContextScore(*this);
1195 
1196   if (!AllowsTraitScore && !Score.isUnset()) {
1197     if (Score.isUsable()) {
1198       Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property)
1199           << getOpenMPContextTraitSelectorName(TISelector.Kind)
1200           << getOpenMPContextTraitSetName(Set) << Score.get();
1201     } else {
1202       Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property)
1203           << getOpenMPContextTraitSelectorName(TISelector.Kind)
1204           << getOpenMPContextTraitSetName(Set) << "<invalid>";
1205     }
1206     Score = ExprResult();
1207   }
1208 
1209   if (Score.isUsable())
1210     TISelector.ScoreOrCondition = Score.get();
1211 
1212   llvm::StringMap<SourceLocation> SeenProperties;
1213   do {
1214     parseOMPContextProperty(TISelector, Set, SeenProperties);
1215   } while (TryConsumeToken(tok::comma));
1216 
1217   // Parse ')'.
1218   BDT.consumeClose();
1219 }
1220 
1221 void Parser::parseOMPTraitSetKind(OMPTraitSet &TISet,
1222                                   llvm::StringMap<SourceLocation> &Seen) {
1223   TISet.Kind = TraitSet::invalid;
1224 
1225   SourceLocation NameLoc = Tok.getLocation();
1226   StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_SET_LVL);
1227   if (Name.empty()) {
1228     Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
1229         << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets();
1230     return;
1231   }
1232 
1233   TISet.Kind = getOpenMPContextTraitSetKind(Name);
1234   if (TISet.Kind != TraitSet::invalid) {
1235     if (checkForDuplicates(*this, Name, NameLoc, Seen,
1236                            CONTEXT_SELECTOR_SET_LVL))
1237       TISet.Kind = TraitSet::invalid;
1238     return;
1239   }
1240 
1241   // It follows diagnosis and helping notes.
1242   Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_set) << Name;
1243 
1244   TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name);
1245   if (SelectorForName != TraitSelector::invalid) {
1246     Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1247         << Name << CONTEXT_SELECTOR_LVL << CONTEXT_SELECTOR_SET_LVL;
1248     bool AllowsTraitScore = false;
1249     bool RequiresProperty = false;
1250     isValidTraitSelectorForTraitSet(
1251         SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName),
1252         AllowsTraitScore, RequiresProperty);
1253     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1254         << getOpenMPContextTraitSetName(
1255                getOpenMPContextTraitSetForSelector(SelectorForName))
1256         << Name << (RequiresProperty ? "(<property-name>)" : "");
1257     return;
1258   }
1259   for (const auto &PotentialSet :
1260        {TraitSet::construct, TraitSet::user, TraitSet::implementation,
1261         TraitSet::device}) {
1262     TraitProperty PropertyForName = getOpenMPContextTraitPropertyKind(
1263         PotentialSet, TraitSelector::invalid, Name);
1264     if (PropertyForName == TraitProperty::invalid)
1265       continue;
1266     Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1267         << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_SET_LVL;
1268     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1269         << getOpenMPContextTraitSetName(
1270                getOpenMPContextTraitSetForProperty(PropertyForName))
1271         << getOpenMPContextTraitSelectorName(
1272                getOpenMPContextTraitSelectorForProperty(PropertyForName))
1273         << ("(" + Name + ")").str();
1274     return;
1275   }
1276   Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
1277       << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets();
1278 }
1279 
1280 /// Parses an OpenMP context selector set.
1281 ///
1282 /// <trait-set-selector-name> '=' '{' <trait-selector> [, <trait-selector>]* '}'
1283 void Parser::parseOMPContextSelectorSet(
1284     OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets) {
1285   auto OuterBC = BraceCount;
1286 
1287   // If anything went wrong we issue an error or warning and then skip the rest
1288   // of the set. However, commas are ambiguous so we look for the nesting
1289   // of braces here as well.
1290   auto FinishSelectorSet = [this, OuterBC]() -> void {
1291     bool Done = false;
1292     while (!Done) {
1293       while (!SkipUntil({tok::comma, tok::r_brace, tok::r_paren,
1294                          tok::annot_pragma_openmp_end},
1295                         StopBeforeMatch))
1296         ;
1297       if (Tok.is(tok::r_brace) && OuterBC > BraceCount)
1298         (void)ConsumeBrace();
1299       if (OuterBC <= BraceCount) {
1300         Done = true;
1301         break;
1302       }
1303       if (!Tok.is(tok::comma) && !Tok.is(tok::r_brace)) {
1304         Done = true;
1305         break;
1306       }
1307       (void)ConsumeAnyToken();
1308     }
1309     Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1310         << CONTEXT_SELECTOR_SET_LVL;
1311   };
1312 
1313   parseOMPTraitSetKind(TISet, SeenSets);
1314   if (TISet.Kind == TraitSet::invalid)
1315     return FinishSelectorSet();
1316 
1317   // Parse '='.
1318   if (!TryConsumeToken(tok::equal))
1319     Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
1320         << "="
1321         << ("context set name \"" + getOpenMPContextTraitSetName(TISet.Kind) +
1322             "\"")
1323                .str();
1324 
1325   // Parse '{'.
1326   if (Tok.is(tok::l_brace)) {
1327     (void)ConsumeBrace();
1328   } else {
1329     Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
1330         << "{"
1331         << ("'=' that follows the context set name \"" +
1332             getOpenMPContextTraitSetName(TISet.Kind) + "\"")
1333                .str();
1334   }
1335 
1336   llvm::StringMap<SourceLocation> SeenSelectors;
1337   do {
1338     OMPTraitSelector TISelector;
1339     parseOMPContextSelector(TISelector, TISet.Kind, SeenSelectors);
1340     if (TISelector.Kind != TraitSelector::invalid &&
1341         !TISelector.Properties.empty())
1342       TISet.Selectors.push_back(TISelector);
1343   } while (TryConsumeToken(tok::comma));
1344 
1345   // Parse '}'.
1346   if (Tok.is(tok::r_brace)) {
1347     (void)ConsumeBrace();
1348   } else {
1349     Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
1350         << "}"
1351         << ("context selectors for the context set \"" +
1352             getOpenMPContextTraitSetName(TISet.Kind) + "\"")
1353                .str();
1354   }
1355 }
1356 
1357 /// Parse OpenMP context selectors:
1358 ///
1359 /// <trait-set-selector> [, <trait-set-selector>]*
1360 bool Parser::parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI) {
1361   llvm::StringMap<SourceLocation> SeenSets;
1362   do {
1363     OMPTraitSet TISet;
1364     parseOMPContextSelectorSet(TISet, SeenSets);
1365     if (TISet.Kind != TraitSet::invalid && !TISet.Selectors.empty())
1366       TI.Sets.push_back(TISet);
1367   } while (TryConsumeToken(tok::comma));
1368 
1369   return false;
1370 }
1371 
1372 /// Parse clauses for '#pragma omp declare variant ( variant-func-id ) clause'.
1373 void Parser::ParseOMPDeclareVariantClauses(Parser::DeclGroupPtrTy Ptr,
1374                                            CachedTokens &Toks,
1375                                            SourceLocation Loc) {
1376   PP.EnterToken(Tok, /*IsReinject*/ true);
1377   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1378                       /*IsReinject*/ true);
1379   // Consume the previously pushed token.
1380   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1381   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1382 
1383   FNContextRAII FnContext(*this, Ptr);
1384   // Parse function declaration id.
1385   SourceLocation RLoc;
1386   // Parse with IsAddressOfOperand set to true to parse methods as DeclRefExprs
1387   // instead of MemberExprs.
1388   ExprResult AssociatedFunction;
1389   {
1390     // Do not mark function as is used to prevent its emission if this is the
1391     // only place where it is used.
1392     EnterExpressionEvaluationContext Unevaluated(
1393         Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1394     AssociatedFunction = ParseOpenMPParensExpr(
1395         getOpenMPDirectiveName(OMPD_declare_variant), RLoc,
1396         /*IsAddressOfOperand=*/true);
1397   }
1398   if (!AssociatedFunction.isUsable()) {
1399     if (!Tok.is(tok::annot_pragma_openmp_end))
1400       while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch))
1401         ;
1402     // Skip the last annot_pragma_openmp_end.
1403     (void)ConsumeAnnotationToken();
1404     return;
1405   }
1406 
1407   OMPTraitInfo *ParentTI = Actions.getOMPTraitInfoForSurroundingScope();
1408   ASTContext &ASTCtx = Actions.getASTContext();
1409   OMPTraitInfo &TI = ASTCtx.getNewOMPTraitInfo();
1410   SmallVector<Expr *, 6> AdjustNothing;
1411   SmallVector<Expr *, 6> AdjustNeedDevicePtr;
1412   SmallVector<OMPDeclareVariantAttr::InteropType, 3> AppendArgs;
1413   SourceLocation AdjustArgsLoc, AppendArgsLoc;
1414 
1415   // At least one clause is required.
1416   if (Tok.is(tok::annot_pragma_openmp_end)) {
1417     Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
1418         << (getLangOpts().OpenMP < 51 ? 0 : 1);
1419   }
1420 
1421   bool IsError = false;
1422   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1423     OpenMPClauseKind CKind = Tok.isAnnotation()
1424                                  ? OMPC_unknown
1425                                  : getOpenMPClauseKind(PP.getSpelling(Tok));
1426     if (!isAllowedClauseForDirective(OMPD_declare_variant, CKind,
1427                                      getLangOpts().OpenMP)) {
1428       Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
1429           << (getLangOpts().OpenMP < 51 ? 0 : 1);
1430       IsError = true;
1431     }
1432     if (!IsError) {
1433       switch (CKind) {
1434       case OMPC_match:
1435         IsError = parseOMPDeclareVariantMatchClause(Loc, TI, ParentTI);
1436         break;
1437       case OMPC_adjust_args: {
1438         AdjustArgsLoc = Tok.getLocation();
1439         ConsumeToken();
1440         Sema::OpenMPVarListDataTy Data;
1441         SmallVector<Expr *> Vars;
1442         IsError = ParseOpenMPVarList(OMPD_declare_variant, OMPC_adjust_args,
1443                                      Vars, Data);
1444         if (!IsError)
1445           llvm::append_range(Data.ExtraModifier == OMPC_ADJUST_ARGS_nothing
1446                                  ? AdjustNothing
1447                                  : AdjustNeedDevicePtr,
1448                              Vars);
1449         break;
1450       }
1451       case OMPC_append_args:
1452         if (!AppendArgs.empty()) {
1453           Diag(AppendArgsLoc, diag::err_omp_more_one_clause)
1454               << getOpenMPDirectiveName(OMPD_declare_variant)
1455               << getOpenMPClauseName(CKind) << 0;
1456           IsError = true;
1457         }
1458         if (!IsError) {
1459           AppendArgsLoc = Tok.getLocation();
1460           ConsumeToken();
1461           IsError = parseOpenMPAppendArgs(AppendArgs);
1462         }
1463         break;
1464       default:
1465         llvm_unreachable("Unexpected clause for declare variant.");
1466       }
1467     }
1468     if (IsError) {
1469       while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch))
1470         ;
1471       // Skip the last annot_pragma_openmp_end.
1472       (void)ConsumeAnnotationToken();
1473       return;
1474     }
1475     // Skip ',' if any.
1476     if (Tok.is(tok::comma))
1477       ConsumeToken();
1478   }
1479 
1480   Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
1481       Actions.checkOpenMPDeclareVariantFunction(
1482           Ptr, AssociatedFunction.get(), TI, AppendArgs.size(),
1483           SourceRange(Loc, Tok.getLocation()));
1484 
1485   if (DeclVarData && !TI.Sets.empty())
1486     Actions.ActOnOpenMPDeclareVariantDirective(
1487         DeclVarData->first, DeclVarData->second, TI, AdjustNothing,
1488         AdjustNeedDevicePtr, AppendArgs, AdjustArgsLoc, AppendArgsLoc,
1489         SourceRange(Loc, Tok.getLocation()));
1490 
1491   // Skip the last annot_pragma_openmp_end.
1492   (void)ConsumeAnnotationToken();
1493 }
1494 
1495 /// Parse a list of interop-types. These are 'target' and 'targetsync'. Both
1496 /// are allowed but duplication of either is not meaningful.
1497 static Optional<OMPDeclareVariantAttr::InteropType>
1498 parseInteropTypeList(Parser &P) {
1499   const Token &Tok = P.getCurToken();
1500   bool HasError = false;
1501   bool IsTarget = false;
1502   bool IsTargetSync = false;
1503 
1504   while (Tok.is(tok::identifier)) {
1505     if (Tok.getIdentifierInfo()->isStr("target")) {
1506       // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
1507       // Each interop-type may be specified on an action-clause at most
1508       // once.
1509       if (IsTarget)
1510         P.Diag(Tok, diag::warn_omp_more_one_interop_type) << "target";
1511       IsTarget = true;
1512     } else if (Tok.getIdentifierInfo()->isStr("targetsync")) {
1513       if (IsTargetSync)
1514         P.Diag(Tok, diag::warn_omp_more_one_interop_type) << "targetsync";
1515       IsTargetSync = true;
1516     } else {
1517       HasError = true;
1518       P.Diag(Tok, diag::err_omp_expected_interop_type);
1519     }
1520     P.ConsumeToken();
1521 
1522     if (!Tok.is(tok::comma))
1523       break;
1524     P.ConsumeToken();
1525   }
1526   if (HasError)
1527     return None;
1528 
1529   if (!IsTarget && !IsTargetSync) {
1530     P.Diag(Tok, diag::err_omp_expected_interop_type);
1531     return None;
1532   }
1533 
1534   // As of OpenMP 5.1,there are two interop-types, "target" and
1535   // "targetsync". Either or both are allowed for a single interop.
1536   if (IsTarget && IsTargetSync)
1537     return OMPDeclareVariantAttr::Target_TargetSync;
1538   if (IsTarget)
1539     return OMPDeclareVariantAttr::Target;
1540   return OMPDeclareVariantAttr::TargetSync;
1541 }
1542 
1543 bool Parser::parseOpenMPAppendArgs(
1544     SmallVectorImpl<OMPDeclareVariantAttr::InteropType> &InterOpTypes) {
1545   bool HasError = false;
1546   // Parse '('.
1547   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1548   if (T.expectAndConsume(diag::err_expected_lparen_after,
1549                          getOpenMPClauseName(OMPC_append_args).data()))
1550     return true;
1551 
1552   // Parse the list of append-ops, each is;
1553   // interop(interop-type[,interop-type]...)
1554   while (Tok.is(tok::identifier) && Tok.getIdentifierInfo()->isStr("interop")) {
1555     ConsumeToken();
1556     BalancedDelimiterTracker IT(*this, tok::l_paren,
1557                                 tok::annot_pragma_openmp_end);
1558     if (IT.expectAndConsume(diag::err_expected_lparen_after, "interop"))
1559       return true;
1560 
1561     // Parse the interop-types.
1562     if (Optional<OMPDeclareVariantAttr::InteropType> IType =
1563             parseInteropTypeList(*this))
1564       InterOpTypes.push_back(IType.getValue());
1565     else
1566       HasError = true;
1567 
1568     IT.consumeClose();
1569     if (Tok.is(tok::comma))
1570       ConsumeToken();
1571   }
1572   if (!HasError && InterOpTypes.empty()) {
1573     HasError = true;
1574     Diag(Tok.getLocation(), diag::err_omp_unexpected_append_op);
1575     SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1576               StopBeforeMatch);
1577   }
1578   HasError = T.consumeClose() || HasError;
1579   return HasError;
1580 }
1581 
1582 bool Parser::parseOMPDeclareVariantMatchClause(SourceLocation Loc,
1583                                                OMPTraitInfo &TI,
1584                                                OMPTraitInfo *ParentTI) {
1585   // Parse 'match'.
1586   OpenMPClauseKind CKind = Tok.isAnnotation()
1587                                ? OMPC_unknown
1588                                : getOpenMPClauseKind(PP.getSpelling(Tok));
1589   if (CKind != OMPC_match) {
1590     Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
1591         << (getLangOpts().OpenMP < 51 ? 0 : 1);
1592     return true;
1593   }
1594   (void)ConsumeToken();
1595   // Parse '('.
1596   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1597   if (T.expectAndConsume(diag::err_expected_lparen_after,
1598                          getOpenMPClauseName(OMPC_match).data()))
1599     return true;
1600 
1601   // Parse inner context selectors.
1602   parseOMPContextSelectors(Loc, TI);
1603 
1604   // Parse ')'
1605   (void)T.consumeClose();
1606 
1607   if (!ParentTI)
1608     return false;
1609 
1610   // Merge the parent/outer trait info into the one we just parsed and diagnose
1611   // problems.
1612   // TODO: Keep some source location in the TI to provide better diagnostics.
1613   // TODO: Perform some kind of equivalence check on the condition and score
1614   //       expressions.
1615   for (const OMPTraitSet &ParentSet : ParentTI->Sets) {
1616     bool MergedSet = false;
1617     for (OMPTraitSet &Set : TI.Sets) {
1618       if (Set.Kind != ParentSet.Kind)
1619         continue;
1620       MergedSet = true;
1621       for (const OMPTraitSelector &ParentSelector : ParentSet.Selectors) {
1622         bool MergedSelector = false;
1623         for (OMPTraitSelector &Selector : Set.Selectors) {
1624           if (Selector.Kind != ParentSelector.Kind)
1625             continue;
1626           MergedSelector = true;
1627           for (const OMPTraitProperty &ParentProperty :
1628                ParentSelector.Properties) {
1629             bool MergedProperty = false;
1630             for (OMPTraitProperty &Property : Selector.Properties) {
1631               // Ignore "equivalent" properties.
1632               if (Property.Kind != ParentProperty.Kind)
1633                 continue;
1634 
1635               // If the kind is the same but the raw string not, we don't want
1636               // to skip out on the property.
1637               MergedProperty |= Property.RawString == ParentProperty.RawString;
1638 
1639               if (Property.RawString == ParentProperty.RawString &&
1640                   Selector.ScoreOrCondition == ParentSelector.ScoreOrCondition)
1641                 continue;
1642 
1643               if (Selector.Kind == llvm::omp::TraitSelector::user_condition) {
1644                 Diag(Loc, diag::err_omp_declare_variant_nested_user_condition);
1645               } else if (Selector.ScoreOrCondition !=
1646                          ParentSelector.ScoreOrCondition) {
1647                 Diag(Loc, diag::err_omp_declare_variant_duplicate_nested_trait)
1648                     << getOpenMPContextTraitPropertyName(
1649                            ParentProperty.Kind, ParentProperty.RawString)
1650                     << getOpenMPContextTraitSelectorName(ParentSelector.Kind)
1651                     << getOpenMPContextTraitSetName(ParentSet.Kind);
1652               }
1653             }
1654             if (!MergedProperty)
1655               Selector.Properties.push_back(ParentProperty);
1656           }
1657         }
1658         if (!MergedSelector)
1659           Set.Selectors.push_back(ParentSelector);
1660       }
1661     }
1662     if (!MergedSet)
1663       TI.Sets.push_back(ParentSet);
1664   }
1665 
1666   return false;
1667 }
1668 
1669 /// `omp assumes` or `omp begin/end assumes` <clause> [[,]<clause>]...
1670 /// where
1671 ///
1672 ///   clause:
1673 ///     'ext_IMPL_DEFINED'
1674 ///     'absent' '(' directive-name [, directive-name]* ')'
1675 ///     'contains' '(' directive-name [, directive-name]* ')'
1676 ///     'holds' '(' scalar-expression ')'
1677 ///     'no_openmp'
1678 ///     'no_openmp_routines'
1679 ///     'no_parallelism'
1680 ///
1681 void Parser::ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
1682                                          SourceLocation Loc) {
1683   SmallVector<std::string, 4> Assumptions;
1684   bool SkippedClauses = false;
1685 
1686   auto SkipBraces = [&](llvm::StringRef Spelling, bool IssueNote) {
1687     BalancedDelimiterTracker T(*this, tok::l_paren,
1688                                tok::annot_pragma_openmp_end);
1689     if (T.expectAndConsume(diag::err_expected_lparen_after, Spelling.data()))
1690       return;
1691     T.skipToEnd();
1692     if (IssueNote && T.getCloseLocation().isValid())
1693       Diag(T.getCloseLocation(),
1694            diag::note_omp_assumption_clause_continue_here);
1695   };
1696 
1697   /// Helper to determine which AssumptionClauseMapping (ACM) in the
1698   /// AssumptionClauseMappings table matches \p RawString. The return value is
1699   /// the index of the matching ACM into the table or -1 if there was no match.
1700   auto MatchACMClause = [&](StringRef RawString) {
1701     llvm::StringSwitch<int> SS(RawString);
1702     unsigned ACMIdx = 0;
1703     for (const AssumptionClauseMappingInfo &ACMI : AssumptionClauseMappings) {
1704       if (ACMI.StartsWith)
1705         SS.StartsWith(ACMI.Identifier, ACMIdx++);
1706       else
1707         SS.Case(ACMI.Identifier, ACMIdx++);
1708     }
1709     return SS.Default(-1);
1710   };
1711 
1712   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1713     IdentifierInfo *II = nullptr;
1714     SourceLocation StartLoc = Tok.getLocation();
1715     int Idx = -1;
1716     if (Tok.isAnyIdentifier()) {
1717       II = Tok.getIdentifierInfo();
1718       Idx = MatchACMClause(II->getName());
1719     }
1720     ConsumeAnyToken();
1721 
1722     bool NextIsLPar = Tok.is(tok::l_paren);
1723     // Handle unknown clauses by skipping them.
1724     if (Idx == -1) {
1725       Diag(StartLoc, diag::warn_omp_unknown_assumption_clause_missing_id)
1726           << llvm::omp::getOpenMPDirectiveName(DKind)
1727           << llvm::omp::getAllAssumeClauseOptions() << NextIsLPar;
1728       if (NextIsLPar)
1729         SkipBraces(II ? II->getName() : "", /* IssueNote */ true);
1730       SkippedClauses = true;
1731       continue;
1732     }
1733     const AssumptionClauseMappingInfo &ACMI = AssumptionClauseMappings[Idx];
1734     if (ACMI.HasDirectiveList || ACMI.HasExpression) {
1735       // TODO: We ignore absent, contains, and holds assumptions for now. We
1736       //       also do not verify the content in the parenthesis at all.
1737       SkippedClauses = true;
1738       SkipBraces(II->getName(), /* IssueNote */ false);
1739       continue;
1740     }
1741 
1742     if (NextIsLPar) {
1743       Diag(Tok.getLocation(),
1744            diag::warn_omp_unknown_assumption_clause_without_args)
1745           << II;
1746       SkipBraces(II->getName(), /* IssueNote */ true);
1747     }
1748 
1749     assert(II && "Expected an identifier clause!");
1750     std::string Assumption = II->getName().str();
1751     if (ACMI.StartsWith)
1752       Assumption = "ompx_" + Assumption.substr(ACMI.Identifier.size());
1753     else
1754       Assumption = "omp_" + Assumption;
1755     Assumptions.push_back(Assumption);
1756   }
1757 
1758   Actions.ActOnOpenMPAssumesDirective(Loc, DKind, Assumptions, SkippedClauses);
1759 }
1760 
1761 void Parser::ParseOpenMPEndAssumesDirective(SourceLocation Loc) {
1762   if (Actions.isInOpenMPAssumeScope())
1763     Actions.ActOnOpenMPEndAssumesDirective();
1764   else
1765     Diag(Loc, diag::err_expected_begin_assumes);
1766 }
1767 
1768 /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
1769 ///
1770 ///    default-clause:
1771 ///         'default' '(' 'none' | 'shared'  | 'private' | 'firstprivate' ')
1772 ///
1773 ///    proc_bind-clause:
1774 ///         'proc_bind' '(' 'master' | 'close' | 'spread' ')
1775 ///
1776 ///    device_type-clause:
1777 ///         'device_type' '(' 'host' | 'nohost' | 'any' )'
1778 namespace {
1779 struct SimpleClauseData {
1780   unsigned Type;
1781   SourceLocation Loc;
1782   SourceLocation LOpen;
1783   SourceLocation TypeLoc;
1784   SourceLocation RLoc;
1785   SimpleClauseData(unsigned Type, SourceLocation Loc, SourceLocation LOpen,
1786                    SourceLocation TypeLoc, SourceLocation RLoc)
1787       : Type(Type), Loc(Loc), LOpen(LOpen), TypeLoc(TypeLoc), RLoc(RLoc) {}
1788 };
1789 } // anonymous namespace
1790 
1791 static Optional<SimpleClauseData>
1792 parseOpenMPSimpleClause(Parser &P, OpenMPClauseKind Kind) {
1793   const Token &Tok = P.getCurToken();
1794   SourceLocation Loc = Tok.getLocation();
1795   SourceLocation LOpen = P.ConsumeToken();
1796   // Parse '('.
1797   BalancedDelimiterTracker T(P, tok::l_paren, tok::annot_pragma_openmp_end);
1798   if (T.expectAndConsume(diag::err_expected_lparen_after,
1799                          getOpenMPClauseName(Kind).data()))
1800     return llvm::None;
1801 
1802   unsigned Type = getOpenMPSimpleClauseType(
1803       Kind, Tok.isAnnotation() ? "" : P.getPreprocessor().getSpelling(Tok),
1804       P.getLangOpts());
1805   SourceLocation TypeLoc = Tok.getLocation();
1806   if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1807       Tok.isNot(tok::annot_pragma_openmp_end))
1808     P.ConsumeAnyToken();
1809 
1810   // Parse ')'.
1811   SourceLocation RLoc = Tok.getLocation();
1812   if (!T.consumeClose())
1813     RLoc = T.getCloseLocation();
1814 
1815   return SimpleClauseData(Type, Loc, LOpen, TypeLoc, RLoc);
1816 }
1817 
1818 void Parser::ParseOMPDeclareTargetClauses(
1819     Sema::DeclareTargetContextInfo &DTCI) {
1820   SourceLocation DeviceTypeLoc;
1821   bool RequiresToOrLinkOrIndirectClause = false;
1822   bool HasToOrLinkOrIndirectClause = false;
1823   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1824     OMPDeclareTargetDeclAttr::MapTypeTy MT = OMPDeclareTargetDeclAttr::MT_To;
1825     bool HasIdentifier = Tok.is(tok::identifier);
1826     if (HasIdentifier) {
1827       // If we see any clause we need a to or link clause.
1828       RequiresToOrLinkOrIndirectClause = true;
1829       IdentifierInfo *II = Tok.getIdentifierInfo();
1830       StringRef ClauseName = II->getName();
1831       bool IsDeviceTypeClause =
1832           getLangOpts().OpenMP >= 50 &&
1833           getOpenMPClauseKind(ClauseName) == OMPC_device_type;
1834 
1835       bool IsIndirectClause = getLangOpts().OpenMP >= 51 &&
1836                               getOpenMPClauseKind(ClauseName) == OMPC_indirect;
1837       if (DTCI.Indirect.hasValue() && IsIndirectClause) {
1838         Diag(Tok, diag::err_omp_more_one_clause)
1839             << getOpenMPDirectiveName(OMPD_declare_target)
1840             << getOpenMPClauseName(OMPC_indirect) << 0;
1841         break;
1842       }
1843       bool IsToOrLinkClause =
1844           OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName, MT);
1845       assert((!IsDeviceTypeClause || !IsToOrLinkClause) && "Cannot be both!");
1846 
1847       if (!IsDeviceTypeClause && !IsIndirectClause &&
1848           DTCI.Kind == OMPD_begin_declare_target) {
1849         Diag(Tok, diag::err_omp_declare_target_unexpected_clause)
1850             << ClauseName << (getLangOpts().OpenMP >= 51 ? 3 : 0);
1851         break;
1852       }
1853       if (!IsDeviceTypeClause && !IsToOrLinkClause && !IsIndirectClause) {
1854         Diag(Tok, diag::err_omp_declare_target_unexpected_clause)
1855             << ClauseName
1856             << (getLangOpts().OpenMP >= 51   ? 4
1857                 : getLangOpts().OpenMP >= 50 ? 2
1858                                              : 1);
1859         break;
1860       }
1861 
1862       if (IsToOrLinkClause || IsIndirectClause)
1863         HasToOrLinkOrIndirectClause = true;
1864 
1865       if (IsIndirectClause) {
1866         if (!ParseOpenMPIndirectClause(DTCI, /*ParseOnly*/ false))
1867           break;
1868         continue;
1869       }
1870       // Parse 'device_type' clause and go to next clause if any.
1871       if (IsDeviceTypeClause) {
1872         Optional<SimpleClauseData> DevTypeData =
1873             parseOpenMPSimpleClause(*this, OMPC_device_type);
1874         if (DevTypeData.hasValue()) {
1875           if (DeviceTypeLoc.isValid()) {
1876             // We already saw another device_type clause, diagnose it.
1877             Diag(DevTypeData.getValue().Loc,
1878                  diag::warn_omp_more_one_device_type_clause);
1879             break;
1880           }
1881           switch (static_cast<OpenMPDeviceType>(DevTypeData.getValue().Type)) {
1882           case OMPC_DEVICE_TYPE_any:
1883             DTCI.DT = OMPDeclareTargetDeclAttr::DT_Any;
1884             break;
1885           case OMPC_DEVICE_TYPE_host:
1886             DTCI.DT = OMPDeclareTargetDeclAttr::DT_Host;
1887             break;
1888           case OMPC_DEVICE_TYPE_nohost:
1889             DTCI.DT = OMPDeclareTargetDeclAttr::DT_NoHost;
1890             break;
1891           case OMPC_DEVICE_TYPE_unknown:
1892             llvm_unreachable("Unexpected device_type");
1893           }
1894           DeviceTypeLoc = DevTypeData.getValue().Loc;
1895         }
1896         continue;
1897       }
1898       ConsumeToken();
1899     }
1900 
1901     if (DTCI.Kind == OMPD_declare_target || HasIdentifier) {
1902       auto &&Callback = [this, MT, &DTCI](CXXScopeSpec &SS,
1903                                           DeclarationNameInfo NameInfo) {
1904         NamedDecl *ND =
1905             Actions.lookupOpenMPDeclareTargetName(getCurScope(), SS, NameInfo);
1906         if (!ND)
1907           return;
1908         Sema::DeclareTargetContextInfo::MapInfo MI{MT, NameInfo.getLoc()};
1909         bool FirstMapping = DTCI.ExplicitlyMapped.try_emplace(ND, MI).second;
1910         if (!FirstMapping)
1911           Diag(NameInfo.getLoc(), diag::err_omp_declare_target_multiple)
1912               << NameInfo.getName();
1913       };
1914       if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback,
1915                                    /*AllowScopeSpecifier=*/true))
1916         break;
1917     }
1918 
1919     if (Tok.is(tok::l_paren)) {
1920       Diag(Tok,
1921            diag::err_omp_begin_declare_target_unexpected_implicit_to_clause);
1922       break;
1923     }
1924     if (!HasIdentifier && Tok.isNot(tok::annot_pragma_openmp_end)) {
1925       Diag(Tok,
1926            diag::err_omp_declare_target_unexpected_clause_after_implicit_to);
1927       break;
1928     }
1929 
1930     // Consume optional ','.
1931     if (Tok.is(tok::comma))
1932       ConsumeToken();
1933   }
1934 
1935   if (DTCI.Indirect.hasValue() && DTCI.DT != OMPDeclareTargetDeclAttr::DT_Any)
1936     Diag(DeviceTypeLoc, diag::err_omp_declare_target_indirect_device_type);
1937 
1938   // For declare target require at least 'to' or 'link' to be present.
1939   if (DTCI.Kind == OMPD_declare_target && RequiresToOrLinkOrIndirectClause &&
1940       !HasToOrLinkOrIndirectClause)
1941     Diag(DTCI.Loc, diag::err_omp_declare_target_missing_to_or_link_clause)
1942         << (getLangOpts().OpenMP >= 51 ? 1 : 0);
1943 
1944   SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1945 }
1946 
1947 void Parser::skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind) {
1948   // The last seen token is annot_pragma_openmp_end - need to check for
1949   // extra tokens.
1950   if (Tok.is(tok::annot_pragma_openmp_end))
1951     return;
1952 
1953   Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
1954       << getOpenMPDirectiveName(DKind);
1955   while (Tok.isNot(tok::annot_pragma_openmp_end))
1956     ConsumeAnyToken();
1957 }
1958 
1959 void Parser::parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
1960                                   OpenMPDirectiveKind ExpectedKind,
1961                                   OpenMPDirectiveKind FoundKind,
1962                                   SourceLocation BeginLoc,
1963                                   SourceLocation FoundLoc,
1964                                   bool SkipUntilOpenMPEnd) {
1965   int DiagSelection = ExpectedKind == OMPD_end_declare_target ? 0 : 1;
1966 
1967   if (FoundKind == ExpectedKind) {
1968     ConsumeAnyToken();
1969     skipUntilPragmaOpenMPEnd(ExpectedKind);
1970     return;
1971   }
1972 
1973   Diag(FoundLoc, diag::err_expected_end_declare_target_or_variant)
1974       << DiagSelection;
1975   Diag(BeginLoc, diag::note_matching)
1976       << ("'#pragma omp " + getOpenMPDirectiveName(BeginKind) + "'").str();
1977   if (SkipUntilOpenMPEnd)
1978     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1979 }
1980 
1981 void Parser::ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind,
1982                                                OpenMPDirectiveKind EndDKind,
1983                                                SourceLocation DKLoc) {
1984   parseOMPEndDirective(BeginDKind, OMPD_end_declare_target, EndDKind, DKLoc,
1985                        Tok.getLocation(),
1986                        /* SkipUntilOpenMPEnd */ false);
1987   // Skip the last annot_pragma_openmp_end.
1988   if (Tok.is(tok::annot_pragma_openmp_end))
1989     ConsumeAnnotationToken();
1990 }
1991 
1992 /// Parsing of declarative OpenMP directives.
1993 ///
1994 ///       threadprivate-directive:
1995 ///         annot_pragma_openmp 'threadprivate' simple-variable-list
1996 ///         annot_pragma_openmp_end
1997 ///
1998 ///       allocate-directive:
1999 ///         annot_pragma_openmp 'allocate' simple-variable-list [<clause>]
2000 ///         annot_pragma_openmp_end
2001 ///
2002 ///       declare-reduction-directive:
2003 ///        annot_pragma_openmp 'declare' 'reduction' [...]
2004 ///        annot_pragma_openmp_end
2005 ///
2006 ///       declare-mapper-directive:
2007 ///         annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
2008 ///         <type> <var> ')' [<clause>[[,] <clause>] ... ]
2009 ///         annot_pragma_openmp_end
2010 ///
2011 ///       declare-simd-directive:
2012 ///         annot_pragma_openmp 'declare simd' {<clause> [,]}
2013 ///         annot_pragma_openmp_end
2014 ///         <function declaration/definition>
2015 ///
2016 ///       requires directive:
2017 ///         annot_pragma_openmp 'requires' <clause> [[[,] <clause>] ... ]
2018 ///         annot_pragma_openmp_end
2019 ///
2020 ///       assumes directive:
2021 ///         annot_pragma_openmp 'assumes' <clause> [[[,] <clause>] ... ]
2022 ///         annot_pragma_openmp_end
2023 ///       or
2024 ///         annot_pragma_openmp 'begin assumes' <clause> [[[,] <clause>] ... ]
2025 ///         annot_pragma_openmp 'end assumes'
2026 ///         annot_pragma_openmp_end
2027 ///
2028 Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
2029     AccessSpecifier &AS, ParsedAttributes &Attrs, bool Delayed,
2030     DeclSpec::TST TagType, Decl *Tag) {
2031   assert(Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) &&
2032          "Not an OpenMP directive!");
2033   ParsingOpenMPDirectiveRAII DirScope(*this);
2034   ParenBraceBracketBalancer BalancerRAIIObj(*this);
2035 
2036   SourceLocation Loc;
2037   OpenMPDirectiveKind DKind;
2038   if (Delayed) {
2039     TentativeParsingAction TPA(*this);
2040     Loc = ConsumeAnnotationToken();
2041     DKind = parseOpenMPDirectiveKind(*this);
2042     if (DKind == OMPD_declare_reduction || DKind == OMPD_declare_mapper) {
2043       // Need to delay parsing until completion of the parent class.
2044       TPA.Revert();
2045       CachedTokens Toks;
2046       unsigned Cnt = 1;
2047       Toks.push_back(Tok);
2048       while (Cnt && Tok.isNot(tok::eof)) {
2049         (void)ConsumeAnyToken();
2050         if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp))
2051           ++Cnt;
2052         else if (Tok.is(tok::annot_pragma_openmp_end))
2053           --Cnt;
2054         Toks.push_back(Tok);
2055       }
2056       // Skip last annot_pragma_openmp_end.
2057       if (Cnt == 0)
2058         (void)ConsumeAnyToken();
2059       auto *LP = new LateParsedPragma(this, AS);
2060       LP->takeToks(Toks);
2061       getCurrentClass().LateParsedDeclarations.push_back(LP);
2062       return nullptr;
2063     }
2064     TPA.Commit();
2065   } else {
2066     Loc = ConsumeAnnotationToken();
2067     DKind = parseOpenMPDirectiveKind(*this);
2068   }
2069 
2070   switch (DKind) {
2071   case OMPD_threadprivate: {
2072     ConsumeToken();
2073     DeclDirectiveListParserHelper Helper(this, DKind);
2074     if (!ParseOpenMPSimpleVarList(DKind, Helper,
2075                                   /*AllowScopeSpecifier=*/true)) {
2076       skipUntilPragmaOpenMPEnd(DKind);
2077       // Skip the last annot_pragma_openmp_end.
2078       ConsumeAnnotationToken();
2079       return Actions.ActOnOpenMPThreadprivateDirective(Loc,
2080                                                        Helper.getIdentifiers());
2081     }
2082     break;
2083   }
2084   case OMPD_allocate: {
2085     ConsumeToken();
2086     DeclDirectiveListParserHelper Helper(this, DKind);
2087     if (!ParseOpenMPSimpleVarList(DKind, Helper,
2088                                   /*AllowScopeSpecifier=*/true)) {
2089       SmallVector<OMPClause *, 1> Clauses;
2090       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
2091         SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
2092                     llvm::omp::Clause_enumSize + 1>
2093             FirstClauses(llvm::omp::Clause_enumSize + 1);
2094         while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2095           OpenMPClauseKind CKind =
2096               Tok.isAnnotation() ? OMPC_unknown
2097                                  : getOpenMPClauseKind(PP.getSpelling(Tok));
2098           Actions.StartOpenMPClause(CKind);
2099           OMPClause *Clause = ParseOpenMPClause(
2100               OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt());
2101           SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
2102                     StopBeforeMatch);
2103           FirstClauses[unsigned(CKind)].setInt(true);
2104           if (Clause != nullptr)
2105             Clauses.push_back(Clause);
2106           if (Tok.is(tok::annot_pragma_openmp_end)) {
2107             Actions.EndOpenMPClause();
2108             break;
2109           }
2110           // Skip ',' if any.
2111           if (Tok.is(tok::comma))
2112             ConsumeToken();
2113           Actions.EndOpenMPClause();
2114         }
2115         skipUntilPragmaOpenMPEnd(DKind);
2116       }
2117       // Skip the last annot_pragma_openmp_end.
2118       ConsumeAnnotationToken();
2119       return Actions.ActOnOpenMPAllocateDirective(Loc, Helper.getIdentifiers(),
2120                                                   Clauses);
2121     }
2122     break;
2123   }
2124   case OMPD_requires: {
2125     SourceLocation StartLoc = ConsumeToken();
2126     SmallVector<OMPClause *, 5> Clauses;
2127     SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
2128                 llvm::omp::Clause_enumSize + 1>
2129         FirstClauses(llvm::omp::Clause_enumSize + 1);
2130     if (Tok.is(tok::annot_pragma_openmp_end)) {
2131       Diag(Tok, diag::err_omp_expected_clause)
2132           << getOpenMPDirectiveName(OMPD_requires);
2133       break;
2134     }
2135     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2136       OpenMPClauseKind CKind = Tok.isAnnotation()
2137                                    ? OMPC_unknown
2138                                    : getOpenMPClauseKind(PP.getSpelling(Tok));
2139       Actions.StartOpenMPClause(CKind);
2140       OMPClause *Clause = ParseOpenMPClause(
2141           OMPD_requires, CKind, !FirstClauses[unsigned(CKind)].getInt());
2142       SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
2143                 StopBeforeMatch);
2144       FirstClauses[unsigned(CKind)].setInt(true);
2145       if (Clause != nullptr)
2146         Clauses.push_back(Clause);
2147       if (Tok.is(tok::annot_pragma_openmp_end)) {
2148         Actions.EndOpenMPClause();
2149         break;
2150       }
2151       // Skip ',' if any.
2152       if (Tok.is(tok::comma))
2153         ConsumeToken();
2154       Actions.EndOpenMPClause();
2155     }
2156     // Consume final annot_pragma_openmp_end
2157     if (Clauses.empty()) {
2158       Diag(Tok, diag::err_omp_expected_clause)
2159           << getOpenMPDirectiveName(OMPD_requires);
2160       ConsumeAnnotationToken();
2161       return nullptr;
2162     }
2163     ConsumeAnnotationToken();
2164     return Actions.ActOnOpenMPRequiresDirective(StartLoc, Clauses);
2165   }
2166   case OMPD_assumes:
2167   case OMPD_begin_assumes:
2168     ParseOpenMPAssumesDirective(DKind, ConsumeToken());
2169     break;
2170   case OMPD_end_assumes:
2171     ParseOpenMPEndAssumesDirective(ConsumeToken());
2172     break;
2173   case OMPD_declare_reduction:
2174     ConsumeToken();
2175     if (DeclGroupPtrTy Res = ParseOpenMPDeclareReductionDirective(AS)) {
2176       skipUntilPragmaOpenMPEnd(OMPD_declare_reduction);
2177       // Skip the last annot_pragma_openmp_end.
2178       ConsumeAnnotationToken();
2179       return Res;
2180     }
2181     break;
2182   case OMPD_declare_mapper: {
2183     ConsumeToken();
2184     if (DeclGroupPtrTy Res = ParseOpenMPDeclareMapperDirective(AS)) {
2185       // Skip the last annot_pragma_openmp_end.
2186       ConsumeAnnotationToken();
2187       return Res;
2188     }
2189     break;
2190   }
2191   case OMPD_begin_declare_variant: {
2192     // The syntax is:
2193     // { #pragma omp begin declare variant clause }
2194     // <function-declaration-or-definition-sequence>
2195     // { #pragma omp end declare variant }
2196     //
2197     ConsumeToken();
2198     OMPTraitInfo *ParentTI = Actions.getOMPTraitInfoForSurroundingScope();
2199     ASTContext &ASTCtx = Actions.getASTContext();
2200     OMPTraitInfo &TI = ASTCtx.getNewOMPTraitInfo();
2201     if (parseOMPDeclareVariantMatchClause(Loc, TI, ParentTI)) {
2202       while (!SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch))
2203         ;
2204       // Skip the last annot_pragma_openmp_end.
2205       (void)ConsumeAnnotationToken();
2206       break;
2207     }
2208 
2209     // Skip last tokens.
2210     skipUntilPragmaOpenMPEnd(OMPD_begin_declare_variant);
2211 
2212     ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
2213 
2214     VariantMatchInfo VMI;
2215     TI.getAsVariantMatchInfo(ASTCtx, VMI);
2216 
2217     std::function<void(StringRef)> DiagUnknownTrait =
2218         [this, Loc](StringRef ISATrait) {
2219           // TODO Track the selector locations in a way that is accessible here
2220           // to improve the diagnostic location.
2221           Diag(Loc, diag::warn_unknown_declare_variant_isa_trait) << ISATrait;
2222         };
2223     TargetOMPContext OMPCtx(
2224         ASTCtx, std::move(DiagUnknownTrait),
2225         /* CurrentFunctionDecl */ nullptr,
2226         /* ConstructTraits */ ArrayRef<llvm::omp::TraitProperty>());
2227 
2228     if (isVariantApplicableInContext(VMI, OMPCtx, /* DeviceSetOnly */ true)) {
2229       Actions.ActOnOpenMPBeginDeclareVariant(Loc, TI);
2230       break;
2231     }
2232 
2233     // Elide all the code till the matching end declare variant was found.
2234     unsigned Nesting = 1;
2235     SourceLocation DKLoc;
2236     OpenMPDirectiveKind DK = OMPD_unknown;
2237     do {
2238       DKLoc = Tok.getLocation();
2239       DK = parseOpenMPDirectiveKind(*this);
2240       if (DK == OMPD_end_declare_variant)
2241         --Nesting;
2242       else if (DK == OMPD_begin_declare_variant)
2243         ++Nesting;
2244       if (!Nesting || isEofOrEom())
2245         break;
2246       ConsumeAnyToken();
2247     } while (true);
2248 
2249     parseOMPEndDirective(OMPD_begin_declare_variant, OMPD_end_declare_variant,
2250                          DK, Loc, DKLoc, /* SkipUntilOpenMPEnd */ true);
2251     if (isEofOrEom())
2252       return nullptr;
2253     break;
2254   }
2255   case OMPD_end_declare_variant: {
2256     if (Actions.isInOpenMPDeclareVariantScope())
2257       Actions.ActOnOpenMPEndDeclareVariant();
2258     else
2259       Diag(Loc, diag::err_expected_begin_declare_variant);
2260     ConsumeToken();
2261     break;
2262   }
2263   case OMPD_declare_variant:
2264   case OMPD_declare_simd: {
2265     // The syntax is:
2266     // { #pragma omp declare {simd|variant} }
2267     // <function-declaration-or-definition>
2268     //
2269     CachedTokens Toks;
2270     Toks.push_back(Tok);
2271     ConsumeToken();
2272     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2273       Toks.push_back(Tok);
2274       ConsumeAnyToken();
2275     }
2276     Toks.push_back(Tok);
2277     ConsumeAnyToken();
2278 
2279     DeclGroupPtrTy Ptr;
2280     if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
2281       Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, Delayed,
2282                                                        TagType, Tag);
2283     } else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2284       // Here we expect to see some function declaration.
2285       if (AS == AS_none) {
2286         assert(TagType == DeclSpec::TST_unspecified);
2287         MaybeParseCXX11Attributes(Attrs);
2288         ParsingDeclSpec PDS(*this);
2289         Ptr = ParseExternalDeclaration(Attrs, &PDS);
2290       } else {
2291         Ptr =
2292             ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag);
2293       }
2294     }
2295     if (!Ptr) {
2296       Diag(Loc, diag::err_omp_decl_in_declare_simd_variant)
2297           << (DKind == OMPD_declare_simd ? 0 : 1);
2298       return DeclGroupPtrTy();
2299     }
2300     if (DKind == OMPD_declare_simd)
2301       return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc);
2302     assert(DKind == OMPD_declare_variant &&
2303            "Expected declare variant directive only");
2304     ParseOMPDeclareVariantClauses(Ptr, Toks, Loc);
2305     return Ptr;
2306   }
2307   case OMPD_begin_declare_target:
2308   case OMPD_declare_target: {
2309     SourceLocation DTLoc = ConsumeAnyToken();
2310     bool HasClauses = Tok.isNot(tok::annot_pragma_openmp_end);
2311     Sema::DeclareTargetContextInfo DTCI(DKind, DTLoc);
2312     if (HasClauses)
2313       ParseOMPDeclareTargetClauses(DTCI);
2314     bool HasImplicitMappings =
2315         DKind == OMPD_begin_declare_target || !HasClauses ||
2316         (DTCI.ExplicitlyMapped.empty() && DTCI.Indirect.hasValue());
2317 
2318     // Skip the last annot_pragma_openmp_end.
2319     ConsumeAnyToken();
2320 
2321     if (HasImplicitMappings) {
2322       Actions.ActOnStartOpenMPDeclareTargetContext(DTCI);
2323       return nullptr;
2324     }
2325 
2326     Actions.ActOnFinishedOpenMPDeclareTargetContext(DTCI);
2327     llvm::SmallVector<Decl *, 4> Decls;
2328     for (auto &It : DTCI.ExplicitlyMapped)
2329       Decls.push_back(It.first);
2330     return Actions.BuildDeclaratorGroup(Decls);
2331   }
2332   case OMPD_end_declare_target: {
2333     if (!Actions.isInOpenMPDeclareTargetContext()) {
2334       Diag(Tok, diag::err_omp_unexpected_directive)
2335           << 1 << getOpenMPDirectiveName(DKind);
2336       break;
2337     }
2338     const Sema::DeclareTargetContextInfo &DTCI =
2339         Actions.ActOnOpenMPEndDeclareTargetDirective();
2340     ParseOMPEndDeclareTargetDirective(DTCI.Kind, DKind, DTCI.Loc);
2341     return nullptr;
2342   }
2343   case OMPD_unknown:
2344     Diag(Tok, diag::err_omp_unknown_directive);
2345     break;
2346   case OMPD_parallel:
2347   case OMPD_simd:
2348   case OMPD_tile:
2349   case OMPD_unroll:
2350   case OMPD_task:
2351   case OMPD_taskyield:
2352   case OMPD_barrier:
2353   case OMPD_taskwait:
2354   case OMPD_taskgroup:
2355   case OMPD_flush:
2356   case OMPD_depobj:
2357   case OMPD_scan:
2358   case OMPD_for:
2359   case OMPD_for_simd:
2360   case OMPD_sections:
2361   case OMPD_section:
2362   case OMPD_single:
2363   case OMPD_master:
2364   case OMPD_ordered:
2365   case OMPD_critical:
2366   case OMPD_parallel_for:
2367   case OMPD_parallel_for_simd:
2368   case OMPD_parallel_sections:
2369   case OMPD_parallel_master:
2370   case OMPD_atomic:
2371   case OMPD_target:
2372   case OMPD_teams:
2373   case OMPD_cancellation_point:
2374   case OMPD_cancel:
2375   case OMPD_target_data:
2376   case OMPD_target_enter_data:
2377   case OMPD_target_exit_data:
2378   case OMPD_target_parallel:
2379   case OMPD_target_parallel_for:
2380   case OMPD_taskloop:
2381   case OMPD_taskloop_simd:
2382   case OMPD_master_taskloop:
2383   case OMPD_master_taskloop_simd:
2384   case OMPD_parallel_master_taskloop:
2385   case OMPD_parallel_master_taskloop_simd:
2386   case OMPD_distribute:
2387   case OMPD_target_update:
2388   case OMPD_distribute_parallel_for:
2389   case OMPD_distribute_parallel_for_simd:
2390   case OMPD_distribute_simd:
2391   case OMPD_target_parallel_for_simd:
2392   case OMPD_target_simd:
2393   case OMPD_teams_distribute:
2394   case OMPD_teams_distribute_simd:
2395   case OMPD_teams_distribute_parallel_for_simd:
2396   case OMPD_teams_distribute_parallel_for:
2397   case OMPD_target_teams:
2398   case OMPD_target_teams_distribute:
2399   case OMPD_target_teams_distribute_parallel_for:
2400   case OMPD_target_teams_distribute_parallel_for_simd:
2401   case OMPD_target_teams_distribute_simd:
2402   case OMPD_dispatch:
2403   case OMPD_masked:
2404   case OMPD_metadirective:
2405   case OMPD_loop:
2406   case OMPD_teams_loop:
2407   case OMPD_target_teams_loop:
2408   case OMPD_parallel_loop:
2409   case OMPD_target_parallel_loop:
2410     Diag(Tok, diag::err_omp_unexpected_directive)
2411         << 1 << getOpenMPDirectiveName(DKind);
2412     break;
2413   default:
2414     break;
2415   }
2416   while (Tok.isNot(tok::annot_pragma_openmp_end))
2417     ConsumeAnyToken();
2418   ConsumeAnyToken();
2419   return nullptr;
2420 }
2421 
2422 /// Parsing of declarative or executable OpenMP directives.
2423 ///
2424 ///       threadprivate-directive:
2425 ///         annot_pragma_openmp 'threadprivate' simple-variable-list
2426 ///         annot_pragma_openmp_end
2427 ///
2428 ///       allocate-directive:
2429 ///         annot_pragma_openmp 'allocate' simple-variable-list
2430 ///         annot_pragma_openmp_end
2431 ///
2432 ///       declare-reduction-directive:
2433 ///         annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':'
2434 ///         <type> {',' <type>} ':' <expression> ')' ['initializer' '('
2435 ///         ('omp_priv' '=' <expression>|<function_call>) ')']
2436 ///         annot_pragma_openmp_end
2437 ///
2438 ///       declare-mapper-directive:
2439 ///         annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
2440 ///         <type> <var> ')' [<clause>[[,] <clause>] ... ]
2441 ///         annot_pragma_openmp_end
2442 ///
2443 ///       executable-directive:
2444 ///         annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
2445 ///         'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
2446 ///         'parallel for' | 'parallel sections' | 'parallel master' | 'task' |
2447 ///         'taskyield' | 'barrier' | 'taskwait' | 'flush' | 'ordered' |
2448 ///         'atomic' | 'for simd' | 'parallel for simd' | 'target' | 'target
2449 ///         data' | 'taskgroup' | 'teams' | 'taskloop' | 'taskloop simd' |
2450 ///         'master taskloop' | 'master taskloop simd' | 'parallel master
2451 ///         taskloop' | 'parallel master taskloop simd' | 'distribute' | 'target
2452 ///         enter data' | 'target exit data' | 'target parallel' | 'target
2453 ///         parallel for' | 'target update' | 'distribute parallel for' |
2454 ///         'distribute paralle for simd' | 'distribute simd' | 'target parallel
2455 ///         for simd' | 'target simd' | 'teams distribute' | 'teams distribute
2456 ///         simd' | 'teams distribute parallel for simd' | 'teams distribute
2457 ///         parallel for' | 'target teams' | 'target teams distribute' | 'target
2458 ///         teams distribute parallel for' | 'target teams distribute parallel
2459 ///         for simd' | 'target teams distribute simd' | 'masked' {clause}
2460 ///         annot_pragma_openmp_end
2461 ///
2462 StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
2463     ParsedStmtContext StmtCtx, bool ReadDirectiveWithinMetadirective) {
2464   if (!ReadDirectiveWithinMetadirective)
2465     assert(Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) &&
2466            "Not an OpenMP directive!");
2467   ParsingOpenMPDirectiveRAII DirScope(*this);
2468   ParenBraceBracketBalancer BalancerRAIIObj(*this);
2469   SmallVector<OMPClause *, 5> Clauses;
2470   SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
2471               llvm::omp::Clause_enumSize + 1>
2472       FirstClauses(llvm::omp::Clause_enumSize + 1);
2473   unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
2474                         Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope;
2475   SourceLocation Loc = ReadDirectiveWithinMetadirective
2476                            ? Tok.getLocation()
2477                            : ConsumeAnnotationToken(),
2478                  EndLoc;
2479   OpenMPDirectiveKind DKind = parseOpenMPDirectiveKind(*this);
2480   if (ReadDirectiveWithinMetadirective && DKind == OMPD_unknown) {
2481     Diag(Tok, diag::err_omp_unknown_directive);
2482     return StmtError();
2483   }
2484   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
2485   // Name of critical directive.
2486   DeclarationNameInfo DirName;
2487   StmtResult Directive = StmtError();
2488   bool HasAssociatedStatement = true;
2489 
2490   switch (DKind) {
2491   case OMPD_nothing:
2492     if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2493         ParsedStmtContext())
2494       Diag(Tok, diag::err_omp_immediate_directive)
2495         << getOpenMPDirectiveName(DKind) << 0;
2496     ConsumeToken();
2497     skipUntilPragmaOpenMPEnd(DKind);
2498     if (Tok.is(tok::annot_pragma_openmp_end))
2499       ConsumeAnnotationToken();
2500     break;
2501   case OMPD_metadirective: {
2502     ConsumeToken();
2503     SmallVector<VariantMatchInfo, 4> VMIs;
2504 
2505     // First iteration of parsing all clauses of metadirective.
2506     // This iteration only parses and collects all context selector ignoring the
2507     // associated directives.
2508     TentativeParsingAction TPA(*this);
2509     ASTContext &ASTContext = Actions.getASTContext();
2510 
2511     BalancedDelimiterTracker T(*this, tok::l_paren,
2512                                tok::annot_pragma_openmp_end);
2513     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2514       OpenMPClauseKind CKind = Tok.isAnnotation()
2515                                    ? OMPC_unknown
2516                                    : getOpenMPClauseKind(PP.getSpelling(Tok));
2517       SourceLocation Loc = ConsumeToken();
2518 
2519       // Parse '('.
2520       if (T.expectAndConsume(diag::err_expected_lparen_after,
2521                              getOpenMPClauseName(CKind).data()))
2522         return Directive;
2523 
2524       OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo();
2525       if (CKind == OMPC_when) {
2526         // parse and get OMPTraitInfo to pass to the When clause
2527         parseOMPContextSelectors(Loc, TI);
2528         if (TI.Sets.size() == 0) {
2529           Diag(Tok, diag::err_omp_expected_context_selector) << "when clause";
2530           TPA.Commit();
2531           return Directive;
2532         }
2533 
2534         // Parse ':'
2535         if (Tok.is(tok::colon))
2536           ConsumeAnyToken();
2537         else {
2538           Diag(Tok, diag::err_omp_expected_colon) << "when clause";
2539           TPA.Commit();
2540           return Directive;
2541         }
2542       }
2543       // Skip Directive for now. We will parse directive in the second iteration
2544       int paren = 0;
2545       while (Tok.isNot(tok::r_paren) || paren != 0) {
2546         if (Tok.is(tok::l_paren))
2547           paren++;
2548         if (Tok.is(tok::r_paren))
2549           paren--;
2550         if (Tok.is(tok::annot_pragma_openmp_end)) {
2551           Diag(Tok, diag::err_omp_expected_punc)
2552               << getOpenMPClauseName(CKind) << 0;
2553           TPA.Commit();
2554           return Directive;
2555         }
2556         ConsumeAnyToken();
2557       }
2558       // Parse ')'
2559       if (Tok.is(tok::r_paren))
2560         T.consumeClose();
2561 
2562       VariantMatchInfo VMI;
2563       TI.getAsVariantMatchInfo(ASTContext, VMI);
2564 
2565       VMIs.push_back(VMI);
2566     }
2567 
2568     TPA.Revert();
2569     // End of the first iteration. Parser is reset to the start of metadirective
2570 
2571     std::function<void(StringRef)> DiagUnknownTrait =
2572         [this, Loc](StringRef ISATrait) {
2573           // TODO Track the selector locations in a way that is accessible here
2574           // to improve the diagnostic location.
2575           Diag(Loc, diag::warn_unknown_declare_variant_isa_trait) << ISATrait;
2576         };
2577     TargetOMPContext OMPCtx(ASTContext, std::move(DiagUnknownTrait),
2578                             /* CurrentFunctionDecl */ nullptr,
2579                             ArrayRef<llvm::omp::TraitProperty>());
2580 
2581     // A single match is returned for OpenMP 5.0
2582     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
2583 
2584     int Idx = 0;
2585     // In OpenMP 5.0 metadirective is either replaced by another directive or
2586     // ignored.
2587     // TODO: In OpenMP 5.1 generate multiple directives based upon the matches
2588     // found by getBestWhenMatchForContext.
2589     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2590       // OpenMP 5.0 implementation - Skip to the best index found.
2591       if (Idx++ != BestIdx) {
2592         ConsumeToken();  // Consume clause name
2593         T.consumeOpen(); // Consume '('
2594         int paren = 0;
2595         // Skip everything inside the clause
2596         while (Tok.isNot(tok::r_paren) || paren != 0) {
2597           if (Tok.is(tok::l_paren))
2598             paren++;
2599           if (Tok.is(tok::r_paren))
2600             paren--;
2601           ConsumeAnyToken();
2602         }
2603         // Parse ')'
2604         if (Tok.is(tok::r_paren))
2605           T.consumeClose();
2606         continue;
2607       }
2608 
2609       OpenMPClauseKind CKind = Tok.isAnnotation()
2610                                    ? OMPC_unknown
2611                                    : getOpenMPClauseKind(PP.getSpelling(Tok));
2612       SourceLocation Loc = ConsumeToken();
2613 
2614       // Parse '('.
2615       T.consumeOpen();
2616 
2617       // Skip ContextSelectors for when clause
2618       if (CKind == OMPC_when) {
2619         OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo();
2620         // parse and skip the ContextSelectors
2621         parseOMPContextSelectors(Loc, TI);
2622 
2623         // Parse ':'
2624         ConsumeAnyToken();
2625       }
2626 
2627       // If no directive is passed, skip in OpenMP 5.0.
2628       // TODO: Generate nothing directive from OpenMP 5.1.
2629       if (Tok.is(tok::r_paren)) {
2630         SkipUntil(tok::annot_pragma_openmp_end);
2631         break;
2632       }
2633 
2634       // Parse Directive
2635       Directive = ParseOpenMPDeclarativeOrExecutableDirective(
2636           StmtCtx,
2637           /*ReadDirectiveWithinMetadirective=*/true);
2638       break;
2639     }
2640     break;
2641   }
2642   case OMPD_threadprivate: {
2643     // FIXME: Should this be permitted in C++?
2644     if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
2645         ParsedStmtContext()) {
2646       Diag(Tok, diag::err_omp_immediate_directive)
2647           << getOpenMPDirectiveName(DKind) << 0;
2648     }
2649     ConsumeToken();
2650     DeclDirectiveListParserHelper Helper(this, DKind);
2651     if (!ParseOpenMPSimpleVarList(DKind, Helper,
2652                                   /*AllowScopeSpecifier=*/false)) {
2653       skipUntilPragmaOpenMPEnd(DKind);
2654       DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective(
2655           Loc, Helper.getIdentifiers());
2656       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2657     }
2658     SkipUntil(tok::annot_pragma_openmp_end);
2659     break;
2660   }
2661   case OMPD_allocate: {
2662     // FIXME: Should this be permitted in C++?
2663     if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
2664         ParsedStmtContext()) {
2665       Diag(Tok, diag::err_omp_immediate_directive)
2666           << getOpenMPDirectiveName(DKind) << 0;
2667     }
2668     ConsumeToken();
2669     DeclDirectiveListParserHelper Helper(this, DKind);
2670     if (!ParseOpenMPSimpleVarList(DKind, Helper,
2671                                   /*AllowScopeSpecifier=*/false)) {
2672       SmallVector<OMPClause *, 1> Clauses;
2673       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
2674         SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
2675                     llvm::omp::Clause_enumSize + 1>
2676             FirstClauses(llvm::omp::Clause_enumSize + 1);
2677         while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2678           OpenMPClauseKind CKind =
2679               Tok.isAnnotation() ? OMPC_unknown
2680                                  : getOpenMPClauseKind(PP.getSpelling(Tok));
2681           Actions.StartOpenMPClause(CKind);
2682           OMPClause *Clause = ParseOpenMPClause(
2683               OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt());
2684           SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
2685                     StopBeforeMatch);
2686           FirstClauses[unsigned(CKind)].setInt(true);
2687           if (Clause != nullptr)
2688             Clauses.push_back(Clause);
2689           if (Tok.is(tok::annot_pragma_openmp_end)) {
2690             Actions.EndOpenMPClause();
2691             break;
2692           }
2693           // Skip ',' if any.
2694           if (Tok.is(tok::comma))
2695             ConsumeToken();
2696           Actions.EndOpenMPClause();
2697         }
2698         skipUntilPragmaOpenMPEnd(DKind);
2699       }
2700       DeclGroupPtrTy Res = Actions.ActOnOpenMPAllocateDirective(
2701           Loc, Helper.getIdentifiers(), Clauses);
2702       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2703     }
2704     SkipUntil(tok::annot_pragma_openmp_end);
2705     break;
2706   }
2707   case OMPD_declare_reduction:
2708     ConsumeToken();
2709     if (DeclGroupPtrTy Res =
2710             ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) {
2711       skipUntilPragmaOpenMPEnd(OMPD_declare_reduction);
2712       ConsumeAnyToken();
2713       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2714     } else {
2715       SkipUntil(tok::annot_pragma_openmp_end);
2716     }
2717     break;
2718   case OMPD_declare_mapper: {
2719     ConsumeToken();
2720     if (DeclGroupPtrTy Res =
2721             ParseOpenMPDeclareMapperDirective(/*AS=*/AS_none)) {
2722       // Skip the last annot_pragma_openmp_end.
2723       ConsumeAnnotationToken();
2724       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2725     } else {
2726       SkipUntil(tok::annot_pragma_openmp_end);
2727     }
2728     break;
2729   }
2730   case OMPD_flush:
2731   case OMPD_depobj:
2732   case OMPD_scan:
2733   case OMPD_taskyield:
2734   case OMPD_barrier:
2735   case OMPD_taskwait:
2736   case OMPD_cancellation_point:
2737   case OMPD_cancel:
2738   case OMPD_target_enter_data:
2739   case OMPD_target_exit_data:
2740   case OMPD_target_update:
2741   case OMPD_interop:
2742     if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2743         ParsedStmtContext()) {
2744       Diag(Tok, diag::err_omp_immediate_directive)
2745           << getOpenMPDirectiveName(DKind) << 0;
2746     }
2747     HasAssociatedStatement = false;
2748     // Fall through for further analysis.
2749     LLVM_FALLTHROUGH;
2750   case OMPD_parallel:
2751   case OMPD_simd:
2752   case OMPD_tile:
2753   case OMPD_unroll:
2754   case OMPD_for:
2755   case OMPD_for_simd:
2756   case OMPD_sections:
2757   case OMPD_single:
2758   case OMPD_section:
2759   case OMPD_master:
2760   case OMPD_critical:
2761   case OMPD_parallel_for:
2762   case OMPD_parallel_for_simd:
2763   case OMPD_parallel_sections:
2764   case OMPD_parallel_master:
2765   case OMPD_task:
2766   case OMPD_ordered:
2767   case OMPD_atomic:
2768   case OMPD_target:
2769   case OMPD_teams:
2770   case OMPD_taskgroup:
2771   case OMPD_target_data:
2772   case OMPD_target_parallel:
2773   case OMPD_target_parallel_for:
2774   case OMPD_loop:
2775   case OMPD_teams_loop:
2776   case OMPD_target_teams_loop:
2777   case OMPD_parallel_loop:
2778   case OMPD_target_parallel_loop:
2779   case OMPD_taskloop:
2780   case OMPD_taskloop_simd:
2781   case OMPD_master_taskloop:
2782   case OMPD_master_taskloop_simd:
2783   case OMPD_parallel_master_taskloop:
2784   case OMPD_parallel_master_taskloop_simd:
2785   case OMPD_distribute:
2786   case OMPD_distribute_parallel_for:
2787   case OMPD_distribute_parallel_for_simd:
2788   case OMPD_distribute_simd:
2789   case OMPD_target_parallel_for_simd:
2790   case OMPD_target_simd:
2791   case OMPD_teams_distribute:
2792   case OMPD_teams_distribute_simd:
2793   case OMPD_teams_distribute_parallel_for_simd:
2794   case OMPD_teams_distribute_parallel_for:
2795   case OMPD_target_teams:
2796   case OMPD_target_teams_distribute:
2797   case OMPD_target_teams_distribute_parallel_for:
2798   case OMPD_target_teams_distribute_parallel_for_simd:
2799   case OMPD_target_teams_distribute_simd:
2800   case OMPD_dispatch:
2801   case OMPD_masked: {
2802     // Special processing for flush and depobj clauses.
2803     Token ImplicitTok;
2804     bool ImplicitClauseAllowed = false;
2805     if (DKind == OMPD_flush || DKind == OMPD_depobj) {
2806       ImplicitTok = Tok;
2807       ImplicitClauseAllowed = true;
2808     }
2809     ConsumeToken();
2810     // Parse directive name of the 'critical' directive if any.
2811     if (DKind == OMPD_critical) {
2812       BalancedDelimiterTracker T(*this, tok::l_paren,
2813                                  tok::annot_pragma_openmp_end);
2814       if (!T.consumeOpen()) {
2815         if (Tok.isAnyIdentifier()) {
2816           DirName =
2817               DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation());
2818           ConsumeAnyToken();
2819         } else {
2820           Diag(Tok, diag::err_omp_expected_identifier_for_critical);
2821         }
2822         T.consumeClose();
2823       }
2824     } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) {
2825       CancelRegion = parseOpenMPDirectiveKind(*this);
2826       if (Tok.isNot(tok::annot_pragma_openmp_end))
2827         ConsumeToken();
2828     }
2829 
2830     if (isOpenMPLoopDirective(DKind))
2831       ScopeFlags |= Scope::OpenMPLoopDirectiveScope;
2832     if (isOpenMPSimdDirective(DKind))
2833       ScopeFlags |= Scope::OpenMPSimdDirectiveScope;
2834     ParseScope OMPDirectiveScope(this, ScopeFlags);
2835     Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc);
2836 
2837     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2838       // If we are parsing for a directive within a metadirective, the directive
2839       // ends with a ')'.
2840       if (ReadDirectiveWithinMetadirective && Tok.is(tok::r_paren)) {
2841         while (Tok.isNot(tok::annot_pragma_openmp_end))
2842           ConsumeAnyToken();
2843         break;
2844       }
2845       bool HasImplicitClause = false;
2846       if (ImplicitClauseAllowed && Tok.is(tok::l_paren)) {
2847         HasImplicitClause = true;
2848         // Push copy of the current token back to stream to properly parse
2849         // pseudo-clause OMPFlushClause or OMPDepobjClause.
2850         PP.EnterToken(Tok, /*IsReinject*/ true);
2851         PP.EnterToken(ImplicitTok, /*IsReinject*/ true);
2852         ConsumeAnyToken();
2853       }
2854       OpenMPClauseKind CKind = Tok.isAnnotation()
2855                                    ? OMPC_unknown
2856                                    : getOpenMPClauseKind(PP.getSpelling(Tok));
2857       if (HasImplicitClause) {
2858         assert(CKind == OMPC_unknown && "Must be unknown implicit clause.");
2859         if (DKind == OMPD_flush) {
2860           CKind = OMPC_flush;
2861         } else {
2862           assert(DKind == OMPD_depobj &&
2863                  "Expected flush or depobj directives.");
2864           CKind = OMPC_depobj;
2865         }
2866       }
2867       // No more implicit clauses allowed.
2868       ImplicitClauseAllowed = false;
2869       Actions.StartOpenMPClause(CKind);
2870       HasImplicitClause = false;
2871       OMPClause *Clause = ParseOpenMPClause(
2872           DKind, CKind, !FirstClauses[unsigned(CKind)].getInt());
2873       FirstClauses[unsigned(CKind)].setInt(true);
2874       if (Clause) {
2875         FirstClauses[unsigned(CKind)].setPointer(Clause);
2876         Clauses.push_back(Clause);
2877       }
2878 
2879       // Skip ',' if any.
2880       if (Tok.is(tok::comma))
2881         ConsumeToken();
2882       Actions.EndOpenMPClause();
2883     }
2884     // End location of the directive.
2885     EndLoc = Tok.getLocation();
2886     // Consume final annot_pragma_openmp_end.
2887     ConsumeAnnotationToken();
2888 
2889     // OpenMP [2.13.8, ordered Construct, Syntax]
2890     // If the depend clause is specified, the ordered construct is a stand-alone
2891     // directive.
2892     if (DKind == OMPD_ordered && FirstClauses[unsigned(OMPC_depend)].getInt()) {
2893       if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2894           ParsedStmtContext()) {
2895         Diag(Loc, diag::err_omp_immediate_directive)
2896             << getOpenMPDirectiveName(DKind) << 1
2897             << getOpenMPClauseName(OMPC_depend);
2898       }
2899       HasAssociatedStatement = false;
2900     }
2901 
2902     if (DKind == OMPD_tile && !FirstClauses[unsigned(OMPC_sizes)].getInt()) {
2903       Diag(Loc, diag::err_omp_required_clause)
2904           << getOpenMPDirectiveName(OMPD_tile) << "sizes";
2905     }
2906 
2907     StmtResult AssociatedStmt;
2908     if (HasAssociatedStatement) {
2909       // The body is a block scope like in Lambdas and Blocks.
2910       Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
2911       // FIXME: We create a bogus CompoundStmt scope to hold the contents of
2912       // the captured region. Code elsewhere assumes that any FunctionScopeInfo
2913       // should have at least one compound statement scope within it.
2914       ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
2915       {
2916         Sema::CompoundScopeRAII Scope(Actions);
2917         AssociatedStmt = ParseStatement();
2918 
2919         if (AssociatedStmt.isUsable() && isOpenMPLoopDirective(DKind) &&
2920             getLangOpts().OpenMPIRBuilder)
2921           AssociatedStmt = Actions.ActOnOpenMPLoopnest(AssociatedStmt.get());
2922       }
2923       AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
2924     } else if (DKind == OMPD_target_update || DKind == OMPD_target_enter_data ||
2925                DKind == OMPD_target_exit_data) {
2926       Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
2927       AssociatedStmt = (Sema::CompoundScopeRAII(Actions),
2928                         Actions.ActOnCompoundStmt(Loc, Loc, llvm::None,
2929                                                   /*isStmtExpr=*/false));
2930       AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
2931     }
2932     Directive = Actions.ActOnOpenMPExecutableDirective(
2933         DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc,
2934         EndLoc);
2935 
2936     // Exit scope.
2937     Actions.EndOpenMPDSABlock(Directive.get());
2938     OMPDirectiveScope.Exit();
2939     break;
2940   }
2941   case OMPD_declare_simd:
2942   case OMPD_declare_target:
2943   case OMPD_begin_declare_target:
2944   case OMPD_end_declare_target:
2945   case OMPD_requires:
2946   case OMPD_begin_declare_variant:
2947   case OMPD_end_declare_variant:
2948   case OMPD_declare_variant:
2949     Diag(Tok, diag::err_omp_unexpected_directive)
2950         << 1 << getOpenMPDirectiveName(DKind);
2951     SkipUntil(tok::annot_pragma_openmp_end);
2952     break;
2953   case OMPD_unknown:
2954   default:
2955     Diag(Tok, diag::err_omp_unknown_directive);
2956     SkipUntil(tok::annot_pragma_openmp_end);
2957     break;
2958   }
2959   return Directive;
2960 }
2961 
2962 // Parses simple list:
2963 //   simple-variable-list:
2964 //         '(' id-expression {, id-expression} ')'
2965 //
2966 bool Parser::ParseOpenMPSimpleVarList(
2967     OpenMPDirectiveKind Kind,
2968     const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)>
2969         &Callback,
2970     bool AllowScopeSpecifier) {
2971   // Parse '('.
2972   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
2973   if (T.expectAndConsume(diag::err_expected_lparen_after,
2974                          getOpenMPDirectiveName(Kind).data()))
2975     return true;
2976   bool IsCorrect = true;
2977   bool NoIdentIsFound = true;
2978 
2979   // Read tokens while ')' or annot_pragma_openmp_end is not found.
2980   while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
2981     CXXScopeSpec SS;
2982     UnqualifiedId Name;
2983     // Read var name.
2984     Token PrevTok = Tok;
2985     NoIdentIsFound = false;
2986 
2987     if (AllowScopeSpecifier && getLangOpts().CPlusPlus &&
2988         ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2989                                        /*ObjectHasErrors=*/false, false)) {
2990       IsCorrect = false;
2991       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
2992                 StopBeforeMatch);
2993     } else if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
2994                                   /*ObjectHadErrors=*/false, false, false,
2995                                   false, false, nullptr, Name)) {
2996       IsCorrect = false;
2997       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
2998                 StopBeforeMatch);
2999     } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) &&
3000                Tok.isNot(tok::annot_pragma_openmp_end)) {
3001       IsCorrect = false;
3002       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3003                 StopBeforeMatch);
3004       Diag(PrevTok.getLocation(), diag::err_expected)
3005           << tok::identifier
3006           << SourceRange(PrevTok.getLocation(), PrevTokLocation);
3007     } else {
3008       Callback(SS, Actions.GetNameFromUnqualifiedId(Name));
3009     }
3010     // Consume ','.
3011     if (Tok.is(tok::comma)) {
3012       ConsumeToken();
3013     }
3014   }
3015 
3016   if (NoIdentIsFound) {
3017     Diag(Tok, diag::err_expected) << tok::identifier;
3018     IsCorrect = false;
3019   }
3020 
3021   // Parse ')'.
3022   IsCorrect = !T.consumeClose() && IsCorrect;
3023 
3024   return !IsCorrect;
3025 }
3026 
3027 OMPClause *Parser::ParseOpenMPSizesClause() {
3028   SourceLocation ClauseNameLoc = ConsumeToken();
3029   SmallVector<Expr *, 4> ValExprs;
3030 
3031   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3032   if (T.consumeOpen()) {
3033     Diag(Tok, diag::err_expected) << tok::l_paren;
3034     return nullptr;
3035   }
3036 
3037   while (true) {
3038     ExprResult Val = ParseConstantExpression();
3039     if (!Val.isUsable()) {
3040       T.skipToEnd();
3041       return nullptr;
3042     }
3043 
3044     ValExprs.push_back(Val.get());
3045 
3046     if (Tok.is(tok::r_paren) || Tok.is(tok::annot_pragma_openmp_end))
3047       break;
3048 
3049     ExpectAndConsume(tok::comma);
3050   }
3051 
3052   T.consumeClose();
3053 
3054   return Actions.ActOnOpenMPSizesClause(
3055       ValExprs, ClauseNameLoc, T.getOpenLocation(), T.getCloseLocation());
3056 }
3057 
3058 OMPClause *Parser::ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind) {
3059   SourceLocation Loc = Tok.getLocation();
3060   ConsumeAnyToken();
3061 
3062   // Parse '('.
3063   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3064   if (T.expectAndConsume(diag::err_expected_lparen_after, "uses_allocator"))
3065     return nullptr;
3066   SmallVector<Sema::UsesAllocatorsData, 4> Data;
3067   do {
3068     ExprResult Allocator =
3069         getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression();
3070     if (Allocator.isInvalid()) {
3071       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3072                 StopBeforeMatch);
3073       break;
3074     }
3075     Sema::UsesAllocatorsData &D = Data.emplace_back();
3076     D.Allocator = Allocator.get();
3077     if (Tok.is(tok::l_paren)) {
3078       BalancedDelimiterTracker T(*this, tok::l_paren,
3079                                  tok::annot_pragma_openmp_end);
3080       T.consumeOpen();
3081       ExprResult AllocatorTraits =
3082           getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression();
3083       T.consumeClose();
3084       if (AllocatorTraits.isInvalid()) {
3085         SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3086                   StopBeforeMatch);
3087         break;
3088       }
3089       D.AllocatorTraits = AllocatorTraits.get();
3090       D.LParenLoc = T.getOpenLocation();
3091       D.RParenLoc = T.getCloseLocation();
3092     }
3093     if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren))
3094       Diag(Tok, diag::err_omp_expected_punc) << "uses_allocators" << 0;
3095     // Parse ','
3096     if (Tok.is(tok::comma))
3097       ConsumeAnyToken();
3098   } while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end));
3099   T.consumeClose();
3100   return Actions.ActOnOpenMPUsesAllocatorClause(Loc, T.getOpenLocation(),
3101                                                 T.getCloseLocation(), Data);
3102 }
3103 
3104 /// Parsing of OpenMP clauses.
3105 ///
3106 ///    clause:
3107 ///       if-clause | final-clause | num_threads-clause | safelen-clause |
3108 ///       default-clause | private-clause | firstprivate-clause | shared-clause
3109 ///       | linear-clause | aligned-clause | collapse-clause | bind-clause |
3110 ///       lastprivate-clause | reduction-clause | proc_bind-clause |
3111 ///       schedule-clause | copyin-clause | copyprivate-clause | untied-clause |
3112 ///       mergeable-clause | flush-clause | read-clause | write-clause |
3113 ///       update-clause | capture-clause | seq_cst-clause | device-clause |
3114 ///       simdlen-clause | threads-clause | simd-clause | num_teams-clause |
3115 ///       thread_limit-clause | priority-clause | grainsize-clause |
3116 ///       nogroup-clause | num_tasks-clause | hint-clause | to-clause |
3117 ///       from-clause | is_device_ptr-clause | task_reduction-clause |
3118 ///       in_reduction-clause | allocator-clause | allocate-clause |
3119 ///       acq_rel-clause | acquire-clause | release-clause | relaxed-clause |
3120 ///       depobj-clause | destroy-clause | detach-clause | inclusive-clause |
3121 ///       exclusive-clause | uses_allocators-clause | use_device_addr-clause |
3122 ///       has_device_addr
3123 ///
3124 OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind,
3125                                      OpenMPClauseKind CKind, bool FirstClause) {
3126   OMPClauseKind = CKind;
3127   OMPClause *Clause = nullptr;
3128   bool ErrorFound = false;
3129   bool WrongDirective = false;
3130   // Check if clause is allowed for the given directive.
3131   if (CKind != OMPC_unknown &&
3132       !isAllowedClauseForDirective(DKind, CKind, getLangOpts().OpenMP)) {
3133     Diag(Tok, diag::err_omp_unexpected_clause)
3134         << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind);
3135     ErrorFound = true;
3136     WrongDirective = true;
3137   }
3138 
3139   switch (CKind) {
3140   case OMPC_final:
3141   case OMPC_num_threads:
3142   case OMPC_safelen:
3143   case OMPC_simdlen:
3144   case OMPC_collapse:
3145   case OMPC_ordered:
3146   case OMPC_num_teams:
3147   case OMPC_thread_limit:
3148   case OMPC_priority:
3149   case OMPC_grainsize:
3150   case OMPC_num_tasks:
3151   case OMPC_hint:
3152   case OMPC_allocator:
3153   case OMPC_depobj:
3154   case OMPC_detach:
3155   case OMPC_novariants:
3156   case OMPC_nocontext:
3157   case OMPC_filter:
3158   case OMPC_partial:
3159   case OMPC_align:
3160     // OpenMP [2.5, Restrictions]
3161     //  At most one num_threads clause can appear on the directive.
3162     // OpenMP [2.8.1, simd construct, Restrictions]
3163     //  Only one safelen  clause can appear on a simd directive.
3164     //  Only one simdlen  clause can appear on a simd directive.
3165     //  Only one collapse clause can appear on a simd directive.
3166     // OpenMP [2.11.1, task Construct, Restrictions]
3167     //  At most one if clause can appear on the directive.
3168     //  At most one final clause can appear on the directive.
3169     // OpenMP [teams Construct, Restrictions]
3170     //  At most one num_teams clause can appear on the directive.
3171     //  At most one thread_limit clause can appear on the directive.
3172     // OpenMP [2.9.1, task Construct, Restrictions]
3173     // At most one priority clause can appear on the directive.
3174     // OpenMP [2.9.2, taskloop Construct, Restrictions]
3175     // At most one grainsize clause can appear on the directive.
3176     // OpenMP [2.9.2, taskloop Construct, Restrictions]
3177     // At most one num_tasks clause can appear on the directive.
3178     // OpenMP [2.11.3, allocate Directive, Restrictions]
3179     // At most one allocator clause can appear on the directive.
3180     // OpenMP 5.0, 2.10.1 task Construct, Restrictions.
3181     // At most one detach clause can appear on the directive.
3182     // OpenMP 5.1, 2.3.6 dispatch Construct, Restrictions.
3183     // At most one novariants clause can appear on a dispatch directive.
3184     // At most one nocontext clause can appear on a dispatch directive.
3185     if (!FirstClause) {
3186       Diag(Tok, diag::err_omp_more_one_clause)
3187           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3188       ErrorFound = true;
3189     }
3190 
3191     if ((CKind == OMPC_ordered || CKind == OMPC_partial) &&
3192         PP.LookAhead(/*N=*/0).isNot(tok::l_paren))
3193       Clause = ParseOpenMPClause(CKind, WrongDirective);
3194     else
3195       Clause = ParseOpenMPSingleExprClause(CKind, WrongDirective);
3196     break;
3197   case OMPC_default:
3198   case OMPC_proc_bind:
3199   case OMPC_atomic_default_mem_order:
3200   case OMPC_order:
3201   case OMPC_bind:
3202     // OpenMP [2.14.3.1, Restrictions]
3203     //  Only a single default clause may be specified on a parallel, task or
3204     //  teams directive.
3205     // OpenMP [2.5, parallel Construct, Restrictions]
3206     //  At most one proc_bind clause can appear on the directive.
3207     // OpenMP [5.0, Requires directive, Restrictions]
3208     //  At most one atomic_default_mem_order clause can appear
3209     //  on the directive
3210     // OpenMP 5.1, 2.11.7 loop Construct, Restrictions.
3211     // At most one bind clause can appear on a loop directive.
3212     if (!FirstClause && CKind != OMPC_order) {
3213       Diag(Tok, diag::err_omp_more_one_clause)
3214           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3215       ErrorFound = true;
3216     }
3217 
3218     Clause = ParseOpenMPSimpleClause(CKind, WrongDirective);
3219     break;
3220   case OMPC_device:
3221   case OMPC_schedule:
3222   case OMPC_dist_schedule:
3223   case OMPC_defaultmap:
3224     // OpenMP [2.7.1, Restrictions, p. 3]
3225     //  Only one schedule clause can appear on a loop directive.
3226     // OpenMP 4.5 [2.10.4, Restrictions, p. 106]
3227     //  At most one defaultmap clause can appear on the directive.
3228     // OpenMP 5.0 [2.12.5, target construct, Restrictions]
3229     //  At most one device clause can appear on the directive.
3230     if ((getLangOpts().OpenMP < 50 || CKind != OMPC_defaultmap) &&
3231         !FirstClause) {
3232       Diag(Tok, diag::err_omp_more_one_clause)
3233           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3234       ErrorFound = true;
3235     }
3236     LLVM_FALLTHROUGH;
3237   case OMPC_if:
3238     Clause = ParseOpenMPSingleExprWithArgClause(DKind, CKind, WrongDirective);
3239     break;
3240   case OMPC_nowait:
3241   case OMPC_untied:
3242   case OMPC_mergeable:
3243   case OMPC_read:
3244   case OMPC_write:
3245   case OMPC_capture:
3246   case OMPC_compare:
3247   case OMPC_seq_cst:
3248   case OMPC_acq_rel:
3249   case OMPC_acquire:
3250   case OMPC_release:
3251   case OMPC_relaxed:
3252   case OMPC_threads:
3253   case OMPC_simd:
3254   case OMPC_nogroup:
3255   case OMPC_unified_address:
3256   case OMPC_unified_shared_memory:
3257   case OMPC_reverse_offload:
3258   case OMPC_dynamic_allocators:
3259   case OMPC_full:
3260     // OpenMP [2.7.1, Restrictions, p. 9]
3261     //  Only one ordered clause can appear on a loop directive.
3262     // OpenMP [2.7.1, Restrictions, C/C++, p. 4]
3263     //  Only one nowait clause can appear on a for directive.
3264     // OpenMP [5.0, Requires directive, Restrictions]
3265     //   Each of the requires clauses can appear at most once on the directive.
3266     if (!FirstClause) {
3267       Diag(Tok, diag::err_omp_more_one_clause)
3268           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3269       ErrorFound = true;
3270     }
3271 
3272     Clause = ParseOpenMPClause(CKind, WrongDirective);
3273     break;
3274   case OMPC_update:
3275     if (!FirstClause) {
3276       Diag(Tok, diag::err_omp_more_one_clause)
3277           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3278       ErrorFound = true;
3279     }
3280 
3281     Clause = (DKind == OMPD_depobj)
3282                  ? ParseOpenMPSimpleClause(CKind, WrongDirective)
3283                  : ParseOpenMPClause(CKind, WrongDirective);
3284     break;
3285   case OMPC_private:
3286   case OMPC_firstprivate:
3287   case OMPC_lastprivate:
3288   case OMPC_shared:
3289   case OMPC_reduction:
3290   case OMPC_task_reduction:
3291   case OMPC_in_reduction:
3292   case OMPC_linear:
3293   case OMPC_aligned:
3294   case OMPC_copyin:
3295   case OMPC_copyprivate:
3296   case OMPC_flush:
3297   case OMPC_depend:
3298   case OMPC_map:
3299   case OMPC_to:
3300   case OMPC_from:
3301   case OMPC_use_device_ptr:
3302   case OMPC_use_device_addr:
3303   case OMPC_is_device_ptr:
3304   case OMPC_has_device_addr:
3305   case OMPC_allocate:
3306   case OMPC_nontemporal:
3307   case OMPC_inclusive:
3308   case OMPC_exclusive:
3309   case OMPC_affinity:
3310     Clause = ParseOpenMPVarListClause(DKind, CKind, WrongDirective);
3311     break;
3312   case OMPC_sizes:
3313     if (!FirstClause) {
3314       Diag(Tok, diag::err_omp_more_one_clause)
3315           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3316       ErrorFound = true;
3317     }
3318 
3319     Clause = ParseOpenMPSizesClause();
3320     break;
3321   case OMPC_uses_allocators:
3322     Clause = ParseOpenMPUsesAllocatorClause(DKind);
3323     break;
3324   case OMPC_destroy:
3325     if (DKind != OMPD_interop) {
3326       if (!FirstClause) {
3327         Diag(Tok, diag::err_omp_more_one_clause)
3328             << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3329         ErrorFound = true;
3330       }
3331       Clause = ParseOpenMPClause(CKind, WrongDirective);
3332       break;
3333     }
3334     LLVM_FALLTHROUGH;
3335   case OMPC_init:
3336   case OMPC_use:
3337     Clause = ParseOpenMPInteropClause(CKind, WrongDirective);
3338     break;
3339   case OMPC_device_type:
3340   case OMPC_unknown:
3341     skipUntilPragmaOpenMPEnd(DKind);
3342     break;
3343   case OMPC_threadprivate:
3344   case OMPC_uniform:
3345   case OMPC_match:
3346     if (!WrongDirective)
3347       Diag(Tok, diag::err_omp_unexpected_clause)
3348           << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind);
3349     SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch);
3350     break;
3351   default:
3352     break;
3353   }
3354   return ErrorFound ? nullptr : Clause;
3355 }
3356 
3357 /// Parses simple expression in parens for single-expression clauses of OpenMP
3358 /// constructs.
3359 /// \param RLoc Returned location of right paren.
3360 ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName,
3361                                          SourceLocation &RLoc,
3362                                          bool IsAddressOfOperand) {
3363   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3364   if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data()))
3365     return ExprError();
3366 
3367   SourceLocation ELoc = Tok.getLocation();
3368   ExprResult LHS(
3369       ParseCastExpression(AnyCastExpr, IsAddressOfOperand, NotTypeCast));
3370   ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
3371   Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
3372 
3373   // Parse ')'.
3374   RLoc = Tok.getLocation();
3375   if (!T.consumeClose())
3376     RLoc = T.getCloseLocation();
3377 
3378   return Val;
3379 }
3380 
3381 /// Parsing of OpenMP clauses with single expressions like 'final',
3382 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
3383 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks', 'hint' or
3384 /// 'detach'.
3385 ///
3386 ///    final-clause:
3387 ///      'final' '(' expression ')'
3388 ///
3389 ///    num_threads-clause:
3390 ///      'num_threads' '(' expression ')'
3391 ///
3392 ///    safelen-clause:
3393 ///      'safelen' '(' expression ')'
3394 ///
3395 ///    simdlen-clause:
3396 ///      'simdlen' '(' expression ')'
3397 ///
3398 ///    collapse-clause:
3399 ///      'collapse' '(' expression ')'
3400 ///
3401 ///    priority-clause:
3402 ///      'priority' '(' expression ')'
3403 ///
3404 ///    grainsize-clause:
3405 ///      'grainsize' '(' expression ')'
3406 ///
3407 ///    num_tasks-clause:
3408 ///      'num_tasks' '(' expression ')'
3409 ///
3410 ///    hint-clause:
3411 ///      'hint' '(' expression ')'
3412 ///
3413 ///    allocator-clause:
3414 ///      'allocator' '(' expression ')'
3415 ///
3416 ///    detach-clause:
3417 ///      'detach' '(' event-handler-expression ')'
3418 ///
3419 ///    align-clause
3420 ///      'align' '(' positive-integer-constant ')'
3421 ///
3422 OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
3423                                                bool ParseOnly) {
3424   SourceLocation Loc = ConsumeToken();
3425   SourceLocation LLoc = Tok.getLocation();
3426   SourceLocation RLoc;
3427 
3428   ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
3429 
3430   if (Val.isInvalid())
3431     return nullptr;
3432 
3433   if (ParseOnly)
3434     return nullptr;
3435   return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc);
3436 }
3437 
3438 /// Parse indirect clause for '#pragma omp declare target' directive.
3439 ///  'indirect' '[' '(' invoked-by-fptr ')' ']'
3440 /// where invoked-by-fptr is a constant boolean expression that evaluates to
3441 /// true or false at compile time.
3442 bool Parser::ParseOpenMPIndirectClause(Sema::DeclareTargetContextInfo &DTCI,
3443                                        bool ParseOnly) {
3444   SourceLocation Loc = ConsumeToken();
3445   SourceLocation RLoc;
3446 
3447   if (Tok.isNot(tok::l_paren)) {
3448     if (ParseOnly)
3449       return false;
3450     DTCI.Indirect = nullptr;
3451     return true;
3452   }
3453 
3454   ExprResult Val =
3455       ParseOpenMPParensExpr(getOpenMPClauseName(OMPC_indirect), RLoc);
3456   if (Val.isInvalid())
3457     return false;
3458 
3459   if (ParseOnly)
3460     return false;
3461 
3462   if (!Val.get()->isValueDependent() && !Val.get()->isTypeDependent() &&
3463       !Val.get()->isInstantiationDependent() &&
3464       !Val.get()->containsUnexpandedParameterPack()) {
3465     ExprResult Ret = Actions.CheckBooleanCondition(Loc, Val.get());
3466     if (Ret.isInvalid())
3467       return false;
3468     llvm::APSInt Result;
3469     Ret = Actions.VerifyIntegerConstantExpression(Val.get(), &Result,
3470                                                   Sema::AllowFold);
3471     if (Ret.isInvalid())
3472       return false;
3473     DTCI.Indirect = Val.get();
3474     return true;
3475   }
3476   return false;
3477 }
3478 
3479 /// Parsing of OpenMP clauses that use an interop-var.
3480 ///
3481 /// init-clause:
3482 ///   init([interop-modifier, ]interop-type[[, interop-type] ... ]:interop-var)
3483 ///
3484 /// destroy-clause:
3485 ///   destroy(interop-var)
3486 ///
3487 /// use-clause:
3488 ///   use(interop-var)
3489 ///
3490 /// interop-modifier:
3491 ///   prefer_type(preference-list)
3492 ///
3493 /// preference-list:
3494 ///   foreign-runtime-id [, foreign-runtime-id]...
3495 ///
3496 /// foreign-runtime-id:
3497 ///   <string-literal> | <constant-integral-expression>
3498 ///
3499 /// interop-type:
3500 ///   target | targetsync
3501 ///
3502 OMPClause *Parser::ParseOpenMPInteropClause(OpenMPClauseKind Kind,
3503                                             bool ParseOnly) {
3504   SourceLocation Loc = ConsumeToken();
3505   // Parse '('.
3506   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3507   if (T.expectAndConsume(diag::err_expected_lparen_after,
3508                          getOpenMPClauseName(Kind).data()))
3509     return nullptr;
3510 
3511   bool IsTarget = false;
3512   bool IsTargetSync = false;
3513   SmallVector<Expr *, 4> Prefs;
3514 
3515   if (Kind == OMPC_init) {
3516 
3517     // Parse optional interop-modifier.
3518     if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "prefer_type") {
3519       ConsumeToken();
3520       BalancedDelimiterTracker PT(*this, tok::l_paren,
3521                                   tok::annot_pragma_openmp_end);
3522       if (PT.expectAndConsume(diag::err_expected_lparen_after, "prefer_type"))
3523         return nullptr;
3524 
3525       while (Tok.isNot(tok::r_paren)) {
3526         SourceLocation Loc = Tok.getLocation();
3527         ExprResult LHS = ParseCastExpression(AnyCastExpr);
3528         ExprResult PTExpr = Actions.CorrectDelayedTyposInExpr(
3529             ParseRHSOfBinaryExpression(LHS, prec::Conditional));
3530         PTExpr = Actions.ActOnFinishFullExpr(PTExpr.get(), Loc,
3531                                              /*DiscardedValue=*/false);
3532         if (PTExpr.isUsable())
3533           Prefs.push_back(PTExpr.get());
3534         else
3535           SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3536                     StopBeforeMatch);
3537 
3538         if (Tok.is(tok::comma))
3539           ConsumeToken();
3540       }
3541       PT.consumeClose();
3542     }
3543 
3544     if (!Prefs.empty()) {
3545       if (Tok.is(tok::comma))
3546         ConsumeToken();
3547       else
3548         Diag(Tok, diag::err_omp_expected_punc_after_interop_mod);
3549     }
3550 
3551     // Parse the interop-types.
3552     if (Optional<OMPDeclareVariantAttr::InteropType> IType =
3553             parseInteropTypeList(*this)) {
3554       IsTarget = IType != OMPDeclareVariantAttr::TargetSync;
3555       IsTargetSync = IType != OMPDeclareVariantAttr::Target;
3556       if (Tok.isNot(tok::colon))
3557         Diag(Tok, diag::warn_pragma_expected_colon) << "interop types";
3558     }
3559     if (Tok.is(tok::colon))
3560       ConsumeToken();
3561   }
3562 
3563   // Parse the variable.
3564   SourceLocation VarLoc = Tok.getLocation();
3565   ExprResult InteropVarExpr =
3566       Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3567   if (!InteropVarExpr.isUsable()) {
3568     SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3569               StopBeforeMatch);
3570   }
3571 
3572   // Parse ')'.
3573   SourceLocation RLoc = Tok.getLocation();
3574   if (!T.consumeClose())
3575     RLoc = T.getCloseLocation();
3576 
3577   if (ParseOnly || !InteropVarExpr.isUsable() ||
3578       (Kind == OMPC_init && !IsTarget && !IsTargetSync))
3579     return nullptr;
3580 
3581   if (Kind == OMPC_init)
3582     return Actions.ActOnOpenMPInitClause(InteropVarExpr.get(), Prefs, IsTarget,
3583                                          IsTargetSync, Loc, T.getOpenLocation(),
3584                                          VarLoc, RLoc);
3585   if (Kind == OMPC_use)
3586     return Actions.ActOnOpenMPUseClause(InteropVarExpr.get(), Loc,
3587                                         T.getOpenLocation(), VarLoc, RLoc);
3588 
3589   if (Kind == OMPC_destroy)
3590     return Actions.ActOnOpenMPDestroyClause(InteropVarExpr.get(), Loc,
3591                                             T.getOpenLocation(), VarLoc, RLoc);
3592 
3593   llvm_unreachable("Unexpected interop variable clause.");
3594 }
3595 
3596 /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
3597 ///
3598 ///    default-clause:
3599 ///         'default' '(' 'none' | 'shared' | 'private' | 'firstprivate' ')'
3600 ///
3601 ///    proc_bind-clause:
3602 ///         'proc_bind' '(' 'master' | 'close' | 'spread' ')'
3603 ///
3604 ///    bind-clause:
3605 ///         'bind' '(' 'teams' | 'parallel' | 'thread' ')'
3606 ///
3607 ///    update-clause:
3608 ///         'update' '(' 'in' | 'out' | 'inout' | 'mutexinoutset' |
3609 ///         'inoutset' ')'
3610 ///
3611 OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind,
3612                                            bool ParseOnly) {
3613   llvm::Optional<SimpleClauseData> Val = parseOpenMPSimpleClause(*this, Kind);
3614   if (!Val || ParseOnly)
3615     return nullptr;
3616   if (getLangOpts().OpenMP < 51 && Kind == OMPC_default &&
3617       (static_cast<DefaultKind>(Val.getValue().Type) == OMP_DEFAULT_private ||
3618        static_cast<DefaultKind>(Val.getValue().Type) ==
3619            OMP_DEFAULT_firstprivate)) {
3620     Diag(Val.getValue().LOpen, diag::err_omp_invalid_dsa)
3621         << getOpenMPClauseName(static_cast<DefaultKind>(Val.getValue().Type) ==
3622                                        OMP_DEFAULT_private
3623                                    ? OMPC_private
3624                                    : OMPC_firstprivate)
3625         << getOpenMPClauseName(OMPC_default) << "5.1";
3626     return nullptr;
3627   }
3628   return Actions.ActOnOpenMPSimpleClause(
3629       Kind, Val.getValue().Type, Val.getValue().TypeLoc, Val.getValue().LOpen,
3630       Val.getValue().Loc, Val.getValue().RLoc);
3631 }
3632 
3633 /// Parsing of OpenMP clauses like 'ordered'.
3634 ///
3635 ///    ordered-clause:
3636 ///         'ordered'
3637 ///
3638 ///    nowait-clause:
3639 ///         'nowait'
3640 ///
3641 ///    untied-clause:
3642 ///         'untied'
3643 ///
3644 ///    mergeable-clause:
3645 ///         'mergeable'
3646 ///
3647 ///    read-clause:
3648 ///         'read'
3649 ///
3650 ///    threads-clause:
3651 ///         'threads'
3652 ///
3653 ///    simd-clause:
3654 ///         'simd'
3655 ///
3656 ///    nogroup-clause:
3657 ///         'nogroup'
3658 ///
3659 OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly) {
3660   SourceLocation Loc = Tok.getLocation();
3661   ConsumeAnyToken();
3662 
3663   if (ParseOnly)
3664     return nullptr;
3665   return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation());
3666 }
3667 
3668 /// Parsing of OpenMP clauses with single expressions and some additional
3669 /// argument like 'schedule' or 'dist_schedule'.
3670 ///
3671 ///    schedule-clause:
3672 ///      'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
3673 ///      ')'
3674 ///
3675 ///    if-clause:
3676 ///      'if' '(' [ directive-name-modifier ':' ] expression ')'
3677 ///
3678 ///    defaultmap:
3679 ///      'defaultmap' '(' modifier [ ':' kind ] ')'
3680 ///
3681 ///    device-clause:
3682 ///      'device' '(' [ device-modifier ':' ] expression ')'
3683 ///
3684 OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
3685                                                       OpenMPClauseKind Kind,
3686                                                       bool ParseOnly) {
3687   SourceLocation Loc = ConsumeToken();
3688   SourceLocation DelimLoc;
3689   // Parse '('.
3690   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3691   if (T.expectAndConsume(diag::err_expected_lparen_after,
3692                          getOpenMPClauseName(Kind).data()))
3693     return nullptr;
3694 
3695   ExprResult Val;
3696   SmallVector<unsigned, 4> Arg;
3697   SmallVector<SourceLocation, 4> KLoc;
3698   if (Kind == OMPC_schedule) {
3699     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
3700     Arg.resize(NumberOfElements);
3701     KLoc.resize(NumberOfElements);
3702     Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown;
3703     Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown;
3704     Arg[ScheduleKind] = OMPC_SCHEDULE_unknown;
3705     unsigned KindModifier = getOpenMPSimpleClauseType(
3706         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3707     if (KindModifier > OMPC_SCHEDULE_unknown) {
3708       // Parse 'modifier'
3709       Arg[Modifier1] = KindModifier;
3710       KLoc[Modifier1] = Tok.getLocation();
3711       if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3712           Tok.isNot(tok::annot_pragma_openmp_end))
3713         ConsumeAnyToken();
3714       if (Tok.is(tok::comma)) {
3715         // Parse ',' 'modifier'
3716         ConsumeAnyToken();
3717         KindModifier = getOpenMPSimpleClauseType(
3718             Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3719         Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown
3720                              ? KindModifier
3721                              : (unsigned)OMPC_SCHEDULE_unknown;
3722         KLoc[Modifier2] = Tok.getLocation();
3723         if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3724             Tok.isNot(tok::annot_pragma_openmp_end))
3725           ConsumeAnyToken();
3726       }
3727       // Parse ':'
3728       if (Tok.is(tok::colon))
3729         ConsumeAnyToken();
3730       else
3731         Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier";
3732       KindModifier = getOpenMPSimpleClauseType(
3733           Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3734     }
3735     Arg[ScheduleKind] = KindModifier;
3736     KLoc[ScheduleKind] = Tok.getLocation();
3737     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3738         Tok.isNot(tok::annot_pragma_openmp_end))
3739       ConsumeAnyToken();
3740     if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static ||
3741          Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic ||
3742          Arg[ScheduleKind] == OMPC_SCHEDULE_guided) &&
3743         Tok.is(tok::comma))
3744       DelimLoc = ConsumeAnyToken();
3745   } else if (Kind == OMPC_dist_schedule) {
3746     Arg.push_back(getOpenMPSimpleClauseType(
3747         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
3748     KLoc.push_back(Tok.getLocation());
3749     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3750         Tok.isNot(tok::annot_pragma_openmp_end))
3751       ConsumeAnyToken();
3752     if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma))
3753       DelimLoc = ConsumeAnyToken();
3754   } else if (Kind == OMPC_defaultmap) {
3755     // Get a defaultmap modifier
3756     unsigned Modifier = getOpenMPSimpleClauseType(
3757         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3758     // Set defaultmap modifier to unknown if it is either scalar, aggregate, or
3759     // pointer
3760     if (Modifier < OMPC_DEFAULTMAP_MODIFIER_unknown)
3761       Modifier = OMPC_DEFAULTMAP_MODIFIER_unknown;
3762     Arg.push_back(Modifier);
3763     KLoc.push_back(Tok.getLocation());
3764     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3765         Tok.isNot(tok::annot_pragma_openmp_end))
3766       ConsumeAnyToken();
3767     // Parse ':'
3768     if (Tok.is(tok::colon) || getLangOpts().OpenMP < 50) {
3769       if (Tok.is(tok::colon))
3770         ConsumeAnyToken();
3771       else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown)
3772         Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier";
3773       // Get a defaultmap kind
3774       Arg.push_back(getOpenMPSimpleClauseType(
3775           Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
3776       KLoc.push_back(Tok.getLocation());
3777       if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3778           Tok.isNot(tok::annot_pragma_openmp_end))
3779         ConsumeAnyToken();
3780     } else {
3781       Arg.push_back(OMPC_DEFAULTMAP_unknown);
3782       KLoc.push_back(SourceLocation());
3783     }
3784   } else if (Kind == OMPC_device) {
3785     // Only target executable directives support extended device construct.
3786     if (isOpenMPTargetExecutionDirective(DKind) && getLangOpts().OpenMP >= 50 &&
3787         NextToken().is(tok::colon)) {
3788       // Parse optional <device modifier> ':'
3789       Arg.push_back(getOpenMPSimpleClauseType(
3790           Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
3791       KLoc.push_back(Tok.getLocation());
3792       ConsumeAnyToken();
3793       // Parse ':'
3794       ConsumeAnyToken();
3795     } else {
3796       Arg.push_back(OMPC_DEVICE_unknown);
3797       KLoc.emplace_back();
3798     }
3799   } else {
3800     assert(Kind == OMPC_if);
3801     KLoc.push_back(Tok.getLocation());
3802     TentativeParsingAction TPA(*this);
3803     auto DK = parseOpenMPDirectiveKind(*this);
3804     Arg.push_back(DK);
3805     if (DK != OMPD_unknown) {
3806       ConsumeToken();
3807       if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) {
3808         TPA.Commit();
3809         DelimLoc = ConsumeToken();
3810       } else {
3811         TPA.Revert();
3812         Arg.back() = unsigned(OMPD_unknown);
3813       }
3814     } else {
3815       TPA.Revert();
3816     }
3817   }
3818 
3819   bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) ||
3820                           (Kind == OMPC_dist_schedule && DelimLoc.isValid()) ||
3821                           Kind == OMPC_if || Kind == OMPC_device;
3822   if (NeedAnExpression) {
3823     SourceLocation ELoc = Tok.getLocation();
3824     ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
3825     Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
3826     Val =
3827         Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
3828   }
3829 
3830   // Parse ')'.
3831   SourceLocation RLoc = Tok.getLocation();
3832   if (!T.consumeClose())
3833     RLoc = T.getCloseLocation();
3834 
3835   if (NeedAnExpression && Val.isInvalid())
3836     return nullptr;
3837 
3838   if (ParseOnly)
3839     return nullptr;
3840   return Actions.ActOnOpenMPSingleExprWithArgClause(
3841       Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc, RLoc);
3842 }
3843 
3844 static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec,
3845                              UnqualifiedId &ReductionId) {
3846   if (ReductionIdScopeSpec.isEmpty()) {
3847     auto OOK = OO_None;
3848     switch (P.getCurToken().getKind()) {
3849     case tok::plus:
3850       OOK = OO_Plus;
3851       break;
3852     case tok::minus:
3853       OOK = OO_Minus;
3854       break;
3855     case tok::star:
3856       OOK = OO_Star;
3857       break;
3858     case tok::amp:
3859       OOK = OO_Amp;
3860       break;
3861     case tok::pipe:
3862       OOK = OO_Pipe;
3863       break;
3864     case tok::caret:
3865       OOK = OO_Caret;
3866       break;
3867     case tok::ampamp:
3868       OOK = OO_AmpAmp;
3869       break;
3870     case tok::pipepipe:
3871       OOK = OO_PipePipe;
3872       break;
3873     default:
3874       break;
3875     }
3876     if (OOK != OO_None) {
3877       SourceLocation OpLoc = P.ConsumeToken();
3878       SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()};
3879       ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations);
3880       return false;
3881     }
3882   }
3883   return P.ParseUnqualifiedId(
3884       ReductionIdScopeSpec, /*ObjectType=*/nullptr,
3885       /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
3886       /*AllowDestructorName*/ false,
3887       /*AllowConstructorName*/ false,
3888       /*AllowDeductionGuide*/ false, nullptr, ReductionId);
3889 }
3890 
3891 /// Checks if the token is a valid map-type-modifier.
3892 /// FIXME: It will return an OpenMPMapClauseKind if that's what it parses.
3893 static OpenMPMapModifierKind isMapModifier(Parser &P) {
3894   Token Tok = P.getCurToken();
3895   if (!Tok.is(tok::identifier))
3896     return OMPC_MAP_MODIFIER_unknown;
3897 
3898   Preprocessor &PP = P.getPreprocessor();
3899   OpenMPMapModifierKind TypeModifier =
3900       static_cast<OpenMPMapModifierKind>(getOpenMPSimpleClauseType(
3901           OMPC_map, PP.getSpelling(Tok), P.getLangOpts()));
3902   return TypeModifier;
3903 }
3904 
3905 /// Parse the mapper modifier in map, to, and from clauses.
3906 bool Parser::parseMapperModifier(Sema::OpenMPVarListDataTy &Data) {
3907   // Parse '('.
3908   BalancedDelimiterTracker T(*this, tok::l_paren, tok::colon);
3909   if (T.expectAndConsume(diag::err_expected_lparen_after, "mapper")) {
3910     SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
3911               StopBeforeMatch);
3912     return true;
3913   }
3914   // Parse mapper-identifier
3915   if (getLangOpts().CPlusPlus)
3916     ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
3917                                    /*ObjectType=*/nullptr,
3918                                    /*ObjectHasErrors=*/false,
3919                                    /*EnteringContext=*/false);
3920   if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
3921     Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
3922     SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
3923               StopBeforeMatch);
3924     return true;
3925   }
3926   auto &DeclNames = Actions.getASTContext().DeclarationNames;
3927   Data.ReductionOrMapperId = DeclarationNameInfo(
3928       DeclNames.getIdentifier(Tok.getIdentifierInfo()), Tok.getLocation());
3929   ConsumeToken();
3930   // Parse ')'.
3931   return T.consumeClose();
3932 }
3933 
3934 /// Parse map-type-modifiers in map clause.
3935 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
3936 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) |
3937 /// present
3938 bool Parser::parseMapTypeModifiers(Sema::OpenMPVarListDataTy &Data) {
3939   while (getCurToken().isNot(tok::colon)) {
3940     OpenMPMapModifierKind TypeModifier = isMapModifier(*this);
3941     if (TypeModifier == OMPC_MAP_MODIFIER_always ||
3942         TypeModifier == OMPC_MAP_MODIFIER_close ||
3943         TypeModifier == OMPC_MAP_MODIFIER_present ||
3944         TypeModifier == OMPC_MAP_MODIFIER_ompx_hold) {
3945       Data.MapTypeModifiers.push_back(TypeModifier);
3946       Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
3947       ConsumeToken();
3948     } else if (TypeModifier == OMPC_MAP_MODIFIER_mapper) {
3949       Data.MapTypeModifiers.push_back(TypeModifier);
3950       Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
3951       ConsumeToken();
3952       if (parseMapperModifier(Data))
3953         return true;
3954     } else {
3955       // For the case of unknown map-type-modifier or a map-type.
3956       // Map-type is followed by a colon; the function returns when it
3957       // encounters a token followed by a colon.
3958       if (Tok.is(tok::comma)) {
3959         Diag(Tok, diag::err_omp_map_type_modifier_missing);
3960         ConsumeToken();
3961         continue;
3962       }
3963       // Potential map-type token as it is followed by a colon.
3964       if (PP.LookAhead(0).is(tok::colon))
3965         return false;
3966       Diag(Tok, diag::err_omp_unknown_map_type_modifier)
3967           << (getLangOpts().OpenMP >= 51 ? 1 : 0)
3968           << getLangOpts().OpenMPExtensions;
3969       ConsumeToken();
3970     }
3971     if (getCurToken().is(tok::comma))
3972       ConsumeToken();
3973   }
3974   return false;
3975 }
3976 
3977 /// Checks if the token is a valid map-type.
3978 /// FIXME: It will return an OpenMPMapModifierKind if that's what it parses.
3979 static OpenMPMapClauseKind isMapType(Parser &P) {
3980   Token Tok = P.getCurToken();
3981   // The map-type token can be either an identifier or the C++ delete keyword.
3982   if (!Tok.isOneOf(tok::identifier, tok::kw_delete))
3983     return OMPC_MAP_unknown;
3984   Preprocessor &PP = P.getPreprocessor();
3985   OpenMPMapClauseKind MapType =
3986       static_cast<OpenMPMapClauseKind>(getOpenMPSimpleClauseType(
3987           OMPC_map, PP.getSpelling(Tok), P.getLangOpts()));
3988   return MapType;
3989 }
3990 
3991 /// Parse map-type in map clause.
3992 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
3993 /// where, map-type ::= to | from | tofrom | alloc | release | delete
3994 static void parseMapType(Parser &P, Sema::OpenMPVarListDataTy &Data) {
3995   Token Tok = P.getCurToken();
3996   if (Tok.is(tok::colon)) {
3997     P.Diag(Tok, diag::err_omp_map_type_missing);
3998     return;
3999   }
4000   Data.ExtraModifier = isMapType(P);
4001   if (Data.ExtraModifier == OMPC_MAP_unknown)
4002     P.Diag(Tok, diag::err_omp_unknown_map_type);
4003   P.ConsumeToken();
4004 }
4005 
4006 /// Parses simple expression in parens for single-expression clauses of OpenMP
4007 /// constructs.
4008 ExprResult Parser::ParseOpenMPIteratorsExpr() {
4009   assert(Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator" &&
4010          "Expected 'iterator' token.");
4011   SourceLocation IteratorKwLoc = ConsumeToken();
4012 
4013   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
4014   if (T.expectAndConsume(diag::err_expected_lparen_after, "iterator"))
4015     return ExprError();
4016 
4017   SourceLocation LLoc = T.getOpenLocation();
4018   SmallVector<Sema::OMPIteratorData, 4> Data;
4019   while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
4020     // Check if the type parsing is required.
4021     ParsedType IteratorType;
4022     if (Tok.isNot(tok::identifier) || NextToken().isNot(tok::equal)) {
4023       // identifier '=' is not found - parse type.
4024       TypeResult TR = ParseTypeName();
4025       if (TR.isInvalid()) {
4026         T.skipToEnd();
4027         return ExprError();
4028       }
4029       IteratorType = TR.get();
4030     }
4031 
4032     // Parse identifier.
4033     IdentifierInfo *II = nullptr;
4034     SourceLocation IdLoc;
4035     if (Tok.is(tok::identifier)) {
4036       II = Tok.getIdentifierInfo();
4037       IdLoc = ConsumeToken();
4038     } else {
4039       Diag(Tok, diag::err_expected_unqualified_id) << 0;
4040     }
4041 
4042     // Parse '='.
4043     SourceLocation AssignLoc;
4044     if (Tok.is(tok::equal))
4045       AssignLoc = ConsumeToken();
4046     else
4047       Diag(Tok, diag::err_omp_expected_equal_in_iterator);
4048 
4049     // Parse range-specification - <begin> ':' <end> [ ':' <step> ]
4050     ColonProtectionRAIIObject ColonRAII(*this);
4051     // Parse <begin>
4052     SourceLocation Loc = Tok.getLocation();
4053     ExprResult LHS = ParseCastExpression(AnyCastExpr);
4054     ExprResult Begin = Actions.CorrectDelayedTyposInExpr(
4055         ParseRHSOfBinaryExpression(LHS, prec::Conditional));
4056     Begin = Actions.ActOnFinishFullExpr(Begin.get(), Loc,
4057                                         /*DiscardedValue=*/false);
4058     // Parse ':'.
4059     SourceLocation ColonLoc;
4060     if (Tok.is(tok::colon))
4061       ColonLoc = ConsumeToken();
4062 
4063     // Parse <end>
4064     Loc = Tok.getLocation();
4065     LHS = ParseCastExpression(AnyCastExpr);
4066     ExprResult End = Actions.CorrectDelayedTyposInExpr(
4067         ParseRHSOfBinaryExpression(LHS, prec::Conditional));
4068     End = Actions.ActOnFinishFullExpr(End.get(), Loc,
4069                                       /*DiscardedValue=*/false);
4070 
4071     SourceLocation SecColonLoc;
4072     ExprResult Step;
4073     // Parse optional step.
4074     if (Tok.is(tok::colon)) {
4075       // Parse ':'
4076       SecColonLoc = ConsumeToken();
4077       // Parse <step>
4078       Loc = Tok.getLocation();
4079       LHS = ParseCastExpression(AnyCastExpr);
4080       Step = Actions.CorrectDelayedTyposInExpr(
4081           ParseRHSOfBinaryExpression(LHS, prec::Conditional));
4082       Step = Actions.ActOnFinishFullExpr(Step.get(), Loc,
4083                                          /*DiscardedValue=*/false);
4084     }
4085 
4086     // Parse ',' or ')'
4087     if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren))
4088       Diag(Tok, diag::err_omp_expected_punc_after_iterator);
4089     if (Tok.is(tok::comma))
4090       ConsumeToken();
4091 
4092     Sema::OMPIteratorData &D = Data.emplace_back();
4093     D.DeclIdent = II;
4094     D.DeclIdentLoc = IdLoc;
4095     D.Type = IteratorType;
4096     D.AssignLoc = AssignLoc;
4097     D.ColonLoc = ColonLoc;
4098     D.SecColonLoc = SecColonLoc;
4099     D.Range.Begin = Begin.get();
4100     D.Range.End = End.get();
4101     D.Range.Step = Step.get();
4102   }
4103 
4104   // Parse ')'.
4105   SourceLocation RLoc = Tok.getLocation();
4106   if (!T.consumeClose())
4107     RLoc = T.getCloseLocation();
4108 
4109   return Actions.ActOnOMPIteratorExpr(getCurScope(), IteratorKwLoc, LLoc, RLoc,
4110                                       Data);
4111 }
4112 
4113 bool Parser::ParseOpenMPReservedLocator(OpenMPClauseKind Kind,
4114                                         Sema::OpenMPVarListDataTy &Data,
4115                                         const LangOptions &LangOpts) {
4116   // Currently the only reserved locator is 'omp_all_memory' which is only
4117   // allowed on a depend clause.
4118   if (Kind != OMPC_depend || LangOpts.OpenMP < 51)
4119     return false;
4120 
4121   if (Tok.is(tok::identifier) &&
4122       Tok.getIdentifierInfo()->isStr("omp_all_memory")) {
4123 
4124     if (Data.ExtraModifier == OMPC_DEPEND_outallmemory ||
4125         Data.ExtraModifier == OMPC_DEPEND_inoutallmemory)
4126       Diag(Tok, diag::warn_omp_more_one_omp_all_memory);
4127     else if (Data.ExtraModifier != OMPC_DEPEND_out &&
4128              Data.ExtraModifier != OMPC_DEPEND_inout)
4129       Diag(Tok, diag::err_omp_requires_out_inout_depend_type);
4130     else
4131       Data.ExtraModifier = Data.ExtraModifier == OMPC_DEPEND_out
4132                                ? OMPC_DEPEND_outallmemory
4133                                : OMPC_DEPEND_inoutallmemory;
4134     ConsumeToken();
4135     return true;
4136   }
4137   return false;
4138 }
4139 
4140 /// Parses clauses with list.
4141 bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind,
4142                                 OpenMPClauseKind Kind,
4143                                 SmallVectorImpl<Expr *> &Vars,
4144                                 Sema::OpenMPVarListDataTy &Data) {
4145   UnqualifiedId UnqualifiedReductionId;
4146   bool InvalidReductionId = false;
4147   bool IsInvalidMapperModifier = false;
4148 
4149   // Parse '('.
4150   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
4151   if (T.expectAndConsume(diag::err_expected_lparen_after,
4152                          getOpenMPClauseName(Kind).data()))
4153     return true;
4154 
4155   bool HasIterator = false;
4156   bool NeedRParenForLinear = false;
4157   BalancedDelimiterTracker LinearT(*this, tok::l_paren,
4158                                    tok::annot_pragma_openmp_end);
4159   // Handle reduction-identifier for reduction clause.
4160   if (Kind == OMPC_reduction || Kind == OMPC_task_reduction ||
4161       Kind == OMPC_in_reduction) {
4162     Data.ExtraModifier = OMPC_REDUCTION_unknown;
4163     if (Kind == OMPC_reduction && getLangOpts().OpenMP >= 50 &&
4164         (Tok.is(tok::identifier) || Tok.is(tok::kw_default)) &&
4165         NextToken().is(tok::comma)) {
4166       // Parse optional reduction modifier.
4167       Data.ExtraModifier =
4168           getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
4169       Data.ExtraModifierLoc = Tok.getLocation();
4170       ConsumeToken();
4171       assert(Tok.is(tok::comma) && "Expected comma.");
4172       (void)ConsumeToken();
4173     }
4174     ColonProtectionRAIIObject ColonRAII(*this);
4175     if (getLangOpts().CPlusPlus)
4176       ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
4177                                      /*ObjectType=*/nullptr,
4178                                      /*ObjectHasErrors=*/false,
4179                                      /*EnteringContext=*/false);
4180     InvalidReductionId = ParseReductionId(
4181         *this, Data.ReductionOrMapperIdScopeSpec, UnqualifiedReductionId);
4182     if (InvalidReductionId) {
4183       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4184                 StopBeforeMatch);
4185     }
4186     if (Tok.is(tok::colon))
4187       Data.ColonLoc = ConsumeToken();
4188     else
4189       Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier";
4190     if (!InvalidReductionId)
4191       Data.ReductionOrMapperId =
4192           Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId);
4193   } else if (Kind == OMPC_depend) {
4194     if (getLangOpts().OpenMP >= 50) {
4195       if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator") {
4196         // Handle optional dependence modifier.
4197         // iterator(iterators-definition)
4198         // where iterators-definition is iterator-specifier [,
4199         // iterators-definition ]
4200         // where iterator-specifier is [ iterator-type ] identifier =
4201         // range-specification
4202         HasIterator = true;
4203         EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope);
4204         ExprResult IteratorRes = ParseOpenMPIteratorsExpr();
4205         Data.DepModOrTailExpr = IteratorRes.get();
4206         // Parse ','
4207         ExpectAndConsume(tok::comma);
4208       }
4209     }
4210     // Handle dependency type for depend clause.
4211     ColonProtectionRAIIObject ColonRAII(*this);
4212     Data.ExtraModifier = getOpenMPSimpleClauseType(
4213         Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
4214         getLangOpts());
4215     Data.ExtraModifierLoc = Tok.getLocation();
4216     if (Data.ExtraModifier == OMPC_DEPEND_unknown) {
4217       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4218                 StopBeforeMatch);
4219     } else {
4220       ConsumeToken();
4221       // Special processing for depend(source) clause.
4222       if (DKind == OMPD_ordered && Data.ExtraModifier == OMPC_DEPEND_source) {
4223         // Parse ')'.
4224         T.consumeClose();
4225         return false;
4226       }
4227     }
4228     if (Tok.is(tok::colon)) {
4229       Data.ColonLoc = ConsumeToken();
4230     } else {
4231       Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren
4232                                       : diag::warn_pragma_expected_colon)
4233           << "dependency type";
4234     }
4235   } else if (Kind == OMPC_linear) {
4236     // Try to parse modifier if any.
4237     Data.ExtraModifier = OMPC_LINEAR_val;
4238     if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) {
4239       Data.ExtraModifier =
4240           getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
4241       Data.ExtraModifierLoc = ConsumeToken();
4242       LinearT.consumeOpen();
4243       NeedRParenForLinear = true;
4244     }
4245   } else if (Kind == OMPC_lastprivate) {
4246     // Try to parse modifier if any.
4247     Data.ExtraModifier = OMPC_LASTPRIVATE_unknown;
4248     // Conditional modifier allowed only in OpenMP 5.0 and not supported in
4249     // distribute and taskloop based directives.
4250     if ((getLangOpts().OpenMP >= 50 && !isOpenMPDistributeDirective(DKind) &&
4251          !isOpenMPTaskLoopDirective(DKind)) &&
4252         Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::colon)) {
4253       Data.ExtraModifier =
4254           getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
4255       Data.ExtraModifierLoc = Tok.getLocation();
4256       ConsumeToken();
4257       assert(Tok.is(tok::colon) && "Expected colon.");
4258       Data.ColonLoc = ConsumeToken();
4259     }
4260   } else if (Kind == OMPC_map) {
4261     // Handle map type for map clause.
4262     ColonProtectionRAIIObject ColonRAII(*this);
4263 
4264     // The first identifier may be a list item, a map-type or a
4265     // map-type-modifier. The map-type can also be delete which has the same
4266     // spelling of the C++ delete keyword.
4267     Data.ExtraModifier = OMPC_MAP_unknown;
4268     Data.ExtraModifierLoc = Tok.getLocation();
4269 
4270     // Check for presence of a colon in the map clause.
4271     TentativeParsingAction TPA(*this);
4272     bool ColonPresent = false;
4273     if (SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4274                   StopBeforeMatch)) {
4275       if (Tok.is(tok::colon))
4276         ColonPresent = true;
4277     }
4278     TPA.Revert();
4279     // Only parse map-type-modifier[s] and map-type if a colon is present in
4280     // the map clause.
4281     if (ColonPresent) {
4282       IsInvalidMapperModifier = parseMapTypeModifiers(Data);
4283       if (!IsInvalidMapperModifier)
4284         parseMapType(*this, Data);
4285       else
4286         SkipUntil(tok::colon, tok::annot_pragma_openmp_end, StopBeforeMatch);
4287     }
4288     if (Data.ExtraModifier == OMPC_MAP_unknown) {
4289       Data.ExtraModifier = OMPC_MAP_tofrom;
4290       Data.IsMapTypeImplicit = true;
4291     }
4292 
4293     if (Tok.is(tok::colon))
4294       Data.ColonLoc = ConsumeToken();
4295   } else if (Kind == OMPC_to || Kind == OMPC_from) {
4296     while (Tok.is(tok::identifier)) {
4297       auto Modifier = static_cast<OpenMPMotionModifierKind>(
4298           getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts()));
4299       if (Modifier == OMPC_MOTION_MODIFIER_unknown)
4300         break;
4301       Data.MotionModifiers.push_back(Modifier);
4302       Data.MotionModifiersLoc.push_back(Tok.getLocation());
4303       ConsumeToken();
4304       if (Modifier == OMPC_MOTION_MODIFIER_mapper) {
4305         IsInvalidMapperModifier = parseMapperModifier(Data);
4306         if (IsInvalidMapperModifier)
4307           break;
4308       }
4309       // OpenMP < 5.1 doesn't permit a ',' or additional modifiers.
4310       if (getLangOpts().OpenMP < 51)
4311         break;
4312       // OpenMP 5.1 accepts an optional ',' even if the next character is ':'.
4313       // TODO: Is that intentional?
4314       if (Tok.is(tok::comma))
4315         ConsumeToken();
4316     }
4317     if (!Data.MotionModifiers.empty() && Tok.isNot(tok::colon)) {
4318       if (!IsInvalidMapperModifier) {
4319         if (getLangOpts().OpenMP < 51)
4320           Diag(Tok, diag::warn_pragma_expected_colon) << ")";
4321         else
4322           Diag(Tok, diag::warn_pragma_expected_colon) << "motion modifier";
4323       }
4324       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4325                 StopBeforeMatch);
4326     }
4327     // OpenMP 5.1 permits a ':' even without a preceding modifier.  TODO: Is
4328     // that intentional?
4329     if ((!Data.MotionModifiers.empty() || getLangOpts().OpenMP >= 51) &&
4330         Tok.is(tok::colon))
4331       Data.ColonLoc = ConsumeToken();
4332   } else if (Kind == OMPC_allocate ||
4333              (Kind == OMPC_affinity && Tok.is(tok::identifier) &&
4334               PP.getSpelling(Tok) == "iterator")) {
4335     // Handle optional allocator expression followed by colon delimiter.
4336     ColonProtectionRAIIObject ColonRAII(*this);
4337     TentativeParsingAction TPA(*this);
4338     // OpenMP 5.0, 2.10.1, task Construct.
4339     // where aff-modifier is one of the following:
4340     // iterator(iterators-definition)
4341     ExprResult Tail;
4342     if (Kind == OMPC_allocate) {
4343       Tail = ParseAssignmentExpression();
4344     } else {
4345       HasIterator = true;
4346       EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope);
4347       Tail = ParseOpenMPIteratorsExpr();
4348     }
4349     Tail = Actions.CorrectDelayedTyposInExpr(Tail);
4350     Tail = Actions.ActOnFinishFullExpr(Tail.get(), T.getOpenLocation(),
4351                                        /*DiscardedValue=*/false);
4352     if (Tail.isUsable()) {
4353       if (Tok.is(tok::colon)) {
4354         Data.DepModOrTailExpr = Tail.get();
4355         Data.ColonLoc = ConsumeToken();
4356         TPA.Commit();
4357       } else {
4358         // Colon not found, parse only list of variables.
4359         TPA.Revert();
4360       }
4361     } else {
4362       // Parsing was unsuccessfull, revert and skip to the end of clause or
4363       // directive.
4364       TPA.Revert();
4365       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4366                 StopBeforeMatch);
4367     }
4368   } else if (Kind == OMPC_adjust_args) {
4369     // Handle adjust-op for adjust_args clause.
4370     ColonProtectionRAIIObject ColonRAII(*this);
4371     Data.ExtraModifier = getOpenMPSimpleClauseType(
4372         Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
4373         getLangOpts());
4374     Data.ExtraModifierLoc = Tok.getLocation();
4375     if (Data.ExtraModifier == OMPC_ADJUST_ARGS_unknown) {
4376       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4377                 StopBeforeMatch);
4378     } else {
4379       ConsumeToken();
4380       if (Tok.is(tok::colon))
4381         Data.ColonLoc = Tok.getLocation();
4382       ExpectAndConsume(tok::colon, diag::warn_pragma_expected_colon,
4383                        "adjust-op");
4384     }
4385   }
4386 
4387   bool IsComma =
4388       (Kind != OMPC_reduction && Kind != OMPC_task_reduction &&
4389        Kind != OMPC_in_reduction && Kind != OMPC_depend && Kind != OMPC_map) ||
4390       (Kind == OMPC_reduction && !InvalidReductionId) ||
4391       (Kind == OMPC_map && Data.ExtraModifier != OMPC_MAP_unknown) ||
4392       (Kind == OMPC_depend && Data.ExtraModifier != OMPC_DEPEND_unknown) ||
4393       (Kind == OMPC_adjust_args &&
4394        Data.ExtraModifier != OMPC_ADJUST_ARGS_unknown);
4395   const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned);
4396   while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) &&
4397                      Tok.isNot(tok::annot_pragma_openmp_end))) {
4398     ParseScope OMPListScope(this, Scope::OpenMPDirectiveScope);
4399     ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
4400     if (!ParseOpenMPReservedLocator(Kind, Data, getLangOpts())) {
4401       // Parse variable
4402       ExprResult VarExpr =
4403           Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
4404       if (VarExpr.isUsable()) {
4405         Vars.push_back(VarExpr.get());
4406       } else {
4407         SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4408                   StopBeforeMatch);
4409       }
4410     }
4411     // Skip ',' if any
4412     IsComma = Tok.is(tok::comma);
4413     if (IsComma)
4414       ConsumeToken();
4415     else if (Tok.isNot(tok::r_paren) &&
4416              Tok.isNot(tok::annot_pragma_openmp_end) &&
4417              (!MayHaveTail || Tok.isNot(tok::colon)))
4418       Diag(Tok, diag::err_omp_expected_punc)
4419           << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush)
4420                                    : getOpenMPClauseName(Kind))
4421           << (Kind == OMPC_flush);
4422   }
4423 
4424   // Parse ')' for linear clause with modifier.
4425   if (NeedRParenForLinear)
4426     LinearT.consumeClose();
4427 
4428   // Parse ':' linear-step (or ':' alignment).
4429   const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon);
4430   if (MustHaveTail) {
4431     Data.ColonLoc = Tok.getLocation();
4432     SourceLocation ELoc = ConsumeToken();
4433     ExprResult Tail = ParseAssignmentExpression();
4434     Tail =
4435         Actions.ActOnFinishFullExpr(Tail.get(), ELoc, /*DiscardedValue*/ false);
4436     if (Tail.isUsable())
4437       Data.DepModOrTailExpr = Tail.get();
4438     else
4439       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4440                 StopBeforeMatch);
4441   }
4442 
4443   // Parse ')'.
4444   Data.RLoc = Tok.getLocation();
4445   if (!T.consumeClose())
4446     Data.RLoc = T.getCloseLocation();
4447   // Exit from scope when the iterator is used in depend clause.
4448   if (HasIterator)
4449     ExitScope();
4450   return (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) ||
4451          (MustHaveTail && !Data.DepModOrTailExpr) || InvalidReductionId ||
4452          IsInvalidMapperModifier;
4453 }
4454 
4455 /// Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate',
4456 /// 'shared', 'copyin', 'copyprivate', 'flush', 'reduction', 'task_reduction',
4457 /// 'in_reduction', 'nontemporal', 'exclusive' or 'inclusive'.
4458 ///
4459 ///    private-clause:
4460 ///       'private' '(' list ')'
4461 ///    firstprivate-clause:
4462 ///       'firstprivate' '(' list ')'
4463 ///    lastprivate-clause:
4464 ///       'lastprivate' '(' list ')'
4465 ///    shared-clause:
4466 ///       'shared' '(' list ')'
4467 ///    linear-clause:
4468 ///       'linear' '(' linear-list [ ':' linear-step ] ')'
4469 ///    aligned-clause:
4470 ///       'aligned' '(' list [ ':' alignment ] ')'
4471 ///    reduction-clause:
4472 ///       'reduction' '(' [ modifier ',' ] reduction-identifier ':' list ')'
4473 ///    task_reduction-clause:
4474 ///       'task_reduction' '(' reduction-identifier ':' list ')'
4475 ///    in_reduction-clause:
4476 ///       'in_reduction' '(' reduction-identifier ':' list ')'
4477 ///    copyprivate-clause:
4478 ///       'copyprivate' '(' list ')'
4479 ///    flush-clause:
4480 ///       'flush' '(' list ')'
4481 ///    depend-clause:
4482 ///       'depend' '(' in | out | inout : list | source ')'
4483 ///    map-clause:
4484 ///       'map' '(' [ [ always [,] ] [ close [,] ]
4485 ///          [ mapper '(' mapper-identifier ')' [,] ]
4486 ///          to | from | tofrom | alloc | release | delete ':' ] list ')';
4487 ///    to-clause:
4488 ///       'to' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
4489 ///    from-clause:
4490 ///       'from' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
4491 ///    use_device_ptr-clause:
4492 ///       'use_device_ptr' '(' list ')'
4493 ///    use_device_addr-clause:
4494 ///       'use_device_addr' '(' list ')'
4495 ///    is_device_ptr-clause:
4496 ///       'is_device_ptr' '(' list ')'
4497 ///    has_device_addr-clause:
4498 ///       'has_device_addr' '(' list ')'
4499 ///    allocate-clause:
4500 ///       'allocate' '(' [ allocator ':' ] list ')'
4501 ///    nontemporal-clause:
4502 ///       'nontemporal' '(' list ')'
4503 ///    inclusive-clause:
4504 ///       'inclusive' '(' list ')'
4505 ///    exclusive-clause:
4506 ///       'exclusive' '(' list ')'
4507 ///
4508 /// For 'linear' clause linear-list may have the following forms:
4509 ///  list
4510 ///  modifier(list)
4511 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
4512 OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
4513                                             OpenMPClauseKind Kind,
4514                                             bool ParseOnly) {
4515   SourceLocation Loc = Tok.getLocation();
4516   SourceLocation LOpen = ConsumeToken();
4517   SmallVector<Expr *, 4> Vars;
4518   Sema::OpenMPVarListDataTy Data;
4519 
4520   if (ParseOpenMPVarList(DKind, Kind, Vars, Data))
4521     return nullptr;
4522 
4523   if (ParseOnly)
4524     return nullptr;
4525   OMPVarListLocTy Locs(Loc, LOpen, Data.RLoc);
4526   return Actions.ActOnOpenMPVarListClause(Kind, Vars, Locs, Data);
4527 }
4528