clang 24.0.0git
ParseOpenMP.cpp
Go to the documentation of this file.
1//===--- ParseOpenMP.cpp - OpenMP directives parsing ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements parsing of all OpenMP directives and clauses.
10///
11//===----------------------------------------------------------------------===//
12
19#include "clang/Parse/Parser.h"
22#include "clang/Sema/Scope.h"
26#include "llvm/ADT/SmallBitVector.h"
27#include "llvm/ADT/StringSwitch.h"
28#include "llvm/Frontend/OpenMP/DirectiveNameParser.h"
29#include "llvm/Frontend/OpenMP/OMPAssume.h"
30#include "llvm/Frontend/OpenMP/OMPContext.h"
31#include <optional>
32
33using namespace clang;
34using namespace llvm::omp;
35
36//===----------------------------------------------------------------------===//
37// OpenMP declarative directives.
38//===----------------------------------------------------------------------===//
39
40namespace {
41class DeclDirectiveListParserHelper final {
42 SmallVector<Expr *, 4> Identifiers;
43 Parser *P;
45
46public:
47 DeclDirectiveListParserHelper(Parser *P, OpenMPDirectiveKind Kind)
48 : P(P), Kind(Kind) {}
49 void operator()(CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
50 ExprResult Res = P->getActions().OpenMP().ActOnOpenMPIdExpression(
51 P->getCurScope(), SS, NameInfo, Kind);
52 if (Res.isUsable())
53 Identifiers.push_back(Res.get());
54 }
55 llvm::ArrayRef<Expr *> getIdentifiers() const { return Identifiers; }
56};
57} // namespace
58
62 StringRef Name) {
63 llvm::omp::Version Version = P.getLangOpts().getOpenMPVersion();
64 auto [D, VR] = getOpenMPDirectiveKindAndVersions(Name);
65 // "ORDERED" is parsed as OMPD_ordered_standalone.
66 if (D == Directive::OMPD_ordered_blockassoc)
67 D = Directive::OMPD_ordered_standalone;
68 assert(D == Kind && "Directive kind mismatch");
69 // Ignore the case Version > VR.Max: In OpenMP 6.0 all prior spellings
70 // are explicitly allowed.
71 if (Version < VR.Min)
72 P.Diag(Loc, diag::warn_omp_future_directive_spelling) << Name;
73
74 return Kind;
75}
76
78 static const DirectiveNameParser DirParser;
79
80 const DirectiveNameParser::State *S = DirParser.initial();
81
82 Token Tok = P.getCurToken();
83 if (Tok.isAnnotation())
84 return OMPD_unknown;
85
86 std::string Concat = P.getPreprocessor().getSpelling(Tok);
87 SourceLocation Loc = Tok.getLocation();
88
89 S = DirParser.consume(S, Concat);
90 if (S == nullptr)
91 return OMPD_unknown;
92
93 while (!Tok.isAnnotation()) {
94 OpenMPDirectiveKind DKind = S->Value;
96 if (!Tok.isAnnotation()) {
97 std::string TS = P.getPreprocessor().getSpelling(Tok);
98 S = DirParser.consume(S, TS);
99 if (S == nullptr)
100 return checkOpenMPDirectiveName(P, Loc, DKind, Concat);
101 Concat += ' ' + TS;
102 P.ConsumeToken();
103 }
104 }
105
106 assert(S && "Should have exited early");
107 return checkOpenMPDirectiveName(P, Loc, S->Value, Concat);
108}
109
111 Token Tok = P.getCurToken();
112 Sema &Actions = P.getActions();
114 // Allow to use 'operator' keyword for C++ operators
115 bool WithOperator = false;
116 if (Tok.is(tok::kw_operator)) {
117 P.ConsumeToken();
118 Tok = P.getCurToken();
119 WithOperator = true;
120 }
121 switch (Tok.getKind()) {
122 case tok::plus: // '+'
123 OOK = OO_Plus;
124 break;
125 case tok::minus: // '-'
126 OOK = OO_Minus;
127 break;
128 case tok::star: // '*'
129 OOK = OO_Star;
130 break;
131 case tok::amp: // '&'
132 OOK = OO_Amp;
133 break;
134 case tok::pipe: // '|'
135 OOK = OO_Pipe;
136 break;
137 case tok::caret: // '^'
138 OOK = OO_Caret;
139 break;
140 case tok::ampamp: // '&&'
141 OOK = OO_AmpAmp;
142 break;
143 case tok::pipepipe: // '||'
144 OOK = OO_PipePipe;
145 break;
146 case tok::identifier: // identifier
147 if (!WithOperator)
148 break;
149 [[fallthrough]];
150 default:
151 P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier);
152 P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
154 return DeclarationName();
155 }
156 P.ConsumeToken();
157 auto &DeclNames = Actions.getASTContext().DeclarationNames;
158 return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo())
159 : DeclNames.getCXXOperatorName(OOK);
160}
161
163Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) {
164 llvm::omp::Version OMPVersion = Actions.getLangOpts().getOpenMPVersion();
165 // Parse '('.
166 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
167 if (T.expectAndConsume(
168 diag::err_expected_lparen_after,
169 getOpenMPDirectiveName(OMPD_declare_reduction, OMPVersion).data())) {
170 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
171 return DeclGroupPtrTy();
172 }
173
174 DeclarationName Name = parseOpenMPReductionId(*this);
175 if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end))
176 return DeclGroupPtrTy();
177
178 // Consume ':'.
179 bool IsCorrect = !ExpectAndConsume(tok::colon);
180
181 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
182 return DeclGroupPtrTy();
183
184 IsCorrect = IsCorrect && !Name.isEmpty();
185
186 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) {
187 Diag(Tok.getLocation(), diag::err_expected_type);
188 IsCorrect = false;
189 }
190
191 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
192 return DeclGroupPtrTy();
193
194 SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes;
195 // Parse list of types until ':' token.
196 do {
197 ColonProtectionRAIIObject ColonRAII(*this);
198 SourceRange Range;
200 if (TR.isUsable()) {
201 QualType ReductionType = Actions.OpenMP().ActOnOpenMPDeclareReductionType(
202 Range.getBegin(), TR);
203 if (!ReductionType.isNull()) {
204 ReductionTypes.push_back(
205 std::make_pair(ReductionType, Range.getBegin()));
206 }
207 } else {
208 SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end,
210 }
211
212 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end))
213 break;
214
215 // Consume ','.
216 if (ExpectAndConsume(tok::comma)) {
217 IsCorrect = false;
218 if (Tok.is(tok::annot_pragma_openmp_end)) {
219 Diag(Tok.getLocation(), diag::err_expected_type);
220 return DeclGroupPtrTy();
221 }
222 }
223 } while (Tok.isNot(tok::annot_pragma_openmp_end));
224
225 if (ReductionTypes.empty()) {
226 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
227 return DeclGroupPtrTy();
228 }
229
230 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
231 return DeclGroupPtrTy();
232
233 // Consume ':'.
234 if (ExpectAndConsume(tok::colon))
235 IsCorrect = false;
236
237 if (Tok.is(tok::annot_pragma_openmp_end)) {
238 Diag(Tok.getLocation(), diag::err_expected_expression);
239 return DeclGroupPtrTy();
240 }
241
242 DeclGroupPtrTy DRD =
243 Actions.OpenMP().ActOnOpenMPDeclareReductionDirectiveStart(
244 getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes,
245 AS);
246
247 // Parse <combiner> expression and then parse initializer if any for each
248 // correct type.
249 unsigned I = 0, E = ReductionTypes.size();
250 for (Decl *D : DRD.get()) {
251 TentativeParsingAction TPA(*this);
252 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
255 // Parse <combiner> expression.
256 Actions.OpenMP().ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D);
257 ExprResult CombinerResult = Actions.ActOnFinishFullExpr(
258 ParseExpression().get(), D->getLocation(), /*DiscardedValue*/ false);
259 Actions.OpenMP().ActOnOpenMPDeclareReductionCombinerEnd(
260 D, CombinerResult.get());
261
262 if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
263 Tok.isNot(tok::annot_pragma_openmp_end)) {
264 TPA.Commit();
265 IsCorrect = false;
266 break;
267 }
268 IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable();
269 ExprResult InitializerResult;
270 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
271 // Parse <initializer> expression.
272 if (Tok.is(tok::identifier) &&
273 Tok.getIdentifierInfo()->isStr("initializer")) {
274 ConsumeToken();
275 } else {
276 Diag(Tok.getLocation(), diag::err_expected) << "'initializer'";
277 TPA.Commit();
278 IsCorrect = false;
279 break;
280 }
281 // Parse '('.
282 BalancedDelimiterTracker T(*this, tok::l_paren,
283 tok::annot_pragma_openmp_end);
284 IsCorrect =
285 !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") &&
286 IsCorrect;
287 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
288 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
291 // Parse expression.
292 VarDecl *OmpPrivParm =
293 Actions.OpenMP().ActOnOpenMPDeclareReductionInitializerStart(
294 getCurScope(), D);
295 // Check if initializer is omp_priv <init_expr> or something else.
296 if (Tok.is(tok::identifier) &&
297 Tok.getIdentifierInfo()->isStr("omp_priv")) {
298 ConsumeToken();
299 ParseOpenMPReductionInitializerForDecl(OmpPrivParm);
300 } else {
301 InitializerResult = Actions.ActOnFinishFullExpr(
302 ParseAssignmentExpression().get(), D->getLocation(),
303 /*DiscardedValue*/ false);
304 }
305 Actions.OpenMP().ActOnOpenMPDeclareReductionInitializerEnd(
306 D, InitializerResult.get(), OmpPrivParm);
307 if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
308 Tok.isNot(tok::annot_pragma_openmp_end)) {
309 TPA.Commit();
310 IsCorrect = false;
311 break;
312 }
313 IsCorrect =
314 !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid();
315 }
316 }
317
318 ++I;
319 // Revert parsing if not the last type, otherwise accept it, we're done with
320 // parsing.
321 if (I != E)
322 TPA.Revert();
323 else
324 TPA.Commit();
325 }
326 return Actions.OpenMP().ActOnOpenMPDeclareReductionDirectiveEnd(
327 getCurScope(), DRD, IsCorrect);
328}
329
330void Parser::ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm) {
331 // Parse declarator '=' initializer.
332 // If a '==' or '+=' is found, suggest a fixit to '='.
333 if (isTokenEqualOrEqualTypo()) {
334 ConsumeToken();
335
336 if (Tok.is(tok::code_completion)) {
337 cutOffParsing();
338 Actions.CodeCompletion().CodeCompleteInitializer(getCurScope(),
339 OmpPrivParm);
340 Actions.FinalizeDeclaration(OmpPrivParm);
341 return;
342 }
343
344 PreferredType.enterVariableInit(Tok.getLocation(), OmpPrivParm);
345 ExprResult Init = ParseInitializer(OmpPrivParm);
346
347 if (Init.isInvalid()) {
348 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
349 Actions.ActOnInitializerError(OmpPrivParm);
350 } else {
351 Actions.AddInitializerToDecl(OmpPrivParm, Init.get(),
352 /*DirectInit=*/false);
353 }
354 } else if (Tok.is(tok::l_paren)) {
355 // Parse C++ direct initializer: '(' expression-list ')'
356 BalancedDelimiterTracker T(*this, tok::l_paren);
357 T.consumeOpen();
358
359 ExprVector Exprs;
360
361 SourceLocation LParLoc = T.getOpenLocation();
362 auto RunSignatureHelp = [this, OmpPrivParm, LParLoc, &Exprs]() {
363 QualType PreferredType =
364 Actions.CodeCompletion().ProduceConstructorSignatureHelp(
365 OmpPrivParm->getType()->getCanonicalTypeInternal(),
366 OmpPrivParm->getLocation(), Exprs, LParLoc, /*Braced=*/false);
367 CalledSignatureHelp = true;
368 return PreferredType;
369 };
370 if (ParseExpressionList(Exprs, [&] {
371 PreferredType.enterFunctionArgument(Tok.getLocation(),
372 RunSignatureHelp);
373 })) {
374 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
375 RunSignatureHelp();
376 Actions.ActOnInitializerError(OmpPrivParm);
377 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
378 } else {
379 // Match the ')'.
380 SourceLocation RLoc = Tok.getLocation();
381 if (!T.consumeClose())
382 RLoc = T.getCloseLocation();
383
385 Actions.ActOnParenListExpr(T.getOpenLocation(), RLoc, Exprs);
386 Actions.AddInitializerToDecl(OmpPrivParm, Initializer.get(),
387 /*DirectInit=*/true);
388 }
389 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
390 // Parse C++0x braced-init-list.
391 Diag(Tok, diag::compat_cxx11_generalized_initializer_lists);
392
393 ExprResult Init(ParseBraceInitializer());
394
395 if (Init.isInvalid()) {
396 Actions.ActOnInitializerError(OmpPrivParm);
397 } else {
398 Actions.AddInitializerToDecl(OmpPrivParm, Init.get(),
399 /*DirectInit=*/true);
400 }
401 } else {
402 Actions.ActOnUninitializedDecl(OmpPrivParm);
403 }
404}
405
407Parser::ParseOpenMPDeclareMapperDirective(AccessSpecifier AS) {
408 bool IsCorrect = true;
409 llvm::omp::Version OMPVersion = Actions.getLangOpts().getOpenMPVersion();
410 // Parse '('
411 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
412 if (T.expectAndConsume(
413 diag::err_expected_lparen_after,
414 getOpenMPDirectiveName(OMPD_declare_mapper, OMPVersion).data())) {
415 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
416 return DeclGroupPtrTy();
417 }
418
419 // Parse <mapper-identifier>
420 auto &DeclNames = Actions.getASTContext().DeclarationNames;
421 DeclarationName MapperId;
422 if (PP.LookAhead(0).is(tok::colon)) {
423 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
424 Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
425 IsCorrect = false;
426 } else {
427 MapperId = DeclNames.getIdentifier(Tok.getIdentifierInfo());
428 }
429 ConsumeToken();
430 // Consume ':'.
431 ExpectAndConsume(tok::colon);
432 } else {
433 // If no mapper identifier is provided, its name is "default" by default
434 MapperId =
435 DeclNames.getIdentifier(&Actions.getASTContext().Idents.get("default"));
436 }
437
438 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
439 return DeclGroupPtrTy();
440
441 // Parse <type> <var>
442 DeclarationName VName;
443 QualType MapperType;
444 SourceRange Range;
445 TypeResult ParsedType = parseOpenMPDeclareMapperVarDecl(Range, VName, AS);
446 if (ParsedType.isUsable())
447 MapperType = Actions.OpenMP().ActOnOpenMPDeclareMapperType(Range.getBegin(),
448 ParsedType);
449 if (MapperType.isNull())
450 IsCorrect = false;
451 if (!IsCorrect) {
452 SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch);
453 return DeclGroupPtrTy();
454 }
455
456 // Consume ')'.
457 IsCorrect &= !T.consumeClose();
458 if (!IsCorrect) {
459 SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch);
460 return DeclGroupPtrTy();
461 }
462
463 Scope *OuterScope = getCurScope();
464 // Enter scope.
465 DeclarationNameInfo DirName;
466 SourceLocation Loc = Tok.getLocation();
467 unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
469 ParseScope OMPDirectiveScope(this, ScopeFlags);
470 Actions.OpenMP().StartOpenMPDSABlock(OMPD_declare_mapper, DirName,
471 getCurScope(), Loc);
472
473 // Add the mapper variable declaration.
474 ExprResult MapperVarRef =
475 Actions.OpenMP().ActOnOpenMPDeclareMapperDirectiveVarDecl(
476 getCurScope(), MapperType, Range.getBegin(), VName);
477
478 // Parse map clauses.
479 SmallVector<OMPClause *, 6> Clauses;
480 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
481 OpenMPClauseKind CKind = Tok.isAnnotation()
482 ? OMPC_unknown
483 : getOpenMPClauseKind(PP.getSpelling(Tok));
484 Actions.OpenMP().StartOpenMPClause(CKind);
485 OMPClause *Clause =
486 ParseOpenMPClause(OMPD_declare_mapper, CKind, Clauses.empty());
487 if (Clause)
488 Clauses.push_back(Clause);
489 else
490 IsCorrect = false;
491 // Skip ',' if any.
492 if (Tok.is(tok::comma))
493 ConsumeToken();
494 Actions.OpenMP().EndOpenMPClause();
495 }
496 if (Clauses.empty()) {
497 Diag(Tok, diag::err_omp_expected_clause)
498 << getOpenMPDirectiveName(OMPD_declare_mapper, OMPVersion);
499 IsCorrect = false;
500 }
501
502 // This needs to be called within the scope because
503 // processImplicitMapsWithDefaultMappers may add clauses when analyzing nested
504 // types. The scope used for calling ActOnOpenMPDeclareMapperDirective,
505 // however, needs to be the outer one, otherwise declared mappers don't become
506 // visible.
507 DeclGroupPtrTy DG = Actions.OpenMP().ActOnOpenMPDeclareMapperDirective(
508 OuterScope, Actions.getCurLexicalContext(), MapperId, MapperType,
509 Range.getBegin(), VName, AS, MapperVarRef.get(), Clauses);
510 // Exit scope.
511 Actions.OpenMP().EndOpenMPDSABlock(nullptr);
512 OMPDirectiveScope.Exit();
513 if (!IsCorrect)
514 return DeclGroupPtrTy();
515
516 return DG;
517}
518
519TypeResult Parser::parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
520 DeclarationName &Name,
521 AccessSpecifier AS) {
522 // Parse the common declaration-specifiers piece.
523 Parser::DeclSpecContext DSC = Parser::DeclSpecContext::DSC_type_specifier;
524 DeclSpec DS(AttrFactory);
525 ParseSpecifierQualifierList(DS, AS, DSC);
526
527 // Parse the declarator.
529 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
530 ParseDeclarator(DeclaratorInfo);
531 Range = DeclaratorInfo.getSourceRange();
532 if (DeclaratorInfo.getIdentifier() == nullptr) {
533 Diag(Tok.getLocation(), diag::err_omp_mapper_expected_declarator);
534 return true;
535 }
536 Name = Actions.GetNameForDeclarator(DeclaratorInfo).getName();
537
538 return Actions.OpenMP().ActOnOpenMPDeclareMapperVarDecl(getCurScope(),
539 DeclaratorInfo);
540}
541
542/// Parses 'omp begin declare variant' directive.
543// The syntax is:
544// { #pragma omp begin declare variant clause }
545// <function-declaration-or-definition-sequence>
546// { #pragma omp end declare variant }
547//
549 OMPTraitInfo *ParentTI =
550 Actions.OpenMP().getOMPTraitInfoForSurroundingScope();
551 ASTContext &ASTCtx = Actions.getASTContext();
552 OMPTraitInfo &TI = ASTCtx.getNewOMPTraitInfo();
553 if (parseOMPDeclareVariantMatchClause(Loc, TI, ParentTI)) {
554 while (!SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch))
555 ;
556 // Skip the last annot_pragma_openmp_end.
557 (void)ConsumeAnnotationToken();
558 return true;
559 }
560
561 // Skip last tokens.
562 skipUntilPragmaOpenMPEnd(OMPD_begin_declare_variant);
563
564 ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
565
566 VariantMatchInfo VMI;
567 TI.getAsVariantMatchInfo(ASTCtx, VMI);
568
569 std::function<void(StringRef)> DiagUnknownTrait = [this,
570 Loc](StringRef ISATrait) {
571 // TODO Track the selector locations in a way that is accessible here
572 // to improve the diagnostic location.
573 Diag(Loc, diag::warn_unknown_declare_variant_isa_trait) << ISATrait;
574 };
575 TargetOMPContext OMPCtx(
576 ASTCtx, std::move(DiagUnknownTrait),
577 /* CurrentFunctionDecl */ nullptr,
578 /* ConstructTraits */ ArrayRef<llvm::omp::TraitProperty>(),
579 Actions.OpenMP().getOpenMPDeviceNum());
580
581 if (isVariantApplicableInContext(VMI, OMPCtx,
582 /*DeviceOrImplementationSetOnly=*/true)) {
583 Actions.OpenMP().ActOnOpenMPBeginDeclareVariant(Loc, TI);
584 return false;
585 }
586
587 // Elide all the code till the matching end declare variant was found.
588 unsigned Nesting = 1;
589 SourceLocation DKLoc;
590 OpenMPDirectiveKind DK = OMPD_unknown;
591 do {
592 DKLoc = Tok.getLocation();
593 DK = parseOpenMPDirectiveKind(*this);
594 if (DK == OMPD_end_declare_variant)
595 --Nesting;
596 else if (DK == OMPD_begin_declare_variant)
597 ++Nesting;
598 if (!Nesting || isEofOrEom())
599 break;
601 } while (true);
602
603 parseOMPEndDirective(OMPD_begin_declare_variant, OMPD_end_declare_variant, DK,
604 Loc, DKLoc, /* SkipUntilOpenMPEnd */ true);
605 return false;
606}
607
608namespace {
609/// RAII that recreates function context for correct parsing of clauses of
610/// 'declare simd' construct.
611/// OpenMP, 2.8.2 declare simd Construct
612/// The expressions appearing in the clauses of this directive are evaluated in
613/// the scope of the arguments of the function declaration or definition.
614class FNContextRAII final {
615 Parser &P;
616 Sema::CXXThisScopeRAII *ThisScope;
618 bool HasFunScope = false;
619 FNContextRAII() = delete;
620 FNContextRAII(const FNContextRAII &) = delete;
621 FNContextRAII &operator=(const FNContextRAII &) = delete;
622
623public:
624 FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P), Scopes(P) {
625 Decl *D = *Ptr.get().begin();
626 NamedDecl *ND = dyn_cast<NamedDecl>(D);
627 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
628 Sema &Actions = P.getActions();
629
630 // Allow 'this' within late-parsed attributes.
631 ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, Qualifiers(),
632 ND && ND->isCXXInstanceMember());
633
634 // If the Decl is templatized, add template parameters to scope.
635 // FIXME: Track CurTemplateDepth?
636 P.ReenterTemplateScopes(Scopes, D);
637
638 // If the Decl is on a function, add function parameters to the scope.
640 HasFunScope = true;
643 Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D);
644 }
645 }
646 ~FNContextRAII() {
647 if (HasFunScope)
649 delete ThisScope;
650 }
651};
652} // namespace
653
654/// Parses clauses for 'declare simd' directive.
655/// clause:
656/// 'inbranch' | 'notinbranch'
657/// 'simdlen' '(' <expr> ')'
658/// { 'uniform' '(' <argument_list> ')' }
659/// { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' }
660/// { 'linear '(' <argument_list> [ ':' <step> ] ')' }
662 Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen,
666 SourceRange BSRange;
667 const Token &Tok = P.getCurToken();
668 bool IsError = false;
669 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
670 if (Tok.isNot(tok::identifier))
671 break;
672 OMPDeclareSimdDeclAttr::BranchStateTy Out;
673 IdentifierInfo *II = Tok.getIdentifierInfo();
674 StringRef ClauseName = II->getName();
675 // Parse 'inranch|notinbranch' clauses.
676 if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) {
677 if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) {
678 P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch)
679 << ClauseName
680 << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange;
681 IsError = true;
682 }
683 BS = Out;
684 BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc());
685 P.ConsumeToken();
686 } else if (ClauseName == "simdlen") {
687 if (SimdLen.isUsable()) {
688 llvm::omp::Version OMPVersion =
690 P.Diag(Tok, diag::err_omp_more_one_clause)
691 << getOpenMPDirectiveName(OMPD_declare_simd, OMPVersion)
692 << ClauseName << 0;
693 IsError = true;
694 }
695 P.ConsumeToken();
696 SourceLocation RLoc;
697 SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc);
698 if (SimdLen.isInvalid())
699 IsError = true;
700 } else {
701 OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName);
702 if (CKind == OMPC_uniform || CKind == OMPC_aligned ||
703 CKind == OMPC_linear) {
705 SmallVectorImpl<Expr *> *Vars = &Uniforms;
706 if (CKind == OMPC_aligned) {
707 Vars = &Aligneds;
708 } else if (CKind == OMPC_linear) {
709 Data.ExtraModifier = OMPC_LINEAR_val;
710 Vars = &Linears;
711 }
712
713 P.ConsumeToken();
714 SmallVector<OMPAdjustArgsItem> AdjustArgsItems;
715 if (P.ParseOpenMPVarList(OMPD_declare_simd,
716 getOpenMPClauseKind(ClauseName), *Vars, Data,
717 AdjustArgsItems))
718 IsError = true;
719 if (CKind == OMPC_aligned) {
720 Alignments.append(Aligneds.size() - Alignments.size(),
721 Data.DepModOrTailExpr);
722 } else if (CKind == OMPC_linear) {
723 assert(0 <= Data.ExtraModifier &&
724 Data.ExtraModifier <= OMPC_LINEAR_unknown &&
725 "Unexpected linear modifier.");
727 static_cast<OpenMPLinearClauseKind>(Data.ExtraModifier),
728 Data.ExtraModifierLoc))
729 Data.ExtraModifier = OMPC_LINEAR_val;
730 LinModifiers.append(Linears.size() - LinModifiers.size(),
731 Data.ExtraModifier);
732 Steps.append(Linears.size() - Steps.size(), Data.DepModOrTailExpr);
733 }
734 } else
735 // TODO: add parsing of other clauses.
736 break;
737 }
738 // Skip ',' if any.
739 if (Tok.is(tok::comma))
740 P.ConsumeToken();
741 }
742 return IsError;
743}
744
746Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr,
747 CachedTokens &Toks, SourceLocation Loc) {
748 PP.EnterToken(Tok, /*IsReinject*/ true);
749 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
750 /*IsReinject*/ true);
751 // Consume the previously pushed token.
752 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
753 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
754
755 FNContextRAII FnContext(*this, Ptr);
756 OMPDeclareSimdDeclAttr::BranchStateTy BS =
757 OMPDeclareSimdDeclAttr::BS_Undefined;
758 ExprResult Simdlen;
759 SmallVector<Expr *, 4> Uniforms;
760 SmallVector<Expr *, 4> Aligneds;
761 SmallVector<Expr *, 4> Alignments;
762 SmallVector<Expr *, 4> Linears;
763 SmallVector<unsigned, 4> LinModifiers;
764 SmallVector<Expr *, 4> Steps;
765 bool IsError =
766 parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds,
767 Alignments, Linears, LinModifiers, Steps);
768 skipUntilPragmaOpenMPEnd(OMPD_declare_simd);
769 // Skip the last annot_pragma_openmp_end.
770 SourceLocation EndLoc = ConsumeAnnotationToken();
771 if (IsError)
772 return Ptr;
773 return Actions.OpenMP().ActOnOpenMPDeclareSimdDirective(
774 Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears,
775 LinModifiers, Steps, SourceRange(Loc, EndLoc));
776}
777
778namespace {
779/// Constant used in the diagnostics to distinguish the levels in an OpenMP
780/// contexts: selector-set={selector(trait, ...), ...}, ....
781enum OMPContextLvl {
782 CONTEXT_SELECTOR_SET_LVL = 0,
783 CONTEXT_SELECTOR_LVL = 1,
784 CONTEXT_TRAIT_LVL = 2,
785};
786
787static StringRef stringLiteralParser(Parser &P) {
789 return Res.isUsable() ? Res.getAs<StringLiteral>()->getString() : "";
790}
791
792static StringRef getNameFromIdOrString(Parser &P, Token &Tok,
793 OMPContextLvl Lvl) {
794 if (Tok.is(tok::identifier) || Tok.is(tok::kw_for)) {
796 StringRef Name = P.getPreprocessor().getSpelling(Tok, Buffer);
797 (void)P.ConsumeToken();
798 return Name;
799 }
800
802 return stringLiteralParser(P);
803
804 P.Diag(Tok.getLocation(),
805 diag::warn_omp_declare_variant_string_literal_or_identifier)
806 << Lvl;
807 return "";
808}
809
810static bool checkForDuplicates(Parser &P, StringRef Name,
811 SourceLocation NameLoc,
812 llvm::StringMap<SourceLocation> &Seen,
813 OMPContextLvl Lvl) {
814 auto Res = Seen.try_emplace(Name, NameLoc);
815 if (Res.second)
816 return false;
817
818 // Each trait-set-selector-name, trait-selector-name and trait-name can
819 // only be specified once.
820 P.Diag(NameLoc, diag::warn_omp_declare_variant_ctx_mutiple_use)
821 << Lvl << Name;
822 P.Diag(Res.first->getValue(), diag::note_omp_declare_variant_ctx_used_here)
823 << Lvl << Name;
824 return true;
825}
826} // namespace
827
828void Parser::parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
829 llvm::omp::TraitSet Set,
830 llvm::omp::TraitSelector Selector,
831 llvm::StringMap<SourceLocation> &Seen) {
832 TIProperty.Kind = TraitProperty::invalid;
833
834 SourceLocation NameLoc = Tok.getLocation();
835 StringRef Name;
836 if (Selector == llvm::omp::TraitSelector::target_device_device_num) {
837 Name = "number";
838 TIProperty.Kind = getOpenMPContextTraitPropertyKind(Set, Selector, Name);
839 ExprResult DeviceNumExprResult = ParseExpression();
840 if (DeviceNumExprResult.isUsable()) {
841 Expr *DeviceNumExpr = DeviceNumExprResult.get();
842 Actions.OpenMP().ActOnOpenMPDeviceNum(DeviceNumExpr);
843 }
844 return;
845 }
846 Name = getNameFromIdOrString(*this, Tok, CONTEXT_TRAIT_LVL);
847 if (Name.empty()) {
848 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
849 << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector);
850 return;
851 }
852
853 TIProperty.RawString = Name;
854 TIProperty.Kind = getOpenMPContextTraitPropertyKind(Set, Selector, Name);
855 if (TIProperty.Kind != TraitProperty::invalid) {
856 if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_TRAIT_LVL))
857 TIProperty.Kind = TraitProperty::invalid;
858 return;
859 }
860
861 // It follows diagnosis and helping notes.
862 // FIXME: We should move the diagnosis string generation into libFrontend.
863 Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_property)
864 << Name << getOpenMPContextTraitSelectorName(Selector)
865 << getOpenMPContextTraitSetName(Set);
866
867 TraitSet SetForName = getOpenMPContextTraitSetKind(Name);
868 if (SetForName != TraitSet::invalid) {
869 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
870 << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_TRAIT_LVL;
871 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
872 << Name << "<selector-name>"
873 << "(<property-name>)";
874 return;
875 }
876 TraitSelector SelectorForName =
877 getOpenMPContextTraitSelectorKind(Name, SetForName);
878 if (SelectorForName != TraitSelector::invalid) {
879 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
880 << Name << CONTEXT_SELECTOR_LVL << CONTEXT_TRAIT_LVL;
881 bool AllowsTraitScore = false;
882 bool RequiresProperty = false;
883 isValidTraitSelectorForTraitSet(
884 SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName),
885 AllowsTraitScore, RequiresProperty);
886 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
887 << getOpenMPContextTraitSetName(
888 getOpenMPContextTraitSetForSelector(SelectorForName))
889 << Name << (RequiresProperty ? "(<property-name>)" : "");
890 return;
891 }
892 for (const auto &PotentialSet :
893 {TraitSet::construct, TraitSet::user, TraitSet::implementation,
894 TraitSet::device, TraitSet::target_device}) {
895 TraitProperty PropertyForName =
896 getOpenMPContextTraitPropertyKind(PotentialSet, Selector, Name);
897 if (PropertyForName == TraitProperty::invalid)
898 continue;
899 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
900 << getOpenMPContextTraitSetName(
901 getOpenMPContextTraitSetForProperty(PropertyForName))
902 << getOpenMPContextTraitSelectorName(
903 getOpenMPContextTraitSelectorForProperty(PropertyForName))
904 << ("(" + Name + ")").str();
905 return;
906 }
907 Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
908 << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector);
909}
910
912 OMPTraitProperty &TIProperty,
913 OMPTraitSelector &TISelector,
914 llvm::StringMap<SourceLocation> &Seen) {
915 assert(TISelector.Kind ==
916 llvm::omp::TraitSelector::implementation_extension &&
917 "Only for extension properties, e.g., "
918 "`implementation={extension(PROPERTY)}`");
919 if (TIProperty.Kind == TraitProperty::invalid)
920 return false;
921
922 if (TIProperty.Kind ==
923 TraitProperty::implementation_extension_disable_implicit_base)
924 return true;
925
926 if (TIProperty.Kind ==
927 TraitProperty::implementation_extension_allow_templates)
928 return true;
929
930 if (TIProperty.Kind ==
931 TraitProperty::implementation_extension_bind_to_declaration)
932 return true;
933
934 auto IsMatchExtension = [](OMPTraitProperty &TP) {
935 return (TP.Kind ==
936 llvm::omp::TraitProperty::implementation_extension_match_all ||
937 TP.Kind ==
938 llvm::omp::TraitProperty::implementation_extension_match_any ||
939 TP.Kind ==
940 llvm::omp::TraitProperty::implementation_extension_match_none);
941 };
942
943 if (IsMatchExtension(TIProperty)) {
944 for (OMPTraitProperty &SeenProp : TISelector.Properties)
945 if (IsMatchExtension(SeenProp)) {
946 P.Diag(Loc, diag::err_omp_variant_ctx_second_match_extension);
947 StringRef SeenName = llvm::omp::getOpenMPContextTraitPropertyName(
948 SeenProp.Kind, SeenProp.RawString);
949 SourceLocation SeenLoc = Seen[SeenName];
950 P.Diag(SeenLoc, diag::note_omp_declare_variant_ctx_used_here)
951 << CONTEXT_TRAIT_LVL << SeenName;
952 return false;
953 }
954 return true;
955 }
956
957 llvm_unreachable("Unknown extension property!");
958}
959
960void Parser::parseOMPContextProperty(OMPTraitSelector &TISelector,
961 llvm::omp::TraitSet Set,
962 llvm::StringMap<SourceLocation> &Seen) {
963 assert(TISelector.Kind != TraitSelector::user_condition &&
964 "User conditions are special properties not handled here!");
965
966 SourceLocation PropertyLoc = Tok.getLocation();
967 OMPTraitProperty TIProperty;
968 parseOMPTraitPropertyKind(TIProperty, Set, TISelector.Kind, Seen);
969
970 if (TISelector.Kind == llvm::omp::TraitSelector::implementation_extension)
971 if (!checkExtensionProperty(*this, Tok.getLocation(), TIProperty,
972 TISelector, Seen))
973 TIProperty.Kind = TraitProperty::invalid;
974
975 // If we have an invalid property here we already issued a warning.
976 if (TIProperty.Kind == TraitProperty::invalid) {
977 if (PropertyLoc != Tok.getLocation())
978 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
979 << CONTEXT_TRAIT_LVL;
980 return;
981 }
982
983 if (isValidTraitPropertyForTraitSetAndSelector(TIProperty.Kind,
984 TISelector.Kind, Set)) {
985
986 // If we make it here the property, selector, set, score, condition, ... are
987 // all valid (or have been corrected). Thus we can record the property.
988 TISelector.Properties.push_back(TIProperty);
989 return;
990 }
991
992 Diag(PropertyLoc, diag::warn_omp_ctx_incompatible_property_for_selector)
993 << getOpenMPContextTraitPropertyName(TIProperty.Kind,
994 TIProperty.RawString)
995 << getOpenMPContextTraitSelectorName(TISelector.Kind)
996 << getOpenMPContextTraitSetName(Set);
997 Diag(PropertyLoc, diag::note_omp_ctx_compatible_set_and_selector_for_property)
998 << getOpenMPContextTraitPropertyName(TIProperty.Kind,
999 TIProperty.RawString)
1000 << getOpenMPContextTraitSelectorName(
1001 getOpenMPContextTraitSelectorForProperty(TIProperty.Kind))
1002 << getOpenMPContextTraitSetName(
1003 getOpenMPContextTraitSetForProperty(TIProperty.Kind));
1004 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1005 << CONTEXT_TRAIT_LVL;
1006}
1007
1008void Parser::parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
1009 llvm::omp::TraitSet Set,
1010 llvm::StringMap<SourceLocation> &Seen) {
1011 TISelector.Kind = TraitSelector::invalid;
1012
1013 SourceLocation NameLoc = Tok.getLocation();
1014 StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_LVL);
1015 if (Name.empty()) {
1016 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
1017 << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set);
1018 return;
1019 }
1020
1021 TISelector.Kind = getOpenMPContextTraitSelectorKind(Name, Set);
1022 if (TISelector.Kind != TraitSelector::invalid) {
1023 if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_SELECTOR_LVL))
1024 TISelector.Kind = TraitSelector::invalid;
1025 return;
1026 }
1027
1028 // It follows diagnosis and helping notes.
1029 Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_selector)
1030 << Name << getOpenMPContextTraitSetName(Set);
1031
1032 TraitSet SetForName = getOpenMPContextTraitSetKind(Name);
1033 if (SetForName != TraitSet::invalid) {
1034 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1035 << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_SELECTOR_LVL;
1036 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1037 << Name << "<selector-name>"
1038 << "<property-name>";
1039 return;
1040 }
1041 for (const auto &PotentialSet :
1042 {TraitSet::construct, TraitSet::user, TraitSet::implementation,
1043 TraitSet::device, TraitSet::target_device}) {
1044 TraitProperty PropertyForName = getOpenMPContextTraitPropertyKind(
1045 PotentialSet, TraitSelector::invalid, Name);
1046 if (PropertyForName == TraitProperty::invalid)
1047 continue;
1048 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1049 << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_LVL;
1050 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1051 << getOpenMPContextTraitSetName(
1052 getOpenMPContextTraitSetForProperty(PropertyForName))
1053 << getOpenMPContextTraitSelectorName(
1054 getOpenMPContextTraitSelectorForProperty(PropertyForName))
1055 << ("(" + Name + ")").str();
1056 return;
1057 }
1058 Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
1059 << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set);
1060}
1061
1062/// Parse optional 'score' '(' <expr> ')' ':'.
1064 ExprResult ScoreExpr;
1065 llvm::SmallString<16> Buffer;
1066 StringRef SelectorName =
1067 P.getPreprocessor().getSpelling(P.getCurToken(), Buffer);
1068 if (SelectorName != "score")
1069 return ScoreExpr;
1070 (void)P.ConsumeToken();
1071 SourceLocation RLoc;
1072 ScoreExpr = P.ParseOpenMPParensExpr(SelectorName, RLoc);
1073 // Parse ':'
1074 if (P.getCurToken().is(tok::colon))
1075 (void)P.ConsumeAnyToken();
1076 else
1077 P.Diag(P.getCurToken(), diag::warn_omp_declare_variant_expected)
1078 << "':'"
1079 << "score expression";
1080 return ScoreExpr;
1081}
1082
1083void Parser::parseOMPContextSelector(
1084 OMPTraitSelector &TISelector, llvm::omp::TraitSet Set,
1085 llvm::StringMap<SourceLocation> &SeenSelectors) {
1086 unsigned short OuterPC = ParenCount;
1087
1088 // If anything went wrong we issue an error or warning and then skip the rest
1089 // of the selector. However, commas are ambiguous so we look for the nesting
1090 // of parentheses here as well.
1091 auto FinishSelector = [OuterPC, this]() -> void {
1092 bool Done = false;
1093 while (!Done) {
1094 while (!SkipUntil({tok::r_brace, tok::r_paren, tok::comma,
1095 tok::annot_pragma_openmp_end},
1097 ;
1098 if (Tok.is(tok::r_paren) && OuterPC > ParenCount)
1099 (void)ConsumeParen();
1100 if (OuterPC <= ParenCount) {
1101 Done = true;
1102 break;
1103 }
1104 if (!Tok.is(tok::comma) && !Tok.is(tok::r_paren)) {
1105 Done = true;
1106 break;
1107 }
1108 (void)ConsumeAnyToken();
1109 }
1110 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1111 << CONTEXT_SELECTOR_LVL;
1112 };
1113
1114 SourceLocation SelectorLoc = Tok.getLocation();
1115 parseOMPTraitSelectorKind(TISelector, Set, SeenSelectors);
1116 if (TISelector.Kind == TraitSelector::invalid)
1117 return FinishSelector();
1118
1119 bool AllowsTraitScore = false;
1120 bool RequiresProperty = false;
1121 if (!isValidTraitSelectorForTraitSet(TISelector.Kind, Set, AllowsTraitScore,
1122 RequiresProperty)) {
1123 Diag(SelectorLoc, diag::warn_omp_ctx_incompatible_selector_for_set)
1124 << getOpenMPContextTraitSelectorName(TISelector.Kind)
1125 << getOpenMPContextTraitSetName(Set);
1126 Diag(SelectorLoc, diag::note_omp_ctx_compatible_set_for_selector)
1127 << getOpenMPContextTraitSelectorName(TISelector.Kind)
1128 << getOpenMPContextTraitSetName(
1129 getOpenMPContextTraitSetForSelector(TISelector.Kind))
1130 << RequiresProperty;
1131 return FinishSelector();
1132 }
1133
1134 if (!RequiresProperty) {
1135 TISelector.Properties.push_back(
1136 {getOpenMPContextTraitPropertyForSelector(TISelector.Kind),
1137 getOpenMPContextTraitSelectorName(TISelector.Kind)});
1138 return;
1139 }
1140
1141 if (!Tok.is(tok::l_paren)) {
1142 Diag(SelectorLoc, diag::warn_omp_ctx_selector_without_properties)
1143 << getOpenMPContextTraitSelectorName(TISelector.Kind)
1144 << getOpenMPContextTraitSetName(Set);
1145 return FinishSelector();
1146 }
1147
1148 if (TISelector.Kind == TraitSelector::user_condition) {
1149 SourceLocation RLoc;
1150 ExprResult Condition = ParseOpenMPParensExpr("user condition", RLoc);
1151 if (!Condition.isUsable())
1152 return FinishSelector();
1153 TISelector.ScoreOrCondition = Condition.get();
1154 TISelector.Properties.push_back(
1155 {TraitProperty::user_condition_unknown, "<condition>"});
1156 return;
1157 }
1158
1159 BalancedDelimiterTracker BDT(*this, tok::l_paren,
1160 tok::annot_pragma_openmp_end);
1161 // Parse '('.
1162 (void)BDT.consumeOpen();
1163
1164 SourceLocation ScoreLoc = Tok.getLocation();
1165 ExprResult Score = parseContextScore(*this);
1166
1167 if (!AllowsTraitScore && !Score.isUnset()) {
1168 if (Score.isUsable()) {
1169 Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property)
1170 << getOpenMPContextTraitSelectorName(TISelector.Kind)
1171 << getOpenMPContextTraitSetName(Set) << Score.get();
1172 } else {
1173 Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property)
1174 << getOpenMPContextTraitSelectorName(TISelector.Kind)
1175 << getOpenMPContextTraitSetName(Set) << "<invalid>";
1176 }
1177 Score = ExprResult();
1178 }
1179
1180 if (Score.isUsable())
1181 TISelector.ScoreOrCondition = Score.get();
1182
1183 llvm::StringMap<SourceLocation> SeenProperties;
1184 do {
1185 parseOMPContextProperty(TISelector, Set, SeenProperties);
1186 } while (TryConsumeToken(tok::comma));
1187
1188 // Parse ')'.
1189 BDT.consumeClose();
1190}
1191
1192void Parser::parseOMPTraitSetKind(OMPTraitSet &TISet,
1193 llvm::StringMap<SourceLocation> &Seen) {
1194 TISet.Kind = TraitSet::invalid;
1195
1196 SourceLocation NameLoc = Tok.getLocation();
1197 StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_SET_LVL);
1198 if (Name.empty()) {
1199 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
1200 << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets();
1201 return;
1202 }
1203
1204 TISet.Kind = getOpenMPContextTraitSetKind(Name);
1205 if (TISet.Kind != TraitSet::invalid) {
1206 if (checkForDuplicates(*this, Name, NameLoc, Seen,
1207 CONTEXT_SELECTOR_SET_LVL))
1208 TISet.Kind = TraitSet::invalid;
1209 return;
1210 }
1211
1212 // It follows diagnosis and helping notes.
1213 Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_set) << Name;
1214
1215 TraitSelector SelectorForName =
1216 getOpenMPContextTraitSelectorKind(Name, TISet.Kind);
1217 if (SelectorForName != TraitSelector::invalid) {
1218 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1219 << Name << CONTEXT_SELECTOR_LVL << CONTEXT_SELECTOR_SET_LVL;
1220 bool AllowsTraitScore = false;
1221 bool RequiresProperty = false;
1222 isValidTraitSelectorForTraitSet(
1223 SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName),
1224 AllowsTraitScore, RequiresProperty);
1225 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1226 << getOpenMPContextTraitSetName(
1227 getOpenMPContextTraitSetForSelector(SelectorForName))
1228 << Name << (RequiresProperty ? "(<property-name>)" : "");
1229 return;
1230 }
1231 for (const auto &PotentialSet :
1232 {TraitSet::construct, TraitSet::user, TraitSet::implementation,
1233 TraitSet::device, TraitSet::target_device}) {
1234 TraitProperty PropertyForName = getOpenMPContextTraitPropertyKind(
1235 PotentialSet, TraitSelector::invalid, Name);
1236 if (PropertyForName == TraitProperty::invalid)
1237 continue;
1238 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1239 << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_SET_LVL;
1240 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1241 << getOpenMPContextTraitSetName(
1242 getOpenMPContextTraitSetForProperty(PropertyForName))
1243 << getOpenMPContextTraitSelectorName(
1244 getOpenMPContextTraitSelectorForProperty(PropertyForName))
1245 << ("(" + Name + ")").str();
1246 return;
1247 }
1248 Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
1249 << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets();
1250}
1251
1252void Parser::parseOMPContextSelectorSet(
1253 OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets) {
1254 auto OuterBC = BraceCount;
1255
1256 // If anything went wrong we issue an error or warning and then skip the rest
1257 // of the set. However, commas are ambiguous so we look for the nesting
1258 // of braces here as well.
1259 auto FinishSelectorSet = [this, OuterBC]() -> void {
1260 bool Done = false;
1261 while (!Done) {
1262 while (!SkipUntil({tok::comma, tok::r_brace, tok::r_paren,
1263 tok::annot_pragma_openmp_end},
1265 ;
1266 if (Tok.is(tok::r_brace) && OuterBC > BraceCount)
1267 (void)ConsumeBrace();
1268 if (OuterBC <= BraceCount) {
1269 Done = true;
1270 break;
1271 }
1272 if (!Tok.is(tok::comma) && !Tok.is(tok::r_brace)) {
1273 Done = true;
1274 break;
1275 }
1276 (void)ConsumeAnyToken();
1277 }
1278 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1279 << CONTEXT_SELECTOR_SET_LVL;
1280 };
1281
1282 parseOMPTraitSetKind(TISet, SeenSets);
1283 if (TISet.Kind == TraitSet::invalid)
1284 return FinishSelectorSet();
1285
1286 // Parse '='.
1287 if (!TryConsumeToken(tok::equal))
1288 Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
1289 << "="
1290 << ("context set name \"" + getOpenMPContextTraitSetName(TISet.Kind) +
1291 "\"");
1292
1293 // Parse '{'.
1294 if (Tok.is(tok::l_brace)) {
1295 (void)ConsumeBrace();
1296 } else {
1297 Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
1298 << "{"
1299 << ("'=' that follows the context set name \"" +
1300 getOpenMPContextTraitSetName(TISet.Kind) + "\"")
1301 .str();
1302 }
1303
1304 llvm::StringMap<SourceLocation> SeenSelectors;
1305 do {
1306 OMPTraitSelector TISelector;
1307 parseOMPContextSelector(TISelector, TISet.Kind, SeenSelectors);
1308 if (TISelector.Kind != TraitSelector::invalid &&
1309 !TISelector.Properties.empty())
1310 TISet.Selectors.push_back(TISelector);
1311 } while (TryConsumeToken(tok::comma));
1312
1313 // Parse '}'.
1314 if (Tok.is(tok::r_brace)) {
1315 (void)ConsumeBrace();
1316 } else {
1317 Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
1318 << "}"
1319 << ("context selectors for the context set \"" +
1320 getOpenMPContextTraitSetName(TISet.Kind) + "\"")
1321 .str();
1322 }
1323}
1324
1325bool Parser::parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI) {
1326 llvm::StringMap<SourceLocation> SeenSets;
1327 do {
1328 OMPTraitSet TISet;
1329 parseOMPContextSelectorSet(TISet, SeenSets);
1330 if (TISet.Kind != TraitSet::invalid && !TISet.Selectors.empty())
1331 TI.Sets.push_back(TISet);
1332 } while (TryConsumeToken(tok::comma));
1333
1334 return false;
1335}
1336
1337void Parser::ParseOMPDeclareVariantClauses(Parser::DeclGroupPtrTy Ptr,
1338 CachedTokens &Toks,
1339 SourceLocation Loc) {
1340 llvm::omp::Version OMPVersion = Actions.getLangOpts().getOpenMPVersion();
1341 PP.EnterToken(Tok, /*IsReinject*/ true);
1342 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1343 /*IsReinject*/ true);
1344 // Consume the previously pushed token.
1345 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1346 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1347
1348 FNContextRAII FnContext(*this, Ptr);
1349 // Parse function declaration id.
1350 SourceLocation RLoc;
1351 // Parse with IsAddressOfOperand set to true to parse methods as DeclRefExprs
1352 // instead of MemberExprs.
1353 ExprResult AssociatedFunction;
1354 {
1355 // Do not mark function as is used to prevent its emission if this is the
1356 // only place where it is used.
1357 EnterExpressionEvaluationContext Unevaluated(
1359 AssociatedFunction = ParseOpenMPParensExpr(
1360 getOpenMPDirectiveName(OMPD_declare_variant, OMPVersion), RLoc,
1361 /*IsAddressOfOperand=*/true);
1362 }
1363 if (!AssociatedFunction.isUsable()) {
1364 if (!Tok.is(tok::annot_pragma_openmp_end))
1365 while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch))
1366 ;
1367 // Skip the last annot_pragma_openmp_end.
1368 (void)ConsumeAnnotationToken();
1369 return;
1370 }
1371
1372 OMPTraitInfo *ParentTI =
1373 Actions.OpenMP().getOMPTraitInfoForSurroundingScope();
1374 ASTContext &ASTCtx = Actions.getASTContext();
1375 OMPTraitInfo &TI = ASTCtx.getNewOMPTraitInfo();
1376 SmallVector<OMPAdjustArgsDescriptor *, 3> AdjustArgs;
1377 SmallVector<OMPInteropInfo, 3> AppendArgs;
1378 SourceLocation AdjustArgsLoc, AppendArgsLoc;
1379
1380 // At least one clause is required.
1381 if (Tok.is(tok::annot_pragma_openmp_end)) {
1382 Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
1383 << (getLangOpts().OpenMP < 51 ? 0 : 1);
1384 }
1385
1386 bool IsError = false;
1387 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1388 OpenMPClauseKind CKind = Tok.isAnnotation()
1389 ? OMPC_unknown
1390 : getOpenMPClauseKind(PP.getSpelling(Tok));
1391 if (!isAllowedClauseForDirective(OMPD_declare_variant, CKind, OMPVersion)) {
1392 Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
1393 << (OMPVersion < 51 ? 0 : 1);
1394 IsError = true;
1395 }
1396 if (!IsError) {
1397 switch (CKind) {
1398 case OMPC_match:
1399 IsError = parseOMPDeclareVariantMatchClause(Loc, TI, ParentTI);
1400 break;
1401 case OMPC_adjust_args: {
1402 AdjustArgsLoc = Tok.getLocation();
1403 ConsumeToken();
1404 SemaOpenMP::OpenMPVarListDataTy Data;
1405 SmallVector<Expr *> Vars;
1406 SmallVector<OMPAdjustArgsItem, 4> Items;
1407 IsError = ParseOpenMPVarList(OMPD_declare_variant, OMPC_adjust_args,
1408 Vars, Data, Items);
1409 if (!IsError) {
1410 for (Expr *E : Vars) {
1411 OMPAdjustArgsItem Item;
1412 Item.E = E;
1413 Items.push_back(Item);
1414 }
1415 OpenMPAdjustArgsOpKind AdjustOp =
1416 static_cast<OpenMPAdjustArgsOpKind>(Data.ExtraModifier);
1417 OpenMPNeedDevicePtrModifier NeedDevicePtrModifier =
1419 if (Data.NeedDevicePtrModifierLoc.isValid())
1420 NeedDevicePtrModifier = static_cast<OpenMPNeedDevicePtrModifier>(
1421 Data.NeedDevicePtrModifier);
1422 OMPAdjustArgsDescriptor *Desc =
1423 Actions.OpenMP().ActOnOpenMPAdjustArgsClause(
1424 AdjustOp, NeedDevicePtrModifier, Items, AdjustArgsLoc);
1425 if (Desc)
1426 AdjustArgs.push_back(Desc);
1427 else
1428 IsError = true;
1429 }
1430 break;
1431 }
1432 case OMPC_append_args:
1433 if (!AppendArgs.empty()) {
1434 Diag(AppendArgsLoc, diag::err_omp_more_one_clause)
1435 << getOpenMPDirectiveName(OMPD_declare_variant, OMPVersion)
1436 << getOpenMPClauseName(CKind) << 0;
1437 IsError = true;
1438 }
1439 if (!IsError) {
1440 AppendArgsLoc = Tok.getLocation();
1441 ConsumeToken();
1442 IsError = parseOpenMPAppendArgs(AppendArgs);
1443 }
1444 break;
1445 default:
1446 llvm_unreachable("Unexpected clause for declare variant.");
1447 }
1448 }
1449 if (IsError) {
1450 while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch))
1451 ;
1452 // Skip the last annot_pragma_openmp_end.
1453 (void)ConsumeAnnotationToken();
1454 return;
1455 }
1456 // Skip ',' if any.
1457 if (Tok.is(tok::comma))
1458 ConsumeToken();
1459 }
1460
1461 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
1462 Actions.OpenMP().checkOpenMPDeclareVariantFunction(
1463 Ptr, AssociatedFunction.get(), TI, AppendArgs.size(),
1464 SourceRange(Loc, Tok.getLocation()));
1465
1466 if (DeclVarData && !TI.Sets.empty())
1467 Actions.OpenMP().ActOnOpenMPDeclareVariantDirective(
1468 DeclVarData->first, DeclVarData->second, TI, AdjustArgs, AppendArgs,
1469 AdjustArgsLoc, AppendArgsLoc, SourceRange(Loc, Tok.getLocation()));
1470
1471 // Skip the last annot_pragma_openmp_end.
1472 (void)ConsumeAnnotationToken();
1473}
1474
1475bool Parser::parseOpenMPAppendArgs(
1476 SmallVectorImpl<OMPInteropInfo> &InteropInfos) {
1477 bool HasError = false;
1478 // Parse '('.
1479 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1480 if (T.expectAndConsume(diag::err_expected_lparen_after,
1481 getOpenMPClauseName(OMPC_append_args).data()))
1482 return true;
1483
1484 // Parse the list of append-ops, each is;
1485 // interop(interop-type[,interop-type]...)
1486 while (Tok.is(tok::identifier) && Tok.getIdentifierInfo()->isStr("interop")) {
1487 ConsumeToken();
1488 BalancedDelimiterTracker IT(*this, tok::l_paren,
1489 tok::annot_pragma_openmp_end);
1490 if (IT.expectAndConsume(diag::err_expected_lparen_after, "interop"))
1491 return true;
1492
1493 OMPInteropInfo InteropInfo;
1494 if (ParseOMPInteropInfo(InteropInfo, OMPC_append_args))
1495 HasError = true;
1496 else
1497 InteropInfos.push_back(InteropInfo);
1498
1499 IT.consumeClose();
1500 if (Tok.is(tok::comma))
1501 ConsumeToken();
1502 }
1503 if (!HasError && InteropInfos.empty()) {
1504 HasError = true;
1505 Diag(Tok.getLocation(), diag::err_omp_unexpected_append_op);
1506 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1508 }
1509 HasError = T.consumeClose() || HasError;
1510 return HasError;
1511}
1512
1513bool Parser::parseOMPDeclareVariantMatchClause(SourceLocation Loc,
1514 OMPTraitInfo &TI,
1515 OMPTraitInfo *ParentTI) {
1516 // Parse 'match'.
1517 OpenMPClauseKind CKind = Tok.isAnnotation()
1518 ? OMPC_unknown
1519 : getOpenMPClauseKind(PP.getSpelling(Tok));
1520 if (CKind != OMPC_match) {
1521 Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
1522 << (getLangOpts().OpenMP < 51 ? 0 : 1);
1523 return true;
1524 }
1525 (void)ConsumeToken();
1526 // Parse '('.
1527 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1528 if (T.expectAndConsume(diag::err_expected_lparen_after,
1529 getOpenMPClauseName(OMPC_match).data()))
1530 return true;
1531
1532 // Parse inner context selectors.
1533 parseOMPContextSelectors(Loc, TI);
1534
1535 // Parse ')'
1536 (void)T.consumeClose();
1537
1538 if (!ParentTI)
1539 return false;
1540
1541 // Merge the parent/outer trait info into the one we just parsed and diagnose
1542 // problems.
1543 // TODO: Keep some source location in the TI to provide better diagnostics.
1544 // TODO: Perform some kind of equivalence check on the condition and score
1545 // expressions.
1546 for (const OMPTraitSet &ParentSet : ParentTI->Sets) {
1547 bool MergedSet = false;
1548 for (OMPTraitSet &Set : TI.Sets) {
1549 if (Set.Kind != ParentSet.Kind)
1550 continue;
1551 MergedSet = true;
1552 for (const OMPTraitSelector &ParentSelector : ParentSet.Selectors) {
1553 bool MergedSelector = false;
1554 for (OMPTraitSelector &Selector : Set.Selectors) {
1555 if (Selector.Kind != ParentSelector.Kind)
1556 continue;
1557 MergedSelector = true;
1558 for (const OMPTraitProperty &ParentProperty :
1559 ParentSelector.Properties) {
1560 bool MergedProperty = false;
1561 for (OMPTraitProperty &Property : Selector.Properties) {
1562 // Ignore "equivalent" properties.
1563 if (Property.Kind != ParentProperty.Kind)
1564 continue;
1565
1566 // If the kind is the same but the raw string not, we don't want
1567 // to skip out on the property.
1568 MergedProperty |= Property.RawString == ParentProperty.RawString;
1569
1570 if (Property.RawString == ParentProperty.RawString &&
1571 Selector.ScoreOrCondition == ParentSelector.ScoreOrCondition)
1572 continue;
1573
1574 if (Selector.Kind == llvm::omp::TraitSelector::user_condition) {
1575 Diag(Loc, diag::err_omp_declare_variant_nested_user_condition);
1576 } else if (Selector.ScoreOrCondition !=
1577 ParentSelector.ScoreOrCondition) {
1578 Diag(Loc, diag::err_omp_declare_variant_duplicate_nested_trait)
1579 << getOpenMPContextTraitPropertyName(
1580 ParentProperty.Kind, ParentProperty.RawString)
1581 << getOpenMPContextTraitSelectorName(ParentSelector.Kind)
1582 << getOpenMPContextTraitSetName(ParentSet.Kind);
1583 }
1584 }
1585 if (!MergedProperty)
1586 Selector.Properties.push_back(ParentProperty);
1587 }
1588 }
1589 if (!MergedSelector)
1590 Set.Selectors.push_back(ParentSelector);
1591 }
1592 }
1593 if (!MergedSet)
1594 TI.Sets.push_back(ParentSet);
1595 }
1596
1597 return false;
1598}
1599
1600void Parser::ParseOpenMPClauses(OpenMPDirectiveKind DKind,
1602 SourceLocation Loc) {
1603 std::bitset<llvm::omp::Clause_enumSize + 1> SeenClauses;
1604 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1605 OpenMPClauseKind CKind = Tok.isAnnotation()
1606 ? OMPC_unknown
1607 : getOpenMPClauseKind(PP.getSpelling(Tok));
1608 if (DKind == OMPD_depobj && CKind == OMPC_update)
1609 CKind = OMPC_update_depend_objects;
1610 Actions.OpenMP().StartOpenMPClause(CKind);
1611 OMPClause *Clause =
1612 ParseOpenMPClause(DKind, CKind, !SeenClauses[unsigned(CKind)]);
1613 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
1615 SeenClauses[unsigned(CKind)] = true;
1616 if (Clause != nullptr)
1617 Clauses.push_back(Clause);
1618 if (Tok.is(tok::annot_pragma_openmp_end)) {
1619 Actions.OpenMP().EndOpenMPClause();
1620 break;
1621 }
1622 // Skip ',' if any.
1623 if (Tok.is(tok::comma))
1624 ConsumeToken();
1625 Actions.OpenMP().EndOpenMPClause();
1626 }
1627}
1628
1629void Parser::ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
1630 SourceLocation Loc) {
1631 SmallVector<std::string, 4> Assumptions;
1632 bool SkippedClauses = false;
1633
1634 auto SkipBraces = [&](llvm::StringRef Spelling, bool IssueNote) {
1635 BalancedDelimiterTracker T(*this, tok::l_paren,
1636 tok::annot_pragma_openmp_end);
1637 if (T.expectAndConsume(diag::err_expected_lparen_after, Spelling.data()))
1638 return;
1639 T.skipToEnd();
1640 if (IssueNote && T.getCloseLocation().isValid())
1641 Diag(T.getCloseLocation(),
1642 diag::note_omp_assumption_clause_continue_here);
1643 };
1644
1645 /// Helper to determine which AssumptionClauseMapping (ACM) in the
1646 /// AssumptionClauseMappings table matches \p RawString. The return value is
1647 /// the index of the matching ACM into the table or -1 if there was no match.
1648 auto MatchACMClause = [&](StringRef RawString) {
1649 llvm::StringSwitch<int> SS(RawString);
1650 unsigned ACMIdx = 0;
1651 for (const AssumptionClauseMappingInfo &ACMI : AssumptionClauseMappings) {
1652 if (ACMI.StartsWith)
1653 SS.StartsWith(ACMI.Identifier, ACMIdx++);
1654 else
1655 SS.Case(ACMI.Identifier, ACMIdx++);
1656 }
1657 return SS.Default(-1);
1658 };
1659
1660 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1661 IdentifierInfo *II = nullptr;
1662 SourceLocation StartLoc = Tok.getLocation();
1663 int Idx = -1;
1664 if (Tok.isAnyIdentifier()) {
1665 II = Tok.getIdentifierInfo();
1666 Idx = MatchACMClause(II->getName());
1667 }
1669
1670 bool NextIsLPar = Tok.is(tok::l_paren);
1671 // Handle unknown clauses by skipping them.
1672 if (Idx == -1) {
1673 llvm::omp::Version OMPVersion = Actions.getLangOpts().getOpenMPVersion();
1674 Diag(StartLoc, diag::warn_omp_unknown_assumption_clause_missing_id)
1675 << llvm::omp::getOpenMPDirectiveName(DKind, OMPVersion)
1676 << llvm::omp::getAllAssumeClauseOptions() << NextIsLPar;
1677 if (NextIsLPar)
1678 SkipBraces(II ? II->getName() : "", /* IssueNote */ true);
1679 SkippedClauses = true;
1680 continue;
1681 }
1682 const AssumptionClauseMappingInfo &ACMI = AssumptionClauseMappings[Idx];
1683 if (ACMI.HasDirectiveList || ACMI.HasExpression) {
1684 // TODO: We ignore absent, contains, and holds assumptions for now. We
1685 // also do not verify the content in the parenthesis at all.
1686 SkippedClauses = true;
1687 SkipBraces(II->getName(), /* IssueNote */ false);
1688 continue;
1689 }
1690
1691 if (NextIsLPar) {
1692 Diag(Tok.getLocation(),
1693 diag::warn_omp_unknown_assumption_clause_without_args)
1694 << II;
1695 SkipBraces(II->getName(), /* IssueNote */ true);
1696 }
1697
1698 assert(II && "Expected an identifier clause!");
1699 std::string Assumption = II->getName().str();
1700 if (ACMI.StartsWith)
1701 Assumption = "ompx_" + Assumption.substr(ACMI.Identifier.size());
1702 else
1703 Assumption = "omp_" + Assumption;
1704 Assumptions.push_back(Assumption);
1705 }
1706
1707 Actions.OpenMP().ActOnOpenMPAssumesDirective(Loc, DKind, Assumptions,
1708 SkippedClauses);
1709}
1710
1711void Parser::ParseOpenMPEndAssumesDirective(SourceLocation Loc) {
1712 if (Actions.OpenMP().isInOpenMPAssumeScope())
1713 Actions.OpenMP().ActOnOpenMPEndAssumesDirective();
1714 else
1715 Diag(Loc, diag::err_expected_begin_assumes);
1716}
1717
1718/// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
1719///
1720/// default-clause:
1721/// 'default' '(' 'none' | 'shared' | 'private' | 'firstprivate' ')
1722///
1723/// proc_bind-clause:
1724/// 'proc_bind' '(' 'master' | 'close' | 'spread' ')
1725///
1726/// device_type-clause:
1727/// 'device_type' '(' 'host' | 'nohost' | 'any' )'
1728namespace {
1729struct SimpleClauseData {
1730 unsigned Type;
1731 SourceLocation Loc;
1732 SourceLocation LOpen;
1733 SourceLocation TypeLoc;
1734 SourceLocation RLoc;
1735 SimpleClauseData(unsigned Type, SourceLocation Loc, SourceLocation LOpen,
1736 SourceLocation TypeLoc, SourceLocation RLoc)
1737 : Type(Type), Loc(Loc), LOpen(LOpen), TypeLoc(TypeLoc), RLoc(RLoc) {}
1738};
1739} // anonymous namespace
1740
1741static std::optional<SimpleClauseData>
1743 const Token &Tok = P.getCurToken();
1744 SourceLocation Loc = Tok.getLocation();
1745 SourceLocation LOpen = P.ConsumeToken();
1746 // Parse '('.
1747 BalancedDelimiterTracker T(P, tok::l_paren, tok::annot_pragma_openmp_end);
1748 if (T.expectAndConsume(diag::err_expected_lparen_after,
1749 getOpenMPClauseName(Kind).data()))
1750 return std::nullopt;
1751
1753 Kind, Tok.isAnnotation() ? "" : P.getPreprocessor().getSpelling(Tok),
1754 P.getLangOpts());
1755 SourceLocation TypeLoc = Tok.getLocation();
1756 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1757 Tok.isNot(tok::annot_pragma_openmp_end))
1758 P.ConsumeAnyToken();
1759
1760 // Parse ')'.
1761 SourceLocation RLoc = Tok.getLocation();
1762 if (!T.consumeClose())
1763 RLoc = T.getCloseLocation();
1764
1765 return SimpleClauseData(Type, Loc, LOpen, TypeLoc, RLoc);
1766}
1767
1768void Parser::ParseOMPDeclareTargetClauses(
1770 SourceLocation DeviceTypeLoc;
1771 bool RequiresToLinkLocalOrIndirectClause = false;
1772 bool HasToLinkLocalOrIndirectClause = false;
1773 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1774 OMPDeclareTargetDeclAttr::MapTypeTy MT = OMPDeclareTargetDeclAttr::MT_To;
1775 bool HasIdentifier = Tok.is(tok::identifier);
1776 if (HasIdentifier) {
1777 // If we see any clause we need a to, link, or local clause.
1778 RequiresToLinkLocalOrIndirectClause = true;
1779 IdentifierInfo *II = Tok.getIdentifierInfo();
1780 StringRef ClauseName = II->getName();
1781 bool IsDeviceTypeClause =
1782 getLangOpts().OpenMP >= 50 &&
1783 getOpenMPClauseKind(ClauseName) == OMPC_device_type;
1784
1785 bool IsIndirectClause = getLangOpts().OpenMP >= 51 &&
1786 getOpenMPClauseKind(ClauseName) == OMPC_indirect;
1787
1788 if (DTCI.Indirect && IsIndirectClause) {
1789 llvm::omp::Version OMPVersion =
1790 Actions.getLangOpts().getOpenMPVersion();
1791 Diag(Tok, diag::err_omp_more_one_clause)
1792 << getOpenMPDirectiveName(OMPD_declare_target, OMPVersion)
1793 << getOpenMPClauseName(OMPC_indirect) << 0;
1794 break;
1795 }
1796 bool IsToEnterLinkOrLocalClause =
1797 OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName, MT);
1798 assert((!IsDeviceTypeClause || !IsToEnterLinkOrLocalClause) &&
1799 "Cannot be both!");
1800
1801 // Starting with OpenMP 5.2 the `to` clause has been replaced by the
1802 // `enter` clause.
1803 if (getLangOpts().OpenMP >= 52 && ClauseName == "to") {
1804 Diag(Tok, diag::err_omp_declare_target_unexpected_to_clause);
1805 break;
1806 }
1807 if (getLangOpts().OpenMP <= 51 && ClauseName == "enter") {
1808 Diag(Tok, diag::err_omp_declare_target_unexpected_enter_clause);
1809 break;
1810 }
1811
1812 // The 'local' clause is only available in OpenMP 6.0.
1813 if (getLangOpts().OpenMP < 60 && ClauseName == "local") {
1814 Diag(Tok, getLangOpts().OpenMP >= 52
1815 ? diag::err_omp_declare_target_unexpected_clause_52
1816 : diag::err_omp_declare_target_unexpected_clause)
1817 << ClauseName
1818 << (getLangOpts().OpenMP >= 51 ? 4
1819 : getLangOpts().OpenMP >= 50 ? 2
1820 : 1);
1821 break;
1822 }
1823
1824 if (!IsDeviceTypeClause && !IsIndirectClause &&
1825 DTCI.Kind == OMPD_begin_declare_target) {
1826 Diag(Tok, getLangOpts().OpenMP >= 52
1827 ? diag::err_omp_declare_target_unexpected_clause_52
1828 : diag::err_omp_declare_target_unexpected_clause)
1829 << ClauseName << (getLangOpts().OpenMP >= 51 ? 3 : 0);
1830 break;
1831 }
1832
1833 if (!IsDeviceTypeClause && !IsToEnterLinkOrLocalClause &&
1834 !IsIndirectClause) {
1835 Diag(Tok, getLangOpts().OpenMP >= 52
1836 ? diag::err_omp_declare_target_unexpected_clause_52
1837 : diag::err_omp_declare_target_unexpected_clause)
1838 << ClauseName
1839 << (getLangOpts().OpenMP > 52 ? 5
1840 : getLangOpts().OpenMP >= 51 ? 4
1841 : getLangOpts().OpenMP >= 50 ? 2
1842 : 1);
1843 break;
1844 }
1845
1846 if (IsToEnterLinkOrLocalClause || IsIndirectClause)
1847 HasToLinkLocalOrIndirectClause = true;
1848
1849 if (IsIndirectClause) {
1850 if (!ParseOpenMPIndirectClause(DTCI, /*ParseOnly*/ false))
1851 break;
1852 continue;
1853 }
1854 // Parse 'device_type' clause and go to next clause if any.
1855 if (IsDeviceTypeClause) {
1856 std::optional<SimpleClauseData> DevTypeData =
1857 parseOpenMPSimpleClause(*this, OMPC_device_type);
1858 if (DevTypeData) {
1859 if (DeviceTypeLoc.isValid()) {
1860 // We already saw another device_type clause, diagnose it.
1861 Diag(DevTypeData->Loc,
1862 diag::warn_omp_more_one_device_type_clause);
1863 break;
1864 }
1865 switch (static_cast<OpenMPDeviceType>(DevTypeData->Type)) {
1866 case OMPC_DEVICE_TYPE_any:
1867 DTCI.DT = OMPDeclareTargetDeclAttr::DT_Any;
1868 break;
1869 case OMPC_DEVICE_TYPE_host:
1870 DTCI.DT = OMPDeclareTargetDeclAttr::DT_Host;
1871 break;
1872 case OMPC_DEVICE_TYPE_nohost:
1873 DTCI.DT = OMPDeclareTargetDeclAttr::DT_NoHost;
1874 break;
1876 llvm_unreachable("Unexpected device_type");
1877 }
1878 DeviceTypeLoc = DevTypeData->Loc;
1879 }
1880 continue;
1881 }
1882 ConsumeToken();
1883 }
1884
1885 if (DTCI.Kind == OMPD_declare_target || HasIdentifier) {
1886 auto &&Callback = [this, MT, &DTCI](CXXScopeSpec &SS,
1887 DeclarationNameInfo NameInfo) {
1888 NamedDecl *ND = Actions.OpenMP().lookupOpenMPDeclareTargetName(
1889 getCurScope(), SS, NameInfo);
1890 if (!ND)
1891 return;
1892 SemaOpenMP::DeclareTargetContextInfo::MapInfo MI{MT, NameInfo.getLoc()};
1893 bool FirstMapping = DTCI.ExplicitlyMapped.try_emplace(ND, MI).second;
1894 if (!FirstMapping)
1895 Diag(NameInfo.getLoc(), diag::err_omp_declare_target_multiple)
1896 << NameInfo.getName();
1897 };
1898 if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback,
1899 /*AllowScopeSpecifier=*/true))
1900 break;
1901 }
1902
1903 if (Tok.is(tok::l_paren)) {
1904 Diag(Tok,
1905 diag::err_omp_begin_declare_target_unexpected_implicit_to_clause);
1906 break;
1907 }
1908 if (!HasIdentifier && Tok.isNot(tok::annot_pragma_openmp_end)) {
1909 Diag(Tok,
1910 getLangOpts().OpenMP >= 52
1911 ? diag::err_omp_declare_target_wrong_clause_after_implicit_enter
1912 : diag::err_omp_declare_target_wrong_clause_after_implicit_to);
1913 break;
1914 }
1915
1916 // Consume optional ','.
1917 if (Tok.is(tok::comma))
1918 ConsumeToken();
1919 }
1920
1921 if (DTCI.Indirect && DTCI.DT != OMPDeclareTargetDeclAttr::DT_Any)
1922 Diag(DeviceTypeLoc, diag::err_omp_declare_target_indirect_device_type);
1923
1924 // declare target requires at least one clause.
1925 if (DTCI.Kind == OMPD_declare_target && RequiresToLinkLocalOrIndirectClause &&
1926 !HasToLinkLocalOrIndirectClause)
1927 Diag(DTCI.Loc, diag::err_omp_declare_target_missing_required_clause)
1928 << (getLangOpts().OpenMP >= 60 ? 3
1929 : getLangOpts().OpenMP == 52 ? 2
1930 : getLangOpts().OpenMP == 51 ? 1
1931 : 0);
1932
1933 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1934}
1935
1936void Parser::skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind) {
1937 // The last seen token is annot_pragma_openmp_end - need to check for
1938 // extra tokens.
1939 if (Tok.is(tok::annot_pragma_openmp_end))
1940 return;
1941
1942 llvm::omp::Version OMPVersion = Actions.getLangOpts().getOpenMPVersion();
1943 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
1944 << getOpenMPDirectiveName(DKind, OMPVersion);
1945 while (Tok.isNot(tok::annot_pragma_openmp_end))
1947}
1948
1949void Parser::parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
1950 OpenMPDirectiveKind ExpectedKind,
1951 OpenMPDirectiveKind FoundKind,
1952 SourceLocation BeginLoc,
1953 SourceLocation FoundLoc,
1954 bool SkipUntilOpenMPEnd) {
1955 int DiagSelection = ExpectedKind == OMPD_end_declare_target ? 0 : 1;
1956
1957 if (FoundKind == ExpectedKind) {
1959 skipUntilPragmaOpenMPEnd(ExpectedKind);
1960 return;
1961 }
1962
1963 llvm::omp::Version OMPVersion = Actions.getLangOpts().getOpenMPVersion();
1964 Diag(FoundLoc, diag::err_expected_end_declare_target_or_variant)
1965 << DiagSelection;
1966 Diag(BeginLoc, diag::note_matching)
1967 << ("'#pragma omp " + getOpenMPDirectiveName(BeginKind, OMPVersion) + "'")
1968 .str();
1969 if (SkipUntilOpenMPEnd)
1970 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1971}
1972
1973void Parser::ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind,
1974 OpenMPDirectiveKind EndDKind,
1975 SourceLocation DKLoc) {
1976 parseOMPEndDirective(BeginDKind, OMPD_end_declare_target, EndDKind, DKLoc,
1977 Tok.getLocation(),
1978 /* SkipUntilOpenMPEnd */ false);
1979 // Skip the last annot_pragma_openmp_end.
1980 if (Tok.is(tok::annot_pragma_openmp_end))
1981 ConsumeAnnotationToken();
1982}
1983
1984Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
1985 AccessSpecifier &AS, ParsedAttributes &Attrs, bool Delayed,
1986 DeclSpec::TST TagType, Decl *Tag) {
1987 assert(Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) &&
1988 "Not an OpenMP directive!");
1989 ParsingOpenMPDirectiveRAII DirScope(*this);
1990 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1991 llvm::omp::Version OMPVersion = Actions.getLangOpts().getOpenMPVersion();
1992
1993 SourceLocation Loc;
1994 OpenMPDirectiveKind DKind;
1995 if (Delayed) {
1996 TentativeParsingAction TPA(*this);
1997 Loc = ConsumeAnnotationToken();
1998 DKind = parseOpenMPDirectiveKind(*this);
1999 if (DKind == OMPD_declare_reduction || DKind == OMPD_declare_mapper) {
2000 // Need to delay parsing until completion of the parent class.
2001 TPA.Revert();
2002 CachedTokens Toks;
2003 unsigned Cnt = 1;
2004 Toks.push_back(Tok);
2005 while (Cnt && Tok.isNot(tok::eof)) {
2006 (void)ConsumeAnyToken();
2007 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp))
2008 ++Cnt;
2009 else if (Tok.is(tok::annot_pragma_openmp_end))
2010 --Cnt;
2011 Toks.push_back(Tok);
2012 }
2013 // Skip last annot_pragma_openmp_end.
2014 if (Cnt == 0)
2015 (void)ConsumeAnyToken();
2016 auto *LP = new LateParsedPragma(this, AS);
2017 LP->takeToks(Toks);
2018 getCurrentClass().LateParsedDeclarations.push_back(LP);
2019 return nullptr;
2020 }
2021 TPA.Commit();
2022 } else {
2023 Loc = ConsumeAnnotationToken();
2024 DKind = parseOpenMPDirectiveKind(*this);
2025 }
2026
2027 switch (DKind) {
2028 case OMPD_threadprivate: {
2029 ConsumeToken();
2030 DeclDirectiveListParserHelper Helper(this, DKind);
2031 if (!ParseOpenMPSimpleVarList(DKind, Helper,
2032 /*AllowScopeSpecifier=*/true)) {
2033 skipUntilPragmaOpenMPEnd(DKind);
2034 // Skip the last annot_pragma_openmp_end.
2035 ConsumeAnnotationToken();
2036 return Actions.OpenMP().ActOnOpenMPThreadprivateDirective(
2037 Loc, Helper.getIdentifiers());
2038 }
2039 break;
2040 }
2041 case OMPD_groupprivate: {
2042 ConsumeToken();
2043 DeclDirectiveListParserHelper Helper(this, DKind);
2044 if (!ParseOpenMPSimpleVarList(DKind, Helper,
2045 /*AllowScopeSpecifier=*/true)) {
2046 skipUntilPragmaOpenMPEnd(DKind);
2047 // Skip the last annot_pragma_openmp_end.
2048 ConsumeAnnotationToken();
2049 return Actions.OpenMP().ActOnOpenMPGroupPrivateDirective(
2050 Loc, Helper.getIdentifiers());
2051 }
2052 break;
2053 }
2054 case OMPD_allocate: {
2055 ConsumeToken();
2056 DeclDirectiveListParserHelper Helper(this, DKind);
2057 if (!ParseOpenMPSimpleVarList(DKind, Helper,
2058 /*AllowScopeSpecifier=*/true)) {
2059 SmallVector<OMPClause *, 1> Clauses;
2060 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
2061 std::bitset<llvm::omp::Clause_enumSize + 1> SeenClauses;
2062 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2063 OpenMPClauseKind CKind =
2064 Tok.isAnnotation() ? OMPC_unknown
2065 : getOpenMPClauseKind(PP.getSpelling(Tok));
2066 Actions.OpenMP().StartOpenMPClause(CKind);
2067 OMPClause *Clause = ParseOpenMPClause(OMPD_allocate, CKind,
2068 !SeenClauses[unsigned(CKind)]);
2069 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
2071 SeenClauses[unsigned(CKind)] = true;
2072 if (Clause != nullptr)
2073 Clauses.push_back(Clause);
2074 if (Tok.is(tok::annot_pragma_openmp_end)) {
2075 Actions.OpenMP().EndOpenMPClause();
2076 break;
2077 }
2078 // Skip ',' if any.
2079 if (Tok.is(tok::comma))
2080 ConsumeToken();
2081 Actions.OpenMP().EndOpenMPClause();
2082 }
2083 skipUntilPragmaOpenMPEnd(DKind);
2084 }
2085 // Skip the last annot_pragma_openmp_end.
2086 ConsumeAnnotationToken();
2087 return Actions.OpenMP().ActOnOpenMPAllocateDirective(
2088 Loc, Helper.getIdentifiers(), Clauses);
2089 }
2090 break;
2091 }
2092 case OMPD_requires: {
2093 SourceLocation StartLoc = ConsumeToken();
2094 SmallVector<OMPClause *, 5> Clauses;
2095 llvm::SmallBitVector SeenClauses(llvm::omp::Clause_enumSize + 1);
2096 if (Tok.is(tok::annot_pragma_openmp_end)) {
2097 Diag(Tok, diag::err_omp_expected_clause)
2098 << getOpenMPDirectiveName(OMPD_requires, OMPVersion);
2099 break;
2100 }
2101 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2102 OpenMPClauseKind CKind = Tok.isAnnotation()
2103 ? OMPC_unknown
2104 : getOpenMPClauseKind(PP.getSpelling(Tok));
2105 Actions.OpenMP().StartOpenMPClause(CKind);
2106 OMPClause *Clause = ParseOpenMPClause(OMPD_requires, CKind,
2107 !SeenClauses[unsigned(CKind)]);
2108 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
2110 SeenClauses[unsigned(CKind)] = true;
2111 if (Clause != nullptr)
2112 Clauses.push_back(Clause);
2113 if (Tok.is(tok::annot_pragma_openmp_end)) {
2114 Actions.OpenMP().EndOpenMPClause();
2115 break;
2116 }
2117 // Skip ',' if any.
2118 if (Tok.is(tok::comma))
2119 ConsumeToken();
2120 Actions.OpenMP().EndOpenMPClause();
2121 }
2122 // Consume final annot_pragma_openmp_end
2123 if (Clauses.empty()) {
2124 Diag(Tok, diag::err_omp_expected_clause)
2125 << getOpenMPDirectiveName(OMPD_requires, OMPVersion);
2126 ConsumeAnnotationToken();
2127 return nullptr;
2128 }
2129 ConsumeAnnotationToken();
2130 return Actions.OpenMP().ActOnOpenMPRequiresDirective(StartLoc, Clauses);
2131 }
2132 case OMPD_error: {
2133 SmallVector<OMPClause *, 1> Clauses;
2134 SourceLocation StartLoc = ConsumeToken();
2135 ParseOpenMPClauses(DKind, Clauses, StartLoc);
2136 Actions.OpenMP().ActOnOpenMPErrorDirective(Clauses, StartLoc,
2137 SourceLocation(),
2138 /*InExContext = */ false);
2139 break;
2140 }
2141 case OMPD_assumes:
2142 case OMPD_begin_assumes:
2143 ParseOpenMPAssumesDirective(DKind, ConsumeToken());
2144 break;
2145 case OMPD_end_assumes:
2146 ParseOpenMPEndAssumesDirective(ConsumeToken());
2147 break;
2148 case OMPD_declare_reduction:
2149 ConsumeToken();
2150 if (DeclGroupPtrTy Res = ParseOpenMPDeclareReductionDirective(AS)) {
2151 skipUntilPragmaOpenMPEnd(OMPD_declare_reduction);
2152 // Skip the last annot_pragma_openmp_end.
2153 ConsumeAnnotationToken();
2154 return Res;
2155 }
2156 break;
2157 case OMPD_declare_mapper: {
2158 ConsumeToken();
2159 if (DeclGroupPtrTy Res = ParseOpenMPDeclareMapperDirective(AS)) {
2160 // Skip the last annot_pragma_openmp_end.
2161 ConsumeAnnotationToken();
2162 return Res;
2163 }
2164 break;
2165 }
2166 case OMPD_begin_declare_variant: {
2167 ConsumeToken();
2169 // Skip the last annot_pragma_openmp_end.
2170 if (!isEofOrEom())
2171 ConsumeAnnotationToken();
2172 }
2173 return nullptr;
2174 }
2175 case OMPD_end_declare_variant: {
2176 ConsumeToken();
2177 if (Actions.OpenMP().isInOpenMPDeclareVariantScope())
2178 Actions.OpenMP().ActOnOpenMPEndDeclareVariant();
2179 else
2180 Diag(Loc, diag::err_expected_begin_declare_variant);
2181 // Skip the last annot_pragma_openmp_end.
2182 ConsumeAnnotationToken();
2183 return nullptr;
2184 }
2185 case OMPD_declare_variant:
2186 case OMPD_declare_simd: {
2187 // The syntax is:
2188 // { #pragma omp declare {simd|variant} }
2189 // <function-declaration-or-definition>
2190 //
2191 CachedTokens Toks;
2192 Toks.push_back(Tok);
2193 ConsumeToken();
2194 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2195 Toks.push_back(Tok);
2197 }
2198 Toks.push_back(Tok);
2200
2202 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
2203 Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, Delayed,
2204 TagType, Tag);
2205 } else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2206 // Here we expect to see some function declaration.
2207 if (AS == AS_none) {
2208 assert(TagType == DeclSpec::TST_unspecified);
2209 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2210 MaybeParseCXX11Attributes(Attrs);
2211 ParsingDeclSpec PDS(*this);
2212 Ptr = ParseExternalDeclaration(Attrs, EmptyDeclSpecAttrs, &PDS);
2213 } else {
2214 Ptr =
2215 ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag);
2216 }
2217 }
2218 if (!Ptr) {
2219 Diag(Loc, diag::err_omp_decl_in_declare_simd_variant)
2220 << (DKind == OMPD_declare_simd ? 0 : 1);
2221 return DeclGroupPtrTy();
2222 }
2223
2224 DeclGroupRef DG = Ptr.get();
2225 SourceManager &SM = PP.getSourceManager();
2226 if (llvm::none_of(DG, [&](const Decl *D) {
2227 return SM.isBeforeInTranslationUnit(Loc, D->getBeginLoc());
2228 })) {
2229 Diag(Loc, diag::err_omp_decl_in_declare_simd_variant)
2230 << (DKind == OMPD_declare_simd ? 0 : 1);
2231 return DeclGroupPtrTy();
2232 }
2233
2234 if (DKind == OMPD_declare_simd)
2235 return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc);
2236 assert(DKind == OMPD_declare_variant &&
2237 "Expected declare variant directive only");
2238 ParseOMPDeclareVariantClauses(Ptr, Toks, Loc);
2239 return Ptr;
2240 }
2241 case OMPD_begin_declare_target:
2242 case OMPD_declare_target: {
2243 SourceLocation DTLoc = ConsumeAnyToken();
2244 bool HasClauses = Tok.isNot(tok::annot_pragma_openmp_end);
2245 SemaOpenMP::DeclareTargetContextInfo DTCI(DKind, DTLoc);
2246 if (DKind == OMPD_declare_target && !HasClauses &&
2247 getLangOpts().OpenMP >= 52)
2248 Diag(DTLoc, diag::warn_omp_deprecated_declare_target_delimited_form);
2249 if (HasClauses)
2250 ParseOMPDeclareTargetClauses(DTCI);
2251 bool HasImplicitMappings = DKind == OMPD_begin_declare_target ||
2252 !HasClauses ||
2253 (DTCI.ExplicitlyMapped.empty() && DTCI.Indirect);
2254
2255 // Skip the last annot_pragma_openmp_end.
2257
2258 if (HasImplicitMappings) {
2259 Actions.OpenMP().ActOnStartOpenMPDeclareTargetContext(DTCI);
2260 return nullptr;
2261 }
2262
2263 Actions.OpenMP().ActOnFinishedOpenMPDeclareTargetContext(DTCI);
2264 llvm::SmallVector<Decl *, 4> Decls;
2265 for (auto &It : DTCI.ExplicitlyMapped)
2266 Decls.push_back(It.first);
2267 return Actions.BuildDeclaratorGroup(Decls);
2268 }
2269 case OMPD_end_declare_target: {
2270 if (!Actions.OpenMP().isInOpenMPDeclareTargetContext()) {
2271 Diag(Tok, diag::err_omp_unexpected_directive)
2272 << 1 << getOpenMPDirectiveName(DKind, OMPVersion);
2273 break;
2274 }
2275 const SemaOpenMP::DeclareTargetContextInfo &DTCI =
2276 Actions.OpenMP().ActOnOpenMPEndDeclareTargetDirective();
2277 ParseOMPEndDeclareTargetDirective(DTCI.Kind, DKind, DTCI.Loc);
2278 return nullptr;
2279 }
2280 case OMPD_assume: {
2281 Diag(Tok, diag::err_omp_unexpected_directive)
2282 << 1 << getOpenMPDirectiveName(DKind, OMPVersion);
2283 break;
2284 }
2285 case OMPD_unknown:
2286 Diag(Tok, diag::err_omp_unknown_directive);
2287 break;
2288 default:
2289 switch (getDirectiveCategory(DKind)) {
2290 case Category::Executable:
2291 case Category::Meta:
2292 case Category::Subsidiary:
2293 case Category::Utility:
2294 Diag(Tok, diag::err_omp_unexpected_directive)
2295 << 1 << getOpenMPDirectiveName(DKind, OMPVersion);
2296 break;
2297 case Category::Declarative:
2298 case Category::Informational:
2299 break;
2300 }
2301 }
2302 while (Tok.isNot(tok::annot_pragma_openmp_end))
2305 return nullptr;
2306}
2307
2308StmtResult Parser::ParseOpenMPExecutableDirective(
2309 ParsedStmtContext StmtCtx, OpenMPDirectiveKind DKind, SourceLocation Loc,
2310 bool ReadDirectiveWithinMetadirective) {
2311 assert(isOpenMPExecutableDirective(DKind) && "Unexpected directive category");
2312 llvm::omp::Version OMPVersion = Actions.getLangOpts().getOpenMPVersion();
2313
2314 bool HasAssociatedStatement = true;
2315 Association Assoc = getDirectiveAssociation(DKind);
2316
2317 // OMPD_scan and OMPD_section are both "separating", but section is treated
2318 // as if it was associated with a statement, while scan is not.
2319 if (DKind != OMPD_ordered_standalone && DKind != OMPD_section &&
2320 (Assoc == Association::None || Assoc == Association::Separating)) {
2321 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2322 ParsedStmtContext()) {
2323 Diag(Tok, diag::err_omp_immediate_directive)
2324 << getOpenMPDirectiveName(DKind, OMPVersion) << 0;
2325 if (DKind == OMPD_error) {
2326 SkipUntil(tok::annot_pragma_openmp_end);
2327 return StmtError();
2328 }
2329 }
2330 HasAssociatedStatement = false;
2331 }
2332
2333 SourceLocation EndLoc;
2334 SmallVector<OMPClause *, 5> Clauses;
2335 llvm::SmallBitVector SeenClauses(llvm::omp::Clause_enumSize + 1);
2336 DeclarationNameInfo DirName;
2337 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
2338 unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
2340
2341 // Special processing for flush and depobj clauses.
2342 Token ImplicitTok;
2343 bool ImplicitClauseAllowed = false;
2344 if (DKind == OMPD_flush || DKind == OMPD_depobj) {
2345 ImplicitTok = Tok;
2346 ImplicitClauseAllowed = true;
2347 }
2348 ConsumeToken();
2349 // Parse directive name of the 'critical' directive if any.
2350 if (DKind == OMPD_critical) {
2351 BalancedDelimiterTracker T(*this, tok::l_paren,
2352 tok::annot_pragma_openmp_end);
2353 if (!T.consumeOpen()) {
2354 if (Tok.isAnyIdentifier()) {
2355 DirName =
2356 DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation());
2358 } else {
2359 Diag(Tok, diag::err_omp_expected_identifier_for_critical);
2360 }
2361 T.consumeClose();
2362 }
2363 } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) {
2364 CancelRegion = parseOpenMPDirectiveKind(*this);
2365 if (Tok.isNot(tok::annot_pragma_openmp_end))
2367 }
2368
2369 if (isOpenMPLoopDirective(DKind))
2370 ScopeFlags |= Scope::OpenMPLoopDirectiveScope;
2371 if (isOpenMPSimdDirective(DKind))
2372 ScopeFlags |= Scope::OpenMPSimdDirectiveScope;
2373 ParseScope OMPDirectiveScope(this, ScopeFlags);
2374 Actions.OpenMP().StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(),
2375 Loc);
2376
2377 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2378 // If we are parsing for a directive within a metadirective, the directive
2379 // ends with a ')'.
2380 if (ReadDirectiveWithinMetadirective && Tok.is(tok::r_paren)) {
2381 while (Tok.isNot(tok::annot_pragma_openmp_end))
2383 break;
2384 }
2385 bool HasImplicitClause = false;
2386 if (ImplicitClauseAllowed && Tok.is(tok::l_paren)) {
2387 HasImplicitClause = true;
2388 // Push copy of the current token back to stream to properly parse
2389 // pseudo-clause OMPFlushClause or OMPDepobjClause.
2390 PP.EnterToken(Tok, /*IsReinject*/ true);
2391 PP.EnterToken(ImplicitTok, /*IsReinject*/ true);
2393 }
2394 OpenMPClauseKind CKind = Tok.isAnnotation()
2395 ? OMPC_unknown
2396 : getOpenMPClauseKind(PP.getSpelling(Tok));
2397 if (DKind == OMPD_depobj && CKind == OMPC_update)
2398 CKind = OMPC_update_depend_objects;
2399
2400 if (HasImplicitClause) {
2401 assert(CKind == OMPC_unknown && "Must be unknown implicit clause.");
2402 if (DKind == OMPD_flush) {
2403 CKind = OMPC_flush;
2404 } else {
2405 assert(DKind == OMPD_depobj && "Expected flush or depobj directives.");
2406 CKind = OMPC_depobj;
2407 }
2408 }
2409 // No more implicit clauses allowed.
2410 ImplicitClauseAllowed = false;
2411 Actions.OpenMP().StartOpenMPClause(CKind);
2412 HasImplicitClause = false;
2413 SourceLocation ClauseLoc = Tok.getLocation();
2414
2415 OMPClause *Clause =
2416 ParseOpenMPClause(DKind, CKind, !SeenClauses[unsigned(CKind)]);
2417 SeenClauses[unsigned(CKind)] = true;
2418 if (Clause)
2419 Clauses.push_back(Clause);
2420
2421 // Skip ',' if any.
2422 if (Tok.is(tok::comma))
2423 ConsumeToken();
2424 Actions.OpenMP().EndOpenMPClause();
2425
2426 // If ParseOpenMPClause returned without consuming any tokens, skip
2427 // to end to avoid an infinite loop.
2428 if (Tok.getLocation() == ClauseLoc) {
2429 skipUntilPragmaOpenMPEnd(DKind);
2430 break;
2431 }
2432 }
2433 // End location of the directive.
2434 EndLoc = Tok.getLocation();
2435 // Consume final annot_pragma_openmp_end.
2436 ConsumeAnnotationToken();
2437
2438 assert(DKind != OMPD_ordered_blockassoc &&
2439 "Wrong kind for ordered directive");
2440 if (DKind == OMPD_ordered_standalone) {
2441 // If the depend or doacross clause is specified, the ordered construct
2442 // is a stand-alone directive.
2443 for (auto CK : {OMPC_depend, OMPC_doacross}) {
2444 if (SeenClauses[unsigned(CK)]) {
2445 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2446 ParsedStmtContext()) {
2447 Diag(Loc, diag::err_omp_immediate_directive)
2448 << getOpenMPDirectiveName(DKind, OMPVersion) << 1
2449 << getOpenMPClauseName(CK);
2450 }
2451 HasAssociatedStatement = false;
2452 }
2453 }
2454
2455 if (HasAssociatedStatement)
2456 DKind = OMPD_ordered_blockassoc;
2457 }
2458
2459 if ((DKind == OMPD_tile || DKind == OMPD_stripe) &&
2460 !SeenClauses[unsigned(OMPC_sizes)]) {
2461 Diag(Loc, diag::err_omp_required_clause)
2462 << getOpenMPDirectiveName(DKind, OMPVersion) << "sizes";
2463 }
2464 if (DKind == OMPD_split && !SeenClauses[unsigned(OMPC_counts)]) {
2465 Diag(Loc, diag::err_omp_required_clause)
2466 << getOpenMPDirectiveName(DKind, OMPVersion) << "counts";
2467 }
2468
2469 StmtResult AssociatedStmt;
2470 if (HasAssociatedStatement) {
2471 // The body is a block scope like in Lambdas and Blocks.
2472 Actions.OpenMP().ActOnOpenMPRegionStart(DKind, getCurScope());
2473 // FIXME: We create a bogus CompoundStmt scope to hold the contents of
2474 // the captured region. Code elsewhere assumes that any FunctionScopeInfo
2475 // should have at least one compound statement scope within it.
2476 ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
2477 {
2478 Sema::CompoundScopeRAII Scope(Actions);
2479 AssociatedStmt = ParseStatement();
2480
2481 if (AssociatedStmt.isUsable() && isOpenMPLoopDirective(DKind) &&
2482 getLangOpts().OpenMPIRBuilder)
2483 AssociatedStmt =
2484 Actions.OpenMP().ActOnOpenMPLoopnest(AssociatedStmt.get());
2485 }
2486 AssociatedStmt =
2487 Actions.OpenMP().ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
2488 } else if (DKind == OMPD_target_update || DKind == OMPD_target_enter_data ||
2489 DKind == OMPD_target_exit_data) {
2490 Actions.OpenMP().ActOnOpenMPRegionStart(DKind, getCurScope());
2491 AssociatedStmt = (Sema::CompoundScopeRAII(Actions),
2492 Actions.ActOnCompoundStmt(Loc, Loc, {},
2493 /*isStmtExpr=*/false));
2494 AssociatedStmt =
2495 Actions.OpenMP().ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
2496 }
2497
2498 StmtResult Directive = Actions.OpenMP().ActOnOpenMPExecutableDirective(
2499 DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc, EndLoc);
2500
2501 // Exit scope.
2502 Actions.OpenMP().EndOpenMPDSABlock(Directive.get());
2503 OMPDirectiveScope.Exit();
2504
2505 return Directive;
2506}
2507
2508StmtResult Parser::ParseOpenMPInformationalDirective(
2509 ParsedStmtContext StmtCtx, OpenMPDirectiveKind DKind, SourceLocation Loc,
2510 bool ReadDirectiveWithinMetadirective) {
2511 assert(isOpenMPInformationalDirective(DKind) &&
2512 "Unexpected directive category");
2513
2514 bool HasAssociatedStatement = true;
2515
2516 SmallVector<OMPClause *, 5> Clauses;
2517 llvm::SmallBitVector SeenClauses(llvm::omp::Clause_enumSize + 1);
2518 DeclarationNameInfo DirName;
2519 unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
2521 ParseScope OMPDirectiveScope(this, ScopeFlags);
2522
2523 Actions.OpenMP().StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(),
2524 Loc);
2525
2526 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2527 if (ReadDirectiveWithinMetadirective && Tok.is(tok::r_paren)) {
2528 while (Tok.isNot(tok::annot_pragma_openmp_end))
2530 break;
2531 }
2532
2533 OpenMPClauseKind CKind = Tok.isAnnotation()
2534 ? OMPC_unknown
2535 : getOpenMPClauseKind(PP.getSpelling(Tok));
2536 Actions.OpenMP().StartOpenMPClause(CKind);
2537 OMPClause *Clause =
2538 ParseOpenMPClause(DKind, CKind, !SeenClauses[unsigned(CKind)]);
2539 SeenClauses[unsigned(CKind)] = true;
2540 if (Clause)
2541 Clauses.push_back(Clause);
2542
2543 if (Tok.is(tok::comma))
2544 ConsumeToken();
2545 Actions.OpenMP().EndOpenMPClause();
2546 }
2547
2548 SourceLocation EndLoc = Tok.getLocation();
2549 ConsumeAnnotationToken();
2550
2551 StmtResult AssociatedStmt;
2552 if (HasAssociatedStatement) {
2553 Actions.OpenMP().ActOnOpenMPRegionStart(DKind, getCurScope());
2554 ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
2555 {
2556 Sema::CompoundScopeRAII Scope(Actions);
2557 AssociatedStmt = ParseStatement();
2558 }
2559 AssociatedStmt =
2560 Actions.OpenMP().ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
2561 }
2562
2563 StmtResult Directive = Actions.OpenMP().ActOnOpenMPInformationalDirective(
2564 DKind, DirName, Clauses, AssociatedStmt.get(), Loc, EndLoc);
2565
2566 Actions.OpenMP().EndOpenMPDSABlock(Directive.get());
2567 OMPDirectiveScope.Exit();
2568
2569 return Directive;
2570}
2571
2572StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
2573 ParsedStmtContext StmtCtx, bool ReadDirectiveWithinMetadirective) {
2574 if (!ReadDirectiveWithinMetadirective)
2575 assert(Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) &&
2576 "Not an OpenMP directive!");
2577 ParsingOpenMPDirectiveRAII DirScope(*this);
2578 ParenBraceBracketBalancer BalancerRAIIObj(*this);
2579 SourceLocation Loc = ReadDirectiveWithinMetadirective
2580 ? Tok.getLocation()
2581 : ConsumeAnnotationToken();
2582 llvm::omp::Version OMPVersion = Actions.getLangOpts().getOpenMPVersion();
2584 if (ReadDirectiveWithinMetadirective && DKind == OMPD_unknown) {
2585 Diag(Tok, diag::err_omp_unknown_directive);
2586 return StmtError();
2587 }
2588
2590
2591 bool IsExecutable = [&]() {
2592 if (DKind == OMPD_error) // OMPD_error is handled as executable
2593 return true;
2594 auto Res = getDirectiveCategory(DKind);
2595 return Res == Category::Executable || Res == Category::Subsidiary;
2596 }();
2597
2598 if (IsExecutable) {
2599 Directive = ParseOpenMPExecutableDirective(
2600 StmtCtx, DKind, Loc, ReadDirectiveWithinMetadirective);
2601 assert(!Directive.isUnset() && "Executable directive remained unprocessed");
2602 return Directive;
2603 }
2604
2605 switch (DKind) {
2606 case OMPD_nothing:
2607 ConsumeToken();
2608 // If we are parsing the directive within a metadirective, the directive
2609 // ends with a ')'.
2610 if (ReadDirectiveWithinMetadirective && Tok.is(tok::r_paren))
2611 while (Tok.isNot(tok::annot_pragma_openmp_end))
2613 else
2614 skipUntilPragmaOpenMPEnd(DKind);
2615 if (Tok.is(tok::annot_pragma_openmp_end))
2616 ConsumeAnnotationToken();
2617 // return an empty statement
2618 return StmtEmpty();
2619 case OMPD_metadirective: {
2620 ConsumeToken();
2621 SmallVector<VariantMatchInfo, 4> VMIs;
2622 SmallVector<OMPTraitInfo *, 4> TraitInfos;
2623
2624 // First iteration of parsing all clauses of metadirective.
2625 // This iteration only parses and collects all context selectors ignoring
2626 // the associated directives.
2627 TentativeParsingAction TPA(*this);
2628 ASTContext &ASTContext = Actions.getASTContext();
2629
2630 BalancedDelimiterTracker T(*this, tok::l_paren,
2631 tok::annot_pragma_openmp_end);
2632 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2633 OpenMPClauseKind CKind = Tok.isAnnotation()
2634 ? OMPC_unknown
2635 : getOpenMPClauseKind(PP.getSpelling(Tok));
2636 // Check if the clause is unrecognized.
2637 if (CKind == OMPC_unknown) {
2638 Diag(Tok, diag::err_omp_expected_clause) << "metadirective";
2639 TPA.Revert();
2640 SkipUntil(tok::annot_pragma_openmp_end);
2641 return Directive;
2642 }
2643 if (getLangOpts().OpenMP < 52 && CKind == OMPC_otherwise)
2644 Diag(Tok, diag::err_omp_unexpected_clause)
2645 << getOpenMPClauseName(CKind) << "metadirective";
2646 if (CKind == OMPC_default && getLangOpts().OpenMP >= 52)
2647 Diag(Tok, diag::warn_omp_default_deprecated);
2648
2649 SourceLocation Loc = ConsumeToken();
2650
2651 // Parse '('.
2652 if (T.expectAndConsume(diag::err_expected_lparen_after,
2653 getOpenMPClauseName(CKind).data())) {
2654 TPA.Revert();
2655 SkipUntil(tok::annot_pragma_openmp_end);
2656 return Directive;
2657 }
2658
2659 OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo();
2660 if (CKind == OMPC_when) {
2661 // parse and get OMPTraitInfo to pass to the When clause
2662 parseOMPContextSelectors(Loc, TI);
2663 if (TI.Sets.size() == 0) {
2664 Diag(Tok, diag::err_omp_expected_context_selector) << "when clause";
2665 TPA.Commit();
2666 return Directive;
2667 }
2668
2669 // Parse ':'
2670 if (Tok.is(tok::colon))
2672 else {
2673 Diag(Tok, diag::err_omp_expected_colon) << "when clause";
2674 TPA.Commit();
2675 return Directive;
2676 }
2677 }
2678
2679 // Skip Directive for now. We will parse directive in the second iteration
2680 int paren = 0;
2681 while (Tok.isNot(tok::r_paren) || paren != 0) {
2682 if (Tok.is(tok::l_paren))
2683 paren++;
2684 if (Tok.is(tok::r_paren))
2685 paren--;
2686 if (Tok.is(tok::annot_pragma_openmp_end)) {
2687 Diag(Tok, diag::err_omp_expected_punc)
2688 << getOpenMPClauseName(CKind) << 0;
2689 TPA.Commit();
2690 return Directive;
2691 }
2693 }
2694 // Parse ')'
2695 if (Tok.is(tok::r_paren))
2696 T.consumeClose();
2697
2698 VariantMatchInfo VMI;
2699 TI.getAsVariantMatchInfo(ASTContext, VMI);
2700
2701 VMIs.push_back(VMI);
2702 TraitInfos.push_back(&TI);
2703 }
2704
2705 SourceLocation EndLoc = Tok.getLocation();
2706 TPA.Revert();
2707 // End of the first iteration. Parser is reset to the start of metadirective
2708
2709 std::function<void(StringRef)> DiagUnknownTrait =
2710 [this, Loc](StringRef ISATrait) {
2711 // TODO Track the selector locations in a way that is accessible here
2712 // to improve the diagnostic location.
2713 Diag(Loc, diag::warn_unknown_declare_variant_isa_trait) << ISATrait;
2714 };
2715 TargetOMPContext OMPCtx(ASTContext, std::move(DiagUnknownTrait),
2716 /* CurrentFunctionDecl */ nullptr,
2717 ArrayRef<llvm::omp::TraitProperty>(),
2718 Actions.OpenMP().getOpenMPDeviceNum());
2719
2720 // A single match is returned for OpenMP 5.0
2721 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
2722
2723 // Check if we have user conditions with non-constant expressions that
2724 // require runtime selection.
2725 bool HasNonConstUserCondition =
2726 llvm::any_of(TraitInfos, [&](OMPTraitInfo *TI) {
2727 return TI->anyScoreOrCondition([&](Expr *&E, bool IsScore) {
2728 return !IsScore && E && !E->getIntegerConstantExpr(ASTContext);
2729 });
2730 });
2731
2732 if (HasNonConstUserCondition &&
2733 getLangOpts().OpenMPMetadirectiveRuntimeSelection) {
2734 // OpenMP 5.2, 7.4: without an 'otherwise' clause the effect is as if one
2735 // was specified without an associated directive variant. Only
2736 // 'otherwise' (or the deprecated 'default') has no context selectors.
2737 unsigned NumClauses = TraitInfos.size();
2738 bool HasOtherwise = llvm::any_of(
2739 TraitInfos, [](const OMPTraitInfo *TI) { return TI->Sets.empty(); });
2740 unsigned NumVariants = NumClauses + (HasOtherwise ? 0 : 1);
2741
2742 // Reuse the normal metadirective variant parse per clause so every
2743 // variant is a complete directive node with its own body and its own
2744 // data-sharing context. Diagnostics in the associated statement are
2745 // reported once per variant.
2746 SmallVector<Stmt *, 4> Variants;
2747 bool HasError = false;
2748 for (unsigned I : llvm::seq<unsigned>(NumVariants)) {
2749 bool HasDirective = false;
2750 if (I < NumClauses) {
2751 OpenMPClauseKind CKind = getOpenMPClauseKind(PP.getSpelling(Tok));
2752 ConsumeToken();
2753 T.consumeOpen();
2754 if (CKind == OMPC_when) {
2755 // The selectors were parsed into TraitInfos[I] by the first pass;
2756 // skip them so their diagnostics are not repeated.
2757 SkipUntil(tok::colon, StopBeforeMatch);
2758 TryConsumeToken(tok::colon);
2759 }
2760 HasDirective = Tok.isNot(tok::r_paren) &&
2761 Tok.isNot(tok::annot_pragma_openmp_end);
2762 }
2763 // Re-parse the directive and body for every variant but the last.
2764 std::optional<TentativeParsingAction> VariantTPA;
2765 if (I + 1 < NumVariants)
2766 VariantTPA.emplace(*this, /*Unannotated=*/true);
2767
2768 StmtResult Variant;
2769 if (HasDirective) {
2770 Variant = ParseOpenMPDeclarativeOrExecutableDirective(
2771 StmtCtx, /*ReadDirectiveWithinMetadirective=*/true);
2772 } else {
2773 // No directive variant: skip to the end of the pragma.
2774 while (Tok.isNot(tok::annot_pragma_openmp_end))
2776 ConsumeAnnotationToken();
2777 }
2778 // No directive or 'nothing': the variant is the associated statement.
2779 if (!Variant.isInvalid() && !Variant.isUsable()) {
2780 ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
2781 Variant = ParseStatement();
2782 }
2783 // A standalone variant does not take the associated statement while
2784 // the others do; reject the mix until Sema models it.
2785 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(Variant.get());
2786 D && !D->hasAssociatedStmt()) {
2787 Diag(Loc, diag::err_omp_metadirective_standalone_variant);
2788 Variant = StmtError();
2789 }
2790
2791 if (VariantTPA) {
2792 VariantTPA->Revert();
2793 SkipUntil(tok::r_paren, StopBeforeMatch);
2794 T.consumeClose();
2795 }
2796 if (Variant.isInvalid())
2797 HasError = true;
2798 else
2799 Variants.push_back(Variant.get());
2800 }
2801 if (HasError)
2802 return StmtError();
2803 return Actions.OpenMP().ActOnOpenMPMetaDirective(Loc, EndLoc, TraitInfos,
2804 Variants);
2805 }
2806
2807 int Idx = 0;
2808 // In OpenMP 5.0 metadirective is either replaced by another directive or
2809 // ignored.
2810 // TODO: In OpenMP 5.1 generate multiple directives based upon the matches
2811 // found by getBestWhenMatchForContext.
2812 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2813 // OpenMP 5.0 implementation - Skip to the best index found.
2814 if (Idx++ != BestIdx) {
2815 ConsumeToken(); // Consume clause name
2816 T.consumeOpen(); // Consume '('
2817 int paren = 0;
2818 // Skip everything inside the clause
2819 while (Tok.isNot(tok::r_paren) || paren != 0) {
2820 if (Tok.is(tok::l_paren))
2821 paren++;
2822 if (Tok.is(tok::r_paren))
2823 paren--;
2825 }
2826 // Parse ')'
2827 if (Tok.is(tok::r_paren))
2828 T.consumeClose();
2829 continue;
2830 }
2831
2832 OpenMPClauseKind CKind = Tok.isAnnotation()
2833 ? OMPC_unknown
2834 : getOpenMPClauseKind(PP.getSpelling(Tok));
2835 SourceLocation Loc = ConsumeToken();
2836
2837 // Parse '('.
2838 T.consumeOpen();
2839
2840 // Skip ContextSelectors for when clause
2841 if (CKind == OMPC_when) {
2842 OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo();
2843 // parse and skip the ContextSelectors
2844 parseOMPContextSelectors(Loc, TI);
2845
2846 // Parse ':'
2848 }
2849
2850 // If no directive is passed, skip in OpenMP 5.0.
2851 // TODO: Generate nothing directive from OpenMP 5.1.
2852 if (Tok.is(tok::r_paren)) {
2853 SkipUntil(tok::annot_pragma_openmp_end);
2854 break;
2855 }
2856
2857 // Parse Directive
2858 Directive = ParseOpenMPDeclarativeOrExecutableDirective(
2859 StmtCtx,
2860 /*ReadDirectiveWithinMetadirective=*/true);
2861 break;
2862 }
2863 // If no match is found and no otherwise clause is present, skip
2864 // OMP5.2 Chapter 7.4: If no otherwise clause is specified the effect is as
2865 // if one was specified without an associated directive variant.
2866 if (BestIdx == -1 && Idx > 0) {
2867 assert(Tok.is(tok::annot_pragma_openmp_end) &&
2868 "Expecting the end of the pragma here");
2869 ConsumeAnnotationToken();
2870 return StmtEmpty();
2871 }
2872 break;
2873 }
2874 case OMPD_threadprivate: {
2875 // FIXME: Should this be permitted in C++?
2876 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2877 ParsedStmtContext()) {
2878 Diag(Tok, diag::err_omp_immediate_directive)
2879 << getOpenMPDirectiveName(DKind, OMPVersion) << 0;
2880 }
2881 ConsumeToken();
2882 DeclDirectiveListParserHelper Helper(this, DKind);
2883 if (!ParseOpenMPSimpleVarList(DKind, Helper,
2884 /*AllowScopeSpecifier=*/false)) {
2885 skipUntilPragmaOpenMPEnd(DKind);
2886 DeclGroupPtrTy Res = Actions.OpenMP().ActOnOpenMPThreadprivateDirective(
2887 Loc, Helper.getIdentifiers());
2888 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2889 }
2890 SkipUntil(tok::annot_pragma_openmp_end);
2891 break;
2892 }
2893 case OMPD_groupprivate: {
2894 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2895 ParsedStmtContext()) {
2896 Diag(Tok, diag::err_omp_immediate_directive)
2897 << getOpenMPDirectiveName(DKind, OMPVersion) << 0;
2898 }
2899 ConsumeToken();
2900 DeclDirectiveListParserHelper Helper(this, DKind);
2901 if (!ParseOpenMPSimpleVarList(DKind, Helper,
2902 /*AllowScopeSpecifier=*/false)) {
2903 skipUntilPragmaOpenMPEnd(DKind);
2904 DeclGroupPtrTy Res = Actions.OpenMP().ActOnOpenMPGroupPrivateDirective(
2905 Loc, Helper.getIdentifiers());
2906 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2907 }
2908 SkipUntil(tok::annot_pragma_openmp_end);
2909 break;
2910 }
2911 case OMPD_allocate: {
2912 // FIXME: Should this be permitted in C++?
2913 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2914 ParsedStmtContext()) {
2915 Diag(Tok, diag::err_omp_immediate_directive)
2916 << getOpenMPDirectiveName(DKind, OMPVersion) << 0;
2917 }
2918 ConsumeToken();
2919 DeclDirectiveListParserHelper Helper(this, DKind);
2920 if (!ParseOpenMPSimpleVarList(DKind, Helper,
2921 /*AllowScopeSpecifier=*/false)) {
2922 SmallVector<OMPClause *, 1> Clauses;
2923 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
2924 llvm::SmallBitVector SeenClauses(llvm::omp::Clause_enumSize + 1);
2925 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2926 OpenMPClauseKind CKind =
2927 Tok.isAnnotation() ? OMPC_unknown
2928 : getOpenMPClauseKind(PP.getSpelling(Tok));
2929 Actions.OpenMP().StartOpenMPClause(CKind);
2930 OMPClause *Clause = ParseOpenMPClause(OMPD_allocate, CKind,
2931 !SeenClauses[unsigned(CKind)]);
2932 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
2934 SeenClauses[unsigned(CKind)] = true;
2935 if (Clause != nullptr)
2936 Clauses.push_back(Clause);
2937 if (Tok.is(tok::annot_pragma_openmp_end)) {
2938 Actions.OpenMP().EndOpenMPClause();
2939 break;
2940 }
2941 // Skip ',' if any.
2942 if (Tok.is(tok::comma))
2943 ConsumeToken();
2944 Actions.OpenMP().EndOpenMPClause();
2945 }
2946 skipUntilPragmaOpenMPEnd(DKind);
2947 }
2948 DeclGroupPtrTy Res = Actions.OpenMP().ActOnOpenMPAllocateDirective(
2949 Loc, Helper.getIdentifiers(), Clauses);
2950 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2951 }
2952 SkipUntil(tok::annot_pragma_openmp_end);
2953 break;
2954 }
2955 case OMPD_declare_reduction:
2956 ConsumeToken();
2957 if (DeclGroupPtrTy Res =
2958 ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) {
2959 skipUntilPragmaOpenMPEnd(OMPD_declare_reduction);
2961 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2962 } else {
2963 SkipUntil(tok::annot_pragma_openmp_end);
2964 }
2965 break;
2966 case OMPD_declare_mapper: {
2967 ConsumeToken();
2968 if (DeclGroupPtrTy Res =
2969 ParseOpenMPDeclareMapperDirective(/*AS=*/AS_none)) {
2970 // Skip the last annot_pragma_openmp_end.
2971 ConsumeAnnotationToken();
2972 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2973 } else {
2974 SkipUntil(tok::annot_pragma_openmp_end);
2975 }
2976 break;
2977 }
2978 case OMPD_declare_target: {
2979 SourceLocation DTLoc = ConsumeAnyToken();
2980 bool HasClauses = Tok.isNot(tok::annot_pragma_openmp_end);
2981 SemaOpenMP::DeclareTargetContextInfo DTCI(DKind, DTLoc);
2982 if (HasClauses)
2983 ParseOMPDeclareTargetClauses(DTCI);
2984 bool HasImplicitMappings =
2985 !HasClauses || (DTCI.ExplicitlyMapped.empty() && DTCI.Indirect);
2986
2987 if (HasImplicitMappings) {
2988 Diag(Tok, diag::err_omp_unexpected_directive)
2989 << 1 << getOpenMPDirectiveName(DKind, OMPVersion);
2990 SkipUntil(tok::annot_pragma_openmp_end);
2991 break;
2992 }
2993
2994 // Skip the last annot_pragma_openmp_end.
2996
2997 Actions.OpenMP().ActOnFinishedOpenMPDeclareTargetContext(DTCI);
2998 break;
2999 }
3000 case OMPD_begin_declare_variant: {
3001 ConsumeToken();
3003 // Skip the last annot_pragma_openmp_end.
3004 if (!isEofOrEom())
3005 ConsumeAnnotationToken();
3006 }
3007 return Directive;
3008 }
3009 case OMPD_end_declare_variant: {
3010 ConsumeToken();
3011 if (Actions.OpenMP().isInOpenMPDeclareVariantScope())
3012 Actions.OpenMP().ActOnOpenMPEndDeclareVariant();
3013 else
3014 Diag(Loc, diag::err_expected_begin_declare_variant);
3015 ConsumeAnnotationToken();
3016 break;
3017 }
3018 case OMPD_declare_simd:
3019 case OMPD_begin_declare_target:
3020 case OMPD_end_declare_target:
3021 case OMPD_requires:
3022 case OMPD_declare_variant:
3023 Diag(Tok, diag::err_omp_unexpected_directive)
3024 << 1 << getOpenMPDirectiveName(DKind, OMPVersion);
3025 SkipUntil(tok::annot_pragma_openmp_end);
3026 break;
3027 case OMPD_assume: {
3028 ConsumeToken();
3029 Directive = ParseOpenMPInformationalDirective(
3030 StmtCtx, DKind, Loc, ReadDirectiveWithinMetadirective);
3031 assert(!Directive.isUnset() &&
3032 "Informational directive remains unprocessed");
3033 return Directive;
3034 }
3035 case OMPD_unknown:
3036 default:
3037 Diag(Tok, diag::err_omp_unknown_directive);
3038 SkipUntil(tok::annot_pragma_openmp_end);
3039 break;
3040 }
3041 return Directive;
3042}
3043
3044bool Parser::ParseOpenMPSimpleVarList(
3046 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)>
3047 &Callback,
3048 bool AllowScopeSpecifier) {
3049 llvm::omp::Version OMPVersion = Actions.getLangOpts().getOpenMPVersion();
3050 // Parse '('.
3051 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3052 if (T.expectAndConsume(diag::err_expected_lparen_after,
3053 getOpenMPDirectiveName(Kind, OMPVersion).data()))
3054 return true;
3055 bool IsCorrect = true;
3056 bool NoIdentIsFound = true;
3057
3058 // Read tokens while ')' or annot_pragma_openmp_end is not found.
3059 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
3060 CXXScopeSpec SS;
3061 UnqualifiedId Name;
3062 // Read var name.
3063 Token PrevTok = Tok;
3064 NoIdentIsFound = false;
3065
3066 if (AllowScopeSpecifier && getLangOpts().CPlusPlus &&
3067 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
3068 /*ObjectHasErrors=*/false, false)) {
3069 IsCorrect = false;
3070 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3072 } else if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
3073 /*ObjectHadErrors=*/false, false, false,
3074 false, false, nullptr, Name)) {
3075 IsCorrect = false;
3076 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3078 } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) &&
3079 Tok.isNot(tok::annot_pragma_openmp_end)) {
3080 IsCorrect = false;
3081 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3083 Diag(PrevTok.getLocation(), diag::err_expected)
3084 << tok::identifier
3085 << SourceRange(PrevTok.getLocation(), PrevTokLocation);
3086 } else {
3087 Callback(SS, Actions.GetNameFromUnqualifiedId(Name));
3088 }
3089 // Consume ','.
3090 if (Tok.is(tok::comma)) {
3091 ConsumeToken();
3092 }
3093 }
3094
3095 if (NoIdentIsFound) {
3096 Diag(Tok, diag::err_expected) << tok::identifier;
3097 IsCorrect = false;
3098 }
3099
3100 // Parse ')'.
3101 IsCorrect = !T.consumeClose() && IsCorrect;
3102
3103 return !IsCorrect;
3104}
3105
3106OMPClause *Parser::ParseOpenMPSizesClause() {
3107 SourceLocation ClauseNameLoc, OpenLoc, CloseLoc;
3108 SmallVector<Expr *, 4> ValExprs;
3109 if (ParseOpenMPExprListClause(OMPC_sizes, ClauseNameLoc, OpenLoc, CloseLoc,
3110 ValExprs))
3111 return nullptr;
3112
3113 return Actions.OpenMP().ActOnOpenMPSizesClause(ValExprs, ClauseNameLoc,
3114 OpenLoc, CloseLoc);
3115}
3116
3117OMPClause *Parser::ParseOpenMPCountsClause() {
3118 SourceLocation ClauseNameLoc, OpenLoc, CloseLoc;
3119 SmallVector<Expr *, 4> ValExprs;
3120 std::optional<unsigned> FillIdx;
3121 unsigned FillCount = 0;
3122 SourceLocation FillLoc;
3123
3124 assert(getOpenMPClauseName(OMPC_counts) == PP.getSpelling(Tok) &&
3125 "Expected parsing to start at clause name");
3126 ClauseNameLoc = ConsumeToken();
3127
3128 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3129 if (T.consumeOpen()) {
3130 Diag(Tok, diag::err_expected) << tok::l_paren;
3131 return nullptr;
3132 }
3133
3134 do {
3135 if (Tok.is(tok::identifier) &&
3136 Tok.getIdentifierInfo()->getName() == "omp_fill") {
3137 if (FillCount == 0)
3138 FillIdx = ValExprs.size();
3139 ++FillCount;
3140 FillLoc = Tok.getLocation();
3141 ConsumeToken();
3142 ValExprs.push_back(nullptr);
3143 } else {
3145 if (!Val.isUsable()) {
3146 T.skipToEnd();
3147 return nullptr;
3148 }
3149 ValExprs.push_back(Val.get());
3150 }
3151 } while (TryConsumeToken(tok::comma));
3152
3153 if (T.consumeClose())
3154 return nullptr;
3155 OpenLoc = T.getOpenLocation();
3156 CloseLoc = T.getCloseLocation();
3157
3158 return Actions.OpenMP().ActOnOpenMPCountsClause(
3159 ValExprs, ClauseNameLoc, OpenLoc, CloseLoc, FillIdx, FillLoc, FillCount);
3160}
3161
3162OMPClause *Parser::ParseOpenMPLoopRangeClause() {
3163 SourceLocation ClauseNameLoc = ConsumeToken();
3164 SourceLocation FirstLoc, CountLoc;
3165
3166 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3167 if (T.consumeOpen()) {
3168 Diag(Tok, diag::err_expected) << tok::l_paren;
3169 return nullptr;
3170 }
3171
3172 FirstLoc = Tok.getLocation();
3174 if (!FirstVal.isUsable()) {
3175 T.skipToEnd();
3176 return nullptr;
3177 }
3178
3179 ExpectAndConsume(tok::comma);
3180
3181 CountLoc = Tok.getLocation();
3183 if (!CountVal.isUsable()) {
3184 T.skipToEnd();
3185 return nullptr;
3186 }
3187
3188 T.consumeClose();
3189
3190 return Actions.OpenMP().ActOnOpenMPLoopRangeClause(
3191 FirstVal.get(), CountVal.get(), ClauseNameLoc, T.getOpenLocation(),
3192 FirstLoc, CountLoc, T.getCloseLocation());
3193}
3194
3195OMPClause *Parser::ParseOpenMPPermutationClause() {
3196 SourceLocation ClauseNameLoc, OpenLoc, CloseLoc;
3197 SmallVector<Expr *> ArgExprs;
3198 if (ParseOpenMPExprListClause(OMPC_permutation, ClauseNameLoc, OpenLoc,
3199 CloseLoc, ArgExprs,
3200 /*ReqIntConst=*/true))
3201 return nullptr;
3202
3203 return Actions.OpenMP().ActOnOpenMPPermutationClause(ArgExprs, ClauseNameLoc,
3204 OpenLoc, CloseLoc);
3205}
3206
3207OMPClause *Parser::ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind) {
3208 SourceLocation Loc = Tok.getLocation();
3210
3211 // Parse '('.
3212 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3213 if (T.expectAndConsume(diag::err_expected_lparen_after, "uses_allocator"))
3214 return nullptr;
3215 SmallVector<SemaOpenMP::UsesAllocatorsData, 4> Data;
3216 do {
3217 // Parse 'traits(expr) : Allocator' for >=5.2
3218 if (getLangOpts().OpenMP >= 52 && Tok.is(tok::identifier) &&
3219 Tok.getIdentifierInfo()->getName() == "traits") {
3220
3221 SemaOpenMP::UsesAllocatorsData &D = Data.emplace_back();
3222
3223 ConsumeToken();
3224
3225 // Parse '(' <expr> ')'
3226 BalancedDelimiterTracker TraitParens(*this, tok::l_paren,
3227 tok::annot_pragma_openmp_end);
3228 TraitParens.consumeOpen();
3229 ExprResult AllocatorTraits =
3230 getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression();
3231 TraitParens.consumeClose();
3232
3233 if (AllocatorTraits.isInvalid()) {
3234 SkipUntil(
3235 {tok::comma, tok::semi, tok::r_paren, tok::annot_pragma_openmp_end},
3237 break;
3238 }
3239
3240 // Expect ':'
3241 if (Tok.isNot(tok::colon)) {
3242 Diag(Tok, diag::err_expected) << tok::colon;
3243 SkipUntil(
3244 {tok::comma, tok::semi, tok::r_paren, tok::annot_pragma_openmp_end},
3246 continue;
3247 }
3248 ConsumeToken();
3249
3250 CXXScopeSpec SS;
3251 ExprResult AllocatorExpr =
3252 getLangOpts().CPlusPlus
3253 ? ParseCXXIdExpression()
3254 : tryParseCXXIdExpression(SS, /*isAddressOfOperand=*/false);
3255
3256 if (AllocatorExpr.isInvalid()) {
3257 SkipUntil(
3258 {tok::comma, tok::semi, tok::r_paren, tok::annot_pragma_openmp_end},
3260 break;
3261 }
3262
3263 D.Allocator = AllocatorExpr.get();
3264 D.AllocatorTraits = AllocatorTraits.get();
3265 D.LParenLoc = TraitParens.getOpenLocation();
3266 D.RParenLoc = TraitParens.getCloseLocation();
3267
3268 // Separator handling(;)
3269 if (Tok.is(tok::comma)) {
3270 // In 5.2, comma is invalid
3271 Diag(Tok.getLocation(), diag::err_omp_allocator_comma_separator)
3272 << FixItHint::CreateReplacement(Tok.getLocation(), ";");
3274 } else if (Tok.is(tok::semi)) {
3275 ConsumeAnyToken(); // valid separator
3276 }
3277
3278 continue;
3279 }
3280
3281 // Parse 'Allocator(expr)' for <5.2
3282 CXXScopeSpec SS;
3283 ExprResult Allocator =
3284 getLangOpts().CPlusPlus
3285 ? ParseCXXIdExpression()
3286 : tryParseCXXIdExpression(SS, /*isAddressOfOperand=*/false);
3287 if (Allocator.isInvalid()) {
3288 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3289 StopBeforeMatch);
3290 break;
3291 }
3292 SemaOpenMP::UsesAllocatorsData &D = Data.emplace_back();
3293 D.Allocator = Allocator.get();
3294 if (Tok.is(tok::l_paren)) {
3295 BalancedDelimiterTracker T(*this, tok::l_paren,
3296 tok::annot_pragma_openmp_end);
3297 T.consumeOpen();
3298 ExprResult AllocatorTraits =
3299 getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression();
3300 T.consumeClose();
3301 if (AllocatorTraits.isInvalid()) {
3302 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3303 StopBeforeMatch);
3304 break;
3305 }
3306 D.AllocatorTraits = AllocatorTraits.get();
3307 D.LParenLoc = T.getOpenLocation();
3308 D.RParenLoc = T.getCloseLocation();
3309
3310 // Deprecation diagnostic in >= 5.2
3311 if (getLangOpts().OpenMP >= 52) {
3312 Diag(Loc, diag::err_omp_deprecate_old_syntax)
3313 << "allocator(expr)" // %0: old form
3314 << "uses_allocators" // %1: clause name
3315 << "traits(expr): alloc"; // %2: suggested new form
3316 }
3317 }
3318 if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren))
3319 Diag(Tok, diag::err_omp_expected_punc) << "uses_allocators" << 0;
3320 // Parse ','
3321 if (Tok.is(tok::comma))
3322 ConsumeAnyToken();
3323 } while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end));
3324 T.consumeClose();
3325 return Actions.OpenMP().ActOnOpenMPUsesAllocatorClause(
3326 Loc, T.getOpenLocation(), T.getCloseLocation(), Data);
3327}
3328
3329OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind,
3330 OpenMPClauseKind CKind, bool FirstClause) {
3331 OMPClauseKind = CKind;
3332 OMPClause *Clause = nullptr;
3333 bool ErrorFound = false;
3334 bool WrongDirective = false;
3335 llvm::omp::Version OMPVersion = Actions.getLangOpts().getOpenMPVersion();
3336
3337 auto CheckClauseValid = [&](OpenMPDirectiveKind D, OpenMPClauseKind C) {
3338 if (!isAllowedClauseForDirective(D, C, OMPVersion)) {
3339 Diag(Tok, diag::err_omp_unexpected_clause)
3340 << getOpenMPClauseName(C) << getOpenMPDirectiveName(D, OMPVersion);
3341 ErrorFound = true;
3342 WrongDirective = true;
3343 }
3344 };
3345
3346 if (CKind != OMPC_unknown) {
3347 // Check if clause is allowed for the given directive.
3348 assert(DKind != OMPD_ordered_blockassoc &&
3349 "Wrong kind for ordered directive");
3350 if (DKind == OMPD_ordered_standalone) {
3351 // Initially OMPD_ordered_standalone is used for ORDERED, before the
3352 // actual kind can be determined.
3353 if (!isAllowedClauseForDirective(DKind, CKind, OMPVersion))
3354 CheckClauseValid(OMPD_ordered_blockassoc, CKind);
3355 } else {
3356 CheckClauseValid(DKind, CKind);
3357 }
3358 }
3359
3360 switch (CKind) {
3361 case OMPC_final:
3362 case OMPC_safelen:
3363 case OMPC_simdlen:
3364 case OMPC_collapse:
3365 case OMPC_ordered:
3366 case OMPC_priority:
3367 case OMPC_grainsize:
3368 case OMPC_num_tasks:
3369 case OMPC_hint:
3370 case OMPC_allocator:
3371 case OMPC_depobj:
3372 case OMPC_detach:
3373 case OMPC_novariants:
3374 case OMPC_nocontext:
3375 case OMPC_filter:
3376 case OMPC_partial:
3377 case OMPC_depth:
3378 case OMPC_align:
3379 case OMPC_message:
3380 case OMPC_ompx_dyn_cgroup_mem:
3381 case OMPC_dyn_groupprivate:
3382 case OMPC_transparent:
3383 // OpenMP [2.5, Restrictions]
3384 // At most one num_threads clause can appear on the directive.
3385 // OpenMP [2.8.1, simd construct, Restrictions]
3386 // Only one safelen clause can appear on a simd directive.
3387 // Only one simdlen clause can appear on a simd directive.
3388 // Only one collapse clause can appear on a simd directive.
3389 // OpenMP [2.11.1, task Construct, Restrictions]
3390 // At most one if clause can appear on the directive.
3391 // At most one final clause can appear on the directive.
3392 // OpenMP [teams Construct, Restrictions]
3393 // At most one num_teams clause can appear on the directive.
3394 // At most one thread_limit clause can appear on the directive.
3395 // OpenMP [2.9.1, task Construct, Restrictions]
3396 // At most one priority clause can appear on the directive.
3397 // OpenMP [2.9.2, taskloop Construct, Restrictions]
3398 // At most one grainsize clause can appear on the directive.
3399 // OpenMP [2.9.2, taskloop Construct, Restrictions]
3400 // At most one num_tasks clause can appear on the directive.
3401 // OpenMP [2.11.3, allocate Directive, Restrictions]
3402 // At most one allocator clause can appear on the directive.
3403 // OpenMP 5.0, 2.10.1 task Construct, Restrictions.
3404 // At most one detach clause can appear on the directive.
3405 // OpenMP 5.1, 2.3.6 dispatch Construct, Restrictions.
3406 // At most one novariants clause can appear on a dispatch directive.
3407 // At most one nocontext clause can appear on a dispatch directive.
3408 // OpenMP [5.1, error directive, Restrictions]
3409 // At most one message clause can appear on the directive
3410 if (!FirstClause) {
3411 Diag(Tok, diag::err_omp_more_one_clause)
3412 << getOpenMPDirectiveName(DKind, OMPVersion)
3413 << getOpenMPClauseName(CKind) << 0;
3414 ErrorFound = true;
3415 }
3416
3417 if (CKind == OMPC_transparent && PP.LookAhead(0).isNot(tok::l_paren)) {
3418 SourceLocation Loc = ConsumeToken();
3419 SourceLocation LLoc = Tok.getLocation();
3420 if (!WrongDirective)
3421 Clause = Actions.OpenMP().ActOnOpenMPTransparentClause(nullptr, LLoc,
3422 LLoc, Loc);
3423 break;
3424 }
3425 if ((CKind == OMPC_ordered || CKind == OMPC_partial) &&
3426 PP.LookAhead(/*N=*/0).isNot(tok::l_paren))
3427 Clause = ParseOpenMPClause(CKind, WrongDirective);
3428 else if (CKind == OMPC_grainsize || CKind == OMPC_num_tasks ||
3429 CKind == OMPC_dyn_groupprivate)
3430 Clause = ParseOpenMPSingleExprWithArgClause(DKind, CKind, WrongDirective);
3431 else
3432 Clause = ParseOpenMPSingleExprClause(CKind, WrongDirective);
3433 break;
3434 case OMPC_threadset:
3435 case OMPC_fail:
3436 case OMPC_proc_bind:
3437 case OMPC_atomic_default_mem_order:
3438 case OMPC_at:
3439 case OMPC_severity:
3440 case OMPC_bind:
3441 // OpenMP [2.14.3.1, Restrictions]
3442 // Only a single default clause may be specified on a parallel, task or
3443 // teams directive.
3444 // OpenMP [2.5, parallel Construct, Restrictions]
3445 // At most one proc_bind clause can appear on the directive.
3446 // OpenMP [5.0, Requires directive, Restrictions]
3447 // At most one atomic_default_mem_order clause can appear
3448 // on the directive
3449 // OpenMP [5.1, error directive, Restrictions]
3450 // At most one at clause can appear on the directive
3451 // At most one severity clause can appear on the directive
3452 // OpenMP 5.1, 2.11.7 loop Construct, Restrictions.
3453 // At most one bind clause can appear on a loop directive.
3454 if (!FirstClause) {
3455 Diag(Tok, diag::err_omp_more_one_clause)
3456 << getOpenMPDirectiveName(DKind, OMPVersion)
3457 << getOpenMPClauseName(CKind) << 0;
3458 ErrorFound = true;
3459 }
3460
3461 Clause = ParseOpenMPSimpleClause(CKind, WrongDirective);
3462 break;
3463 case OMPC_device:
3464 case OMPC_schedule:
3465 case OMPC_dist_schedule:
3466 case OMPC_defaultmap:
3467 case OMPC_default:
3468 case OMPC_order:
3469 // OpenMP [2.7.1, Restrictions, p. 3]
3470 // Only one schedule clause can appear on a loop directive.
3471 // OpenMP 4.5 [2.10.4, Restrictions, p. 106]
3472 // At most one defaultmap clause can appear on the directive.
3473 // OpenMP 5.0 [2.12.5, target construct, Restrictions]
3474 // At most one device clause can appear on the directive.
3475 // OpenMP 5.1 [2.11.3, order clause, Restrictions]
3476 // At most one order clause may appear on a construct.
3477 if ((getLangOpts().OpenMP < 50 || CKind != OMPC_defaultmap) &&
3478 (CKind != OMPC_order || getLangOpts().OpenMP >= 51) && !FirstClause) {
3479 Diag(Tok, diag::err_omp_more_one_clause)
3480 << getOpenMPDirectiveName(DKind, OMPVersion)
3481 << getOpenMPClauseName(CKind) << 0;
3482 ErrorFound = true;
3483 }
3484 [[fallthrough]];
3485 case OMPC_if:
3486 Clause = ParseOpenMPSingleExprWithArgClause(DKind, CKind, WrongDirective);
3487 break;
3488 case OMPC_holds:
3489 Clause = ParseOpenMPSingleExprClause(CKind, WrongDirective);
3490 break;
3491 case OMPC_nowait:
3492 case OMPC_untied:
3493 case OMPC_mergeable:
3494 case OMPC_read:
3495 case OMPC_write:
3496 case OMPC_capture:
3497 case OMPC_compare:
3498 case OMPC_seq_cst:
3499 case OMPC_acq_rel:
3500 case OMPC_acquire:
3501 case OMPC_release:
3502 case OMPC_relaxed:
3503 case OMPC_weak:
3504 case OMPC_threads:
3505 case OMPC_simd:
3506 case OMPC_nogroup:
3507 case OMPC_unified_address:
3508 case OMPC_unified_shared_memory:
3509 case OMPC_reverse_offload:
3510 case OMPC_dynamic_allocators:
3511 case OMPC_full:
3512 // OpenMP [2.7.1, Restrictions, p. 9]
3513 // Only one ordered clause can appear on a loop directive.
3514 // OpenMP [2.7.1, Restrictions, C/C++, p. 4]
3515 // Only one nowait clause can appear on a for directive.
3516 // OpenMP [5.0, Requires directive, Restrictions]
3517 // Each of the requires clauses can appear at most once on the directive.
3518 if (!FirstClause) {
3519 Diag(Tok, diag::err_omp_more_one_clause)
3520 << getOpenMPDirectiveName(DKind, OMPVersion)
3521 << getOpenMPClauseName(CKind) << 0;
3522 ErrorFound = true;
3523 }
3524
3525 if (CKind == OMPC_nowait && PP.LookAhead(/*N=*/0).is(tok::l_paren) &&
3526 getLangOpts().OpenMP >= 60)
3527 Clause = ParseOpenMPSingleExprClause(CKind, WrongDirective);
3528 else
3529 Clause = ParseOpenMPClause(CKind, WrongDirective);
3530 break;
3531 case OMPC_self_maps:
3532 // OpenMP [6.0, self_maps clause]
3533 if (getLangOpts().OpenMP < 60) {
3534 Diag(Tok, diag::err_omp_expected_clause)
3535 << getOpenMPDirectiveName(OMPD_requires, OMPVersion);
3536 ErrorFound = true;
3537 }
3538 if (!FirstClause) {
3539 Diag(Tok, diag::err_omp_more_one_clause)
3540 << getOpenMPDirectiveName(DKind, OMPVersion)
3541 << getOpenMPClauseName(CKind) << 0;
3542 ErrorFound = true;
3543 }
3544 Clause = ParseOpenMPClause(CKind, WrongDirective);
3545 break;
3546 case OMPC_update:
3547 if (!FirstClause) {
3548 Diag(Tok, diag::err_omp_more_one_clause)
3549 << getOpenMPDirectiveName(DKind, OMPVersion)
3550 << getOpenMPClauseName(CKind) << 0;
3551 ErrorFound = true;
3552 }
3553 Clause = ParseOpenMPClause(CKind, WrongDirective);
3554 break;
3555 case OMPC_update_depend_objects:
3556 if (!FirstClause) {
3557 Diag(Tok, diag::err_omp_more_one_clause)
3558 << getOpenMPDirectiveName(DKind, OMPVersion)
3559 << getOpenMPClauseName(CKind) << 0;
3560 ErrorFound = true;
3561 }
3562
3563 Clause = ParseOpenMPSimpleClause(CKind, WrongDirective);
3564 break;
3565 case OMPC_num_teams:
3566 case OMPC_thread_limit:
3567 case OMPC_num_threads:
3568 if (!FirstClause) {
3569 Diag(Tok, diag::err_omp_more_one_clause)
3570 << getOpenMPDirectiveName(DKind, OMPVersion)
3571 << getOpenMPClauseName(CKind) << 0;
3572 ErrorFound = true;
3573 }
3574 [[fallthrough]];
3575 case OMPC_private:
3576 case OMPC_firstprivate:
3577 case OMPC_lastprivate:
3578 case OMPC_shared:
3579 case OMPC_reduction:
3580 case OMPC_task_reduction:
3581 case OMPC_in_reduction:
3582 case OMPC_linear:
3583 case OMPC_aligned:
3584 case OMPC_copyin:
3585 case OMPC_copyprivate:
3586 case OMPC_flush:
3587 case OMPC_depend:
3588 case OMPC_map:
3589 case OMPC_to:
3590 case OMPC_from:
3591 case OMPC_use_device_ptr:
3592 case OMPC_use_device_addr:
3593 case OMPC_is_device_ptr:
3594 case OMPC_has_device_addr:
3595 case OMPC_allocate:
3596 case OMPC_nontemporal:
3597 case OMPC_inclusive:
3598 case OMPC_exclusive:
3599 case OMPC_affinity:
3600 case OMPC_doacross:
3601 case OMPC_enter:
3602 if (getLangOpts().OpenMP >= 52 && DKind == OMPD_ordered_standalone &&
3603 CKind == OMPC_depend)
3604 Diag(Tok, diag::warn_omp_depend_in_ordered_deprecated);
3605 Clause = ParseOpenMPVarListClause(DKind, CKind, WrongDirective);
3606 break;
3607 case OMPC_sizes:
3608 if (!FirstClause) {
3609 Diag(Tok, diag::err_omp_more_one_clause)
3610 << getOpenMPDirectiveName(DKind, OMPVersion)
3611 << getOpenMPClauseName(CKind) << 0;
3612 ErrorFound = true;
3613 }
3614
3615 Clause = ParseOpenMPSizesClause();
3616 break;
3617 case OMPC_permutation:
3618 if (!FirstClause) {
3619 Diag(Tok, diag::err_omp_more_one_clause)
3620 << getOpenMPDirectiveName(DKind, OMPVersion)
3621 << getOpenMPClauseName(CKind) << 0;
3622 ErrorFound = true;
3623 }
3624 Clause = ParseOpenMPPermutationClause();
3625 break;
3626 case OMPC_counts:
3627 if (!FirstClause) {
3628 Diag(Tok, diag::err_omp_more_one_clause)
3629 << getOpenMPDirectiveName(DKind, OMPVersion)
3630 << getOpenMPClauseName(CKind) << 0;
3631 ErrorFound = true;
3632 }
3633 Clause = ParseOpenMPCountsClause();
3634 break;
3635 case OMPC_uses_allocators:
3636 Clause = ParseOpenMPUsesAllocatorClause(DKind);
3637 break;
3638 case OMPC_destroy:
3639 if (DKind != OMPD_interop) {
3640 if (!FirstClause) {
3641 Diag(Tok, diag::err_omp_more_one_clause)
3642 << getOpenMPDirectiveName(DKind, OMPVersion)
3643 << getOpenMPClauseName(CKind) << 0;
3644 ErrorFound = true;
3645 }
3646 Clause = ParseOpenMPClause(CKind, WrongDirective);
3647 break;
3648 }
3649 [[fallthrough]];
3650 case OMPC_init:
3651 case OMPC_use:
3652 Clause = ParseOpenMPInteropClause(CKind, WrongDirective);
3653 break;
3654 case OMPC_device_type:
3655 case OMPC_unknown:
3656 skipUntilPragmaOpenMPEnd(DKind);
3657 break;
3658 case OMPC_threadprivate:
3659 case OMPC_groupprivate:
3660 case OMPC_uniform:
3661 case OMPC_match:
3662 if (!WrongDirective)
3663 Diag(Tok, diag::err_omp_unexpected_clause)
3664 << getOpenMPClauseName(CKind)
3665 << getOpenMPDirectiveName(DKind, OMPVersion);
3666 SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch);
3667 break;
3668 case OMPC_absent:
3669 case OMPC_contains: {
3670 SourceLocation Loc = ConsumeToken();
3671 SourceLocation LLoc = Tok.getLocation();
3672 SourceLocation RLoc;
3673 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
3674 BalancedDelimiterTracker T(*this, tok::l_paren);
3675 T.consumeOpen();
3676 do {
3677 OpenMPDirectiveKind DK = getOpenMPDirectiveKind(PP.getSpelling(Tok));
3678 if (DK == OMPD_unknown) {
3679 skipUntilPragmaOpenMPEnd(OMPD_assume);
3680 Diag(Tok, diag::err_omp_unexpected_clause)
3681 << getOpenMPClauseName(CKind)
3682 << getOpenMPDirectiveName(DKind, OMPVersion);
3683 break;
3684 }
3686 DKVec.push_back(DK);
3687 ConsumeToken();
3688 } else {
3689 Diag(Tok, diag::err_omp_unexpected_clause)
3690 << getOpenMPClauseName(CKind)
3691 << getOpenMPDirectiveName(DKind, OMPVersion);
3692 }
3693 } while (TryConsumeToken(tok::comma));
3694 RLoc = Tok.getLocation();
3695 T.consumeClose();
3696 if (!WrongDirective)
3697 Clause = Actions.OpenMP().ActOnOpenMPDirectivePresenceClause(
3698 CKind, DKVec, Loc, LLoc, RLoc);
3699 break;
3700 }
3701 case OMPC_no_openmp:
3702 case OMPC_no_openmp_routines:
3703 case OMPC_no_openmp_constructs:
3704 case OMPC_no_parallelism: {
3705 if (!FirstClause) {
3706 Diag(Tok, diag::err_omp_more_one_clause)
3707 << getOpenMPDirectiveName(DKind, OMPVersion)
3708 << getOpenMPClauseName(CKind) << 0;
3709 ErrorFound = true;
3710 }
3711 SourceLocation Loc = ConsumeToken();
3712 if (!WrongDirective)
3713 Clause = Actions.OpenMP().ActOnOpenMPNullaryAssumptionClause(
3714 CKind, Loc, Tok.getLocation());
3715 break;
3716 }
3717 case OMPC_ompx_attribute:
3718 Clause = ParseOpenMPOMPXAttributesClause(WrongDirective);
3719 break;
3720 case OMPC_ompx_bare:
3721 if (DKind == llvm::omp::Directive::OMPD_target) {
3722 // Flang splits the combined directives which requires OMPD_target to be
3723 // marked as accepting the `ompx_bare` clause in `OMP.td`. Thus, we need
3724 // to explicitly check whether this clause is applied to an `omp target`
3725 // without `teams` and emit an error.
3726 Diag(Tok, diag::err_omp_unexpected_clause)
3727 << getOpenMPClauseName(CKind)
3728 << getOpenMPDirectiveName(DKind, OMPVersion);
3729 ErrorFound = true;
3730 WrongDirective = true;
3731 }
3732 if (WrongDirective)
3733 Diag(Tok, diag::note_ompx_bare_clause)
3734 << getOpenMPClauseName(CKind) << "target teams";
3735 if (!ErrorFound && !getLangOpts().OpenMPExtensions) {
3736 Diag(Tok, diag::err_omp_unexpected_clause_extension_only)
3737 << getOpenMPClauseName(CKind)
3738 << getOpenMPDirectiveName(DKind, OMPVersion);
3739 ErrorFound = true;
3740 }
3741 Clause = ParseOpenMPClause(CKind, WrongDirective);
3742 break;
3743 case OMPC_looprange:
3744 Clause = ParseOpenMPLoopRangeClause();
3745 break;
3746 default:
3747 break;
3748 }
3749 return ErrorFound ? nullptr : Clause;
3750}
3751
3752/// Parses simple expression in parens for single-expression clauses of OpenMP
3753/// constructs.
3754/// \param RLoc Returned location of right paren.
3756 SourceLocation &RLoc,
3757 bool IsAddressOfOperand) {
3758 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3759 if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data()))
3760 return ExprError();
3761
3762 SourceLocation ELoc = Tok.getLocation();
3763 ExprResult LHS(
3764 ParseCastExpression(CastParseKind::AnyCastExpr, IsAddressOfOperand,
3766 ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
3767 Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
3768
3769 // Parse ')'.
3770 RLoc = Tok.getLocation();
3771 if (!T.consumeClose())
3772 RLoc = T.getCloseLocation();
3773
3774 return Val;
3775}
3776
3777OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
3778 bool ParseOnly) {
3780 SourceLocation LLoc = Tok.getLocation();
3781 SourceLocation RLoc;
3782
3783 ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
3784
3785 if (Val.isInvalid())
3786 return nullptr;
3787
3788 if (ParseOnly)
3789 return nullptr;
3790 return Actions.OpenMP().ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc,
3791 LLoc, RLoc);
3792}
3793
3794bool Parser::ParseOpenMPIndirectClause(
3795 SemaOpenMP::DeclareTargetContextInfo &DTCI, bool ParseOnly) {
3797 SourceLocation RLoc;
3798
3799 if (Tok.isNot(tok::l_paren)) {
3800 if (ParseOnly)
3801 return false;
3802 DTCI.Indirect = nullptr;
3803 return true;
3804 }
3805
3806 ExprResult Val =
3807 ParseOpenMPParensExpr(getOpenMPClauseName(OMPC_indirect), RLoc);
3808 if (Val.isInvalid())
3809 return false;
3810
3811 if (ParseOnly)
3812 return false;
3813
3814 if (!Val.get()->isValueDependent() && !Val.get()->isTypeDependent() &&
3815 !Val.get()->isInstantiationDependent() &&
3817 ExprResult Ret = Actions.CheckBooleanCondition(Loc, Val.get());
3818 if (Ret.isInvalid())
3819 return false;
3820 llvm::APSInt Result;
3821 Ret = Actions.VerifyIntegerConstantExpression(Val.get(), &Result,
3823 if (Ret.isInvalid())
3824 return false;
3825 DTCI.Indirect = Val.get();
3826 return true;
3827 }
3828 return false;
3829}
3830
3831ExprResult Parser::ParseOMPInteropFrSelector() {
3832 ConsumeToken(); // 'fr'
3833 BalancedDelimiterTracker FT(*this, tok::l_paren,
3834 tok::annot_pragma_openmp_end);
3835 if (FT.expectAndConsume(diag::err_expected_lparen_after, "fr")) {
3836 SkipUntil(
3837 {tok::comma, tok::r_brace, tok::r_paren, tok::annot_pragma_openmp_end},
3839 return ExprError();
3840 }
3841 SourceLocation Loc = Tok.getLocation();
3842 ExprResult LHS = ParseCastExpression(CastParseKind::AnyCastExpr);
3843 ExprResult Arg = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
3844 Arg = Actions.ActOnFinishFullExpr(Arg.get(), Loc, /*DiscardedValue=*/false);
3845 FT.consumeClose();
3846 return Arg;
3847}
3848
3849bool Parser::ParseOMPInteropAttrSelector(SmallVectorImpl<Expr *> &Attrs) {
3850 ConsumeToken(); // 'attr'
3851 BalancedDelimiterTracker AT(*this, tok::l_paren,
3852 tok::annot_pragma_openmp_end);
3853 if (AT.expectAndConsume(diag::err_expected_lparen_after, "attr")) {
3854 SkipUntil(
3855 {tok::comma, tok::r_brace, tok::r_paren, tok::annot_pragma_openmp_end},
3857 return true;
3858 }
3859 bool HasError = false;
3860 // attr() requires at least one ext-string-literal argument; an empty list is
3861 // not permitted by the prefer_type grammar.
3862 if (Tok.is(tok::r_paren)) {
3863 Diag(Tok, diag::err_omp_interop_attr_not_string);
3864 HasError = true;
3865 }
3866 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::r_brace) &&
3867 Tok.isNot(tok::annot_pragma_openmp_end)) {
3868 if (Tok.is(tok::string_literal)) {
3870 if (S.isUsable())
3871 Attrs.push_back(S.get());
3872 else
3873 HasError = true;
3874 } else {
3875 HasError = true;
3876 Diag(Tok, diag::err_omp_interop_attr_not_string);
3877 ConsumeToken();
3878 }
3879 if (Tok.is(tok::comma))
3880 ConsumeToken();
3881 }
3882 AT.consumeClose();
3883 return HasError;
3884}
3885
3886bool Parser::ParseOMPInteropInfo(OMPInteropInfo &InteropInfo,
3887 OpenMPClauseKind Kind) {
3888 const Token &Tok = getCurToken();
3889 bool HasError = false;
3890 bool IsTarget = false;
3891 bool IsTargetSync = false;
3892
3893 while (Tok.is(tok::identifier)) {
3894 // prefer_type is allowed with 'init' and 'append_args' and must be first.
3895 bool PreferTypeAllowed = (Kind == OMPC_init || Kind == OMPC_append_args) &&
3896 InteropInfo.Prefs.empty() && !IsTarget &&
3897 !IsTargetSync;
3898 if (Tok.getIdentifierInfo()->isStr("target")) {
3899 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
3900 // Each interop-type may be specified on an action-clause at most
3901 // once.
3902 if (IsTarget)
3903 Diag(Tok, diag::warn_omp_more_one_interop_type) << "target";
3904 IsTarget = true;
3905 ConsumeToken();
3906 } else if (Tok.getIdentifierInfo()->isStr("targetsync")) {
3907 if (IsTargetSync)
3908 Diag(Tok, diag::warn_omp_more_one_interop_type) << "targetsync";
3909 IsTargetSync = true;
3910 ConsumeToken();
3911 } else if (Tok.getIdentifierInfo()->isStr("prefer_type") &&
3912 PreferTypeAllowed) {
3913 if (Kind == OMPC_append_args && getLangOpts().OpenMP < 60) {
3914 Diag(Tok, diag::err_omp_append_args_prefer_type_60);
3915 HasError = true;
3916 }
3917 ConsumeToken();
3918 BalancedDelimiterTracker PT(*this, tok::l_paren,
3919 tok::annot_pragma_openmp_end);
3920 if (PT.expectAndConsume(diag::err_expected_lparen_after, "prefer_type"))
3921 HasError = true;
3922
3923 // prefer_type requires at least one preference-specification.
3924 if (Tok.is(tok::r_paren)) {
3925 Diag(Tok, diag::err_omp_expected_pref_spec);
3926 HasError = true;
3927 }
3928
3929 while (Tok.isNot(tok::r_paren) &&
3930 Tok.isNot(tok::annot_pragma_openmp_end)) {
3931 // OMP 6.0: { fr(...), attr(...) } brace-grouped pref-spec
3932 if (Tok.is(tok::l_brace)) {
3933 // The brace-grouped form was introduced in OpenMP 6.0; earlier
3934 // versions only allow the flat foreign-runtime-id list.
3935 if (getLangOpts().OpenMP < 60) {
3936 Diag(Tok, diag::err_omp_prefer_type_brace_60);
3937 HasError = true;
3938 }
3939 BalancedDelimiterTracker BT(*this, tok::l_brace,
3940 tok::annot_pragma_openmp_end);
3941 BT.consumeOpen();
3942 Expr *FrExpr = nullptr;
3943 SmallVector<Expr *, 2> AttrExprs;
3944 bool SeenFr = false;
3945
3946 // A pref-spec requires at least one 'fr'/'attr' selector; {} is not
3947 // permitted by the grammar.
3948 if (Tok.is(tok::r_brace)) {
3949 Diag(Tok, diag::err_omp_expected_fr_or_attr_selector);
3950 HasError = true;
3951 }
3952
3953 while (Tok.isNot(tok::r_brace) &&
3954 Tok.isNot(tok::annot_pragma_openmp_end)) {
3955 if (Tok.is(tok::identifier) &&
3956 Tok.getIdentifierInfo()->isStr("fr")) {
3957 if (SeenFr) {
3958 Diag(Tok, diag::err_omp_interop_multiple_fr);
3959 HasError = true;
3960 ConsumeToken(); // 'fr'
3961 SkipUntil(
3962 {tok::comma, tok::r_brace, tok::annot_pragma_openmp_end},
3964 continue;
3965 }
3966 SeenFr = true;
3967 ExprResult Fr = ParseOMPInteropFrSelector();
3968 if (Fr.isUsable())
3969 FrExpr = Fr.get();
3970 else
3971 HasError = true;
3972 } else if (Tok.is(tok::identifier) &&
3973 Tok.getIdentifierInfo()->isStr("attr")) {
3974 if (ParseOMPInteropAttrSelector(AttrExprs))
3975 HasError = true;
3976 } else {
3977 // Neither 'fr' nor 'attr' (a non-identifier or some other word).
3978 HasError = true;
3979 Diag(Tok, diag::err_omp_expected_fr_or_attr_selector);
3980 ConsumeToken();
3981 }
3982 if (Tok.is(tok::comma))
3983 ConsumeToken();
3984 }
3985 if (BT.consumeClose())
3986 HasError = true;
3987
3988 if (FrExpr || !AttrExprs.empty())
3989 InteropInfo.Prefs.emplace_back(FrExpr, AttrExprs);
3990 InteropInfo.HasPreferAttrs = true;
3991 } else {
3992 // OMP 5.1: flat foreign-runtime-id (string or int). Stored as a
3993 // pref-spec with Fr=expr and no attr() entries.
3994 SourceLocation Loc = Tok.getLocation();
3995 ExprResult LHS = ParseCastExpression(CastParseKind::AnyCastExpr);
3996 ExprResult PTExpr =
3997 ParseRHSOfBinaryExpression(LHS, prec::Conditional);
3998 PTExpr = Actions.ActOnFinishFullExpr(PTExpr.get(), Loc,
3999 /*DiscardedValue=*/false);
4000 if (PTExpr.isUsable()) {
4001 InteropInfo.Prefs.emplace_back(PTExpr.get(),
4002 llvm::SmallVector<Expr *, 2>{});
4003 } else {
4004 HasError = true;
4005 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4007 }
4008 }
4009
4010 if (Tok.is(tok::comma))
4011 ConsumeToken();
4012 }
4013 PT.consumeClose();
4014 } else {
4015 HasError = true;
4016 Diag(Tok, diag::err_omp_expected_interop_type);
4017 ConsumeToken();
4018 }
4019 if (!Tok.is(tok::comma))
4020 break;
4021 ConsumeToken();
4022 }
4023
4024 if (!HasError && !IsTarget && !IsTargetSync) {
4025 Diag(Tok, diag::err_omp_expected_interop_type);
4026 HasError = true;
4027 }
4028
4029 if (Kind == OMPC_init) {
4030 if (Tok.isNot(tok::colon) && (IsTarget || IsTargetSync))
4031 Diag(Tok, diag::warn_pragma_expected_colon) << "interop types";
4032 if (Tok.is(tok::colon))
4033 ConsumeToken();
4034 }
4035
4036 // As of OpenMP 5.1,there are two interop-types, "target" and
4037 // "targetsync". Either or both are allowed for a single interop.
4038 InteropInfo.IsTarget = IsTarget;
4039 InteropInfo.IsTargetSync = IsTargetSync;
4040
4041 return HasError;
4042}
4043
4044OMPClause *Parser::ParseOpenMPInteropClause(OpenMPClauseKind Kind,
4045 bool ParseOnly) {
4046 SourceLocation Loc = ConsumeToken();
4047 // Parse '('.
4048 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
4049 if (T.expectAndConsume(diag::err_expected_lparen_after,
4050 getOpenMPClauseName(Kind).data()))
4051 return nullptr;
4052
4053 bool InteropError = false;
4054 OMPInteropInfo InteropInfo;
4055 if (Kind == OMPC_init)
4056 InteropError = ParseOMPInteropInfo(InteropInfo, OMPC_init);
4057
4058 // Parse the variable.
4059 SourceLocation VarLoc = Tok.getLocation();
4060 ExprResult InteropVarExpr = ParseAssignmentExpression();
4061 if (!InteropVarExpr.isUsable()) {
4062 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4064 }
4065
4066 // Parse ')'.
4067 SourceLocation RLoc = Tok.getLocation();
4068 if (!T.consumeClose())
4069 RLoc = T.getCloseLocation();
4070
4071 if (ParseOnly || !InteropVarExpr.isUsable() || InteropError)
4072 return nullptr;
4073
4074 if (Kind == OMPC_init)
4075 return Actions.OpenMP().ActOnOpenMPInitClause(
4076 InteropVarExpr.get(), InteropInfo, Loc, T.getOpenLocation(), VarLoc,
4077 RLoc);
4078 if (Kind == OMPC_use)
4079 return Actions.OpenMP().ActOnOpenMPUseClause(
4080 InteropVarExpr.get(), Loc, T.getOpenLocation(), VarLoc, RLoc);
4081
4082 if (Kind == OMPC_destroy)
4083 return Actions.OpenMP().ActOnOpenMPDestroyClause(
4084 InteropVarExpr.get(), Loc, T.getOpenLocation(), VarLoc, RLoc);
4085
4086 llvm_unreachable("Unexpected interop variable clause.");
4087}
4088
4089OMPClause *Parser::ParseOpenMPOMPXAttributesClause(bool ParseOnly) {
4090 SourceLocation Loc = ConsumeToken();
4091 // Parse '('.
4092 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
4093 if (T.expectAndConsume(diag::err_expected_lparen_after,
4094 getOpenMPClauseName(OMPC_ompx_attribute).data()))
4095 return nullptr;
4096
4097 ParsedAttributes ParsedAttrs(AttrFactory);
4098 ParseAttributes(PAKM_GNU | PAKM_CXX11, ParsedAttrs);
4099
4100 // Parse ')'.
4101 if (T.consumeClose())
4102 return nullptr;
4103
4104 if (ParseOnly)
4105 return nullptr;
4106
4107 SmallVector<Attr *> Attrs;
4108 for (const ParsedAttr &PA : ParsedAttrs) {
4109 switch (PA.getKind()) {
4110 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
4111 if (!PA.checkExactlyNumArgs(Actions, 2))
4112 continue;
4113 if (auto *A = Actions.AMDGPU().CreateAMDGPUFlatWorkGroupSizeAttr(
4114 PA, PA.getArgAsExpr(0), PA.getArgAsExpr(1)))
4115 Attrs.push_back(A);
4116 continue;
4117 case ParsedAttr::AT_AMDGPUWavesPerEU:
4118 if (!PA.checkAtLeastNumArgs(Actions, 1) ||
4119 !PA.checkAtMostNumArgs(Actions, 2))
4120 continue;
4121 if (auto *A = Actions.AMDGPU().CreateAMDGPUWavesPerEUAttr(
4122 PA, PA.getArgAsExpr(0),
4123 PA.getNumArgs() > 1 ? PA.getArgAsExpr(1) : nullptr))
4124 Attrs.push_back(A);
4125 continue;
4126 case ParsedAttr::AT_CUDALaunchBounds:
4127 if (!PA.checkAtLeastNumArgs(Actions, 1) ||
4128 !PA.checkAtMostNumArgs(Actions, 3))
4129 continue;
4130 if (auto *A = Actions.CreateLaunchBoundsAttr(
4131 PA, PA.getArgAsExpr(0),
4132 PA.getNumArgs() > 1 ? PA.getArgAsExpr(1) : nullptr,
4133 PA.getNumArgs() > 2 ? PA.getArgAsExpr(2) : nullptr,
4134 /*IgnoreArch=*/true))
4135 Attrs.push_back(A);
4136 continue;
4137 default:
4138 Diag(Loc, diag::warn_omp_invalid_attribute_for_ompx_attributes) << PA;
4139 continue;
4140 };
4141 }
4142
4143 return Actions.OpenMP().ActOnOpenMPXAttributeClause(
4144 Attrs, Loc, T.getOpenLocation(), T.getCloseLocation());
4145}
4146
4147OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind,
4148 bool ParseOnly) {
4149 std::optional<SimpleClauseData> Val = parseOpenMPSimpleClause(*this, Kind);
4150 if (!Val || ParseOnly)
4151 return nullptr;
4152 if (getLangOpts().OpenMP < 51 && Kind == OMPC_default &&
4153 (static_cast<DefaultKind>(Val->Type) == OMP_DEFAULT_private ||
4154 static_cast<DefaultKind>(Val->Type) ==
4155 OMP_DEFAULT_firstprivate)) {
4156 Diag(Val->LOpen, diag::err_omp_invalid_dsa)
4157 << getOpenMPClauseName(static_cast<DefaultKind>(Val->Type) ==
4158 OMP_DEFAULT_private
4159 ? OMPC_private
4160 : OMPC_firstprivate)
4161 << getOpenMPClauseName(OMPC_default) << "5.1";
4162 return nullptr;
4163 }
4164 return Actions.OpenMP().ActOnOpenMPSimpleClause(
4165 Kind, Val->Type, Val->TypeLoc, Val->LOpen, Val->Loc, Val->RLoc);
4166}
4167
4168OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly) {
4169 SourceLocation Loc = Tok.getLocation();
4171
4172 if (ParseOnly)
4173 return nullptr;
4174 return Actions.OpenMP().ActOnOpenMPClause(Kind, Loc, Tok.getLocation());
4175}
4176
4177OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
4178 OpenMPClauseKind Kind,
4179 bool ParseOnly) {
4180 SourceLocation Loc = ConsumeToken();
4181 SourceLocation DelimLoc;
4182 // Parse '('.
4183 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
4184 if (T.expectAndConsume(diag::err_expected_lparen_after,
4185 getOpenMPClauseName(Kind).data()))
4186 return nullptr;
4187
4188 ExprResult Val;
4189 SmallVector<unsigned, 4> Arg;
4190 SmallVector<SourceLocation, 4> KLoc;
4191 if (Kind == OMPC_schedule) {
4192 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
4193 Arg.resize(NumberOfElements);
4194 KLoc.resize(NumberOfElements);
4195 Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown;
4196 Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown;
4197 Arg[ScheduleKind] = OMPC_SCHEDULE_unknown;
4198 unsigned KindModifier = getOpenMPSimpleClauseType(
4199 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
4200 if (KindModifier > OMPC_SCHEDULE_unknown) {
4201 // Parse 'modifier'
4202 Arg[Modifier1] = KindModifier;
4203 KLoc[Modifier1] = Tok.getLocation();
4204 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
4205 Tok.isNot(tok::annot_pragma_openmp_end))
4207 if (Tok.is(tok::comma)) {
4208 // Parse ',' 'modifier'
4210 KindModifier = getOpenMPSimpleClauseType(
4211 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
4212 Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown
4213 ? KindModifier
4215 KLoc[Modifier2] = Tok.getLocation();
4216 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
4217 Tok.isNot(tok::annot_pragma_openmp_end))
4219 }
4220 // Parse ':'
4221 if (Tok.is(tok::colon))
4223 else
4224 Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier";
4225 KindModifier = getOpenMPSimpleClauseType(
4226 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
4227 }
4228 Arg[ScheduleKind] = KindModifier;
4229 KLoc[ScheduleKind] = Tok.getLocation();
4230 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
4231 Tok.isNot(tok::annot_pragma_openmp_end))
4233 if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static ||
4234 Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic ||
4235 Arg[ScheduleKind] == OMPC_SCHEDULE_guided) &&
4236 Tok.is(tok::comma))
4237 DelimLoc = ConsumeAnyToken();
4238 } else if (Kind == OMPC_dist_schedule) {
4239 Arg.push_back(getOpenMPSimpleClauseType(
4240 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
4241 KLoc.push_back(Tok.getLocation());
4242 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
4243 Tok.isNot(tok::annot_pragma_openmp_end))
4245 if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma))
4246 DelimLoc = ConsumeAnyToken();
4247 } else if (Kind == OMPC_default) {
4248 // Get a default modifier
4249 unsigned Modifier = getOpenMPSimpleClauseType(
4250 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
4251
4252 Arg.push_back(Modifier);
4253 KLoc.push_back(Tok.getLocation());
4254 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
4255 Tok.isNot(tok::annot_pragma_openmp_end))
4257 // Parse ':'
4258 if (Tok.is(tok::colon) && getLangOpts().OpenMP >= 60) {
4260 // Get a variable-category attribute for default clause modifier
4261 OpenMPDefaultClauseVariableCategory VariableCategory =
4263 Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
4264 Arg.push_back(VariableCategory);
4265 KLoc.push_back(Tok.getLocation());
4266 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
4267 Tok.isNot(tok::annot_pragma_openmp_end))
4269 } else {
4270 Arg.push_back(OMPC_DEFAULT_VC_all);
4271 KLoc.push_back(SourceLocation());
4272 }
4273 } else if (Kind == OMPC_defaultmap) {
4274 // Get a defaultmap modifier
4275 unsigned Modifier = getOpenMPSimpleClauseType(
4276 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
4277
4278 // Set defaultmap modifier to unknown if it is either scalar, aggregate, or
4279 // pointer
4280 if (Modifier < OMPC_DEFAULTMAP_MODIFIER_unknown)
4282 Arg.push_back(Modifier);
4283 KLoc.push_back(Tok.getLocation());
4284 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
4285 Tok.isNot(tok::annot_pragma_openmp_end))
4287 // Parse ':'
4288 if (Tok.is(tok::colon) || getLangOpts().OpenMP < 50) {
4289 if (Tok.is(tok::colon))
4291 else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown)
4292 Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier";
4293 // Get a defaultmap kind
4294 Arg.push_back(getOpenMPSimpleClauseType(
4295 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
4296 KLoc.push_back(Tok.getLocation());
4297 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
4298 Tok.isNot(tok::annot_pragma_openmp_end))
4300 } else {
4301 Arg.push_back(OMPC_DEFAULTMAP_unknown);
4302 KLoc.push_back(SourceLocation());
4303 }
4304 } else if (Kind == OMPC_order) {
4305 enum { Modifier, OrderKind, NumberOfElements };
4306 Arg.resize(NumberOfElements);
4307 KLoc.resize(NumberOfElements);
4308 Arg[Modifier] = OMPC_ORDER_MODIFIER_unknown;
4309 Arg[OrderKind] = OMPC_ORDER_unknown;
4310 unsigned KindModifier = getOpenMPSimpleClauseType(
4311 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
4312 if (KindModifier > OMPC_ORDER_unknown) {
4313 // Parse 'modifier'
4314 Arg[Modifier] = KindModifier;
4315 KLoc[Modifier] = Tok.getLocation();
4316 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
4317 Tok.isNot(tok::annot_pragma_openmp_end))
4319 // Parse ':'
4320 if (Tok.is(tok::colon))
4322 else
4323 Diag(Tok, diag::warn_pragma_expected_colon) << "order modifier";
4324 KindModifier = getOpenMPSimpleClauseType(
4325 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
4326 }
4327 Arg[OrderKind] = KindModifier;
4328 KLoc[OrderKind] = Tok.getLocation();
4329 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
4330 Tok.isNot(tok::annot_pragma_openmp_end))
4332 } else if (Kind == OMPC_device) {
4333 // Only target executable directives support extended device construct.
4334 if (isOpenMPTargetExecutionDirective(DKind) && getLangOpts().OpenMP >= 50 &&
4335 NextToken().is(tok::colon)) {
4336 // Parse optional <device modifier> ':'
4337 Arg.push_back(getOpenMPSimpleClauseType(
4338 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
4339 KLoc.push_back(Tok.getLocation());
4341 // Parse ':'
4343 } else {
4344 Arg.push_back(OMPC_DEVICE_unknown);
4345 KLoc.emplace_back();
4346 }
4347 } else if (Kind == OMPC_grainsize) {
4348 // Parse optional <grainsize modifier> ':'
4351 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok),
4352 getLangOpts()));
4353 if (getLangOpts().OpenMP >= 51) {
4354 if (NextToken().is(tok::colon)) {
4355 Arg.push_back(Modifier);
4356 KLoc.push_back(Tok.getLocation());
4357 // Parse modifier
4359 // Parse ':'
4361 } else {
4362 if (Modifier == OMPC_GRAINSIZE_strict) {
4363 Diag(Tok, diag::err_modifier_expected_colon) << "strict";
4364 // Parse modifier
4366 }
4367 Arg.push_back(OMPC_GRAINSIZE_unknown);
4368 KLoc.emplace_back();
4369 }
4370 } else {
4371 Arg.push_back(OMPC_GRAINSIZE_unknown);
4372 KLoc.emplace_back();
4373 }
4374 } else if (Kind == OMPC_dyn_groupprivate) {
4375 enum { SimpleModifier, ComplexModifier, NumberOfModifiers };
4376 Arg.resize(NumberOfModifiers);
4377 KLoc.resize(NumberOfModifiers);
4378 Arg[SimpleModifier] = OMPC_DYN_GROUPPRIVATE_unknown;
4379 Arg[ComplexModifier] = OMPC_DYN_GROUPPRIVATE_FALLBACK_unknown;
4380
4381 auto ConsumeModifier = [&]() {
4382 unsigned Type = NumberOfModifiers;
4383 unsigned Modifier;
4384 SourceLocation Loc;
4385 if (!Tok.isAnnotation() && PP.getSpelling(Tok) == "fallback" &&
4386 NextToken().is(tok::l_paren)) {
4387 ConsumeToken();
4388 BalancedDelimiterTracker ParenT(*this, tok::l_paren, tok::r_paren);
4389 ParenT.consumeOpen();
4390
4391 Modifier = getOpenMPSimpleClauseType(
4392 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
4395 Diag(Tok.getLocation(), diag::err_expected)
4396 << "'abort', 'null' or 'default_mem' in fallback modifier";
4397 SkipUntil(tok::r_paren);
4398 return std::make_tuple(Type, Modifier, Loc);
4399 }
4400 Type = ComplexModifier;
4401 Loc = Tok.getLocation();
4402 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
4403 Tok.isNot(tok::annot_pragma_openmp_end))
4405 ParenT.consumeClose();
4406 } else {
4407 Modifier = getOpenMPSimpleClauseType(
4408 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
4409 if (Modifier < OMPC_DYN_GROUPPRIVATE_unknown) {
4410 Type = SimpleModifier;
4411 Loc = Tok.getLocation();
4412 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
4413 Tok.isNot(tok::annot_pragma_openmp_end))
4415 }
4416 }
4417 return std::make_tuple(Type, Modifier, Loc);
4418 };
4419
4420 auto SaveModifier = [&](unsigned Type, unsigned Modifier,
4421 SourceLocation Loc) {
4422 assert(Type < NumberOfModifiers && "Unexpected modifier type");
4423 if (!KLoc[Type].isValid()) {
4424 Arg[Type] = Modifier;
4425 KLoc[Type] = Loc;
4426 } else {
4427 Diag(Loc, diag::err_omp_incompatible_dyn_groupprivate_modifier)
4428 << getOpenMPSimpleClauseTypeName(OMPC_dyn_groupprivate, Modifier)
4429 << getOpenMPSimpleClauseTypeName(OMPC_dyn_groupprivate, Arg[Type]);
4430 }
4431 };
4432
4433 // Parse 'modifier'
4434 auto [Type1, Mod1, Loc1] = ConsumeModifier();
4435 if (Type1 < NumberOfModifiers) {
4436 SaveModifier(Type1, Mod1, Loc1);
4437 if (Tok.is(tok::comma)) {
4438 // Parse ',' 'modifier'
4440 auto [Type2, Mod2, Loc2] = ConsumeModifier();
4441 if (Type2 < NumberOfModifiers)
4442 SaveModifier(Type2, Mod2, Loc2);
4443 }
4444 // Parse ':'
4445 if (Tok.is(tok::colon))
4447 else
4448 Diag(Tok, diag::warn_pragma_expected_colon)
4449 << "dyn_groupprivate modifier";
4450 }
4451 } else if (Kind == OMPC_num_tasks) {
4452 // Parse optional <num_tasks modifier> ':'
4455 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok),
4456 getLangOpts()));
4457 if (getLangOpts().OpenMP >= 51) {
4458 if (NextToken().is(tok::colon)) {
4459 Arg.push_back(Modifier);
4460 KLoc.push_back(Tok.getLocation());
4461 // Parse modifier
4463 // Parse ':'
4465 } else {
4466 if (Modifier == OMPC_NUMTASKS_strict) {
4467 Diag(Tok, diag::err_modifier_expected_colon) << "strict";
4468 // Parse modifier
4470 }
4471 Arg.push_back(OMPC_NUMTASKS_unknown);
4472 KLoc.emplace_back();
4473 }
4474 } else {
4475 Arg.push_back(OMPC_NUMTASKS_unknown);
4476 KLoc.emplace_back();
4477 }
4478 } else {
4479 assert(Kind == OMPC_if);
4480 KLoc.push_back(Tok.getLocation());
4481 TentativeParsingAction TPA(*this);
4482 auto DK = parseOpenMPDirectiveKind(*this);
4483 Arg.push_back(static_cast<unsigned>(DK));
4484 if (DK != OMPD_unknown) {
4485 ConsumeToken();
4486 if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) {
4487 TPA.Commit();
4488 DelimLoc = ConsumeToken();
4489 } else {
4490 TPA.Revert();
4491 Arg.back() = unsigned(OMPD_unknown);
4492 }
4493 } else {
4494 TPA.Revert();
4495 }
4496 }
4497
4498 bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) ||
4499 (Kind == OMPC_dist_schedule && DelimLoc.isValid()) ||
4500 Kind == OMPC_if || Kind == OMPC_device ||
4501 Kind == OMPC_grainsize || Kind == OMPC_num_tasks ||
4502 Kind == OMPC_dyn_groupprivate;
4503 if (NeedAnExpression) {
4504 SourceLocation ELoc = Tok.getLocation();
4505 ExprResult LHS(
4506 ParseCastExpression(CastParseKind::AnyCastExpr, false,
4508 Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
4509 Val =
4510 Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
4511 }
4512
4513 // Parse ')'.
4514 SourceLocation RLoc = Tok.getLocation();
4515 if (!T.consumeClose())
4516 RLoc = T.getCloseLocation();
4517
4518 if (NeedAnExpression && Val.isInvalid())
4519 return nullptr;
4520
4521 if (Kind == OMPC_default && getLangOpts().OpenMP < 51 && Arg[0] &&
4522 (static_cast<DefaultKind>(Arg[0]) == OMP_DEFAULT_private ||
4523 static_cast<DefaultKind>(Arg[0]) == OMP_DEFAULT_firstprivate)) {
4524 Diag(KLoc[0], diag::err_omp_invalid_dsa)
4525 << getOpenMPClauseName(static_cast<DefaultKind>(Arg[0]) ==
4526 OMP_DEFAULT_private
4527 ? OMPC_private
4528 : OMPC_firstprivate)
4529 << getOpenMPClauseName(OMPC_default) << "5.1";
4530 return nullptr;
4531 }
4532
4533 if (ParseOnly)
4534 return nullptr;
4535 return Actions.OpenMP().ActOnOpenMPSingleExprWithArgClause(
4536 Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc, RLoc);
4537}
4538
4539static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec,
4540 UnqualifiedId &ReductionId) {
4541 if (ReductionIdScopeSpec.isEmpty()) {
4542 auto OOK = OO_None;
4543 switch (P.getCurToken().getKind()) {
4544 case tok::plus:
4545 OOK = OO_Plus;
4546 break;
4547 case tok::minus:
4548 OOK = OO_Minus;
4549 break;
4550 case tok::star:
4551 OOK = OO_Star;
4552 break;
4553 case tok::amp:
4554 OOK = OO_Amp;
4555 break;
4556 case tok::pipe:
4557 OOK = OO_Pipe;
4558 break;
4559 case tok::caret:
4560 OOK = OO_Caret;
4561 break;
4562 case tok::ampamp:
4563 OOK = OO_AmpAmp;
4564 break;
4565 case tok::pipepipe:
4566 OOK = OO_PipePipe;
4567 break;
4568 default:
4569 break;
4570 }
4571 if (OOK != OO_None) {
4572 SourceLocation OpLoc = P.ConsumeToken();
4573 SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()};
4574 ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations);
4575 return false;
4576 }
4577 }
4578 return P.ParseUnqualifiedId(
4579 ReductionIdScopeSpec, /*ObjectType=*/nullptr,
4580 /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
4581 /*AllowDestructorName*/ false,
4582 /*AllowConstructorName*/ false,
4583 /*AllowDeductionGuide*/ false, nullptr, ReductionId);
4584}
4585
4586/// Checks if the token is a valid map-type-modifier.
4587/// FIXME: It will return an OpenMPMapClauseKind if that's what it parses.
4589 Token Tok = P.getCurToken();
4590 if (!Tok.is(tok::identifier))
4592
4593 Preprocessor &PP = P.getPreprocessor();
4594 OpenMPMapModifierKind TypeModifier =
4596 OMPC_map, PP.getSpelling(Tok), P.getLangOpts()));
4597 return TypeModifier;
4598}
4599
4601 // Parse '('.
4602 BalancedDelimiterTracker T(*this, tok::l_paren, tok::colon);
4603 if (T.expectAndConsume(diag::err_expected_lparen_after, "mapper")) {
4604 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4606 return true;
4607 }
4608 // Parse mapper-identifier
4609 if (getLangOpts().CPlusPlus)
4610 ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
4611 /*ObjectType=*/nullptr,
4612 /*ObjectHasErrors=*/false,
4613 /*EnteringContext=*/false);
4614 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
4615 Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
4616 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4618 return true;
4619 }
4620 auto &DeclNames = Actions.getASTContext().DeclarationNames;
4621 Data.ReductionOrMapperId = DeclarationNameInfo(
4622 DeclNames.getIdentifier(Tok.getIdentifierInfo()), Tok.getLocation());
4623 ConsumeToken();
4624 // Parse ')'.
4625 return T.consumeClose();
4626}
4627
4629
4631 bool HasMapType = false;
4632 SourceLocation PreMapLoc = Tok.getLocation();
4633 StringRef PreMapName = "";
4634 while (getCurToken().isNot(tok::colon)) {
4635 OpenMPMapModifierKind TypeModifier = isMapModifier(*this);
4636 OpenMPMapClauseKind MapKind = isMapType(*this);
4637 if (TypeModifier == OMPC_MAP_MODIFIER_always ||
4638 TypeModifier == OMPC_MAP_MODIFIER_close ||
4639 TypeModifier == OMPC_MAP_MODIFIER_present ||
4640 TypeModifier == OMPC_MAP_MODIFIER_ompx_hold) {
4641 Data.MapTypeModifiers.push_back(TypeModifier);
4642 Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
4643 if (PP.LookAhead(0).isNot(tok::comma) &&
4644 PP.LookAhead(0).isNot(tok::colon) && getLangOpts().OpenMP >= 52)
4645 Diag(Tok.getLocation(), diag::err_omp_missing_comma)
4646 << "map type modifier";
4647 ConsumeToken();
4648 } else if (TypeModifier == OMPC_MAP_MODIFIER_mapper) {
4649 Data.MapTypeModifiers.push_back(TypeModifier);
4650 Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
4651 ConsumeToken();
4653 return true;
4654 if (Tok.isNot(tok::comma) && Tok.isNot(tok::colon) &&
4655 getLangOpts().OpenMP >= 52)
4656 Diag(Data.MapTypeModifiersLoc.back(), diag::err_omp_missing_comma)
4657 << "map type modifier";
4658
4659 } else if (getLangOpts().OpenMP >= 60 && MapKind != OMPC_MAP_unknown) {
4660 if (!HasMapType) {
4661 HasMapType = true;
4662 Data.ExtraModifier = MapKind;
4663 MapKind = OMPC_MAP_unknown;
4664 PreMapLoc = Tok.getLocation();
4665 PreMapName = Tok.getIdentifierInfo()->getName();
4666 } else {
4667 Diag(Tok, diag::err_omp_more_one_map_type);
4668 Diag(PreMapLoc, diag::note_previous_map_type_specified_here)
4669 << PreMapName;
4670 }
4671 ConsumeToken();
4672 } else if (TypeModifier == OMPC_MAP_MODIFIER_self) {
4673 Data.MapTypeModifiers.push_back(TypeModifier);
4674 Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
4675 if (PP.LookAhead(0).isNot(tok::comma) &&
4676 PP.LookAhead(0).isNot(tok::colon))
4677 Diag(Tok.getLocation(), diag::err_omp_missing_comma)
4678 << "map type modifier";
4679 if (getLangOpts().OpenMP < 60)
4680 Diag(Tok, diag::err_omp_unknown_map_type_modifier)
4681 << (getLangOpts().OpenMP >= 51
4682 ? (getLangOpts().OpenMP >= 52 ? 2 : 1)
4683 : 0)
4684 << getLangOpts().OpenMPExtensions << 0;
4685 ConsumeToken();
4686 } else {
4687 // For the case of unknown map-type-modifier or a map-type.
4688 // Map-type is followed by a colon; the function returns when it
4689 // encounters a token followed by a colon.
4690 if (Tok.is(tok::comma)) {
4691 Diag(Tok, diag::err_omp_map_type_modifier_missing);
4692 ConsumeToken();
4693 continue;
4694 }
4695 // Potential map-type token as it is followed by a colon.
4696 if (PP.LookAhead(0).is(tok::colon)) {
4697 if (getLangOpts().OpenMP >= 60) {
4698 break;
4699 } else {
4700 return false;
4701 }
4702 }
4703
4704 Diag(Tok, diag::err_omp_unknown_map_type_modifier)
4705 << (getLangOpts().OpenMP >= 51 ? (getLangOpts().OpenMP >= 52 ? 2 : 1)
4706 : 0)
4707 << getLangOpts().OpenMPExtensions
4708 << (getLangOpts().OpenMP >= 60 ? 1 : 0);
4709 ConsumeToken();
4710 }
4711 if (getCurToken().is(tok::comma))
4712 ConsumeToken();
4713 }
4714 if (getLangOpts().OpenMP >= 60 && !HasMapType) {
4715 if (!Tok.is(tok::colon)) {
4716 Diag(Tok, diag::err_omp_unknown_map_type);
4717 ConsumeToken();
4718 } else {
4719 Data.ExtraModifier = OMPC_MAP_unknown;
4720 }
4721 }
4722 return false;
4723}
4724
4725/// Checks if the token is a valid map-type.
4726/// If it is not MapType kind, OMPC_MAP_unknown is returned.
4728 Token Tok = P.getCurToken();
4729 // The map-type token can be either an identifier or the C++ delete keyword.
4730 if (!Tok.isOneOf(tok::identifier, tok::kw_delete))
4731 return OMPC_MAP_unknown;
4732 Preprocessor &PP = P.getPreprocessor();
4733 unsigned MapType =
4735 if (MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
4736 MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc ||
4737 MapType == OMPC_MAP_delete || MapType == OMPC_MAP_release)
4738 return static_cast<OpenMPMapClauseKind>(MapType);
4739 return OMPC_MAP_unknown;
4740}
4741
4742/// Parse map-type in map clause.
4743/// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
4744/// where, map-type ::= to | from | tofrom | alloc | release | delete
4746 Token Tok = P.getCurToken();
4747 if (Tok.is(tok::colon)) {
4748 P.Diag(Tok, diag::err_omp_map_type_missing);
4749 return;
4750 }
4751 Data.ExtraModifier = isMapType(P);
4752 if (Data.ExtraModifier == OMPC_MAP_unknown)
4753 P.Diag(Tok, diag::err_omp_unknown_map_type);
4754 P.ConsumeToken();
4755}
4756
4757ExprResult Parser::ParseOpenMPIteratorsExpr() {
4758 assert(Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator" &&
4759 "Expected 'iterator' token.");
4760 SourceLocation IteratorKwLoc = ConsumeToken();
4761
4762 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
4763 if (T.expectAndConsume(diag::err_expected_lparen_after, "iterator"))
4764 return ExprError();
4765
4766 SourceLocation LLoc = T.getOpenLocation();
4767 SmallVector<SemaOpenMP::OMPIteratorData, 4> Data;
4768 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
4769 // Check if the type parsing is required.
4770 ParsedType IteratorType;
4771 if (Tok.isNot(tok::identifier) || NextToken().isNot(tok::equal)) {
4772 // identifier '=' is not found - parse type.
4774 if (TR.isInvalid()) {
4775 T.skipToEnd();
4776 return ExprError();
4777 }
4778 IteratorType = TR.get();
4779 }
4780
4781 // Parse identifier.
4782 IdentifierInfo *II = nullptr;
4783 SourceLocation IdLoc;
4784 if (Tok.is(tok::identifier)) {
4785 II = Tok.getIdentifierInfo();
4786 IdLoc = ConsumeToken();
4787 } else {
4788 Diag(Tok, diag::err_expected_unqualified_id) << 0;
4789 }
4790
4791 // Parse '='.
4792 SourceLocation AssignLoc;
4793 if (Tok.is(tok::equal))
4794 AssignLoc = ConsumeToken();
4795 else
4796 Diag(Tok, diag::err_omp_expected_equal_in_iterator);
4797
4798 // Parse range-specification - <begin> ':' <end> [ ':' <step> ]
4799 ColonProtectionRAIIObject ColonRAII(*this);
4800 // Parse <begin>
4801 SourceLocation Loc = Tok.getLocation();
4802 ExprResult LHS = ParseCastExpression(CastParseKind::AnyCastExpr);
4803 ExprResult Begin = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
4804 Begin = Actions.ActOnFinishFullExpr(Begin.get(), Loc,
4805 /*DiscardedValue=*/false);
4806 // Parse ':'.
4807 SourceLocation ColonLoc;
4808 if (Tok.is(tok::colon))
4809 ColonLoc = ConsumeToken();
4810
4811 // Parse <end>
4812 Loc = Tok.getLocation();
4813 LHS = ParseCastExpression(CastParseKind::AnyCastExpr);
4814 ExprResult End = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
4815 End = Actions.ActOnFinishFullExpr(End.get(), Loc,
4816 /*DiscardedValue=*/false);
4817
4818 SourceLocation SecColonLoc;
4819 ExprResult Step;
4820 // Parse optional step.
4821 if (Tok.is(tok::colon)) {
4822 // Parse ':'
4823 SecColonLoc = ConsumeToken();
4824 // Parse <step>
4825 Loc = Tok.getLocation();
4826 LHS = ParseCastExpression(CastParseKind::AnyCastExpr);
4827 Step = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
4828 Step = Actions.ActOnFinishFullExpr(Step.get(), Loc,
4829 /*DiscardedValue=*/false);
4830 }
4831
4832 // Parse ',' or ')'
4833 if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren))
4834 Diag(Tok, diag::err_omp_expected_punc_after_iterator);
4835 if (Tok.is(tok::comma))
4836 ConsumeToken();
4837
4838 SemaOpenMP::OMPIteratorData &D = Data.emplace_back();
4839 D.DeclIdent = II;
4840 D.DeclIdentLoc = IdLoc;
4841 D.Type = IteratorType;
4842 D.AssignLoc = AssignLoc;
4843 D.ColonLoc = ColonLoc;
4844 D.SecColonLoc = SecColonLoc;
4845 D.Range.Begin = Begin.get();
4846 D.Range.End = End.get();
4847 D.Range.Step = Step.get();
4848 }
4849
4850 // Parse ')'.
4851 SourceLocation RLoc = Tok.getLocation();
4852 if (!T.consumeClose())
4853 RLoc = T.getCloseLocation();
4854
4855 return Actions.OpenMP().ActOnOMPIteratorExpr(getCurScope(), IteratorKwLoc,
4856 LLoc, RLoc, Data);
4857}
4858
4861 const LangOptions &LangOpts) {
4862 // Currently the only reserved locator is 'omp_all_memory' which is only
4863 // allowed on a depend clause.
4864 if (Kind != OMPC_depend || LangOpts.OpenMP < 51)
4865 return false;
4866
4867 if (Tok.is(tok::identifier) &&
4868 Tok.getIdentifierInfo()->isStr("omp_all_memory")) {
4869
4870 if (Data.ExtraModifier == OMPC_DEPEND_outallmemory ||
4871 Data.ExtraModifier == OMPC_DEPEND_inoutallmemory)
4872 Diag(Tok, diag::warn_omp_more_one_omp_all_memory);
4873 else if (Data.ExtraModifier != OMPC_DEPEND_out &&
4874 Data.ExtraModifier != OMPC_DEPEND_inout)
4875 Diag(Tok, diag::err_omp_requires_out_inout_depend_type);
4876 else
4877 Data.ExtraModifier = Data.ExtraModifier == OMPC_DEPEND_out
4878 ? OMPC_DEPEND_outallmemory
4879 : OMPC_DEPEND_inoutallmemory;
4880 ConsumeToken();
4881 return true;
4882 }
4883 return false;
4884}
4885
4887 // 'omp_num_args' is recognised by spelling: OpenMP 6.0 [5.2.1] gives it no
4888 // declaration, so it is never looked up.
4889 if (Tok.isNot(tok::identifier) ||
4890 !Tok.getIdentifierInfo()->isStr("omp_num_args")) {
4892 if (E.isInvalid())
4893 return true;
4894 E = Actions.ActOnFinishFullExpr(E.get(), E.get()->getExprLoc(),
4895 /*DiscardedValue=*/false);
4896 if (E.isInvalid())
4897 return true;
4899 Bound.E = E.get();
4900 return false;
4901 }
4902
4904 ConsumeToken();
4905 if (Tok.isOneOf(tok::plus, tok::minus)) {
4906 Bound.IsSubtraction = Tok.is(tok::minus);
4907 ConsumeToken();
4908 // OpenMP 6.0 [5.2.1]: the logical offset is a constant expression.
4910 if (Offset.isInvalid())
4911 return true;
4912 Bound.E = Offset.get();
4913 }
4914 // 'omp_num_args' is a whole bound, not an operand of a larger expression, so
4915 // nothing else may follow it.
4916 if (!Tok.isOneOf(tok::colon, tok::comma, tok::r_paren,
4917 tok::annot_pragma_openmp_end)) {
4918 Diag(Tok, diag::err_omp_num_args_invalid_form) << 1;
4919 return true;
4920 }
4921 return false;
4922}
4923
4926 bool IsError = false;
4927 ColonProtectionRAIIObject ColonRAII(*this);
4928 while (true) {
4929 SourceLocation ItemLoc = Tok.getLocation();
4930 // An omitted lower bound stands for 1, and is written as a leading ':'.
4931 OMPAdjustArgsItem::Bound LowerBound;
4932 bool ItemError = false;
4933 if (Tok.isNot(tok::colon)) {
4934 ItemError = ParseOpenMPAdjustArgsBound(LowerBound);
4935 if (ItemError) {
4936 IsError = true;
4937 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4939 }
4940 }
4941
4942 if (Tok.is(tok::colon)) {
4943 ConsumeToken();
4944 // An omitted upper bound stands for 'omp_num_args'.
4945 OMPAdjustArgsItem::Bound UpperBound;
4946 if (!Tok.isOneOf(tok::comma, tok::r_paren,
4947 tok::annot_pragma_openmp_end)) {
4948 if (ParseOpenMPAdjustArgsBound(UpperBound)) {
4949 ItemError = true;
4950 IsError = true;
4951 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4953 }
4954 }
4955 if (!ItemError) {
4956 OMPAdjustArgsItem Item;
4958 Item.Lower = LowerBound;
4959 Item.Upper = UpperBound;
4960 Items.push_back(Item);
4961 }
4962 } else if (!ItemError &&
4964 // Without a colon the item is a parameter name or a position, and is
4965 // stored as a regular expression.
4966 if (LowerBound.Kind == OMPAdjustArgsItem::Bound::NumArgs) {
4967 Diag(ItemLoc, diag::err_omp_num_args_invalid_form) << 0;
4968 IsError = true;
4969 } else {
4970 OMPAdjustArgsItem Item;
4971 Item.E = LowerBound.E;
4972 Items.push_back(Item);
4973 }
4974 }
4975
4976 // Separator handling mirrors the shared var-list loop, so that a malformed
4977 // item such as '1:2:3' diagnoses instead of silently mis-parsing.
4978 if (Tok.isNot(tok::comma)) {
4979 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
4980 Diag(Tok, diag::err_omp_expected_punc)
4981 << getOpenMPClauseName(OMPC_adjust_args) << /*IsDirective=*/0;
4982 IsError = true;
4983 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4985 }
4986 if (Tok.isNot(tok::comma))
4987 break;
4988 }
4989 ConsumeToken();
4990 }
4991 return IsError;
4992}
4993
4994/// Parse step size expression. Returns true if parsing is successfull,
4995/// otherwise returns false.
4997 OpenMPClauseKind CKind, SourceLocation ELoc) {
4999 Sema &Actions = P.getActions();
5000 Tail = Actions.ActOnFinishFullExpr(Tail.get(), ELoc,
5001 /*DiscardedValue*/ false);
5002 if (Tail.isUsable()) {
5003 Data.DepModOrTailExpr = Tail.get();
5004 Token CurTok = P.getCurToken();
5005 if (CurTok.isNot(tok::r_paren) && CurTok.isNot(tok::comma)) {
5006 P.Diag(CurTok, diag::err_expected_punc) << "step expression";
5007 }
5008 return true;
5009 }
5010 return false;
5011}
5012
5013/// Parse 'allocate' clause modifiers.
5014/// If allocator-modifier exists, return an expression for it. For both
5015/// allocator and align modifiers, set Data fields as appropriate.
5016static ExprResult
5019 const Token &Tok = P.getCurToken();
5020 Preprocessor &PP = P.getPreprocessor();
5021 ExprResult Tail;
5022 ExprResult Val;
5023 SourceLocation RLoc;
5024 bool AllocatorSeen = false;
5025 bool AlignSeen = false;
5026 SourceLocation CurrentModifierLoc = Tok.getLocation();
5027 auto CurrentModifier = static_cast<OpenMPAllocateClauseModifier>(
5029
5030 // Modifiers did not exist before 5.1
5031 if (P.getLangOpts().OpenMP < 51)
5032 return P.ParseAssignmentExpression();
5033
5034 // An allocator-simple-modifier is exclusive and must appear alone. See
5035 // OpenMP6.0 spec, pg. 313, L1 on Modifiers, as well as Table 5.1, pg. 50,
5036 // description of "exclusive" property. If we don't recognized an explicit
5037 // simple-/complex- modifier, assume we're looking at expression
5038 // representing allocator and consider ourselves done.
5039 if (CurrentModifier == OMPC_ALLOCATE_unknown)
5040 return P.ParseAssignmentExpression();
5041
5042 do {
5043 P.ConsumeToken();
5044 if (Tok.is(tok::l_paren)) {
5045 switch (CurrentModifier) {
5046 case OMPC_ALLOCATE_allocator: {
5047 if (AllocatorSeen) {
5048 P.Diag(Tok, diag::err_omp_duplicate_modifier)
5049 << getOpenMPSimpleClauseTypeName(OMPC_allocate, CurrentModifier)
5050 << getOpenMPClauseName(Kind);
5051 } else {
5052 Data.AllocClauseModifiers.push_back(CurrentModifier);
5053 Data.AllocClauseModifiersLoc.push_back(CurrentModifierLoc);
5054 }
5055 BalancedDelimiterTracker AllocateT(P, tok::l_paren,
5056 tok::annot_pragma_openmp_end);
5057 AllocateT.consumeOpen();
5058 Tail = P.ParseAssignmentExpression();
5059 AllocateT.consumeClose();
5060 AllocatorSeen = true;
5061 break;
5062 }
5063 case OMPC_ALLOCATE_align: {
5064 if (AlignSeen) {
5065 P.Diag(Tok, diag::err_omp_duplicate_modifier)
5066 << getOpenMPSimpleClauseTypeName(OMPC_allocate, CurrentModifier)
5067 << getOpenMPClauseName(Kind);
5068 } else {
5069 Data.AllocClauseModifiers.push_back(CurrentModifier);
5070 Data.AllocClauseModifiersLoc.push_back(CurrentModifierLoc);
5071 }
5072 Val = P.ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
5073 if (Val.isUsable())
5074 Data.AllocateAlignment = Val.get();
5075 AlignSeen = true;
5076 break;
5077 }
5078 default:
5079 llvm_unreachable("Unexpected allocate modifier");
5080 }
5081 } else {
5082 P.Diag(Tok, diag::err_expected) << tok::l_paren;
5083 }
5084 if (Tok.isNot(tok::comma))
5085 break;
5086 P.ConsumeToken();
5087 CurrentModifierLoc = Tok.getLocation();
5088 CurrentModifier = static_cast<OpenMPAllocateClauseModifier>(
5090 // A modifier followed by a comma implies another modifier.
5091 if (CurrentModifier == OMPC_ALLOCATE_unknown) {
5092 P.Diag(Tok, diag::err_omp_expected_modifier) << getOpenMPClauseName(Kind);
5093 break;
5094 }
5095 } while (!AllocatorSeen || !AlignSeen);
5096 return Tail;
5097}
5098
5102 SmallVectorImpl<OMPAdjustArgsItem> &AdjustArgsItems) {
5103 UnqualifiedId UnqualifiedReductionId;
5104 bool InvalidReductionId = false;
5105 bool IsInvalidMapperModifier = false;
5106
5107 // Parse '('.
5108 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
5109 if (T.expectAndConsume(diag::err_expected_lparen_after,
5110 getOpenMPClauseName(Kind).data()))
5111 return true;
5112
5113 bool HasIterator = false;
5114 bool InvalidIterator = false;
5115 bool NeedRParenForLinear = false;
5116 // Set when the OpenMP 6.0 'adjust_args' parameter list has already been
5117 // parsed by ParseOpenMPAdjustArgsList, so the shared list loop must be
5118 // skipped.
5119 bool ParsedAdjustArgsList = false;
5120 bool InvalidAdjustArgsList = false;
5121 BalancedDelimiterTracker LinearT(*this, tok::l_paren,
5122 tok::annot_pragma_openmp_end);
5123 // Handle reduction-identifier for reduction clause.
5124 if (Kind == OMPC_reduction || Kind == OMPC_task_reduction ||
5125 Kind == OMPC_in_reduction) {
5126 Data.ExtraModifier = OMPC_REDUCTION_unknown;
5127 if (Kind == OMPC_reduction && getLangOpts().OpenMP >= 50 &&
5128 (Tok.is(tok::identifier) || Tok.is(tok::kw_default)) &&
5129 NextToken().is(tok::comma)) {
5130 // Parse optional reduction modifier.
5131 Data.ExtraModifier =
5132 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
5133 Data.ExtraModifierLoc = Tok.getLocation();
5134 ConsumeToken();
5135 assert(Tok.is(tok::comma) && "Expected comma.");
5136 (void)ConsumeToken();
5137 }
5138 // Handle original(private / shared) Modifier
5139 if (Kind == OMPC_reduction && getLangOpts().OpenMP >= 60 &&
5140 Tok.is(tok::identifier) && PP.getSpelling(Tok) == "original" &&
5141 NextToken().is(tok::l_paren)) {
5142 // Parse original(private) modifier.
5143 ConsumeToken();
5144 BalancedDelimiterTracker ParenT(*this, tok::l_paren, tok::r_paren);
5145 ParenT.consumeOpen();
5146 if (Tok.is(tok::kw_private)) {
5147 Data.OriginalSharingModifier = OMPC_ORIGINAL_SHARING_private;
5148 Data.OriginalSharingModifierLoc = Tok.getLocation();
5149 ConsumeToken();
5150 } else if (Tok.is(tok::identifier) &&
5151 (PP.getSpelling(Tok) == "shared" ||
5152 PP.getSpelling(Tok) == "default")) {
5153 Data.OriginalSharingModifier = OMPC_ORIGINAL_SHARING_shared;
5154 Data.OriginalSharingModifierLoc = Tok.getLocation();
5155 ConsumeToken();
5156 } else {
5157 Diag(Tok.getLocation(), diag::err_expected)
5158 << "'private or shared or default'";
5159 SkipUntil(tok::r_paren);
5160 return false;
5161 }
5162 ParenT.consumeClose();
5163 if (!Tok.is(tok::comma)) {
5164 Diag(Tok.getLocation(), diag::err_expected) << "',' (comma)";
5165 return false;
5166 }
5167 (void)ConsumeToken();
5168 }
5169 ColonProtectionRAIIObject ColonRAII(*this);
5170 if (getLangOpts().CPlusPlus)
5171 ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
5172 /*ObjectType=*/nullptr,
5173 /*ObjectHasErrors=*/false,
5174 /*EnteringContext=*/false);
5175 InvalidReductionId = ParseReductionId(
5176 *this, Data.ReductionOrMapperIdScopeSpec, UnqualifiedReductionId);
5177 if (InvalidReductionId) {
5178 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
5180 }
5181 if (Tok.is(tok::colon))
5182 Data.ColonLoc = ConsumeToken();
5183 else
5184 Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier";
5185 if (!InvalidReductionId)
5186 Data.ReductionOrMapperId =
5187 Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId);
5188 } else if (Kind == OMPC_depend || Kind == OMPC_doacross) {
5189 if (getLangOpts().OpenMP >= 50) {
5190 if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator") {
5191 // Handle optional dependence modifier.
5192 // iterator(iterators-definition)
5193 // where iterators-definition is iterator-specifier [,
5194 // iterators-definition ]
5195 // where iterator-specifier is [ iterator-type ] identifier =
5196 // range-specification
5197 HasIterator = true;
5199 ExprResult IteratorRes = ParseOpenMPIteratorsExpr();
5200 Data.DepModOrTailExpr = IteratorRes.get();
5201 // Parse ','
5202 ExpectAndConsume(tok::comma);
5203 }
5204 }
5205 // Handle dependency type for depend clause.
5206 ColonProtectionRAIIObject ColonRAII(*this);
5207 Data.ExtraModifier = getOpenMPSimpleClauseType(
5208 Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
5209 getLangOpts());
5210 Data.ExtraModifierLoc = Tok.getLocation();
5211 if ((Kind == OMPC_depend && Data.ExtraModifier == OMPC_DEPEND_unknown) ||
5212 (Kind == OMPC_doacross &&
5213 Data.ExtraModifier == OMPC_DOACROSS_unknown)) {
5214 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
5216 } else {
5217 ConsumeToken();
5218 // Special processing for depend(source) clause.
5219 if (DKind == OMPD_ordered_standalone && Kind == OMPC_depend &&
5220 Data.ExtraModifier == OMPC_DEPEND_source) {
5221 // Parse ')'.
5222 T.consumeClose();
5223 return false;
5224 }
5225 }
5226 if (Tok.is(tok::colon)) {
5227 Data.ColonLoc = ConsumeToken();
5228 } else if (Kind != OMPC_doacross || Tok.isNot(tok::r_paren)) {
5229 Diag(Tok, DKind == OMPD_ordered_standalone
5230 ? diag::warn_pragma_expected_colon_r_paren
5231 : diag::warn_pragma_expected_colon)
5232 << (Kind == OMPC_depend ? "dependency type" : "dependence-type");
5233 }
5234 if (Kind == OMPC_doacross) {
5235 if (Tok.is(tok::identifier) &&
5236 Tok.getIdentifierInfo()->isStr("omp_cur_iteration")) {
5237 Data.ExtraModifier = Data.ExtraModifier == OMPC_DOACROSS_source
5238 ? OMPC_DOACROSS_source_omp_cur_iteration
5239 : OMPC_DOACROSS_sink_omp_cur_iteration;
5240 ConsumeToken();
5241 }
5242 if (Data.ExtraModifier == OMPC_DOACROSS_sink_omp_cur_iteration) {
5243 if (Tok.isNot(tok::minus)) {
5244 Diag(Tok, diag::err_omp_sink_and_source_iteration_not_allowd)
5245 << getOpenMPClauseName(Kind) << 0 << 0;
5246 SkipUntil(tok::r_paren);
5247 return false;
5248 } else {
5249 ConsumeToken();
5250 SourceLocation Loc = Tok.getLocation();
5251 uint64_t Value = 0;
5252 if (Tok.isNot(tok::numeric_constant) ||
5253 (PP.parseSimpleIntegerLiteral(Tok, Value) && Value != 1)) {
5254 Diag(Loc, diag::err_omp_sink_and_source_iteration_not_allowd)
5255 << getOpenMPClauseName(Kind) << 0 << 0;
5256 SkipUntil(tok::r_paren);
5257 return false;
5258 }
5259 }
5260 }
5261 if (Data.ExtraModifier == OMPC_DOACROSS_source_omp_cur_iteration) {
5262 if (Tok.isNot(tok::r_paren)) {
5263 Diag(Tok, diag::err_omp_sink_and_source_iteration_not_allowd)
5264 << getOpenMPClauseName(Kind) << 1 << 1;
5265 SkipUntil(tok::r_paren);
5266 return false;
5267 }
5268 }
5269 // Only the 'sink' case has the expression list.
5270 if (Kind == OMPC_doacross &&
5271 (Data.ExtraModifier == OMPC_DOACROSS_source ||
5272 Data.ExtraModifier == OMPC_DOACROSS_source_omp_cur_iteration ||
5273 Data.ExtraModifier == OMPC_DOACROSS_sink_omp_cur_iteration)) {
5274 // Parse ')'.
5275 T.consumeClose();
5276 return false;
5277 }
5278 }
5279 } else if (Kind == OMPC_linear) {
5280 // Try to parse modifier if any.
5281 Data.ExtraModifier = OMPC_LINEAR_val;
5282 if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) {
5283 Data.ExtraModifier =
5284 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
5285 Data.ExtraModifierLoc = ConsumeToken();
5286 LinearT.consumeOpen();
5287 NeedRParenForLinear = true;
5288 if (getLangOpts().OpenMP >= 52)
5289 Diag(Data.ExtraModifierLoc, diag::err_omp_deprecate_old_syntax)
5290 << "linear-modifier(list)" << getOpenMPClauseName(Kind)
5291 << "linear(list: [linear-modifier,] step(step-size))";
5292 }
5293 } else if (Kind == OMPC_lastprivate) {
5294 // Try to parse modifier if any.
5295 Data.ExtraModifier = OMPC_LASTPRIVATE_unknown;
5296 // Conditional modifier allowed only in OpenMP 5.0 and not supported in
5297 // distribute and taskloop based directives.
5298 if ((getLangOpts().OpenMP >= 50 && !isOpenMPDistributeDirective(DKind) &&
5299 !isOpenMPTaskLoopDirective(DKind)) &&
5300 Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::colon)) {
5301 Data.ExtraModifier =
5302 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
5303 Data.ExtraModifierLoc = Tok.getLocation();
5304 ConsumeToken();
5305 assert(Tok.is(tok::colon) && "Expected colon.");
5306 Data.ColonLoc = ConsumeToken();
5307 }
5308 } else if (Kind == OMPC_map) {
5309 // Handle optional iterator map modifier.
5310 if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator") {
5311 HasIterator = true;
5313 Data.MapTypeModifiers.push_back(OMPC_MAP_MODIFIER_iterator);
5314 Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
5315 ExprResult IteratorRes = ParseOpenMPIteratorsExpr();
5316 Data.IteratorExpr = IteratorRes.get();
5317 // Parse ','
5318 ExpectAndConsume(tok::comma);
5319 if (getLangOpts().OpenMP < 52) {
5320 Diag(Tok, diag::err_omp_unknown_map_type_modifier)
5321 << (getLangOpts().OpenMP >= 51 ? 1 : 0)
5322 << getLangOpts().OpenMPExtensions << 0;
5323 InvalidIterator = true;
5324 }
5325 }
5326 // Handle map type for map clause.
5327 ColonProtectionRAIIObject ColonRAII(*this);
5328
5329 // The first identifier may be a list item, a map-type or a
5330 // map-type-modifier. The map-type can also be delete which has the same
5331 // spelling of the C++ delete keyword.
5332 Data.ExtraModifier = OMPC_MAP_unknown;
5333 Data.ExtraModifierLoc = Tok.getLocation();
5334
5335 // Check for presence of a colon in the map clause.
5336 TentativeParsingAction TPA(*this);
5337 bool ColonPresent = false;
5338 if (SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
5339 StopBeforeMatch)) {
5340 if (Tok.is(tok::colon))
5341 ColonPresent = true;
5342 }
5343 TPA.Revert();
5344 // Only parse map-type-modifier[s] and map-type if a colon is present in
5345 // the map clause.
5346 if (ColonPresent) {
5347 if (getLangOpts().OpenMP >= 60 && getCurToken().is(tok::colon))
5348 Diag(Tok, diag::err_omp_map_modifier_specification_list);
5349 IsInvalidMapperModifier = parseMapTypeModifiers(Data);
5350 if (getLangOpts().OpenMP < 60 && !IsInvalidMapperModifier)
5351 parseMapType(*this, Data);
5352 else
5353 SkipUntil(tok::colon, tok::annot_pragma_openmp_end, StopBeforeMatch);
5354 }
5355 if (Data.ExtraModifier == OMPC_MAP_unknown) {
5356 Data.ExtraModifier = OMPC_MAP_tofrom;
5357 if (getLangOpts().OpenMP >= 52) {
5358 if (DKind == OMPD_target_enter_data)
5359 Data.ExtraModifier = OMPC_MAP_to;
5360 else if (DKind == OMPD_target_exit_data)
5361 Data.ExtraModifier = OMPC_MAP_from;
5362 }
5363 Data.IsMapTypeImplicit = true;
5364 }
5365
5366 if (Tok.is(tok::colon))
5367 Data.ColonLoc = ConsumeToken();
5368 } else if (Kind == OMPC_to || Kind == OMPC_from) {
5369 while (Tok.is(tok::identifier)) {
5370 auto Modifier = static_cast<OpenMPMotionModifierKind>(
5371 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts()));
5372 if (Modifier == OMPC_MOTION_MODIFIER_unknown)
5373 break;
5374 Data.MotionModifiers.push_back(Modifier);
5375 Data.MotionModifiersLoc.push_back(Tok.getLocation());
5376 if (PP.getSpelling(Tok) == "iterator" && getLangOpts().OpenMP >= 51) {
5377 ExprResult Tail;
5378 Tail = ParseOpenMPIteratorsExpr();
5379 Tail = Actions.ActOnFinishFullExpr(Tail.get(), T.getOpenLocation(),
5380 /*DiscardedValue=*/false);
5381 if (Tail.isUsable())
5382 Data.IteratorExpr = Tail.get();
5383 } else {
5384 ConsumeToken();
5385 if (Modifier == OMPC_MOTION_MODIFIER_mapper) {
5386 IsInvalidMapperModifier = parseMapperModifier(Data);
5387 if (IsInvalidMapperModifier)
5388 break;
5389 }
5390 // OpenMP < 5.1 doesn't permit a ',' or additional modifiers.
5391 if (getLangOpts().OpenMP < 51)
5392 break;
5393 // OpenMP 5.1 accepts an optional ',' even if the next character is ':'.
5394 // TODO: Is that intentional?
5395 if (Tok.is(tok::comma))
5396 ConsumeToken();
5397 }
5398 }
5399 if (!Data.MotionModifiers.empty() && Tok.isNot(tok::colon)) {
5400 if (!IsInvalidMapperModifier) {
5401 if (getLangOpts().OpenMP < 51)
5402 Diag(Tok, diag::warn_pragma_expected_colon) << ")";
5403 else
5404 Diag(Tok, diag::warn_pragma_expected_colon) << "motion modifier";
5405 }
5406 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
5408 }
5409 // OpenMP 5.1 permits a ':' even without a preceding modifier. TODO: Is
5410 // that intentional?
5411 if ((!Data.MotionModifiers.empty() || getLangOpts().OpenMP >= 51) &&
5412 Tok.is(tok::colon))
5413 Data.ColonLoc = ConsumeToken();
5414 } else if (Kind == OMPC_allocate ||
5415 (Kind == OMPC_affinity && Tok.is(tok::identifier) &&
5416 PP.getSpelling(Tok) == "iterator")) {
5417 // Handle optional allocator and align modifiers followed by colon
5418 // delimiter.
5419 ColonProtectionRAIIObject ColonRAII(*this);
5420 TentativeParsingAction TPA(*this);
5421 // OpenMP 5.0, 2.10.1, task Construct.
5422 // where aff-modifier is one of the following:
5423 // iterator(iterators-definition)
5424 ExprResult Tail;
5425 if (Kind == OMPC_allocate) {
5426 Tail = parseOpenMPAllocateClauseModifiers(*this, Kind, Data);
5427 } else {
5428 HasIterator = true;
5430 Tail = ParseOpenMPIteratorsExpr();
5431 }
5432 Tail = Actions.ActOnFinishFullExpr(Tail.get(), T.getOpenLocation(),
5433 /*DiscardedValue=*/false);
5434 if (Tail.isUsable() || Data.AllocateAlignment) {
5435 if (Tok.is(tok::colon)) {
5436 Data.DepModOrTailExpr = Tail.isUsable() ? Tail.get() : nullptr;
5437 Data.ColonLoc = ConsumeToken();
5438 TPA.Commit();
5439 } else {
5440 // Colon not found, parse only list of variables.
5441 TPA.Revert();
5442 if (Kind == OMPC_allocate && Data.AllocClauseModifiers.size()) {
5443 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end,
5445 Diag(Tok, diag::err_modifier_expected_colon) << "allocate clause";
5446 }
5447 }
5448 } else {
5449 // Parsing was unsuccessfull, revert and skip to the end of clause or
5450 // directive.
5451 TPA.Revert();
5452 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
5454 }
5455 } else if (Kind == OMPC_adjust_args) {
5456 // Handle adjust-op for adjust_args clause.
5457 ColonProtectionRAIIObject ColonRAII(*this);
5458 Data.ExtraModifier = getOpenMPSimpleClauseType(
5459 Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
5460 getLangOpts());
5461 Data.ExtraModifierLoc = Tok.getLocation();
5462 if (Data.ExtraModifier == OMPC_ADJUST_ARGS_unknown) {
5463 Diag(Tok, diag::err_omp_unknown_adjust_args_op)
5464 << (getLangOpts().OpenMP >= 60 ? 1 : 0);
5465 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
5466 } else {
5467 ConsumeToken();
5468 if (Tok.is(tok::colon))
5469 Data.ColonLoc = Tok.getLocation();
5470 if (getLangOpts().OpenMP >= 61) {
5471 // Handle the optional fallback argument for the need_device_ptr
5472 // modifier.
5473 if (Tok.is(tok::l_paren)) {
5474 BalancedDelimiterTracker T(*this, tok::l_paren);
5475 T.consumeOpen();
5476 if (Tok.is(tok::identifier)) {
5477 std::string Modifier = PP.getSpelling(Tok);
5478 if (Modifier == "fb_nullify" || Modifier == "fb_preserve") {
5479 Data.NeedDevicePtrModifier =
5480 Modifier == "fb_nullify" ? OMPC_NEED_DEVICE_PTR_fb_nullify
5481 : OMPC_NEED_DEVICE_PTR_fb_preserve;
5482 } else {
5483 Diag(Tok, diag::err_omp_unknown_need_device_ptr_kind);
5484 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end,
5486 return false;
5487 }
5488 ConsumeToken();
5489 if (Tok.is(tok::r_paren)) {
5490 Data.NeedDevicePtrModifierLoc = Tok.getLocation();
5492 } else {
5493 Diag(Tok, diag::err_expected) << tok::r_paren;
5494 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end,
5496 return false;
5497 }
5498 } else {
5499 Data.NeedDevicePtrModifier = OMPC_NEED_DEVICE_PTR_unknown;
5500 }
5501 }
5502 }
5503 ExpectAndConsume(tok::colon, diag::warn_pragma_expected_colon,
5504 "adjust-op");
5505 // OpenMP 6.0 [5.2.1, Parameter List Items] adds positions and parameter
5506 // ranges, which the shared list loop below cannot express because a range
5507 // colon terminates it.
5508 if (getLangOpts().OpenMP >= 60) {
5509 ParsedAdjustArgsList = true;
5510 InvalidAdjustArgsList = ParseOpenMPAdjustArgsList(AdjustArgsItems);
5511 }
5512 }
5513 } else if (Kind == OMPC_use_device_ptr) {
5514 // Handle optional fallback modifier for use_device_ptr clause.
5515 // use_device_ptr([fb_preserve | fb_nullify :] list)
5517 if (getLangOpts().OpenMP >= 61 && Tok.is(tok::identifier)) {
5518 auto FallbackModifier = static_cast<OpenMPUseDevicePtrFallbackModifier>(
5519 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts()));
5520 if (FallbackModifier != OMPC_USE_DEVICE_PTR_FALLBACK_unknown) {
5521 Data.ExtraModifier = FallbackModifier;
5522 Data.ExtraModifierLoc = Tok.getLocation();
5523 ConsumeToken();
5524 if (Tok.is(tok::colon))
5525 Data.ColonLoc = ConsumeToken();
5526 else
5527 Diag(Tok, diag::err_modifier_expected_colon) << "fallback";
5528 }
5529 }
5530 } else if (Kind == OMPC_num_teams || Kind == OMPC_thread_limit) {
5531 int Mod = 0;
5532 // Handle optional dims and lower-bound modifiers for num_teams clause, and
5533 // the optional dims modifier for thread_limit clause.
5534 Data.ExtraModifierArray[0] = Data.ExtraModifierArray[1] =
5535 Kind == OMPC_num_teams ? static_cast<int>(OMPC_NUMTEAMS_unknown)
5536 : static_cast<int>(OMPC_THREADLIMIT_unknown);
5537
5538 // Lower-bound modifier is only accepted in num_teams.
5539 bool CanParseLowerBoundModifier = (Kind == OMPC_num_teams);
5540 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo()->isStr("dims") &&
5541 NextToken().is(tok::l_paren)) {
5542 SourceLocation TLoc = Tok.getLocation();
5543 ConsumeToken();
5544 SourceLocation RLoc;
5545 ExprResult ExprR = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
5546 if (ExprR.isUsable()) {
5547 Data.ExtraModifierArray[Mod] =
5548 Kind == OMPC_num_teams ? static_cast<int>(OMPC_NUMTEAMS_dims)
5549 : static_cast<int>(OMPC_THREADLIMIT_dims);
5550 Data.ExtraModifierExprArray[Mod] = ExprR.get();
5551 Data.ExtraModifierLocArray[Mod] = TLoc;
5552 ++Mod;
5553 }
5554
5555 if (Tok.is(tok::colon)) {
5556 // A colon was found, no more modifiers are expected.
5557 ConsumeToken();
5558 CanParseLowerBoundModifier = false;
5559 } else if (CanParseLowerBoundModifier && Tok.is(tok::comma)) {
5560 // num_teams(dims(N), lower : upper) is invalid. Only lower:upper may
5561 // follow dims via comma, but sema will reject the combination.
5562 ConsumeToken();
5563 } else {
5564 Diag(Tok, diag::err_modifier_expected_colon)
5565 << getOpenMPClauseName(Kind);
5566 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
5567 Data.RLoc = Tok.getLocation();
5568 if (!T.consumeClose())
5569 Data.RLoc = T.getCloseLocation();
5570 return true;
5571 }
5572 }
5573
5574 // The lower bound modifier must appear as the last modifier.
5575 if (CanParseLowerBoundModifier) {
5576 TentativeParsingAction TPA(*this);
5577 SourceLocation TLoc = Tok.getLocation();
5579 if (FirstExpr.isInvalid()) {
5580 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
5581 Data.RLoc = Tok.getLocation();
5582 if (!T.consumeClose())
5583 Data.RLoc = T.getCloseLocation();
5584 TPA.Commit();
5585 return true;
5586 }
5587
5588 if (Tok.is(tok::colon)) {
5589 // Correctly parsed the lower bound modifier.
5590 ConsumeToken();
5591 Data.ExtraModifierArray[Mod] = OMPC_NUMTEAMS_lower_bound;
5592 Data.ExtraModifierExprArray[Mod] = FirstExpr.get();
5593 Data.ExtraModifierLocArray[Mod] = TLoc;
5594 TPA.Commit();
5595 } else {
5596 // Could not find the colon after the expression, revert it and let this
5597 // function parse it as a list of expressions.
5598 TPA.Revert();
5599 }
5600 }
5601 } else if (Kind == OMPC_num_threads) {
5602 Data.ExtraModifierArray[0] = static_cast<int>(OMPC_NUMTHREADS_unknown);
5603 Data.ExtraModifierArray[1] = static_cast<int>(OMPC_NUMTHREADS_unknown);
5604
5605 bool HasModifier = false;
5606 while (true) {
5607 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo()->isStr("dims") &&
5608 NextToken().is(tok::l_paren)) {
5609 // Parse the dims modifier.
5610 SourceLocation TLoc = Tok.getLocation();
5611 ConsumeToken();
5612 SourceLocation RLoc;
5613
5614 ExprResult ExprR =
5615 ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
5616
5617 if (Data.ExtraModifierArray[1] != OMPC_NUMTHREADS_unknown)
5618 Diag(TLoc, diag::err_omp_incompatible_modifiers)
5619 << getOpenMPSimpleClauseTypeName(Kind, OMPC_NUMTHREADS_dims)
5620 << getOpenMPSimpleClauseTypeName(Kind, Data.ExtraModifierArray[1])
5621 << getOpenMPClauseName(Kind);
5622
5623 Data.ExtraModifierArray[1] = static_cast<int>(OMPC_NUMTHREADS_dims);
5624 Data.ExtraModifierExprArray[1] =
5625 (ExprR.isUsable()) ? ExprR.get() : nullptr;
5626 Data.ExtraModifierLocArray[1] = TLoc;
5627 HasModifier = true;
5628 } else {
5629 // Parse any other modifier.
5631 static_cast<OpenMPNumThreadsClauseModifier>(
5633 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok),
5634 getLangOpts()));
5635
5636 if (Modifier != OMPC_NUMTHREADS_unknown) {
5637 if (Data.ExtraModifierArray[0] != OMPC_NUMTHREADS_unknown)
5638 Diag(Tok, diag::err_omp_incompatible_modifiers)
5639 << getOpenMPSimpleClauseTypeName(Kind, Modifier)
5641 Data.ExtraModifierArray[0])
5642 << getOpenMPClauseName(Kind);
5643 Data.ExtraModifierArray[0] = Modifier;
5644 Data.ExtraModifierLocArray[0] = Tok.getLocation();
5646 HasModifier = true;
5647 } else {
5648 // Not a recognized modifier.
5649 break;
5650 }
5651 }
5652
5653 // If a comma is present, continue parsing modifiers, and stop otherwise.
5654 if (Tok.is(tok::comma))
5655 ConsumeToken();
5656 else
5657 break;
5658 }
5659
5660 // If any modifier was parsed, the next token must be a colon.
5661 if (HasModifier) {
5662 if (!Tok.is(tok::colon)) {
5663 Diag(Tok, diag::err_modifier_expected_colon)
5664 << getOpenMPClauseName(Kind);
5665 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
5666 Data.RLoc = Tok.getLocation();
5667 if (!T.consumeClose())
5668 Data.RLoc = T.getCloseLocation();
5669 return true;
5670 }
5671 ConsumeToken();
5672 }
5673 }
5674
5675 bool IsComma =
5676 (Kind != OMPC_reduction && Kind != OMPC_task_reduction &&
5677 Kind != OMPC_in_reduction && Kind != OMPC_depend &&
5678 Kind != OMPC_doacross && Kind != OMPC_map && Kind != OMPC_adjust_args) ||
5679 (Kind == OMPC_reduction && !InvalidReductionId) ||
5680 (Kind == OMPC_map && Data.ExtraModifier != OMPC_MAP_unknown) ||
5681 (Kind == OMPC_depend && Data.ExtraModifier != OMPC_DEPEND_unknown) ||
5682 (Kind == OMPC_doacross && Data.ExtraModifier != OMPC_DOACROSS_unknown) ||
5683 (Kind == OMPC_adjust_args &&
5684 Data.ExtraModifier != OMPC_ADJUST_ARGS_unknown);
5685 const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned);
5686 while (!ParsedAdjustArgsList &&
5687 (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) &&
5688 Tok.isNot(tok::annot_pragma_openmp_end)))) {
5689 ParseScope OMPListScope(this, Scope::OpenMPDirectiveScope);
5690 ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
5692 // Parse variable
5694 if (VarExpr.isUsable()) {
5695 Vars.push_back(VarExpr.get());
5696 } else {
5697 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
5699 }
5700 }
5701 // Skip ',' if any
5702 IsComma = Tok.is(tok::comma);
5703 if (IsComma)
5704 ConsumeToken();
5705 else if (Tok.isNot(tok::r_paren) &&
5706 Tok.isNot(tok::annot_pragma_openmp_end) &&
5707 (!MayHaveTail || Tok.isNot(tok::colon))) {
5708 llvm::omp::Version OMPVersion = Actions.getLangOpts().getOpenMPVersion();
5709 Diag(Tok, diag::err_omp_expected_punc)
5710 << ((Kind == OMPC_flush)
5711 ? getOpenMPDirectiveName(OMPD_flush, OMPVersion)
5712 : getOpenMPClauseName(Kind))
5713 << (Kind == OMPC_flush);
5714 }
5715 }
5716
5717 // Parse ')' for linear clause with modifier.
5718 if (NeedRParenForLinear)
5719 LinearT.consumeClose();
5720 // Parse ':' linear modifiers (val, uval, ref or step(step-size))
5721 // or parse ':' alignment.
5722 const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon);
5723 bool StepFound = false;
5724 bool ModifierFound = false;
5725 if (MustHaveTail) {
5726 Data.ColonLoc = Tok.getLocation();
5728
5729 if (getLangOpts().OpenMP >= 52 && Kind == OMPC_linear) {
5730 bool Malformed = false;
5731 while (Tok.isNot(tok::r_paren)) {
5732 if (Tok.is(tok::identifier)) {
5733 // identifier could be a linear kind (val, uval, ref) or step
5734 // modifier or step size
5735 OpenMPLinearClauseKind LinKind =
5737 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok),
5738 getLangOpts()));
5739
5740 if (LinKind == OMPC_LINEAR_step) {
5741 if (StepFound)
5742 Diag(Tok, diag::err_omp_multiple_step_or_linear_modifier) << 0;
5743
5744 BalancedDelimiterTracker StepT(*this, tok::l_paren,
5745 tok::annot_pragma_openmp_end);
5746 SourceLocation StepModifierLoc = ConsumeToken();
5747 // parse '('
5748 if (StepT.consumeOpen())
5749 Diag(StepModifierLoc, diag::err_expected_lparen_after) << "step";
5750
5751 // parse step size expression
5752 StepFound = parseStepSize(*this, Data, Kind, Tok.getLocation());
5753 if (StepFound)
5754 Data.StepModifierLoc = StepModifierLoc;
5755
5756 // parse ')'
5757 StepT.consumeClose();
5758 } else if (LinKind >= 0 && LinKind < OMPC_LINEAR_step) {
5759 if (ModifierFound)
5760 Diag(Tok, diag::err_omp_multiple_step_or_linear_modifier) << 1;
5761
5762 Data.ExtraModifier = LinKind;
5763 Data.ExtraModifierLoc = ConsumeToken();
5764 ModifierFound = true;
5765 } else {
5766 StepFound = parseStepSize(*this, Data, Kind, Tok.getLocation());
5767 if (!StepFound) {
5768 Malformed = true;
5769 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
5771 }
5772 }
5773 } else {
5774 // parse an integer expression as step size
5775 StepFound = parseStepSize(*this, Data, Kind, Tok.getLocation());
5776 }
5777
5778 if (Tok.is(tok::comma))
5779 ConsumeToken();
5780 if (Tok.is(tok::r_paren) || Tok.is(tok::annot_pragma_openmp_end))
5781 break;
5782 }
5783 if (!Malformed && !StepFound && !ModifierFound)
5784 Diag(ELoc, diag::err_expected_expression);
5785 } else {
5786 // for OMPC_aligned and OMPC_linear (with OpenMP <= 5.1)
5788 Tail = Actions.ActOnFinishFullExpr(Tail.get(), ELoc,
5789 /*DiscardedValue*/ false);
5790 if (Tail.isUsable())
5791 Data.DepModOrTailExpr = Tail.get();
5792 else
5793 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
5795 }
5796 }
5797
5798 // Parse ')'.
5799 Data.RLoc = Tok.getLocation();
5800 if (!T.consumeClose())
5801 Data.RLoc = T.getCloseLocation();
5802 // Exit from scope when the iterator is used in depend clause.
5803 if (HasIterator)
5804 ExitScope();
5805 return (Kind != OMPC_depend && Kind != OMPC_doacross && Kind != OMPC_map &&
5806 Vars.empty() && AdjustArgsItems.empty()) ||
5807 (MustHaveTail && !Data.DepModOrTailExpr && StepFound) ||
5808 InvalidReductionId || IsInvalidMapperModifier || InvalidIterator ||
5809 InvalidAdjustArgsList;
5810}
5811
5812OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
5813 OpenMPClauseKind Kind,
5814 bool ParseOnly) {
5815 SourceLocation Loc = Tok.getLocation();
5816 SourceLocation LOpen = ConsumeToken();
5818 SmallVector<OMPAdjustArgsItem> AdjustArgsItems;
5820
5821 if (ParseOpenMPVarList(DKind, Kind, Vars, Data, AdjustArgsItems))
5822 return nullptr;
5823
5824 if (ParseOnly)
5825 return nullptr;
5826 OMPVarListLocTy Locs(Loc, LOpen, Data.RLoc);
5827 return Actions.OpenMP().ActOnOpenMPVarListClause(Kind, Vars, Locs, Data);
5828}
5829
5830bool Parser::ParseOpenMPExprListClause(OpenMPClauseKind Kind,
5831 SourceLocation &ClauseNameLoc,
5832 SourceLocation &OpenLoc,
5833 SourceLocation &CloseLoc,
5835 bool ReqIntConst) {
5836 assert(getOpenMPClauseName(Kind) == PP.getSpelling(Tok) &&
5837 "Expected parsing to start at clause name");
5838 ClauseNameLoc = ConsumeToken();
5839
5840 // Parse inside of '(' and ')'.
5841 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
5842 if (T.consumeOpen()) {
5843 Diag(Tok, diag::err_expected) << tok::l_paren;
5844 return true;
5845 }
5846
5847 // Parse the list with interleaved commas.
5848 do {
5849 ExprResult Val =
5851 if (!Val.isUsable()) {
5852 // Encountered something other than an expression; abort to ')'.
5853 T.skipToEnd();
5854 return true;
5855 }
5856 Exprs.push_back(Val.get());
5857 } while (TryConsumeToken(tok::comma));
5858
5859 bool Result = T.consumeClose();
5860 OpenLoc = T.getOpenLocation();
5861 CloseLoc = T.getCloseLocation();
5862 return Result;
5863}
Defines the clang::ASTContext interface.
bool is(tok::TokenKind Kind) const
Token Tok
The Token.
bool isNot(T Kind) const
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
This file defines OpenMP AST classes for clauses.
Defines some OpenMP-specific enums and functions.
static OpenMPDirectiveKind checkOpenMPDirectiveName(Parser &P, SourceLocation Loc, OpenMPDirectiveKind Kind, StringRef Name)
static OpenMPDirectiveKind parseOpenMPDirectiveKind(Parser &P)
static OpenMPMapModifierKind isMapModifier(Parser &P)
Checks if the token is a valid map-type-modifier.
static std::optional< SimpleClauseData > parseOpenMPSimpleClause(Parser &P, OpenMPClauseKind Kind)
static bool checkExtensionProperty(Parser &P, SourceLocation Loc, OMPTraitProperty &TIProperty, OMPTraitSelector &TISelector, llvm::StringMap< SourceLocation > &Seen)
static ExprResult parseOpenMPAllocateClauseModifiers(Parser &P, OpenMPClauseKind Kind, SemaOpenMP::OpenMPVarListDataTy &Data)
Parse 'allocate' clause modifiers.
static DeclarationName parseOpenMPReductionId(Parser &P)
static ExprResult parseContextScore(Parser &P)
Parse optional 'score' '(' <expr> ')' ':'.
static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec, UnqualifiedId &ReductionId)
static bool parseStepSize(Parser &P, SemaOpenMP::OpenMPVarListDataTy &Data, OpenMPClauseKind CKind, SourceLocation ELoc)
Parse step size expression.
static void parseMapType(Parser &P, SemaOpenMP::OpenMPVarListDataTy &Data)
Parse map-type in map clause.
static bool parseDeclareSimdClauses(Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen, SmallVectorImpl< Expr * > &Uniforms, SmallVectorImpl< Expr * > &Aligneds, SmallVectorImpl< Expr * > &Alignments, SmallVectorImpl< Expr * > &Linears, SmallVectorImpl< unsigned > &LinModifiers, SmallVectorImpl< Expr * > &Steps)
Parses clauses for 'declare simd' directive.
static OpenMPMapClauseKind isMapType(Parser &P)
Checks if the token is a valid map-type.
This file declares semantic analysis functions specific to AMDGPU.
This file declares facilities that support code completion.
This file declares semantic analysis for OpenMP constructs and clauses.
Defines the clang::TokenKind enum and support functions.
VerifyDiagnosticConsumer::Directive Directive
void getAsVariantMatchInfo(ASTContext &ASTCtx, llvm::omp::VariantMatchInfo &VMI) const
Create a variant match info object from this trait info object.
llvm::SmallVector< OMPTraitSet, 2 > Sets
The outermost level of selector sets.
bool anyScoreOrCondition(llvm::function_ref< bool(Expr *&, bool)> Cond)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:246
DeclarationNameTable DeclarationNames
Definition ASTContext.h:866
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ....
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:182
TypeSpecifierType TST
Definition DeclSpec.h:314
static const TST TST_unspecified
Definition DeclSpec.h:315
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition DeclBase.h:1138
SourceLocation getLocation() const
Definition DeclBase.h:449
DeclContext * getDeclContext()
Definition DeclBase.h:458
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:441
The name of a declaration.
bool isEmpty() const
Evaluates true when this declaration name is empty.
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition Expr.h:243
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:225
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:139
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
llvm::omp::Version getOpenMPVersion() const
Return the OpenMP version.
This represents a decl that may have a name.
Definition Decl.h:276
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition Decl.cpp:1979
This is a basic class for representing single OpenMP clause.
static const ParsedAttributesView & none()
Definition ParsedAttr.h:838
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:958
Introduces zero or more scopes for parsing.
Definition Parser.h:538
void Enter(unsigned ScopeFlags)
Definition Parser.h:546
ParseScope - Introduces a new scope for parsing.
Definition Parser.h:502
Parser - This implements a parser for the C family of languages.
Definition Parser.h:265
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeName, AccessSpecifier AS=AS_none, Decl **OwnedType=nullptr, ParsedAttributes *Attrs=nullptr)
ParseTypeName.
Definition ParseDecl.cpp:45
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition Parser.cpp:100
Preprocessor & getPreprocessor() const
Definition Parser.h:301
bool parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data)
Parse map-type-modifiers in map clause.
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral=false)
ParseStringLiteralExpression - This handles the various token types that form string literals,...
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition Parser.h:357
bool ParseOpenMPAdjustArgsList(SmallVectorImpl< OMPAdjustArgsItem > &Items)
Parses an OpenMP 6.0 'adjust_args' parameter list, whose items may be parameter names,...
Sema & getActions() const
Definition Parser.h:302
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
Definition Parser.cpp:438
bool parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data)
Parses the mapper modifier in map, to, and from clauses.
friend class ParsingOpenMPDirectiveRAII
Definition Parser.h:6444
bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
friend class ColonProtectionRAIIObject
Definition Parser.h:290
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition Parser.h:385
ExprResult ParseConstantExpression()
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:365
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Parser.h:314
Scope * getCurScope() const
Definition Parser.h:306
bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl< Expr * > &Vars, SemaOpenMP::OpenMPVarListDataTy &Data, SmallVectorImpl< OMPAdjustArgsItem > &AdjustArgsItems)
Parses clauses with list.
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition Parser.h:601
const Token & getCurToken() const
Definition Parser.h:305
bool ParseOpenMPAdjustArgsBound(OMPAdjustArgsItem::Bound &Bound)
Parses one bound of an OpenMP 6.0 'adjust_args' parameter range, which may be 'omp_num_args' with an ...
void ExitScope()
ExitScope - Pop a scope off the scope stack.
Definition Parser.cpp:448
ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand=false)
Parses simple expression in parens for single-expression clauses of OpenMP constructs.
const LangOptions & getLangOpts() const
Definition Parser.h:299
friend class ParenBraceBracketBalancer
Definition Parser.h:293
ExprResult ParseExpression(TypoCorrectionTypeBehavior CorrectionBehavior=TypoCorrectionTypeBehavior::AllowNonTypes)
Simple precedence-based parser for binary/ternary operators.
Definition ParseExpr.cpp:47
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition Parser.h:582
bool ParseOpenMPReservedLocator(OpenMPClauseKind Kind, SemaOpenMP::OpenMPVarListDataTy &Data, const LangOptions &LangOpts)
Parses a reserved locator like 'omp_all_memory'.
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:419
ExprResult ParseAssignmentExpression(TypoCorrectionTypeBehavior CorrectionBehavior=TypoCorrectionTypeBehavior::AllowNonTypes)
Parse an expr that doesn't include (top-level) commas.
Definition ParseExpr.cpp:75
friend class BalancedDelimiterTracker
Definition Parser.h:294
unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D)
Re-enter a possible template scope, creating as many template parameter scopes as necessary.
bool ParseOpenMPDeclareBeginVariantDirective(SourceLocation Loc)
Parses 'omp begin declare variant' directive.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
const Token & LookAhead(unsigned N)
Peeks ahead N tokens and returns that token without consuming any tokens.
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
Represents a struct/union/class.
Definition Decl.h:4512
@ OpenMPDirectiveScope
This is the scope of OpenMP executable directive.
Definition Scope.h:112
@ CompoundStmtScope
This is a compound statement scope.
Definition Scope.h:135
@ OpenMPSimdDirectiveScope
This is the scope of some OpenMP simd directive.
Definition Scope.h:120
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
Definition Scope.h:52
@ OpenMPLoopDirectiveScope
This is the scope of some OpenMP loop directive.
Definition Scope.h:115
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:64
Smart pointer class that efficiently represents Objective-C method names.
bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc)
Checks correctness of linear modifiers.
OMPClause * ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef< UsesAllocatorsData > Data)
Called on well-formed 'uses_allocators' clause.
OMPClause * ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
OMPClause * ActOnOpenMPVarListClause(OpenMPClauseKind Kind, ArrayRef< Expr * > Vars, const OMPVarListLocTy &Locs, OpenMPVarListDataTy &Data)
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8718
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1172
SemaOpenMP & OpenMP()
Definition Sema.h:1578
void ActOnExitFunctionContext()
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
ASTContext & getASTContext() const
Definition Sema.h:935
const LangOptions & getLangOpts() const
Definition Sema.h:928
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6936
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8931
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
Token - This structure provides full information about a lexed token.
Definition Token.h:36
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:142
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:104
tok::TokenKind getKind() const
Definition Token.h:99
bool isNot(tok::TokenKind K) const
Definition Token.h:111
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
The base class of the type hierarchy.
Definition TypeBase.h:1879
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3201
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1114
void setOperatorFunctionId(SourceLocation OperatorLoc, OverloadedOperatorKind Op, SourceLocation SymbolLocations[3])
Specify that this unqualified-id was parsed as an operator-function-id.
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
Defines the clang::TargetInfo interface.
PRESERVE_NONE bool Ret(InterpState &S)
Definition Interp.h:276
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition TokenKinds.h:101
Top level wrappers for InstallAPI frontend operations.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ CPlusPlus
@ CPlusPlus11
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
OpenMPDefaultClauseVariableCategory
OpenMP variable-category for 'default' clause.
@ OMPC_DEFAULTMAP_MODIFIER_unknown
@ OMPC_ORDER_MODIFIER_unknown
Stmt Stmt * Callback
Definition StmtOpenMP.h:930
OpenMPNeedDevicePtrModifier
OpenMP 6.1 need_device modifier.
@ OMPC_NEED_DEVICE_PTR_unknown
OpenMPAdjustArgsOpKind
OpenMP adjust-op kinds for 'adjust_args' clause.
@ OMPC_ADJUST_ARGS_unknown
bool isOpenMPDistributeDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a distribute directive.
@ OMPC_REDUCTION_unknown
OpenMPDeviceType
OpenMP device type for 'device_type' clause.
@ OMPC_DEVICE_TYPE_unknown
@ OMPC_SCHEDULE_MODIFIER_unknown
Definition OpenMPKinds.h:40
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:127
@ AS_none
Definition Specifiers.h:131
const char * getOpenMPSimpleClauseTypeName(OpenMPClauseKind Kind, unsigned Type)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ OMPC_NUMTEAMS_unknown
@ OMPC_DOACROSS_unknown
bool isOpenMPTargetExecutionDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a target code offload directive.
@ OMPC_DYN_GROUPPRIVATE_FALLBACK_unknown
@ OMPC_DYN_GROUPPRIVATE_FALLBACK_last
StmtResult StmtError()
Definition Ownership.h:266
DeclaratorContext
Definition DeclSpec.h:1950
@ Property
The type of a property.
Definition TypeBase.h:912
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
@ OMPC_LASTPRIVATE_unknown
@ OMPC_DEPEND_unknown
Definition OpenMPKinds.h:59
OpenMPGrainsizeClauseModifier
@ OMPC_GRAINSIZE_unknown
unsigned getOpenMPSimpleClauseType(OpenMPClauseKind Kind, llvm::StringRef Str, const LangOptions &LangOpts)
OpenMPNumTasksClauseModifier
@ OMPC_NUMTASKS_unknown
OpenMPUseDevicePtrFallbackModifier
OpenMP 6.1 use_device_ptr fallback modifier.
@ OMPC_USE_DEVICE_PTR_FALLBACK_unknown
ExprResult ExprError()
Definition Ownership.h:265
bool isOpenMPLoopDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a directive with an associated loop construct.
OpenMPMotionModifierKind
OpenMP modifier kind for 'to' or 'from' clause.
Definition OpenMPKinds.h:92
@ OMPC_MOTION_MODIFIER_unknown
Definition OpenMPKinds.h:96
@ OMPC_DEFAULTMAP_unknown
OpenMPAllocateClauseModifier
OpenMP modifiers for 'allocate' clause.
@ OMPC_ALLOCATE_unknown
OpenMPLinearClauseKind
OpenMP attributes for 'linear' clause.
Definition OpenMPKinds.h:63
@ OMPC_LINEAR_unknown
Definition OpenMPKinds.h:67
bool isOpenMPExecutableDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is considered as "executable".
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition OpenMPKinds.h:25
@ OMPC_DYN_GROUPPRIVATE_unknown
bool isOpenMPInformationalDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is considered as "informational".
bool isOpenMPSimdDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a simd directive.
@ OMPC_THREADLIMIT_unknown
OpenMPNumThreadsClauseModifier
@ OMPC_NUMTHREADS_unknown
StmtResult StmtEmpty()
Definition Ownership.h:273
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:218
@ OMPC_DEVICE_unknown
Definition OpenMPKinds.h:51
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
OpenMPMapModifierKind
OpenMP modifier kind for 'map' clause.
Definition OpenMPKinds.h:79
@ OMPC_MAP_MODIFIER_unknown
Definition OpenMPKinds.h:80
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition OpenMPKinds.h:28
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ OMPC_ORDER_unknown
@ OMPC_SCHEDULE_unknown
Definition OpenMPKinds.h:35
bool isOpenMPTaskLoopDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a taskloop directive.
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
OpenMPDefaultClauseVariableCategory getOpenMPDefaultVariableCategory(StringRef Str, const LangOptions &LangOpts)
OpenMPMapClauseKind
OpenMP mapping kind for 'map' clause.
Definition OpenMPKinds.h:71
@ OMPC_MAP_unknown
Definition OpenMPKinds.h:75
int const char * function
Definition c++config.h:31
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
#define false
Definition stdbool.h:26
llvm::omp::TraitProperty Kind
StringRef RawString
The raw string as we parsed it. This is needed for the isa trait set (which accepts anything) and (la...
llvm::omp::TraitSelector Kind
SmallVector< OMPTraitProperty, 1 > Properties
SmallVector< OMPTraitSelector, 2 > Selectors
llvm::omp::TraitSet Kind
Clang specific specialization of the OMPContext to lookup target features.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
One bound of a parameter range.
Expr * E
The bound expression, or the logical offset for a NumArgs bound.
One item in an OpenMP 'adjust_args' parameter list.
Expr * E
A named parameter or positional expression for a Single item.
llvm::SmallVector< OMPInteropPref, 4 > Prefs
This structure contains most locations needed for by an OMPVarListClause.
std::optional< Expr * > Indirect
The directive with indirect clause.
Definition SemaOpenMP.h:332
OpenMPDirectiveKind Kind
The directive kind, begin declare target or declare target.
Definition SemaOpenMP.h:329
OMPDeclareTargetDeclAttr::DevTypeTy DT
The 'device_type' as parsed from the clause.
Definition SemaOpenMP.h:326
SourceLocation Loc
The directive location.
Definition SemaOpenMP.h:335
llvm::DenseMap< NamedDecl *, MapInfo > ExplicitlyMapped
Explicitly listed variables and functions in a 'to' or 'link' clause.
Definition SemaOpenMP.h:323
OMPIteratorExpr::IteratorRange Range
Data used for processing a list of variables in OpenMP clauses.
Data for list of allocators.
Expr * AllocatorTraits
Allocator traits.
SourceLocation LParenLoc
Locations of '(' and ')' symbols.