1 //===--- ParseOpenMP.cpp - OpenMP directives parsing ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// \brief This file implements parsing of all OpenMP directives and clauses.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "RAIIObjectsForParser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/StmtOpenMP.h"
17 #include "clang/Parse/ParseDiagnostic.h"
18 #include "clang/Parse/Parser.h"
19 #include "clang/Sema/Scope.h"
20 #include "llvm/ADT/PointerIntPair.h"
21 
22 using namespace clang;
23 
24 //===----------------------------------------------------------------------===//
25 // OpenMP declarative directives.
26 //===----------------------------------------------------------------------===//
27 
28 namespace {
29 enum OpenMPDirectiveKindEx {
30   OMPD_cancellation = OMPD_unknown + 1,
31   OMPD_data,
32   OMPD_declare,
33   OMPD_end,
34   OMPD_end_declare,
35   OMPD_enter,
36   OMPD_exit,
37   OMPD_point,
38   OMPD_reduction,
39   OMPD_target_enter,
40   OMPD_target_exit,
41   OMPD_update,
42   OMPD_distribute_parallel
43 };
44 
45 class ThreadprivateListParserHelper final {
46   SmallVector<Expr *, 4> Identifiers;
47   Parser *P;
48 
49 public:
50   ThreadprivateListParserHelper(Parser *P) : P(P) {}
51   void operator()(CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
52     ExprResult Res =
53         P->getActions().ActOnOpenMPIdExpression(P->getCurScope(), SS, NameInfo);
54     if (Res.isUsable())
55       Identifiers.push_back(Res.get());
56   }
57   llvm::ArrayRef<Expr *> getIdentifiers() const { return Identifiers; }
58 };
59 } // namespace
60 
61 // Map token string to extended OMP token kind that are
62 // OpenMPDirectiveKind + OpenMPDirectiveKindEx.
63 static unsigned getOpenMPDirectiveKindEx(StringRef S) {
64   auto DKind = getOpenMPDirectiveKind(S);
65   if (DKind != OMPD_unknown)
66     return DKind;
67 
68   return llvm::StringSwitch<unsigned>(S)
69       .Case("cancellation", OMPD_cancellation)
70       .Case("data", OMPD_data)
71       .Case("declare", OMPD_declare)
72       .Case("end", OMPD_end)
73       .Case("enter", OMPD_enter)
74       .Case("exit", OMPD_exit)
75       .Case("point", OMPD_point)
76       .Case("reduction", OMPD_reduction)
77       .Case("update", OMPD_update)
78       .Default(OMPD_unknown);
79 }
80 
81 static OpenMPDirectiveKind ParseOpenMPDirectiveKind(Parser &P) {
82   // Array of foldings: F[i][0] F[i][1] ===> F[i][2].
83   // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd
84   // TODO: add other combined directives in topological order.
85   static const unsigned F[][3] = {
86     { OMPD_cancellation, OMPD_point, OMPD_cancellation_point },
87     { OMPD_declare, OMPD_reduction, OMPD_declare_reduction },
88     { OMPD_declare, OMPD_simd, OMPD_declare_simd },
89     { OMPD_declare, OMPD_target, OMPD_declare_target },
90     { OMPD_distribute, OMPD_parallel, OMPD_distribute_parallel },
91     { OMPD_distribute_parallel, OMPD_for, OMPD_distribute_parallel_for },
92     { OMPD_distribute_parallel_for, OMPD_simd,
93       OMPD_distribute_parallel_for_simd },
94     { OMPD_distribute, OMPD_simd, OMPD_distribute_simd },
95     { OMPD_end, OMPD_declare, OMPD_end_declare },
96     { OMPD_end_declare, OMPD_target, OMPD_end_declare_target },
97     { OMPD_target, OMPD_data, OMPD_target_data },
98     { OMPD_target, OMPD_enter, OMPD_target_enter },
99     { OMPD_target, OMPD_exit, OMPD_target_exit },
100     { OMPD_target, OMPD_update, OMPD_target_update },
101     { OMPD_target_enter, OMPD_data, OMPD_target_enter_data },
102     { OMPD_target_exit, OMPD_data, OMPD_target_exit_data },
103     { OMPD_for, OMPD_simd, OMPD_for_simd },
104     { OMPD_parallel, OMPD_for, OMPD_parallel_for },
105     { OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd },
106     { OMPD_parallel, OMPD_sections, OMPD_parallel_sections },
107     { OMPD_taskloop, OMPD_simd, OMPD_taskloop_simd },
108     { OMPD_target, OMPD_parallel, OMPD_target_parallel },
109     { OMPD_target, OMPD_simd, OMPD_target_simd },
110     { OMPD_target_parallel, OMPD_for, OMPD_target_parallel_for },
111     { OMPD_target_parallel_for, OMPD_simd, OMPD_target_parallel_for_simd },
112     { OMPD_teams, OMPD_distribute, OMPD_teams_distribute },
113     { OMPD_teams_distribute, OMPD_simd, OMPD_teams_distribute_simd }
114   };
115   enum { CancellationPoint = 0, DeclareReduction = 1, TargetData = 2 };
116   auto Tok = P.getCurToken();
117   unsigned DKind =
118       Tok.isAnnotation()
119           ? static_cast<unsigned>(OMPD_unknown)
120           : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
121   if (DKind == OMPD_unknown)
122     return OMPD_unknown;
123 
124   for (unsigned i = 0; i < llvm::array_lengthof(F); ++i) {
125     if (DKind != F[i][0])
126       continue;
127 
128     Tok = P.getPreprocessor().LookAhead(0);
129     unsigned SDKind =
130         Tok.isAnnotation()
131             ? static_cast<unsigned>(OMPD_unknown)
132             : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
133     if (SDKind == OMPD_unknown)
134       continue;
135 
136     if (SDKind == F[i][1]) {
137       P.ConsumeToken();
138       DKind = F[i][2];
139     }
140   }
141   return DKind < OMPD_unknown ? static_cast<OpenMPDirectiveKind>(DKind)
142                               : OMPD_unknown;
143 }
144 
145 static DeclarationName parseOpenMPReductionId(Parser &P) {
146   Token Tok = P.getCurToken();
147   Sema &Actions = P.getActions();
148   OverloadedOperatorKind OOK = OO_None;
149   // Allow to use 'operator' keyword for C++ operators
150   bool WithOperator = false;
151   if (Tok.is(tok::kw_operator)) {
152     P.ConsumeToken();
153     Tok = P.getCurToken();
154     WithOperator = true;
155   }
156   switch (Tok.getKind()) {
157   case tok::plus: // '+'
158     OOK = OO_Plus;
159     break;
160   case tok::minus: // '-'
161     OOK = OO_Minus;
162     break;
163   case tok::star: // '*'
164     OOK = OO_Star;
165     break;
166   case tok::amp: // '&'
167     OOK = OO_Amp;
168     break;
169   case tok::pipe: // '|'
170     OOK = OO_Pipe;
171     break;
172   case tok::caret: // '^'
173     OOK = OO_Caret;
174     break;
175   case tok::ampamp: // '&&'
176     OOK = OO_AmpAmp;
177     break;
178   case tok::pipepipe: // '||'
179     OOK = OO_PipePipe;
180     break;
181   case tok::identifier: // identifier
182     if (!WithOperator)
183       break;
184   default:
185     P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier);
186     P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
187                 Parser::StopBeforeMatch);
188     return DeclarationName();
189   }
190   P.ConsumeToken();
191   auto &DeclNames = Actions.getASTContext().DeclarationNames;
192   return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo())
193                         : DeclNames.getCXXOperatorName(OOK);
194 }
195 
196 /// \brief Parse 'omp declare reduction' construct.
197 ///
198 ///       declare-reduction-directive:
199 ///        annot_pragma_openmp 'declare' 'reduction'
200 ///        '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')'
201 ///        ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')']
202 ///        annot_pragma_openmp_end
203 /// <reduction_id> is either a base language identifier or one of the following
204 /// operators: '+', '-', '*', '&', '|', '^', '&&' and '||'.
205 ///
206 Parser::DeclGroupPtrTy
207 Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) {
208   // Parse '('.
209   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
210   if (T.expectAndConsume(diag::err_expected_lparen_after,
211                          getOpenMPDirectiveName(OMPD_declare_reduction))) {
212     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
213     return DeclGroupPtrTy();
214   }
215 
216   DeclarationName Name = parseOpenMPReductionId(*this);
217   if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end))
218     return DeclGroupPtrTy();
219 
220   // Consume ':'.
221   bool IsCorrect = !ExpectAndConsume(tok::colon);
222 
223   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
224     return DeclGroupPtrTy();
225 
226   IsCorrect = IsCorrect && !Name.isEmpty();
227 
228   if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) {
229     Diag(Tok.getLocation(), diag::err_expected_type);
230     IsCorrect = false;
231   }
232 
233   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
234     return DeclGroupPtrTy();
235 
236   SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes;
237   // Parse list of types until ':' token.
238   do {
239     ColonProtectionRAIIObject ColonRAII(*this);
240     SourceRange Range;
241     TypeResult TR = ParseTypeName(&Range, Declarator::PrototypeContext, AS);
242     if (TR.isUsable()) {
243       auto ReductionType =
244           Actions.ActOnOpenMPDeclareReductionType(Range.getBegin(), TR);
245       if (!ReductionType.isNull()) {
246         ReductionTypes.push_back(
247             std::make_pair(ReductionType, Range.getBegin()));
248       }
249     } else {
250       SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end,
251                 StopBeforeMatch);
252     }
253 
254     if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end))
255       break;
256 
257     // Consume ','.
258     if (ExpectAndConsume(tok::comma)) {
259       IsCorrect = false;
260       if (Tok.is(tok::annot_pragma_openmp_end)) {
261         Diag(Tok.getLocation(), diag::err_expected_type);
262         return DeclGroupPtrTy();
263       }
264     }
265   } while (Tok.isNot(tok::annot_pragma_openmp_end));
266 
267   if (ReductionTypes.empty()) {
268     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
269     return DeclGroupPtrTy();
270   }
271 
272   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
273     return DeclGroupPtrTy();
274 
275   // Consume ':'.
276   if (ExpectAndConsume(tok::colon))
277     IsCorrect = false;
278 
279   if (Tok.is(tok::annot_pragma_openmp_end)) {
280     Diag(Tok.getLocation(), diag::err_expected_expression);
281     return DeclGroupPtrTy();
282   }
283 
284   DeclGroupPtrTy DRD = Actions.ActOnOpenMPDeclareReductionDirectiveStart(
285       getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes, AS);
286 
287   // Parse <combiner> expression and then parse initializer if any for each
288   // correct type.
289   unsigned I = 0, E = ReductionTypes.size();
290   for (auto *D : DRD.get()) {
291     TentativeParsingAction TPA(*this);
292     ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
293                                     Scope::OpenMPDirectiveScope);
294     // Parse <combiner> expression.
295     Actions.ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D);
296     ExprResult CombinerResult =
297         Actions.ActOnFinishFullExpr(ParseAssignmentExpression().get(),
298                                     D->getLocation(), /*DiscardedValue=*/true);
299     Actions.ActOnOpenMPDeclareReductionCombinerEnd(D, CombinerResult.get());
300 
301     if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
302         Tok.isNot(tok::annot_pragma_openmp_end)) {
303       TPA.Commit();
304       IsCorrect = false;
305       break;
306     }
307     IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable();
308     ExprResult InitializerResult;
309     if (Tok.isNot(tok::annot_pragma_openmp_end)) {
310       // Parse <initializer> expression.
311       if (Tok.is(tok::identifier) &&
312           Tok.getIdentifierInfo()->isStr("initializer"))
313         ConsumeToken();
314       else {
315         Diag(Tok.getLocation(), diag::err_expected) << "'initializer'";
316         TPA.Commit();
317         IsCorrect = false;
318         break;
319       }
320       // Parse '('.
321       BalancedDelimiterTracker T(*this, tok::l_paren,
322                                  tok::annot_pragma_openmp_end);
323       IsCorrect =
324           !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") &&
325           IsCorrect;
326       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
327         ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
328                                         Scope::OpenMPDirectiveScope);
329         // Parse expression.
330         Actions.ActOnOpenMPDeclareReductionInitializerStart(getCurScope(), D);
331         InitializerResult = Actions.ActOnFinishFullExpr(
332             ParseAssignmentExpression().get(), D->getLocation(),
333             /*DiscardedValue=*/true);
334         Actions.ActOnOpenMPDeclareReductionInitializerEnd(
335             D, InitializerResult.get());
336         if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
337             Tok.isNot(tok::annot_pragma_openmp_end)) {
338           TPA.Commit();
339           IsCorrect = false;
340           break;
341         }
342         IsCorrect =
343             !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid();
344       }
345     }
346 
347     ++I;
348     // Revert parsing if not the last type, otherwise accept it, we're done with
349     // parsing.
350     if (I != E)
351       TPA.Revert();
352     else
353       TPA.Commit();
354   }
355   return Actions.ActOnOpenMPDeclareReductionDirectiveEnd(getCurScope(), DRD,
356                                                          IsCorrect);
357 }
358 
359 namespace {
360 /// RAII that recreates function context for correct parsing of clauses of
361 /// 'declare simd' construct.
362 /// OpenMP, 2.8.2 declare simd Construct
363 /// The expressions appearing in the clauses of this directive are evaluated in
364 /// the scope of the arguments of the function declaration or definition.
365 class FNContextRAII final {
366   Parser &P;
367   Sema::CXXThisScopeRAII *ThisScope;
368   Parser::ParseScope *TempScope;
369   Parser::ParseScope *FnScope;
370   bool HasTemplateScope = false;
371   bool HasFunScope = false;
372   FNContextRAII() = delete;
373   FNContextRAII(const FNContextRAII &) = delete;
374   FNContextRAII &operator=(const FNContextRAII &) = delete;
375 
376 public:
377   FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P) {
378     Decl *D = *Ptr.get().begin();
379     NamedDecl *ND = dyn_cast<NamedDecl>(D);
380     RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
381     Sema &Actions = P.getActions();
382 
383     // Allow 'this' within late-parsed attributes.
384     ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, /*TypeQuals=*/0,
385                                            ND && ND->isCXXInstanceMember());
386 
387     // If the Decl is templatized, add template parameters to scope.
388     HasTemplateScope = D->isTemplateDecl();
389     TempScope =
390         new Parser::ParseScope(&P, Scope::TemplateParamScope, HasTemplateScope);
391     if (HasTemplateScope)
392       Actions.ActOnReenterTemplateScope(Actions.getCurScope(), D);
393 
394     // If the Decl is on a function, add function parameters to the scope.
395     HasFunScope = D->isFunctionOrFunctionTemplate();
396     FnScope = new Parser::ParseScope(&P, Scope::FnScope | Scope::DeclScope,
397                                      HasFunScope);
398     if (HasFunScope)
399       Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D);
400   }
401   ~FNContextRAII() {
402     if (HasFunScope) {
403       P.getActions().ActOnExitFunctionContext();
404       FnScope->Exit(); // Pop scope, and remove Decls from IdResolver
405     }
406     if (HasTemplateScope)
407       TempScope->Exit();
408     delete FnScope;
409     delete TempScope;
410     delete ThisScope;
411   }
412 };
413 } // namespace
414 
415 /// Parses clauses for 'declare simd' directive.
416 ///    clause:
417 ///      'inbranch' | 'notinbranch'
418 ///      'simdlen' '(' <expr> ')'
419 ///      { 'uniform' '(' <argument_list> ')' }
420 ///      { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' }
421 ///      { 'linear '(' <argument_list> [ ':' <step> ] ')' }
422 static bool parseDeclareSimdClauses(
423     Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen,
424     SmallVectorImpl<Expr *> &Uniforms, SmallVectorImpl<Expr *> &Aligneds,
425     SmallVectorImpl<Expr *> &Alignments, SmallVectorImpl<Expr *> &Linears,
426     SmallVectorImpl<unsigned> &LinModifiers, SmallVectorImpl<Expr *> &Steps) {
427   SourceRange BSRange;
428   const Token &Tok = P.getCurToken();
429   bool IsError = false;
430   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
431     if (Tok.isNot(tok::identifier))
432       break;
433     OMPDeclareSimdDeclAttr::BranchStateTy Out;
434     IdentifierInfo *II = Tok.getIdentifierInfo();
435     StringRef ClauseName = II->getName();
436     // Parse 'inranch|notinbranch' clauses.
437     if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) {
438       if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) {
439         P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch)
440             << ClauseName
441             << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange;
442         IsError = true;
443       }
444       BS = Out;
445       BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc());
446       P.ConsumeToken();
447     } else if (ClauseName.equals("simdlen")) {
448       if (SimdLen.isUsable()) {
449         P.Diag(Tok, diag::err_omp_more_one_clause)
450             << getOpenMPDirectiveName(OMPD_declare_simd) << ClauseName << 0;
451         IsError = true;
452       }
453       P.ConsumeToken();
454       SourceLocation RLoc;
455       SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc);
456       if (SimdLen.isInvalid())
457         IsError = true;
458     } else {
459       OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName);
460       if (CKind == OMPC_uniform || CKind == OMPC_aligned ||
461           CKind == OMPC_linear) {
462         Parser::OpenMPVarListDataTy Data;
463         auto *Vars = &Uniforms;
464         if (CKind == OMPC_aligned)
465           Vars = &Aligneds;
466         else if (CKind == OMPC_linear)
467           Vars = &Linears;
468 
469         P.ConsumeToken();
470         if (P.ParseOpenMPVarList(OMPD_declare_simd,
471                                  getOpenMPClauseKind(ClauseName), *Vars, Data))
472           IsError = true;
473         if (CKind == OMPC_aligned)
474           Alignments.append(Aligneds.size() - Alignments.size(), Data.TailExpr);
475         else if (CKind == OMPC_linear) {
476           if (P.getActions().CheckOpenMPLinearModifier(Data.LinKind,
477                                                        Data.DepLinMapLoc))
478             Data.LinKind = OMPC_LINEAR_val;
479           LinModifiers.append(Linears.size() - LinModifiers.size(),
480                               Data.LinKind);
481           Steps.append(Linears.size() - Steps.size(), Data.TailExpr);
482         }
483       } else
484         // TODO: add parsing of other clauses.
485         break;
486     }
487     // Skip ',' if any.
488     if (Tok.is(tok::comma))
489       P.ConsumeToken();
490   }
491   return IsError;
492 }
493 
494 /// Parse clauses for '#pragma omp declare simd'.
495 Parser::DeclGroupPtrTy
496 Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr,
497                                    CachedTokens &Toks, SourceLocation Loc) {
498   PP.EnterToken(Tok);
499   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
500   // Consume the previously pushed token.
501   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
502 
503   FNContextRAII FnContext(*this, Ptr);
504   OMPDeclareSimdDeclAttr::BranchStateTy BS =
505       OMPDeclareSimdDeclAttr::BS_Undefined;
506   ExprResult Simdlen;
507   SmallVector<Expr *, 4> Uniforms;
508   SmallVector<Expr *, 4> Aligneds;
509   SmallVector<Expr *, 4> Alignments;
510   SmallVector<Expr *, 4> Linears;
511   SmallVector<unsigned, 4> LinModifiers;
512   SmallVector<Expr *, 4> Steps;
513   bool IsError =
514       parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds,
515                               Alignments, Linears, LinModifiers, Steps);
516   // Need to check for extra tokens.
517   if (Tok.isNot(tok::annot_pragma_openmp_end)) {
518     Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
519         << getOpenMPDirectiveName(OMPD_declare_simd);
520     while (Tok.isNot(tok::annot_pragma_openmp_end))
521       ConsumeAnyToken();
522   }
523   // Skip the last annot_pragma_openmp_end.
524   SourceLocation EndLoc = ConsumeToken();
525   if (!IsError) {
526     return Actions.ActOnOpenMPDeclareSimdDirective(
527         Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears,
528         LinModifiers, Steps, SourceRange(Loc, EndLoc));
529   }
530   return Ptr;
531 }
532 
533 /// \brief Parsing of declarative OpenMP directives.
534 ///
535 ///       threadprivate-directive:
536 ///         annot_pragma_openmp 'threadprivate' simple-variable-list
537 ///         annot_pragma_openmp_end
538 ///
539 ///       declare-reduction-directive:
540 ///        annot_pragma_openmp 'declare' 'reduction' [...]
541 ///        annot_pragma_openmp_end
542 ///
543 ///       declare-simd-directive:
544 ///         annot_pragma_openmp 'declare simd' {<clause> [,]}
545 ///         annot_pragma_openmp_end
546 ///         <function declaration/definition>
547 ///
548 Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
549     AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
550     DeclSpec::TST TagType, Decl *Tag) {
551   assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
552   ParenBraceBracketBalancer BalancerRAIIObj(*this);
553 
554   SourceLocation Loc = ConsumeToken();
555   auto DKind = ParseOpenMPDirectiveKind(*this);
556 
557   switch (DKind) {
558   case OMPD_threadprivate: {
559     ConsumeToken();
560     ThreadprivateListParserHelper Helper(this);
561     if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Helper, true)) {
562       // The last seen token is annot_pragma_openmp_end - need to check for
563       // extra tokens.
564       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
565         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
566             << getOpenMPDirectiveName(OMPD_threadprivate);
567         SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
568       }
569       // Skip the last annot_pragma_openmp_end.
570       ConsumeToken();
571       return Actions.ActOnOpenMPThreadprivateDirective(Loc,
572                                                        Helper.getIdentifiers());
573     }
574     break;
575   }
576   case OMPD_declare_reduction:
577     ConsumeToken();
578     if (auto Res = ParseOpenMPDeclareReductionDirective(AS)) {
579       // The last seen token is annot_pragma_openmp_end - need to check for
580       // extra tokens.
581       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
582         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
583             << getOpenMPDirectiveName(OMPD_declare_reduction);
584         while (Tok.isNot(tok::annot_pragma_openmp_end))
585           ConsumeAnyToken();
586       }
587       // Skip the last annot_pragma_openmp_end.
588       ConsumeToken();
589       return Res;
590     }
591     break;
592   case OMPD_declare_simd: {
593     // The syntax is:
594     // { #pragma omp declare simd }
595     // <function-declaration-or-definition>
596     //
597     ConsumeToken();
598     CachedTokens Toks;
599     while(Tok.isNot(tok::annot_pragma_openmp_end)) {
600       Toks.push_back(Tok);
601       ConsumeAnyToken();
602     }
603     Toks.push_back(Tok);
604     ConsumeAnyToken();
605 
606     DeclGroupPtrTy Ptr;
607     if (Tok.is(tok::annot_pragma_openmp))
608       Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, TagType, Tag);
609     else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
610       // Here we expect to see some function declaration.
611       if (AS == AS_none) {
612         assert(TagType == DeclSpec::TST_unspecified);
613         MaybeParseCXX11Attributes(Attrs);
614         MaybeParseMicrosoftAttributes(Attrs);
615         ParsingDeclSpec PDS(*this);
616         Ptr = ParseExternalDeclaration(Attrs, &PDS);
617       } else {
618         Ptr =
619             ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag);
620       }
621     }
622     if (!Ptr) {
623       Diag(Loc, diag::err_omp_decl_in_declare_simd);
624       return DeclGroupPtrTy();
625     }
626     return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc);
627   }
628   case OMPD_declare_target: {
629     SourceLocation DTLoc = ConsumeAnyToken();
630     if (Tok.isNot(tok::annot_pragma_openmp_end)) {
631       // OpenMP 4.5 syntax with list of entities.
632       llvm::SmallSetVector<const NamedDecl*, 16> SameDirectiveDecls;
633       while (Tok.isNot(tok::annot_pragma_openmp_end)) {
634         OMPDeclareTargetDeclAttr::MapTypeTy MT =
635             OMPDeclareTargetDeclAttr::MT_To;
636         if (Tok.is(tok::identifier)) {
637           IdentifierInfo *II = Tok.getIdentifierInfo();
638           StringRef ClauseName = II->getName();
639           // Parse 'to|link' clauses.
640           if (!OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName,
641                                                                MT)) {
642             Diag(Tok, diag::err_omp_declare_target_unexpected_clause)
643                 << ClauseName;
644             break;
645           }
646           ConsumeToken();
647         }
648         auto Callback = [this, MT, &SameDirectiveDecls](
649             CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
650           Actions.ActOnOpenMPDeclareTargetName(getCurScope(), SS, NameInfo, MT,
651                                                SameDirectiveDecls);
652         };
653         if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback, true))
654           break;
655 
656         // Consume optional ','.
657         if (Tok.is(tok::comma))
658           ConsumeToken();
659       }
660       SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
661       ConsumeAnyToken();
662       return DeclGroupPtrTy();
663     }
664 
665     // Skip the last annot_pragma_openmp_end.
666     ConsumeAnyToken();
667 
668     if (!Actions.ActOnStartOpenMPDeclareTargetDirective(DTLoc))
669       return DeclGroupPtrTy();
670 
671     DKind = ParseOpenMPDirectiveKind(*this);
672     while (DKind != OMPD_end_declare_target && DKind != OMPD_declare_target &&
673            Tok.isNot(tok::eof) && Tok.isNot(tok::r_brace)) {
674       ParsedAttributesWithRange attrs(AttrFactory);
675       MaybeParseCXX11Attributes(attrs);
676       MaybeParseMicrosoftAttributes(attrs);
677       ParseExternalDeclaration(attrs);
678       if (Tok.isAnnotation() && Tok.is(tok::annot_pragma_openmp)) {
679         TentativeParsingAction TPA(*this);
680         ConsumeToken();
681         DKind = ParseOpenMPDirectiveKind(*this);
682         if (DKind != OMPD_end_declare_target)
683           TPA.Revert();
684         else
685           TPA.Commit();
686       }
687     }
688 
689     if (DKind == OMPD_end_declare_target) {
690       ConsumeAnyToken();
691       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
692         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
693             << getOpenMPDirectiveName(OMPD_end_declare_target);
694         SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
695       }
696       // Skip the last annot_pragma_openmp_end.
697       ConsumeAnyToken();
698     } else {
699       Diag(Tok, diag::err_expected_end_declare_target);
700       Diag(DTLoc, diag::note_matching) << "'#pragma omp declare target'";
701     }
702     Actions.ActOnFinishOpenMPDeclareTargetDirective();
703     return DeclGroupPtrTy();
704   }
705   case OMPD_unknown:
706     Diag(Tok, diag::err_omp_unknown_directive);
707     break;
708   case OMPD_parallel:
709   case OMPD_simd:
710   case OMPD_task:
711   case OMPD_taskyield:
712   case OMPD_barrier:
713   case OMPD_taskwait:
714   case OMPD_taskgroup:
715   case OMPD_flush:
716   case OMPD_for:
717   case OMPD_for_simd:
718   case OMPD_sections:
719   case OMPD_section:
720   case OMPD_single:
721   case OMPD_master:
722   case OMPD_ordered:
723   case OMPD_critical:
724   case OMPD_parallel_for:
725   case OMPD_parallel_for_simd:
726   case OMPD_parallel_sections:
727   case OMPD_atomic:
728   case OMPD_target:
729   case OMPD_teams:
730   case OMPD_cancellation_point:
731   case OMPD_cancel:
732   case OMPD_target_data:
733   case OMPD_target_enter_data:
734   case OMPD_target_exit_data:
735   case OMPD_target_parallel:
736   case OMPD_target_parallel_for:
737   case OMPD_taskloop:
738   case OMPD_taskloop_simd:
739   case OMPD_distribute:
740   case OMPD_end_declare_target:
741   case OMPD_target_update:
742   case OMPD_distribute_parallel_for:
743   case OMPD_distribute_parallel_for_simd:
744   case OMPD_distribute_simd:
745   case OMPD_target_parallel_for_simd:
746   case OMPD_target_simd:
747   case OMPD_teams_distribute:
748   case OMPD_teams_distribute_simd:
749     Diag(Tok, diag::err_omp_unexpected_directive)
750         << getOpenMPDirectiveName(DKind);
751     break;
752   }
753   while (Tok.isNot(tok::annot_pragma_openmp_end))
754     ConsumeAnyToken();
755   ConsumeAnyToken();
756   return nullptr;
757 }
758 
759 /// \brief Parsing of declarative or executable OpenMP directives.
760 ///
761 ///       threadprivate-directive:
762 ///         annot_pragma_openmp 'threadprivate' simple-variable-list
763 ///         annot_pragma_openmp_end
764 ///
765 ///       declare-reduction-directive:
766 ///         annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':'
767 ///         <type> {',' <type>} ':' <expression> ')' ['initializer' '('
768 ///         ('omp_priv' '=' <expression>|<function_call>) ')']
769 ///         annot_pragma_openmp_end
770 ///
771 ///       executable-directive:
772 ///         annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
773 ///         'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
774 ///         'parallel for' | 'parallel sections' | 'task' | 'taskyield' |
775 ///         'barrier' | 'taskwait' | 'flush' | 'ordered' | 'atomic' |
776 ///         'for simd' | 'parallel for simd' | 'target' | 'target data' |
777 ///         'taskgroup' | 'teams' | 'taskloop' | 'taskloop simd' |
778 ///         'distribute' | 'target enter data' | 'target exit data' |
779 ///         'target parallel' | 'target parallel for' |
780 ///         'target update' | 'distribute parallel for' |
781 ///         'distribute paralle for simd' | 'distribute simd' |
782 ///         'target parallel for simd' | 'target simd' |
783 ///         'teams distribute' | 'teams distribute simd' {clause}
784 ///         annot_pragma_openmp_end
785 ///
786 StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
787     AllowedContsructsKind Allowed) {
788   assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
789   ParenBraceBracketBalancer BalancerRAIIObj(*this);
790   SmallVector<OMPClause *, 5> Clauses;
791   SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, OMPC_unknown + 1>
792   FirstClauses(OMPC_unknown + 1);
793   unsigned ScopeFlags =
794       Scope::FnScope | Scope::DeclScope | Scope::OpenMPDirectiveScope;
795   SourceLocation Loc = ConsumeToken(), EndLoc;
796   auto DKind = ParseOpenMPDirectiveKind(*this);
797   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
798   // Name of critical directive.
799   DeclarationNameInfo DirName;
800   StmtResult Directive = StmtError();
801   bool HasAssociatedStatement = true;
802   bool FlushHasClause = false;
803 
804   switch (DKind) {
805   case OMPD_threadprivate: {
806     if (Allowed != ACK_Any) {
807       Diag(Tok, diag::err_omp_immediate_directive)
808           << getOpenMPDirectiveName(DKind) << 0;
809     }
810     ConsumeToken();
811     ThreadprivateListParserHelper Helper(this);
812     if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Helper, false)) {
813       // The last seen token is annot_pragma_openmp_end - need to check for
814       // extra tokens.
815       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
816         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
817             << getOpenMPDirectiveName(OMPD_threadprivate);
818         SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
819       }
820       DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective(
821           Loc, Helper.getIdentifiers());
822       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
823     }
824     SkipUntil(tok::annot_pragma_openmp_end);
825     break;
826   }
827   case OMPD_declare_reduction:
828     ConsumeToken();
829     if (auto Res = ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) {
830       // The last seen token is annot_pragma_openmp_end - need to check for
831       // extra tokens.
832       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
833         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
834             << getOpenMPDirectiveName(OMPD_declare_reduction);
835         while (Tok.isNot(tok::annot_pragma_openmp_end))
836           ConsumeAnyToken();
837       }
838       ConsumeAnyToken();
839       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
840     } else
841       SkipUntil(tok::annot_pragma_openmp_end);
842     break;
843   case OMPD_flush:
844     if (PP.LookAhead(0).is(tok::l_paren)) {
845       FlushHasClause = true;
846       // Push copy of the current token back to stream to properly parse
847       // pseudo-clause OMPFlushClause.
848       PP.EnterToken(Tok);
849     }
850   case OMPD_taskyield:
851   case OMPD_barrier:
852   case OMPD_taskwait:
853   case OMPD_cancellation_point:
854   case OMPD_cancel:
855   case OMPD_target_enter_data:
856   case OMPD_target_exit_data:
857   case OMPD_target_update:
858     if (Allowed == ACK_StatementsOpenMPNonStandalone) {
859       Diag(Tok, diag::err_omp_immediate_directive)
860           << getOpenMPDirectiveName(DKind) << 0;
861     }
862     HasAssociatedStatement = false;
863     // Fall through for further analysis.
864   case OMPD_parallel:
865   case OMPD_simd:
866   case OMPD_for:
867   case OMPD_for_simd:
868   case OMPD_sections:
869   case OMPD_single:
870   case OMPD_section:
871   case OMPD_master:
872   case OMPD_critical:
873   case OMPD_parallel_for:
874   case OMPD_parallel_for_simd:
875   case OMPD_parallel_sections:
876   case OMPD_task:
877   case OMPD_ordered:
878   case OMPD_atomic:
879   case OMPD_target:
880   case OMPD_teams:
881   case OMPD_taskgroup:
882   case OMPD_target_data:
883   case OMPD_target_parallel:
884   case OMPD_target_parallel_for:
885   case OMPD_taskloop:
886   case OMPD_taskloop_simd:
887   case OMPD_distribute:
888   case OMPD_distribute_parallel_for:
889   case OMPD_distribute_parallel_for_simd:
890   case OMPD_distribute_simd:
891   case OMPD_target_parallel_for_simd:
892   case OMPD_target_simd:
893   case OMPD_teams_distribute:
894   case OMPD_teams_distribute_simd: {
895     ConsumeToken();
896     // Parse directive name of the 'critical' directive if any.
897     if (DKind == OMPD_critical) {
898       BalancedDelimiterTracker T(*this, tok::l_paren,
899                                  tok::annot_pragma_openmp_end);
900       if (!T.consumeOpen()) {
901         if (Tok.isAnyIdentifier()) {
902           DirName =
903               DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation());
904           ConsumeAnyToken();
905         } else {
906           Diag(Tok, diag::err_omp_expected_identifier_for_critical);
907         }
908         T.consumeClose();
909       }
910     } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) {
911       CancelRegion = ParseOpenMPDirectiveKind(*this);
912       if (Tok.isNot(tok::annot_pragma_openmp_end))
913         ConsumeToken();
914     }
915 
916     if (isOpenMPLoopDirective(DKind))
917       ScopeFlags |= Scope::OpenMPLoopDirectiveScope;
918     if (isOpenMPSimdDirective(DKind))
919       ScopeFlags |= Scope::OpenMPSimdDirectiveScope;
920     ParseScope OMPDirectiveScope(this, ScopeFlags);
921     Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc);
922 
923     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
924       OpenMPClauseKind CKind =
925           Tok.isAnnotation()
926               ? OMPC_unknown
927               : FlushHasClause ? OMPC_flush
928                                : getOpenMPClauseKind(PP.getSpelling(Tok));
929       Actions.StartOpenMPClause(CKind);
930       FlushHasClause = false;
931       OMPClause *Clause =
932           ParseOpenMPClause(DKind, CKind, !FirstClauses[CKind].getInt());
933       FirstClauses[CKind].setInt(true);
934       if (Clause) {
935         FirstClauses[CKind].setPointer(Clause);
936         Clauses.push_back(Clause);
937       }
938 
939       // Skip ',' if any.
940       if (Tok.is(tok::comma))
941         ConsumeToken();
942       Actions.EndOpenMPClause();
943     }
944     // End location of the directive.
945     EndLoc = Tok.getLocation();
946     // Consume final annot_pragma_openmp_end.
947     ConsumeToken();
948 
949     // OpenMP [2.13.8, ordered Construct, Syntax]
950     // If the depend clause is specified, the ordered construct is a stand-alone
951     // directive.
952     if (DKind == OMPD_ordered && FirstClauses[OMPC_depend].getInt()) {
953       if (Allowed == ACK_StatementsOpenMPNonStandalone) {
954         Diag(Loc, diag::err_omp_immediate_directive)
955             << getOpenMPDirectiveName(DKind) << 1
956             << getOpenMPClauseName(OMPC_depend);
957       }
958       HasAssociatedStatement = false;
959     }
960 
961     StmtResult AssociatedStmt;
962     if (HasAssociatedStatement) {
963       // The body is a block scope like in Lambdas and Blocks.
964       Sema::CompoundScopeRAII CompoundScope(Actions);
965       Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
966       Actions.ActOnStartOfCompoundStmt();
967       // Parse statement
968       AssociatedStmt = ParseStatement();
969       Actions.ActOnFinishOfCompoundStmt();
970       AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
971     }
972     Directive = Actions.ActOnOpenMPExecutableDirective(
973         DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc,
974         EndLoc);
975 
976     // Exit scope.
977     Actions.EndOpenMPDSABlock(Directive.get());
978     OMPDirectiveScope.Exit();
979     break;
980   }
981   case OMPD_declare_simd:
982   case OMPD_declare_target:
983   case OMPD_end_declare_target:
984     Diag(Tok, diag::err_omp_unexpected_directive)
985         << getOpenMPDirectiveName(DKind);
986     SkipUntil(tok::annot_pragma_openmp_end);
987     break;
988   case OMPD_unknown:
989     Diag(Tok, diag::err_omp_unknown_directive);
990     SkipUntil(tok::annot_pragma_openmp_end);
991     break;
992   }
993   return Directive;
994 }
995 
996 // Parses simple list:
997 //   simple-variable-list:
998 //         '(' id-expression {, id-expression} ')'
999 //
1000 bool Parser::ParseOpenMPSimpleVarList(
1001     OpenMPDirectiveKind Kind,
1002     const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
1003         Callback,
1004     bool AllowScopeSpecifier) {
1005   // Parse '('.
1006   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1007   if (T.expectAndConsume(diag::err_expected_lparen_after,
1008                          getOpenMPDirectiveName(Kind)))
1009     return true;
1010   bool IsCorrect = true;
1011   bool NoIdentIsFound = true;
1012 
1013   // Read tokens while ')' or annot_pragma_openmp_end is not found.
1014   while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
1015     CXXScopeSpec SS;
1016     SourceLocation TemplateKWLoc;
1017     UnqualifiedId Name;
1018     // Read var name.
1019     Token PrevTok = Tok;
1020     NoIdentIsFound = false;
1021 
1022     if (AllowScopeSpecifier && getLangOpts().CPlusPlus &&
1023         ParseOptionalCXXScopeSpecifier(SS, nullptr, false)) {
1024       IsCorrect = false;
1025       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1026                 StopBeforeMatch);
1027     } else if (ParseUnqualifiedId(SS, false, false, false, nullptr,
1028                                   TemplateKWLoc, Name)) {
1029       IsCorrect = false;
1030       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1031                 StopBeforeMatch);
1032     } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) &&
1033                Tok.isNot(tok::annot_pragma_openmp_end)) {
1034       IsCorrect = false;
1035       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1036                 StopBeforeMatch);
1037       Diag(PrevTok.getLocation(), diag::err_expected)
1038           << tok::identifier
1039           << SourceRange(PrevTok.getLocation(), PrevTokLocation);
1040     } else {
1041       Callback(SS, Actions.GetNameFromUnqualifiedId(Name));
1042     }
1043     // Consume ','.
1044     if (Tok.is(tok::comma)) {
1045       ConsumeToken();
1046     }
1047   }
1048 
1049   if (NoIdentIsFound) {
1050     Diag(Tok, diag::err_expected) << tok::identifier;
1051     IsCorrect = false;
1052   }
1053 
1054   // Parse ')'.
1055   IsCorrect = !T.consumeClose() && IsCorrect;
1056 
1057   return !IsCorrect;
1058 }
1059 
1060 /// \brief Parsing of OpenMP clauses.
1061 ///
1062 ///    clause:
1063 ///       if-clause | final-clause | num_threads-clause | safelen-clause |
1064 ///       default-clause | private-clause | firstprivate-clause | shared-clause
1065 ///       | linear-clause | aligned-clause | collapse-clause |
1066 ///       lastprivate-clause | reduction-clause | proc_bind-clause |
1067 ///       schedule-clause | copyin-clause | copyprivate-clause | untied-clause |
1068 ///       mergeable-clause | flush-clause | read-clause | write-clause |
1069 ///       update-clause | capture-clause | seq_cst-clause | device-clause |
1070 ///       simdlen-clause | threads-clause | simd-clause | num_teams-clause |
1071 ///       thread_limit-clause | priority-clause | grainsize-clause |
1072 ///       nogroup-clause | num_tasks-clause | hint-clause | to-clause |
1073 ///       from-clause | is_device_ptr-clause
1074 ///
1075 OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind,
1076                                      OpenMPClauseKind CKind, bool FirstClause) {
1077   OMPClause *Clause = nullptr;
1078   bool ErrorFound = false;
1079   // Check if clause is allowed for the given directive.
1080   if (CKind != OMPC_unknown && !isAllowedClauseForDirective(DKind, CKind)) {
1081     Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind)
1082                                                << getOpenMPDirectiveName(DKind);
1083     ErrorFound = true;
1084   }
1085 
1086   switch (CKind) {
1087   case OMPC_final:
1088   case OMPC_num_threads:
1089   case OMPC_safelen:
1090   case OMPC_simdlen:
1091   case OMPC_collapse:
1092   case OMPC_ordered:
1093   case OMPC_device:
1094   case OMPC_num_teams:
1095   case OMPC_thread_limit:
1096   case OMPC_priority:
1097   case OMPC_grainsize:
1098   case OMPC_num_tasks:
1099   case OMPC_hint:
1100     // OpenMP [2.5, Restrictions]
1101     //  At most one num_threads clause can appear on the directive.
1102     // OpenMP [2.8.1, simd construct, Restrictions]
1103     //  Only one safelen  clause can appear on a simd directive.
1104     //  Only one simdlen  clause can appear on a simd directive.
1105     //  Only one collapse clause can appear on a simd directive.
1106     // OpenMP [2.9.1, target data construct, Restrictions]
1107     //  At most one device clause can appear on the directive.
1108     // OpenMP [2.11.1, task Construct, Restrictions]
1109     //  At most one if clause can appear on the directive.
1110     //  At most one final clause can appear on the directive.
1111     // OpenMP [teams Construct, Restrictions]
1112     //  At most one num_teams clause can appear on the directive.
1113     //  At most one thread_limit clause can appear on the directive.
1114     // OpenMP [2.9.1, task Construct, Restrictions]
1115     // At most one priority clause can appear on the directive.
1116     // OpenMP [2.9.2, taskloop Construct, Restrictions]
1117     // At most one grainsize clause can appear on the directive.
1118     // OpenMP [2.9.2, taskloop Construct, Restrictions]
1119     // At most one num_tasks clause can appear on the directive.
1120     if (!FirstClause) {
1121       Diag(Tok, diag::err_omp_more_one_clause)
1122           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1123       ErrorFound = true;
1124     }
1125 
1126     if (CKind == OMPC_ordered && PP.LookAhead(/*N=*/0).isNot(tok::l_paren))
1127       Clause = ParseOpenMPClause(CKind);
1128     else
1129       Clause = ParseOpenMPSingleExprClause(CKind);
1130     break;
1131   case OMPC_default:
1132   case OMPC_proc_bind:
1133     // OpenMP [2.14.3.1, Restrictions]
1134     //  Only a single default clause may be specified on a parallel, task or
1135     //  teams directive.
1136     // OpenMP [2.5, parallel Construct, Restrictions]
1137     //  At most one proc_bind clause can appear on the directive.
1138     if (!FirstClause) {
1139       Diag(Tok, diag::err_omp_more_one_clause)
1140           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1141       ErrorFound = true;
1142     }
1143 
1144     Clause = ParseOpenMPSimpleClause(CKind);
1145     break;
1146   case OMPC_schedule:
1147   case OMPC_dist_schedule:
1148   case OMPC_defaultmap:
1149     // OpenMP [2.7.1, Restrictions, p. 3]
1150     //  Only one schedule clause can appear on a loop directive.
1151     // OpenMP [2.10.4, Restrictions, p. 106]
1152     //  At most one defaultmap clause can appear on the directive.
1153     if (!FirstClause) {
1154       Diag(Tok, diag::err_omp_more_one_clause)
1155           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1156       ErrorFound = true;
1157     }
1158 
1159   case OMPC_if:
1160     Clause = ParseOpenMPSingleExprWithArgClause(CKind);
1161     break;
1162   case OMPC_nowait:
1163   case OMPC_untied:
1164   case OMPC_mergeable:
1165   case OMPC_read:
1166   case OMPC_write:
1167   case OMPC_update:
1168   case OMPC_capture:
1169   case OMPC_seq_cst:
1170   case OMPC_threads:
1171   case OMPC_simd:
1172   case OMPC_nogroup:
1173     // OpenMP [2.7.1, Restrictions, p. 9]
1174     //  Only one ordered clause can appear on a loop directive.
1175     // OpenMP [2.7.1, Restrictions, C/C++, p. 4]
1176     //  Only one nowait clause can appear on a for directive.
1177     if (!FirstClause) {
1178       Diag(Tok, diag::err_omp_more_one_clause)
1179           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1180       ErrorFound = true;
1181     }
1182 
1183     Clause = ParseOpenMPClause(CKind);
1184     break;
1185   case OMPC_private:
1186   case OMPC_firstprivate:
1187   case OMPC_lastprivate:
1188   case OMPC_shared:
1189   case OMPC_reduction:
1190   case OMPC_linear:
1191   case OMPC_aligned:
1192   case OMPC_copyin:
1193   case OMPC_copyprivate:
1194   case OMPC_flush:
1195   case OMPC_depend:
1196   case OMPC_map:
1197   case OMPC_to:
1198   case OMPC_from:
1199   case OMPC_use_device_ptr:
1200   case OMPC_is_device_ptr:
1201     Clause = ParseOpenMPVarListClause(DKind, CKind);
1202     break;
1203   case OMPC_unknown:
1204     Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
1205         << getOpenMPDirectiveName(DKind);
1206     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1207     break;
1208   case OMPC_threadprivate:
1209   case OMPC_uniform:
1210     Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind)
1211                                                << getOpenMPDirectiveName(DKind);
1212     SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch);
1213     break;
1214   }
1215   return ErrorFound ? nullptr : Clause;
1216 }
1217 
1218 /// Parses simple expression in parens for single-expression clauses of OpenMP
1219 /// constructs.
1220 /// \param RLoc Returned location of right paren.
1221 ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName,
1222                                          SourceLocation &RLoc) {
1223   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1224   if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data()))
1225     return ExprError();
1226 
1227   SourceLocation ELoc = Tok.getLocation();
1228   ExprResult LHS(ParseCastExpression(
1229       /*isUnaryExpression=*/false, /*isAddressOfOperand=*/false, NotTypeCast));
1230   ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
1231   Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc);
1232 
1233   // Parse ')'.
1234   T.consumeClose();
1235 
1236   RLoc = T.getCloseLocation();
1237   return Val;
1238 }
1239 
1240 /// \brief Parsing of OpenMP clauses with single expressions like 'final',
1241 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
1242 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks' or 'hint'.
1243 ///
1244 ///    final-clause:
1245 ///      'final' '(' expression ')'
1246 ///
1247 ///    num_threads-clause:
1248 ///      'num_threads' '(' expression ')'
1249 ///
1250 ///    safelen-clause:
1251 ///      'safelen' '(' expression ')'
1252 ///
1253 ///    simdlen-clause:
1254 ///      'simdlen' '(' expression ')'
1255 ///
1256 ///    collapse-clause:
1257 ///      'collapse' '(' expression ')'
1258 ///
1259 ///    priority-clause:
1260 ///      'priority' '(' expression ')'
1261 ///
1262 ///    grainsize-clause:
1263 ///      'grainsize' '(' expression ')'
1264 ///
1265 ///    num_tasks-clause:
1266 ///      'num_tasks' '(' expression ')'
1267 ///
1268 ///    hint-clause:
1269 ///      'hint' '(' expression ')'
1270 ///
1271 OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind) {
1272   SourceLocation Loc = ConsumeToken();
1273   SourceLocation LLoc = Tok.getLocation();
1274   SourceLocation RLoc;
1275 
1276   ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
1277 
1278   if (Val.isInvalid())
1279     return nullptr;
1280 
1281   return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc);
1282 }
1283 
1284 /// \brief Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
1285 ///
1286 ///    default-clause:
1287 ///         'default' '(' 'none' | 'shared' ')
1288 ///
1289 ///    proc_bind-clause:
1290 ///         'proc_bind' '(' 'master' | 'close' | 'spread' ')
1291 ///
1292 OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind) {
1293   SourceLocation Loc = Tok.getLocation();
1294   SourceLocation LOpen = ConsumeToken();
1295   // Parse '('.
1296   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1297   if (T.expectAndConsume(diag::err_expected_lparen_after,
1298                          getOpenMPClauseName(Kind)))
1299     return nullptr;
1300 
1301   unsigned Type = getOpenMPSimpleClauseType(
1302       Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1303   SourceLocation TypeLoc = Tok.getLocation();
1304   if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1305       Tok.isNot(tok::annot_pragma_openmp_end))
1306     ConsumeAnyToken();
1307 
1308   // Parse ')'.
1309   T.consumeClose();
1310 
1311   return Actions.ActOnOpenMPSimpleClause(Kind, Type, TypeLoc, LOpen, Loc,
1312                                          Tok.getLocation());
1313 }
1314 
1315 /// \brief Parsing of OpenMP clauses like 'ordered'.
1316 ///
1317 ///    ordered-clause:
1318 ///         'ordered'
1319 ///
1320 ///    nowait-clause:
1321 ///         'nowait'
1322 ///
1323 ///    untied-clause:
1324 ///         'untied'
1325 ///
1326 ///    mergeable-clause:
1327 ///         'mergeable'
1328 ///
1329 ///    read-clause:
1330 ///         'read'
1331 ///
1332 ///    threads-clause:
1333 ///         'threads'
1334 ///
1335 ///    simd-clause:
1336 ///         'simd'
1337 ///
1338 ///    nogroup-clause:
1339 ///         'nogroup'
1340 ///
1341 OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind) {
1342   SourceLocation Loc = Tok.getLocation();
1343   ConsumeAnyToken();
1344 
1345   return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation());
1346 }
1347 
1348 
1349 /// \brief Parsing of OpenMP clauses with single expressions and some additional
1350 /// argument like 'schedule' or 'dist_schedule'.
1351 ///
1352 ///    schedule-clause:
1353 ///      'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
1354 ///      ')'
1355 ///
1356 ///    if-clause:
1357 ///      'if' '(' [ directive-name-modifier ':' ] expression ')'
1358 ///
1359 ///    defaultmap:
1360 ///      'defaultmap' '(' modifier ':' kind ')'
1361 ///
1362 OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind) {
1363   SourceLocation Loc = ConsumeToken();
1364   SourceLocation DelimLoc;
1365   // Parse '('.
1366   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1367   if (T.expectAndConsume(diag::err_expected_lparen_after,
1368                          getOpenMPClauseName(Kind)))
1369     return nullptr;
1370 
1371   ExprResult Val;
1372   SmallVector<unsigned, 4> Arg;
1373   SmallVector<SourceLocation, 4> KLoc;
1374   if (Kind == OMPC_schedule) {
1375     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
1376     Arg.resize(NumberOfElements);
1377     KLoc.resize(NumberOfElements);
1378     Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown;
1379     Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown;
1380     Arg[ScheduleKind] = OMPC_SCHEDULE_unknown;
1381     auto KindModifier = getOpenMPSimpleClauseType(
1382         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1383     if (KindModifier > OMPC_SCHEDULE_unknown) {
1384       // Parse 'modifier'
1385       Arg[Modifier1] = KindModifier;
1386       KLoc[Modifier1] = Tok.getLocation();
1387       if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1388           Tok.isNot(tok::annot_pragma_openmp_end))
1389         ConsumeAnyToken();
1390       if (Tok.is(tok::comma)) {
1391         // Parse ',' 'modifier'
1392         ConsumeAnyToken();
1393         KindModifier = getOpenMPSimpleClauseType(
1394             Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1395         Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown
1396                              ? KindModifier
1397                              : (unsigned)OMPC_SCHEDULE_unknown;
1398         KLoc[Modifier2] = Tok.getLocation();
1399         if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1400             Tok.isNot(tok::annot_pragma_openmp_end))
1401           ConsumeAnyToken();
1402       }
1403       // Parse ':'
1404       if (Tok.is(tok::colon))
1405         ConsumeAnyToken();
1406       else
1407         Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier";
1408       KindModifier = getOpenMPSimpleClauseType(
1409           Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1410     }
1411     Arg[ScheduleKind] = KindModifier;
1412     KLoc[ScheduleKind] = Tok.getLocation();
1413     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1414         Tok.isNot(tok::annot_pragma_openmp_end))
1415       ConsumeAnyToken();
1416     if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static ||
1417          Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic ||
1418          Arg[ScheduleKind] == OMPC_SCHEDULE_guided) &&
1419         Tok.is(tok::comma))
1420       DelimLoc = ConsumeAnyToken();
1421   } else if (Kind == OMPC_dist_schedule) {
1422     Arg.push_back(getOpenMPSimpleClauseType(
1423         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1424     KLoc.push_back(Tok.getLocation());
1425     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1426         Tok.isNot(tok::annot_pragma_openmp_end))
1427       ConsumeAnyToken();
1428     if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma))
1429       DelimLoc = ConsumeAnyToken();
1430   } else if (Kind == OMPC_defaultmap) {
1431     // Get a defaultmap modifier
1432     Arg.push_back(getOpenMPSimpleClauseType(
1433         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1434     KLoc.push_back(Tok.getLocation());
1435     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1436         Tok.isNot(tok::annot_pragma_openmp_end))
1437       ConsumeAnyToken();
1438     // Parse ':'
1439     if (Tok.is(tok::colon))
1440       ConsumeAnyToken();
1441     else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown)
1442       Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier";
1443     // Get a defaultmap kind
1444     Arg.push_back(getOpenMPSimpleClauseType(
1445         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1446     KLoc.push_back(Tok.getLocation());
1447     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1448         Tok.isNot(tok::annot_pragma_openmp_end))
1449       ConsumeAnyToken();
1450   } else {
1451     assert(Kind == OMPC_if);
1452     KLoc.push_back(Tok.getLocation());
1453     Arg.push_back(ParseOpenMPDirectiveKind(*this));
1454     if (Arg.back() != OMPD_unknown) {
1455       ConsumeToken();
1456       if (Tok.is(tok::colon))
1457         DelimLoc = ConsumeToken();
1458       else
1459         Diag(Tok, diag::warn_pragma_expected_colon)
1460             << "directive name modifier";
1461     }
1462   }
1463 
1464   bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) ||
1465                           (Kind == OMPC_dist_schedule && DelimLoc.isValid()) ||
1466                           Kind == OMPC_if;
1467   if (NeedAnExpression) {
1468     SourceLocation ELoc = Tok.getLocation();
1469     ExprResult LHS(ParseCastExpression(false, false, NotTypeCast));
1470     Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
1471     Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc);
1472   }
1473 
1474   // Parse ')'.
1475   T.consumeClose();
1476 
1477   if (NeedAnExpression && Val.isInvalid())
1478     return nullptr;
1479 
1480   return Actions.ActOnOpenMPSingleExprWithArgClause(
1481       Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc,
1482       T.getCloseLocation());
1483 }
1484 
1485 static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec,
1486                              UnqualifiedId &ReductionId) {
1487   SourceLocation TemplateKWLoc;
1488   if (ReductionIdScopeSpec.isEmpty()) {
1489     auto OOK = OO_None;
1490     switch (P.getCurToken().getKind()) {
1491     case tok::plus:
1492       OOK = OO_Plus;
1493       break;
1494     case tok::minus:
1495       OOK = OO_Minus;
1496       break;
1497     case tok::star:
1498       OOK = OO_Star;
1499       break;
1500     case tok::amp:
1501       OOK = OO_Amp;
1502       break;
1503     case tok::pipe:
1504       OOK = OO_Pipe;
1505       break;
1506     case tok::caret:
1507       OOK = OO_Caret;
1508       break;
1509     case tok::ampamp:
1510       OOK = OO_AmpAmp;
1511       break;
1512     case tok::pipepipe:
1513       OOK = OO_PipePipe;
1514       break;
1515     default:
1516       break;
1517     }
1518     if (OOK != OO_None) {
1519       SourceLocation OpLoc = P.ConsumeToken();
1520       SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()};
1521       ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations);
1522       return false;
1523     }
1524   }
1525   return P.ParseUnqualifiedId(ReductionIdScopeSpec, /*EnteringContext*/ false,
1526                               /*AllowDestructorName*/ false,
1527                               /*AllowConstructorName*/ false, nullptr,
1528                               TemplateKWLoc, ReductionId);
1529 }
1530 
1531 /// Parses clauses with list.
1532 bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind,
1533                                 OpenMPClauseKind Kind,
1534                                 SmallVectorImpl<Expr *> &Vars,
1535                                 OpenMPVarListDataTy &Data) {
1536   UnqualifiedId UnqualifiedReductionId;
1537   bool InvalidReductionId = false;
1538   bool MapTypeModifierSpecified = false;
1539 
1540   // Parse '('.
1541   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1542   if (T.expectAndConsume(diag::err_expected_lparen_after,
1543                          getOpenMPClauseName(Kind)))
1544     return true;
1545 
1546   bool NeedRParenForLinear = false;
1547   BalancedDelimiterTracker LinearT(*this, tok::l_paren,
1548                                   tok::annot_pragma_openmp_end);
1549   // Handle reduction-identifier for reduction clause.
1550   if (Kind == OMPC_reduction) {
1551     ColonProtectionRAIIObject ColonRAII(*this);
1552     if (getLangOpts().CPlusPlus)
1553       ParseOptionalCXXScopeSpecifier(Data.ReductionIdScopeSpec,
1554                                      /*ObjectType=*/nullptr,
1555                                      /*EnteringContext=*/false);
1556     InvalidReductionId = ParseReductionId(*this, Data.ReductionIdScopeSpec,
1557                                           UnqualifiedReductionId);
1558     if (InvalidReductionId) {
1559       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
1560                 StopBeforeMatch);
1561     }
1562     if (Tok.is(tok::colon))
1563       Data.ColonLoc = ConsumeToken();
1564     else
1565       Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier";
1566     if (!InvalidReductionId)
1567       Data.ReductionId =
1568           Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId);
1569   } else if (Kind == OMPC_depend) {
1570   // Handle dependency type for depend clause.
1571     ColonProtectionRAIIObject ColonRAII(*this);
1572     Data.DepKind =
1573         static_cast<OpenMPDependClauseKind>(getOpenMPSimpleClauseType(
1574             Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : ""));
1575     Data.DepLinMapLoc = Tok.getLocation();
1576 
1577     if (Data.DepKind == OMPC_DEPEND_unknown) {
1578       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
1579                 StopBeforeMatch);
1580     } else {
1581       ConsumeToken();
1582       // Special processing for depend(source) clause.
1583       if (DKind == OMPD_ordered && Data.DepKind == OMPC_DEPEND_source) {
1584         // Parse ')'.
1585         T.consumeClose();
1586         return false;
1587       }
1588     }
1589     if (Tok.is(tok::colon))
1590       Data.ColonLoc = ConsumeToken();
1591     else {
1592       Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren
1593                                       : diag::warn_pragma_expected_colon)
1594           << "dependency type";
1595     }
1596   } else if (Kind == OMPC_linear) {
1597     // Try to parse modifier if any.
1598     if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) {
1599       Data.LinKind = static_cast<OpenMPLinearClauseKind>(
1600           getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)));
1601       Data.DepLinMapLoc = ConsumeToken();
1602       LinearT.consumeOpen();
1603       NeedRParenForLinear = true;
1604     }
1605   } else if (Kind == OMPC_map) {
1606     // Handle map type for map clause.
1607     ColonProtectionRAIIObject ColonRAII(*this);
1608 
1609     /// The map clause modifier token can be either a identifier or the C++
1610     /// delete keyword.
1611     auto &&IsMapClauseModifierToken = [](const Token &Tok) -> bool {
1612       return Tok.isOneOf(tok::identifier, tok::kw_delete);
1613     };
1614 
1615     // The first identifier may be a list item, a map-type or a
1616     // map-type-modifier. The map modifier can also be delete which has the same
1617     // spelling of the C++ delete keyword.
1618     Data.MapType =
1619         IsMapClauseModifierToken(Tok)
1620             ? static_cast<OpenMPMapClauseKind>(
1621                   getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)))
1622             : OMPC_MAP_unknown;
1623     Data.DepLinMapLoc = Tok.getLocation();
1624     bool ColonExpected = false;
1625 
1626     if (IsMapClauseModifierToken(Tok)) {
1627       if (PP.LookAhead(0).is(tok::colon)) {
1628         if (Data.MapType == OMPC_MAP_unknown)
1629           Diag(Tok, diag::err_omp_unknown_map_type);
1630         else if (Data.MapType == OMPC_MAP_always)
1631           Diag(Tok, diag::err_omp_map_type_missing);
1632         ConsumeToken();
1633       } else if (PP.LookAhead(0).is(tok::comma)) {
1634         if (IsMapClauseModifierToken(PP.LookAhead(1)) &&
1635             PP.LookAhead(2).is(tok::colon)) {
1636           Data.MapTypeModifier = Data.MapType;
1637           if (Data.MapTypeModifier != OMPC_MAP_always) {
1638             Diag(Tok, diag::err_omp_unknown_map_type_modifier);
1639             Data.MapTypeModifier = OMPC_MAP_unknown;
1640           } else
1641             MapTypeModifierSpecified = true;
1642 
1643           ConsumeToken();
1644           ConsumeToken();
1645 
1646           Data.MapType =
1647               IsMapClauseModifierToken(Tok)
1648                   ? static_cast<OpenMPMapClauseKind>(
1649                         getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)))
1650                   : OMPC_MAP_unknown;
1651           if (Data.MapType == OMPC_MAP_unknown ||
1652               Data.MapType == OMPC_MAP_always)
1653             Diag(Tok, diag::err_omp_unknown_map_type);
1654           ConsumeToken();
1655         } else {
1656           Data.MapType = OMPC_MAP_tofrom;
1657           Data.IsMapTypeImplicit = true;
1658         }
1659       } else {
1660         Data.MapType = OMPC_MAP_tofrom;
1661         Data.IsMapTypeImplicit = true;
1662       }
1663     } else {
1664       Data.MapType = OMPC_MAP_tofrom;
1665       Data.IsMapTypeImplicit = true;
1666     }
1667 
1668     if (Tok.is(tok::colon))
1669       Data.ColonLoc = ConsumeToken();
1670     else if (ColonExpected)
1671       Diag(Tok, diag::warn_pragma_expected_colon) << "map type";
1672   }
1673 
1674   bool IsComma =
1675       (Kind != OMPC_reduction && Kind != OMPC_depend && Kind != OMPC_map) ||
1676       (Kind == OMPC_reduction && !InvalidReductionId) ||
1677       (Kind == OMPC_map && Data.MapType != OMPC_MAP_unknown &&
1678        (!MapTypeModifierSpecified ||
1679         Data.MapTypeModifier == OMPC_MAP_always)) ||
1680       (Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown);
1681   const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned);
1682   while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) &&
1683                      Tok.isNot(tok::annot_pragma_openmp_end))) {
1684     ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
1685     // Parse variable
1686     ExprResult VarExpr =
1687         Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
1688     if (VarExpr.isUsable())
1689       Vars.push_back(VarExpr.get());
1690     else {
1691       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1692                 StopBeforeMatch);
1693     }
1694     // Skip ',' if any
1695     IsComma = Tok.is(tok::comma);
1696     if (IsComma)
1697       ConsumeToken();
1698     else if (Tok.isNot(tok::r_paren) &&
1699              Tok.isNot(tok::annot_pragma_openmp_end) &&
1700              (!MayHaveTail || Tok.isNot(tok::colon)))
1701       Diag(Tok, diag::err_omp_expected_punc)
1702           << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush)
1703                                    : getOpenMPClauseName(Kind))
1704           << (Kind == OMPC_flush);
1705   }
1706 
1707   // Parse ')' for linear clause with modifier.
1708   if (NeedRParenForLinear)
1709     LinearT.consumeClose();
1710 
1711   // Parse ':' linear-step (or ':' alignment).
1712   const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon);
1713   if (MustHaveTail) {
1714     Data.ColonLoc = Tok.getLocation();
1715     SourceLocation ELoc = ConsumeToken();
1716     ExprResult Tail = ParseAssignmentExpression();
1717     Tail = Actions.ActOnFinishFullExpr(Tail.get(), ELoc);
1718     if (Tail.isUsable())
1719       Data.TailExpr = Tail.get();
1720     else
1721       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1722                 StopBeforeMatch);
1723   }
1724 
1725   // Parse ')'.
1726   T.consumeClose();
1727   if ((Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown &&
1728        Vars.empty()) ||
1729       (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) ||
1730       (MustHaveTail && !Data.TailExpr) || InvalidReductionId)
1731     return true;
1732   return false;
1733 }
1734 
1735 /// \brief Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate',
1736 /// 'shared', 'copyin', 'copyprivate', 'flush' or 'reduction'.
1737 ///
1738 ///    private-clause:
1739 ///       'private' '(' list ')'
1740 ///    firstprivate-clause:
1741 ///       'firstprivate' '(' list ')'
1742 ///    lastprivate-clause:
1743 ///       'lastprivate' '(' list ')'
1744 ///    shared-clause:
1745 ///       'shared' '(' list ')'
1746 ///    linear-clause:
1747 ///       'linear' '(' linear-list [ ':' linear-step ] ')'
1748 ///    aligned-clause:
1749 ///       'aligned' '(' list [ ':' alignment ] ')'
1750 ///    reduction-clause:
1751 ///       'reduction' '(' reduction-identifier ':' list ')'
1752 ///    copyprivate-clause:
1753 ///       'copyprivate' '(' list ')'
1754 ///    flush-clause:
1755 ///       'flush' '(' list ')'
1756 ///    depend-clause:
1757 ///       'depend' '(' in | out | inout : list | source ')'
1758 ///    map-clause:
1759 ///       'map' '(' [ [ always , ]
1760 ///          to | from | tofrom | alloc | release | delete ':' ] list ')';
1761 ///    to-clause:
1762 ///       'to' '(' list ')'
1763 ///    from-clause:
1764 ///       'from' '(' list ')'
1765 ///    use_device_ptr-clause:
1766 ///       'use_device_ptr' '(' list ')'
1767 ///    is_device_ptr-clause:
1768 ///       'is_device_ptr' '(' list ')'
1769 ///
1770 /// For 'linear' clause linear-list may have the following forms:
1771 ///  list
1772 ///  modifier(list)
1773 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
1774 OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
1775                                             OpenMPClauseKind Kind) {
1776   SourceLocation Loc = Tok.getLocation();
1777   SourceLocation LOpen = ConsumeToken();
1778   SmallVector<Expr *, 4> Vars;
1779   OpenMPVarListDataTy Data;
1780 
1781   if (ParseOpenMPVarList(DKind, Kind, Vars, Data))
1782     return nullptr;
1783 
1784   return Actions.ActOnOpenMPVarListClause(
1785       Kind, Vars, Data.TailExpr, Loc, LOpen, Data.ColonLoc, Tok.getLocation(),
1786       Data.ReductionIdScopeSpec, Data.ReductionId, Data.DepKind, Data.LinKind,
1787       Data.MapTypeModifier, Data.MapType, Data.IsMapTypeImplicit,
1788       Data.DepLinMapLoc);
1789 }
1790 
1791