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, 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         Parser::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         Parser::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'  | '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_metadirective: {
2492     ConsumeToken();
2493     SmallVector<VariantMatchInfo, 4> VMIs;
2494 
2495     // First iteration of parsing all clauses of metadirective.
2496     // This iteration only parses and collects all context selector ignoring the
2497     // associated directives.
2498     TentativeParsingAction TPA(*this);
2499     ASTContext &ASTContext = Actions.getASTContext();
2500 
2501     BalancedDelimiterTracker T(*this, tok::l_paren,
2502                                tok::annot_pragma_openmp_end);
2503     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2504       OpenMPClauseKind CKind = Tok.isAnnotation()
2505                                    ? OMPC_unknown
2506                                    : getOpenMPClauseKind(PP.getSpelling(Tok));
2507       SourceLocation Loc = ConsumeToken();
2508 
2509       // Parse '('.
2510       if (T.expectAndConsume(diag::err_expected_lparen_after,
2511                              getOpenMPClauseName(CKind).data()))
2512         return Directive;
2513 
2514       OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo();
2515       if (CKind == OMPC_when) {
2516         // parse and get OMPTraitInfo to pass to the When clause
2517         parseOMPContextSelectors(Loc, TI);
2518         if (TI.Sets.size() == 0) {
2519           Diag(Tok, diag::err_omp_expected_context_selector) << "when clause";
2520           TPA.Commit();
2521           return Directive;
2522         }
2523 
2524         // Parse ':'
2525         if (Tok.is(tok::colon))
2526           ConsumeAnyToken();
2527         else {
2528           Diag(Tok, diag::err_omp_expected_colon) << "when clause";
2529           TPA.Commit();
2530           return Directive;
2531         }
2532       }
2533       // Skip Directive for now. We will parse directive in the second iteration
2534       int paren = 0;
2535       while (Tok.isNot(tok::r_paren) || paren != 0) {
2536         if (Tok.is(tok::l_paren))
2537           paren++;
2538         if (Tok.is(tok::r_paren))
2539           paren--;
2540         if (Tok.is(tok::annot_pragma_openmp_end)) {
2541           Diag(Tok, diag::err_omp_expected_punc)
2542               << getOpenMPClauseName(CKind) << 0;
2543           TPA.Commit();
2544           return Directive;
2545         }
2546         ConsumeAnyToken();
2547       }
2548       // Parse ')'
2549       if (Tok.is(tok::r_paren))
2550         T.consumeClose();
2551 
2552       VariantMatchInfo VMI;
2553       TI.getAsVariantMatchInfo(ASTContext, VMI);
2554 
2555       VMIs.push_back(VMI);
2556     }
2557 
2558     TPA.Revert();
2559     // End of the first iteration. Parser is reset to the start of metadirective
2560 
2561     std::function<void(StringRef)> DiagUnknownTrait =
2562         [this, Loc](StringRef ISATrait) {
2563           // TODO Track the selector locations in a way that is accessible here
2564           // to improve the diagnostic location.
2565           Diag(Loc, diag::warn_unknown_declare_variant_isa_trait) << ISATrait;
2566         };
2567     TargetOMPContext OMPCtx(ASTContext, std::move(DiagUnknownTrait),
2568                             /* CurrentFunctionDecl */ nullptr,
2569                             ArrayRef<llvm::omp::TraitProperty>());
2570 
2571     // A single match is returned for OpenMP 5.0
2572     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
2573 
2574     int Idx = 0;
2575     // In OpenMP 5.0 metadirective is either replaced by another directive or
2576     // ignored.
2577     // TODO: In OpenMP 5.1 generate multiple directives based upon the matches
2578     // found by getBestWhenMatchForContext.
2579     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2580       // OpenMP 5.0 implementation - Skip to the best index found.
2581       if (Idx++ != BestIdx) {
2582         ConsumeToken();  // Consume clause name
2583         T.consumeOpen(); // Consume '('
2584         int paren = 0;
2585         // Skip everything inside the clause
2586         while (Tok.isNot(tok::r_paren) || paren != 0) {
2587           if (Tok.is(tok::l_paren))
2588             paren++;
2589           if (Tok.is(tok::r_paren))
2590             paren--;
2591           ConsumeAnyToken();
2592         }
2593         // Parse ')'
2594         if (Tok.is(tok::r_paren))
2595           T.consumeClose();
2596         continue;
2597       }
2598 
2599       OpenMPClauseKind CKind = Tok.isAnnotation()
2600                                    ? OMPC_unknown
2601                                    : getOpenMPClauseKind(PP.getSpelling(Tok));
2602       SourceLocation Loc = ConsumeToken();
2603 
2604       // Parse '('.
2605       T.consumeOpen();
2606 
2607       // Skip ContextSelectors for when clause
2608       if (CKind == OMPC_when) {
2609         OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo();
2610         // parse and skip the ContextSelectors
2611         parseOMPContextSelectors(Loc, TI);
2612 
2613         // Parse ':'
2614         ConsumeAnyToken();
2615       }
2616 
2617       // If no directive is passed, skip in OpenMP 5.0.
2618       // TODO: Generate nothing directive from OpenMP 5.1.
2619       if (Tok.is(tok::r_paren)) {
2620         SkipUntil(tok::annot_pragma_openmp_end);
2621         break;
2622       }
2623 
2624       // Parse Directive
2625       Directive = ParseOpenMPDeclarativeOrExecutableDirective(
2626           StmtCtx,
2627           /*ReadDirectiveWithinMetadirective=*/true);
2628       break;
2629     }
2630     break;
2631   }
2632   case OMPD_threadprivate: {
2633     // FIXME: Should this be permitted in C++?
2634     if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
2635         ParsedStmtContext()) {
2636       Diag(Tok, diag::err_omp_immediate_directive)
2637           << getOpenMPDirectiveName(DKind) << 0;
2638     }
2639     ConsumeToken();
2640     DeclDirectiveListParserHelper Helper(this, DKind);
2641     if (!ParseOpenMPSimpleVarList(DKind, Helper,
2642                                   /*AllowScopeSpecifier=*/false)) {
2643       skipUntilPragmaOpenMPEnd(DKind);
2644       DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective(
2645           Loc, Helper.getIdentifiers());
2646       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2647     }
2648     SkipUntil(tok::annot_pragma_openmp_end);
2649     break;
2650   }
2651   case OMPD_allocate: {
2652     // FIXME: Should this be permitted in C++?
2653     if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
2654         ParsedStmtContext()) {
2655       Diag(Tok, diag::err_omp_immediate_directive)
2656           << getOpenMPDirectiveName(DKind) << 0;
2657     }
2658     ConsumeToken();
2659     DeclDirectiveListParserHelper Helper(this, DKind);
2660     if (!ParseOpenMPSimpleVarList(DKind, Helper,
2661                                   /*AllowScopeSpecifier=*/false)) {
2662       SmallVector<OMPClause *, 1> Clauses;
2663       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
2664         SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
2665                     llvm::omp::Clause_enumSize + 1>
2666             FirstClauses(llvm::omp::Clause_enumSize + 1);
2667         while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2668           OpenMPClauseKind CKind =
2669               Tok.isAnnotation() ? OMPC_unknown
2670                                  : getOpenMPClauseKind(PP.getSpelling(Tok));
2671           Actions.StartOpenMPClause(CKind);
2672           OMPClause *Clause = ParseOpenMPClause(
2673               OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt());
2674           SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
2675                     StopBeforeMatch);
2676           FirstClauses[unsigned(CKind)].setInt(true);
2677           if (Clause != nullptr)
2678             Clauses.push_back(Clause);
2679           if (Tok.is(tok::annot_pragma_openmp_end)) {
2680             Actions.EndOpenMPClause();
2681             break;
2682           }
2683           // Skip ',' if any.
2684           if (Tok.is(tok::comma))
2685             ConsumeToken();
2686           Actions.EndOpenMPClause();
2687         }
2688         skipUntilPragmaOpenMPEnd(DKind);
2689       }
2690       DeclGroupPtrTy Res = Actions.ActOnOpenMPAllocateDirective(
2691           Loc, Helper.getIdentifiers(), Clauses);
2692       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2693     }
2694     SkipUntil(tok::annot_pragma_openmp_end);
2695     break;
2696   }
2697   case OMPD_declare_reduction:
2698     ConsumeToken();
2699     if (DeclGroupPtrTy Res =
2700             ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) {
2701       skipUntilPragmaOpenMPEnd(OMPD_declare_reduction);
2702       ConsumeAnyToken();
2703       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2704     } else {
2705       SkipUntil(tok::annot_pragma_openmp_end);
2706     }
2707     break;
2708   case OMPD_declare_mapper: {
2709     ConsumeToken();
2710     if (DeclGroupPtrTy Res =
2711             ParseOpenMPDeclareMapperDirective(/*AS=*/AS_none)) {
2712       // Skip the last annot_pragma_openmp_end.
2713       ConsumeAnnotationToken();
2714       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2715     } else {
2716       SkipUntil(tok::annot_pragma_openmp_end);
2717     }
2718     break;
2719   }
2720   case OMPD_flush:
2721   case OMPD_depobj:
2722   case OMPD_scan:
2723   case OMPD_taskyield:
2724   case OMPD_barrier:
2725   case OMPD_taskwait:
2726   case OMPD_cancellation_point:
2727   case OMPD_cancel:
2728   case OMPD_target_enter_data:
2729   case OMPD_target_exit_data:
2730   case OMPD_target_update:
2731   case OMPD_interop:
2732     if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2733         ParsedStmtContext()) {
2734       Diag(Tok, diag::err_omp_immediate_directive)
2735           << getOpenMPDirectiveName(DKind) << 0;
2736     }
2737     HasAssociatedStatement = false;
2738     // Fall through for further analysis.
2739     LLVM_FALLTHROUGH;
2740   case OMPD_parallel:
2741   case OMPD_simd:
2742   case OMPD_tile:
2743   case OMPD_unroll:
2744   case OMPD_for:
2745   case OMPD_for_simd:
2746   case OMPD_sections:
2747   case OMPD_single:
2748   case OMPD_section:
2749   case OMPD_master:
2750   case OMPD_critical:
2751   case OMPD_parallel_for:
2752   case OMPD_parallel_for_simd:
2753   case OMPD_parallel_sections:
2754   case OMPD_parallel_master:
2755   case OMPD_task:
2756   case OMPD_ordered:
2757   case OMPD_atomic:
2758   case OMPD_target:
2759   case OMPD_teams:
2760   case OMPD_taskgroup:
2761   case OMPD_target_data:
2762   case OMPD_target_parallel:
2763   case OMPD_target_parallel_for:
2764   case OMPD_loop:
2765   case OMPD_teams_loop:
2766   case OMPD_target_teams_loop:
2767   case OMPD_parallel_loop:
2768   case OMPD_target_parallel_loop:
2769   case OMPD_taskloop:
2770   case OMPD_taskloop_simd:
2771   case OMPD_master_taskloop:
2772   case OMPD_master_taskloop_simd:
2773   case OMPD_parallel_master_taskloop:
2774   case OMPD_parallel_master_taskloop_simd:
2775   case OMPD_distribute:
2776   case OMPD_distribute_parallel_for:
2777   case OMPD_distribute_parallel_for_simd:
2778   case OMPD_distribute_simd:
2779   case OMPD_target_parallel_for_simd:
2780   case OMPD_target_simd:
2781   case OMPD_teams_distribute:
2782   case OMPD_teams_distribute_simd:
2783   case OMPD_teams_distribute_parallel_for_simd:
2784   case OMPD_teams_distribute_parallel_for:
2785   case OMPD_target_teams:
2786   case OMPD_target_teams_distribute:
2787   case OMPD_target_teams_distribute_parallel_for:
2788   case OMPD_target_teams_distribute_parallel_for_simd:
2789   case OMPD_target_teams_distribute_simd:
2790   case OMPD_dispatch:
2791   case OMPD_masked: {
2792     // Special processing for flush and depobj clauses.
2793     Token ImplicitTok;
2794     bool ImplicitClauseAllowed = false;
2795     if (DKind == OMPD_flush || DKind == OMPD_depobj) {
2796       ImplicitTok = Tok;
2797       ImplicitClauseAllowed = true;
2798     }
2799     ConsumeToken();
2800     // Parse directive name of the 'critical' directive if any.
2801     if (DKind == OMPD_critical) {
2802       BalancedDelimiterTracker T(*this, tok::l_paren,
2803                                  tok::annot_pragma_openmp_end);
2804       if (!T.consumeOpen()) {
2805         if (Tok.isAnyIdentifier()) {
2806           DirName =
2807               DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation());
2808           ConsumeAnyToken();
2809         } else {
2810           Diag(Tok, diag::err_omp_expected_identifier_for_critical);
2811         }
2812         T.consumeClose();
2813       }
2814     } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) {
2815       CancelRegion = parseOpenMPDirectiveKind(*this);
2816       if (Tok.isNot(tok::annot_pragma_openmp_end))
2817         ConsumeToken();
2818     }
2819 
2820     if (isOpenMPLoopDirective(DKind))
2821       ScopeFlags |= Scope::OpenMPLoopDirectiveScope;
2822     if (isOpenMPSimdDirective(DKind))
2823       ScopeFlags |= Scope::OpenMPSimdDirectiveScope;
2824     ParseScope OMPDirectiveScope(this, ScopeFlags);
2825     Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc);
2826 
2827     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2828       // If we are parsing for a directive within a metadirective, the directive
2829       // ends with a ')'.
2830       if (ReadDirectiveWithinMetadirective && Tok.is(tok::r_paren)) {
2831         while (Tok.isNot(tok::annot_pragma_openmp_end))
2832           ConsumeAnyToken();
2833         break;
2834       }
2835       bool HasImplicitClause = false;
2836       if (ImplicitClauseAllowed && Tok.is(tok::l_paren)) {
2837         HasImplicitClause = true;
2838         // Push copy of the current token back to stream to properly parse
2839         // pseudo-clause OMPFlushClause or OMPDepobjClause.
2840         PP.EnterToken(Tok, /*IsReinject*/ true);
2841         PP.EnterToken(ImplicitTok, /*IsReinject*/ true);
2842         ConsumeAnyToken();
2843       }
2844       OpenMPClauseKind CKind = Tok.isAnnotation()
2845                                    ? OMPC_unknown
2846                                    : getOpenMPClauseKind(PP.getSpelling(Tok));
2847       if (HasImplicitClause) {
2848         assert(CKind == OMPC_unknown && "Must be unknown implicit clause.");
2849         if (DKind == OMPD_flush) {
2850           CKind = OMPC_flush;
2851         } else {
2852           assert(DKind == OMPD_depobj &&
2853                  "Expected flush or depobj directives.");
2854           CKind = OMPC_depobj;
2855         }
2856       }
2857       // No more implicit clauses allowed.
2858       ImplicitClauseAllowed = false;
2859       Actions.StartOpenMPClause(CKind);
2860       HasImplicitClause = false;
2861       OMPClause *Clause = ParseOpenMPClause(
2862           DKind, CKind, !FirstClauses[unsigned(CKind)].getInt());
2863       FirstClauses[unsigned(CKind)].setInt(true);
2864       if (Clause) {
2865         FirstClauses[unsigned(CKind)].setPointer(Clause);
2866         Clauses.push_back(Clause);
2867       }
2868 
2869       // Skip ',' if any.
2870       if (Tok.is(tok::comma))
2871         ConsumeToken();
2872       Actions.EndOpenMPClause();
2873     }
2874     // End location of the directive.
2875     EndLoc = Tok.getLocation();
2876     // Consume final annot_pragma_openmp_end.
2877     ConsumeAnnotationToken();
2878 
2879     // OpenMP [2.13.8, ordered Construct, Syntax]
2880     // If the depend clause is specified, the ordered construct is a stand-alone
2881     // directive.
2882     if (DKind == OMPD_ordered && FirstClauses[unsigned(OMPC_depend)].getInt()) {
2883       if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2884           ParsedStmtContext()) {
2885         Diag(Loc, diag::err_omp_immediate_directive)
2886             << getOpenMPDirectiveName(DKind) << 1
2887             << getOpenMPClauseName(OMPC_depend);
2888       }
2889       HasAssociatedStatement = false;
2890     }
2891 
2892     if (DKind == OMPD_tile && !FirstClauses[unsigned(OMPC_sizes)].getInt()) {
2893       Diag(Loc, diag::err_omp_required_clause)
2894           << getOpenMPDirectiveName(OMPD_tile) << "sizes";
2895     }
2896 
2897     StmtResult AssociatedStmt;
2898     if (HasAssociatedStatement) {
2899       // The body is a block scope like in Lambdas and Blocks.
2900       Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
2901       // FIXME: We create a bogus CompoundStmt scope to hold the contents of
2902       // the captured region. Code elsewhere assumes that any FunctionScopeInfo
2903       // should have at least one compound statement scope within it.
2904       ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
2905       {
2906         Sema::CompoundScopeRAII Scope(Actions);
2907         AssociatedStmt = ParseStatement();
2908 
2909         if (AssociatedStmt.isUsable() && isOpenMPLoopDirective(DKind) &&
2910             getLangOpts().OpenMPIRBuilder)
2911           AssociatedStmt = Actions.ActOnOpenMPLoopnest(AssociatedStmt.get());
2912       }
2913       AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
2914     } else if (DKind == OMPD_target_update || DKind == OMPD_target_enter_data ||
2915                DKind == OMPD_target_exit_data) {
2916       Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
2917       AssociatedStmt = (Sema::CompoundScopeRAII(Actions),
2918                         Actions.ActOnCompoundStmt(Loc, Loc, llvm::None,
2919                                                   /*isStmtExpr=*/false));
2920       AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
2921     }
2922     Directive = Actions.ActOnOpenMPExecutableDirective(
2923         DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc,
2924         EndLoc);
2925 
2926     // Exit scope.
2927     Actions.EndOpenMPDSABlock(Directive.get());
2928     OMPDirectiveScope.Exit();
2929     break;
2930   }
2931   case OMPD_declare_simd:
2932   case OMPD_declare_target:
2933   case OMPD_begin_declare_target:
2934   case OMPD_end_declare_target:
2935   case OMPD_requires:
2936   case OMPD_begin_declare_variant:
2937   case OMPD_end_declare_variant:
2938   case OMPD_declare_variant:
2939     Diag(Tok, diag::err_omp_unexpected_directive)
2940         << 1 << getOpenMPDirectiveName(DKind);
2941     SkipUntil(tok::annot_pragma_openmp_end);
2942     break;
2943   case OMPD_unknown:
2944   default:
2945     Diag(Tok, diag::err_omp_unknown_directive);
2946     SkipUntil(tok::annot_pragma_openmp_end);
2947     break;
2948   }
2949   return Directive;
2950 }
2951 
2952 // Parses simple list:
2953 //   simple-variable-list:
2954 //         '(' id-expression {, id-expression} ')'
2955 //
2956 bool Parser::ParseOpenMPSimpleVarList(
2957     OpenMPDirectiveKind Kind,
2958     const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)>
2959         &Callback,
2960     bool AllowScopeSpecifier) {
2961   // Parse '('.
2962   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
2963   if (T.expectAndConsume(diag::err_expected_lparen_after,
2964                          getOpenMPDirectiveName(Kind).data()))
2965     return true;
2966   bool IsCorrect = true;
2967   bool NoIdentIsFound = true;
2968 
2969   // Read tokens while ')' or annot_pragma_openmp_end is not found.
2970   while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
2971     CXXScopeSpec SS;
2972     UnqualifiedId Name;
2973     // Read var name.
2974     Token PrevTok = Tok;
2975     NoIdentIsFound = false;
2976 
2977     if (AllowScopeSpecifier && getLangOpts().CPlusPlus &&
2978         ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2979                                        /*ObjectHasErrors=*/false, false)) {
2980       IsCorrect = false;
2981       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
2982                 StopBeforeMatch);
2983     } else if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
2984                                   /*ObjectHadErrors=*/false, false, false,
2985                                   false, false, nullptr, Name)) {
2986       IsCorrect = false;
2987       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
2988                 StopBeforeMatch);
2989     } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) &&
2990                Tok.isNot(tok::annot_pragma_openmp_end)) {
2991       IsCorrect = false;
2992       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
2993                 StopBeforeMatch);
2994       Diag(PrevTok.getLocation(), diag::err_expected)
2995           << tok::identifier
2996           << SourceRange(PrevTok.getLocation(), PrevTokLocation);
2997     } else {
2998       Callback(SS, Actions.GetNameFromUnqualifiedId(Name));
2999     }
3000     // Consume ','.
3001     if (Tok.is(tok::comma)) {
3002       ConsumeToken();
3003     }
3004   }
3005 
3006   if (NoIdentIsFound) {
3007     Diag(Tok, diag::err_expected) << tok::identifier;
3008     IsCorrect = false;
3009   }
3010 
3011   // Parse ')'.
3012   IsCorrect = !T.consumeClose() && IsCorrect;
3013 
3014   return !IsCorrect;
3015 }
3016 
3017 OMPClause *Parser::ParseOpenMPSizesClause() {
3018   SourceLocation ClauseNameLoc = ConsumeToken();
3019   SmallVector<Expr *, 4> ValExprs;
3020 
3021   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3022   if (T.consumeOpen()) {
3023     Diag(Tok, diag::err_expected) << tok::l_paren;
3024     return nullptr;
3025   }
3026 
3027   while (true) {
3028     ExprResult Val = ParseConstantExpression();
3029     if (!Val.isUsable()) {
3030       T.skipToEnd();
3031       return nullptr;
3032     }
3033 
3034     ValExprs.push_back(Val.get());
3035 
3036     if (Tok.is(tok::r_paren) || Tok.is(tok::annot_pragma_openmp_end))
3037       break;
3038 
3039     ExpectAndConsume(tok::comma);
3040   }
3041 
3042   T.consumeClose();
3043 
3044   return Actions.ActOnOpenMPSizesClause(
3045       ValExprs, ClauseNameLoc, T.getOpenLocation(), T.getCloseLocation());
3046 }
3047 
3048 OMPClause *Parser::ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind) {
3049   SourceLocation Loc = Tok.getLocation();
3050   ConsumeAnyToken();
3051 
3052   // Parse '('.
3053   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3054   if (T.expectAndConsume(diag::err_expected_lparen_after, "uses_allocator"))
3055     return nullptr;
3056   SmallVector<Sema::UsesAllocatorsData, 4> Data;
3057   do {
3058     ExprResult Allocator =
3059         getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression();
3060     if (Allocator.isInvalid()) {
3061       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3062                 StopBeforeMatch);
3063       break;
3064     }
3065     Sema::UsesAllocatorsData &D = Data.emplace_back();
3066     D.Allocator = Allocator.get();
3067     if (Tok.is(tok::l_paren)) {
3068       BalancedDelimiterTracker T(*this, tok::l_paren,
3069                                  tok::annot_pragma_openmp_end);
3070       T.consumeOpen();
3071       ExprResult AllocatorTraits =
3072           getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression();
3073       T.consumeClose();
3074       if (AllocatorTraits.isInvalid()) {
3075         SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3076                   StopBeforeMatch);
3077         break;
3078       }
3079       D.AllocatorTraits = AllocatorTraits.get();
3080       D.LParenLoc = T.getOpenLocation();
3081       D.RParenLoc = T.getCloseLocation();
3082     }
3083     if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren))
3084       Diag(Tok, diag::err_omp_expected_punc) << "uses_allocators" << 0;
3085     // Parse ','
3086     if (Tok.is(tok::comma))
3087       ConsumeAnyToken();
3088   } while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end));
3089   T.consumeClose();
3090   return Actions.ActOnOpenMPUsesAllocatorClause(Loc, T.getOpenLocation(),
3091                                                 T.getCloseLocation(), Data);
3092 }
3093 
3094 /// Parsing of OpenMP clauses.
3095 ///
3096 ///    clause:
3097 ///       if-clause | final-clause | num_threads-clause | safelen-clause |
3098 ///       default-clause | private-clause | firstprivate-clause | shared-clause
3099 ///       | linear-clause | aligned-clause | collapse-clause | bind-clause |
3100 ///       lastprivate-clause | reduction-clause | proc_bind-clause |
3101 ///       schedule-clause | copyin-clause | copyprivate-clause | untied-clause |
3102 ///       mergeable-clause | flush-clause | read-clause | write-clause |
3103 ///       update-clause | capture-clause | seq_cst-clause | device-clause |
3104 ///       simdlen-clause | threads-clause | simd-clause | num_teams-clause |
3105 ///       thread_limit-clause | priority-clause | grainsize-clause |
3106 ///       nogroup-clause | num_tasks-clause | hint-clause | to-clause |
3107 ///       from-clause | is_device_ptr-clause | task_reduction-clause |
3108 ///       in_reduction-clause | allocator-clause | allocate-clause |
3109 ///       acq_rel-clause | acquire-clause | release-clause | relaxed-clause |
3110 ///       depobj-clause | destroy-clause | detach-clause | inclusive-clause |
3111 ///       exclusive-clause | uses_allocators-clause | use_device_addr-clause
3112 ///
3113 OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind,
3114                                      OpenMPClauseKind CKind, bool FirstClause) {
3115   OMPClauseKind = CKind;
3116   OMPClause *Clause = nullptr;
3117   bool ErrorFound = false;
3118   bool WrongDirective = false;
3119   // Check if clause is allowed for the given directive.
3120   if (CKind != OMPC_unknown &&
3121       !isAllowedClauseForDirective(DKind, CKind, getLangOpts().OpenMP)) {
3122     Diag(Tok, diag::err_omp_unexpected_clause)
3123         << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind);
3124     ErrorFound = true;
3125     WrongDirective = true;
3126   }
3127 
3128   switch (CKind) {
3129   case OMPC_final:
3130   case OMPC_num_threads:
3131   case OMPC_safelen:
3132   case OMPC_simdlen:
3133   case OMPC_collapse:
3134   case OMPC_ordered:
3135   case OMPC_num_teams:
3136   case OMPC_thread_limit:
3137   case OMPC_priority:
3138   case OMPC_grainsize:
3139   case OMPC_num_tasks:
3140   case OMPC_hint:
3141   case OMPC_allocator:
3142   case OMPC_depobj:
3143   case OMPC_detach:
3144   case OMPC_novariants:
3145   case OMPC_nocontext:
3146   case OMPC_filter:
3147   case OMPC_partial:
3148   case OMPC_align:
3149     // OpenMP [2.5, Restrictions]
3150     //  At most one num_threads clause can appear on the directive.
3151     // OpenMP [2.8.1, simd construct, Restrictions]
3152     //  Only one safelen  clause can appear on a simd directive.
3153     //  Only one simdlen  clause can appear on a simd directive.
3154     //  Only one collapse clause can appear on a simd directive.
3155     // OpenMP [2.11.1, task Construct, Restrictions]
3156     //  At most one if clause can appear on the directive.
3157     //  At most one final clause can appear on the directive.
3158     // OpenMP [teams Construct, Restrictions]
3159     //  At most one num_teams clause can appear on the directive.
3160     //  At most one thread_limit clause can appear on the directive.
3161     // OpenMP [2.9.1, task Construct, Restrictions]
3162     // At most one priority clause can appear on the directive.
3163     // OpenMP [2.9.2, taskloop Construct, Restrictions]
3164     // At most one grainsize clause can appear on the directive.
3165     // OpenMP [2.9.2, taskloop Construct, Restrictions]
3166     // At most one num_tasks clause can appear on the directive.
3167     // OpenMP [2.11.3, allocate Directive, Restrictions]
3168     // At most one allocator clause can appear on the directive.
3169     // OpenMP 5.0, 2.10.1 task Construct, Restrictions.
3170     // At most one detach clause can appear on the directive.
3171     // OpenMP 5.1, 2.3.6 dispatch Construct, Restrictions.
3172     // At most one novariants clause can appear on a dispatch directive.
3173     // At most one nocontext clause can appear on a dispatch directive.
3174     if (!FirstClause) {
3175       Diag(Tok, diag::err_omp_more_one_clause)
3176           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3177       ErrorFound = true;
3178     }
3179 
3180     if ((CKind == OMPC_ordered || CKind == OMPC_partial) &&
3181         PP.LookAhead(/*N=*/0).isNot(tok::l_paren))
3182       Clause = ParseOpenMPClause(CKind, WrongDirective);
3183     else
3184       Clause = ParseOpenMPSingleExprClause(CKind, WrongDirective);
3185     break;
3186   case OMPC_default:
3187   case OMPC_proc_bind:
3188   case OMPC_atomic_default_mem_order:
3189   case OMPC_order:
3190   case OMPC_bind:
3191     // OpenMP [2.14.3.1, Restrictions]
3192     //  Only a single default clause may be specified on a parallel, task or
3193     //  teams directive.
3194     // OpenMP [2.5, parallel Construct, Restrictions]
3195     //  At most one proc_bind clause can appear on the directive.
3196     // OpenMP [5.0, Requires directive, Restrictions]
3197     //  At most one atomic_default_mem_order clause can appear
3198     //  on the directive
3199     // OpenMP 5.1, 2.11.7 loop Construct, Restrictions.
3200     // At most one bind clause can appear on a loop directive.
3201     if (!FirstClause && CKind != OMPC_order) {
3202       Diag(Tok, diag::err_omp_more_one_clause)
3203           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3204       ErrorFound = true;
3205     }
3206 
3207     Clause = ParseOpenMPSimpleClause(CKind, WrongDirective);
3208     break;
3209   case OMPC_device:
3210   case OMPC_schedule:
3211   case OMPC_dist_schedule:
3212   case OMPC_defaultmap:
3213     // OpenMP [2.7.1, Restrictions, p. 3]
3214     //  Only one schedule clause can appear on a loop directive.
3215     // OpenMP 4.5 [2.10.4, Restrictions, p. 106]
3216     //  At most one defaultmap clause can appear on the directive.
3217     // OpenMP 5.0 [2.12.5, target construct, Restrictions]
3218     //  At most one device clause can appear on the directive.
3219     if ((getLangOpts().OpenMP < 50 || CKind != OMPC_defaultmap) &&
3220         !FirstClause) {
3221       Diag(Tok, diag::err_omp_more_one_clause)
3222           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3223       ErrorFound = true;
3224     }
3225     LLVM_FALLTHROUGH;
3226   case OMPC_if:
3227     Clause = ParseOpenMPSingleExprWithArgClause(DKind, CKind, WrongDirective);
3228     break;
3229   case OMPC_nowait:
3230   case OMPC_untied:
3231   case OMPC_mergeable:
3232   case OMPC_read:
3233   case OMPC_write:
3234   case OMPC_capture:
3235   case OMPC_compare:
3236   case OMPC_seq_cst:
3237   case OMPC_acq_rel:
3238   case OMPC_acquire:
3239   case OMPC_release:
3240   case OMPC_relaxed:
3241   case OMPC_threads:
3242   case OMPC_simd:
3243   case OMPC_nogroup:
3244   case OMPC_unified_address:
3245   case OMPC_unified_shared_memory:
3246   case OMPC_reverse_offload:
3247   case OMPC_dynamic_allocators:
3248   case OMPC_full:
3249     // OpenMP [2.7.1, Restrictions, p. 9]
3250     //  Only one ordered clause can appear on a loop directive.
3251     // OpenMP [2.7.1, Restrictions, C/C++, p. 4]
3252     //  Only one nowait clause can appear on a for directive.
3253     // OpenMP [5.0, Requires directive, Restrictions]
3254     //   Each of the requires clauses can appear at most once on the directive.
3255     if (!FirstClause) {
3256       Diag(Tok, diag::err_omp_more_one_clause)
3257           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3258       ErrorFound = true;
3259     }
3260 
3261     Clause = ParseOpenMPClause(CKind, WrongDirective);
3262     break;
3263   case OMPC_update:
3264     if (!FirstClause) {
3265       Diag(Tok, diag::err_omp_more_one_clause)
3266           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3267       ErrorFound = true;
3268     }
3269 
3270     Clause = (DKind == OMPD_depobj)
3271                  ? ParseOpenMPSimpleClause(CKind, WrongDirective)
3272                  : ParseOpenMPClause(CKind, WrongDirective);
3273     break;
3274   case OMPC_private:
3275   case OMPC_firstprivate:
3276   case OMPC_lastprivate:
3277   case OMPC_shared:
3278   case OMPC_reduction:
3279   case OMPC_task_reduction:
3280   case OMPC_in_reduction:
3281   case OMPC_linear:
3282   case OMPC_aligned:
3283   case OMPC_copyin:
3284   case OMPC_copyprivate:
3285   case OMPC_flush:
3286   case OMPC_depend:
3287   case OMPC_map:
3288   case OMPC_to:
3289   case OMPC_from:
3290   case OMPC_use_device_ptr:
3291   case OMPC_use_device_addr:
3292   case OMPC_is_device_ptr:
3293   case OMPC_allocate:
3294   case OMPC_nontemporal:
3295   case OMPC_inclusive:
3296   case OMPC_exclusive:
3297   case OMPC_affinity:
3298     Clause = ParseOpenMPVarListClause(DKind, CKind, WrongDirective);
3299     break;
3300   case OMPC_sizes:
3301     if (!FirstClause) {
3302       Diag(Tok, diag::err_omp_more_one_clause)
3303           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3304       ErrorFound = true;
3305     }
3306 
3307     Clause = ParseOpenMPSizesClause();
3308     break;
3309   case OMPC_uses_allocators:
3310     Clause = ParseOpenMPUsesAllocatorClause(DKind);
3311     break;
3312   case OMPC_destroy:
3313     if (DKind != OMPD_interop) {
3314       if (!FirstClause) {
3315         Diag(Tok, diag::err_omp_more_one_clause)
3316             << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3317         ErrorFound = true;
3318       }
3319       Clause = ParseOpenMPClause(CKind, WrongDirective);
3320       break;
3321     }
3322     LLVM_FALLTHROUGH;
3323   case OMPC_init:
3324   case OMPC_use:
3325     Clause = ParseOpenMPInteropClause(CKind, WrongDirective);
3326     break;
3327   case OMPC_device_type:
3328   case OMPC_unknown:
3329     skipUntilPragmaOpenMPEnd(DKind);
3330     break;
3331   case OMPC_threadprivate:
3332   case OMPC_uniform:
3333   case OMPC_match:
3334     if (!WrongDirective)
3335       Diag(Tok, diag::err_omp_unexpected_clause)
3336           << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind);
3337     SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch);
3338     break;
3339   default:
3340     break;
3341   }
3342   return ErrorFound ? nullptr : Clause;
3343 }
3344 
3345 /// Parses simple expression in parens for single-expression clauses of OpenMP
3346 /// constructs.
3347 /// \param RLoc Returned location of right paren.
3348 ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName,
3349                                          SourceLocation &RLoc,
3350                                          bool IsAddressOfOperand) {
3351   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3352   if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data()))
3353     return ExprError();
3354 
3355   SourceLocation ELoc = Tok.getLocation();
3356   ExprResult LHS(
3357       ParseCastExpression(AnyCastExpr, IsAddressOfOperand, NotTypeCast));
3358   ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
3359   Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
3360 
3361   // Parse ')'.
3362   RLoc = Tok.getLocation();
3363   if (!T.consumeClose())
3364     RLoc = T.getCloseLocation();
3365 
3366   return Val;
3367 }
3368 
3369 /// Parsing of OpenMP clauses with single expressions like 'final',
3370 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
3371 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks', 'hint' or
3372 /// 'detach'.
3373 ///
3374 ///    final-clause:
3375 ///      'final' '(' expression ')'
3376 ///
3377 ///    num_threads-clause:
3378 ///      'num_threads' '(' expression ')'
3379 ///
3380 ///    safelen-clause:
3381 ///      'safelen' '(' expression ')'
3382 ///
3383 ///    simdlen-clause:
3384 ///      'simdlen' '(' expression ')'
3385 ///
3386 ///    collapse-clause:
3387 ///      'collapse' '(' expression ')'
3388 ///
3389 ///    priority-clause:
3390 ///      'priority' '(' expression ')'
3391 ///
3392 ///    grainsize-clause:
3393 ///      'grainsize' '(' expression ')'
3394 ///
3395 ///    num_tasks-clause:
3396 ///      'num_tasks' '(' expression ')'
3397 ///
3398 ///    hint-clause:
3399 ///      'hint' '(' expression ')'
3400 ///
3401 ///    allocator-clause:
3402 ///      'allocator' '(' expression ')'
3403 ///
3404 ///    detach-clause:
3405 ///      'detach' '(' event-handler-expression ')'
3406 ///
3407 ///    align-clause
3408 ///      'align' '(' positive-integer-constant ')'
3409 ///
3410 OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
3411                                                bool ParseOnly) {
3412   SourceLocation Loc = ConsumeToken();
3413   SourceLocation LLoc = Tok.getLocation();
3414   SourceLocation RLoc;
3415 
3416   ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
3417 
3418   if (Val.isInvalid())
3419     return nullptr;
3420 
3421   if (ParseOnly)
3422     return nullptr;
3423   return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc);
3424 }
3425 
3426 /// Parse indirect clause for '#pragma omp declare target' directive.
3427 ///  'indirect' '[' '(' invoked-by-fptr ')' ']'
3428 /// where invoked-by-fptr is a constant boolean expression that evaluates to
3429 /// true or false at compile time.
3430 bool Parser::ParseOpenMPIndirectClause(Sema::DeclareTargetContextInfo &DTCI,
3431                                        bool ParseOnly) {
3432   SourceLocation Loc = ConsumeToken();
3433   SourceLocation RLoc;
3434 
3435   if (Tok.isNot(tok::l_paren)) {
3436     if (ParseOnly)
3437       return false;
3438     DTCI.Indirect = nullptr;
3439     return true;
3440   }
3441 
3442   ExprResult Val =
3443       ParseOpenMPParensExpr(getOpenMPClauseName(OMPC_indirect), RLoc);
3444   if (Val.isInvalid())
3445     return false;
3446 
3447   if (ParseOnly)
3448     return false;
3449 
3450   if (!Val.get()->isValueDependent() && !Val.get()->isTypeDependent() &&
3451       !Val.get()->isInstantiationDependent() &&
3452       !Val.get()->containsUnexpandedParameterPack()) {
3453     ExprResult Ret = Actions.CheckBooleanCondition(Loc, Val.get());
3454     if (Ret.isInvalid())
3455       return false;
3456     llvm::APSInt Result;
3457     Ret = Actions.VerifyIntegerConstantExpression(Val.get(), &Result,
3458                                                   Sema::AllowFold);
3459     if (Ret.isInvalid())
3460       return false;
3461     DTCI.Indirect = Val.get();
3462     return true;
3463   }
3464   return false;
3465 }
3466 
3467 /// Parsing of OpenMP clauses that use an interop-var.
3468 ///
3469 /// init-clause:
3470 ///   init([interop-modifier, ]interop-type[[, interop-type] ... ]:interop-var)
3471 ///
3472 /// destroy-clause:
3473 ///   destroy(interop-var)
3474 ///
3475 /// use-clause:
3476 ///   use(interop-var)
3477 ///
3478 /// interop-modifier:
3479 ///   prefer_type(preference-list)
3480 ///
3481 /// preference-list:
3482 ///   foreign-runtime-id [, foreign-runtime-id]...
3483 ///
3484 /// foreign-runtime-id:
3485 ///   <string-literal> | <constant-integral-expression>
3486 ///
3487 /// interop-type:
3488 ///   target | targetsync
3489 ///
3490 OMPClause *Parser::ParseOpenMPInteropClause(OpenMPClauseKind Kind,
3491                                             bool ParseOnly) {
3492   SourceLocation Loc = ConsumeToken();
3493   // Parse '('.
3494   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3495   if (T.expectAndConsume(diag::err_expected_lparen_after,
3496                          getOpenMPClauseName(Kind).data()))
3497     return nullptr;
3498 
3499   bool IsTarget = false;
3500   bool IsTargetSync = false;
3501   SmallVector<Expr *, 4> Prefs;
3502 
3503   if (Kind == OMPC_init) {
3504 
3505     // Parse optional interop-modifier.
3506     if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "prefer_type") {
3507       ConsumeToken();
3508       BalancedDelimiterTracker PT(*this, tok::l_paren,
3509                                   tok::annot_pragma_openmp_end);
3510       if (PT.expectAndConsume(diag::err_expected_lparen_after, "prefer_type"))
3511         return nullptr;
3512 
3513       while (Tok.isNot(tok::r_paren)) {
3514         SourceLocation Loc = Tok.getLocation();
3515         ExprResult LHS = ParseCastExpression(AnyCastExpr);
3516         ExprResult PTExpr = Actions.CorrectDelayedTyposInExpr(
3517             ParseRHSOfBinaryExpression(LHS, prec::Conditional));
3518         PTExpr = Actions.ActOnFinishFullExpr(PTExpr.get(), Loc,
3519                                              /*DiscardedValue=*/false);
3520         if (PTExpr.isUsable())
3521           Prefs.push_back(PTExpr.get());
3522         else
3523           SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3524                     StopBeforeMatch);
3525 
3526         if (Tok.is(tok::comma))
3527           ConsumeToken();
3528       }
3529       PT.consumeClose();
3530     }
3531 
3532     if (!Prefs.empty()) {
3533       if (Tok.is(tok::comma))
3534         ConsumeToken();
3535       else
3536         Diag(Tok, diag::err_omp_expected_punc_after_interop_mod);
3537     }
3538 
3539     // Parse the interop-types.
3540     if (Optional<OMPDeclareVariantAttr::InteropType> IType =
3541             parseInteropTypeList(*this)) {
3542       IsTarget = IType != OMPDeclareVariantAttr::TargetSync;
3543       IsTargetSync = IType != OMPDeclareVariantAttr::Target;
3544       if (Tok.isNot(tok::colon))
3545         Diag(Tok, diag::warn_pragma_expected_colon) << "interop types";
3546     }
3547     if (Tok.is(tok::colon))
3548       ConsumeToken();
3549   }
3550 
3551   // Parse the variable.
3552   SourceLocation VarLoc = Tok.getLocation();
3553   ExprResult InteropVarExpr =
3554       Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3555   if (!InteropVarExpr.isUsable()) {
3556     SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3557               StopBeforeMatch);
3558   }
3559 
3560   // Parse ')'.
3561   SourceLocation RLoc = Tok.getLocation();
3562   if (!T.consumeClose())
3563     RLoc = T.getCloseLocation();
3564 
3565   if (ParseOnly || !InteropVarExpr.isUsable() ||
3566       (Kind == OMPC_init && !IsTarget && !IsTargetSync))
3567     return nullptr;
3568 
3569   if (Kind == OMPC_init)
3570     return Actions.ActOnOpenMPInitClause(InteropVarExpr.get(), Prefs, IsTarget,
3571                                          IsTargetSync, Loc, T.getOpenLocation(),
3572                                          VarLoc, RLoc);
3573   if (Kind == OMPC_use)
3574     return Actions.ActOnOpenMPUseClause(InteropVarExpr.get(), Loc,
3575                                         T.getOpenLocation(), VarLoc, RLoc);
3576 
3577   if (Kind == OMPC_destroy)
3578     return Actions.ActOnOpenMPDestroyClause(InteropVarExpr.get(), Loc,
3579                                             T.getOpenLocation(), VarLoc, RLoc);
3580 
3581   llvm_unreachable("Unexpected interop variable clause.");
3582 }
3583 
3584 /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
3585 ///
3586 ///    default-clause:
3587 ///         'default' '(' 'none' | 'shared' | 'firstprivate' ')'
3588 ///
3589 ///    proc_bind-clause:
3590 ///         'proc_bind' '(' 'master' | 'close' | 'spread' ')'
3591 ///
3592 ///    bind-clause:
3593 ///         'bind' '(' 'teams' | 'parallel' | 'thread' ')'
3594 ///
3595 ///    update-clause:
3596 ///         'update' '(' 'in' | 'out' | 'inout' | 'mutexinoutset' |
3597 ///         'inoutset' ')'
3598 ///
3599 OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind,
3600                                            bool ParseOnly) {
3601   llvm::Optional<SimpleClauseData> Val = parseOpenMPSimpleClause(*this, Kind);
3602   if (!Val || ParseOnly)
3603     return nullptr;
3604   if (getLangOpts().OpenMP < 51 && Kind == OMPC_default &&
3605       static_cast<DefaultKind>(Val.getValue().Type) ==
3606           OMP_DEFAULT_firstprivate) {
3607     Diag(Val.getValue().LOpen, diag::err_omp_invalid_dsa)
3608         << getOpenMPClauseName(OMPC_firstprivate)
3609         << getOpenMPClauseName(OMPC_default) << "5.1";
3610     return nullptr;
3611   }
3612   return Actions.ActOnOpenMPSimpleClause(
3613       Kind, Val.getValue().Type, Val.getValue().TypeLoc, Val.getValue().LOpen,
3614       Val.getValue().Loc, Val.getValue().RLoc);
3615 }
3616 
3617 /// Parsing of OpenMP clauses like 'ordered'.
3618 ///
3619 ///    ordered-clause:
3620 ///         'ordered'
3621 ///
3622 ///    nowait-clause:
3623 ///         'nowait'
3624 ///
3625 ///    untied-clause:
3626 ///         'untied'
3627 ///
3628 ///    mergeable-clause:
3629 ///         'mergeable'
3630 ///
3631 ///    read-clause:
3632 ///         'read'
3633 ///
3634 ///    threads-clause:
3635 ///         'threads'
3636 ///
3637 ///    simd-clause:
3638 ///         'simd'
3639 ///
3640 ///    nogroup-clause:
3641 ///         'nogroup'
3642 ///
3643 OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly) {
3644   SourceLocation Loc = Tok.getLocation();
3645   ConsumeAnyToken();
3646 
3647   if (ParseOnly)
3648     return nullptr;
3649   return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation());
3650 }
3651 
3652 /// Parsing of OpenMP clauses with single expressions and some additional
3653 /// argument like 'schedule' or 'dist_schedule'.
3654 ///
3655 ///    schedule-clause:
3656 ///      'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
3657 ///      ')'
3658 ///
3659 ///    if-clause:
3660 ///      'if' '(' [ directive-name-modifier ':' ] expression ')'
3661 ///
3662 ///    defaultmap:
3663 ///      'defaultmap' '(' modifier [ ':' kind ] ')'
3664 ///
3665 ///    device-clause:
3666 ///      'device' '(' [ device-modifier ':' ] expression ')'
3667 ///
3668 OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
3669                                                       OpenMPClauseKind Kind,
3670                                                       bool ParseOnly) {
3671   SourceLocation Loc = ConsumeToken();
3672   SourceLocation DelimLoc;
3673   // Parse '('.
3674   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3675   if (T.expectAndConsume(diag::err_expected_lparen_after,
3676                          getOpenMPClauseName(Kind).data()))
3677     return nullptr;
3678 
3679   ExprResult Val;
3680   SmallVector<unsigned, 4> Arg;
3681   SmallVector<SourceLocation, 4> KLoc;
3682   if (Kind == OMPC_schedule) {
3683     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
3684     Arg.resize(NumberOfElements);
3685     KLoc.resize(NumberOfElements);
3686     Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown;
3687     Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown;
3688     Arg[ScheduleKind] = OMPC_SCHEDULE_unknown;
3689     unsigned KindModifier = getOpenMPSimpleClauseType(
3690         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3691     if (KindModifier > OMPC_SCHEDULE_unknown) {
3692       // Parse 'modifier'
3693       Arg[Modifier1] = KindModifier;
3694       KLoc[Modifier1] = Tok.getLocation();
3695       if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3696           Tok.isNot(tok::annot_pragma_openmp_end))
3697         ConsumeAnyToken();
3698       if (Tok.is(tok::comma)) {
3699         // Parse ',' 'modifier'
3700         ConsumeAnyToken();
3701         KindModifier = getOpenMPSimpleClauseType(
3702             Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3703         Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown
3704                              ? KindModifier
3705                              : (unsigned)OMPC_SCHEDULE_unknown;
3706         KLoc[Modifier2] = Tok.getLocation();
3707         if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3708             Tok.isNot(tok::annot_pragma_openmp_end))
3709           ConsumeAnyToken();
3710       }
3711       // Parse ':'
3712       if (Tok.is(tok::colon))
3713         ConsumeAnyToken();
3714       else
3715         Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier";
3716       KindModifier = getOpenMPSimpleClauseType(
3717           Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3718     }
3719     Arg[ScheduleKind] = KindModifier;
3720     KLoc[ScheduleKind] = Tok.getLocation();
3721     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3722         Tok.isNot(tok::annot_pragma_openmp_end))
3723       ConsumeAnyToken();
3724     if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static ||
3725          Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic ||
3726          Arg[ScheduleKind] == OMPC_SCHEDULE_guided) &&
3727         Tok.is(tok::comma))
3728       DelimLoc = ConsumeAnyToken();
3729   } else if (Kind == OMPC_dist_schedule) {
3730     Arg.push_back(getOpenMPSimpleClauseType(
3731         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
3732     KLoc.push_back(Tok.getLocation());
3733     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3734         Tok.isNot(tok::annot_pragma_openmp_end))
3735       ConsumeAnyToken();
3736     if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma))
3737       DelimLoc = ConsumeAnyToken();
3738   } else if (Kind == OMPC_defaultmap) {
3739     // Get a defaultmap modifier
3740     unsigned Modifier = getOpenMPSimpleClauseType(
3741         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3742     // Set defaultmap modifier to unknown if it is either scalar, aggregate, or
3743     // pointer
3744     if (Modifier < OMPC_DEFAULTMAP_MODIFIER_unknown)
3745       Modifier = OMPC_DEFAULTMAP_MODIFIER_unknown;
3746     Arg.push_back(Modifier);
3747     KLoc.push_back(Tok.getLocation());
3748     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3749         Tok.isNot(tok::annot_pragma_openmp_end))
3750       ConsumeAnyToken();
3751     // Parse ':'
3752     if (Tok.is(tok::colon) || getLangOpts().OpenMP < 50) {
3753       if (Tok.is(tok::colon))
3754         ConsumeAnyToken();
3755       else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown)
3756         Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier";
3757       // Get a defaultmap kind
3758       Arg.push_back(getOpenMPSimpleClauseType(
3759           Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
3760       KLoc.push_back(Tok.getLocation());
3761       if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3762           Tok.isNot(tok::annot_pragma_openmp_end))
3763         ConsumeAnyToken();
3764     } else {
3765       Arg.push_back(OMPC_DEFAULTMAP_unknown);
3766       KLoc.push_back(SourceLocation());
3767     }
3768   } else if (Kind == OMPC_device) {
3769     // Only target executable directives support extended device construct.
3770     if (isOpenMPTargetExecutionDirective(DKind) && getLangOpts().OpenMP >= 50 &&
3771         NextToken().is(tok::colon)) {
3772       // Parse optional <device modifier> ':'
3773       Arg.push_back(getOpenMPSimpleClauseType(
3774           Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
3775       KLoc.push_back(Tok.getLocation());
3776       ConsumeAnyToken();
3777       // Parse ':'
3778       ConsumeAnyToken();
3779     } else {
3780       Arg.push_back(OMPC_DEVICE_unknown);
3781       KLoc.emplace_back();
3782     }
3783   } else {
3784     assert(Kind == OMPC_if);
3785     KLoc.push_back(Tok.getLocation());
3786     TentativeParsingAction TPA(*this);
3787     auto DK = parseOpenMPDirectiveKind(*this);
3788     Arg.push_back(DK);
3789     if (DK != OMPD_unknown) {
3790       ConsumeToken();
3791       if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) {
3792         TPA.Commit();
3793         DelimLoc = ConsumeToken();
3794       } else {
3795         TPA.Revert();
3796         Arg.back() = unsigned(OMPD_unknown);
3797       }
3798     } else {
3799       TPA.Revert();
3800     }
3801   }
3802 
3803   bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) ||
3804                           (Kind == OMPC_dist_schedule && DelimLoc.isValid()) ||
3805                           Kind == OMPC_if || Kind == OMPC_device;
3806   if (NeedAnExpression) {
3807     SourceLocation ELoc = Tok.getLocation();
3808     ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
3809     Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
3810     Val =
3811         Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
3812   }
3813 
3814   // Parse ')'.
3815   SourceLocation RLoc = Tok.getLocation();
3816   if (!T.consumeClose())
3817     RLoc = T.getCloseLocation();
3818 
3819   if (NeedAnExpression && Val.isInvalid())
3820     return nullptr;
3821 
3822   if (ParseOnly)
3823     return nullptr;
3824   return Actions.ActOnOpenMPSingleExprWithArgClause(
3825       Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc, RLoc);
3826 }
3827 
3828 static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec,
3829                              UnqualifiedId &ReductionId) {
3830   if (ReductionIdScopeSpec.isEmpty()) {
3831     auto OOK = OO_None;
3832     switch (P.getCurToken().getKind()) {
3833     case tok::plus:
3834       OOK = OO_Plus;
3835       break;
3836     case tok::minus:
3837       OOK = OO_Minus;
3838       break;
3839     case tok::star:
3840       OOK = OO_Star;
3841       break;
3842     case tok::amp:
3843       OOK = OO_Amp;
3844       break;
3845     case tok::pipe:
3846       OOK = OO_Pipe;
3847       break;
3848     case tok::caret:
3849       OOK = OO_Caret;
3850       break;
3851     case tok::ampamp:
3852       OOK = OO_AmpAmp;
3853       break;
3854     case tok::pipepipe:
3855       OOK = OO_PipePipe;
3856       break;
3857     default:
3858       break;
3859     }
3860     if (OOK != OO_None) {
3861       SourceLocation OpLoc = P.ConsumeToken();
3862       SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()};
3863       ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations);
3864       return false;
3865     }
3866   }
3867   return P.ParseUnqualifiedId(
3868       ReductionIdScopeSpec, /*ObjectType=*/nullptr,
3869       /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
3870       /*AllowDestructorName*/ false,
3871       /*AllowConstructorName*/ false,
3872       /*AllowDeductionGuide*/ false, nullptr, ReductionId);
3873 }
3874 
3875 /// Checks if the token is a valid map-type-modifier.
3876 /// FIXME: It will return an OpenMPMapClauseKind if that's what it parses.
3877 static OpenMPMapModifierKind isMapModifier(Parser &P) {
3878   Token Tok = P.getCurToken();
3879   if (!Tok.is(tok::identifier))
3880     return OMPC_MAP_MODIFIER_unknown;
3881 
3882   Preprocessor &PP = P.getPreprocessor();
3883   OpenMPMapModifierKind TypeModifier =
3884       static_cast<OpenMPMapModifierKind>(getOpenMPSimpleClauseType(
3885           OMPC_map, PP.getSpelling(Tok), P.getLangOpts()));
3886   return TypeModifier;
3887 }
3888 
3889 /// Parse the mapper modifier in map, to, and from clauses.
3890 bool Parser::parseMapperModifier(OpenMPVarListDataTy &Data) {
3891   // Parse '('.
3892   BalancedDelimiterTracker T(*this, tok::l_paren, tok::colon);
3893   if (T.expectAndConsume(diag::err_expected_lparen_after, "mapper")) {
3894     SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
3895               StopBeforeMatch);
3896     return true;
3897   }
3898   // Parse mapper-identifier
3899   if (getLangOpts().CPlusPlus)
3900     ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
3901                                    /*ObjectType=*/nullptr,
3902                                    /*ObjectHasErrors=*/false,
3903                                    /*EnteringContext=*/false);
3904   if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
3905     Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
3906     SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
3907               StopBeforeMatch);
3908     return true;
3909   }
3910   auto &DeclNames = Actions.getASTContext().DeclarationNames;
3911   Data.ReductionOrMapperId = DeclarationNameInfo(
3912       DeclNames.getIdentifier(Tok.getIdentifierInfo()), Tok.getLocation());
3913   ConsumeToken();
3914   // Parse ')'.
3915   return T.consumeClose();
3916 }
3917 
3918 /// Parse map-type-modifiers in map clause.
3919 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
3920 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) |
3921 /// present
3922 bool Parser::parseMapTypeModifiers(OpenMPVarListDataTy &Data) {
3923   while (getCurToken().isNot(tok::colon)) {
3924     OpenMPMapModifierKind TypeModifier = isMapModifier(*this);
3925     if (TypeModifier == OMPC_MAP_MODIFIER_always ||
3926         TypeModifier == OMPC_MAP_MODIFIER_close ||
3927         TypeModifier == OMPC_MAP_MODIFIER_present ||
3928         TypeModifier == OMPC_MAP_MODIFIER_ompx_hold) {
3929       Data.MapTypeModifiers.push_back(TypeModifier);
3930       Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
3931       ConsumeToken();
3932     } else if (TypeModifier == OMPC_MAP_MODIFIER_mapper) {
3933       Data.MapTypeModifiers.push_back(TypeModifier);
3934       Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
3935       ConsumeToken();
3936       if (parseMapperModifier(Data))
3937         return true;
3938     } else {
3939       // For the case of unknown map-type-modifier or a map-type.
3940       // Map-type is followed by a colon; the function returns when it
3941       // encounters a token followed by a colon.
3942       if (Tok.is(tok::comma)) {
3943         Diag(Tok, diag::err_omp_map_type_modifier_missing);
3944         ConsumeToken();
3945         continue;
3946       }
3947       // Potential map-type token as it is followed by a colon.
3948       if (PP.LookAhead(0).is(tok::colon))
3949         return false;
3950       Diag(Tok, diag::err_omp_unknown_map_type_modifier)
3951           << (getLangOpts().OpenMP >= 51 ? 1 : 0)
3952           << getLangOpts().OpenMPExtensions;
3953       ConsumeToken();
3954     }
3955     if (getCurToken().is(tok::comma))
3956       ConsumeToken();
3957   }
3958   return false;
3959 }
3960 
3961 /// Checks if the token is a valid map-type.
3962 /// FIXME: It will return an OpenMPMapModifierKind if that's what it parses.
3963 static OpenMPMapClauseKind isMapType(Parser &P) {
3964   Token Tok = P.getCurToken();
3965   // The map-type token can be either an identifier or the C++ delete keyword.
3966   if (!Tok.isOneOf(tok::identifier, tok::kw_delete))
3967     return OMPC_MAP_unknown;
3968   Preprocessor &PP = P.getPreprocessor();
3969   OpenMPMapClauseKind MapType =
3970       static_cast<OpenMPMapClauseKind>(getOpenMPSimpleClauseType(
3971           OMPC_map, PP.getSpelling(Tok), P.getLangOpts()));
3972   return MapType;
3973 }
3974 
3975 /// Parse map-type in map clause.
3976 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
3977 /// where, map-type ::= to | from | tofrom | alloc | release | delete
3978 static void parseMapType(Parser &P, Parser::OpenMPVarListDataTy &Data) {
3979   Token Tok = P.getCurToken();
3980   if (Tok.is(tok::colon)) {
3981     P.Diag(Tok, diag::err_omp_map_type_missing);
3982     return;
3983   }
3984   Data.ExtraModifier = isMapType(P);
3985   if (Data.ExtraModifier == OMPC_MAP_unknown)
3986     P.Diag(Tok, diag::err_omp_unknown_map_type);
3987   P.ConsumeToken();
3988 }
3989 
3990 /// Parses simple expression in parens for single-expression clauses of OpenMP
3991 /// constructs.
3992 ExprResult Parser::ParseOpenMPIteratorsExpr() {
3993   assert(Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator" &&
3994          "Expected 'iterator' token.");
3995   SourceLocation IteratorKwLoc = ConsumeToken();
3996 
3997   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3998   if (T.expectAndConsume(diag::err_expected_lparen_after, "iterator"))
3999     return ExprError();
4000 
4001   SourceLocation LLoc = T.getOpenLocation();
4002   SmallVector<Sema::OMPIteratorData, 4> Data;
4003   while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
4004     // Check if the type parsing is required.
4005     ParsedType IteratorType;
4006     if (Tok.isNot(tok::identifier) || NextToken().isNot(tok::equal)) {
4007       // identifier '=' is not found - parse type.
4008       TypeResult TR = ParseTypeName();
4009       if (TR.isInvalid()) {
4010         T.skipToEnd();
4011         return ExprError();
4012       }
4013       IteratorType = TR.get();
4014     }
4015 
4016     // Parse identifier.
4017     IdentifierInfo *II = nullptr;
4018     SourceLocation IdLoc;
4019     if (Tok.is(tok::identifier)) {
4020       II = Tok.getIdentifierInfo();
4021       IdLoc = ConsumeToken();
4022     } else {
4023       Diag(Tok, diag::err_expected_unqualified_id) << 0;
4024     }
4025 
4026     // Parse '='.
4027     SourceLocation AssignLoc;
4028     if (Tok.is(tok::equal))
4029       AssignLoc = ConsumeToken();
4030     else
4031       Diag(Tok, diag::err_omp_expected_equal_in_iterator);
4032 
4033     // Parse range-specification - <begin> ':' <end> [ ':' <step> ]
4034     ColonProtectionRAIIObject ColonRAII(*this);
4035     // Parse <begin>
4036     SourceLocation Loc = Tok.getLocation();
4037     ExprResult LHS = ParseCastExpression(AnyCastExpr);
4038     ExprResult Begin = Actions.CorrectDelayedTyposInExpr(
4039         ParseRHSOfBinaryExpression(LHS, prec::Conditional));
4040     Begin = Actions.ActOnFinishFullExpr(Begin.get(), Loc,
4041                                         /*DiscardedValue=*/false);
4042     // Parse ':'.
4043     SourceLocation ColonLoc;
4044     if (Tok.is(tok::colon))
4045       ColonLoc = ConsumeToken();
4046 
4047     // Parse <end>
4048     Loc = Tok.getLocation();
4049     LHS = ParseCastExpression(AnyCastExpr);
4050     ExprResult End = Actions.CorrectDelayedTyposInExpr(
4051         ParseRHSOfBinaryExpression(LHS, prec::Conditional));
4052     End = Actions.ActOnFinishFullExpr(End.get(), Loc,
4053                                       /*DiscardedValue=*/false);
4054 
4055     SourceLocation SecColonLoc;
4056     ExprResult Step;
4057     // Parse optional step.
4058     if (Tok.is(tok::colon)) {
4059       // Parse ':'
4060       SecColonLoc = ConsumeToken();
4061       // Parse <step>
4062       Loc = Tok.getLocation();
4063       LHS = ParseCastExpression(AnyCastExpr);
4064       Step = Actions.CorrectDelayedTyposInExpr(
4065           ParseRHSOfBinaryExpression(LHS, prec::Conditional));
4066       Step = Actions.ActOnFinishFullExpr(Step.get(), Loc,
4067                                          /*DiscardedValue=*/false);
4068     }
4069 
4070     // Parse ',' or ')'
4071     if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren))
4072       Diag(Tok, diag::err_omp_expected_punc_after_iterator);
4073     if (Tok.is(tok::comma))
4074       ConsumeToken();
4075 
4076     Sema::OMPIteratorData &D = Data.emplace_back();
4077     D.DeclIdent = II;
4078     D.DeclIdentLoc = IdLoc;
4079     D.Type = IteratorType;
4080     D.AssignLoc = AssignLoc;
4081     D.ColonLoc = ColonLoc;
4082     D.SecColonLoc = SecColonLoc;
4083     D.Range.Begin = Begin.get();
4084     D.Range.End = End.get();
4085     D.Range.Step = Step.get();
4086   }
4087 
4088   // Parse ')'.
4089   SourceLocation RLoc = Tok.getLocation();
4090   if (!T.consumeClose())
4091     RLoc = T.getCloseLocation();
4092 
4093   return Actions.ActOnOMPIteratorExpr(getCurScope(), IteratorKwLoc, LLoc, RLoc,
4094                                       Data);
4095 }
4096 
4097 /// Parses clauses with list.
4098 bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind,
4099                                 OpenMPClauseKind Kind,
4100                                 SmallVectorImpl<Expr *> &Vars,
4101                                 OpenMPVarListDataTy &Data) {
4102   UnqualifiedId UnqualifiedReductionId;
4103   bool InvalidReductionId = false;
4104   bool IsInvalidMapperModifier = false;
4105 
4106   // Parse '('.
4107   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
4108   if (T.expectAndConsume(diag::err_expected_lparen_after,
4109                          getOpenMPClauseName(Kind).data()))
4110     return true;
4111 
4112   bool HasIterator = false;
4113   bool NeedRParenForLinear = false;
4114   BalancedDelimiterTracker LinearT(*this, tok::l_paren,
4115                                    tok::annot_pragma_openmp_end);
4116   // Handle reduction-identifier for reduction clause.
4117   if (Kind == OMPC_reduction || Kind == OMPC_task_reduction ||
4118       Kind == OMPC_in_reduction) {
4119     Data.ExtraModifier = OMPC_REDUCTION_unknown;
4120     if (Kind == OMPC_reduction && getLangOpts().OpenMP >= 50 &&
4121         (Tok.is(tok::identifier) || Tok.is(tok::kw_default)) &&
4122         NextToken().is(tok::comma)) {
4123       // Parse optional reduction modifier.
4124       Data.ExtraModifier =
4125           getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
4126       Data.ExtraModifierLoc = Tok.getLocation();
4127       ConsumeToken();
4128       assert(Tok.is(tok::comma) && "Expected comma.");
4129       (void)ConsumeToken();
4130     }
4131     ColonProtectionRAIIObject ColonRAII(*this);
4132     if (getLangOpts().CPlusPlus)
4133       ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
4134                                      /*ObjectType=*/nullptr,
4135                                      /*ObjectHasErrors=*/false,
4136                                      /*EnteringContext=*/false);
4137     InvalidReductionId = ParseReductionId(
4138         *this, Data.ReductionOrMapperIdScopeSpec, UnqualifiedReductionId);
4139     if (InvalidReductionId) {
4140       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4141                 StopBeforeMatch);
4142     }
4143     if (Tok.is(tok::colon))
4144       Data.ColonLoc = ConsumeToken();
4145     else
4146       Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier";
4147     if (!InvalidReductionId)
4148       Data.ReductionOrMapperId =
4149           Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId);
4150   } else if (Kind == OMPC_depend) {
4151     if (getLangOpts().OpenMP >= 50) {
4152       if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator") {
4153         // Handle optional dependence modifier.
4154         // iterator(iterators-definition)
4155         // where iterators-definition is iterator-specifier [,
4156         // iterators-definition ]
4157         // where iterator-specifier is [ iterator-type ] identifier =
4158         // range-specification
4159         HasIterator = true;
4160         EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope);
4161         ExprResult IteratorRes = ParseOpenMPIteratorsExpr();
4162         Data.DepModOrTailExpr = IteratorRes.get();
4163         // Parse ','
4164         ExpectAndConsume(tok::comma);
4165       }
4166     }
4167     // Handle dependency type for depend clause.
4168     ColonProtectionRAIIObject ColonRAII(*this);
4169     Data.ExtraModifier = getOpenMPSimpleClauseType(
4170         Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
4171         getLangOpts());
4172     Data.ExtraModifierLoc = Tok.getLocation();
4173     if (Data.ExtraModifier == OMPC_DEPEND_unknown) {
4174       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4175                 StopBeforeMatch);
4176     } else {
4177       ConsumeToken();
4178       // Special processing for depend(source) clause.
4179       if (DKind == OMPD_ordered && Data.ExtraModifier == OMPC_DEPEND_source) {
4180         // Parse ')'.
4181         T.consumeClose();
4182         return false;
4183       }
4184     }
4185     if (Tok.is(tok::colon)) {
4186       Data.ColonLoc = ConsumeToken();
4187     } else {
4188       Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren
4189                                       : diag::warn_pragma_expected_colon)
4190           << "dependency type";
4191     }
4192   } else if (Kind == OMPC_linear) {
4193     // Try to parse modifier if any.
4194     Data.ExtraModifier = OMPC_LINEAR_val;
4195     if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) {
4196       Data.ExtraModifier =
4197           getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
4198       Data.ExtraModifierLoc = ConsumeToken();
4199       LinearT.consumeOpen();
4200       NeedRParenForLinear = true;
4201     }
4202   } else if (Kind == OMPC_lastprivate) {
4203     // Try to parse modifier if any.
4204     Data.ExtraModifier = OMPC_LASTPRIVATE_unknown;
4205     // Conditional modifier allowed only in OpenMP 5.0 and not supported in
4206     // distribute and taskloop based directives.
4207     if ((getLangOpts().OpenMP >= 50 && !isOpenMPDistributeDirective(DKind) &&
4208          !isOpenMPTaskLoopDirective(DKind)) &&
4209         Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::colon)) {
4210       Data.ExtraModifier =
4211           getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
4212       Data.ExtraModifierLoc = Tok.getLocation();
4213       ConsumeToken();
4214       assert(Tok.is(tok::colon) && "Expected colon.");
4215       Data.ColonLoc = ConsumeToken();
4216     }
4217   } else if (Kind == OMPC_map) {
4218     // Handle map type for map clause.
4219     ColonProtectionRAIIObject ColonRAII(*this);
4220 
4221     // The first identifier may be a list item, a map-type or a
4222     // map-type-modifier. The map-type can also be delete which has the same
4223     // spelling of the C++ delete keyword.
4224     Data.ExtraModifier = OMPC_MAP_unknown;
4225     Data.ExtraModifierLoc = Tok.getLocation();
4226 
4227     // Check for presence of a colon in the map clause.
4228     TentativeParsingAction TPA(*this);
4229     bool ColonPresent = false;
4230     if (SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4231                   StopBeforeMatch)) {
4232       if (Tok.is(tok::colon))
4233         ColonPresent = true;
4234     }
4235     TPA.Revert();
4236     // Only parse map-type-modifier[s] and map-type if a colon is present in
4237     // the map clause.
4238     if (ColonPresent) {
4239       IsInvalidMapperModifier = parseMapTypeModifiers(Data);
4240       if (!IsInvalidMapperModifier)
4241         parseMapType(*this, Data);
4242       else
4243         SkipUntil(tok::colon, tok::annot_pragma_openmp_end, StopBeforeMatch);
4244     }
4245     if (Data.ExtraModifier == OMPC_MAP_unknown) {
4246       Data.ExtraModifier = OMPC_MAP_tofrom;
4247       Data.IsMapTypeImplicit = true;
4248     }
4249 
4250     if (Tok.is(tok::colon))
4251       Data.ColonLoc = ConsumeToken();
4252   } else if (Kind == OMPC_to || Kind == OMPC_from) {
4253     while (Tok.is(tok::identifier)) {
4254       auto Modifier = static_cast<OpenMPMotionModifierKind>(
4255           getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts()));
4256       if (Modifier == OMPC_MOTION_MODIFIER_unknown)
4257         break;
4258       Data.MotionModifiers.push_back(Modifier);
4259       Data.MotionModifiersLoc.push_back(Tok.getLocation());
4260       ConsumeToken();
4261       if (Modifier == OMPC_MOTION_MODIFIER_mapper) {
4262         IsInvalidMapperModifier = parseMapperModifier(Data);
4263         if (IsInvalidMapperModifier)
4264           break;
4265       }
4266       // OpenMP < 5.1 doesn't permit a ',' or additional modifiers.
4267       if (getLangOpts().OpenMP < 51)
4268         break;
4269       // OpenMP 5.1 accepts an optional ',' even if the next character is ':'.
4270       // TODO: Is that intentional?
4271       if (Tok.is(tok::comma))
4272         ConsumeToken();
4273     }
4274     if (!Data.MotionModifiers.empty() && Tok.isNot(tok::colon)) {
4275       if (!IsInvalidMapperModifier) {
4276         if (getLangOpts().OpenMP < 51)
4277           Diag(Tok, diag::warn_pragma_expected_colon) << ")";
4278         else
4279           Diag(Tok, diag::warn_pragma_expected_colon) << "motion modifier";
4280       }
4281       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4282                 StopBeforeMatch);
4283     }
4284     // OpenMP 5.1 permits a ':' even without a preceding modifier.  TODO: Is
4285     // that intentional?
4286     if ((!Data.MotionModifiers.empty() || getLangOpts().OpenMP >= 51) &&
4287         Tok.is(tok::colon))
4288       Data.ColonLoc = ConsumeToken();
4289   } else if (Kind == OMPC_allocate ||
4290              (Kind == OMPC_affinity && Tok.is(tok::identifier) &&
4291               PP.getSpelling(Tok) == "iterator")) {
4292     // Handle optional allocator expression followed by colon delimiter.
4293     ColonProtectionRAIIObject ColonRAII(*this);
4294     TentativeParsingAction TPA(*this);
4295     // OpenMP 5.0, 2.10.1, task Construct.
4296     // where aff-modifier is one of the following:
4297     // iterator(iterators-definition)
4298     ExprResult Tail;
4299     if (Kind == OMPC_allocate) {
4300       Tail = ParseAssignmentExpression();
4301     } else {
4302       HasIterator = true;
4303       EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope);
4304       Tail = ParseOpenMPIteratorsExpr();
4305     }
4306     Tail = Actions.CorrectDelayedTyposInExpr(Tail);
4307     Tail = Actions.ActOnFinishFullExpr(Tail.get(), T.getOpenLocation(),
4308                                        /*DiscardedValue=*/false);
4309     if (Tail.isUsable()) {
4310       if (Tok.is(tok::colon)) {
4311         Data.DepModOrTailExpr = Tail.get();
4312         Data.ColonLoc = ConsumeToken();
4313         TPA.Commit();
4314       } else {
4315         // Colon not found, parse only list of variables.
4316         TPA.Revert();
4317       }
4318     } else {
4319       // Parsing was unsuccessfull, revert and skip to the end of clause or
4320       // directive.
4321       TPA.Revert();
4322       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4323                 StopBeforeMatch);
4324     }
4325   } else if (Kind == OMPC_adjust_args) {
4326     // Handle adjust-op for adjust_args clause.
4327     ColonProtectionRAIIObject ColonRAII(*this);
4328     Data.ExtraModifier = getOpenMPSimpleClauseType(
4329         Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
4330         getLangOpts());
4331     Data.ExtraModifierLoc = Tok.getLocation();
4332     if (Data.ExtraModifier == OMPC_ADJUST_ARGS_unknown) {
4333       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4334                 StopBeforeMatch);
4335     } else {
4336       ConsumeToken();
4337       if (Tok.is(tok::colon))
4338         Data.ColonLoc = Tok.getLocation();
4339       ExpectAndConsume(tok::colon, diag::warn_pragma_expected_colon,
4340                        "adjust-op");
4341     }
4342   }
4343 
4344   bool IsComma =
4345       (Kind != OMPC_reduction && Kind != OMPC_task_reduction &&
4346        Kind != OMPC_in_reduction && Kind != OMPC_depend && Kind != OMPC_map) ||
4347       (Kind == OMPC_reduction && !InvalidReductionId) ||
4348       (Kind == OMPC_map && Data.ExtraModifier != OMPC_MAP_unknown) ||
4349       (Kind == OMPC_depend && Data.ExtraModifier != OMPC_DEPEND_unknown) ||
4350       (Kind == OMPC_adjust_args &&
4351        Data.ExtraModifier != OMPC_ADJUST_ARGS_unknown);
4352   const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned);
4353   while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) &&
4354                      Tok.isNot(tok::annot_pragma_openmp_end))) {
4355     ParseScope OMPListScope(this, Scope::OpenMPDirectiveScope);
4356     ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
4357     // Parse variable
4358     ExprResult VarExpr =
4359         Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
4360     if (VarExpr.isUsable()) {
4361       Vars.push_back(VarExpr.get());
4362     } else {
4363       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4364                 StopBeforeMatch);
4365     }
4366     // Skip ',' if any
4367     IsComma = Tok.is(tok::comma);
4368     if (IsComma)
4369       ConsumeToken();
4370     else if (Tok.isNot(tok::r_paren) &&
4371              Tok.isNot(tok::annot_pragma_openmp_end) &&
4372              (!MayHaveTail || Tok.isNot(tok::colon)))
4373       Diag(Tok, diag::err_omp_expected_punc)
4374           << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush)
4375                                    : getOpenMPClauseName(Kind))
4376           << (Kind == OMPC_flush);
4377   }
4378 
4379   // Parse ')' for linear clause with modifier.
4380   if (NeedRParenForLinear)
4381     LinearT.consumeClose();
4382 
4383   // Parse ':' linear-step (or ':' alignment).
4384   const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon);
4385   if (MustHaveTail) {
4386     Data.ColonLoc = Tok.getLocation();
4387     SourceLocation ELoc = ConsumeToken();
4388     ExprResult Tail = ParseAssignmentExpression();
4389     Tail =
4390         Actions.ActOnFinishFullExpr(Tail.get(), ELoc, /*DiscardedValue*/ false);
4391     if (Tail.isUsable())
4392       Data.DepModOrTailExpr = Tail.get();
4393     else
4394       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4395                 StopBeforeMatch);
4396   }
4397 
4398   // Parse ')'.
4399   Data.RLoc = Tok.getLocation();
4400   if (!T.consumeClose())
4401     Data.RLoc = T.getCloseLocation();
4402   // Exit from scope when the iterator is used in depend clause.
4403   if (HasIterator)
4404     ExitScope();
4405   return (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) ||
4406          (MustHaveTail && !Data.DepModOrTailExpr) || InvalidReductionId ||
4407          IsInvalidMapperModifier;
4408 }
4409 
4410 /// Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate',
4411 /// 'shared', 'copyin', 'copyprivate', 'flush', 'reduction', 'task_reduction',
4412 /// 'in_reduction', 'nontemporal', 'exclusive' or 'inclusive'.
4413 ///
4414 ///    private-clause:
4415 ///       'private' '(' list ')'
4416 ///    firstprivate-clause:
4417 ///       'firstprivate' '(' list ')'
4418 ///    lastprivate-clause:
4419 ///       'lastprivate' '(' list ')'
4420 ///    shared-clause:
4421 ///       'shared' '(' list ')'
4422 ///    linear-clause:
4423 ///       'linear' '(' linear-list [ ':' linear-step ] ')'
4424 ///    aligned-clause:
4425 ///       'aligned' '(' list [ ':' alignment ] ')'
4426 ///    reduction-clause:
4427 ///       'reduction' '(' [ modifier ',' ] reduction-identifier ':' list ')'
4428 ///    task_reduction-clause:
4429 ///       'task_reduction' '(' reduction-identifier ':' list ')'
4430 ///    in_reduction-clause:
4431 ///       'in_reduction' '(' reduction-identifier ':' list ')'
4432 ///    copyprivate-clause:
4433 ///       'copyprivate' '(' list ')'
4434 ///    flush-clause:
4435 ///       'flush' '(' list ')'
4436 ///    depend-clause:
4437 ///       'depend' '(' in | out | inout : list | source ')'
4438 ///    map-clause:
4439 ///       'map' '(' [ [ always [,] ] [ close [,] ]
4440 ///          [ mapper '(' mapper-identifier ')' [,] ]
4441 ///          to | from | tofrom | alloc | release | delete ':' ] list ')';
4442 ///    to-clause:
4443 ///       'to' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
4444 ///    from-clause:
4445 ///       'from' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
4446 ///    use_device_ptr-clause:
4447 ///       'use_device_ptr' '(' list ')'
4448 ///    use_device_addr-clause:
4449 ///       'use_device_addr' '(' list ')'
4450 ///    is_device_ptr-clause:
4451 ///       'is_device_ptr' '(' list ')'
4452 ///    allocate-clause:
4453 ///       'allocate' '(' [ allocator ':' ] list ')'
4454 ///    nontemporal-clause:
4455 ///       'nontemporal' '(' list ')'
4456 ///    inclusive-clause:
4457 ///       'inclusive' '(' list ')'
4458 ///    exclusive-clause:
4459 ///       'exclusive' '(' list ')'
4460 ///
4461 /// For 'linear' clause linear-list may have the following forms:
4462 ///  list
4463 ///  modifier(list)
4464 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
4465 OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
4466                                             OpenMPClauseKind Kind,
4467                                             bool ParseOnly) {
4468   SourceLocation Loc = Tok.getLocation();
4469   SourceLocation LOpen = ConsumeToken();
4470   SmallVector<Expr *, 4> Vars;
4471   OpenMPVarListDataTy Data;
4472 
4473   if (ParseOpenMPVarList(DKind, Kind, Vars, Data))
4474     return nullptr;
4475 
4476   if (ParseOnly)
4477     return nullptr;
4478   OMPVarListLocTy Locs(Loc, LOpen, Data.RLoc);
4479   return Actions.ActOnOpenMPVarListClause(
4480       Kind, Vars, Data.DepModOrTailExpr, Locs, Data.ColonLoc,
4481       Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId,
4482       Data.ExtraModifier, Data.MapTypeModifiers, Data.MapTypeModifiersLoc,
4483       Data.IsMapTypeImplicit, Data.ExtraModifierLoc, Data.MotionModifiers,
4484       Data.MotionModifiersLoc);
4485 }
4486