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