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