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/UniqueVector.h"
25 #include "llvm/Frontend/OpenMP/OMPContext.h"
26 
27 using namespace clang;
28 using namespace llvm::omp;
29 
30 //===----------------------------------------------------------------------===//
31 // OpenMP declarative directives.
32 //===----------------------------------------------------------------------===//
33 
34 namespace {
35 enum OpenMPDirectiveKindEx {
36   OMPD_cancellation = unsigned(OMPD_unknown) + 1,
37   OMPD_data,
38   OMPD_declare,
39   OMPD_end,
40   OMPD_end_declare,
41   OMPD_enter,
42   OMPD_exit,
43   OMPD_point,
44   OMPD_reduction,
45   OMPD_target_enter,
46   OMPD_target_exit,
47   OMPD_update,
48   OMPD_distribute_parallel,
49   OMPD_teams_distribute_parallel,
50   OMPD_target_teams_distribute_parallel,
51   OMPD_mapper,
52   OMPD_variant,
53   OMPD_begin,
54   OMPD_begin_declare,
55 };
56 
57 // Helper to unify the enum class OpenMPDirectiveKind with its extension
58 // the OpenMPDirectiveKindEx enum which allows to use them together as if they
59 // are unsigned values.
60 struct OpenMPDirectiveKindExWrapper {
61   OpenMPDirectiveKindExWrapper(unsigned Value) : Value(Value) {}
62   OpenMPDirectiveKindExWrapper(OpenMPDirectiveKind DK) : Value(unsigned(DK)) {}
63   bool operator==(OpenMPDirectiveKind V) const { return Value == unsigned(V); }
64   bool operator!=(OpenMPDirectiveKind V) const { return Value != unsigned(V); }
65   bool operator<(OpenMPDirectiveKind V) const { return Value < unsigned(V); }
66   operator unsigned() const { return Value; }
67   operator OpenMPDirectiveKind() const { return OpenMPDirectiveKind(Value); }
68   unsigned Value;
69 };
70 
71 class DeclDirectiveListParserHelper final {
72   SmallVector<Expr *, 4> Identifiers;
73   Parser *P;
74   OpenMPDirectiveKind Kind;
75 
76 public:
77   DeclDirectiveListParserHelper(Parser *P, OpenMPDirectiveKind Kind)
78       : P(P), Kind(Kind) {}
79   void operator()(CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
80     ExprResult Res = P->getActions().ActOnOpenMPIdExpression(
81         P->getCurScope(), SS, NameInfo, Kind);
82     if (Res.isUsable())
83       Identifiers.push_back(Res.get());
84   }
85   llvm::ArrayRef<Expr *> getIdentifiers() const { return Identifiers; }
86 };
87 } // namespace
88 
89 // Map token string to extended OMP token kind that are
90 // OpenMPDirectiveKind + OpenMPDirectiveKindEx.
91 static unsigned getOpenMPDirectiveKindEx(StringRef S) {
92   OpenMPDirectiveKindExWrapper DKind = getOpenMPDirectiveKind(S);
93   if (DKind != OMPD_unknown)
94     return DKind;
95 
96   return llvm::StringSwitch<OpenMPDirectiveKindExWrapper>(S)
97       .Case("cancellation", OMPD_cancellation)
98       .Case("data", OMPD_data)
99       .Case("declare", OMPD_declare)
100       .Case("end", OMPD_end)
101       .Case("enter", OMPD_enter)
102       .Case("exit", OMPD_exit)
103       .Case("point", OMPD_point)
104       .Case("reduction", OMPD_reduction)
105       .Case("update", OMPD_update)
106       .Case("mapper", OMPD_mapper)
107       .Case("variant", OMPD_variant)
108       .Case("begin", OMPD_begin)
109       .Default(OMPD_unknown);
110 }
111 
112 static OpenMPDirectiveKindExWrapper parseOpenMPDirectiveKind(Parser &P) {
113   // Array of foldings: F[i][0] F[i][1] ===> F[i][2].
114   // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd
115   // TODO: add other combined directives in topological order.
116   static const OpenMPDirectiveKindExWrapper F[][3] = {
117       {OMPD_begin, OMPD_declare, OMPD_begin_declare},
118       {OMPD_end, OMPD_declare, OMPD_end_declare},
119       {OMPD_cancellation, OMPD_point, OMPD_cancellation_point},
120       {OMPD_declare, OMPD_reduction, OMPD_declare_reduction},
121       {OMPD_declare, OMPD_mapper, OMPD_declare_mapper},
122       {OMPD_declare, OMPD_simd, OMPD_declare_simd},
123       {OMPD_declare, OMPD_target, OMPD_declare_target},
124       {OMPD_declare, OMPD_variant, OMPD_declare_variant},
125       {OMPD_begin_declare, OMPD_variant, OMPD_begin_declare_variant},
126       {OMPD_end_declare, OMPD_variant, OMPD_end_declare_variant},
127       {OMPD_distribute, OMPD_parallel, OMPD_distribute_parallel},
128       {OMPD_distribute_parallel, OMPD_for, OMPD_distribute_parallel_for},
129       {OMPD_distribute_parallel_for, OMPD_simd,
130        OMPD_distribute_parallel_for_simd},
131       {OMPD_distribute, OMPD_simd, OMPD_distribute_simd},
132       {OMPD_end_declare, OMPD_target, OMPD_end_declare_target},
133       {OMPD_target, OMPD_data, OMPD_target_data},
134       {OMPD_target, OMPD_enter, OMPD_target_enter},
135       {OMPD_target, OMPD_exit, OMPD_target_exit},
136       {OMPD_target, OMPD_update, OMPD_target_update},
137       {OMPD_target_enter, OMPD_data, OMPD_target_enter_data},
138       {OMPD_target_exit, OMPD_data, OMPD_target_exit_data},
139       {OMPD_for, OMPD_simd, OMPD_for_simd},
140       {OMPD_parallel, OMPD_for, OMPD_parallel_for},
141       {OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd},
142       {OMPD_parallel, OMPD_sections, OMPD_parallel_sections},
143       {OMPD_taskloop, OMPD_simd, OMPD_taskloop_simd},
144       {OMPD_target, OMPD_parallel, OMPD_target_parallel},
145       {OMPD_target, OMPD_simd, OMPD_target_simd},
146       {OMPD_target_parallel, OMPD_for, OMPD_target_parallel_for},
147       {OMPD_target_parallel_for, OMPD_simd, OMPD_target_parallel_for_simd},
148       {OMPD_teams, OMPD_distribute, OMPD_teams_distribute},
149       {OMPD_teams_distribute, OMPD_simd, OMPD_teams_distribute_simd},
150       {OMPD_teams_distribute, OMPD_parallel, OMPD_teams_distribute_parallel},
151       {OMPD_teams_distribute_parallel, OMPD_for,
152        OMPD_teams_distribute_parallel_for},
153       {OMPD_teams_distribute_parallel_for, OMPD_simd,
154        OMPD_teams_distribute_parallel_for_simd},
155       {OMPD_target, OMPD_teams, OMPD_target_teams},
156       {OMPD_target_teams, OMPD_distribute, OMPD_target_teams_distribute},
157       {OMPD_target_teams_distribute, OMPD_parallel,
158        OMPD_target_teams_distribute_parallel},
159       {OMPD_target_teams_distribute, OMPD_simd,
160        OMPD_target_teams_distribute_simd},
161       {OMPD_target_teams_distribute_parallel, OMPD_for,
162        OMPD_target_teams_distribute_parallel_for},
163       {OMPD_target_teams_distribute_parallel_for, OMPD_simd,
164        OMPD_target_teams_distribute_parallel_for_simd},
165       {OMPD_master, OMPD_taskloop, OMPD_master_taskloop},
166       {OMPD_master_taskloop, OMPD_simd, OMPD_master_taskloop_simd},
167       {OMPD_parallel, OMPD_master, OMPD_parallel_master},
168       {OMPD_parallel_master, OMPD_taskloop, OMPD_parallel_master_taskloop},
169       {OMPD_parallel_master_taskloop, OMPD_simd,
170        OMPD_parallel_master_taskloop_simd}};
171   enum { CancellationPoint = 0, DeclareReduction = 1, TargetData = 2 };
172   Token Tok = P.getCurToken();
173   OpenMPDirectiveKindExWrapper DKind =
174       Tok.isAnnotation()
175           ? static_cast<unsigned>(OMPD_unknown)
176           : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
177   if (DKind == OMPD_unknown)
178     return OMPD_unknown;
179 
180   for (unsigned I = 0; I < llvm::array_lengthof(F); ++I) {
181     if (DKind != F[I][0])
182       continue;
183 
184     Tok = P.getPreprocessor().LookAhead(0);
185     OpenMPDirectiveKindExWrapper SDKind =
186         Tok.isAnnotation()
187             ? static_cast<unsigned>(OMPD_unknown)
188             : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
189     if (SDKind == OMPD_unknown)
190       continue;
191 
192     if (SDKind == F[I][1]) {
193       P.ConsumeToken();
194       DKind = F[I][2];
195     }
196   }
197   return DKind < OMPD_unknown ? static_cast<OpenMPDirectiveKind>(DKind)
198                               : OMPD_unknown;
199 }
200 
201 static DeclarationName parseOpenMPReductionId(Parser &P) {
202   Token Tok = P.getCurToken();
203   Sema &Actions = P.getActions();
204   OverloadedOperatorKind OOK = OO_None;
205   // Allow to use 'operator' keyword for C++ operators
206   bool WithOperator = false;
207   if (Tok.is(tok::kw_operator)) {
208     P.ConsumeToken();
209     Tok = P.getCurToken();
210     WithOperator = true;
211   }
212   switch (Tok.getKind()) {
213   case tok::plus: // '+'
214     OOK = OO_Plus;
215     break;
216   case tok::minus: // '-'
217     OOK = OO_Minus;
218     break;
219   case tok::star: // '*'
220     OOK = OO_Star;
221     break;
222   case tok::amp: // '&'
223     OOK = OO_Amp;
224     break;
225   case tok::pipe: // '|'
226     OOK = OO_Pipe;
227     break;
228   case tok::caret: // '^'
229     OOK = OO_Caret;
230     break;
231   case tok::ampamp: // '&&'
232     OOK = OO_AmpAmp;
233     break;
234   case tok::pipepipe: // '||'
235     OOK = OO_PipePipe;
236     break;
237   case tok::identifier: // identifier
238     if (!WithOperator)
239       break;
240     LLVM_FALLTHROUGH;
241   default:
242     P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier);
243     P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
244                 Parser::StopBeforeMatch);
245     return DeclarationName();
246   }
247   P.ConsumeToken();
248   auto &DeclNames = Actions.getASTContext().DeclarationNames;
249   return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo())
250                         : DeclNames.getCXXOperatorName(OOK);
251 }
252 
253 /// Parse 'omp declare reduction' construct.
254 ///
255 ///       declare-reduction-directive:
256 ///        annot_pragma_openmp 'declare' 'reduction'
257 ///        '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')'
258 ///        ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')']
259 ///        annot_pragma_openmp_end
260 /// <reduction_id> is either a base language identifier or one of the following
261 /// operators: '+', '-', '*', '&', '|', '^', '&&' and '||'.
262 ///
263 Parser::DeclGroupPtrTy
264 Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) {
265   // Parse '('.
266   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
267   if (T.expectAndConsume(
268           diag::err_expected_lparen_after,
269           getOpenMPDirectiveName(OMPD_declare_reduction).data())) {
270     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
271     return DeclGroupPtrTy();
272   }
273 
274   DeclarationName Name = parseOpenMPReductionId(*this);
275   if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end))
276     return DeclGroupPtrTy();
277 
278   // Consume ':'.
279   bool IsCorrect = !ExpectAndConsume(tok::colon);
280 
281   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
282     return DeclGroupPtrTy();
283 
284   IsCorrect = IsCorrect && !Name.isEmpty();
285 
286   if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) {
287     Diag(Tok.getLocation(), diag::err_expected_type);
288     IsCorrect = false;
289   }
290 
291   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
292     return DeclGroupPtrTy();
293 
294   SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes;
295   // Parse list of types until ':' token.
296   do {
297     ColonProtectionRAIIObject ColonRAII(*this);
298     SourceRange Range;
299     TypeResult TR =
300         ParseTypeName(&Range, DeclaratorContext::PrototypeContext, AS);
301     if (TR.isUsable()) {
302       QualType ReductionType =
303           Actions.ActOnOpenMPDeclareReductionType(Range.getBegin(), TR);
304       if (!ReductionType.isNull()) {
305         ReductionTypes.push_back(
306             std::make_pair(ReductionType, Range.getBegin()));
307       }
308     } else {
309       SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end,
310                 StopBeforeMatch);
311     }
312 
313     if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end))
314       break;
315 
316     // Consume ','.
317     if (ExpectAndConsume(tok::comma)) {
318       IsCorrect = false;
319       if (Tok.is(tok::annot_pragma_openmp_end)) {
320         Diag(Tok.getLocation(), diag::err_expected_type);
321         return DeclGroupPtrTy();
322       }
323     }
324   } while (Tok.isNot(tok::annot_pragma_openmp_end));
325 
326   if (ReductionTypes.empty()) {
327     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
328     return DeclGroupPtrTy();
329   }
330 
331   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
332     return DeclGroupPtrTy();
333 
334   // Consume ':'.
335   if (ExpectAndConsume(tok::colon))
336     IsCorrect = false;
337 
338   if (Tok.is(tok::annot_pragma_openmp_end)) {
339     Diag(Tok.getLocation(), diag::err_expected_expression);
340     return DeclGroupPtrTy();
341   }
342 
343   DeclGroupPtrTy DRD = Actions.ActOnOpenMPDeclareReductionDirectiveStart(
344       getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes, AS);
345 
346   // Parse <combiner> expression and then parse initializer if any for each
347   // correct type.
348   unsigned I = 0, E = ReductionTypes.size();
349   for (Decl *D : DRD.get()) {
350     TentativeParsingAction TPA(*this);
351     ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
352                                     Scope::CompoundStmtScope |
353                                     Scope::OpenMPDirectiveScope);
354     // Parse <combiner> expression.
355     Actions.ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D);
356     ExprResult CombinerResult = Actions.ActOnFinishFullExpr(
357         ParseExpression().get(), D->getLocation(), /*DiscardedValue*/ false);
358     Actions.ActOnOpenMPDeclareReductionCombinerEnd(D, CombinerResult.get());
359 
360     if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
361         Tok.isNot(tok::annot_pragma_openmp_end)) {
362       TPA.Commit();
363       IsCorrect = false;
364       break;
365     }
366     IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable();
367     ExprResult InitializerResult;
368     if (Tok.isNot(tok::annot_pragma_openmp_end)) {
369       // Parse <initializer> expression.
370       if (Tok.is(tok::identifier) &&
371           Tok.getIdentifierInfo()->isStr("initializer")) {
372         ConsumeToken();
373       } else {
374         Diag(Tok.getLocation(), diag::err_expected) << "'initializer'";
375         TPA.Commit();
376         IsCorrect = false;
377         break;
378       }
379       // Parse '('.
380       BalancedDelimiterTracker T(*this, tok::l_paren,
381                                  tok::annot_pragma_openmp_end);
382       IsCorrect =
383           !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") &&
384           IsCorrect;
385       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
386         ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
387                                         Scope::CompoundStmtScope |
388                                         Scope::OpenMPDirectiveScope);
389         // Parse expression.
390         VarDecl *OmpPrivParm =
391             Actions.ActOnOpenMPDeclareReductionInitializerStart(getCurScope(),
392                                                                 D);
393         // Check if initializer is omp_priv <init_expr> or something else.
394         if (Tok.is(tok::identifier) &&
395             Tok.getIdentifierInfo()->isStr("omp_priv")) {
396           ConsumeToken();
397           ParseOpenMPReductionInitializerForDecl(OmpPrivParm);
398         } else {
399           InitializerResult = Actions.ActOnFinishFullExpr(
400               ParseAssignmentExpression().get(), D->getLocation(),
401               /*DiscardedValue*/ false);
402         }
403         Actions.ActOnOpenMPDeclareReductionInitializerEnd(
404             D, InitializerResult.get(), OmpPrivParm);
405         if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
406             Tok.isNot(tok::annot_pragma_openmp_end)) {
407           TPA.Commit();
408           IsCorrect = false;
409           break;
410         }
411         IsCorrect =
412             !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid();
413       }
414     }
415 
416     ++I;
417     // Revert parsing if not the last type, otherwise accept it, we're done with
418     // parsing.
419     if (I != E)
420       TPA.Revert();
421     else
422       TPA.Commit();
423   }
424   return Actions.ActOnOpenMPDeclareReductionDirectiveEnd(getCurScope(), DRD,
425                                                          IsCorrect);
426 }
427 
428 void Parser::ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm) {
429   // Parse declarator '=' initializer.
430   // If a '==' or '+=' is found, suggest a fixit to '='.
431   if (isTokenEqualOrEqualTypo()) {
432     ConsumeToken();
433 
434     if (Tok.is(tok::code_completion)) {
435       Actions.CodeCompleteInitializer(getCurScope(), OmpPrivParm);
436       Actions.FinalizeDeclaration(OmpPrivParm);
437       cutOffParsing();
438       return;
439     }
440 
441     PreferredType.enterVariableInit(Tok.getLocation(), OmpPrivParm);
442     ExprResult Init = ParseInitializer();
443 
444     if (Init.isInvalid()) {
445       SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
446       Actions.ActOnInitializerError(OmpPrivParm);
447     } else {
448       Actions.AddInitializerToDecl(OmpPrivParm, Init.get(),
449                                    /*DirectInit=*/false);
450     }
451   } else if (Tok.is(tok::l_paren)) {
452     // Parse C++ direct initializer: '(' expression-list ')'
453     BalancedDelimiterTracker T(*this, tok::l_paren);
454     T.consumeOpen();
455 
456     ExprVector Exprs;
457     CommaLocsTy CommaLocs;
458 
459     SourceLocation LParLoc = T.getOpenLocation();
460     auto RunSignatureHelp = [this, OmpPrivParm, LParLoc, &Exprs]() {
461       QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
462           getCurScope(), OmpPrivParm->getType()->getCanonicalTypeInternal(),
463           OmpPrivParm->getLocation(), Exprs, LParLoc);
464       CalledSignatureHelp = true;
465       return PreferredType;
466     };
467     if (ParseExpressionList(Exprs, CommaLocs, [&] {
468           PreferredType.enterFunctionArgument(Tok.getLocation(),
469                                               RunSignatureHelp);
470         })) {
471       if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
472         RunSignatureHelp();
473       Actions.ActOnInitializerError(OmpPrivParm);
474       SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
475     } else {
476       // Match the ')'.
477       SourceLocation RLoc = Tok.getLocation();
478       if (!T.consumeClose())
479         RLoc = T.getCloseLocation();
480 
481       assert(!Exprs.empty() && Exprs.size() - 1 == CommaLocs.size() &&
482              "Unexpected number of commas!");
483 
484       ExprResult Initializer =
485           Actions.ActOnParenListExpr(T.getOpenLocation(), RLoc, Exprs);
486       Actions.AddInitializerToDecl(OmpPrivParm, Initializer.get(),
487                                    /*DirectInit=*/true);
488     }
489   } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
490     // Parse C++0x braced-init-list.
491     Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
492 
493     ExprResult Init(ParseBraceInitializer());
494 
495     if (Init.isInvalid()) {
496       Actions.ActOnInitializerError(OmpPrivParm);
497     } else {
498       Actions.AddInitializerToDecl(OmpPrivParm, Init.get(),
499                                    /*DirectInit=*/true);
500     }
501   } else {
502     Actions.ActOnUninitializedDecl(OmpPrivParm);
503   }
504 }
505 
506 /// Parses 'omp declare mapper' directive.
507 ///
508 ///       declare-mapper-directive:
509 ///         annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifier> ':']
510 ///         <type> <var> ')' [<clause>[[,] <clause>] ... ]
511 ///         annot_pragma_openmp_end
512 /// <mapper-identifier> and <var> are base language identifiers.
513 ///
514 Parser::DeclGroupPtrTy
515 Parser::ParseOpenMPDeclareMapperDirective(AccessSpecifier AS) {
516   bool IsCorrect = true;
517   // Parse '('
518   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
519   if (T.expectAndConsume(diag::err_expected_lparen_after,
520                          getOpenMPDirectiveName(OMPD_declare_mapper).data())) {
521     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
522     return DeclGroupPtrTy();
523   }
524 
525   // Parse <mapper-identifier>
526   auto &DeclNames = Actions.getASTContext().DeclarationNames;
527   DeclarationName MapperId;
528   if (PP.LookAhead(0).is(tok::colon)) {
529     if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
530       Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
531       IsCorrect = false;
532     } else {
533       MapperId = DeclNames.getIdentifier(Tok.getIdentifierInfo());
534     }
535     ConsumeToken();
536     // Consume ':'.
537     ExpectAndConsume(tok::colon);
538   } else {
539     // If no mapper identifier is provided, its name is "default" by default
540     MapperId =
541         DeclNames.getIdentifier(&Actions.getASTContext().Idents.get("default"));
542   }
543 
544   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
545     return DeclGroupPtrTy();
546 
547   // Parse <type> <var>
548   DeclarationName VName;
549   QualType MapperType;
550   SourceRange Range;
551   TypeResult ParsedType = parseOpenMPDeclareMapperVarDecl(Range, VName, AS);
552   if (ParsedType.isUsable())
553     MapperType =
554         Actions.ActOnOpenMPDeclareMapperType(Range.getBegin(), ParsedType);
555   if (MapperType.isNull())
556     IsCorrect = false;
557   if (!IsCorrect) {
558     SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch);
559     return DeclGroupPtrTy();
560   }
561 
562   // Consume ')'.
563   IsCorrect &= !T.consumeClose();
564   if (!IsCorrect) {
565     SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch);
566     return DeclGroupPtrTy();
567   }
568 
569   // Enter scope.
570   OMPDeclareMapperDecl *DMD = Actions.ActOnOpenMPDeclareMapperDirectiveStart(
571       getCurScope(), Actions.getCurLexicalContext(), MapperId, MapperType,
572       Range.getBegin(), VName, AS);
573   DeclarationNameInfo DirName;
574   SourceLocation Loc = Tok.getLocation();
575   unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
576                         Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope;
577   ParseScope OMPDirectiveScope(this, ScopeFlags);
578   Actions.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, getCurScope(), Loc);
579 
580   // Add the mapper variable declaration.
581   Actions.ActOnOpenMPDeclareMapperDirectiveVarDecl(
582       DMD, getCurScope(), MapperType, Range.getBegin(), VName);
583 
584   // Parse map clauses.
585   SmallVector<OMPClause *, 6> Clauses;
586   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
587     OpenMPClauseKind CKind = Tok.isAnnotation()
588                                  ? OMPC_unknown
589                                  : getOpenMPClauseKind(PP.getSpelling(Tok));
590     Actions.StartOpenMPClause(CKind);
591     OMPClause *Clause =
592         ParseOpenMPClause(OMPD_declare_mapper, CKind, Clauses.size() == 0);
593     if (Clause)
594       Clauses.push_back(Clause);
595     else
596       IsCorrect = false;
597     // Skip ',' if any.
598     if (Tok.is(tok::comma))
599       ConsumeToken();
600     Actions.EndOpenMPClause();
601   }
602   if (Clauses.empty()) {
603     Diag(Tok, diag::err_omp_expected_clause)
604         << getOpenMPDirectiveName(OMPD_declare_mapper);
605     IsCorrect = false;
606   }
607 
608   // Exit scope.
609   Actions.EndOpenMPDSABlock(nullptr);
610   OMPDirectiveScope.Exit();
611 
612   DeclGroupPtrTy DGP =
613       Actions.ActOnOpenMPDeclareMapperDirectiveEnd(DMD, getCurScope(), Clauses);
614   if (!IsCorrect)
615     return DeclGroupPtrTy();
616   return DGP;
617 }
618 
619 TypeResult Parser::parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
620                                                    DeclarationName &Name,
621                                                    AccessSpecifier AS) {
622   // Parse the common declaration-specifiers piece.
623   Parser::DeclSpecContext DSC = Parser::DeclSpecContext::DSC_type_specifier;
624   DeclSpec DS(AttrFactory);
625   ParseSpecifierQualifierList(DS, AS, DSC);
626 
627   // Parse the declarator.
628   DeclaratorContext Context = DeclaratorContext::PrototypeContext;
629   Declarator DeclaratorInfo(DS, Context);
630   ParseDeclarator(DeclaratorInfo);
631   Range = DeclaratorInfo.getSourceRange();
632   if (DeclaratorInfo.getIdentifier() == nullptr) {
633     Diag(Tok.getLocation(), diag::err_omp_mapper_expected_declarator);
634     return true;
635   }
636   Name = Actions.GetNameForDeclarator(DeclaratorInfo).getName();
637 
638   return Actions.ActOnOpenMPDeclareMapperVarDecl(getCurScope(), DeclaratorInfo);
639 }
640 
641 namespace {
642 /// RAII that recreates function context for correct parsing of clauses of
643 /// 'declare simd' construct.
644 /// OpenMP, 2.8.2 declare simd Construct
645 /// The expressions appearing in the clauses of this directive are evaluated in
646 /// the scope of the arguments of the function declaration or definition.
647 class FNContextRAII final {
648   Parser &P;
649   Sema::CXXThisScopeRAII *ThisScope;
650   Parser::ParseScope *TempScope;
651   Parser::ParseScope *FnScope;
652   bool HasTemplateScope = false;
653   bool HasFunScope = false;
654   FNContextRAII() = delete;
655   FNContextRAII(const FNContextRAII &) = delete;
656   FNContextRAII &operator=(const FNContextRAII &) = delete;
657 
658 public:
659   FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P) {
660     Decl *D = *Ptr.get().begin();
661     NamedDecl *ND = dyn_cast<NamedDecl>(D);
662     RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
663     Sema &Actions = P.getActions();
664 
665     // Allow 'this' within late-parsed attributes.
666     ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, Qualifiers(),
667                                            ND && ND->isCXXInstanceMember());
668 
669     // If the Decl is templatized, add template parameters to scope.
670     HasTemplateScope = D->isTemplateDecl();
671     TempScope =
672         new Parser::ParseScope(&P, Scope::TemplateParamScope, HasTemplateScope);
673     if (HasTemplateScope)
674       Actions.ActOnReenterTemplateScope(Actions.getCurScope(), D);
675 
676     // If the Decl is on a function, add function parameters to the scope.
677     HasFunScope = D->isFunctionOrFunctionTemplate();
678     FnScope = new Parser::ParseScope(
679         &P, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
680         HasFunScope);
681     if (HasFunScope)
682       Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D);
683   }
684   ~FNContextRAII() {
685     if (HasFunScope) {
686       P.getActions().ActOnExitFunctionContext();
687       FnScope->Exit(); // Pop scope, and remove Decls from IdResolver
688     }
689     if (HasTemplateScope)
690       TempScope->Exit();
691     delete FnScope;
692     delete TempScope;
693     delete ThisScope;
694   }
695 };
696 } // namespace
697 
698 /// Parses clauses for 'declare simd' directive.
699 ///    clause:
700 ///      'inbranch' | 'notinbranch'
701 ///      'simdlen' '(' <expr> ')'
702 ///      { 'uniform' '(' <argument_list> ')' }
703 ///      { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' }
704 ///      { 'linear '(' <argument_list> [ ':' <step> ] ')' }
705 static bool parseDeclareSimdClauses(
706     Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen,
707     SmallVectorImpl<Expr *> &Uniforms, SmallVectorImpl<Expr *> &Aligneds,
708     SmallVectorImpl<Expr *> &Alignments, SmallVectorImpl<Expr *> &Linears,
709     SmallVectorImpl<unsigned> &LinModifiers, SmallVectorImpl<Expr *> &Steps) {
710   SourceRange BSRange;
711   const Token &Tok = P.getCurToken();
712   bool IsError = false;
713   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
714     if (Tok.isNot(tok::identifier))
715       break;
716     OMPDeclareSimdDeclAttr::BranchStateTy Out;
717     IdentifierInfo *II = Tok.getIdentifierInfo();
718     StringRef ClauseName = II->getName();
719     // Parse 'inranch|notinbranch' clauses.
720     if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) {
721       if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) {
722         P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch)
723             << ClauseName
724             << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange;
725         IsError = true;
726       }
727       BS = Out;
728       BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc());
729       P.ConsumeToken();
730     } else if (ClauseName.equals("simdlen")) {
731       if (SimdLen.isUsable()) {
732         P.Diag(Tok, diag::err_omp_more_one_clause)
733             << getOpenMPDirectiveName(OMPD_declare_simd) << ClauseName << 0;
734         IsError = true;
735       }
736       P.ConsumeToken();
737       SourceLocation RLoc;
738       SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc);
739       if (SimdLen.isInvalid())
740         IsError = true;
741     } else {
742       OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName);
743       if (CKind == OMPC_uniform || CKind == OMPC_aligned ||
744           CKind == OMPC_linear) {
745         Parser::OpenMPVarListDataTy Data;
746         SmallVectorImpl<Expr *> *Vars = &Uniforms;
747         if (CKind == OMPC_aligned) {
748           Vars = &Aligneds;
749         } else if (CKind == OMPC_linear) {
750           Data.ExtraModifier = OMPC_LINEAR_val;
751           Vars = &Linears;
752         }
753 
754         P.ConsumeToken();
755         if (P.ParseOpenMPVarList(OMPD_declare_simd,
756                                  getOpenMPClauseKind(ClauseName), *Vars, Data))
757           IsError = true;
758         if (CKind == OMPC_aligned) {
759           Alignments.append(Aligneds.size() - Alignments.size(),
760                             Data.DepModOrTailExpr);
761         } else if (CKind == OMPC_linear) {
762           assert(0 <= Data.ExtraModifier &&
763                  Data.ExtraModifier <= OMPC_LINEAR_unknown &&
764                  "Unexpected linear modifier.");
765           if (P.getActions().CheckOpenMPLinearModifier(
766                   static_cast<OpenMPLinearClauseKind>(Data.ExtraModifier),
767                   Data.ExtraModifierLoc))
768             Data.ExtraModifier = OMPC_LINEAR_val;
769           LinModifiers.append(Linears.size() - LinModifiers.size(),
770                               Data.ExtraModifier);
771           Steps.append(Linears.size() - Steps.size(), Data.DepModOrTailExpr);
772         }
773       } else
774         // TODO: add parsing of other clauses.
775         break;
776     }
777     // Skip ',' if any.
778     if (Tok.is(tok::comma))
779       P.ConsumeToken();
780   }
781   return IsError;
782 }
783 
784 /// Parse clauses for '#pragma omp declare simd'.
785 Parser::DeclGroupPtrTy
786 Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr,
787                                    CachedTokens &Toks, SourceLocation Loc) {
788   PP.EnterToken(Tok, /*IsReinject*/ true);
789   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
790                       /*IsReinject*/ true);
791   // Consume the previously pushed token.
792   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
793   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
794 
795   FNContextRAII FnContext(*this, Ptr);
796   OMPDeclareSimdDeclAttr::BranchStateTy BS =
797       OMPDeclareSimdDeclAttr::BS_Undefined;
798   ExprResult Simdlen;
799   SmallVector<Expr *, 4> Uniforms;
800   SmallVector<Expr *, 4> Aligneds;
801   SmallVector<Expr *, 4> Alignments;
802   SmallVector<Expr *, 4> Linears;
803   SmallVector<unsigned, 4> LinModifiers;
804   SmallVector<Expr *, 4> Steps;
805   bool IsError =
806       parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds,
807                               Alignments, Linears, LinModifiers, Steps);
808   skipUntilPragmaOpenMPEnd(OMPD_declare_simd);
809   // Skip the last annot_pragma_openmp_end.
810   SourceLocation EndLoc = ConsumeAnnotationToken();
811   if (IsError)
812     return Ptr;
813   return Actions.ActOnOpenMPDeclareSimdDirective(
814       Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears,
815       LinModifiers, Steps, SourceRange(Loc, EndLoc));
816 }
817 
818 namespace {
819 /// Constant used in the diagnostics to distinguish the levels in an OpenMP
820 /// contexts: selector-set={selector(trait, ...), ...}, ....
821 enum OMPContextLvl {
822   CONTEXT_SELECTOR_SET_LVL = 0,
823   CONTEXT_SELECTOR_LVL = 1,
824   CONTEXT_TRAIT_LVL = 2,
825 };
826 
827 static StringRef stringLiteralParser(Parser &P) {
828   ExprResult Res = P.ParseStringLiteralExpression(true);
829   return Res.isUsable() ? Res.getAs<StringLiteral>()->getString() : "";
830 }
831 
832 static StringRef getNameFromIdOrString(Parser &P, Token &Tok,
833                                        OMPContextLvl Lvl) {
834   if (Tok.is(tok::identifier)) {
835     llvm::SmallString<16> Buffer;
836     StringRef Name = P.getPreprocessor().getSpelling(Tok, Buffer);
837     (void)P.ConsumeToken();
838     return Name;
839   }
840 
841   if (tok::isStringLiteral(Tok.getKind()))
842     return stringLiteralParser(P);
843 
844   P.Diag(Tok.getLocation(),
845          diag::warn_omp_declare_variant_string_literal_or_identifier)
846       << Lvl;
847   return "";
848 }
849 
850 static bool checkForDuplicates(Parser &P, StringRef Name,
851                                SourceLocation NameLoc,
852                                llvm::StringMap<SourceLocation> &Seen,
853                                OMPContextLvl Lvl) {
854   auto Res = Seen.try_emplace(Name, NameLoc);
855   if (Res.second)
856     return false;
857 
858   // Each trait-set-selector-name, trait-selector-name and trait-name can
859   // only be specified once.
860   P.Diag(NameLoc, diag::warn_omp_declare_variant_ctx_mutiple_use)
861       << Lvl << Name;
862   P.Diag(Res.first->getValue(), diag::note_omp_declare_variant_ctx_used_here)
863       << Lvl << Name;
864   return true;
865 }
866 } // namespace
867 
868 void Parser::parseOMPTraitPropertyKind(
869     OMPTraitProperty &TIProperty, llvm::omp::TraitSet Set,
870     llvm::omp::TraitSelector Selector, llvm::StringMap<SourceLocation> &Seen) {
871   TIProperty.Kind = TraitProperty::invalid;
872 
873   SourceLocation NameLoc = Tok.getLocation();
874   StringRef Name =
875       getNameFromIdOrString(*this, Tok, CONTEXT_TRAIT_LVL);
876   if (Name.empty()) {
877     Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
878         << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector);
879     return;
880   }
881 
882   TIProperty.Kind = getOpenMPContextTraitPropertyKind(Set, Name);
883   if (TIProperty.Kind != TraitProperty::invalid) {
884     if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_TRAIT_LVL))
885       TIProperty.Kind = TraitProperty::invalid;
886     return;
887   }
888 
889   // It follows diagnosis and helping notes.
890   // FIXME: We should move the diagnosis string generation into libFrontend.
891   Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_property)
892       << Name << getOpenMPContextTraitSelectorName(Selector)
893       << getOpenMPContextTraitSetName(Set);
894 
895   TraitSet SetForName = getOpenMPContextTraitSetKind(Name);
896   if (SetForName != TraitSet::invalid) {
897     Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
898         << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_TRAIT_LVL;
899     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
900         << Name << "<selector-name>"
901         << "(<property-name>)";
902     return;
903   }
904   TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name);
905   if (SelectorForName != TraitSelector::invalid) {
906     Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
907         << Name << CONTEXT_SELECTOR_LVL << CONTEXT_TRAIT_LVL;
908     bool AllowsTraitScore = false;
909     bool RequiresProperty = false;
910     isValidTraitSelectorForTraitSet(
911         SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName),
912         AllowsTraitScore, RequiresProperty);
913     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
914         << getOpenMPContextTraitSetName(
915                getOpenMPContextTraitSetForSelector(SelectorForName))
916         << Name << (RequiresProperty ? "(<property-name>)" : "");
917     return;
918   }
919   for (const auto &PotentialSet :
920        {TraitSet::construct, TraitSet::user, TraitSet::implementation,
921         TraitSet::device}) {
922     TraitProperty PropertyForName =
923         getOpenMPContextTraitPropertyKind(PotentialSet, Name);
924     if (PropertyForName == TraitProperty::invalid)
925       continue;
926     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
927         << getOpenMPContextTraitSetName(
928                getOpenMPContextTraitSetForProperty(PropertyForName))
929         << getOpenMPContextTraitSelectorName(
930                getOpenMPContextTraitSelectorForProperty(PropertyForName))
931         << ("(" + Name + ")").str();
932     return;
933   }
934   Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
935       << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector);
936 }
937 
938 static bool checkExtensionProperty(Parser &P, SourceLocation Loc,
939                                    OMPTraitProperty &TIProperty,
940                                    OMPTraitSelector &TISelector,
941                                    llvm::StringMap<SourceLocation> &Seen) {
942   assert(TISelector.Kind ==
943              llvm::omp::TraitSelector::implementation_extension &&
944          "Only for extension properties, e.g., "
945          "`implementation={extension(PROPERTY)}`");
946   if (TIProperty.Kind == TraitProperty::invalid)
947     return false;
948 
949   auto IsMatchExtension = [](OMPTraitProperty &TP) {
950     return (TP.Kind ==
951                 llvm::omp::TraitProperty::implementation_extension_match_all ||
952             TP.Kind ==
953                 llvm::omp::TraitProperty::implementation_extension_match_any ||
954             TP.Kind ==
955                 llvm::omp::TraitProperty::implementation_extension_match_none);
956   };
957 
958   if (IsMatchExtension(TIProperty)) {
959     for (OMPTraitProperty &SeenProp : TISelector.Properties)
960       if (IsMatchExtension(SeenProp)) {
961         P.Diag(Loc, diag::err_omp_variant_ctx_second_match_extension);
962         StringRef SeenName =
963             llvm::omp::getOpenMPContextTraitPropertyName(SeenProp.Kind);
964         SourceLocation SeenLoc = Seen[SeenName];
965         P.Diag(SeenLoc, diag::note_omp_declare_variant_ctx_used_here)
966             << CONTEXT_TRAIT_LVL << SeenName;
967         return false;
968       }
969     return true;
970   }
971 
972   llvm_unreachable("Unknown extension property!");
973 }
974 
975 void Parser::parseOMPContextProperty(OMPTraitSelector &TISelector,
976                                      llvm::omp::TraitSet Set,
977                                      llvm::StringMap<SourceLocation> &Seen) {
978   assert(TISelector.Kind != TraitSelector::user_condition &&
979          "User conditions are special properties not handled here!");
980 
981   SourceLocation PropertyLoc = Tok.getLocation();
982   OMPTraitProperty TIProperty;
983   parseOMPTraitPropertyKind(TIProperty, Set, TISelector.Kind, Seen);
984 
985   if (TISelector.Kind == llvm::omp::TraitSelector::implementation_extension)
986     if (!checkExtensionProperty(*this, Tok.getLocation(), TIProperty,
987                                 TISelector, Seen))
988       TIProperty.Kind = TraitProperty::invalid;
989 
990   // If we have an invalid property here we already issued a warning.
991   if (TIProperty.Kind == TraitProperty::invalid) {
992     if (PropertyLoc != Tok.getLocation())
993       Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
994           << CONTEXT_TRAIT_LVL;
995     return;
996   }
997 
998   if (isValidTraitPropertyForTraitSetAndSelector(TIProperty.Kind,
999                                                  TISelector.Kind, Set)) {
1000 
1001     // If we make it here the property, selector, set, score, condition, ... are
1002     // all valid (or have been corrected). Thus we can record the property.
1003     TISelector.Properties.push_back(TIProperty);
1004     return;
1005   }
1006 
1007   Diag(PropertyLoc, diag::warn_omp_ctx_incompatible_property_for_selector)
1008       << getOpenMPContextTraitPropertyName(TIProperty.Kind)
1009       << getOpenMPContextTraitSelectorName(TISelector.Kind)
1010       << getOpenMPContextTraitSetName(Set);
1011   Diag(PropertyLoc, diag::note_omp_ctx_compatible_set_and_selector_for_property)
1012       << getOpenMPContextTraitPropertyName(TIProperty.Kind)
1013       << getOpenMPContextTraitSelectorName(
1014              getOpenMPContextTraitSelectorForProperty(TIProperty.Kind))
1015       << getOpenMPContextTraitSetName(
1016              getOpenMPContextTraitSetForProperty(TIProperty.Kind));
1017   Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1018       << CONTEXT_TRAIT_LVL;
1019 }
1020 
1021 void Parser::parseOMPTraitSelectorKind(
1022     OMPTraitSelector &TISelector, llvm::omp::TraitSet Set,
1023     llvm::StringMap<SourceLocation> &Seen) {
1024   TISelector.Kind = TraitSelector::invalid;
1025 
1026   SourceLocation NameLoc = Tok.getLocation();
1027   StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_LVL
1028                     );
1029   if (Name.empty()) {
1030     Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
1031         << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set);
1032     return;
1033   }
1034 
1035   TISelector.Kind = getOpenMPContextTraitSelectorKind(Name);
1036   if (TISelector.Kind != TraitSelector::invalid) {
1037     if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_SELECTOR_LVL))
1038       TISelector.Kind = TraitSelector::invalid;
1039     return;
1040   }
1041 
1042   // It follows diagnosis and helping notes.
1043   Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_selector)
1044       << Name << getOpenMPContextTraitSetName(Set);
1045 
1046   TraitSet SetForName = getOpenMPContextTraitSetKind(Name);
1047   if (SetForName != TraitSet::invalid) {
1048     Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1049         << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_SELECTOR_LVL;
1050     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1051         << Name << "<selector-name>"
1052         << "<property-name>";
1053     return;
1054   }
1055   for (const auto &PotentialSet :
1056        {TraitSet::construct, TraitSet::user, TraitSet::implementation,
1057         TraitSet::device}) {
1058     TraitProperty PropertyForName =
1059         getOpenMPContextTraitPropertyKind(PotentialSet, Name);
1060     if (PropertyForName == TraitProperty::invalid)
1061       continue;
1062     Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1063         << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_LVL;
1064     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1065         << getOpenMPContextTraitSetName(
1066                getOpenMPContextTraitSetForProperty(PropertyForName))
1067         << getOpenMPContextTraitSelectorName(
1068                getOpenMPContextTraitSelectorForProperty(PropertyForName))
1069         << ("(" + Name + ")").str();
1070     return;
1071   }
1072   Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
1073       << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set);
1074 }
1075 
1076 /// Parse optional 'score' '(' <expr> ')' ':'.
1077 static ExprResult parseContextScore(Parser &P) {
1078   ExprResult ScoreExpr;
1079   llvm::SmallString<16> Buffer;
1080   StringRef SelectorName =
1081       P.getPreprocessor().getSpelling(P.getCurToken(), Buffer);
1082   if (!SelectorName.equals("score"))
1083     return ScoreExpr;
1084   (void)P.ConsumeToken();
1085   SourceLocation RLoc;
1086   ScoreExpr = P.ParseOpenMPParensExpr(SelectorName, RLoc);
1087   // Parse ':'
1088   if (P.getCurToken().is(tok::colon))
1089     (void)P.ConsumeAnyToken();
1090   else
1091     P.Diag(P.getCurToken(), diag::warn_omp_declare_variant_expected)
1092         << "':'"
1093         << "score expression";
1094   return ScoreExpr;
1095 }
1096 
1097 /// Parses an OpenMP context selector.
1098 ///
1099 /// <trait-selector-name> ['('[<trait-score>] <trait-property> [, <t-p>]* ')']
1100 void Parser::parseOMPContextSelector(
1101     OMPTraitSelector &TISelector, llvm::omp::TraitSet Set,
1102     llvm::StringMap<SourceLocation> &SeenSelectors) {
1103   unsigned short OuterPC = ParenCount;
1104 
1105   // If anything went wrong we issue an error or warning and then skip the rest
1106   // of the selector. However, commas are ambiguous so we look for the nesting
1107   // of parentheses here as well.
1108   auto FinishSelector = [OuterPC, this]() -> void {
1109     bool Done = false;
1110     while (!Done) {
1111       while (!SkipUntil({tok::r_brace, tok::r_paren, tok::comma,
1112                          tok::annot_pragma_openmp_end},
1113                         StopBeforeMatch))
1114         ;
1115       if (Tok.is(tok::r_paren) && OuterPC > ParenCount)
1116         (void)ConsumeParen();
1117       if (OuterPC <= ParenCount) {
1118         Done = true;
1119         break;
1120       }
1121       if (!Tok.is(tok::comma) && !Tok.is(tok::r_paren)) {
1122         Done = true;
1123         break;
1124       }
1125       (void)ConsumeAnyToken();
1126     }
1127     Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1128         << CONTEXT_SELECTOR_LVL;
1129   };
1130 
1131   SourceLocation SelectorLoc = Tok.getLocation();
1132   parseOMPTraitSelectorKind(TISelector, Set, SeenSelectors);
1133   if (TISelector.Kind == TraitSelector::invalid)
1134     return FinishSelector();
1135 
1136   bool AllowsTraitScore = false;
1137   bool RequiresProperty = false;
1138   if (!isValidTraitSelectorForTraitSet(TISelector.Kind, Set, AllowsTraitScore,
1139                                        RequiresProperty)) {
1140     Diag(SelectorLoc, diag::warn_omp_ctx_incompatible_selector_for_set)
1141         << getOpenMPContextTraitSelectorName(TISelector.Kind)
1142         << getOpenMPContextTraitSetName(Set);
1143     Diag(SelectorLoc, diag::note_omp_ctx_compatible_set_for_selector)
1144         << getOpenMPContextTraitSelectorName(TISelector.Kind)
1145         << getOpenMPContextTraitSetName(
1146                getOpenMPContextTraitSetForSelector(TISelector.Kind))
1147         << RequiresProperty;
1148     return FinishSelector();
1149   }
1150 
1151   if (!RequiresProperty) {
1152     TISelector.Properties.push_back(
1153         {getOpenMPContextTraitPropertyForSelector(TISelector.Kind)});
1154     return;
1155   }
1156 
1157   if (!Tok.is(tok::l_paren)) {
1158     Diag(SelectorLoc, diag::warn_omp_ctx_selector_without_properties)
1159         << getOpenMPContextTraitSelectorName(TISelector.Kind)
1160         << getOpenMPContextTraitSetName(Set);
1161     return FinishSelector();
1162   }
1163 
1164   if (TISelector.Kind == TraitSelector::user_condition) {
1165     SourceLocation RLoc;
1166     ExprResult Condition = ParseOpenMPParensExpr("user condition", RLoc);
1167     if (!Condition.isUsable())
1168       return FinishSelector();
1169     TISelector.ScoreOrCondition = Condition.get();
1170     TISelector.Properties.push_back({TraitProperty::user_condition_unknown});
1171     return;
1172   }
1173 
1174   BalancedDelimiterTracker BDT(*this, tok::l_paren,
1175                                tok::annot_pragma_openmp_end);
1176   // Parse '('.
1177   (void)BDT.consumeOpen();
1178 
1179   SourceLocation ScoreLoc = Tok.getLocation();
1180   ExprResult Score = parseContextScore(*this);
1181 
1182   if (!AllowsTraitScore && !Score.isUnset()) {
1183     if (Score.isUsable()) {
1184       Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property)
1185           << getOpenMPContextTraitSelectorName(TISelector.Kind)
1186           << getOpenMPContextTraitSetName(Set) << Score.get();
1187     } else {
1188       Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property)
1189           << getOpenMPContextTraitSelectorName(TISelector.Kind)
1190           << getOpenMPContextTraitSetName(Set) << "<invalid>";
1191     }
1192     Score = ExprResult();
1193   }
1194 
1195   if (Score.isUsable())
1196     TISelector.ScoreOrCondition = Score.get();
1197 
1198   llvm::StringMap<SourceLocation> SeenProperties;
1199   do {
1200     parseOMPContextProperty(TISelector, Set, SeenProperties);
1201   } while (TryConsumeToken(tok::comma));
1202 
1203   // Parse ')'.
1204   BDT.consumeClose();
1205 }
1206 
1207 void Parser::parseOMPTraitSetKind(OMPTraitSet &TISet,
1208                                   llvm::StringMap<SourceLocation> &Seen) {
1209   TISet.Kind = TraitSet::invalid;
1210 
1211   SourceLocation NameLoc = Tok.getLocation();
1212   StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_SET_LVL
1213                    );
1214   if (Name.empty()) {
1215     Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
1216         << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets();
1217     return;
1218   }
1219 
1220   TISet.Kind = getOpenMPContextTraitSetKind(Name);
1221   if (TISet.Kind != TraitSet::invalid) {
1222     if (checkForDuplicates(*this, Name, NameLoc, Seen,
1223                            CONTEXT_SELECTOR_SET_LVL))
1224       TISet.Kind = TraitSet::invalid;
1225     return;
1226   }
1227 
1228   // It follows diagnosis and helping notes.
1229   Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_set) << Name;
1230 
1231   TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name);
1232   if (SelectorForName != TraitSelector::invalid) {
1233     Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1234         << Name << CONTEXT_SELECTOR_LVL << CONTEXT_SELECTOR_SET_LVL;
1235     bool AllowsTraitScore = false;
1236     bool RequiresProperty = false;
1237     isValidTraitSelectorForTraitSet(
1238         SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName),
1239         AllowsTraitScore, RequiresProperty);
1240     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1241         << getOpenMPContextTraitSetName(
1242                getOpenMPContextTraitSetForSelector(SelectorForName))
1243         << Name << (RequiresProperty ? "(<property-name>)" : "");
1244     return;
1245   }
1246   for (const auto &PotentialSet :
1247        {TraitSet::construct, TraitSet::user, TraitSet::implementation,
1248         TraitSet::device}) {
1249     TraitProperty PropertyForName =
1250         getOpenMPContextTraitPropertyKind(PotentialSet, Name);
1251     if (PropertyForName == TraitProperty::invalid)
1252       continue;
1253     Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1254         << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_SET_LVL;
1255     Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1256         << getOpenMPContextTraitSetName(
1257                getOpenMPContextTraitSetForProperty(PropertyForName))
1258         << getOpenMPContextTraitSelectorName(
1259                getOpenMPContextTraitSelectorForProperty(PropertyForName))
1260         << ("(" + Name + ")").str();
1261     return;
1262   }
1263   Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
1264       << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets();
1265 }
1266 
1267 /// Parses an OpenMP context selector set.
1268 ///
1269 /// <trait-set-selector-name> '=' '{' <trait-selector> [, <trait-selector>]* '}'
1270 void Parser::parseOMPContextSelectorSet(
1271     OMPTraitSet &TISet,
1272     llvm::StringMap<SourceLocation> &SeenSets) {
1273   auto OuterBC = BraceCount;
1274 
1275   // If anything went wrong we issue an error or warning and then skip the rest
1276   // of the set. However, commas are ambiguous so we look for the nesting
1277   // of braces here as well.
1278   auto FinishSelectorSet = [this, OuterBC]() -> void {
1279     bool Done = false;
1280     while (!Done) {
1281       while (!SkipUntil({tok::comma, tok::r_brace, tok::r_paren,
1282                          tok::annot_pragma_openmp_end},
1283                         StopBeforeMatch))
1284         ;
1285       if (Tok.is(tok::r_brace) && OuterBC > BraceCount)
1286         (void)ConsumeBrace();
1287       if (OuterBC <= BraceCount) {
1288         Done = true;
1289         break;
1290       }
1291       if (!Tok.is(tok::comma) && !Tok.is(tok::r_brace)) {
1292         Done = true;
1293         break;
1294       }
1295       (void)ConsumeAnyToken();
1296     }
1297     Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1298         << CONTEXT_SELECTOR_SET_LVL;
1299   };
1300 
1301   parseOMPTraitSetKind(TISet, SeenSets);
1302   if (TISet.Kind == TraitSet::invalid)
1303     return FinishSelectorSet();
1304 
1305   // Parse '='.
1306   if (!TryConsumeToken(tok::equal))
1307     Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
1308         << "="
1309         << ("context set name \"" + getOpenMPContextTraitSetName(TISet.Kind) +
1310             "\"")
1311                .str();
1312 
1313   // Parse '{'.
1314   if (Tok.is(tok::l_brace)) {
1315     (void)ConsumeBrace();
1316   } else {
1317     Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
1318         << "{"
1319         << ("'=' that follows the context set name \"" +
1320             getOpenMPContextTraitSetName(TISet.Kind) + "\"")
1321                .str();
1322   }
1323 
1324   llvm::StringMap<SourceLocation> SeenSelectors;
1325   do {
1326     OMPTraitSelector TISelector;
1327     parseOMPContextSelector(TISelector, TISet.Kind, SeenSelectors);
1328     if (TISelector.Kind != TraitSelector::invalid &&
1329         !TISelector.Properties.empty())
1330       TISet.Selectors.push_back(TISelector);
1331   } while (TryConsumeToken(tok::comma));
1332 
1333   // Parse '}'.
1334   if (Tok.is(tok::r_brace)) {
1335     (void)ConsumeBrace();
1336   } else {
1337     Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
1338         << "}"
1339         << ("context selectors for the context set \"" +
1340             getOpenMPContextTraitSetName(TISet.Kind) + "\"")
1341                .str();
1342   }
1343 }
1344 
1345 /// Parse OpenMP context selectors:
1346 ///
1347 /// <trait-set-selector> [, <trait-set-selector>]*
1348 bool Parser::parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo& TI) {
1349   llvm::StringMap<SourceLocation> SeenSets;
1350   do {
1351     OMPTraitSet TISet;
1352     parseOMPContextSelectorSet(TISet, SeenSets);
1353     if (TISet.Kind != TraitSet::invalid && !TISet.Selectors.empty())
1354       TI.Sets.push_back(TISet);
1355   } while (TryConsumeToken(tok::comma));
1356 
1357   return false;
1358 }
1359 
1360 /// Parse clauses for '#pragma omp declare variant ( variant-func-id ) clause'.
1361 void Parser::ParseOMPDeclareVariantClauses(Parser::DeclGroupPtrTy Ptr,
1362                                            CachedTokens &Toks,
1363                                            SourceLocation Loc) {
1364   PP.EnterToken(Tok, /*IsReinject*/ true);
1365   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1366                       /*IsReinject*/ true);
1367   // Consume the previously pushed token.
1368   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1369   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1370 
1371   FNContextRAII FnContext(*this, Ptr);
1372   // Parse function declaration id.
1373   SourceLocation RLoc;
1374   // Parse with IsAddressOfOperand set to true to parse methods as DeclRefExprs
1375   // instead of MemberExprs.
1376   ExprResult AssociatedFunction;
1377   {
1378     // Do not mark function as is used to prevent its emission if this is the
1379     // only place where it is used.
1380     EnterExpressionEvaluationContext Unevaluated(
1381         Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1382     AssociatedFunction = ParseOpenMPParensExpr(
1383         getOpenMPDirectiveName(OMPD_declare_variant), RLoc,
1384         /*IsAddressOfOperand=*/true);
1385   }
1386   if (!AssociatedFunction.isUsable()) {
1387     if (!Tok.is(tok::annot_pragma_openmp_end))
1388       while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch))
1389         ;
1390     // Skip the last annot_pragma_openmp_end.
1391     (void)ConsumeAnnotationToken();
1392     return;
1393   }
1394 
1395   OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo();
1396   if (parseOMPDeclareVariantMatchClause(Loc, TI))
1397     return;
1398 
1399   Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
1400       Actions.checkOpenMPDeclareVariantFunction(
1401           Ptr, AssociatedFunction.get(), TI,
1402           SourceRange(Loc, Tok.getLocation()));
1403 
1404   // Skip last tokens.
1405   while (Tok.isNot(tok::annot_pragma_openmp_end))
1406     ConsumeAnyToken();
1407   if (DeclVarData && !TI.Sets.empty())
1408     Actions.ActOnOpenMPDeclareVariantDirective(
1409         DeclVarData->first, DeclVarData->second, TI,
1410         SourceRange(Loc, Tok.getLocation()));
1411 
1412   // Skip the last annot_pragma_openmp_end.
1413   (void)ConsumeAnnotationToken();
1414 }
1415 
1416 bool Parser::parseOMPDeclareVariantMatchClause(SourceLocation Loc,
1417                                                OMPTraitInfo &TI) {
1418   // Parse 'match'.
1419   OpenMPClauseKind CKind = Tok.isAnnotation()
1420                                ? OMPC_unknown
1421                                : getOpenMPClauseKind(PP.getSpelling(Tok));
1422   if (CKind != OMPC_match) {
1423     Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
1424         << getOpenMPClauseName(OMPC_match);
1425     while (!SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch))
1426       ;
1427     // Skip the last annot_pragma_openmp_end.
1428     (void)ConsumeAnnotationToken();
1429     return true;
1430   }
1431   (void)ConsumeToken();
1432   // Parse '('.
1433   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1434   if (T.expectAndConsume(diag::err_expected_lparen_after,
1435                          getOpenMPClauseName(OMPC_match).data())) {
1436     while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch))
1437       ;
1438     // Skip the last annot_pragma_openmp_end.
1439     (void)ConsumeAnnotationToken();
1440     return true;
1441   }
1442 
1443   // Parse inner context selectors.
1444   parseOMPContextSelectors(Loc, TI);
1445 
1446   // Parse ')'
1447   (void)T.consumeClose();
1448   return false;
1449 }
1450 
1451 /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
1452 ///
1453 ///    default-clause:
1454 ///         'default' '(' 'none' | 'shared' ')
1455 ///
1456 ///    proc_bind-clause:
1457 ///         'proc_bind' '(' 'master' | 'close' | 'spread' ')
1458 ///
1459 ///    device_type-clause:
1460 ///         'device_type' '(' 'host' | 'nohost' | 'any' )'
1461 namespace {
1462   struct SimpleClauseData {
1463     unsigned Type;
1464     SourceLocation Loc;
1465     SourceLocation LOpen;
1466     SourceLocation TypeLoc;
1467     SourceLocation RLoc;
1468     SimpleClauseData(unsigned Type, SourceLocation Loc, SourceLocation LOpen,
1469                      SourceLocation TypeLoc, SourceLocation RLoc)
1470         : Type(Type), Loc(Loc), LOpen(LOpen), TypeLoc(TypeLoc), RLoc(RLoc) {}
1471   };
1472 } // anonymous namespace
1473 
1474 static Optional<SimpleClauseData>
1475 parseOpenMPSimpleClause(Parser &P, OpenMPClauseKind Kind) {
1476   const Token &Tok = P.getCurToken();
1477   SourceLocation Loc = Tok.getLocation();
1478   SourceLocation LOpen = P.ConsumeToken();
1479   // Parse '('.
1480   BalancedDelimiterTracker T(P, tok::l_paren, tok::annot_pragma_openmp_end);
1481   if (T.expectAndConsume(diag::err_expected_lparen_after,
1482                          getOpenMPClauseName(Kind).data()))
1483     return llvm::None;
1484 
1485   unsigned Type = getOpenMPSimpleClauseType(
1486       Kind, Tok.isAnnotation() ? "" : P.getPreprocessor().getSpelling(Tok));
1487   SourceLocation TypeLoc = Tok.getLocation();
1488   if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1489       Tok.isNot(tok::annot_pragma_openmp_end))
1490     P.ConsumeAnyToken();
1491 
1492   // Parse ')'.
1493   SourceLocation RLoc = Tok.getLocation();
1494   if (!T.consumeClose())
1495     RLoc = T.getCloseLocation();
1496 
1497   return SimpleClauseData(Type, Loc, LOpen, TypeLoc, RLoc);
1498 }
1499 
1500 Parser::DeclGroupPtrTy Parser::ParseOMPDeclareTargetClauses() {
1501   // OpenMP 4.5 syntax with list of entities.
1502   Sema::NamedDeclSetType SameDirectiveDecls;
1503   SmallVector<std::tuple<OMPDeclareTargetDeclAttr::MapTypeTy, SourceLocation,
1504                          NamedDecl *>,
1505               4>
1506       DeclareTargetDecls;
1507   OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any;
1508   SourceLocation DeviceTypeLoc;
1509   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1510     OMPDeclareTargetDeclAttr::MapTypeTy MT = OMPDeclareTargetDeclAttr::MT_To;
1511     if (Tok.is(tok::identifier)) {
1512       IdentifierInfo *II = Tok.getIdentifierInfo();
1513       StringRef ClauseName = II->getName();
1514       bool IsDeviceTypeClause =
1515           getLangOpts().OpenMP >= 50 &&
1516           getOpenMPClauseKind(ClauseName) == OMPC_device_type;
1517       // Parse 'to|link|device_type' clauses.
1518       if (!OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName, MT) &&
1519           !IsDeviceTypeClause) {
1520         Diag(Tok, diag::err_omp_declare_target_unexpected_clause)
1521             << ClauseName << (getLangOpts().OpenMP >= 50 ? 1 : 0);
1522         break;
1523       }
1524       // Parse 'device_type' clause and go to next clause if any.
1525       if (IsDeviceTypeClause) {
1526         Optional<SimpleClauseData> DevTypeData =
1527             parseOpenMPSimpleClause(*this, OMPC_device_type);
1528         if (DevTypeData.hasValue()) {
1529           if (DeviceTypeLoc.isValid()) {
1530             // We already saw another device_type clause, diagnose it.
1531             Diag(DevTypeData.getValue().Loc,
1532                  diag::warn_omp_more_one_device_type_clause);
1533           }
1534           switch(static_cast<OpenMPDeviceType>(DevTypeData.getValue().Type)) {
1535           case OMPC_DEVICE_TYPE_any:
1536             DT = OMPDeclareTargetDeclAttr::DT_Any;
1537             break;
1538           case OMPC_DEVICE_TYPE_host:
1539             DT = OMPDeclareTargetDeclAttr::DT_Host;
1540             break;
1541           case OMPC_DEVICE_TYPE_nohost:
1542             DT = OMPDeclareTargetDeclAttr::DT_NoHost;
1543             break;
1544           case OMPC_DEVICE_TYPE_unknown:
1545             llvm_unreachable("Unexpected device_type");
1546           }
1547           DeviceTypeLoc = DevTypeData.getValue().Loc;
1548         }
1549         continue;
1550       }
1551       ConsumeToken();
1552     }
1553     auto &&Callback = [this, MT, &DeclareTargetDecls, &SameDirectiveDecls](
1554                           CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
1555       NamedDecl *ND = Actions.lookupOpenMPDeclareTargetName(
1556           getCurScope(), SS, NameInfo, SameDirectiveDecls);
1557       if (ND)
1558         DeclareTargetDecls.emplace_back(MT, NameInfo.getLoc(), ND);
1559     };
1560     if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback,
1561                                  /*AllowScopeSpecifier=*/true))
1562       break;
1563 
1564     // Consume optional ','.
1565     if (Tok.is(tok::comma))
1566       ConsumeToken();
1567   }
1568   SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1569   ConsumeAnyToken();
1570   for (auto &MTLocDecl : DeclareTargetDecls) {
1571     OMPDeclareTargetDeclAttr::MapTypeTy MT;
1572     SourceLocation Loc;
1573     NamedDecl *ND;
1574     std::tie(MT, Loc, ND) = MTLocDecl;
1575     // device_type clause is applied only to functions.
1576     Actions.ActOnOpenMPDeclareTargetName(
1577         ND, Loc, MT, isa<VarDecl>(ND) ? OMPDeclareTargetDeclAttr::DT_Any : DT);
1578   }
1579   SmallVector<Decl *, 4> Decls(SameDirectiveDecls.begin(),
1580                                SameDirectiveDecls.end());
1581   if (Decls.empty())
1582     return DeclGroupPtrTy();
1583   return Actions.BuildDeclaratorGroup(Decls);
1584 }
1585 
1586 void Parser::skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind) {
1587   // The last seen token is annot_pragma_openmp_end - need to check for
1588   // extra tokens.
1589   if (Tok.is(tok::annot_pragma_openmp_end))
1590     return;
1591 
1592   Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
1593       << getOpenMPDirectiveName(DKind);
1594   while (Tok.isNot(tok::annot_pragma_openmp_end))
1595     ConsumeAnyToken();
1596 }
1597 
1598 void Parser::parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
1599                                   OpenMPDirectiveKind ExpectedKind,
1600                                   OpenMPDirectiveKind FoundKind,
1601                                   SourceLocation BeginLoc,
1602                                   SourceLocation FoundLoc,
1603                                   bool SkipUntilOpenMPEnd) {
1604   int DiagSelection = ExpectedKind == OMPD_end_declare_target ? 0 : 1;
1605 
1606   if (FoundKind == ExpectedKind) {
1607     ConsumeAnyToken();
1608     skipUntilPragmaOpenMPEnd(ExpectedKind);
1609     return;
1610   }
1611 
1612   Diag(FoundLoc, diag::err_expected_end_declare_target_or_variant)
1613       << DiagSelection;
1614   Diag(BeginLoc, diag::note_matching)
1615       << ("'#pragma omp " + getOpenMPDirectiveName(BeginKind) + "'").str();
1616   if (SkipUntilOpenMPEnd)
1617     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1618 }
1619 
1620 void Parser::ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind,
1621                                                SourceLocation DKLoc) {
1622   parseOMPEndDirective(OMPD_declare_target, OMPD_end_declare_target, DKind,
1623                        DKLoc, Tok.getLocation(),
1624                        /* SkipUntilOpenMPEnd */ false);
1625   // Skip the last annot_pragma_openmp_end.
1626   if (Tok.is(tok::annot_pragma_openmp_end))
1627     ConsumeAnnotationToken();
1628 }
1629 
1630 /// Parsing of declarative OpenMP directives.
1631 ///
1632 ///       threadprivate-directive:
1633 ///         annot_pragma_openmp 'threadprivate' simple-variable-list
1634 ///         annot_pragma_openmp_end
1635 ///
1636 ///       allocate-directive:
1637 ///         annot_pragma_openmp 'allocate' simple-variable-list [<clause>]
1638 ///         annot_pragma_openmp_end
1639 ///
1640 ///       declare-reduction-directive:
1641 ///        annot_pragma_openmp 'declare' 'reduction' [...]
1642 ///        annot_pragma_openmp_end
1643 ///
1644 ///       declare-mapper-directive:
1645 ///         annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
1646 ///         <type> <var> ')' [<clause>[[,] <clause>] ... ]
1647 ///         annot_pragma_openmp_end
1648 ///
1649 ///       declare-simd-directive:
1650 ///         annot_pragma_openmp 'declare simd' {<clause> [,]}
1651 ///         annot_pragma_openmp_end
1652 ///         <function declaration/definition>
1653 ///
1654 ///       requires directive:
1655 ///         annot_pragma_openmp 'requires' <clause> [[[,] <clause>] ... ]
1656 ///         annot_pragma_openmp_end
1657 ///
1658 Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
1659     AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, bool Delayed,
1660     DeclSpec::TST TagType, Decl *Tag) {
1661   assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
1662   ParsingOpenMPDirectiveRAII DirScope(*this);
1663   ParenBraceBracketBalancer BalancerRAIIObj(*this);
1664 
1665   SourceLocation Loc;
1666   OpenMPDirectiveKind DKind;
1667   if (Delayed) {
1668     TentativeParsingAction TPA(*this);
1669     Loc = ConsumeAnnotationToken();
1670     DKind = parseOpenMPDirectiveKind(*this);
1671     if (DKind == OMPD_declare_reduction || DKind == OMPD_declare_mapper) {
1672       // Need to delay parsing until completion of the parent class.
1673       TPA.Revert();
1674       CachedTokens Toks;
1675       unsigned Cnt = 1;
1676       Toks.push_back(Tok);
1677       while (Cnt && Tok.isNot(tok::eof)) {
1678         (void)ConsumeAnyToken();
1679         if (Tok.is(tok::annot_pragma_openmp))
1680           ++Cnt;
1681         else if (Tok.is(tok::annot_pragma_openmp_end))
1682           --Cnt;
1683         Toks.push_back(Tok);
1684       }
1685       // Skip last annot_pragma_openmp_end.
1686       if (Cnt == 0)
1687         (void)ConsumeAnyToken();
1688       auto *LP = new LateParsedPragma(this, AS);
1689       LP->takeToks(Toks);
1690       getCurrentClass().LateParsedDeclarations.push_back(LP);
1691       return nullptr;
1692     }
1693     TPA.Commit();
1694   } else {
1695     Loc = ConsumeAnnotationToken();
1696     DKind = parseOpenMPDirectiveKind(*this);
1697   }
1698 
1699   switch (DKind) {
1700   case OMPD_threadprivate: {
1701     ConsumeToken();
1702     DeclDirectiveListParserHelper Helper(this, DKind);
1703     if (!ParseOpenMPSimpleVarList(DKind, Helper,
1704                                   /*AllowScopeSpecifier=*/true)) {
1705       skipUntilPragmaOpenMPEnd(DKind);
1706       // Skip the last annot_pragma_openmp_end.
1707       ConsumeAnnotationToken();
1708       return Actions.ActOnOpenMPThreadprivateDirective(Loc,
1709                                                        Helper.getIdentifiers());
1710     }
1711     break;
1712   }
1713   case OMPD_allocate: {
1714     ConsumeToken();
1715     DeclDirectiveListParserHelper Helper(this, DKind);
1716     if (!ParseOpenMPSimpleVarList(DKind, Helper,
1717                                   /*AllowScopeSpecifier=*/true)) {
1718       SmallVector<OMPClause *, 1> Clauses;
1719       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
1720         SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
1721                     unsigned(OMPC_unknown) + 1>
1722           FirstClauses(unsigned(OMPC_unknown) + 1);
1723         while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1724           OpenMPClauseKind CKind =
1725               Tok.isAnnotation() ? OMPC_unknown
1726                                  : getOpenMPClauseKind(PP.getSpelling(Tok));
1727           Actions.StartOpenMPClause(CKind);
1728           OMPClause *Clause = ParseOpenMPClause(
1729               OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt());
1730           SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
1731                     StopBeforeMatch);
1732           FirstClauses[unsigned(CKind)].setInt(true);
1733           if (Clause != nullptr)
1734             Clauses.push_back(Clause);
1735           if (Tok.is(tok::annot_pragma_openmp_end)) {
1736             Actions.EndOpenMPClause();
1737             break;
1738           }
1739           // Skip ',' if any.
1740           if (Tok.is(tok::comma))
1741             ConsumeToken();
1742           Actions.EndOpenMPClause();
1743         }
1744         skipUntilPragmaOpenMPEnd(DKind);
1745       }
1746       // Skip the last annot_pragma_openmp_end.
1747       ConsumeAnnotationToken();
1748       return Actions.ActOnOpenMPAllocateDirective(Loc, Helper.getIdentifiers(),
1749                                                   Clauses);
1750     }
1751     break;
1752   }
1753   case OMPD_requires: {
1754     SourceLocation StartLoc = ConsumeToken();
1755     SmallVector<OMPClause *, 5> Clauses;
1756     SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
1757                 unsigned(OMPC_unknown) + 1>
1758     FirstClauses(unsigned(OMPC_unknown) + 1);
1759     if (Tok.is(tok::annot_pragma_openmp_end)) {
1760       Diag(Tok, diag::err_omp_expected_clause)
1761           << getOpenMPDirectiveName(OMPD_requires);
1762       break;
1763     }
1764     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1765       OpenMPClauseKind CKind = Tok.isAnnotation()
1766                                    ? OMPC_unknown
1767                                    : getOpenMPClauseKind(PP.getSpelling(Tok));
1768       Actions.StartOpenMPClause(CKind);
1769       OMPClause *Clause = ParseOpenMPClause(
1770           OMPD_requires, CKind, !FirstClauses[unsigned(CKind)].getInt());
1771       SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
1772                 StopBeforeMatch);
1773       FirstClauses[unsigned(CKind)].setInt(true);
1774       if (Clause != nullptr)
1775         Clauses.push_back(Clause);
1776       if (Tok.is(tok::annot_pragma_openmp_end)) {
1777         Actions.EndOpenMPClause();
1778         break;
1779       }
1780       // Skip ',' if any.
1781       if (Tok.is(tok::comma))
1782         ConsumeToken();
1783       Actions.EndOpenMPClause();
1784     }
1785     // Consume final annot_pragma_openmp_end
1786     if (Clauses.empty()) {
1787       Diag(Tok, diag::err_omp_expected_clause)
1788           << getOpenMPDirectiveName(OMPD_requires);
1789       ConsumeAnnotationToken();
1790       return nullptr;
1791     }
1792     ConsumeAnnotationToken();
1793     return Actions.ActOnOpenMPRequiresDirective(StartLoc, Clauses);
1794   }
1795   case OMPD_declare_reduction:
1796     ConsumeToken();
1797     if (DeclGroupPtrTy Res = ParseOpenMPDeclareReductionDirective(AS)) {
1798       skipUntilPragmaOpenMPEnd(OMPD_declare_reduction);
1799       // Skip the last annot_pragma_openmp_end.
1800       ConsumeAnnotationToken();
1801       return Res;
1802     }
1803     break;
1804   case OMPD_declare_mapper: {
1805     ConsumeToken();
1806     if (DeclGroupPtrTy Res = ParseOpenMPDeclareMapperDirective(AS)) {
1807       // Skip the last annot_pragma_openmp_end.
1808       ConsumeAnnotationToken();
1809       return Res;
1810     }
1811     break;
1812   }
1813   case OMPD_begin_declare_variant: {
1814     // The syntax is:
1815     // { #pragma omp begin declare variant clause }
1816     // <function-declaration-or-definition-sequence>
1817     // { #pragma omp end declare variant }
1818     //
1819     ConsumeToken();
1820     OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo();
1821     if (parseOMPDeclareVariantMatchClause(Loc, TI))
1822       break;
1823 
1824     // Skip last tokens.
1825     skipUntilPragmaOpenMPEnd(OMPD_begin_declare_variant);
1826 
1827     ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
1828 
1829     VariantMatchInfo VMI;
1830     ASTContext &ASTCtx = Actions.getASTContext();
1831     TI.getAsVariantMatchInfo(ASTCtx, VMI);
1832     OMPContext OMPCtx(ASTCtx.getLangOpts().OpenMPIsDevice,
1833                       ASTCtx.getTargetInfo().getTriple());
1834 
1835     if (isVariantApplicableInContext(VMI, OMPCtx, /* DeviceSetOnly */ true)) {
1836       Actions.ActOnOpenMPBeginDeclareVariant(Loc, TI);
1837       break;
1838     }
1839 
1840     // Elide all the code till the matching end declare variant was found.
1841     unsigned Nesting = 1;
1842     SourceLocation DKLoc;
1843     OpenMPDirectiveKind DK = OMPD_unknown;
1844     do {
1845       DKLoc = Tok.getLocation();
1846       DK = parseOpenMPDirectiveKind(*this);
1847       if (DK == OMPD_end_declare_variant)
1848         --Nesting;
1849       else if (DK == OMPD_begin_declare_variant)
1850         ++Nesting;
1851       if (!Nesting || isEofOrEom())
1852         break;
1853       ConsumeAnyToken();
1854     } while (true);
1855 
1856     parseOMPEndDirective(OMPD_begin_declare_variant, OMPD_end_declare_variant,
1857                          DK, Loc, DKLoc, /* SkipUntilOpenMPEnd */ true);
1858     if (isEofOrEom())
1859       return nullptr;
1860     break;
1861   }
1862   case OMPD_end_declare_variant: {
1863     if (Actions.isInOpenMPDeclareVariantScope())
1864       Actions.ActOnOpenMPEndDeclareVariant();
1865     else
1866       Diag(Loc, diag::err_expected_begin_declare_variant);
1867     ConsumeToken();
1868     break;
1869   }
1870   case OMPD_declare_variant:
1871   case OMPD_declare_simd: {
1872     // The syntax is:
1873     // { #pragma omp declare {simd|variant} }
1874     // <function-declaration-or-definition>
1875     //
1876     CachedTokens Toks;
1877     Toks.push_back(Tok);
1878     ConsumeToken();
1879     while(Tok.isNot(tok::annot_pragma_openmp_end)) {
1880       Toks.push_back(Tok);
1881       ConsumeAnyToken();
1882     }
1883     Toks.push_back(Tok);
1884     ConsumeAnyToken();
1885 
1886     DeclGroupPtrTy Ptr;
1887     if (Tok.is(tok::annot_pragma_openmp)) {
1888       Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, Delayed,
1889                                                        TagType, Tag);
1890     } else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1891       // Here we expect to see some function declaration.
1892       if (AS == AS_none) {
1893         assert(TagType == DeclSpec::TST_unspecified);
1894         MaybeParseCXX11Attributes(Attrs);
1895         ParsingDeclSpec PDS(*this);
1896         Ptr = ParseExternalDeclaration(Attrs, &PDS);
1897       } else {
1898         Ptr =
1899             ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag);
1900       }
1901     }
1902     if (!Ptr) {
1903       Diag(Loc, diag::err_omp_decl_in_declare_simd_variant)
1904           << (DKind == OMPD_declare_simd ? 0 : 1);
1905       return DeclGroupPtrTy();
1906     }
1907     if (DKind == OMPD_declare_simd)
1908       return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc);
1909     assert(DKind == OMPD_declare_variant &&
1910            "Expected declare variant directive only");
1911     ParseOMPDeclareVariantClauses(Ptr, Toks, Loc);
1912     return Ptr;
1913   }
1914   case OMPD_declare_target: {
1915     SourceLocation DTLoc = ConsumeAnyToken();
1916     if (Tok.isNot(tok::annot_pragma_openmp_end)) {
1917       return ParseOMPDeclareTargetClauses();
1918     }
1919 
1920     // Skip the last annot_pragma_openmp_end.
1921     ConsumeAnyToken();
1922 
1923     if (!Actions.ActOnStartOpenMPDeclareTargetDirective(DTLoc))
1924       return DeclGroupPtrTy();
1925 
1926     ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
1927     llvm::SmallVector<Decl *, 4>  Decls;
1928     DKind = parseOpenMPDirectiveKind(*this);
1929     while (DKind != OMPD_end_declare_target && Tok.isNot(tok::eof) &&
1930            Tok.isNot(tok::r_brace)) {
1931       DeclGroupPtrTy Ptr;
1932       // Here we expect to see some function declaration.
1933       if (AS == AS_none) {
1934         assert(TagType == DeclSpec::TST_unspecified);
1935         MaybeParseCXX11Attributes(Attrs);
1936         ParsingDeclSpec PDS(*this);
1937         Ptr = ParseExternalDeclaration(Attrs, &PDS);
1938       } else {
1939         Ptr =
1940             ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag);
1941       }
1942       if (Ptr) {
1943         DeclGroupRef Ref = Ptr.get();
1944         Decls.append(Ref.begin(), Ref.end());
1945       }
1946       if (Tok.isAnnotation() && Tok.is(tok::annot_pragma_openmp)) {
1947         TentativeParsingAction TPA(*this);
1948         ConsumeAnnotationToken();
1949         DKind = parseOpenMPDirectiveKind(*this);
1950         if (DKind != OMPD_end_declare_target)
1951           TPA.Revert();
1952         else
1953           TPA.Commit();
1954       }
1955     }
1956 
1957     ParseOMPEndDeclareTargetDirective(DKind, DTLoc);
1958     Actions.ActOnFinishOpenMPDeclareTargetDirective();
1959     return Actions.BuildDeclaratorGroup(Decls);
1960   }
1961   case OMPD_unknown:
1962     Diag(Tok, diag::err_omp_unknown_directive);
1963     break;
1964   case OMPD_parallel:
1965   case OMPD_simd:
1966   case OMPD_task:
1967   case OMPD_taskyield:
1968   case OMPD_barrier:
1969   case OMPD_taskwait:
1970   case OMPD_taskgroup:
1971   case OMPD_flush:
1972   case OMPD_depobj:
1973   case OMPD_scan:
1974   case OMPD_for:
1975   case OMPD_for_simd:
1976   case OMPD_sections:
1977   case OMPD_section:
1978   case OMPD_single:
1979   case OMPD_master:
1980   case OMPD_ordered:
1981   case OMPD_critical:
1982   case OMPD_parallel_for:
1983   case OMPD_parallel_for_simd:
1984   case OMPD_parallel_sections:
1985   case OMPD_parallel_master:
1986   case OMPD_atomic:
1987   case OMPD_target:
1988   case OMPD_teams:
1989   case OMPD_cancellation_point:
1990   case OMPD_cancel:
1991   case OMPD_target_data:
1992   case OMPD_target_enter_data:
1993   case OMPD_target_exit_data:
1994   case OMPD_target_parallel:
1995   case OMPD_target_parallel_for:
1996   case OMPD_taskloop:
1997   case OMPD_taskloop_simd:
1998   case OMPD_master_taskloop:
1999   case OMPD_master_taskloop_simd:
2000   case OMPD_parallel_master_taskloop:
2001   case OMPD_parallel_master_taskloop_simd:
2002   case OMPD_distribute:
2003   case OMPD_end_declare_target:
2004   case OMPD_target_update:
2005   case OMPD_distribute_parallel_for:
2006   case OMPD_distribute_parallel_for_simd:
2007   case OMPD_distribute_simd:
2008   case OMPD_target_parallel_for_simd:
2009   case OMPD_target_simd:
2010   case OMPD_teams_distribute:
2011   case OMPD_teams_distribute_simd:
2012   case OMPD_teams_distribute_parallel_for_simd:
2013   case OMPD_teams_distribute_parallel_for:
2014   case OMPD_target_teams:
2015   case OMPD_target_teams_distribute:
2016   case OMPD_target_teams_distribute_parallel_for:
2017   case OMPD_target_teams_distribute_parallel_for_simd:
2018   case OMPD_target_teams_distribute_simd:
2019     Diag(Tok, diag::err_omp_unexpected_directive)
2020         << 1 << getOpenMPDirectiveName(DKind);
2021     break;
2022   }
2023   while (Tok.isNot(tok::annot_pragma_openmp_end))
2024     ConsumeAnyToken();
2025   ConsumeAnyToken();
2026   return nullptr;
2027 }
2028 
2029 /// Parsing of declarative or executable OpenMP directives.
2030 ///
2031 ///       threadprivate-directive:
2032 ///         annot_pragma_openmp 'threadprivate' simple-variable-list
2033 ///         annot_pragma_openmp_end
2034 ///
2035 ///       allocate-directive:
2036 ///         annot_pragma_openmp 'allocate' simple-variable-list
2037 ///         annot_pragma_openmp_end
2038 ///
2039 ///       declare-reduction-directive:
2040 ///         annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':'
2041 ///         <type> {',' <type>} ':' <expression> ')' ['initializer' '('
2042 ///         ('omp_priv' '=' <expression>|<function_call>) ')']
2043 ///         annot_pragma_openmp_end
2044 ///
2045 ///       declare-mapper-directive:
2046 ///         annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
2047 ///         <type> <var> ')' [<clause>[[,] <clause>] ... ]
2048 ///         annot_pragma_openmp_end
2049 ///
2050 ///       executable-directive:
2051 ///         annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
2052 ///         'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
2053 ///         'parallel for' | 'parallel sections' | 'parallel master' | 'task' |
2054 ///         'taskyield' | 'barrier' | 'taskwait' | 'flush' | 'ordered' |
2055 ///         'atomic' | 'for simd' | 'parallel for simd' | 'target' | 'target
2056 ///         data' | 'taskgroup' | 'teams' | 'taskloop' | 'taskloop simd' |
2057 ///         'master taskloop' | 'master taskloop simd' | 'parallel master
2058 ///         taskloop' | 'parallel master taskloop simd' | 'distribute' | 'target
2059 ///         enter data' | 'target exit data' | 'target parallel' | 'target
2060 ///         parallel for' | 'target update' | 'distribute parallel for' |
2061 ///         'distribute paralle for simd' | 'distribute simd' | 'target parallel
2062 ///         for simd' | 'target simd' | 'teams distribute' | 'teams distribute
2063 ///         simd' | 'teams distribute parallel for simd' | 'teams distribute
2064 ///         parallel for' | 'target teams' | 'target teams distribute' | 'target
2065 ///         teams distribute parallel for' | 'target teams distribute parallel
2066 ///         for simd' | 'target teams distribute simd' {clause}
2067 ///         annot_pragma_openmp_end
2068 ///
2069 StmtResult
2070 Parser::ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx) {
2071   assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
2072   ParsingOpenMPDirectiveRAII DirScope(*this);
2073   ParenBraceBracketBalancer BalancerRAIIObj(*this);
2074   SmallVector<OMPClause *, 5> Clauses;
2075   SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
2076               unsigned(OMPC_unknown) + 1>
2077   FirstClauses(unsigned(OMPC_unknown) + 1);
2078   unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
2079                         Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope;
2080   SourceLocation Loc = ConsumeAnnotationToken(), EndLoc;
2081   OpenMPDirectiveKind DKind = parseOpenMPDirectiveKind(*this);
2082   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
2083   // Name of critical directive.
2084   DeclarationNameInfo DirName;
2085   StmtResult Directive = StmtError();
2086   bool HasAssociatedStatement = true;
2087 
2088   switch (DKind) {
2089   case OMPD_threadprivate: {
2090     // FIXME: Should this be permitted in C++?
2091     if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
2092         ParsedStmtContext()) {
2093       Diag(Tok, diag::err_omp_immediate_directive)
2094           << getOpenMPDirectiveName(DKind) << 0;
2095     }
2096     ConsumeToken();
2097     DeclDirectiveListParserHelper Helper(this, DKind);
2098     if (!ParseOpenMPSimpleVarList(DKind, Helper,
2099                                   /*AllowScopeSpecifier=*/false)) {
2100       skipUntilPragmaOpenMPEnd(DKind);
2101       DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective(
2102           Loc, Helper.getIdentifiers());
2103       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2104     }
2105     SkipUntil(tok::annot_pragma_openmp_end);
2106     break;
2107   }
2108   case OMPD_allocate: {
2109     // FIXME: Should this be permitted in C++?
2110     if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
2111         ParsedStmtContext()) {
2112       Diag(Tok, diag::err_omp_immediate_directive)
2113           << getOpenMPDirectiveName(DKind) << 0;
2114     }
2115     ConsumeToken();
2116     DeclDirectiveListParserHelper Helper(this, DKind);
2117     if (!ParseOpenMPSimpleVarList(DKind, Helper,
2118                                   /*AllowScopeSpecifier=*/false)) {
2119       SmallVector<OMPClause *, 1> Clauses;
2120       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
2121         SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
2122                     unsigned(OMPC_unknown) + 1>
2123             FirstClauses(unsigned(OMPC_unknown) + 1);
2124         while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2125           OpenMPClauseKind CKind =
2126               Tok.isAnnotation() ? OMPC_unknown
2127                                  : getOpenMPClauseKind(PP.getSpelling(Tok));
2128           Actions.StartOpenMPClause(CKind);
2129           OMPClause *Clause = ParseOpenMPClause(
2130               OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt());
2131           SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
2132                     StopBeforeMatch);
2133           FirstClauses[unsigned(CKind)].setInt(true);
2134           if (Clause != nullptr)
2135             Clauses.push_back(Clause);
2136           if (Tok.is(tok::annot_pragma_openmp_end)) {
2137             Actions.EndOpenMPClause();
2138             break;
2139           }
2140           // Skip ',' if any.
2141           if (Tok.is(tok::comma))
2142             ConsumeToken();
2143           Actions.EndOpenMPClause();
2144         }
2145         skipUntilPragmaOpenMPEnd(DKind);
2146       }
2147       DeclGroupPtrTy Res = Actions.ActOnOpenMPAllocateDirective(
2148           Loc, Helper.getIdentifiers(), Clauses);
2149       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2150     }
2151     SkipUntil(tok::annot_pragma_openmp_end);
2152     break;
2153   }
2154   case OMPD_declare_reduction:
2155     ConsumeToken();
2156     if (DeclGroupPtrTy Res =
2157             ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) {
2158       skipUntilPragmaOpenMPEnd(OMPD_declare_reduction);
2159       ConsumeAnyToken();
2160       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2161     } else {
2162       SkipUntil(tok::annot_pragma_openmp_end);
2163     }
2164     break;
2165   case OMPD_declare_mapper: {
2166     ConsumeToken();
2167     if (DeclGroupPtrTy Res =
2168             ParseOpenMPDeclareMapperDirective(/*AS=*/AS_none)) {
2169       // Skip the last annot_pragma_openmp_end.
2170       ConsumeAnnotationToken();
2171       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2172     } else {
2173       SkipUntil(tok::annot_pragma_openmp_end);
2174     }
2175     break;
2176   }
2177   case OMPD_flush:
2178   case OMPD_depobj:
2179   case OMPD_scan:
2180   case OMPD_taskyield:
2181   case OMPD_barrier:
2182   case OMPD_taskwait:
2183   case OMPD_cancellation_point:
2184   case OMPD_cancel:
2185   case OMPD_target_enter_data:
2186   case OMPD_target_exit_data:
2187   case OMPD_target_update:
2188     if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2189         ParsedStmtContext()) {
2190       Diag(Tok, diag::err_omp_immediate_directive)
2191           << getOpenMPDirectiveName(DKind) << 0;
2192     }
2193     HasAssociatedStatement = false;
2194     // Fall through for further analysis.
2195     LLVM_FALLTHROUGH;
2196   case OMPD_parallel:
2197   case OMPD_simd:
2198   case OMPD_for:
2199   case OMPD_for_simd:
2200   case OMPD_sections:
2201   case OMPD_single:
2202   case OMPD_section:
2203   case OMPD_master:
2204   case OMPD_critical:
2205   case OMPD_parallel_for:
2206   case OMPD_parallel_for_simd:
2207   case OMPD_parallel_sections:
2208   case OMPD_parallel_master:
2209   case OMPD_task:
2210   case OMPD_ordered:
2211   case OMPD_atomic:
2212   case OMPD_target:
2213   case OMPD_teams:
2214   case OMPD_taskgroup:
2215   case OMPD_target_data:
2216   case OMPD_target_parallel:
2217   case OMPD_target_parallel_for:
2218   case OMPD_taskloop:
2219   case OMPD_taskloop_simd:
2220   case OMPD_master_taskloop:
2221   case OMPD_master_taskloop_simd:
2222   case OMPD_parallel_master_taskloop:
2223   case OMPD_parallel_master_taskloop_simd:
2224   case OMPD_distribute:
2225   case OMPD_distribute_parallel_for:
2226   case OMPD_distribute_parallel_for_simd:
2227   case OMPD_distribute_simd:
2228   case OMPD_target_parallel_for_simd:
2229   case OMPD_target_simd:
2230   case OMPD_teams_distribute:
2231   case OMPD_teams_distribute_simd:
2232   case OMPD_teams_distribute_parallel_for_simd:
2233   case OMPD_teams_distribute_parallel_for:
2234   case OMPD_target_teams:
2235   case OMPD_target_teams_distribute:
2236   case OMPD_target_teams_distribute_parallel_for:
2237   case OMPD_target_teams_distribute_parallel_for_simd:
2238   case OMPD_target_teams_distribute_simd: {
2239     // Special processing for flush and depobj clauses.
2240     Token ImplicitTok;
2241     bool ImplicitClauseAllowed = false;
2242     if (DKind == OMPD_flush || DKind == OMPD_depobj) {
2243       ImplicitTok = Tok;
2244       ImplicitClauseAllowed = true;
2245     }
2246     ConsumeToken();
2247     // Parse directive name of the 'critical' directive if any.
2248     if (DKind == OMPD_critical) {
2249       BalancedDelimiterTracker T(*this, tok::l_paren,
2250                                  tok::annot_pragma_openmp_end);
2251       if (!T.consumeOpen()) {
2252         if (Tok.isAnyIdentifier()) {
2253           DirName =
2254               DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation());
2255           ConsumeAnyToken();
2256         } else {
2257           Diag(Tok, diag::err_omp_expected_identifier_for_critical);
2258         }
2259         T.consumeClose();
2260       }
2261     } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) {
2262       CancelRegion = parseOpenMPDirectiveKind(*this);
2263       if (Tok.isNot(tok::annot_pragma_openmp_end))
2264         ConsumeToken();
2265     }
2266 
2267     if (isOpenMPLoopDirective(DKind))
2268       ScopeFlags |= Scope::OpenMPLoopDirectiveScope;
2269     if (isOpenMPSimdDirective(DKind))
2270       ScopeFlags |= Scope::OpenMPSimdDirectiveScope;
2271     ParseScope OMPDirectiveScope(this, ScopeFlags);
2272     Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc);
2273 
2274     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2275       bool HasImplicitClause = false;
2276       if (ImplicitClauseAllowed && Tok.is(tok::l_paren)) {
2277         HasImplicitClause = true;
2278         // Push copy of the current token back to stream to properly parse
2279         // pseudo-clause OMPFlushClause or OMPDepobjClause.
2280         PP.EnterToken(Tok, /*IsReinject*/ true);
2281         PP.EnterToken(ImplicitTok, /*IsReinject*/ true);
2282         ConsumeAnyToken();
2283       }
2284       OpenMPClauseKind CKind = Tok.isAnnotation()
2285                                    ? OMPC_unknown
2286                                    : getOpenMPClauseKind(PP.getSpelling(Tok));
2287       if (HasImplicitClause) {
2288         assert(CKind == OMPC_unknown && "Must be unknown implicit clause.");
2289         if (DKind == OMPD_flush) {
2290           CKind = OMPC_flush;
2291         } else {
2292           assert(DKind == OMPD_depobj &&
2293                  "Expected flush or depobj directives.");
2294           CKind = OMPC_depobj;
2295         }
2296       }
2297       // No more implicit clauses allowed.
2298       ImplicitClauseAllowed = false;
2299       Actions.StartOpenMPClause(CKind);
2300       HasImplicitClause = false;
2301       OMPClause *Clause = ParseOpenMPClause(
2302           DKind, CKind, !FirstClauses[unsigned(CKind)].getInt());
2303       FirstClauses[unsigned(CKind)].setInt(true);
2304       if (Clause) {
2305         FirstClauses[unsigned(CKind)].setPointer(Clause);
2306         Clauses.push_back(Clause);
2307       }
2308 
2309       // Skip ',' if any.
2310       if (Tok.is(tok::comma))
2311         ConsumeToken();
2312       Actions.EndOpenMPClause();
2313     }
2314     // End location of the directive.
2315     EndLoc = Tok.getLocation();
2316     // Consume final annot_pragma_openmp_end.
2317     ConsumeAnnotationToken();
2318 
2319     // OpenMP [2.13.8, ordered Construct, Syntax]
2320     // If the depend clause is specified, the ordered construct is a stand-alone
2321     // directive.
2322     if (DKind == OMPD_ordered && FirstClauses[unsigned(OMPC_depend)].getInt()) {
2323       if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2324           ParsedStmtContext()) {
2325         Diag(Loc, diag::err_omp_immediate_directive)
2326             << getOpenMPDirectiveName(DKind) << 1
2327             << getOpenMPClauseName(OMPC_depend);
2328       }
2329       HasAssociatedStatement = false;
2330     }
2331 
2332     StmtResult AssociatedStmt;
2333     if (HasAssociatedStatement) {
2334       // The body is a block scope like in Lambdas and Blocks.
2335       Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
2336       // FIXME: We create a bogus CompoundStmt scope to hold the contents of
2337       // the captured region. Code elsewhere assumes that any FunctionScopeInfo
2338       // should have at least one compound statement scope within it.
2339       ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
2340       AssociatedStmt = (Sema::CompoundScopeRAII(Actions), ParseStatement());
2341       AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
2342     } else if (DKind == OMPD_target_update || DKind == OMPD_target_enter_data ||
2343                DKind == OMPD_target_exit_data) {
2344       Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
2345       AssociatedStmt = (Sema::CompoundScopeRAII(Actions),
2346                         Actions.ActOnCompoundStmt(Loc, Loc, llvm::None,
2347                                                   /*isStmtExpr=*/false));
2348       AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
2349     }
2350     Directive = Actions.ActOnOpenMPExecutableDirective(
2351         DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc,
2352         EndLoc);
2353 
2354     // Exit scope.
2355     Actions.EndOpenMPDSABlock(Directive.get());
2356     OMPDirectiveScope.Exit();
2357     break;
2358   }
2359   case OMPD_declare_simd:
2360   case OMPD_declare_target:
2361   case OMPD_end_declare_target:
2362   case OMPD_requires:
2363   case OMPD_begin_declare_variant:
2364   case OMPD_end_declare_variant:
2365   case OMPD_declare_variant:
2366     Diag(Tok, diag::err_omp_unexpected_directive)
2367         << 1 << getOpenMPDirectiveName(DKind);
2368     SkipUntil(tok::annot_pragma_openmp_end);
2369     break;
2370   case OMPD_unknown:
2371     Diag(Tok, diag::err_omp_unknown_directive);
2372     SkipUntil(tok::annot_pragma_openmp_end);
2373     break;
2374   }
2375   return Directive;
2376 }
2377 
2378 // Parses simple list:
2379 //   simple-variable-list:
2380 //         '(' id-expression {, id-expression} ')'
2381 //
2382 bool Parser::ParseOpenMPSimpleVarList(
2383     OpenMPDirectiveKind Kind,
2384     const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2385         Callback,
2386     bool AllowScopeSpecifier) {
2387   // Parse '('.
2388   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
2389   if (T.expectAndConsume(diag::err_expected_lparen_after,
2390                          getOpenMPDirectiveName(Kind).data()))
2391     return true;
2392   bool IsCorrect = true;
2393   bool NoIdentIsFound = true;
2394 
2395   // Read tokens while ')' or annot_pragma_openmp_end is not found.
2396   while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
2397     CXXScopeSpec SS;
2398     UnqualifiedId Name;
2399     // Read var name.
2400     Token PrevTok = Tok;
2401     NoIdentIsFound = false;
2402 
2403     if (AllowScopeSpecifier && getLangOpts().CPlusPlus &&
2404         ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2405                                        /*ObjectHadErrors=*/false, false)) {
2406       IsCorrect = false;
2407       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
2408                 StopBeforeMatch);
2409     } else if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
2410                                   /*ObjectHadErrors=*/false, false, false,
2411                                   false, false, nullptr, Name)) {
2412       IsCorrect = false;
2413       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
2414                 StopBeforeMatch);
2415     } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) &&
2416                Tok.isNot(tok::annot_pragma_openmp_end)) {
2417       IsCorrect = false;
2418       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
2419                 StopBeforeMatch);
2420       Diag(PrevTok.getLocation(), diag::err_expected)
2421           << tok::identifier
2422           << SourceRange(PrevTok.getLocation(), PrevTokLocation);
2423     } else {
2424       Callback(SS, Actions.GetNameFromUnqualifiedId(Name));
2425     }
2426     // Consume ','.
2427     if (Tok.is(tok::comma)) {
2428       ConsumeToken();
2429     }
2430   }
2431 
2432   if (NoIdentIsFound) {
2433     Diag(Tok, diag::err_expected) << tok::identifier;
2434     IsCorrect = false;
2435   }
2436 
2437   // Parse ')'.
2438   IsCorrect = !T.consumeClose() && IsCorrect;
2439 
2440   return !IsCorrect;
2441 }
2442 
2443 OMPClause *Parser::ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind) {
2444   SourceLocation Loc = Tok.getLocation();
2445   ConsumeAnyToken();
2446 
2447   // Parse '('.
2448   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
2449   if (T.expectAndConsume(diag::err_expected_lparen_after, "uses_allocator"))
2450     return nullptr;
2451   SmallVector<Sema::UsesAllocatorsData, 4> Data;
2452   do {
2453     ExprResult Allocator = ParseCXXIdExpression();
2454     if (Allocator.isInvalid()) {
2455       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
2456                 StopBeforeMatch);
2457       break;
2458     }
2459     Sema::UsesAllocatorsData &D = Data.emplace_back();
2460     D.Allocator = Allocator.get();
2461     if (Tok.is(tok::l_paren)) {
2462       BalancedDelimiterTracker T(*this, tok::l_paren,
2463                                  tok::annot_pragma_openmp_end);
2464       T.consumeOpen();
2465       ExprResult AllocatorTraits = ParseCXXIdExpression();
2466       T.consumeClose();
2467       if (AllocatorTraits.isInvalid()) {
2468         SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
2469                   StopBeforeMatch);
2470         break;
2471       }
2472       D.AllocatorTraits = AllocatorTraits.get();
2473       D.LParenLoc = T.getOpenLocation();
2474       D.RParenLoc = T.getCloseLocation();
2475     }
2476     if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren))
2477       Diag(Tok, diag::err_omp_expected_punc) << "uses_allocators" << 0;
2478     // Parse ','
2479     if (Tok.is(tok::comma))
2480       ConsumeAnyToken();
2481   } while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end));
2482   T.consumeClose();
2483   return Actions.ActOnOpenMPUsesAllocatorClause(Loc, T.getOpenLocation(),
2484                                                 T.getCloseLocation(), Data);
2485 }
2486 
2487 /// Parsing of OpenMP clauses.
2488 ///
2489 ///    clause:
2490 ///       if-clause | final-clause | num_threads-clause | safelen-clause |
2491 ///       default-clause | private-clause | firstprivate-clause | shared-clause
2492 ///       | linear-clause | aligned-clause | collapse-clause |
2493 ///       lastprivate-clause | reduction-clause | proc_bind-clause |
2494 ///       schedule-clause | copyin-clause | copyprivate-clause | untied-clause |
2495 ///       mergeable-clause | flush-clause | read-clause | write-clause |
2496 ///       update-clause | capture-clause | seq_cst-clause | device-clause |
2497 ///       simdlen-clause | threads-clause | simd-clause | num_teams-clause |
2498 ///       thread_limit-clause | priority-clause | grainsize-clause |
2499 ///       nogroup-clause | num_tasks-clause | hint-clause | to-clause |
2500 ///       from-clause | is_device_ptr-clause | task_reduction-clause |
2501 ///       in_reduction-clause | allocator-clause | allocate-clause |
2502 ///       acq_rel-clause | acquire-clause | release-clause | relaxed-clause |
2503 ///       depobj-clause | destroy-clause | detach-clause | inclusive-clause |
2504 ///       exclusive-clause | uses_allocators-clause | use_device_addr-clause
2505 ///
2506 OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind,
2507                                      OpenMPClauseKind CKind, bool FirstClause) {
2508   OMPClause *Clause = nullptr;
2509   bool ErrorFound = false;
2510   bool WrongDirective = false;
2511   // Check if clause is allowed for the given directive.
2512   if (CKind != OMPC_unknown &&
2513       !isAllowedClauseForDirective(DKind, CKind, getLangOpts().OpenMP)) {
2514     Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind)
2515                                                << getOpenMPDirectiveName(DKind);
2516     ErrorFound = true;
2517     WrongDirective = true;
2518   }
2519 
2520   switch (CKind) {
2521   case OMPC_final:
2522   case OMPC_num_threads:
2523   case OMPC_safelen:
2524   case OMPC_simdlen:
2525   case OMPC_collapse:
2526   case OMPC_ordered:
2527   case OMPC_num_teams:
2528   case OMPC_thread_limit:
2529   case OMPC_priority:
2530   case OMPC_grainsize:
2531   case OMPC_num_tasks:
2532   case OMPC_hint:
2533   case OMPC_allocator:
2534   case OMPC_depobj:
2535   case OMPC_detach:
2536     // OpenMP [2.5, Restrictions]
2537     //  At most one num_threads clause can appear on the directive.
2538     // OpenMP [2.8.1, simd construct, Restrictions]
2539     //  Only one safelen  clause can appear on a simd directive.
2540     //  Only one simdlen  clause can appear on a simd directive.
2541     //  Only one collapse clause can appear on a simd directive.
2542     // OpenMP [2.11.1, task Construct, Restrictions]
2543     //  At most one if clause can appear on the directive.
2544     //  At most one final clause can appear on the directive.
2545     // OpenMP [teams Construct, Restrictions]
2546     //  At most one num_teams clause can appear on the directive.
2547     //  At most one thread_limit clause can appear on the directive.
2548     // OpenMP [2.9.1, task Construct, Restrictions]
2549     // At most one priority clause can appear on the directive.
2550     // OpenMP [2.9.2, taskloop Construct, Restrictions]
2551     // At most one grainsize clause can appear on the directive.
2552     // OpenMP [2.9.2, taskloop Construct, Restrictions]
2553     // At most one num_tasks clause can appear on the directive.
2554     // OpenMP [2.11.3, allocate Directive, Restrictions]
2555     // At most one allocator clause can appear on the directive.
2556     // OpenMP 5.0, 2.10.1 task Construct, Restrictions.
2557     // At most one detach clause can appear on the directive.
2558     if (!FirstClause) {
2559       Diag(Tok, diag::err_omp_more_one_clause)
2560           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
2561       ErrorFound = true;
2562     }
2563 
2564     if (CKind == OMPC_ordered && PP.LookAhead(/*N=*/0).isNot(tok::l_paren))
2565       Clause = ParseOpenMPClause(CKind, WrongDirective);
2566     else
2567       Clause = ParseOpenMPSingleExprClause(CKind, WrongDirective);
2568     break;
2569   case OMPC_default:
2570   case OMPC_proc_bind:
2571   case OMPC_atomic_default_mem_order:
2572   case OMPC_order:
2573     // OpenMP [2.14.3.1, Restrictions]
2574     //  Only a single default clause may be specified on a parallel, task or
2575     //  teams directive.
2576     // OpenMP [2.5, parallel Construct, Restrictions]
2577     //  At most one proc_bind clause can appear on the directive.
2578     // OpenMP [5.0, Requires directive, Restrictions]
2579     //  At most one atomic_default_mem_order clause can appear
2580     //  on the directive
2581     if (!FirstClause && CKind != OMPC_order) {
2582       Diag(Tok, diag::err_omp_more_one_clause)
2583           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
2584       ErrorFound = true;
2585     }
2586 
2587     Clause = ParseOpenMPSimpleClause(CKind, WrongDirective);
2588     break;
2589   case OMPC_device:
2590   case OMPC_schedule:
2591   case OMPC_dist_schedule:
2592   case OMPC_defaultmap:
2593     // OpenMP [2.7.1, Restrictions, p. 3]
2594     //  Only one schedule clause can appear on a loop directive.
2595     // OpenMP 4.5 [2.10.4, Restrictions, p. 106]
2596     //  At most one defaultmap clause can appear on the directive.
2597     // OpenMP 5.0 [2.12.5, target construct, Restrictions]
2598     //  At most one device clause can appear on the directive.
2599     if ((getLangOpts().OpenMP < 50 || CKind != OMPC_defaultmap) &&
2600         !FirstClause) {
2601       Diag(Tok, diag::err_omp_more_one_clause)
2602           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
2603       ErrorFound = true;
2604     }
2605     LLVM_FALLTHROUGH;
2606   case OMPC_if:
2607     Clause = ParseOpenMPSingleExprWithArgClause(DKind, CKind, WrongDirective);
2608     break;
2609   case OMPC_nowait:
2610   case OMPC_untied:
2611   case OMPC_mergeable:
2612   case OMPC_read:
2613   case OMPC_write:
2614   case OMPC_capture:
2615   case OMPC_seq_cst:
2616   case OMPC_acq_rel:
2617   case OMPC_acquire:
2618   case OMPC_release:
2619   case OMPC_relaxed:
2620   case OMPC_threads:
2621   case OMPC_simd:
2622   case OMPC_nogroup:
2623   case OMPC_unified_address:
2624   case OMPC_unified_shared_memory:
2625   case OMPC_reverse_offload:
2626   case OMPC_dynamic_allocators:
2627   case OMPC_destroy:
2628     // OpenMP [2.7.1, Restrictions, p. 9]
2629     //  Only one ordered clause can appear on a loop directive.
2630     // OpenMP [2.7.1, Restrictions, C/C++, p. 4]
2631     //  Only one nowait clause can appear on a for directive.
2632     // OpenMP [5.0, Requires directive, Restrictions]
2633     //   Each of the requires clauses can appear at most once on the directive.
2634     if (!FirstClause) {
2635       Diag(Tok, diag::err_omp_more_one_clause)
2636           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
2637       ErrorFound = true;
2638     }
2639 
2640     Clause = ParseOpenMPClause(CKind, WrongDirective);
2641     break;
2642   case OMPC_update:
2643     if (!FirstClause) {
2644       Diag(Tok, diag::err_omp_more_one_clause)
2645           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
2646       ErrorFound = true;
2647     }
2648 
2649     Clause = (DKind == OMPD_depobj)
2650                  ? ParseOpenMPSimpleClause(CKind, WrongDirective)
2651                  : ParseOpenMPClause(CKind, WrongDirective);
2652     break;
2653   case OMPC_private:
2654   case OMPC_firstprivate:
2655   case OMPC_lastprivate:
2656   case OMPC_shared:
2657   case OMPC_reduction:
2658   case OMPC_task_reduction:
2659   case OMPC_in_reduction:
2660   case OMPC_linear:
2661   case OMPC_aligned:
2662   case OMPC_copyin:
2663   case OMPC_copyprivate:
2664   case OMPC_flush:
2665   case OMPC_depend:
2666   case OMPC_map:
2667   case OMPC_to:
2668   case OMPC_from:
2669   case OMPC_use_device_ptr:
2670   case OMPC_use_device_addr:
2671   case OMPC_is_device_ptr:
2672   case OMPC_allocate:
2673   case OMPC_nontemporal:
2674   case OMPC_inclusive:
2675   case OMPC_exclusive:
2676   case OMPC_affinity:
2677     Clause = ParseOpenMPVarListClause(DKind, CKind, WrongDirective);
2678     break;
2679   case OMPC_uses_allocators:
2680     Clause = ParseOpenMPUsesAllocatorClause(DKind);
2681     break;
2682   case OMPC_device_type:
2683   case OMPC_unknown:
2684     skipUntilPragmaOpenMPEnd(DKind);
2685     break;
2686   case OMPC_threadprivate:
2687   case OMPC_uniform:
2688   case OMPC_match:
2689     if (!WrongDirective)
2690       Diag(Tok, diag::err_omp_unexpected_clause)
2691           << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind);
2692     SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch);
2693     break;
2694   }
2695   return ErrorFound ? nullptr : Clause;
2696 }
2697 
2698 /// Parses simple expression in parens for single-expression clauses of OpenMP
2699 /// constructs.
2700 /// \param RLoc Returned location of right paren.
2701 ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName,
2702                                          SourceLocation &RLoc,
2703                                          bool IsAddressOfOperand) {
2704   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
2705   if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data()))
2706     return ExprError();
2707 
2708   SourceLocation ELoc = Tok.getLocation();
2709   ExprResult LHS(ParseCastExpression(AnyCastExpr, IsAddressOfOperand,
2710                                      NotTypeCast));
2711   ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
2712   Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
2713 
2714   // Parse ')'.
2715   RLoc = Tok.getLocation();
2716   if (!T.consumeClose())
2717     RLoc = T.getCloseLocation();
2718 
2719   return Val;
2720 }
2721 
2722 /// Parsing of OpenMP clauses with single expressions like 'final',
2723 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
2724 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks', 'hint' or
2725 /// 'detach'.
2726 ///
2727 ///    final-clause:
2728 ///      'final' '(' expression ')'
2729 ///
2730 ///    num_threads-clause:
2731 ///      'num_threads' '(' expression ')'
2732 ///
2733 ///    safelen-clause:
2734 ///      'safelen' '(' expression ')'
2735 ///
2736 ///    simdlen-clause:
2737 ///      'simdlen' '(' expression ')'
2738 ///
2739 ///    collapse-clause:
2740 ///      'collapse' '(' expression ')'
2741 ///
2742 ///    priority-clause:
2743 ///      'priority' '(' expression ')'
2744 ///
2745 ///    grainsize-clause:
2746 ///      'grainsize' '(' expression ')'
2747 ///
2748 ///    num_tasks-clause:
2749 ///      'num_tasks' '(' expression ')'
2750 ///
2751 ///    hint-clause:
2752 ///      'hint' '(' expression ')'
2753 ///
2754 ///    allocator-clause:
2755 ///      'allocator' '(' expression ')'
2756 ///
2757 ///    detach-clause:
2758 ///      'detach' '(' event-handler-expression ')'
2759 ///
2760 OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
2761                                                bool ParseOnly) {
2762   SourceLocation Loc = ConsumeToken();
2763   SourceLocation LLoc = Tok.getLocation();
2764   SourceLocation RLoc;
2765 
2766   ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
2767 
2768   if (Val.isInvalid())
2769     return nullptr;
2770 
2771   if (ParseOnly)
2772     return nullptr;
2773   return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc);
2774 }
2775 
2776 /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
2777 ///
2778 ///    default-clause:
2779 ///         'default' '(' 'none' | 'shared' ')'
2780 ///
2781 ///    proc_bind-clause:
2782 ///         'proc_bind' '(' 'master' | 'close' | 'spread' ')'
2783 ///
2784 ///    update-clause:
2785 ///         'update' '(' 'in' | 'out' | 'inout' | 'mutexinoutset' ')'
2786 ///
2787 OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind,
2788                                            bool ParseOnly) {
2789   llvm::Optional<SimpleClauseData> Val = parseOpenMPSimpleClause(*this, Kind);
2790   if (!Val || ParseOnly)
2791     return nullptr;
2792   return Actions.ActOnOpenMPSimpleClause(
2793       Kind, Val.getValue().Type, Val.getValue().TypeLoc, Val.getValue().LOpen,
2794       Val.getValue().Loc, Val.getValue().RLoc);
2795 }
2796 
2797 /// Parsing of OpenMP clauses like 'ordered'.
2798 ///
2799 ///    ordered-clause:
2800 ///         'ordered'
2801 ///
2802 ///    nowait-clause:
2803 ///         'nowait'
2804 ///
2805 ///    untied-clause:
2806 ///         'untied'
2807 ///
2808 ///    mergeable-clause:
2809 ///         'mergeable'
2810 ///
2811 ///    read-clause:
2812 ///         'read'
2813 ///
2814 ///    threads-clause:
2815 ///         'threads'
2816 ///
2817 ///    simd-clause:
2818 ///         'simd'
2819 ///
2820 ///    nogroup-clause:
2821 ///         'nogroup'
2822 ///
2823 OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly) {
2824   SourceLocation Loc = Tok.getLocation();
2825   ConsumeAnyToken();
2826 
2827   if (ParseOnly)
2828     return nullptr;
2829   return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation());
2830 }
2831 
2832 /// Parsing of OpenMP clauses with single expressions and some additional
2833 /// argument like 'schedule' or 'dist_schedule'.
2834 ///
2835 ///    schedule-clause:
2836 ///      'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
2837 ///      ')'
2838 ///
2839 ///    if-clause:
2840 ///      'if' '(' [ directive-name-modifier ':' ] expression ')'
2841 ///
2842 ///    defaultmap:
2843 ///      'defaultmap' '(' modifier [ ':' kind ] ')'
2844 ///
2845 ///    device-clause:
2846 ///      'device' '(' [ device-modifier ':' ] expression ')'
2847 ///
2848 OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
2849                                                       OpenMPClauseKind Kind,
2850                                                       bool ParseOnly) {
2851   SourceLocation Loc = ConsumeToken();
2852   SourceLocation DelimLoc;
2853   // Parse '('.
2854   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
2855   if (T.expectAndConsume(diag::err_expected_lparen_after,
2856                          getOpenMPClauseName(Kind).data()))
2857     return nullptr;
2858 
2859   ExprResult Val;
2860   SmallVector<unsigned, 4> Arg;
2861   SmallVector<SourceLocation, 4> KLoc;
2862   if (Kind == OMPC_schedule) {
2863     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
2864     Arg.resize(NumberOfElements);
2865     KLoc.resize(NumberOfElements);
2866     Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown;
2867     Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown;
2868     Arg[ScheduleKind] = OMPC_SCHEDULE_unknown;
2869     unsigned KindModifier = getOpenMPSimpleClauseType(
2870         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
2871     if (KindModifier > OMPC_SCHEDULE_unknown) {
2872       // Parse 'modifier'
2873       Arg[Modifier1] = KindModifier;
2874       KLoc[Modifier1] = Tok.getLocation();
2875       if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
2876           Tok.isNot(tok::annot_pragma_openmp_end))
2877         ConsumeAnyToken();
2878       if (Tok.is(tok::comma)) {
2879         // Parse ',' 'modifier'
2880         ConsumeAnyToken();
2881         KindModifier = getOpenMPSimpleClauseType(
2882             Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
2883         Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown
2884                              ? KindModifier
2885                              : (unsigned)OMPC_SCHEDULE_unknown;
2886         KLoc[Modifier2] = Tok.getLocation();
2887         if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
2888             Tok.isNot(tok::annot_pragma_openmp_end))
2889           ConsumeAnyToken();
2890       }
2891       // Parse ':'
2892       if (Tok.is(tok::colon))
2893         ConsumeAnyToken();
2894       else
2895         Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier";
2896       KindModifier = getOpenMPSimpleClauseType(
2897           Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
2898     }
2899     Arg[ScheduleKind] = KindModifier;
2900     KLoc[ScheduleKind] = Tok.getLocation();
2901     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
2902         Tok.isNot(tok::annot_pragma_openmp_end))
2903       ConsumeAnyToken();
2904     if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static ||
2905          Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic ||
2906          Arg[ScheduleKind] == OMPC_SCHEDULE_guided) &&
2907         Tok.is(tok::comma))
2908       DelimLoc = ConsumeAnyToken();
2909   } else if (Kind == OMPC_dist_schedule) {
2910     Arg.push_back(getOpenMPSimpleClauseType(
2911         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
2912     KLoc.push_back(Tok.getLocation());
2913     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
2914         Tok.isNot(tok::annot_pragma_openmp_end))
2915       ConsumeAnyToken();
2916     if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma))
2917       DelimLoc = ConsumeAnyToken();
2918   } else if (Kind == OMPC_defaultmap) {
2919     // Get a defaultmap modifier
2920     unsigned Modifier = getOpenMPSimpleClauseType(
2921         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
2922     // Set defaultmap modifier to unknown if it is either scalar, aggregate, or
2923     // pointer
2924     if (Modifier < OMPC_DEFAULTMAP_MODIFIER_unknown)
2925       Modifier = OMPC_DEFAULTMAP_MODIFIER_unknown;
2926     Arg.push_back(Modifier);
2927     KLoc.push_back(Tok.getLocation());
2928     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
2929         Tok.isNot(tok::annot_pragma_openmp_end))
2930       ConsumeAnyToken();
2931     // Parse ':'
2932     if (Tok.is(tok::colon) || getLangOpts().OpenMP < 50) {
2933       if (Tok.is(tok::colon))
2934         ConsumeAnyToken();
2935       else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown)
2936         Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier";
2937       // Get a defaultmap kind
2938       Arg.push_back(getOpenMPSimpleClauseType(
2939           Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
2940       KLoc.push_back(Tok.getLocation());
2941       if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
2942           Tok.isNot(tok::annot_pragma_openmp_end))
2943         ConsumeAnyToken();
2944     } else {
2945       Arg.push_back(OMPC_DEFAULTMAP_unknown);
2946       KLoc.push_back(SourceLocation());
2947     }
2948   } else if (Kind == OMPC_device) {
2949     // Only target executable directives support extended device construct.
2950     if (isOpenMPTargetExecutionDirective(DKind) && getLangOpts().OpenMP >= 50 &&
2951         NextToken().is(tok::colon)) {
2952       // Parse optional <device modifier> ':'
2953       Arg.push_back(getOpenMPSimpleClauseType(
2954           Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
2955       KLoc.push_back(Tok.getLocation());
2956       ConsumeAnyToken();
2957       // Parse ':'
2958       ConsumeAnyToken();
2959     } else {
2960       Arg.push_back(OMPC_DEVICE_unknown);
2961       KLoc.emplace_back();
2962     }
2963   } else {
2964     assert(Kind == OMPC_if);
2965     KLoc.push_back(Tok.getLocation());
2966     TentativeParsingAction TPA(*this);
2967     auto DK = parseOpenMPDirectiveKind(*this);
2968     Arg.push_back(DK);
2969     if (DK != OMPD_unknown) {
2970       ConsumeToken();
2971       if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) {
2972         TPA.Commit();
2973         DelimLoc = ConsumeToken();
2974       } else {
2975         TPA.Revert();
2976         Arg.back() = unsigned(OMPD_unknown);
2977       }
2978     } else {
2979       TPA.Revert();
2980     }
2981   }
2982 
2983   bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) ||
2984                           (Kind == OMPC_dist_schedule && DelimLoc.isValid()) ||
2985                           Kind == OMPC_if || Kind == OMPC_device;
2986   if (NeedAnExpression) {
2987     SourceLocation ELoc = Tok.getLocation();
2988     ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
2989     Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
2990     Val =
2991         Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
2992   }
2993 
2994   // Parse ')'.
2995   SourceLocation RLoc = Tok.getLocation();
2996   if (!T.consumeClose())
2997     RLoc = T.getCloseLocation();
2998 
2999   if (NeedAnExpression && Val.isInvalid())
3000     return nullptr;
3001 
3002   if (ParseOnly)
3003     return nullptr;
3004   return Actions.ActOnOpenMPSingleExprWithArgClause(
3005       Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc, RLoc);
3006 }
3007 
3008 static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec,
3009                              UnqualifiedId &ReductionId) {
3010   if (ReductionIdScopeSpec.isEmpty()) {
3011     auto OOK = OO_None;
3012     switch (P.getCurToken().getKind()) {
3013     case tok::plus:
3014       OOK = OO_Plus;
3015       break;
3016     case tok::minus:
3017       OOK = OO_Minus;
3018       break;
3019     case tok::star:
3020       OOK = OO_Star;
3021       break;
3022     case tok::amp:
3023       OOK = OO_Amp;
3024       break;
3025     case tok::pipe:
3026       OOK = OO_Pipe;
3027       break;
3028     case tok::caret:
3029       OOK = OO_Caret;
3030       break;
3031     case tok::ampamp:
3032       OOK = OO_AmpAmp;
3033       break;
3034     case tok::pipepipe:
3035       OOK = OO_PipePipe;
3036       break;
3037     default:
3038       break;
3039     }
3040     if (OOK != OO_None) {
3041       SourceLocation OpLoc = P.ConsumeToken();
3042       SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()};
3043       ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations);
3044       return false;
3045     }
3046   }
3047   return P.ParseUnqualifiedId(
3048       ReductionIdScopeSpec, /*ObjectType=*/nullptr,
3049       /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
3050       /*AllowDestructorName*/ false,
3051       /*AllowConstructorName*/ false,
3052       /*AllowDeductionGuide*/ false, nullptr, ReductionId);
3053 }
3054 
3055 /// Checks if the token is a valid map-type-modifier.
3056 static OpenMPMapModifierKind isMapModifier(Parser &P) {
3057   Token Tok = P.getCurToken();
3058   if (!Tok.is(tok::identifier))
3059     return OMPC_MAP_MODIFIER_unknown;
3060 
3061   Preprocessor &PP = P.getPreprocessor();
3062   OpenMPMapModifierKind TypeModifier = static_cast<OpenMPMapModifierKind>(
3063       getOpenMPSimpleClauseType(OMPC_map, PP.getSpelling(Tok)));
3064   return TypeModifier;
3065 }
3066 
3067 /// Parse the mapper modifier in map, to, and from clauses.
3068 bool Parser::parseMapperModifier(OpenMPVarListDataTy &Data) {
3069   // Parse '('.
3070   BalancedDelimiterTracker T(*this, tok::l_paren, tok::colon);
3071   if (T.expectAndConsume(diag::err_expected_lparen_after, "mapper")) {
3072     SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
3073               StopBeforeMatch);
3074     return true;
3075   }
3076   // Parse mapper-identifier
3077   if (getLangOpts().CPlusPlus)
3078     ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
3079                                    /*ObjectType=*/nullptr,
3080                                    /*ObjectHadErrors=*/false,
3081                                    /*EnteringContext=*/false);
3082   if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
3083     Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
3084     SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
3085               StopBeforeMatch);
3086     return true;
3087   }
3088   auto &DeclNames = Actions.getASTContext().DeclarationNames;
3089   Data.ReductionOrMapperId = DeclarationNameInfo(
3090       DeclNames.getIdentifier(Tok.getIdentifierInfo()), Tok.getLocation());
3091   ConsumeToken();
3092   // Parse ')'.
3093   return T.consumeClose();
3094 }
3095 
3096 /// Parse map-type-modifiers in map clause.
3097 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
3098 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier)
3099 bool Parser::parseMapTypeModifiers(OpenMPVarListDataTy &Data) {
3100   while (getCurToken().isNot(tok::colon)) {
3101     OpenMPMapModifierKind TypeModifier = isMapModifier(*this);
3102     if (TypeModifier == OMPC_MAP_MODIFIER_always ||
3103         TypeModifier == OMPC_MAP_MODIFIER_close) {
3104       Data.MapTypeModifiers.push_back(TypeModifier);
3105       Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
3106       ConsumeToken();
3107     } else if (TypeModifier == OMPC_MAP_MODIFIER_mapper) {
3108       Data.MapTypeModifiers.push_back(TypeModifier);
3109       Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
3110       ConsumeToken();
3111       if (parseMapperModifier(Data))
3112         return true;
3113     } else {
3114       // For the case of unknown map-type-modifier or a map-type.
3115       // Map-type is followed by a colon; the function returns when it
3116       // encounters a token followed by a colon.
3117       if (Tok.is(tok::comma)) {
3118         Diag(Tok, diag::err_omp_map_type_modifier_missing);
3119         ConsumeToken();
3120         continue;
3121       }
3122       // Potential map-type token as it is followed by a colon.
3123       if (PP.LookAhead(0).is(tok::colon))
3124         return false;
3125       Diag(Tok, diag::err_omp_unknown_map_type_modifier);
3126       ConsumeToken();
3127     }
3128     if (getCurToken().is(tok::comma))
3129       ConsumeToken();
3130   }
3131   return false;
3132 }
3133 
3134 /// Checks if the token is a valid map-type.
3135 static OpenMPMapClauseKind isMapType(Parser &P) {
3136   Token Tok = P.getCurToken();
3137   // The map-type token can be either an identifier or the C++ delete keyword.
3138   if (!Tok.isOneOf(tok::identifier, tok::kw_delete))
3139     return OMPC_MAP_unknown;
3140   Preprocessor &PP = P.getPreprocessor();
3141   OpenMPMapClauseKind MapType = static_cast<OpenMPMapClauseKind>(
3142       getOpenMPSimpleClauseType(OMPC_map, PP.getSpelling(Tok)));
3143   return MapType;
3144 }
3145 
3146 /// Parse map-type in map clause.
3147 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
3148 /// where, map-type ::= to | from | tofrom | alloc | release | delete
3149 static void parseMapType(Parser &P, Parser::OpenMPVarListDataTy &Data) {
3150   Token Tok = P.getCurToken();
3151   if (Tok.is(tok::colon)) {
3152     P.Diag(Tok, diag::err_omp_map_type_missing);
3153     return;
3154   }
3155   Data.ExtraModifier = isMapType(P);
3156   if (Data.ExtraModifier == OMPC_MAP_unknown)
3157     P.Diag(Tok, diag::err_omp_unknown_map_type);
3158   P.ConsumeToken();
3159 }
3160 
3161 /// Parses simple expression in parens for single-expression clauses of OpenMP
3162 /// constructs.
3163 /// \param RLoc Returned location of right paren.
3164 ExprResult Parser::ParseOpenMPIteratorsExpr() {
3165   assert(Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator" &&
3166          "Expected 'iterator' token.");
3167   SourceLocation IteratorKwLoc = ConsumeToken();
3168 
3169   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3170   if (T.expectAndConsume(diag::err_expected_lparen_after, "iterator"))
3171     return ExprError();
3172 
3173   SourceLocation LLoc = T.getOpenLocation();
3174   SmallVector<Sema::OMPIteratorData, 4> Data;
3175   while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
3176     // Check if the type parsing is required.
3177     ParsedType IteratorType;
3178     if (Tok.isNot(tok::identifier) || NextToken().isNot(tok::equal)) {
3179       // identifier '=' is not found - parse type.
3180       TypeResult TR = ParseTypeName();
3181       if (TR.isInvalid()) {
3182         T.skipToEnd();
3183         return ExprError();
3184       }
3185       IteratorType = TR.get();
3186     }
3187 
3188     // Parse identifier.
3189     IdentifierInfo *II = nullptr;
3190     SourceLocation IdLoc;
3191     if (Tok.is(tok::identifier)) {
3192       II = Tok.getIdentifierInfo();
3193       IdLoc = ConsumeToken();
3194     } else {
3195       Diag(Tok, diag::err_expected_unqualified_id) << 0;
3196     }
3197 
3198     // Parse '='.
3199     SourceLocation AssignLoc;
3200     if (Tok.is(tok::equal))
3201       AssignLoc = ConsumeToken();
3202     else
3203       Diag(Tok, diag::err_omp_expected_equal_in_iterator);
3204 
3205     // Parse range-specification - <begin> ':' <end> [ ':' <step> ]
3206     ColonProtectionRAIIObject ColonRAII(*this);
3207     // Parse <begin>
3208     SourceLocation Loc = Tok.getLocation();
3209     ExprResult LHS = ParseCastExpression(AnyCastExpr);
3210     ExprResult Begin = Actions.CorrectDelayedTyposInExpr(
3211         ParseRHSOfBinaryExpression(LHS, prec::Conditional));
3212     Begin = Actions.ActOnFinishFullExpr(Begin.get(), Loc,
3213                                         /*DiscardedValue=*/false);
3214     // Parse ':'.
3215     SourceLocation ColonLoc;
3216     if (Tok.is(tok::colon))
3217       ColonLoc = ConsumeToken();
3218 
3219     // Parse <end>
3220     Loc = Tok.getLocation();
3221     LHS = ParseCastExpression(AnyCastExpr);
3222     ExprResult End = Actions.CorrectDelayedTyposInExpr(
3223         ParseRHSOfBinaryExpression(LHS, prec::Conditional));
3224     End = Actions.ActOnFinishFullExpr(End.get(), Loc,
3225                                       /*DiscardedValue=*/false);
3226 
3227     SourceLocation SecColonLoc;
3228     ExprResult Step;
3229     // Parse optional step.
3230     if (Tok.is(tok::colon)) {
3231       // Parse ':'
3232       SecColonLoc = ConsumeToken();
3233       // Parse <step>
3234       Loc = Tok.getLocation();
3235       LHS = ParseCastExpression(AnyCastExpr);
3236       Step = Actions.CorrectDelayedTyposInExpr(
3237           ParseRHSOfBinaryExpression(LHS, prec::Conditional));
3238       Step = Actions.ActOnFinishFullExpr(Step.get(), Loc,
3239                                          /*DiscardedValue=*/false);
3240     }
3241 
3242     // Parse ',' or ')'
3243     if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren))
3244       Diag(Tok, diag::err_omp_expected_punc_after_iterator);
3245     if (Tok.is(tok::comma))
3246       ConsumeToken();
3247 
3248     Sema::OMPIteratorData &D = Data.emplace_back();
3249     D.DeclIdent = II;
3250     D.DeclIdentLoc = IdLoc;
3251     D.Type = IteratorType;
3252     D.AssignLoc = AssignLoc;
3253     D.ColonLoc = ColonLoc;
3254     D.SecColonLoc = SecColonLoc;
3255     D.Range.Begin = Begin.get();
3256     D.Range.End = End.get();
3257     D.Range.Step = Step.get();
3258   }
3259 
3260   // Parse ')'.
3261   SourceLocation RLoc = Tok.getLocation();
3262   if (!T.consumeClose())
3263     RLoc = T.getCloseLocation();
3264 
3265   return Actions.ActOnOMPIteratorExpr(getCurScope(), IteratorKwLoc, LLoc, RLoc,
3266                                       Data);
3267 }
3268 
3269 /// Parses clauses with list.
3270 bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind,
3271                                 OpenMPClauseKind Kind,
3272                                 SmallVectorImpl<Expr *> &Vars,
3273                                 OpenMPVarListDataTy &Data) {
3274   UnqualifiedId UnqualifiedReductionId;
3275   bool InvalidReductionId = false;
3276   bool IsInvalidMapperModifier = false;
3277 
3278   // Parse '('.
3279   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3280   if (T.expectAndConsume(diag::err_expected_lparen_after,
3281                          getOpenMPClauseName(Kind).data()))
3282     return true;
3283 
3284   bool HasIterator = false;
3285   bool NeedRParenForLinear = false;
3286   BalancedDelimiterTracker LinearT(*this, tok::l_paren,
3287                                   tok::annot_pragma_openmp_end);
3288   // Handle reduction-identifier for reduction clause.
3289   if (Kind == OMPC_reduction || Kind == OMPC_task_reduction ||
3290       Kind == OMPC_in_reduction) {
3291     Data.ExtraModifier = OMPC_REDUCTION_unknown;
3292     if (Kind == OMPC_reduction && getLangOpts().OpenMP >= 50 &&
3293         (Tok.is(tok::identifier) || Tok.is(tok::kw_default)) &&
3294         NextToken().is(tok::comma)) {
3295       // Parse optional reduction modifier.
3296       Data.ExtraModifier = getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok));
3297       Data.ExtraModifierLoc = Tok.getLocation();
3298       ConsumeToken();
3299       assert(Tok.is(tok::comma) && "Expected comma.");
3300       (void)ConsumeToken();
3301     }
3302     ColonProtectionRAIIObject ColonRAII(*this);
3303     if (getLangOpts().CPlusPlus)
3304       ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
3305                                      /*ObjectType=*/nullptr,
3306                                      /*ObjectHadErrors=*/false,
3307                                      /*EnteringContext=*/false);
3308     InvalidReductionId = ParseReductionId(
3309         *this, Data.ReductionOrMapperIdScopeSpec, UnqualifiedReductionId);
3310     if (InvalidReductionId) {
3311       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
3312                 StopBeforeMatch);
3313     }
3314     if (Tok.is(tok::colon))
3315       Data.ColonLoc = ConsumeToken();
3316     else
3317       Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier";
3318     if (!InvalidReductionId)
3319       Data.ReductionOrMapperId =
3320           Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId);
3321   } else if (Kind == OMPC_depend) {
3322     if (getLangOpts().OpenMP >= 50) {
3323       if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator") {
3324         // Handle optional dependence modifier.
3325         // iterator(iterators-definition)
3326         // where iterators-definition is iterator-specifier [,
3327         // iterators-definition ]
3328         // where iterator-specifier is [ iterator-type ] identifier =
3329         // range-specification
3330         HasIterator = true;
3331         EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope);
3332         ExprResult IteratorRes = ParseOpenMPIteratorsExpr();
3333         Data.DepModOrTailExpr = IteratorRes.get();
3334         // Parse ','
3335         ExpectAndConsume(tok::comma);
3336       }
3337     }
3338     // Handle dependency type for depend clause.
3339     ColonProtectionRAIIObject ColonRAII(*this);
3340     Data.ExtraModifier = getOpenMPSimpleClauseType(
3341         Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "");
3342     Data.ExtraModifierLoc = Tok.getLocation();
3343     if (Data.ExtraModifier == OMPC_DEPEND_unknown) {
3344       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
3345                 StopBeforeMatch);
3346     } else {
3347       ConsumeToken();
3348       // Special processing for depend(source) clause.
3349       if (DKind == OMPD_ordered && Data.ExtraModifier == OMPC_DEPEND_source) {
3350         // Parse ')'.
3351         T.consumeClose();
3352         return false;
3353       }
3354     }
3355     if (Tok.is(tok::colon)) {
3356       Data.ColonLoc = ConsumeToken();
3357     } else {
3358       Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren
3359                                       : diag::warn_pragma_expected_colon)
3360           << "dependency type";
3361     }
3362   } else if (Kind == OMPC_linear) {
3363     // Try to parse modifier if any.
3364     Data.ExtraModifier = OMPC_LINEAR_val;
3365     if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) {
3366       Data.ExtraModifier = getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok));
3367       Data.ExtraModifierLoc = ConsumeToken();
3368       LinearT.consumeOpen();
3369       NeedRParenForLinear = true;
3370     }
3371   } else if (Kind == OMPC_lastprivate) {
3372     // Try to parse modifier if any.
3373     Data.ExtraModifier = OMPC_LASTPRIVATE_unknown;
3374     // Conditional modifier allowed only in OpenMP 5.0 and not supported in
3375     // distribute and taskloop based directives.
3376     if ((getLangOpts().OpenMP >= 50 && !isOpenMPDistributeDirective(DKind) &&
3377          !isOpenMPTaskLoopDirective(DKind)) &&
3378         Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::colon)) {
3379       Data.ExtraModifier = getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok));
3380       Data.ExtraModifierLoc = Tok.getLocation();
3381       ConsumeToken();
3382       assert(Tok.is(tok::colon) && "Expected colon.");
3383       Data.ColonLoc = ConsumeToken();
3384     }
3385   } else if (Kind == OMPC_map) {
3386     // Handle map type for map clause.
3387     ColonProtectionRAIIObject ColonRAII(*this);
3388 
3389     // The first identifier may be a list item, a map-type or a
3390     // map-type-modifier. The map-type can also be delete which has the same
3391     // spelling of the C++ delete keyword.
3392     Data.ExtraModifier = OMPC_MAP_unknown;
3393     Data.ExtraModifierLoc = Tok.getLocation();
3394 
3395     // Check for presence of a colon in the map clause.
3396     TentativeParsingAction TPA(*this);
3397     bool ColonPresent = false;
3398     if (SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
3399         StopBeforeMatch)) {
3400       if (Tok.is(tok::colon))
3401         ColonPresent = true;
3402     }
3403     TPA.Revert();
3404     // Only parse map-type-modifier[s] and map-type if a colon is present in
3405     // the map clause.
3406     if (ColonPresent) {
3407       IsInvalidMapperModifier = parseMapTypeModifiers(Data);
3408       if (!IsInvalidMapperModifier)
3409         parseMapType(*this, Data);
3410       else
3411         SkipUntil(tok::colon, tok::annot_pragma_openmp_end, StopBeforeMatch);
3412     }
3413     if (Data.ExtraModifier == OMPC_MAP_unknown) {
3414       Data.ExtraModifier = OMPC_MAP_tofrom;
3415       Data.IsMapTypeImplicit = true;
3416     }
3417 
3418     if (Tok.is(tok::colon))
3419       Data.ColonLoc = ConsumeToken();
3420   } else if (Kind == OMPC_to || Kind == OMPC_from) {
3421     if (Tok.is(tok::identifier)) {
3422       bool IsMapperModifier = false;
3423       if (Kind == OMPC_to) {
3424         auto Modifier = static_cast<OpenMPToModifierKind>(
3425             getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)));
3426         if (Modifier == OMPC_TO_MODIFIER_mapper)
3427           IsMapperModifier = true;
3428       } else {
3429         auto Modifier = static_cast<OpenMPFromModifierKind>(
3430             getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)));
3431         if (Modifier == OMPC_FROM_MODIFIER_mapper)
3432           IsMapperModifier = true;
3433       }
3434       if (IsMapperModifier) {
3435         // Parse the mapper modifier.
3436         ConsumeToken();
3437         IsInvalidMapperModifier = parseMapperModifier(Data);
3438         if (Tok.isNot(tok::colon)) {
3439           if (!IsInvalidMapperModifier)
3440             Diag(Tok, diag::warn_pragma_expected_colon) << ")";
3441           SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
3442                     StopBeforeMatch);
3443         }
3444         // Consume ':'.
3445         if (Tok.is(tok::colon))
3446           ConsumeToken();
3447       }
3448     }
3449   } else if (Kind == OMPC_allocate ||
3450              (Kind == OMPC_affinity && Tok.is(tok::identifier) &&
3451               PP.getSpelling(Tok) == "iterator")) {
3452     // Handle optional allocator expression followed by colon delimiter.
3453     ColonProtectionRAIIObject ColonRAII(*this);
3454     TentativeParsingAction TPA(*this);
3455     // OpenMP 5.0, 2.10.1, task Construct.
3456     // where aff-modifier is one of the following:
3457     // iterator(iterators-definition)
3458     ExprResult Tail;
3459     if (Kind == OMPC_allocate) {
3460       Tail = ParseAssignmentExpression();
3461     } else {
3462       HasIterator = true;
3463       EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope);
3464       Tail = ParseOpenMPIteratorsExpr();
3465     }
3466     Tail = Actions.CorrectDelayedTyposInExpr(Tail);
3467     Tail = Actions.ActOnFinishFullExpr(Tail.get(), T.getOpenLocation(),
3468                                        /*DiscardedValue=*/false);
3469     if (Tail.isUsable()) {
3470       if (Tok.is(tok::colon)) {
3471         Data.DepModOrTailExpr = Tail.get();
3472         Data.ColonLoc = ConsumeToken();
3473         TPA.Commit();
3474       } else {
3475         // Colon not found, parse only list of variables.
3476         TPA.Revert();
3477       }
3478     } else {
3479       // Parsing was unsuccessfull, revert and skip to the end of clause or
3480       // directive.
3481       TPA.Revert();
3482       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3483                 StopBeforeMatch);
3484     }
3485   }
3486 
3487   bool IsComma =
3488       (Kind != OMPC_reduction && Kind != OMPC_task_reduction &&
3489        Kind != OMPC_in_reduction && Kind != OMPC_depend && Kind != OMPC_map) ||
3490       (Kind == OMPC_reduction && !InvalidReductionId) ||
3491       (Kind == OMPC_map && Data.ExtraModifier != OMPC_MAP_unknown) ||
3492       (Kind == OMPC_depend && Data.ExtraModifier != OMPC_DEPEND_unknown);
3493   const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned);
3494   while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) &&
3495                      Tok.isNot(tok::annot_pragma_openmp_end))) {
3496     ParseScope OMPListScope(this, Scope::OpenMPDirectiveScope);
3497     ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
3498     // Parse variable
3499     ExprResult VarExpr =
3500         Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3501     if (VarExpr.isUsable()) {
3502       Vars.push_back(VarExpr.get());
3503     } else {
3504       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3505                 StopBeforeMatch);
3506     }
3507     // Skip ',' if any
3508     IsComma = Tok.is(tok::comma);
3509     if (IsComma)
3510       ConsumeToken();
3511     else if (Tok.isNot(tok::r_paren) &&
3512              Tok.isNot(tok::annot_pragma_openmp_end) &&
3513              (!MayHaveTail || Tok.isNot(tok::colon)))
3514       Diag(Tok, diag::err_omp_expected_punc)
3515           << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush)
3516                                    : getOpenMPClauseName(Kind))
3517           << (Kind == OMPC_flush);
3518   }
3519 
3520   // Parse ')' for linear clause with modifier.
3521   if (NeedRParenForLinear)
3522     LinearT.consumeClose();
3523 
3524   // Parse ':' linear-step (or ':' alignment).
3525   const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon);
3526   if (MustHaveTail) {
3527     Data.ColonLoc = Tok.getLocation();
3528     SourceLocation ELoc = ConsumeToken();
3529     ExprResult Tail = ParseAssignmentExpression();
3530     Tail =
3531         Actions.ActOnFinishFullExpr(Tail.get(), ELoc, /*DiscardedValue*/ false);
3532     if (Tail.isUsable())
3533       Data.DepModOrTailExpr = Tail.get();
3534     else
3535       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3536                 StopBeforeMatch);
3537   }
3538 
3539   // Parse ')'.
3540   Data.RLoc = Tok.getLocation();
3541   if (!T.consumeClose())
3542     Data.RLoc = T.getCloseLocation();
3543   // Exit from scope when the iterator is used in depend clause.
3544   if (HasIterator)
3545     ExitScope();
3546   return (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) ||
3547          (MustHaveTail && !Data.DepModOrTailExpr) || InvalidReductionId ||
3548          IsInvalidMapperModifier;
3549 }
3550 
3551 /// Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate',
3552 /// 'shared', 'copyin', 'copyprivate', 'flush', 'reduction', 'task_reduction',
3553 /// 'in_reduction', 'nontemporal', 'exclusive' or 'inclusive'.
3554 ///
3555 ///    private-clause:
3556 ///       'private' '(' list ')'
3557 ///    firstprivate-clause:
3558 ///       'firstprivate' '(' list ')'
3559 ///    lastprivate-clause:
3560 ///       'lastprivate' '(' list ')'
3561 ///    shared-clause:
3562 ///       'shared' '(' list ')'
3563 ///    linear-clause:
3564 ///       'linear' '(' linear-list [ ':' linear-step ] ')'
3565 ///    aligned-clause:
3566 ///       'aligned' '(' list [ ':' alignment ] ')'
3567 ///    reduction-clause:
3568 ///       'reduction' '(' [ modifier ',' ] reduction-identifier ':' list ')'
3569 ///    task_reduction-clause:
3570 ///       'task_reduction' '(' reduction-identifier ':' list ')'
3571 ///    in_reduction-clause:
3572 ///       'in_reduction' '(' reduction-identifier ':' list ')'
3573 ///    copyprivate-clause:
3574 ///       'copyprivate' '(' list ')'
3575 ///    flush-clause:
3576 ///       'flush' '(' list ')'
3577 ///    depend-clause:
3578 ///       'depend' '(' in | out | inout : list | source ')'
3579 ///    map-clause:
3580 ///       'map' '(' [ [ always [,] ] [ close [,] ]
3581 ///          [ mapper '(' mapper-identifier ')' [,] ]
3582 ///          to | from | tofrom | alloc | release | delete ':' ] list ')';
3583 ///    to-clause:
3584 ///       'to' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
3585 ///    from-clause:
3586 ///       'from' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
3587 ///    use_device_ptr-clause:
3588 ///       'use_device_ptr' '(' list ')'
3589 ///    use_device_addr-clause:
3590 ///       'use_device_addr' '(' list ')'
3591 ///    is_device_ptr-clause:
3592 ///       'is_device_ptr' '(' list ')'
3593 ///    allocate-clause:
3594 ///       'allocate' '(' [ allocator ':' ] list ')'
3595 ///    nontemporal-clause:
3596 ///       'nontemporal' '(' list ')'
3597 ///    inclusive-clause:
3598 ///       'inclusive' '(' list ')'
3599 ///    exclusive-clause:
3600 ///       'exclusive' '(' list ')'
3601 ///
3602 /// For 'linear' clause linear-list may have the following forms:
3603 ///  list
3604 ///  modifier(list)
3605 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
3606 OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
3607                                             OpenMPClauseKind Kind,
3608                                             bool ParseOnly) {
3609   SourceLocation Loc = Tok.getLocation();
3610   SourceLocation LOpen = ConsumeToken();
3611   SmallVector<Expr *, 4> Vars;
3612   OpenMPVarListDataTy Data;
3613 
3614   if (ParseOpenMPVarList(DKind, Kind, Vars, Data))
3615     return nullptr;
3616 
3617   if (ParseOnly)
3618     return nullptr;
3619   OMPVarListLocTy Locs(Loc, LOpen, Data.RLoc);
3620   return Actions.ActOnOpenMPVarListClause(
3621       Kind, Vars, Data.DepModOrTailExpr, Locs, Data.ColonLoc,
3622       Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId,
3623       Data.ExtraModifier, Data.MapTypeModifiers, Data.MapTypeModifiersLoc,
3624       Data.IsMapTypeImplicit, Data.ExtraModifierLoc);
3625 }
3626 
3627