]> granicus.if.org Git - clang/blob - lib/Parse/ParseOpenMP.cpp
[OPENMP 4.1] Initial support for modifiers in 'linear' clause.
[clang] / lib / Parse / ParseOpenMP.cpp
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/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/StmtOpenMP.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Parse/Parser.h"
20 #include "clang/Sema/Scope.h"
21 #include "llvm/ADT/PointerIntPair.h"
22
23 using namespace clang;
24
25 //===----------------------------------------------------------------------===//
26 // OpenMP declarative directives.
27 //===----------------------------------------------------------------------===//
28
29 static OpenMPDirectiveKind ParseOpenMPDirectiveKind(Parser &P) {
30   // Array of foldings: F[i][0] F[i][1] ===> F[i][2].
31   // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd
32   // TODO: add other combined directives in topological order.
33   const OpenMPDirectiveKind F[][3] = {
34       {OMPD_unknown /*cancellation*/, OMPD_unknown /*point*/,
35        OMPD_cancellation_point},
36       {OMPD_target, OMPD_unknown /*data*/, OMPD_target_data},
37       {OMPD_for, OMPD_simd, OMPD_for_simd},
38       {OMPD_parallel, OMPD_for, OMPD_parallel_for},
39       {OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd},
40       {OMPD_parallel, OMPD_sections, OMPD_parallel_sections}};
41   auto Tok = P.getCurToken();
42   auto DKind =
43       Tok.isAnnotation()
44           ? OMPD_unknown
45           : getOpenMPDirectiveKind(P.getPreprocessor().getSpelling(Tok));
46
47   bool TokenMatched = false;
48   for (unsigned i = 0; i < llvm::array_lengthof(F); ++i) {
49     if (!Tok.isAnnotation() && DKind == OMPD_unknown) {
50       TokenMatched =
51           (i == 0) &&
52           !P.getPreprocessor().getSpelling(Tok).compare("cancellation");
53     } else {
54       TokenMatched = DKind == F[i][0] && DKind != OMPD_unknown;
55     }
56
57     if (TokenMatched) {
58       Tok = P.getPreprocessor().LookAhead(0);
59       auto TokenIsAnnotation = Tok.isAnnotation();
60       auto SDKind =
61           TokenIsAnnotation
62               ? OMPD_unknown
63               : getOpenMPDirectiveKind(P.getPreprocessor().getSpelling(Tok));
64
65       if (!TokenIsAnnotation && SDKind == OMPD_unknown) {
66         TokenMatched =
67             ((i == 0) &&
68              !P.getPreprocessor().getSpelling(Tok).compare("point")) ||
69             ((i == 1) && !P.getPreprocessor().getSpelling(Tok).compare("data"));
70       } else {
71         TokenMatched = SDKind == F[i][1] && SDKind != OMPD_unknown;
72       }
73
74       if (TokenMatched) {
75         P.ConsumeToken();
76         DKind = F[i][2];
77       }
78     }
79   }
80   return DKind;
81 }
82
83 /// \brief Parsing of declarative OpenMP directives.
84 ///
85 ///       threadprivate-directive:
86 ///         annot_pragma_openmp 'threadprivate' simple-variable-list
87 ///
88 Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirective() {
89   assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
90   ParenBraceBracketBalancer BalancerRAIIObj(*this);
91
92   SourceLocation Loc = ConsumeToken();
93   SmallVector<Expr *, 5> Identifiers;
94   auto DKind = ParseOpenMPDirectiveKind(*this);
95
96   switch (DKind) {
97   case OMPD_threadprivate:
98     ConsumeToken();
99     if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Identifiers, true)) {
100       // The last seen token is annot_pragma_openmp_end - need to check for
101       // extra tokens.
102       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
103         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
104             << getOpenMPDirectiveName(OMPD_threadprivate);
105         SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
106       }
107       // Skip the last annot_pragma_openmp_end.
108       ConsumeToken();
109       return Actions.ActOnOpenMPThreadprivateDirective(Loc, Identifiers);
110     }
111     break;
112   case OMPD_unknown:
113     Diag(Tok, diag::err_omp_unknown_directive);
114     break;
115   case OMPD_parallel:
116   case OMPD_simd:
117   case OMPD_task:
118   case OMPD_taskyield:
119   case OMPD_barrier:
120   case OMPD_taskwait:
121   case OMPD_taskgroup:
122   case OMPD_flush:
123   case OMPD_for:
124   case OMPD_for_simd:
125   case OMPD_sections:
126   case OMPD_section:
127   case OMPD_single:
128   case OMPD_master:
129   case OMPD_ordered:
130   case OMPD_critical:
131   case OMPD_parallel_for:
132   case OMPD_parallel_for_simd:
133   case OMPD_parallel_sections:
134   case OMPD_atomic:
135   case OMPD_target:
136   case OMPD_teams:
137   case OMPD_cancellation_point:
138   case OMPD_cancel:
139   case OMPD_target_data:
140     Diag(Tok, diag::err_omp_unexpected_directive)
141         << getOpenMPDirectiveName(DKind);
142     break;
143   }
144   SkipUntil(tok::annot_pragma_openmp_end);
145   return DeclGroupPtrTy();
146 }
147
148 /// \brief Parsing of declarative or executable OpenMP directives.
149 ///
150 ///       threadprivate-directive:
151 ///         annot_pragma_openmp 'threadprivate' simple-variable-list
152 ///         annot_pragma_openmp_end
153 ///
154 ///       executable-directive:
155 ///         annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
156 ///         'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
157 ///         'parallel for' | 'parallel sections' | 'task' | 'taskyield' |
158 ///         'barrier' | 'taskwait' | 'flush' | 'ordered' | 'atomic' |
159 ///         'for simd' | 'parallel for simd' | 'target' | 'target data' |
160 ///         'taskgroup' | 'teams' {clause}
161 ///         annot_pragma_openmp_end
162 ///
163 StmtResult
164 Parser::ParseOpenMPDeclarativeOrExecutableDirective(bool StandAloneAllowed) {
165   assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
166   ParenBraceBracketBalancer BalancerRAIIObj(*this);
167   SmallVector<Expr *, 5> Identifiers;
168   SmallVector<OMPClause *, 5> Clauses;
169   SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, OMPC_unknown + 1>
170   FirstClauses(OMPC_unknown + 1);
171   unsigned ScopeFlags =
172       Scope::FnScope | Scope::DeclScope | Scope::OpenMPDirectiveScope;
173   SourceLocation Loc = ConsumeToken(), EndLoc;
174   auto DKind = ParseOpenMPDirectiveKind(*this);
175   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
176   // Name of critical directive.
177   DeclarationNameInfo DirName;
178   StmtResult Directive = StmtError();
179   bool HasAssociatedStatement = true;
180   bool FlushHasClause = false;
181
182   switch (DKind) {
183   case OMPD_threadprivate:
184     ConsumeToken();
185     if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Identifiers, false)) {
186       // The last seen token is annot_pragma_openmp_end - need to check for
187       // extra tokens.
188       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
189         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
190             << getOpenMPDirectiveName(OMPD_threadprivate);
191         SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
192       }
193       DeclGroupPtrTy Res =
194           Actions.ActOnOpenMPThreadprivateDirective(Loc, Identifiers);
195       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
196     }
197     SkipUntil(tok::annot_pragma_openmp_end);
198     break;
199   case OMPD_flush:
200     if (PP.LookAhead(0).is(tok::l_paren)) {
201       FlushHasClause = true;
202       // Push copy of the current token back to stream to properly parse
203       // pseudo-clause OMPFlushClause.
204       PP.EnterToken(Tok);
205     }
206   case OMPD_taskyield:
207   case OMPD_barrier:
208   case OMPD_taskwait:
209   case OMPD_cancellation_point:
210   case OMPD_cancel:
211     if (!StandAloneAllowed) {
212       Diag(Tok, diag::err_omp_immediate_directive)
213           << getOpenMPDirectiveName(DKind);
214     }
215     HasAssociatedStatement = false;
216     // Fall through for further analysis.
217   case OMPD_parallel:
218   case OMPD_simd:
219   case OMPD_for:
220   case OMPD_for_simd:
221   case OMPD_sections:
222   case OMPD_single:
223   case OMPD_section:
224   case OMPD_master:
225   case OMPD_critical:
226   case OMPD_parallel_for:
227   case OMPD_parallel_for_simd:
228   case OMPD_parallel_sections:
229   case OMPD_task:
230   case OMPD_ordered:
231   case OMPD_atomic:
232   case OMPD_target:
233   case OMPD_teams:
234   case OMPD_taskgroup:
235   case OMPD_target_data: {
236     ConsumeToken();
237     // Parse directive name of the 'critical' directive if any.
238     if (DKind == OMPD_critical) {
239       BalancedDelimiterTracker T(*this, tok::l_paren,
240                                  tok::annot_pragma_openmp_end);
241       if (!T.consumeOpen()) {
242         if (Tok.isAnyIdentifier()) {
243           DirName =
244               DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation());
245           ConsumeAnyToken();
246         } else {
247           Diag(Tok, diag::err_omp_expected_identifier_for_critical);
248         }
249         T.consumeClose();
250       }
251     } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) {
252       CancelRegion = ParseOpenMPDirectiveKind(*this);
253       if (Tok.isNot(tok::annot_pragma_openmp_end))
254         ConsumeToken();
255     }
256
257     if (isOpenMPLoopDirective(DKind))
258       ScopeFlags |= Scope::OpenMPLoopDirectiveScope;
259     if (isOpenMPSimdDirective(DKind))
260       ScopeFlags |= Scope::OpenMPSimdDirectiveScope;
261     ParseScope OMPDirectiveScope(this, ScopeFlags);
262     Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc);
263
264     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
265       OpenMPClauseKind CKind =
266           Tok.isAnnotation()
267               ? OMPC_unknown
268               : FlushHasClause ? OMPC_flush
269                                : getOpenMPClauseKind(PP.getSpelling(Tok));
270       Actions.StartOpenMPClause(CKind);
271       FlushHasClause = false;
272       OMPClause *Clause =
273           ParseOpenMPClause(DKind, CKind, !FirstClauses[CKind].getInt());
274       FirstClauses[CKind].setInt(true);
275       if (Clause) {
276         FirstClauses[CKind].setPointer(Clause);
277         Clauses.push_back(Clause);
278       }
279
280       // Skip ',' if any.
281       if (Tok.is(tok::comma))
282         ConsumeToken();
283       Actions.EndOpenMPClause();
284     }
285     // End location of the directive.
286     EndLoc = Tok.getLocation();
287     // Consume final annot_pragma_openmp_end.
288     ConsumeToken();
289
290     StmtResult AssociatedStmt;
291     bool CreateDirective = true;
292     if (HasAssociatedStatement) {
293       // The body is a block scope like in Lambdas and Blocks.
294       Sema::CompoundScopeRAII CompoundScope(Actions);
295       Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
296       Actions.ActOnStartOfCompoundStmt();
297       // Parse statement
298       AssociatedStmt = ParseStatement();
299       Actions.ActOnFinishOfCompoundStmt();
300       AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
301       CreateDirective = AssociatedStmt.isUsable();
302     }
303     if (CreateDirective)
304       Directive = Actions.ActOnOpenMPExecutableDirective(
305           DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc,
306           EndLoc);
307
308     // Exit scope.
309     Actions.EndOpenMPDSABlock(Directive.get());
310     OMPDirectiveScope.Exit();
311     break;
312   }
313   case OMPD_unknown:
314     Diag(Tok, diag::err_omp_unknown_directive);
315     SkipUntil(tok::annot_pragma_openmp_end);
316     break;
317   }
318   return Directive;
319 }
320
321 /// \brief Parses list of simple variables for '#pragma omp threadprivate'
322 /// directive.
323 ///
324 ///   simple-variable-list:
325 ///         '(' id-expression {, id-expression} ')'
326 ///
327 bool Parser::ParseOpenMPSimpleVarList(OpenMPDirectiveKind Kind,
328                                       SmallVectorImpl<Expr *> &VarList,
329                                       bool AllowScopeSpecifier) {
330   VarList.clear();
331   // Parse '('.
332   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
333   if (T.expectAndConsume(diag::err_expected_lparen_after,
334                          getOpenMPDirectiveName(Kind)))
335     return true;
336   bool IsCorrect = true;
337   bool NoIdentIsFound = true;
338
339   // Read tokens while ')' or annot_pragma_openmp_end is not found.
340   while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
341     CXXScopeSpec SS;
342     SourceLocation TemplateKWLoc;
343     UnqualifiedId Name;
344     // Read var name.
345     Token PrevTok = Tok;
346     NoIdentIsFound = false;
347
348     if (AllowScopeSpecifier && getLangOpts().CPlusPlus &&
349         ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false)) {
350       IsCorrect = false;
351       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
352                 StopBeforeMatch);
353     } else if (ParseUnqualifiedId(SS, false, false, false, ParsedType(),
354                                   TemplateKWLoc, Name)) {
355       IsCorrect = false;
356       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
357                 StopBeforeMatch);
358     } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) &&
359                Tok.isNot(tok::annot_pragma_openmp_end)) {
360       IsCorrect = false;
361       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
362                 StopBeforeMatch);
363       Diag(PrevTok.getLocation(), diag::err_expected)
364           << tok::identifier
365           << SourceRange(PrevTok.getLocation(), PrevTokLocation);
366     } else {
367       DeclarationNameInfo NameInfo = Actions.GetNameFromUnqualifiedId(Name);
368       ExprResult Res =
369           Actions.ActOnOpenMPIdExpression(getCurScope(), SS, NameInfo);
370       if (Res.isUsable())
371         VarList.push_back(Res.get());
372     }
373     // Consume ','.
374     if (Tok.is(tok::comma)) {
375       ConsumeToken();
376     }
377   }
378
379   if (NoIdentIsFound) {
380     Diag(Tok, diag::err_expected) << tok::identifier;
381     IsCorrect = false;
382   }
383
384   // Parse ')'.
385   IsCorrect = !T.consumeClose() && IsCorrect;
386
387   return !IsCorrect && VarList.empty();
388 }
389
390 /// \brief Parsing of OpenMP clauses.
391 ///
392 ///    clause:
393 ///       if-clause | final-clause | num_threads-clause | safelen-clause |
394 ///       default-clause | private-clause | firstprivate-clause | shared-clause
395 ///       | linear-clause | aligned-clause | collapse-clause |
396 ///       lastprivate-clause | reduction-clause | proc_bind-clause |
397 ///       schedule-clause | copyin-clause | copyprivate-clause | untied-clause |
398 ///       mergeable-clause | flush-clause | read-clause | write-clause |
399 ///       update-clause | capture-clause | seq_cst-clause | device-clause
400 ///
401 OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind,
402                                      OpenMPClauseKind CKind, bool FirstClause) {
403   OMPClause *Clause = nullptr;
404   bool ErrorFound = false;
405   // Check if clause is allowed for the given directive.
406   if (CKind != OMPC_unknown && !isAllowedClauseForDirective(DKind, CKind)) {
407     Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind)
408                                                << getOpenMPDirectiveName(DKind);
409     ErrorFound = true;
410   }
411
412   switch (CKind) {
413   case OMPC_if:
414   case OMPC_final:
415   case OMPC_num_threads:
416   case OMPC_safelen:
417   case OMPC_collapse:
418   case OMPC_ordered:
419   case OMPC_device:
420     // OpenMP [2.5, Restrictions]
421     //  At most one if clause can appear on the directive.
422     //  At most one num_threads clause can appear on the directive.
423     // OpenMP [2.8.1, simd construct, Restrictions]
424     //  Only one safelen  clause can appear on a simd directive.
425     //  Only one collapse clause can appear on a simd directive.
426     // OpenMP [2.9.1, target data construct, Restrictions]
427     //  At most one device clause can appear on the directive.
428     // OpenMP [2.11.1, task Construct, Restrictions]
429     //  At most one if clause can appear on the directive.
430     //  At most one final clause can appear on the directive.
431     if (!FirstClause) {
432       Diag(Tok, diag::err_omp_more_one_clause) << getOpenMPDirectiveName(DKind)
433                                                << getOpenMPClauseName(CKind);
434       ErrorFound = true;
435     }
436
437     if (CKind == OMPC_ordered && PP.LookAhead(/*N=*/0).isNot(tok::l_paren))
438       Clause = ParseOpenMPClause(CKind);
439     else
440       Clause = ParseOpenMPSingleExprClause(CKind);
441     break;
442   case OMPC_default:
443   case OMPC_proc_bind:
444     // OpenMP [2.14.3.1, Restrictions]
445     //  Only a single default clause may be specified on a parallel, task or
446     //  teams directive.
447     // OpenMP [2.5, parallel Construct, Restrictions]
448     //  At most one proc_bind clause can appear on the directive.
449     if (!FirstClause) {
450       Diag(Tok, diag::err_omp_more_one_clause) << getOpenMPDirectiveName(DKind)
451                                                << getOpenMPClauseName(CKind);
452       ErrorFound = true;
453     }
454
455     Clause = ParseOpenMPSimpleClause(CKind);
456     break;
457   case OMPC_schedule:
458     // OpenMP [2.7.1, Restrictions, p. 3]
459     //  Only one schedule clause can appear on a loop directive.
460     if (!FirstClause) {
461       Diag(Tok, diag::err_omp_more_one_clause) << getOpenMPDirectiveName(DKind)
462                                                << getOpenMPClauseName(CKind);
463       ErrorFound = true;
464     }
465
466     Clause = ParseOpenMPSingleExprWithArgClause(CKind);
467     break;
468   case OMPC_nowait:
469   case OMPC_untied:
470   case OMPC_mergeable:
471   case OMPC_read:
472   case OMPC_write:
473   case OMPC_update:
474   case OMPC_capture:
475   case OMPC_seq_cst:
476     // OpenMP [2.7.1, Restrictions, p. 9]
477     //  Only one ordered clause can appear on a loop directive.
478     // OpenMP [2.7.1, Restrictions, C/C++, p. 4]
479     //  Only one nowait clause can appear on a for directive.
480     if (!FirstClause) {
481       Diag(Tok, diag::err_omp_more_one_clause) << getOpenMPDirectiveName(DKind)
482                                                << getOpenMPClauseName(CKind);
483       ErrorFound = true;
484     }
485
486     Clause = ParseOpenMPClause(CKind);
487     break;
488   case OMPC_private:
489   case OMPC_firstprivate:
490   case OMPC_lastprivate:
491   case OMPC_shared:
492   case OMPC_reduction:
493   case OMPC_linear:
494   case OMPC_aligned:
495   case OMPC_copyin:
496   case OMPC_copyprivate:
497   case OMPC_flush:
498   case OMPC_depend:
499     Clause = ParseOpenMPVarListClause(CKind);
500     break;
501   case OMPC_unknown:
502     Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
503         << getOpenMPDirectiveName(DKind);
504     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
505     break;
506   case OMPC_threadprivate:
507     Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind)
508                                                << getOpenMPDirectiveName(DKind);
509     SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch);
510     break;
511   }
512   return ErrorFound ? nullptr : Clause;
513 }
514
515 /// \brief Parsing of OpenMP clauses with single expressions like 'if',
516 /// 'final', 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams' or
517 /// 'thread_limit'.
518 ///
519 ///    if-clause:
520 ///      'if' '(' expression ')'
521 ///
522 ///    final-clause:
523 ///      'final' '(' expression ')'
524 ///
525 ///    num_threads-clause:
526 ///      'num_threads' '(' expression ')'
527 ///
528 ///    safelen-clause:
529 ///      'safelen' '(' expression ')'
530 ///
531 ///    collapse-clause:
532 ///      'collapse' '(' expression ')'
533 ///
534 OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind) {
535   SourceLocation Loc = ConsumeToken();
536
537   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
538   if (T.expectAndConsume(diag::err_expected_lparen_after,
539                          getOpenMPClauseName(Kind)))
540     return nullptr;
541
542   ExprResult LHS(ParseCastExpression(false, false, NotTypeCast));
543   ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
544
545   // Parse ')'.
546   T.consumeClose();
547
548   if (Val.isInvalid())
549     return nullptr;
550
551   return Actions.ActOnOpenMPSingleExprClause(
552       Kind, Val.get(), Loc, T.getOpenLocation(), T.getCloseLocation());
553 }
554
555 /// \brief Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
556 ///
557 ///    default-clause:
558 ///         'default' '(' 'none' | 'shared' ')
559 ///
560 ///    proc_bind-clause:
561 ///         'proc_bind' '(' 'master' | 'close' | 'spread' ')
562 ///
563 OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind) {
564   SourceLocation Loc = Tok.getLocation();
565   SourceLocation LOpen = ConsumeToken();
566   // Parse '('.
567   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
568   if (T.expectAndConsume(diag::err_expected_lparen_after,
569                          getOpenMPClauseName(Kind)))
570     return nullptr;
571
572   unsigned Type = getOpenMPSimpleClauseType(
573       Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
574   SourceLocation TypeLoc = Tok.getLocation();
575   if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
576       Tok.isNot(tok::annot_pragma_openmp_end))
577     ConsumeAnyToken();
578
579   // Parse ')'.
580   T.consumeClose();
581
582   return Actions.ActOnOpenMPSimpleClause(Kind, Type, TypeLoc, LOpen, Loc,
583                                          Tok.getLocation());
584 }
585
586 /// \brief Parsing of OpenMP clauses like 'ordered'.
587 ///
588 ///    ordered-clause:
589 ///         'ordered'
590 ///
591 ///    nowait-clause:
592 ///         'nowait'
593 ///
594 ///    untied-clause:
595 ///         'untied'
596 ///
597 ///    mergeable-clause:
598 ///         'mergeable'
599 ///
600 ///    read-clause:
601 ///         'read'
602 ///
603 OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind) {
604   SourceLocation Loc = Tok.getLocation();
605   ConsumeAnyToken();
606
607   return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation());
608 }
609
610
611 /// \brief Parsing of OpenMP clauses with single expressions and some additional
612 /// argument like 'schedule' or 'dist_schedule'.
613 ///
614 ///    schedule-clause:
615 ///      'schedule' '(' kind [',' expression ] ')'
616 ///
617 OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind) {
618   SourceLocation Loc = ConsumeToken();
619   SourceLocation CommaLoc;
620   // Parse '('.
621   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
622   if (T.expectAndConsume(diag::err_expected_lparen_after,
623                          getOpenMPClauseName(Kind)))
624     return nullptr;
625
626   ExprResult Val;
627   unsigned Type = getOpenMPSimpleClauseType(
628       Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
629   SourceLocation KLoc = Tok.getLocation();
630   if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
631       Tok.isNot(tok::annot_pragma_openmp_end))
632     ConsumeAnyToken();
633
634   if (Kind == OMPC_schedule &&
635       (Type == OMPC_SCHEDULE_static || Type == OMPC_SCHEDULE_dynamic ||
636        Type == OMPC_SCHEDULE_guided) &&
637       Tok.is(tok::comma)) {
638     CommaLoc = ConsumeAnyToken();
639     ExprResult LHS(ParseCastExpression(false, false, NotTypeCast));
640     Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
641     if (Val.isInvalid())
642       return nullptr;
643   }
644
645   // Parse ')'.
646   T.consumeClose();
647
648   return Actions.ActOnOpenMPSingleExprWithArgClause(
649       Kind, Type, Val.get(), Loc, T.getOpenLocation(), KLoc, CommaLoc,
650       T.getCloseLocation());
651 }
652
653 static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec,
654                              UnqualifiedId &ReductionId) {
655   SourceLocation TemplateKWLoc;
656   if (ReductionIdScopeSpec.isEmpty()) {
657     auto OOK = OO_None;
658     switch (P.getCurToken().getKind()) {
659     case tok::plus:
660       OOK = OO_Plus;
661       break;
662     case tok::minus:
663       OOK = OO_Minus;
664       break;
665     case tok::star:
666       OOK = OO_Star;
667       break;
668     case tok::amp:
669       OOK = OO_Amp;
670       break;
671     case tok::pipe:
672       OOK = OO_Pipe;
673       break;
674     case tok::caret:
675       OOK = OO_Caret;
676       break;
677     case tok::ampamp:
678       OOK = OO_AmpAmp;
679       break;
680     case tok::pipepipe:
681       OOK = OO_PipePipe;
682       break;
683     default:
684       break;
685     }
686     if (OOK != OO_None) {
687       SourceLocation OpLoc = P.ConsumeToken();
688       SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()};
689       ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations);
690       return false;
691     }
692   }
693   return P.ParseUnqualifiedId(ReductionIdScopeSpec, /*EnteringContext*/ false,
694                               /*AllowDestructorName*/ false,
695                               /*AllowConstructorName*/ false, ParsedType(),
696                               TemplateKWLoc, ReductionId);
697 }
698
699 /// \brief Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate',
700 /// 'shared', 'copyin', 'copyprivate', 'flush' or 'reduction'.
701 ///
702 ///    private-clause:
703 ///       'private' '(' list ')'
704 ///    firstprivate-clause:
705 ///       'firstprivate' '(' list ')'
706 ///    lastprivate-clause:
707 ///       'lastprivate' '(' list ')'
708 ///    shared-clause:
709 ///       'shared' '(' list ')'
710 ///    linear-clause:
711 ///       'linear' '(' linear-list [ ':' linear-step ] ')'
712 ///    aligned-clause:
713 ///       'aligned' '(' list [ ':' alignment ] ')'
714 ///    reduction-clause:
715 ///       'reduction' '(' reduction-identifier ':' list ')'
716 ///    copyprivate-clause:
717 ///       'copyprivate' '(' list ')'
718 ///    flush-clause:
719 ///       'flush' '(' list ')'
720 ///    depend-clause:
721 ///       'depend' '(' in | out | inout : list ')'
722 ///
723 /// For 'linear' clause linear-list may have the following forms:
724 ///  list
725 ///  modifier(list)
726 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
727 OMPClause *Parser::ParseOpenMPVarListClause(OpenMPClauseKind Kind) {
728   SourceLocation Loc = Tok.getLocation();
729   SourceLocation LOpen = ConsumeToken();
730   SourceLocation ColonLoc = SourceLocation();
731   // Optional scope specifier and unqualified id for reduction identifier.
732   CXXScopeSpec ReductionIdScopeSpec;
733   UnqualifiedId ReductionId;
734   bool InvalidReductionId = false;
735   OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
736   // OpenMP 4.1 [2.15.3.7, linear Clause]
737   //  If no modifier is specified it is assumed to be val.
738   OpenMPLinearClauseKind LinearModifier = OMPC_LINEAR_val;
739   SourceLocation DepLinLoc;
740
741   // Parse '('.
742   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
743   if (T.expectAndConsume(diag::err_expected_lparen_after,
744                          getOpenMPClauseName(Kind)))
745     return nullptr;
746
747   bool NeedRParenForLinear = false;
748   BalancedDelimiterTracker LinearT(*this, tok::l_paren,
749                                   tok::annot_pragma_openmp_end);
750   // Handle reduction-identifier for reduction clause.
751   if (Kind == OMPC_reduction) {
752     ColonProtectionRAIIObject ColonRAII(*this);
753     if (getLangOpts().CPlusPlus) {
754       ParseOptionalCXXScopeSpecifier(ReductionIdScopeSpec, ParsedType(), false);
755     }
756     InvalidReductionId =
757         ParseReductionId(*this, ReductionIdScopeSpec, ReductionId);
758     if (InvalidReductionId) {
759       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
760                 StopBeforeMatch);
761     }
762     if (Tok.is(tok::colon)) {
763       ColonLoc = ConsumeToken();
764     } else {
765       Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier";
766     }
767   } else if (Kind == OMPC_depend) {
768   // Handle dependency type for depend clause.
769     ColonProtectionRAIIObject ColonRAII(*this);
770     DepKind = static_cast<OpenMPDependClauseKind>(getOpenMPSimpleClauseType(
771         Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : ""));
772     DepLinLoc = Tok.getLocation();
773
774     if (DepKind == OMPC_DEPEND_unknown) {
775       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
776                 StopBeforeMatch);
777     } else {
778       ConsumeToken();
779     }
780     if (Tok.is(tok::colon)) {
781       ColonLoc = ConsumeToken();
782     } else {
783       Diag(Tok, diag::warn_pragma_expected_colon) << "dependency type";
784     }
785   } else if (Kind == OMPC_linear) {
786     // Try to parse modifier if any.
787     if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) {
788       StringRef TokSpelling = PP.getSpelling(Tok);
789       LinearModifier = static_cast<OpenMPLinearClauseKind>(
790           getOpenMPSimpleClauseType(Kind, TokSpelling));
791       DepLinLoc = ConsumeToken();
792       LinearT.consumeOpen();
793       NeedRParenForLinear = true;
794     }
795   }
796
797   SmallVector<Expr *, 5> Vars;
798   bool IsComma = ((Kind != OMPC_reduction) && (Kind != OMPC_depend)) ||
799                  ((Kind == OMPC_reduction) && !InvalidReductionId) ||
800                  ((Kind == OMPC_depend) && DepKind != OMPC_DEPEND_unknown);
801   const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned);
802   while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) &&
803                      Tok.isNot(tok::annot_pragma_openmp_end))) {
804     ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
805     // Parse variable
806     ExprResult VarExpr =
807         Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
808     if (VarExpr.isUsable()) {
809       Vars.push_back(VarExpr.get());
810     } else {
811       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
812                 StopBeforeMatch);
813     }
814     // Skip ',' if any
815     IsComma = Tok.is(tok::comma);
816     if (IsComma)
817       ConsumeToken();
818     else if (Tok.isNot(tok::r_paren) &&
819              Tok.isNot(tok::annot_pragma_openmp_end) &&
820              (!MayHaveTail || Tok.isNot(tok::colon)))
821       Diag(Tok, diag::err_omp_expected_punc)
822           << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush)
823                                    : getOpenMPClauseName(Kind))
824           << (Kind == OMPC_flush);
825   }
826
827   // Parse ')' for linear clause with modifier.
828   if (NeedRParenForLinear)
829     LinearT.consumeClose();
830
831   // Parse ':' linear-step (or ':' alignment).
832   Expr *TailExpr = nullptr;
833   const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon);
834   if (MustHaveTail) {
835     ColonLoc = Tok.getLocation();
836     ConsumeToken();
837     ExprResult Tail =
838         Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
839     if (Tail.isUsable())
840       TailExpr = Tail.get();
841     else
842       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
843                 StopBeforeMatch);
844   }
845
846   // Parse ')'.
847   T.consumeClose();
848   if ((Kind == OMPC_depend && DepKind != OMPC_DEPEND_unknown && Vars.empty()) ||
849       (Kind != OMPC_depend && Vars.empty()) || (MustHaveTail && !TailExpr) ||
850       InvalidReductionId)
851     return nullptr;
852
853   return Actions.ActOnOpenMPVarListClause(
854       Kind, Vars, TailExpr, Loc, LOpen, ColonLoc, Tok.getLocation(),
855       ReductionIdScopeSpec,
856       ReductionId.isValid() ? Actions.GetNameFromUnqualifiedId(ReductionId)
857                             : DeclarationNameInfo(),
858       DepKind, LinearModifier, DepLinLoc);
859 }
860