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/AST/StmtOpenMP.h" 16 #include "clang/Basic/OpenMPKinds.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/Basic/TokenKinds.h" 19 #include "clang/Parse/ParseDiagnostic.h" 20 #include "clang/Parse/Parser.h" 21 #include "clang/Parse/RAIIObjectsForParser.h" 22 #include "clang/Sema/Scope.h" 23 #include "llvm/ADT/PointerIntPair.h" 24 #include "llvm/ADT/StringSwitch.h" 25 #include "llvm/ADT/UniqueVector.h" 26 #include "llvm/Frontend/OpenMP/OMPContext.h" 27 28 using namespace clang; 29 using namespace llvm::omp; 30 31 //===----------------------------------------------------------------------===// 32 // OpenMP declarative directives. 33 //===----------------------------------------------------------------------===// 34 35 namespace { 36 enum OpenMPDirectiveKindEx { 37 OMPD_cancellation = llvm::omp::Directive_enumSize + 1, 38 OMPD_data, 39 OMPD_declare, 40 OMPD_end, 41 OMPD_end_declare, 42 OMPD_enter, 43 OMPD_exit, 44 OMPD_point, 45 OMPD_reduction, 46 OMPD_target_enter, 47 OMPD_target_exit, 48 OMPD_update, 49 OMPD_distribute_parallel, 50 OMPD_teams_distribute_parallel, 51 OMPD_target_teams_distribute_parallel, 52 OMPD_mapper, 53 OMPD_variant, 54 OMPD_begin, 55 OMPD_begin_declare, 56 }; 57 58 // Helper to unify the enum class OpenMPDirectiveKind with its extension 59 // the OpenMPDirectiveKindEx enum which allows to use them together as if they 60 // are unsigned values. 61 struct OpenMPDirectiveKindExWrapper { 62 OpenMPDirectiveKindExWrapper(unsigned Value) : Value(Value) {} 63 OpenMPDirectiveKindExWrapper(OpenMPDirectiveKind DK) : Value(unsigned(DK)) {} 64 bool operator==(OpenMPDirectiveKindExWrapper V) const { 65 return Value == V.Value; 66 } 67 bool operator!=(OpenMPDirectiveKindExWrapper V) const { 68 return Value != V.Value; 69 } 70 bool operator==(OpenMPDirectiveKind V) const { return Value == unsigned(V); } 71 bool operator!=(OpenMPDirectiveKind V) const { return Value != unsigned(V); } 72 bool operator<(OpenMPDirectiveKind V) const { return Value < unsigned(V); } 73 operator unsigned() const { return Value; } 74 operator OpenMPDirectiveKind() const { return OpenMPDirectiveKind(Value); } 75 unsigned Value; 76 }; 77 78 class DeclDirectiveListParserHelper final { 79 SmallVector<Expr *, 4> Identifiers; 80 Parser *P; 81 OpenMPDirectiveKind Kind; 82 83 public: 84 DeclDirectiveListParserHelper(Parser *P, OpenMPDirectiveKind Kind) 85 : P(P), Kind(Kind) {} 86 void operator()(CXXScopeSpec &SS, DeclarationNameInfo NameInfo) { 87 ExprResult Res = P->getActions().ActOnOpenMPIdExpression( 88 P->getCurScope(), SS, NameInfo, Kind); 89 if (Res.isUsable()) 90 Identifiers.push_back(Res.get()); 91 } 92 llvm::ArrayRef<Expr *> getIdentifiers() const { return Identifiers; } 93 }; 94 } // namespace 95 96 // Map token string to extended OMP token kind that are 97 // OpenMPDirectiveKind + OpenMPDirectiveKindEx. 98 static unsigned getOpenMPDirectiveKindEx(StringRef S) { 99 OpenMPDirectiveKindExWrapper DKind = getOpenMPDirectiveKind(S); 100 if (DKind != OMPD_unknown) 101 return DKind; 102 103 return llvm::StringSwitch<OpenMPDirectiveKindExWrapper>(S) 104 .Case("cancellation", OMPD_cancellation) 105 .Case("data", OMPD_data) 106 .Case("declare", OMPD_declare) 107 .Case("end", OMPD_end) 108 .Case("enter", OMPD_enter) 109 .Case("exit", OMPD_exit) 110 .Case("point", OMPD_point) 111 .Case("reduction", OMPD_reduction) 112 .Case("update", OMPD_update) 113 .Case("mapper", OMPD_mapper) 114 .Case("variant", OMPD_variant) 115 .Case("begin", OMPD_begin) 116 .Default(OMPD_unknown); 117 } 118 119 static OpenMPDirectiveKindExWrapper parseOpenMPDirectiveKind(Parser &P) { 120 // Array of foldings: F[i][0] F[i][1] ===> F[i][2]. 121 // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd 122 // TODO: add other combined directives in topological order. 123 static const OpenMPDirectiveKindExWrapper F[][3] = { 124 {OMPD_begin, OMPD_declare, OMPD_begin_declare}, 125 {OMPD_begin, OMPD_assumes, OMPD_begin_assumes}, 126 {OMPD_end, OMPD_declare, OMPD_end_declare}, 127 {OMPD_end, OMPD_assumes, OMPD_end_assumes}, 128 {OMPD_cancellation, OMPD_point, OMPD_cancellation_point}, 129 {OMPD_declare, OMPD_reduction, OMPD_declare_reduction}, 130 {OMPD_declare, OMPD_mapper, OMPD_declare_mapper}, 131 {OMPD_declare, OMPD_simd, OMPD_declare_simd}, 132 {OMPD_declare, OMPD_target, OMPD_declare_target}, 133 {OMPD_declare, OMPD_variant, OMPD_declare_variant}, 134 {OMPD_begin_declare, OMPD_target, OMPD_begin_declare_target}, 135 {OMPD_begin_declare, OMPD_variant, OMPD_begin_declare_variant}, 136 {OMPD_end_declare, OMPD_variant, OMPD_end_declare_variant}, 137 {OMPD_distribute, OMPD_parallel, OMPD_distribute_parallel}, 138 {OMPD_distribute_parallel, OMPD_for, OMPD_distribute_parallel_for}, 139 {OMPD_distribute_parallel_for, OMPD_simd, 140 OMPD_distribute_parallel_for_simd}, 141 {OMPD_distribute, OMPD_simd, OMPD_distribute_simd}, 142 {OMPD_end_declare, OMPD_target, OMPD_end_declare_target}, 143 {OMPD_target, OMPD_data, OMPD_target_data}, 144 {OMPD_target, OMPD_enter, OMPD_target_enter}, 145 {OMPD_target, OMPD_exit, OMPD_target_exit}, 146 {OMPD_target, OMPD_update, OMPD_target_update}, 147 {OMPD_target_enter, OMPD_data, OMPD_target_enter_data}, 148 {OMPD_target_exit, OMPD_data, OMPD_target_exit_data}, 149 {OMPD_for, OMPD_simd, OMPD_for_simd}, 150 {OMPD_parallel, OMPD_for, OMPD_parallel_for}, 151 {OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd}, 152 {OMPD_parallel, OMPD_sections, OMPD_parallel_sections}, 153 {OMPD_taskloop, OMPD_simd, OMPD_taskloop_simd}, 154 {OMPD_target, OMPD_parallel, OMPD_target_parallel}, 155 {OMPD_target, OMPD_simd, OMPD_target_simd}, 156 {OMPD_target_parallel, OMPD_for, OMPD_target_parallel_for}, 157 {OMPD_target_parallel_for, OMPD_simd, OMPD_target_parallel_for_simd}, 158 {OMPD_teams, OMPD_distribute, OMPD_teams_distribute}, 159 {OMPD_teams_distribute, OMPD_simd, OMPD_teams_distribute_simd}, 160 {OMPD_teams_distribute, OMPD_parallel, OMPD_teams_distribute_parallel}, 161 {OMPD_teams_distribute_parallel, OMPD_for, 162 OMPD_teams_distribute_parallel_for}, 163 {OMPD_teams_distribute_parallel_for, OMPD_simd, 164 OMPD_teams_distribute_parallel_for_simd}, 165 {OMPD_target, OMPD_teams, OMPD_target_teams}, 166 {OMPD_target_teams, OMPD_distribute, OMPD_target_teams_distribute}, 167 {OMPD_target_teams_distribute, OMPD_parallel, 168 OMPD_target_teams_distribute_parallel}, 169 {OMPD_target_teams_distribute, OMPD_simd, 170 OMPD_target_teams_distribute_simd}, 171 {OMPD_target_teams_distribute_parallel, OMPD_for, 172 OMPD_target_teams_distribute_parallel_for}, 173 {OMPD_target_teams_distribute_parallel_for, OMPD_simd, 174 OMPD_target_teams_distribute_parallel_for_simd}, 175 {OMPD_master, OMPD_taskloop, OMPD_master_taskloop}, 176 {OMPD_master_taskloop, OMPD_simd, OMPD_master_taskloop_simd}, 177 {OMPD_parallel, OMPD_master, OMPD_parallel_master}, 178 {OMPD_parallel_master, OMPD_taskloop, OMPD_parallel_master_taskloop}, 179 {OMPD_parallel_master_taskloop, OMPD_simd, 180 OMPD_parallel_master_taskloop_simd}}; 181 enum { CancellationPoint = 0, DeclareReduction = 1, TargetData = 2 }; 182 Token Tok = P.getCurToken(); 183 OpenMPDirectiveKindExWrapper DKind = 184 Tok.isAnnotation() 185 ? static_cast<unsigned>(OMPD_unknown) 186 : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok)); 187 if (DKind == OMPD_unknown) 188 return OMPD_unknown; 189 190 for (unsigned I = 0; I < llvm::array_lengthof(F); ++I) { 191 if (DKind != F[I][0]) 192 continue; 193 194 Tok = P.getPreprocessor().LookAhead(0); 195 OpenMPDirectiveKindExWrapper SDKind = 196 Tok.isAnnotation() 197 ? static_cast<unsigned>(OMPD_unknown) 198 : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok)); 199 if (SDKind == OMPD_unknown) 200 continue; 201 202 if (SDKind == F[I][1]) { 203 P.ConsumeToken(); 204 DKind = F[I][2]; 205 } 206 } 207 return unsigned(DKind) < llvm::omp::Directive_enumSize 208 ? static_cast<OpenMPDirectiveKind>(DKind) 209 : OMPD_unknown; 210 } 211 212 static DeclarationName parseOpenMPReductionId(Parser &P) { 213 Token Tok = P.getCurToken(); 214 Sema &Actions = P.getActions(); 215 OverloadedOperatorKind OOK = OO_None; 216 // Allow to use 'operator' keyword for C++ operators 217 bool WithOperator = false; 218 if (Tok.is(tok::kw_operator)) { 219 P.ConsumeToken(); 220 Tok = P.getCurToken(); 221 WithOperator = true; 222 } 223 switch (Tok.getKind()) { 224 case tok::plus: // '+' 225 OOK = OO_Plus; 226 break; 227 case tok::minus: // '-' 228 OOK = OO_Minus; 229 break; 230 case tok::star: // '*' 231 OOK = OO_Star; 232 break; 233 case tok::amp: // '&' 234 OOK = OO_Amp; 235 break; 236 case tok::pipe: // '|' 237 OOK = OO_Pipe; 238 break; 239 case tok::caret: // '^' 240 OOK = OO_Caret; 241 break; 242 case tok::ampamp: // '&&' 243 OOK = OO_AmpAmp; 244 break; 245 case tok::pipepipe: // '||' 246 OOK = OO_PipePipe; 247 break; 248 case tok::identifier: // identifier 249 if (!WithOperator) 250 break; 251 LLVM_FALLTHROUGH; 252 default: 253 P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier); 254 P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 255 Parser::StopBeforeMatch); 256 return DeclarationName(); 257 } 258 P.ConsumeToken(); 259 auto &DeclNames = Actions.getASTContext().DeclarationNames; 260 return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo()) 261 : DeclNames.getCXXOperatorName(OOK); 262 } 263 264 /// Parse 'omp declare reduction' construct. 265 /// 266 /// declare-reduction-directive: 267 /// annot_pragma_openmp 'declare' 'reduction' 268 /// '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')' 269 /// ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')'] 270 /// annot_pragma_openmp_end 271 /// <reduction_id> is either a base language identifier or one of the following 272 /// operators: '+', '-', '*', '&', '|', '^', '&&' and '||'. 273 /// 274 Parser::DeclGroupPtrTy 275 Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) { 276 // Parse '('. 277 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 278 if (T.expectAndConsume( 279 diag::err_expected_lparen_after, 280 getOpenMPDirectiveName(OMPD_declare_reduction).data())) { 281 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 282 return DeclGroupPtrTy(); 283 } 284 285 DeclarationName Name = parseOpenMPReductionId(*this); 286 if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end)) 287 return DeclGroupPtrTy(); 288 289 // Consume ':'. 290 bool IsCorrect = !ExpectAndConsume(tok::colon); 291 292 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end)) 293 return DeclGroupPtrTy(); 294 295 IsCorrect = IsCorrect && !Name.isEmpty(); 296 297 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) { 298 Diag(Tok.getLocation(), diag::err_expected_type); 299 IsCorrect = false; 300 } 301 302 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end)) 303 return DeclGroupPtrTy(); 304 305 SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes; 306 // Parse list of types until ':' token. 307 do { 308 ColonProtectionRAIIObject ColonRAII(*this); 309 SourceRange Range; 310 TypeResult TR = ParseTypeName(&Range, DeclaratorContext::Prototype, AS); 311 if (TR.isUsable()) { 312 QualType ReductionType = 313 Actions.ActOnOpenMPDeclareReductionType(Range.getBegin(), TR); 314 if (!ReductionType.isNull()) { 315 ReductionTypes.push_back( 316 std::make_pair(ReductionType, Range.getBegin())); 317 } 318 } else { 319 SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end, 320 StopBeforeMatch); 321 } 322 323 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) 324 break; 325 326 // Consume ','. 327 if (ExpectAndConsume(tok::comma)) { 328 IsCorrect = false; 329 if (Tok.is(tok::annot_pragma_openmp_end)) { 330 Diag(Tok.getLocation(), diag::err_expected_type); 331 return DeclGroupPtrTy(); 332 } 333 } 334 } while (Tok.isNot(tok::annot_pragma_openmp_end)); 335 336 if (ReductionTypes.empty()) { 337 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 338 return DeclGroupPtrTy(); 339 } 340 341 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end)) 342 return DeclGroupPtrTy(); 343 344 // Consume ':'. 345 if (ExpectAndConsume(tok::colon)) 346 IsCorrect = false; 347 348 if (Tok.is(tok::annot_pragma_openmp_end)) { 349 Diag(Tok.getLocation(), diag::err_expected_expression); 350 return DeclGroupPtrTy(); 351 } 352 353 DeclGroupPtrTy DRD = Actions.ActOnOpenMPDeclareReductionDirectiveStart( 354 getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes, AS); 355 356 // Parse <combiner> expression and then parse initializer if any for each 357 // correct type. 358 unsigned I = 0, E = ReductionTypes.size(); 359 for (Decl *D : DRD.get()) { 360 TentativeParsingAction TPA(*this); 361 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope | 362 Scope::CompoundStmtScope | 363 Scope::OpenMPDirectiveScope); 364 // Parse <combiner> expression. 365 Actions.ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D); 366 ExprResult CombinerResult = Actions.ActOnFinishFullExpr( 367 ParseExpression().get(), D->getLocation(), /*DiscardedValue*/ false); 368 Actions.ActOnOpenMPDeclareReductionCombinerEnd(D, CombinerResult.get()); 369 370 if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) && 371 Tok.isNot(tok::annot_pragma_openmp_end)) { 372 TPA.Commit(); 373 IsCorrect = false; 374 break; 375 } 376 IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable(); 377 ExprResult InitializerResult; 378 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 379 // Parse <initializer> expression. 380 if (Tok.is(tok::identifier) && 381 Tok.getIdentifierInfo()->isStr("initializer")) { 382 ConsumeToken(); 383 } else { 384 Diag(Tok.getLocation(), diag::err_expected) << "'initializer'"; 385 TPA.Commit(); 386 IsCorrect = false; 387 break; 388 } 389 // Parse '('. 390 BalancedDelimiterTracker T(*this, tok::l_paren, 391 tok::annot_pragma_openmp_end); 392 IsCorrect = 393 !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") && 394 IsCorrect; 395 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 396 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope | 397 Scope::CompoundStmtScope | 398 Scope::OpenMPDirectiveScope); 399 // Parse expression. 400 VarDecl *OmpPrivParm = 401 Actions.ActOnOpenMPDeclareReductionInitializerStart(getCurScope(), 402 D); 403 // Check if initializer is omp_priv <init_expr> or something else. 404 if (Tok.is(tok::identifier) && 405 Tok.getIdentifierInfo()->isStr("omp_priv")) { 406 ConsumeToken(); 407 ParseOpenMPReductionInitializerForDecl(OmpPrivParm); 408 } else { 409 InitializerResult = Actions.ActOnFinishFullExpr( 410 ParseAssignmentExpression().get(), D->getLocation(), 411 /*DiscardedValue*/ false); 412 } 413 Actions.ActOnOpenMPDeclareReductionInitializerEnd( 414 D, InitializerResult.get(), OmpPrivParm); 415 if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) && 416 Tok.isNot(tok::annot_pragma_openmp_end)) { 417 TPA.Commit(); 418 IsCorrect = false; 419 break; 420 } 421 IsCorrect = 422 !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid(); 423 } 424 } 425 426 ++I; 427 // Revert parsing if not the last type, otherwise accept it, we're done with 428 // parsing. 429 if (I != E) 430 TPA.Revert(); 431 else 432 TPA.Commit(); 433 } 434 return Actions.ActOnOpenMPDeclareReductionDirectiveEnd(getCurScope(), DRD, 435 IsCorrect); 436 } 437 438 void Parser::ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm) { 439 // Parse declarator '=' initializer. 440 // If a '==' or '+=' is found, suggest a fixit to '='. 441 if (isTokenEqualOrEqualTypo()) { 442 ConsumeToken(); 443 444 if (Tok.is(tok::code_completion)) { 445 cutOffParsing(); 446 Actions.CodeCompleteInitializer(getCurScope(), OmpPrivParm); 447 Actions.FinalizeDeclaration(OmpPrivParm); 448 return; 449 } 450 451 PreferredType.enterVariableInit(Tok.getLocation(), OmpPrivParm); 452 ExprResult Init = ParseInitializer(); 453 454 if (Init.isInvalid()) { 455 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); 456 Actions.ActOnInitializerError(OmpPrivParm); 457 } else { 458 Actions.AddInitializerToDecl(OmpPrivParm, Init.get(), 459 /*DirectInit=*/false); 460 } 461 } else if (Tok.is(tok::l_paren)) { 462 // Parse C++ direct initializer: '(' expression-list ')' 463 BalancedDelimiterTracker T(*this, tok::l_paren); 464 T.consumeOpen(); 465 466 ExprVector Exprs; 467 CommaLocsTy CommaLocs; 468 469 SourceLocation LParLoc = T.getOpenLocation(); 470 auto RunSignatureHelp = [this, OmpPrivParm, LParLoc, &Exprs]() { 471 QualType PreferredType = Actions.ProduceConstructorSignatureHelp( 472 getCurScope(), OmpPrivParm->getType()->getCanonicalTypeInternal(), 473 OmpPrivParm->getLocation(), Exprs, LParLoc); 474 CalledSignatureHelp = true; 475 return PreferredType; 476 }; 477 if (ParseExpressionList(Exprs, CommaLocs, [&] { 478 PreferredType.enterFunctionArgument(Tok.getLocation(), 479 RunSignatureHelp); 480 })) { 481 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) 482 RunSignatureHelp(); 483 Actions.ActOnInitializerError(OmpPrivParm); 484 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); 485 } else { 486 // Match the ')'. 487 SourceLocation RLoc = Tok.getLocation(); 488 if (!T.consumeClose()) 489 RLoc = T.getCloseLocation(); 490 491 assert(!Exprs.empty() && Exprs.size() - 1 == CommaLocs.size() && 492 "Unexpected number of commas!"); 493 494 ExprResult Initializer = 495 Actions.ActOnParenListExpr(T.getOpenLocation(), RLoc, Exprs); 496 Actions.AddInitializerToDecl(OmpPrivParm, Initializer.get(), 497 /*DirectInit=*/true); 498 } 499 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 500 // Parse C++0x braced-init-list. 501 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 502 503 ExprResult Init(ParseBraceInitializer()); 504 505 if (Init.isInvalid()) { 506 Actions.ActOnInitializerError(OmpPrivParm); 507 } else { 508 Actions.AddInitializerToDecl(OmpPrivParm, Init.get(), 509 /*DirectInit=*/true); 510 } 511 } else { 512 Actions.ActOnUninitializedDecl(OmpPrivParm); 513 } 514 } 515 516 /// Parses 'omp declare mapper' directive. 517 /// 518 /// declare-mapper-directive: 519 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifier> ':'] 520 /// <type> <var> ')' [<clause>[[,] <clause>] ... ] 521 /// annot_pragma_openmp_end 522 /// <mapper-identifier> and <var> are base language identifiers. 523 /// 524 Parser::DeclGroupPtrTy 525 Parser::ParseOpenMPDeclareMapperDirective(AccessSpecifier AS) { 526 bool IsCorrect = true; 527 // Parse '(' 528 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 529 if (T.expectAndConsume(diag::err_expected_lparen_after, 530 getOpenMPDirectiveName(OMPD_declare_mapper).data())) { 531 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 532 return DeclGroupPtrTy(); 533 } 534 535 // Parse <mapper-identifier> 536 auto &DeclNames = Actions.getASTContext().DeclarationNames; 537 DeclarationName MapperId; 538 if (PP.LookAhead(0).is(tok::colon)) { 539 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) { 540 Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier); 541 IsCorrect = false; 542 } else { 543 MapperId = DeclNames.getIdentifier(Tok.getIdentifierInfo()); 544 } 545 ConsumeToken(); 546 // Consume ':'. 547 ExpectAndConsume(tok::colon); 548 } else { 549 // If no mapper identifier is provided, its name is "default" by default 550 MapperId = 551 DeclNames.getIdentifier(&Actions.getASTContext().Idents.get("default")); 552 } 553 554 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end)) 555 return DeclGroupPtrTy(); 556 557 // Parse <type> <var> 558 DeclarationName VName; 559 QualType MapperType; 560 SourceRange Range; 561 TypeResult ParsedType = parseOpenMPDeclareMapperVarDecl(Range, VName, AS); 562 if (ParsedType.isUsable()) 563 MapperType = 564 Actions.ActOnOpenMPDeclareMapperType(Range.getBegin(), ParsedType); 565 if (MapperType.isNull()) 566 IsCorrect = false; 567 if (!IsCorrect) { 568 SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch); 569 return DeclGroupPtrTy(); 570 } 571 572 // Consume ')'. 573 IsCorrect &= !T.consumeClose(); 574 if (!IsCorrect) { 575 SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch); 576 return DeclGroupPtrTy(); 577 } 578 579 // Enter scope. 580 DeclarationNameInfo DirName; 581 SourceLocation Loc = Tok.getLocation(); 582 unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope | 583 Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope; 584 ParseScope OMPDirectiveScope(this, ScopeFlags); 585 Actions.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, getCurScope(), Loc); 586 587 // Add the mapper variable declaration. 588 ExprResult MapperVarRef = Actions.ActOnOpenMPDeclareMapperDirectiveVarDecl( 589 getCurScope(), MapperType, Range.getBegin(), VName); 590 591 // Parse map clauses. 592 SmallVector<OMPClause *, 6> Clauses; 593 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 594 OpenMPClauseKind CKind = Tok.isAnnotation() 595 ? OMPC_unknown 596 : getOpenMPClauseKind(PP.getSpelling(Tok)); 597 Actions.StartOpenMPClause(CKind); 598 OMPClause *Clause = 599 ParseOpenMPClause(OMPD_declare_mapper, CKind, Clauses.empty()); 600 if (Clause) 601 Clauses.push_back(Clause); 602 else 603 IsCorrect = false; 604 // Skip ',' if any. 605 if (Tok.is(tok::comma)) 606 ConsumeToken(); 607 Actions.EndOpenMPClause(); 608 } 609 if (Clauses.empty()) { 610 Diag(Tok, diag::err_omp_expected_clause) 611 << getOpenMPDirectiveName(OMPD_declare_mapper); 612 IsCorrect = false; 613 } 614 615 // Exit scope. 616 Actions.EndOpenMPDSABlock(nullptr); 617 OMPDirectiveScope.Exit(); 618 DeclGroupPtrTy DG = Actions.ActOnOpenMPDeclareMapperDirective( 619 getCurScope(), Actions.getCurLexicalContext(), MapperId, MapperType, 620 Range.getBegin(), VName, AS, MapperVarRef.get(), Clauses); 621 if (!IsCorrect) 622 return DeclGroupPtrTy(); 623 624 return DG; 625 } 626 627 TypeResult Parser::parseOpenMPDeclareMapperVarDecl(SourceRange &Range, 628 DeclarationName &Name, 629 AccessSpecifier AS) { 630 // Parse the common declaration-specifiers piece. 631 Parser::DeclSpecContext DSC = Parser::DeclSpecContext::DSC_type_specifier; 632 DeclSpec DS(AttrFactory); 633 ParseSpecifierQualifierList(DS, AS, DSC); 634 635 // Parse the declarator. 636 DeclaratorContext Context = DeclaratorContext::Prototype; 637 Declarator DeclaratorInfo(DS, Context); 638 ParseDeclarator(DeclaratorInfo); 639 Range = DeclaratorInfo.getSourceRange(); 640 if (DeclaratorInfo.getIdentifier() == nullptr) { 641 Diag(Tok.getLocation(), diag::err_omp_mapper_expected_declarator); 642 return true; 643 } 644 Name = Actions.GetNameForDeclarator(DeclaratorInfo).getName(); 645 646 return Actions.ActOnOpenMPDeclareMapperVarDecl(getCurScope(), DeclaratorInfo); 647 } 648 649 namespace { 650 /// RAII that recreates function context for correct parsing of clauses of 651 /// 'declare simd' construct. 652 /// OpenMP, 2.8.2 declare simd Construct 653 /// The expressions appearing in the clauses of this directive are evaluated in 654 /// the scope of the arguments of the function declaration or definition. 655 class FNContextRAII final { 656 Parser &P; 657 Sema::CXXThisScopeRAII *ThisScope; 658 Parser::MultiParseScope Scopes; 659 bool HasFunScope = false; 660 FNContextRAII() = delete; 661 FNContextRAII(const FNContextRAII &) = delete; 662 FNContextRAII &operator=(const FNContextRAII &) = delete; 663 664 public: 665 FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P), Scopes(P) { 666 Decl *D = *Ptr.get().begin(); 667 NamedDecl *ND = dyn_cast<NamedDecl>(D); 668 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext()); 669 Sema &Actions = P.getActions(); 670 671 // Allow 'this' within late-parsed attributes. 672 ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, Qualifiers(), 673 ND && ND->isCXXInstanceMember()); 674 675 // If the Decl is templatized, add template parameters to scope. 676 // FIXME: Track CurTemplateDepth? 677 P.ReenterTemplateScopes(Scopes, D); 678 679 // If the Decl is on a function, add function parameters to the scope. 680 if (D->isFunctionOrFunctionTemplate()) { 681 HasFunScope = true; 682 Scopes.Enter(Scope::FnScope | Scope::DeclScope | 683 Scope::CompoundStmtScope); 684 Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D); 685 } 686 } 687 ~FNContextRAII() { 688 if (HasFunScope) 689 P.getActions().ActOnExitFunctionContext(); 690 delete ThisScope; 691 } 692 }; 693 } // namespace 694 695 /// Parses clauses for 'declare simd' directive. 696 /// clause: 697 /// 'inbranch' | 'notinbranch' 698 /// 'simdlen' '(' <expr> ')' 699 /// { 'uniform' '(' <argument_list> ')' } 700 /// { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' } 701 /// { 'linear '(' <argument_list> [ ':' <step> ] ')' } 702 static bool parseDeclareSimdClauses( 703 Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen, 704 SmallVectorImpl<Expr *> &Uniforms, SmallVectorImpl<Expr *> &Aligneds, 705 SmallVectorImpl<Expr *> &Alignments, SmallVectorImpl<Expr *> &Linears, 706 SmallVectorImpl<unsigned> &LinModifiers, SmallVectorImpl<Expr *> &Steps) { 707 SourceRange BSRange; 708 const Token &Tok = P.getCurToken(); 709 bool IsError = false; 710 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 711 if (Tok.isNot(tok::identifier)) 712 break; 713 OMPDeclareSimdDeclAttr::BranchStateTy Out; 714 IdentifierInfo *II = Tok.getIdentifierInfo(); 715 StringRef ClauseName = II->getName(); 716 // Parse 'inranch|notinbranch' clauses. 717 if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) { 718 if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) { 719 P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch) 720 << ClauseName 721 << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange; 722 IsError = true; 723 } 724 BS = Out; 725 BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc()); 726 P.ConsumeToken(); 727 } else if (ClauseName.equals("simdlen")) { 728 if (SimdLen.isUsable()) { 729 P.Diag(Tok, diag::err_omp_more_one_clause) 730 << getOpenMPDirectiveName(OMPD_declare_simd) << ClauseName << 0; 731 IsError = true; 732 } 733 P.ConsumeToken(); 734 SourceLocation RLoc; 735 SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc); 736 if (SimdLen.isInvalid()) 737 IsError = true; 738 } else { 739 OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName); 740 if (CKind == OMPC_uniform || CKind == OMPC_aligned || 741 CKind == OMPC_linear) { 742 Parser::OpenMPVarListDataTy Data; 743 SmallVectorImpl<Expr *> *Vars = &Uniforms; 744 if (CKind == OMPC_aligned) { 745 Vars = &Aligneds; 746 } else if (CKind == OMPC_linear) { 747 Data.ExtraModifier = OMPC_LINEAR_val; 748 Vars = &Linears; 749 } 750 751 P.ConsumeToken(); 752 if (P.ParseOpenMPVarList(OMPD_declare_simd, 753 getOpenMPClauseKind(ClauseName), *Vars, Data)) 754 IsError = true; 755 if (CKind == OMPC_aligned) { 756 Alignments.append(Aligneds.size() - Alignments.size(), 757 Data.DepModOrTailExpr); 758 } else if (CKind == OMPC_linear) { 759 assert(0 <= Data.ExtraModifier && 760 Data.ExtraModifier <= OMPC_LINEAR_unknown && 761 "Unexpected linear modifier."); 762 if (P.getActions().CheckOpenMPLinearModifier( 763 static_cast<OpenMPLinearClauseKind>(Data.ExtraModifier), 764 Data.ExtraModifierLoc)) 765 Data.ExtraModifier = OMPC_LINEAR_val; 766 LinModifiers.append(Linears.size() - LinModifiers.size(), 767 Data.ExtraModifier); 768 Steps.append(Linears.size() - Steps.size(), Data.DepModOrTailExpr); 769 } 770 } else 771 // TODO: add parsing of other clauses. 772 break; 773 } 774 // Skip ',' if any. 775 if (Tok.is(tok::comma)) 776 P.ConsumeToken(); 777 } 778 return IsError; 779 } 780 781 /// Parse clauses for '#pragma omp declare simd'. 782 Parser::DeclGroupPtrTy 783 Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr, 784 CachedTokens &Toks, SourceLocation Loc) { 785 PP.EnterToken(Tok, /*IsReinject*/ true); 786 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true, 787 /*IsReinject*/ true); 788 // Consume the previously pushed token. 789 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 790 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 791 792 FNContextRAII FnContext(*this, Ptr); 793 OMPDeclareSimdDeclAttr::BranchStateTy BS = 794 OMPDeclareSimdDeclAttr::BS_Undefined; 795 ExprResult Simdlen; 796 SmallVector<Expr *, 4> Uniforms; 797 SmallVector<Expr *, 4> Aligneds; 798 SmallVector<Expr *, 4> Alignments; 799 SmallVector<Expr *, 4> Linears; 800 SmallVector<unsigned, 4> LinModifiers; 801 SmallVector<Expr *, 4> Steps; 802 bool IsError = 803 parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds, 804 Alignments, Linears, LinModifiers, Steps); 805 skipUntilPragmaOpenMPEnd(OMPD_declare_simd); 806 // Skip the last annot_pragma_openmp_end. 807 SourceLocation EndLoc = ConsumeAnnotationToken(); 808 if (IsError) 809 return Ptr; 810 return Actions.ActOnOpenMPDeclareSimdDirective( 811 Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears, 812 LinModifiers, Steps, SourceRange(Loc, EndLoc)); 813 } 814 815 namespace { 816 /// Constant used in the diagnostics to distinguish the levels in an OpenMP 817 /// contexts: selector-set={selector(trait, ...), ...}, .... 818 enum OMPContextLvl { 819 CONTEXT_SELECTOR_SET_LVL = 0, 820 CONTEXT_SELECTOR_LVL = 1, 821 CONTEXT_TRAIT_LVL = 2, 822 }; 823 824 static StringRef stringLiteralParser(Parser &P) { 825 ExprResult Res = P.ParseStringLiteralExpression(true); 826 return Res.isUsable() ? Res.getAs<StringLiteral>()->getString() : ""; 827 } 828 829 static StringRef getNameFromIdOrString(Parser &P, Token &Tok, 830 OMPContextLvl Lvl) { 831 if (Tok.is(tok::identifier)) { 832 llvm::SmallString<16> Buffer; 833 StringRef Name = P.getPreprocessor().getSpelling(Tok, Buffer); 834 (void)P.ConsumeToken(); 835 return Name; 836 } 837 838 if (tok::isStringLiteral(Tok.getKind())) 839 return stringLiteralParser(P); 840 841 P.Diag(Tok.getLocation(), 842 diag::warn_omp_declare_variant_string_literal_or_identifier) 843 << Lvl; 844 return ""; 845 } 846 847 static bool checkForDuplicates(Parser &P, StringRef Name, 848 SourceLocation NameLoc, 849 llvm::StringMap<SourceLocation> &Seen, 850 OMPContextLvl Lvl) { 851 auto Res = Seen.try_emplace(Name, NameLoc); 852 if (Res.second) 853 return false; 854 855 // Each trait-set-selector-name, trait-selector-name and trait-name can 856 // only be specified once. 857 P.Diag(NameLoc, diag::warn_omp_declare_variant_ctx_mutiple_use) 858 << Lvl << Name; 859 P.Diag(Res.first->getValue(), diag::note_omp_declare_variant_ctx_used_here) 860 << Lvl << Name; 861 return true; 862 } 863 } // namespace 864 865 void Parser::parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty, 866 llvm::omp::TraitSet Set, 867 llvm::omp::TraitSelector Selector, 868 llvm::StringMap<SourceLocation> &Seen) { 869 TIProperty.Kind = TraitProperty::invalid; 870 871 SourceLocation NameLoc = Tok.getLocation(); 872 StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_TRAIT_LVL); 873 if (Name.empty()) { 874 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options) 875 << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector); 876 return; 877 } 878 879 TIProperty.RawString = Name; 880 TIProperty.Kind = getOpenMPContextTraitPropertyKind(Set, Selector, Name); 881 if (TIProperty.Kind != TraitProperty::invalid) { 882 if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_TRAIT_LVL)) 883 TIProperty.Kind = TraitProperty::invalid; 884 return; 885 } 886 887 // It follows diagnosis and helping notes. 888 // FIXME: We should move the diagnosis string generation into libFrontend. 889 Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_property) 890 << Name << getOpenMPContextTraitSelectorName(Selector) 891 << getOpenMPContextTraitSetName(Set); 892 893 TraitSet SetForName = getOpenMPContextTraitSetKind(Name); 894 if (SetForName != TraitSet::invalid) { 895 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a) 896 << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_TRAIT_LVL; 897 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 898 << Name << "<selector-name>" 899 << "(<property-name>)"; 900 return; 901 } 902 TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name); 903 if (SelectorForName != TraitSelector::invalid) { 904 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a) 905 << Name << CONTEXT_SELECTOR_LVL << CONTEXT_TRAIT_LVL; 906 bool AllowsTraitScore = false; 907 bool RequiresProperty = false; 908 isValidTraitSelectorForTraitSet( 909 SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName), 910 AllowsTraitScore, RequiresProperty); 911 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 912 << getOpenMPContextTraitSetName( 913 getOpenMPContextTraitSetForSelector(SelectorForName)) 914 << Name << (RequiresProperty ? "(<property-name>)" : ""); 915 return; 916 } 917 for (const auto &PotentialSet : 918 {TraitSet::construct, TraitSet::user, TraitSet::implementation, 919 TraitSet::device}) { 920 TraitProperty PropertyForName = 921 getOpenMPContextTraitPropertyKind(PotentialSet, Selector, Name); 922 if (PropertyForName == TraitProperty::invalid) 923 continue; 924 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 925 << getOpenMPContextTraitSetName( 926 getOpenMPContextTraitSetForProperty(PropertyForName)) 927 << getOpenMPContextTraitSelectorName( 928 getOpenMPContextTraitSelectorForProperty(PropertyForName)) 929 << ("(" + Name + ")").str(); 930 return; 931 } 932 Diag(NameLoc, diag::note_omp_declare_variant_ctx_options) 933 << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector); 934 } 935 936 static bool checkExtensionProperty(Parser &P, SourceLocation Loc, 937 OMPTraitProperty &TIProperty, 938 OMPTraitSelector &TISelector, 939 llvm::StringMap<SourceLocation> &Seen) { 940 assert(TISelector.Kind == 941 llvm::omp::TraitSelector::implementation_extension && 942 "Only for extension properties, e.g., " 943 "`implementation={extension(PROPERTY)}`"); 944 if (TIProperty.Kind == TraitProperty::invalid) 945 return false; 946 947 if (TIProperty.Kind == 948 TraitProperty::implementation_extension_disable_implicit_base) 949 return true; 950 951 if (TIProperty.Kind == 952 TraitProperty::implementation_extension_allow_templates) 953 return true; 954 955 auto IsMatchExtension = [](OMPTraitProperty &TP) { 956 return (TP.Kind == 957 llvm::omp::TraitProperty::implementation_extension_match_all || 958 TP.Kind == 959 llvm::omp::TraitProperty::implementation_extension_match_any || 960 TP.Kind == 961 llvm::omp::TraitProperty::implementation_extension_match_none); 962 }; 963 964 if (IsMatchExtension(TIProperty)) { 965 for (OMPTraitProperty &SeenProp : TISelector.Properties) 966 if (IsMatchExtension(SeenProp)) { 967 P.Diag(Loc, diag::err_omp_variant_ctx_second_match_extension); 968 StringRef SeenName = llvm::omp::getOpenMPContextTraitPropertyName( 969 SeenProp.Kind, SeenProp.RawString); 970 SourceLocation SeenLoc = Seen[SeenName]; 971 P.Diag(SeenLoc, diag::note_omp_declare_variant_ctx_used_here) 972 << CONTEXT_TRAIT_LVL << SeenName; 973 return false; 974 } 975 return true; 976 } 977 978 llvm_unreachable("Unknown extension property!"); 979 } 980 981 void Parser::parseOMPContextProperty(OMPTraitSelector &TISelector, 982 llvm::omp::TraitSet Set, 983 llvm::StringMap<SourceLocation> &Seen) { 984 assert(TISelector.Kind != TraitSelector::user_condition && 985 "User conditions are special properties not handled here!"); 986 987 SourceLocation PropertyLoc = Tok.getLocation(); 988 OMPTraitProperty TIProperty; 989 parseOMPTraitPropertyKind(TIProperty, Set, TISelector.Kind, Seen); 990 991 if (TISelector.Kind == llvm::omp::TraitSelector::implementation_extension) 992 if (!checkExtensionProperty(*this, Tok.getLocation(), TIProperty, 993 TISelector, Seen)) 994 TIProperty.Kind = TraitProperty::invalid; 995 996 // If we have an invalid property here we already issued a warning. 997 if (TIProperty.Kind == TraitProperty::invalid) { 998 if (PropertyLoc != Tok.getLocation()) 999 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here) 1000 << CONTEXT_TRAIT_LVL; 1001 return; 1002 } 1003 1004 if (isValidTraitPropertyForTraitSetAndSelector(TIProperty.Kind, 1005 TISelector.Kind, Set)) { 1006 1007 // If we make it here the property, selector, set, score, condition, ... are 1008 // all valid (or have been corrected). Thus we can record the property. 1009 TISelector.Properties.push_back(TIProperty); 1010 return; 1011 } 1012 1013 Diag(PropertyLoc, diag::warn_omp_ctx_incompatible_property_for_selector) 1014 << getOpenMPContextTraitPropertyName(TIProperty.Kind, 1015 TIProperty.RawString) 1016 << getOpenMPContextTraitSelectorName(TISelector.Kind) 1017 << getOpenMPContextTraitSetName(Set); 1018 Diag(PropertyLoc, diag::note_omp_ctx_compatible_set_and_selector_for_property) 1019 << getOpenMPContextTraitPropertyName(TIProperty.Kind, 1020 TIProperty.RawString) 1021 << getOpenMPContextTraitSelectorName( 1022 getOpenMPContextTraitSelectorForProperty(TIProperty.Kind)) 1023 << getOpenMPContextTraitSetName( 1024 getOpenMPContextTraitSetForProperty(TIProperty.Kind)); 1025 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here) 1026 << CONTEXT_TRAIT_LVL; 1027 } 1028 1029 void Parser::parseOMPTraitSelectorKind(OMPTraitSelector &TISelector, 1030 llvm::omp::TraitSet Set, 1031 llvm::StringMap<SourceLocation> &Seen) { 1032 TISelector.Kind = TraitSelector::invalid; 1033 1034 SourceLocation NameLoc = Tok.getLocation(); 1035 StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_LVL); 1036 if (Name.empty()) { 1037 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options) 1038 << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set); 1039 return; 1040 } 1041 1042 TISelector.Kind = getOpenMPContextTraitSelectorKind(Name); 1043 if (TISelector.Kind != TraitSelector::invalid) { 1044 if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_SELECTOR_LVL)) 1045 TISelector.Kind = TraitSelector::invalid; 1046 return; 1047 } 1048 1049 // It follows diagnosis and helping notes. 1050 Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_selector) 1051 << Name << getOpenMPContextTraitSetName(Set); 1052 1053 TraitSet SetForName = getOpenMPContextTraitSetKind(Name); 1054 if (SetForName != TraitSet::invalid) { 1055 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a) 1056 << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_SELECTOR_LVL; 1057 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 1058 << Name << "<selector-name>" 1059 << "<property-name>"; 1060 return; 1061 } 1062 for (const auto &PotentialSet : 1063 {TraitSet::construct, TraitSet::user, TraitSet::implementation, 1064 TraitSet::device}) { 1065 TraitProperty PropertyForName = getOpenMPContextTraitPropertyKind( 1066 PotentialSet, TraitSelector::invalid, Name); 1067 if (PropertyForName == TraitProperty::invalid) 1068 continue; 1069 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a) 1070 << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_LVL; 1071 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 1072 << getOpenMPContextTraitSetName( 1073 getOpenMPContextTraitSetForProperty(PropertyForName)) 1074 << getOpenMPContextTraitSelectorName( 1075 getOpenMPContextTraitSelectorForProperty(PropertyForName)) 1076 << ("(" + Name + ")").str(); 1077 return; 1078 } 1079 Diag(NameLoc, diag::note_omp_declare_variant_ctx_options) 1080 << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set); 1081 } 1082 1083 /// Parse optional 'score' '(' <expr> ')' ':'. 1084 static ExprResult parseContextScore(Parser &P) { 1085 ExprResult ScoreExpr; 1086 llvm::SmallString<16> Buffer; 1087 StringRef SelectorName = 1088 P.getPreprocessor().getSpelling(P.getCurToken(), Buffer); 1089 if (!SelectorName.equals("score")) 1090 return ScoreExpr; 1091 (void)P.ConsumeToken(); 1092 SourceLocation RLoc; 1093 ScoreExpr = P.ParseOpenMPParensExpr(SelectorName, RLoc); 1094 // Parse ':' 1095 if (P.getCurToken().is(tok::colon)) 1096 (void)P.ConsumeAnyToken(); 1097 else 1098 P.Diag(P.getCurToken(), diag::warn_omp_declare_variant_expected) 1099 << "':'" 1100 << "score expression"; 1101 return ScoreExpr; 1102 } 1103 1104 /// Parses an OpenMP context selector. 1105 /// 1106 /// <trait-selector-name> ['('[<trait-score>] <trait-property> [, <t-p>]* ')'] 1107 void Parser::parseOMPContextSelector( 1108 OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, 1109 llvm::StringMap<SourceLocation> &SeenSelectors) { 1110 unsigned short OuterPC = ParenCount; 1111 1112 // If anything went wrong we issue an error or warning and then skip the rest 1113 // of the selector. However, commas are ambiguous so we look for the nesting 1114 // of parentheses here as well. 1115 auto FinishSelector = [OuterPC, this]() -> void { 1116 bool Done = false; 1117 while (!Done) { 1118 while (!SkipUntil({tok::r_brace, tok::r_paren, tok::comma, 1119 tok::annot_pragma_openmp_end}, 1120 StopBeforeMatch)) 1121 ; 1122 if (Tok.is(tok::r_paren) && OuterPC > ParenCount) 1123 (void)ConsumeParen(); 1124 if (OuterPC <= ParenCount) { 1125 Done = true; 1126 break; 1127 } 1128 if (!Tok.is(tok::comma) && !Tok.is(tok::r_paren)) { 1129 Done = true; 1130 break; 1131 } 1132 (void)ConsumeAnyToken(); 1133 } 1134 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here) 1135 << CONTEXT_SELECTOR_LVL; 1136 }; 1137 1138 SourceLocation SelectorLoc = Tok.getLocation(); 1139 parseOMPTraitSelectorKind(TISelector, Set, SeenSelectors); 1140 if (TISelector.Kind == TraitSelector::invalid) 1141 return FinishSelector(); 1142 1143 bool AllowsTraitScore = false; 1144 bool RequiresProperty = false; 1145 if (!isValidTraitSelectorForTraitSet(TISelector.Kind, Set, AllowsTraitScore, 1146 RequiresProperty)) { 1147 Diag(SelectorLoc, diag::warn_omp_ctx_incompatible_selector_for_set) 1148 << getOpenMPContextTraitSelectorName(TISelector.Kind) 1149 << getOpenMPContextTraitSetName(Set); 1150 Diag(SelectorLoc, diag::note_omp_ctx_compatible_set_for_selector) 1151 << getOpenMPContextTraitSelectorName(TISelector.Kind) 1152 << getOpenMPContextTraitSetName( 1153 getOpenMPContextTraitSetForSelector(TISelector.Kind)) 1154 << RequiresProperty; 1155 return FinishSelector(); 1156 } 1157 1158 if (!RequiresProperty) { 1159 TISelector.Properties.push_back( 1160 {getOpenMPContextTraitPropertyForSelector(TISelector.Kind), 1161 getOpenMPContextTraitSelectorName(TISelector.Kind)}); 1162 return; 1163 } 1164 1165 if (!Tok.is(tok::l_paren)) { 1166 Diag(SelectorLoc, diag::warn_omp_ctx_selector_without_properties) 1167 << getOpenMPContextTraitSelectorName(TISelector.Kind) 1168 << getOpenMPContextTraitSetName(Set); 1169 return FinishSelector(); 1170 } 1171 1172 if (TISelector.Kind == TraitSelector::user_condition) { 1173 SourceLocation RLoc; 1174 ExprResult Condition = ParseOpenMPParensExpr("user condition", RLoc); 1175 if (!Condition.isUsable()) 1176 return FinishSelector(); 1177 TISelector.ScoreOrCondition = Condition.get(); 1178 TISelector.Properties.push_back( 1179 {TraitProperty::user_condition_unknown, "<condition>"}); 1180 return; 1181 } 1182 1183 BalancedDelimiterTracker BDT(*this, tok::l_paren, 1184 tok::annot_pragma_openmp_end); 1185 // Parse '('. 1186 (void)BDT.consumeOpen(); 1187 1188 SourceLocation ScoreLoc = Tok.getLocation(); 1189 ExprResult Score = parseContextScore(*this); 1190 1191 if (!AllowsTraitScore && !Score.isUnset()) { 1192 if (Score.isUsable()) { 1193 Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property) 1194 << getOpenMPContextTraitSelectorName(TISelector.Kind) 1195 << getOpenMPContextTraitSetName(Set) << Score.get(); 1196 } else { 1197 Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property) 1198 << getOpenMPContextTraitSelectorName(TISelector.Kind) 1199 << getOpenMPContextTraitSetName(Set) << "<invalid>"; 1200 } 1201 Score = ExprResult(); 1202 } 1203 1204 if (Score.isUsable()) 1205 TISelector.ScoreOrCondition = Score.get(); 1206 1207 llvm::StringMap<SourceLocation> SeenProperties; 1208 do { 1209 parseOMPContextProperty(TISelector, Set, SeenProperties); 1210 } while (TryConsumeToken(tok::comma)); 1211 1212 // Parse ')'. 1213 BDT.consumeClose(); 1214 } 1215 1216 void Parser::parseOMPTraitSetKind(OMPTraitSet &TISet, 1217 llvm::StringMap<SourceLocation> &Seen) { 1218 TISet.Kind = TraitSet::invalid; 1219 1220 SourceLocation NameLoc = Tok.getLocation(); 1221 StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_SET_LVL); 1222 if (Name.empty()) { 1223 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options) 1224 << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets(); 1225 return; 1226 } 1227 1228 TISet.Kind = getOpenMPContextTraitSetKind(Name); 1229 if (TISet.Kind != TraitSet::invalid) { 1230 if (checkForDuplicates(*this, Name, NameLoc, Seen, 1231 CONTEXT_SELECTOR_SET_LVL)) 1232 TISet.Kind = TraitSet::invalid; 1233 return; 1234 } 1235 1236 // It follows diagnosis and helping notes. 1237 Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_set) << Name; 1238 1239 TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name); 1240 if (SelectorForName != TraitSelector::invalid) { 1241 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a) 1242 << Name << CONTEXT_SELECTOR_LVL << CONTEXT_SELECTOR_SET_LVL; 1243 bool AllowsTraitScore = false; 1244 bool RequiresProperty = false; 1245 isValidTraitSelectorForTraitSet( 1246 SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName), 1247 AllowsTraitScore, RequiresProperty); 1248 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 1249 << getOpenMPContextTraitSetName( 1250 getOpenMPContextTraitSetForSelector(SelectorForName)) 1251 << Name << (RequiresProperty ? "(<property-name>)" : ""); 1252 return; 1253 } 1254 for (const auto &PotentialSet : 1255 {TraitSet::construct, TraitSet::user, TraitSet::implementation, 1256 TraitSet::device}) { 1257 TraitProperty PropertyForName = getOpenMPContextTraitPropertyKind( 1258 PotentialSet, TraitSelector::invalid, Name); 1259 if (PropertyForName == TraitProperty::invalid) 1260 continue; 1261 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a) 1262 << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_SET_LVL; 1263 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 1264 << getOpenMPContextTraitSetName( 1265 getOpenMPContextTraitSetForProperty(PropertyForName)) 1266 << getOpenMPContextTraitSelectorName( 1267 getOpenMPContextTraitSelectorForProperty(PropertyForName)) 1268 << ("(" + Name + ")").str(); 1269 return; 1270 } 1271 Diag(NameLoc, diag::note_omp_declare_variant_ctx_options) 1272 << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets(); 1273 } 1274 1275 /// Parses an OpenMP context selector set. 1276 /// 1277 /// <trait-set-selector-name> '=' '{' <trait-selector> [, <trait-selector>]* '}' 1278 void Parser::parseOMPContextSelectorSet( 1279 OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets) { 1280 auto OuterBC = BraceCount; 1281 1282 // If anything went wrong we issue an error or warning and then skip the rest 1283 // of the set. However, commas are ambiguous so we look for the nesting 1284 // of braces here as well. 1285 auto FinishSelectorSet = [this, OuterBC]() -> void { 1286 bool Done = false; 1287 while (!Done) { 1288 while (!SkipUntil({tok::comma, tok::r_brace, tok::r_paren, 1289 tok::annot_pragma_openmp_end}, 1290 StopBeforeMatch)) 1291 ; 1292 if (Tok.is(tok::r_brace) && OuterBC > BraceCount) 1293 (void)ConsumeBrace(); 1294 if (OuterBC <= BraceCount) { 1295 Done = true; 1296 break; 1297 } 1298 if (!Tok.is(tok::comma) && !Tok.is(tok::r_brace)) { 1299 Done = true; 1300 break; 1301 } 1302 (void)ConsumeAnyToken(); 1303 } 1304 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here) 1305 << CONTEXT_SELECTOR_SET_LVL; 1306 }; 1307 1308 parseOMPTraitSetKind(TISet, SeenSets); 1309 if (TISet.Kind == TraitSet::invalid) 1310 return FinishSelectorSet(); 1311 1312 // Parse '='. 1313 if (!TryConsumeToken(tok::equal)) 1314 Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected) 1315 << "=" 1316 << ("context set name \"" + getOpenMPContextTraitSetName(TISet.Kind) + 1317 "\"") 1318 .str(); 1319 1320 // Parse '{'. 1321 if (Tok.is(tok::l_brace)) { 1322 (void)ConsumeBrace(); 1323 } else { 1324 Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected) 1325 << "{" 1326 << ("'=' that follows the context set name \"" + 1327 getOpenMPContextTraitSetName(TISet.Kind) + "\"") 1328 .str(); 1329 } 1330 1331 llvm::StringMap<SourceLocation> SeenSelectors; 1332 do { 1333 OMPTraitSelector TISelector; 1334 parseOMPContextSelector(TISelector, TISet.Kind, SeenSelectors); 1335 if (TISelector.Kind != TraitSelector::invalid && 1336 !TISelector.Properties.empty()) 1337 TISet.Selectors.push_back(TISelector); 1338 } while (TryConsumeToken(tok::comma)); 1339 1340 // Parse '}'. 1341 if (Tok.is(tok::r_brace)) { 1342 (void)ConsumeBrace(); 1343 } else { 1344 Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected) 1345 << "}" 1346 << ("context selectors for the context set \"" + 1347 getOpenMPContextTraitSetName(TISet.Kind) + "\"") 1348 .str(); 1349 } 1350 } 1351 1352 /// Parse OpenMP context selectors: 1353 /// 1354 /// <trait-set-selector> [, <trait-set-selector>]* 1355 bool Parser::parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI) { 1356 llvm::StringMap<SourceLocation> SeenSets; 1357 do { 1358 OMPTraitSet TISet; 1359 parseOMPContextSelectorSet(TISet, SeenSets); 1360 if (TISet.Kind != TraitSet::invalid && !TISet.Selectors.empty()) 1361 TI.Sets.push_back(TISet); 1362 } while (TryConsumeToken(tok::comma)); 1363 1364 return false; 1365 } 1366 1367 /// Parse clauses for '#pragma omp declare variant ( variant-func-id ) clause'. 1368 void Parser::ParseOMPDeclareVariantClauses(Parser::DeclGroupPtrTy Ptr, 1369 CachedTokens &Toks, 1370 SourceLocation Loc) { 1371 PP.EnterToken(Tok, /*IsReinject*/ true); 1372 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true, 1373 /*IsReinject*/ true); 1374 // Consume the previously pushed token. 1375 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 1376 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 1377 1378 FNContextRAII FnContext(*this, Ptr); 1379 // Parse function declaration id. 1380 SourceLocation RLoc; 1381 // Parse with IsAddressOfOperand set to true to parse methods as DeclRefExprs 1382 // instead of MemberExprs. 1383 ExprResult AssociatedFunction; 1384 { 1385 // Do not mark function as is used to prevent its emission if this is the 1386 // only place where it is used. 1387 EnterExpressionEvaluationContext Unevaluated( 1388 Actions, Sema::ExpressionEvaluationContext::Unevaluated); 1389 AssociatedFunction = ParseOpenMPParensExpr( 1390 getOpenMPDirectiveName(OMPD_declare_variant), RLoc, 1391 /*IsAddressOfOperand=*/true); 1392 } 1393 if (!AssociatedFunction.isUsable()) { 1394 if (!Tok.is(tok::annot_pragma_openmp_end)) 1395 while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch)) 1396 ; 1397 // Skip the last annot_pragma_openmp_end. 1398 (void)ConsumeAnnotationToken(); 1399 return; 1400 } 1401 1402 OMPTraitInfo *ParentTI = Actions.getOMPTraitInfoForSurroundingScope(); 1403 ASTContext &ASTCtx = Actions.getASTContext(); 1404 OMPTraitInfo &TI = ASTCtx.getNewOMPTraitInfo(); 1405 if (parseOMPDeclareVariantMatchClause(Loc, TI, ParentTI)) 1406 return; 1407 1408 Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData = 1409 Actions.checkOpenMPDeclareVariantFunction( 1410 Ptr, AssociatedFunction.get(), TI, 1411 SourceRange(Loc, Tok.getLocation())); 1412 1413 // Skip last tokens. 1414 while (Tok.isNot(tok::annot_pragma_openmp_end)) 1415 ConsumeAnyToken(); 1416 if (DeclVarData && !TI.Sets.empty()) 1417 Actions.ActOnOpenMPDeclareVariantDirective( 1418 DeclVarData->first, DeclVarData->second, TI, 1419 SourceRange(Loc, Tok.getLocation())); 1420 1421 // Skip the last annot_pragma_openmp_end. 1422 (void)ConsumeAnnotationToken(); 1423 } 1424 1425 bool Parser::parseOMPDeclareVariantMatchClause(SourceLocation Loc, 1426 OMPTraitInfo &TI, 1427 OMPTraitInfo *ParentTI) { 1428 // Parse 'match'. 1429 OpenMPClauseKind CKind = Tok.isAnnotation() 1430 ? OMPC_unknown 1431 : getOpenMPClauseKind(PP.getSpelling(Tok)); 1432 if (CKind != OMPC_match) { 1433 Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause) 1434 << getOpenMPClauseName(OMPC_match); 1435 while (!SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch)) 1436 ; 1437 // Skip the last annot_pragma_openmp_end. 1438 (void)ConsumeAnnotationToken(); 1439 return true; 1440 } 1441 (void)ConsumeToken(); 1442 // Parse '('. 1443 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 1444 if (T.expectAndConsume(diag::err_expected_lparen_after, 1445 getOpenMPClauseName(OMPC_match).data())) { 1446 while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch)) 1447 ; 1448 // Skip the last annot_pragma_openmp_end. 1449 (void)ConsumeAnnotationToken(); 1450 return true; 1451 } 1452 1453 // Parse inner context selectors. 1454 parseOMPContextSelectors(Loc, TI); 1455 1456 // Parse ')' 1457 (void)T.consumeClose(); 1458 1459 if (!ParentTI) 1460 return false; 1461 1462 // Merge the parent/outer trait info into the one we just parsed and diagnose 1463 // problems. 1464 // TODO: Keep some source location in the TI to provide better diagnostics. 1465 // TODO: Perform some kind of equivalence check on the condition and score 1466 // expressions. 1467 for (const OMPTraitSet &ParentSet : ParentTI->Sets) { 1468 bool MergedSet = false; 1469 for (OMPTraitSet &Set : TI.Sets) { 1470 if (Set.Kind != ParentSet.Kind) 1471 continue; 1472 MergedSet = true; 1473 for (const OMPTraitSelector &ParentSelector : ParentSet.Selectors) { 1474 bool MergedSelector = false; 1475 for (OMPTraitSelector &Selector : Set.Selectors) { 1476 if (Selector.Kind != ParentSelector.Kind) 1477 continue; 1478 MergedSelector = true; 1479 for (const OMPTraitProperty &ParentProperty : 1480 ParentSelector.Properties) { 1481 bool MergedProperty = false; 1482 for (OMPTraitProperty &Property : Selector.Properties) { 1483 // Ignore "equivalent" properties. 1484 if (Property.Kind != ParentProperty.Kind) 1485 continue; 1486 1487 // If the kind is the same but the raw string not, we don't want 1488 // to skip out on the property. 1489 MergedProperty |= Property.RawString == ParentProperty.RawString; 1490 1491 if (Property.RawString == ParentProperty.RawString && 1492 Selector.ScoreOrCondition == ParentSelector.ScoreOrCondition) 1493 continue; 1494 1495 if (Selector.Kind == llvm::omp::TraitSelector::user_condition) { 1496 Diag(Loc, diag::err_omp_declare_variant_nested_user_condition); 1497 } else if (Selector.ScoreOrCondition != 1498 ParentSelector.ScoreOrCondition) { 1499 Diag(Loc, diag::err_omp_declare_variant_duplicate_nested_trait) 1500 << getOpenMPContextTraitPropertyName( 1501 ParentProperty.Kind, ParentProperty.RawString) 1502 << getOpenMPContextTraitSelectorName(ParentSelector.Kind) 1503 << getOpenMPContextTraitSetName(ParentSet.Kind); 1504 } 1505 } 1506 if (!MergedProperty) 1507 Selector.Properties.push_back(ParentProperty); 1508 } 1509 } 1510 if (!MergedSelector) 1511 Set.Selectors.push_back(ParentSelector); 1512 } 1513 } 1514 if (!MergedSet) 1515 TI.Sets.push_back(ParentSet); 1516 } 1517 1518 return false; 1519 } 1520 1521 /// `omp assumes` or `omp begin/end assumes` <clause> [[,]<clause>]... 1522 /// where 1523 /// 1524 /// clause: 1525 /// 'ext_IMPL_DEFINED' 1526 /// 'absent' '(' directive-name [, directive-name]* ')' 1527 /// 'contains' '(' directive-name [, directive-name]* ')' 1528 /// 'holds' '(' scalar-expression ')' 1529 /// 'no_openmp' 1530 /// 'no_openmp_routines' 1531 /// 'no_parallelism' 1532 /// 1533 void Parser::ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind, 1534 SourceLocation Loc) { 1535 SmallVector<StringRef, 4> Assumptions; 1536 bool SkippedClauses = false; 1537 1538 auto SkipBraces = [&](llvm::StringRef Spelling, bool IssueNote) { 1539 BalancedDelimiterTracker T(*this, tok::l_paren, 1540 tok::annot_pragma_openmp_end); 1541 if (T.expectAndConsume(diag::err_expected_lparen_after, Spelling.data())) 1542 return; 1543 T.skipToEnd(); 1544 if (IssueNote && T.getCloseLocation().isValid()) 1545 Diag(T.getCloseLocation(), 1546 diag::note_omp_assumption_clause_continue_here); 1547 }; 1548 1549 /// Helper to determine which AssumptionClauseMapping (ACM) in the 1550 /// AssumptionClauseMappings table matches \p RawString. The return value is 1551 /// the index of the matching ACM into the table or -1 if there was no match. 1552 auto MatchACMClause = [&](StringRef RawString) { 1553 llvm::StringSwitch<int> SS(RawString); 1554 unsigned ACMIdx = 0; 1555 for (const AssumptionClauseMappingInfo &ACMI : AssumptionClauseMappings) { 1556 if (ACMI.StartsWith) 1557 SS.StartsWith(ACMI.Identifier, ACMIdx++); 1558 else 1559 SS.Case(ACMI.Identifier, ACMIdx++); 1560 } 1561 return SS.Default(-1); 1562 }; 1563 1564 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 1565 IdentifierInfo *II = nullptr; 1566 SourceLocation StartLoc = Tok.getLocation(); 1567 int Idx = -1; 1568 if (Tok.isAnyIdentifier()) { 1569 II = Tok.getIdentifierInfo(); 1570 Idx = MatchACMClause(II->getName()); 1571 } 1572 ConsumeAnyToken(); 1573 1574 bool NextIsLPar = Tok.is(tok::l_paren); 1575 // Handle unknown clauses by skipping them. 1576 if (Idx == -1) { 1577 Diag(StartLoc, diag::warn_omp_unknown_assumption_clause_missing_id) 1578 << llvm::omp::getOpenMPDirectiveName(DKind) 1579 << llvm::omp::getAllAssumeClauseOptions() << NextIsLPar; 1580 if (NextIsLPar) 1581 SkipBraces(II ? II->getName() : "", /* IssueNote */ true); 1582 SkippedClauses = true; 1583 continue; 1584 } 1585 const AssumptionClauseMappingInfo &ACMI = AssumptionClauseMappings[Idx]; 1586 if (ACMI.HasDirectiveList || ACMI.HasExpression) { 1587 // TODO: We ignore absent, contains, and holds assumptions for now. We 1588 // also do not verify the content in the parenthesis at all. 1589 SkippedClauses = true; 1590 SkipBraces(II->getName(), /* IssueNote */ false); 1591 continue; 1592 } 1593 1594 if (NextIsLPar) { 1595 Diag(Tok.getLocation(), 1596 diag::warn_omp_unknown_assumption_clause_without_args) 1597 << II; 1598 SkipBraces(II->getName(), /* IssueNote */ true); 1599 } 1600 1601 assert(II && "Expected an identifier clause!"); 1602 StringRef Assumption = II->getName(); 1603 if (ACMI.StartsWith) 1604 Assumption = Assumption.substr(ACMI.Identifier.size()); 1605 Assumptions.push_back(Assumption); 1606 } 1607 1608 Actions.ActOnOpenMPAssumesDirective(Loc, DKind, Assumptions, SkippedClauses); 1609 } 1610 1611 void Parser::ParseOpenMPEndAssumesDirective(SourceLocation Loc) { 1612 if (Actions.isInOpenMPAssumeScope()) 1613 Actions.ActOnOpenMPEndAssumesDirective(); 1614 else 1615 Diag(Loc, diag::err_expected_begin_assumes); 1616 } 1617 1618 /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'. 1619 /// 1620 /// default-clause: 1621 /// 'default' '(' 'none' | 'shared' | 'firstprivate' ') 1622 /// 1623 /// proc_bind-clause: 1624 /// 'proc_bind' '(' 'master' | 'close' | 'spread' ') 1625 /// 1626 /// device_type-clause: 1627 /// 'device_type' '(' 'host' | 'nohost' | 'any' )' 1628 namespace { 1629 struct SimpleClauseData { 1630 unsigned Type; 1631 SourceLocation Loc; 1632 SourceLocation LOpen; 1633 SourceLocation TypeLoc; 1634 SourceLocation RLoc; 1635 SimpleClauseData(unsigned Type, SourceLocation Loc, SourceLocation LOpen, 1636 SourceLocation TypeLoc, SourceLocation RLoc) 1637 : Type(Type), Loc(Loc), LOpen(LOpen), TypeLoc(TypeLoc), RLoc(RLoc) {} 1638 }; 1639 } // anonymous namespace 1640 1641 static Optional<SimpleClauseData> 1642 parseOpenMPSimpleClause(Parser &P, OpenMPClauseKind Kind) { 1643 const Token &Tok = P.getCurToken(); 1644 SourceLocation Loc = Tok.getLocation(); 1645 SourceLocation LOpen = P.ConsumeToken(); 1646 // Parse '('. 1647 BalancedDelimiterTracker T(P, tok::l_paren, tok::annot_pragma_openmp_end); 1648 if (T.expectAndConsume(diag::err_expected_lparen_after, 1649 getOpenMPClauseName(Kind).data())) 1650 return llvm::None; 1651 1652 unsigned Type = getOpenMPSimpleClauseType( 1653 Kind, Tok.isAnnotation() ? "" : P.getPreprocessor().getSpelling(Tok), 1654 P.getLangOpts()); 1655 SourceLocation TypeLoc = Tok.getLocation(); 1656 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 1657 Tok.isNot(tok::annot_pragma_openmp_end)) 1658 P.ConsumeAnyToken(); 1659 1660 // Parse ')'. 1661 SourceLocation RLoc = Tok.getLocation(); 1662 if (!T.consumeClose()) 1663 RLoc = T.getCloseLocation(); 1664 1665 return SimpleClauseData(Type, Loc, LOpen, TypeLoc, RLoc); 1666 } 1667 1668 void Parser::ParseOMPDeclareTargetClauses( 1669 Sema::DeclareTargetContextInfo &DTCI) { 1670 SourceLocation DeviceTypeLoc; 1671 bool RequiresToOrLinkClause = false; 1672 bool HasToOrLinkClause = false; 1673 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 1674 OMPDeclareTargetDeclAttr::MapTypeTy MT = OMPDeclareTargetDeclAttr::MT_To; 1675 bool HasIdentifier = Tok.is(tok::identifier); 1676 if (HasIdentifier) { 1677 // If we see any clause we need a to or link clause. 1678 RequiresToOrLinkClause = true; 1679 IdentifierInfo *II = Tok.getIdentifierInfo(); 1680 StringRef ClauseName = II->getName(); 1681 bool IsDeviceTypeClause = 1682 getLangOpts().OpenMP >= 50 && 1683 getOpenMPClauseKind(ClauseName) == OMPC_device_type; 1684 1685 bool IsToOrLinkClause = 1686 OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName, MT); 1687 assert((!IsDeviceTypeClause || !IsToOrLinkClause) && "Cannot be both!"); 1688 1689 if (!IsDeviceTypeClause && DTCI.Kind == OMPD_begin_declare_target) { 1690 Diag(Tok, diag::err_omp_declare_target_unexpected_clause) 1691 << ClauseName << 0; 1692 break; 1693 } 1694 if (!IsDeviceTypeClause && !IsToOrLinkClause) { 1695 Diag(Tok, diag::err_omp_declare_target_unexpected_clause) 1696 << ClauseName << (getLangOpts().OpenMP >= 50 ? 2 : 1); 1697 break; 1698 } 1699 1700 if (IsToOrLinkClause) 1701 HasToOrLinkClause = true; 1702 1703 // Parse 'device_type' clause and go to next clause if any. 1704 if (IsDeviceTypeClause) { 1705 Optional<SimpleClauseData> DevTypeData = 1706 parseOpenMPSimpleClause(*this, OMPC_device_type); 1707 if (DevTypeData.hasValue()) { 1708 if (DeviceTypeLoc.isValid()) { 1709 // We already saw another device_type clause, diagnose it. 1710 Diag(DevTypeData.getValue().Loc, 1711 diag::warn_omp_more_one_device_type_clause); 1712 break; 1713 } 1714 switch (static_cast<OpenMPDeviceType>(DevTypeData.getValue().Type)) { 1715 case OMPC_DEVICE_TYPE_any: 1716 DTCI.DT = OMPDeclareTargetDeclAttr::DT_Any; 1717 break; 1718 case OMPC_DEVICE_TYPE_host: 1719 DTCI.DT = OMPDeclareTargetDeclAttr::DT_Host; 1720 break; 1721 case OMPC_DEVICE_TYPE_nohost: 1722 DTCI.DT = OMPDeclareTargetDeclAttr::DT_NoHost; 1723 break; 1724 case OMPC_DEVICE_TYPE_unknown: 1725 llvm_unreachable("Unexpected device_type"); 1726 } 1727 DeviceTypeLoc = DevTypeData.getValue().Loc; 1728 } 1729 continue; 1730 } 1731 ConsumeToken(); 1732 } 1733 1734 if (DTCI.Kind == OMPD_declare_target || HasIdentifier) { 1735 auto &&Callback = [this, MT, &DTCI](CXXScopeSpec &SS, 1736 DeclarationNameInfo NameInfo) { 1737 NamedDecl *ND = 1738 Actions.lookupOpenMPDeclareTargetName(getCurScope(), SS, NameInfo); 1739 if (!ND) 1740 return; 1741 Sema::DeclareTargetContextInfo::MapInfo MI{MT, NameInfo.getLoc()}; 1742 bool FirstMapping = DTCI.ExplicitlyMapped.try_emplace(ND, MI).second; 1743 if (!FirstMapping) 1744 Diag(NameInfo.getLoc(), diag::err_omp_declare_target_multiple) 1745 << NameInfo.getName(); 1746 }; 1747 if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback, 1748 /*AllowScopeSpecifier=*/true)) 1749 break; 1750 } 1751 1752 if (Tok.is(tok::l_paren)) { 1753 Diag(Tok, 1754 diag::err_omp_begin_declare_target_unexpected_implicit_to_clause); 1755 break; 1756 } 1757 if (!HasIdentifier && Tok.isNot(tok::annot_pragma_openmp_end)) { 1758 Diag(Tok, 1759 diag::err_omp_declare_target_unexpected_clause_after_implicit_to); 1760 break; 1761 } 1762 1763 // Consume optional ','. 1764 if (Tok.is(tok::comma)) 1765 ConsumeToken(); 1766 } 1767 1768 // For declare target require at least 'to' or 'link' to be present. 1769 if (DTCI.Kind == OMPD_declare_target && RequiresToOrLinkClause && 1770 !HasToOrLinkClause) 1771 Diag(DTCI.Loc, diag::err_omp_declare_target_missing_to_or_link_clause); 1772 1773 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 1774 } 1775 1776 void Parser::skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind) { 1777 // The last seen token is annot_pragma_openmp_end - need to check for 1778 // extra tokens. 1779 if (Tok.is(tok::annot_pragma_openmp_end)) 1780 return; 1781 1782 Diag(Tok, diag::warn_omp_extra_tokens_at_eol) 1783 << getOpenMPDirectiveName(DKind); 1784 while (Tok.isNot(tok::annot_pragma_openmp_end)) 1785 ConsumeAnyToken(); 1786 } 1787 1788 void Parser::parseOMPEndDirective(OpenMPDirectiveKind BeginKind, 1789 OpenMPDirectiveKind ExpectedKind, 1790 OpenMPDirectiveKind FoundKind, 1791 SourceLocation BeginLoc, 1792 SourceLocation FoundLoc, 1793 bool SkipUntilOpenMPEnd) { 1794 int DiagSelection = ExpectedKind == OMPD_end_declare_target ? 0 : 1; 1795 1796 if (FoundKind == ExpectedKind) { 1797 ConsumeAnyToken(); 1798 skipUntilPragmaOpenMPEnd(ExpectedKind); 1799 return; 1800 } 1801 1802 Diag(FoundLoc, diag::err_expected_end_declare_target_or_variant) 1803 << DiagSelection; 1804 Diag(BeginLoc, diag::note_matching) 1805 << ("'#pragma omp " + getOpenMPDirectiveName(BeginKind) + "'").str(); 1806 if (SkipUntilOpenMPEnd) 1807 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 1808 } 1809 1810 void Parser::ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind, 1811 OpenMPDirectiveKind EndDKind, 1812 SourceLocation DKLoc) { 1813 parseOMPEndDirective(BeginDKind, OMPD_end_declare_target, EndDKind, DKLoc, 1814 Tok.getLocation(), 1815 /* SkipUntilOpenMPEnd */ false); 1816 // Skip the last annot_pragma_openmp_end. 1817 if (Tok.is(tok::annot_pragma_openmp_end)) 1818 ConsumeAnnotationToken(); 1819 } 1820 1821 /// Parsing of declarative OpenMP directives. 1822 /// 1823 /// threadprivate-directive: 1824 /// annot_pragma_openmp 'threadprivate' simple-variable-list 1825 /// annot_pragma_openmp_end 1826 /// 1827 /// allocate-directive: 1828 /// annot_pragma_openmp 'allocate' simple-variable-list [<clause>] 1829 /// annot_pragma_openmp_end 1830 /// 1831 /// declare-reduction-directive: 1832 /// annot_pragma_openmp 'declare' 'reduction' [...] 1833 /// annot_pragma_openmp_end 1834 /// 1835 /// declare-mapper-directive: 1836 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':'] 1837 /// <type> <var> ')' [<clause>[[,] <clause>] ... ] 1838 /// annot_pragma_openmp_end 1839 /// 1840 /// declare-simd-directive: 1841 /// annot_pragma_openmp 'declare simd' {<clause> [,]} 1842 /// annot_pragma_openmp_end 1843 /// <function declaration/definition> 1844 /// 1845 /// requires directive: 1846 /// annot_pragma_openmp 'requires' <clause> [[[,] <clause>] ... ] 1847 /// annot_pragma_openmp_end 1848 /// 1849 /// assumes directive: 1850 /// annot_pragma_openmp 'assumes' <clause> [[[,] <clause>] ... ] 1851 /// annot_pragma_openmp_end 1852 /// or 1853 /// annot_pragma_openmp 'begin assumes' <clause> [[[,] <clause>] ... ] 1854 /// annot_pragma_openmp 'end assumes' 1855 /// annot_pragma_openmp_end 1856 /// 1857 Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl( 1858 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, bool Delayed, 1859 DeclSpec::TST TagType, Decl *Tag) { 1860 assert(Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) && 1861 "Not an OpenMP directive!"); 1862 ParsingOpenMPDirectiveRAII DirScope(*this); 1863 ParenBraceBracketBalancer BalancerRAIIObj(*this); 1864 1865 SourceLocation Loc; 1866 OpenMPDirectiveKind DKind; 1867 if (Delayed) { 1868 TentativeParsingAction TPA(*this); 1869 Loc = ConsumeAnnotationToken(); 1870 DKind = parseOpenMPDirectiveKind(*this); 1871 if (DKind == OMPD_declare_reduction || DKind == OMPD_declare_mapper) { 1872 // Need to delay parsing until completion of the parent class. 1873 TPA.Revert(); 1874 CachedTokens Toks; 1875 unsigned Cnt = 1; 1876 Toks.push_back(Tok); 1877 while (Cnt && Tok.isNot(tok::eof)) { 1878 (void)ConsumeAnyToken(); 1879 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) 1880 ++Cnt; 1881 else if (Tok.is(tok::annot_pragma_openmp_end)) 1882 --Cnt; 1883 Toks.push_back(Tok); 1884 } 1885 // Skip last annot_pragma_openmp_end. 1886 if (Cnt == 0) 1887 (void)ConsumeAnyToken(); 1888 auto *LP = new LateParsedPragma(this, AS); 1889 LP->takeToks(Toks); 1890 getCurrentClass().LateParsedDeclarations.push_back(LP); 1891 return nullptr; 1892 } 1893 TPA.Commit(); 1894 } else { 1895 Loc = ConsumeAnnotationToken(); 1896 DKind = parseOpenMPDirectiveKind(*this); 1897 } 1898 1899 switch (DKind) { 1900 case OMPD_threadprivate: { 1901 ConsumeToken(); 1902 DeclDirectiveListParserHelper Helper(this, DKind); 1903 if (!ParseOpenMPSimpleVarList(DKind, Helper, 1904 /*AllowScopeSpecifier=*/true)) { 1905 skipUntilPragmaOpenMPEnd(DKind); 1906 // Skip the last annot_pragma_openmp_end. 1907 ConsumeAnnotationToken(); 1908 return Actions.ActOnOpenMPThreadprivateDirective(Loc, 1909 Helper.getIdentifiers()); 1910 } 1911 break; 1912 } 1913 case OMPD_allocate: { 1914 ConsumeToken(); 1915 DeclDirectiveListParserHelper Helper(this, DKind); 1916 if (!ParseOpenMPSimpleVarList(DKind, Helper, 1917 /*AllowScopeSpecifier=*/true)) { 1918 SmallVector<OMPClause *, 1> Clauses; 1919 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 1920 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, 1921 llvm::omp::Clause_enumSize + 1> 1922 FirstClauses(llvm::omp::Clause_enumSize + 1); 1923 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 1924 OpenMPClauseKind CKind = 1925 Tok.isAnnotation() ? OMPC_unknown 1926 : getOpenMPClauseKind(PP.getSpelling(Tok)); 1927 Actions.StartOpenMPClause(CKind); 1928 OMPClause *Clause = ParseOpenMPClause( 1929 OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt()); 1930 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end, 1931 StopBeforeMatch); 1932 FirstClauses[unsigned(CKind)].setInt(true); 1933 if (Clause != nullptr) 1934 Clauses.push_back(Clause); 1935 if (Tok.is(tok::annot_pragma_openmp_end)) { 1936 Actions.EndOpenMPClause(); 1937 break; 1938 } 1939 // Skip ',' if any. 1940 if (Tok.is(tok::comma)) 1941 ConsumeToken(); 1942 Actions.EndOpenMPClause(); 1943 } 1944 skipUntilPragmaOpenMPEnd(DKind); 1945 } 1946 // Skip the last annot_pragma_openmp_end. 1947 ConsumeAnnotationToken(); 1948 return Actions.ActOnOpenMPAllocateDirective(Loc, Helper.getIdentifiers(), 1949 Clauses); 1950 } 1951 break; 1952 } 1953 case OMPD_requires: { 1954 SourceLocation StartLoc = ConsumeToken(); 1955 SmallVector<OMPClause *, 5> Clauses; 1956 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, 1957 llvm::omp::Clause_enumSize + 1> 1958 FirstClauses(llvm::omp::Clause_enumSize + 1); 1959 if (Tok.is(tok::annot_pragma_openmp_end)) { 1960 Diag(Tok, diag::err_omp_expected_clause) 1961 << getOpenMPDirectiveName(OMPD_requires); 1962 break; 1963 } 1964 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 1965 OpenMPClauseKind CKind = Tok.isAnnotation() 1966 ? OMPC_unknown 1967 : getOpenMPClauseKind(PP.getSpelling(Tok)); 1968 Actions.StartOpenMPClause(CKind); 1969 OMPClause *Clause = ParseOpenMPClause( 1970 OMPD_requires, CKind, !FirstClauses[unsigned(CKind)].getInt()); 1971 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end, 1972 StopBeforeMatch); 1973 FirstClauses[unsigned(CKind)].setInt(true); 1974 if (Clause != nullptr) 1975 Clauses.push_back(Clause); 1976 if (Tok.is(tok::annot_pragma_openmp_end)) { 1977 Actions.EndOpenMPClause(); 1978 break; 1979 } 1980 // Skip ',' if any. 1981 if (Tok.is(tok::comma)) 1982 ConsumeToken(); 1983 Actions.EndOpenMPClause(); 1984 } 1985 // Consume final annot_pragma_openmp_end 1986 if (Clauses.empty()) { 1987 Diag(Tok, diag::err_omp_expected_clause) 1988 << getOpenMPDirectiveName(OMPD_requires); 1989 ConsumeAnnotationToken(); 1990 return nullptr; 1991 } 1992 ConsumeAnnotationToken(); 1993 return Actions.ActOnOpenMPRequiresDirective(StartLoc, Clauses); 1994 } 1995 case OMPD_assumes: 1996 case OMPD_begin_assumes: 1997 ParseOpenMPAssumesDirective(DKind, ConsumeToken()); 1998 break; 1999 case OMPD_end_assumes: 2000 ParseOpenMPEndAssumesDirective(ConsumeToken()); 2001 break; 2002 case OMPD_declare_reduction: 2003 ConsumeToken(); 2004 if (DeclGroupPtrTy Res = ParseOpenMPDeclareReductionDirective(AS)) { 2005 skipUntilPragmaOpenMPEnd(OMPD_declare_reduction); 2006 // Skip the last annot_pragma_openmp_end. 2007 ConsumeAnnotationToken(); 2008 return Res; 2009 } 2010 break; 2011 case OMPD_declare_mapper: { 2012 ConsumeToken(); 2013 if (DeclGroupPtrTy Res = ParseOpenMPDeclareMapperDirective(AS)) { 2014 // Skip the last annot_pragma_openmp_end. 2015 ConsumeAnnotationToken(); 2016 return Res; 2017 } 2018 break; 2019 } 2020 case OMPD_begin_declare_variant: { 2021 // The syntax is: 2022 // { #pragma omp begin declare variant clause } 2023 // <function-declaration-or-definition-sequence> 2024 // { #pragma omp end declare variant } 2025 // 2026 ConsumeToken(); 2027 OMPTraitInfo *ParentTI = Actions.getOMPTraitInfoForSurroundingScope(); 2028 ASTContext &ASTCtx = Actions.getASTContext(); 2029 OMPTraitInfo &TI = ASTCtx.getNewOMPTraitInfo(); 2030 if (parseOMPDeclareVariantMatchClause(Loc, TI, ParentTI)) 2031 break; 2032 2033 // Skip last tokens. 2034 skipUntilPragmaOpenMPEnd(OMPD_begin_declare_variant); 2035 2036 ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false); 2037 2038 VariantMatchInfo VMI; 2039 TI.getAsVariantMatchInfo(ASTCtx, VMI); 2040 2041 std::function<void(StringRef)> DiagUnknownTrait = [this, Loc]( 2042 StringRef ISATrait) { 2043 // TODO Track the selector locations in a way that is accessible here to 2044 // improve the diagnostic location. 2045 Diag(Loc, diag::warn_unknown_begin_declare_variant_isa_trait) << ISATrait; 2046 }; 2047 TargetOMPContext OMPCtx(ASTCtx, std::move(DiagUnknownTrait), 2048 /* CurrentFunctionDecl */ nullptr); 2049 2050 if (isVariantApplicableInContext(VMI, OMPCtx, /* DeviceSetOnly */ true)) { 2051 Actions.ActOnOpenMPBeginDeclareVariant(Loc, TI); 2052 break; 2053 } 2054 2055 // Elide all the code till the matching end declare variant was found. 2056 unsigned Nesting = 1; 2057 SourceLocation DKLoc; 2058 OpenMPDirectiveKind DK = OMPD_unknown; 2059 do { 2060 DKLoc = Tok.getLocation(); 2061 DK = parseOpenMPDirectiveKind(*this); 2062 if (DK == OMPD_end_declare_variant) 2063 --Nesting; 2064 else if (DK == OMPD_begin_declare_variant) 2065 ++Nesting; 2066 if (!Nesting || isEofOrEom()) 2067 break; 2068 ConsumeAnyToken(); 2069 } while (true); 2070 2071 parseOMPEndDirective(OMPD_begin_declare_variant, OMPD_end_declare_variant, 2072 DK, Loc, DKLoc, /* SkipUntilOpenMPEnd */ true); 2073 if (isEofOrEom()) 2074 return nullptr; 2075 break; 2076 } 2077 case OMPD_end_declare_variant: { 2078 if (Actions.isInOpenMPDeclareVariantScope()) 2079 Actions.ActOnOpenMPEndDeclareVariant(); 2080 else 2081 Diag(Loc, diag::err_expected_begin_declare_variant); 2082 ConsumeToken(); 2083 break; 2084 } 2085 case OMPD_declare_variant: 2086 case OMPD_declare_simd: { 2087 // The syntax is: 2088 // { #pragma omp declare {simd|variant} } 2089 // <function-declaration-or-definition> 2090 // 2091 CachedTokens Toks; 2092 Toks.push_back(Tok); 2093 ConsumeToken(); 2094 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 2095 Toks.push_back(Tok); 2096 ConsumeAnyToken(); 2097 } 2098 Toks.push_back(Tok); 2099 ConsumeAnyToken(); 2100 2101 DeclGroupPtrTy Ptr; 2102 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) { 2103 Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, Delayed, 2104 TagType, Tag); 2105 } else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 2106 // Here we expect to see some function declaration. 2107 if (AS == AS_none) { 2108 assert(TagType == DeclSpec::TST_unspecified); 2109 MaybeParseCXX11Attributes(Attrs); 2110 ParsingDeclSpec PDS(*this); 2111 Ptr = ParseExternalDeclaration(Attrs, &PDS); 2112 } else { 2113 Ptr = 2114 ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag); 2115 } 2116 } 2117 if (!Ptr) { 2118 Diag(Loc, diag::err_omp_decl_in_declare_simd_variant) 2119 << (DKind == OMPD_declare_simd ? 0 : 1); 2120 return DeclGroupPtrTy(); 2121 } 2122 if (DKind == OMPD_declare_simd) 2123 return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc); 2124 assert(DKind == OMPD_declare_variant && 2125 "Expected declare variant directive only"); 2126 ParseOMPDeclareVariantClauses(Ptr, Toks, Loc); 2127 return Ptr; 2128 } 2129 case OMPD_begin_declare_target: 2130 case OMPD_declare_target: { 2131 SourceLocation DTLoc = ConsumeAnyToken(); 2132 bool HasClauses = Tok.isNot(tok::annot_pragma_openmp_end); 2133 bool HasImplicitMappings = 2134 DKind == OMPD_begin_declare_target || !HasClauses; 2135 Sema::DeclareTargetContextInfo DTCI(DKind, DTLoc); 2136 if (HasClauses) 2137 ParseOMPDeclareTargetClauses(DTCI); 2138 2139 // Skip the last annot_pragma_openmp_end. 2140 ConsumeAnyToken(); 2141 2142 if (HasImplicitMappings) { 2143 Actions.ActOnStartOpenMPDeclareTargetContext(DTCI); 2144 return nullptr; 2145 } 2146 2147 Actions.ActOnFinishedOpenMPDeclareTargetContext(DTCI); 2148 llvm::SmallVector<Decl *, 4> Decls; 2149 for (auto &It : DTCI.ExplicitlyMapped) 2150 Decls.push_back(It.first); 2151 return Actions.BuildDeclaratorGroup(Decls); 2152 } 2153 case OMPD_end_declare_target: { 2154 if (!Actions.isInOpenMPDeclareTargetContext()) { 2155 Diag(Tok, diag::err_omp_unexpected_directive) 2156 << 1 << getOpenMPDirectiveName(DKind); 2157 break; 2158 } 2159 const Sema::DeclareTargetContextInfo &DTCI = 2160 Actions.ActOnOpenMPEndDeclareTargetDirective(); 2161 ParseOMPEndDeclareTargetDirective(DTCI.Kind, DKind, DTCI.Loc); 2162 return nullptr; 2163 } 2164 case OMPD_unknown: 2165 Diag(Tok, diag::err_omp_unknown_directive); 2166 break; 2167 case OMPD_parallel: 2168 case OMPD_simd: 2169 case OMPD_tile: 2170 case OMPD_unroll: 2171 case OMPD_task: 2172 case OMPD_taskyield: 2173 case OMPD_barrier: 2174 case OMPD_taskwait: 2175 case OMPD_taskgroup: 2176 case OMPD_flush: 2177 case OMPD_depobj: 2178 case OMPD_scan: 2179 case OMPD_for: 2180 case OMPD_for_simd: 2181 case OMPD_sections: 2182 case OMPD_section: 2183 case OMPD_single: 2184 case OMPD_master: 2185 case OMPD_ordered: 2186 case OMPD_critical: 2187 case OMPD_parallel_for: 2188 case OMPD_parallel_for_simd: 2189 case OMPD_parallel_sections: 2190 case OMPD_parallel_master: 2191 case OMPD_atomic: 2192 case OMPD_target: 2193 case OMPD_teams: 2194 case OMPD_cancellation_point: 2195 case OMPD_cancel: 2196 case OMPD_target_data: 2197 case OMPD_target_enter_data: 2198 case OMPD_target_exit_data: 2199 case OMPD_target_parallel: 2200 case OMPD_target_parallel_for: 2201 case OMPD_taskloop: 2202 case OMPD_taskloop_simd: 2203 case OMPD_master_taskloop: 2204 case OMPD_master_taskloop_simd: 2205 case OMPD_parallel_master_taskloop: 2206 case OMPD_parallel_master_taskloop_simd: 2207 case OMPD_distribute: 2208 case OMPD_target_update: 2209 case OMPD_distribute_parallel_for: 2210 case OMPD_distribute_parallel_for_simd: 2211 case OMPD_distribute_simd: 2212 case OMPD_target_parallel_for_simd: 2213 case OMPD_target_simd: 2214 case OMPD_teams_distribute: 2215 case OMPD_teams_distribute_simd: 2216 case OMPD_teams_distribute_parallel_for_simd: 2217 case OMPD_teams_distribute_parallel_for: 2218 case OMPD_target_teams: 2219 case OMPD_target_teams_distribute: 2220 case OMPD_target_teams_distribute_parallel_for: 2221 case OMPD_target_teams_distribute_parallel_for_simd: 2222 case OMPD_target_teams_distribute_simd: 2223 case OMPD_dispatch: 2224 case OMPD_masked: 2225 Diag(Tok, diag::err_omp_unexpected_directive) 2226 << 1 << getOpenMPDirectiveName(DKind); 2227 break; 2228 default: 2229 break; 2230 } 2231 while (Tok.isNot(tok::annot_pragma_openmp_end)) 2232 ConsumeAnyToken(); 2233 ConsumeAnyToken(); 2234 return nullptr; 2235 } 2236 2237 /// Parsing of declarative or executable OpenMP directives. 2238 /// 2239 /// threadprivate-directive: 2240 /// annot_pragma_openmp 'threadprivate' simple-variable-list 2241 /// annot_pragma_openmp_end 2242 /// 2243 /// allocate-directive: 2244 /// annot_pragma_openmp 'allocate' simple-variable-list 2245 /// annot_pragma_openmp_end 2246 /// 2247 /// declare-reduction-directive: 2248 /// annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':' 2249 /// <type> {',' <type>} ':' <expression> ')' ['initializer' '(' 2250 /// ('omp_priv' '=' <expression>|<function_call>) ')'] 2251 /// annot_pragma_openmp_end 2252 /// 2253 /// declare-mapper-directive: 2254 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':'] 2255 /// <type> <var> ')' [<clause>[[,] <clause>] ... ] 2256 /// annot_pragma_openmp_end 2257 /// 2258 /// executable-directive: 2259 /// annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' | 2260 /// 'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] | 2261 /// 'parallel for' | 'parallel sections' | 'parallel master' | 'task' | 2262 /// 'taskyield' | 'barrier' | 'taskwait' | 'flush' | 'ordered' | 2263 /// 'atomic' | 'for simd' | 'parallel for simd' | 'target' | 'target 2264 /// data' | 'taskgroup' | 'teams' | 'taskloop' | 'taskloop simd' | 2265 /// 'master taskloop' | 'master taskloop simd' | 'parallel master 2266 /// taskloop' | 'parallel master taskloop simd' | 'distribute' | 'target 2267 /// enter data' | 'target exit data' | 'target parallel' | 'target 2268 /// parallel for' | 'target update' | 'distribute parallel for' | 2269 /// 'distribute paralle for simd' | 'distribute simd' | 'target parallel 2270 /// for simd' | 'target simd' | 'teams distribute' | 'teams distribute 2271 /// simd' | 'teams distribute parallel for simd' | 'teams distribute 2272 /// parallel for' | 'target teams' | 'target teams distribute' | 'target 2273 /// teams distribute parallel for' | 'target teams distribute parallel 2274 /// for simd' | 'target teams distribute simd' | 'masked' {clause} 2275 /// annot_pragma_openmp_end 2276 /// 2277 StmtResult 2278 Parser::ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx) { 2279 assert(Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) && 2280 "Not an OpenMP directive!"); 2281 ParsingOpenMPDirectiveRAII DirScope(*this); 2282 ParenBraceBracketBalancer BalancerRAIIObj(*this); 2283 SmallVector<OMPClause *, 5> Clauses; 2284 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, 2285 llvm::omp::Clause_enumSize + 1> 2286 FirstClauses(llvm::omp::Clause_enumSize + 1); 2287 unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope | 2288 Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope; 2289 SourceLocation Loc = ConsumeAnnotationToken(), EndLoc; 2290 OpenMPDirectiveKind DKind = parseOpenMPDirectiveKind(*this); 2291 OpenMPDirectiveKind CancelRegion = OMPD_unknown; 2292 // Name of critical directive. 2293 DeclarationNameInfo DirName; 2294 StmtResult Directive = StmtError(); 2295 bool HasAssociatedStatement = true; 2296 2297 switch (DKind) { 2298 case OMPD_threadprivate: { 2299 // FIXME: Should this be permitted in C++? 2300 if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) == 2301 ParsedStmtContext()) { 2302 Diag(Tok, diag::err_omp_immediate_directive) 2303 << getOpenMPDirectiveName(DKind) << 0; 2304 } 2305 ConsumeToken(); 2306 DeclDirectiveListParserHelper Helper(this, DKind); 2307 if (!ParseOpenMPSimpleVarList(DKind, Helper, 2308 /*AllowScopeSpecifier=*/false)) { 2309 skipUntilPragmaOpenMPEnd(DKind); 2310 DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective( 2311 Loc, Helper.getIdentifiers()); 2312 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); 2313 } 2314 SkipUntil(tok::annot_pragma_openmp_end); 2315 break; 2316 } 2317 case OMPD_allocate: { 2318 // FIXME: Should this be permitted in C++? 2319 if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) == 2320 ParsedStmtContext()) { 2321 Diag(Tok, diag::err_omp_immediate_directive) 2322 << getOpenMPDirectiveName(DKind) << 0; 2323 } 2324 ConsumeToken(); 2325 DeclDirectiveListParserHelper Helper(this, DKind); 2326 if (!ParseOpenMPSimpleVarList(DKind, Helper, 2327 /*AllowScopeSpecifier=*/false)) { 2328 SmallVector<OMPClause *, 1> Clauses; 2329 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 2330 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, 2331 llvm::omp::Clause_enumSize + 1> 2332 FirstClauses(llvm::omp::Clause_enumSize + 1); 2333 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 2334 OpenMPClauseKind CKind = 2335 Tok.isAnnotation() ? OMPC_unknown 2336 : getOpenMPClauseKind(PP.getSpelling(Tok)); 2337 Actions.StartOpenMPClause(CKind); 2338 OMPClause *Clause = ParseOpenMPClause( 2339 OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt()); 2340 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end, 2341 StopBeforeMatch); 2342 FirstClauses[unsigned(CKind)].setInt(true); 2343 if (Clause != nullptr) 2344 Clauses.push_back(Clause); 2345 if (Tok.is(tok::annot_pragma_openmp_end)) { 2346 Actions.EndOpenMPClause(); 2347 break; 2348 } 2349 // Skip ',' if any. 2350 if (Tok.is(tok::comma)) 2351 ConsumeToken(); 2352 Actions.EndOpenMPClause(); 2353 } 2354 skipUntilPragmaOpenMPEnd(DKind); 2355 } 2356 DeclGroupPtrTy Res = Actions.ActOnOpenMPAllocateDirective( 2357 Loc, Helper.getIdentifiers(), Clauses); 2358 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); 2359 } 2360 SkipUntil(tok::annot_pragma_openmp_end); 2361 break; 2362 } 2363 case OMPD_declare_reduction: 2364 ConsumeToken(); 2365 if (DeclGroupPtrTy Res = 2366 ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) { 2367 skipUntilPragmaOpenMPEnd(OMPD_declare_reduction); 2368 ConsumeAnyToken(); 2369 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); 2370 } else { 2371 SkipUntil(tok::annot_pragma_openmp_end); 2372 } 2373 break; 2374 case OMPD_declare_mapper: { 2375 ConsumeToken(); 2376 if (DeclGroupPtrTy Res = 2377 ParseOpenMPDeclareMapperDirective(/*AS=*/AS_none)) { 2378 // Skip the last annot_pragma_openmp_end. 2379 ConsumeAnnotationToken(); 2380 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); 2381 } else { 2382 SkipUntil(tok::annot_pragma_openmp_end); 2383 } 2384 break; 2385 } 2386 case OMPD_flush: 2387 case OMPD_depobj: 2388 case OMPD_scan: 2389 case OMPD_taskyield: 2390 case OMPD_barrier: 2391 case OMPD_taskwait: 2392 case OMPD_cancellation_point: 2393 case OMPD_cancel: 2394 case OMPD_target_enter_data: 2395 case OMPD_target_exit_data: 2396 case OMPD_target_update: 2397 case OMPD_interop: 2398 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) == 2399 ParsedStmtContext()) { 2400 Diag(Tok, diag::err_omp_immediate_directive) 2401 << getOpenMPDirectiveName(DKind) << 0; 2402 } 2403 HasAssociatedStatement = false; 2404 // Fall through for further analysis. 2405 LLVM_FALLTHROUGH; 2406 case OMPD_parallel: 2407 case OMPD_simd: 2408 case OMPD_tile: 2409 case OMPD_unroll: 2410 case OMPD_for: 2411 case OMPD_for_simd: 2412 case OMPD_sections: 2413 case OMPD_single: 2414 case OMPD_section: 2415 case OMPD_master: 2416 case OMPD_critical: 2417 case OMPD_parallel_for: 2418 case OMPD_parallel_for_simd: 2419 case OMPD_parallel_sections: 2420 case OMPD_parallel_master: 2421 case OMPD_task: 2422 case OMPD_ordered: 2423 case OMPD_atomic: 2424 case OMPD_target: 2425 case OMPD_teams: 2426 case OMPD_taskgroup: 2427 case OMPD_target_data: 2428 case OMPD_target_parallel: 2429 case OMPD_target_parallel_for: 2430 case OMPD_taskloop: 2431 case OMPD_taskloop_simd: 2432 case OMPD_master_taskloop: 2433 case OMPD_master_taskloop_simd: 2434 case OMPD_parallel_master_taskloop: 2435 case OMPD_parallel_master_taskloop_simd: 2436 case OMPD_distribute: 2437 case OMPD_distribute_parallel_for: 2438 case OMPD_distribute_parallel_for_simd: 2439 case OMPD_distribute_simd: 2440 case OMPD_target_parallel_for_simd: 2441 case OMPD_target_simd: 2442 case OMPD_teams_distribute: 2443 case OMPD_teams_distribute_simd: 2444 case OMPD_teams_distribute_parallel_for_simd: 2445 case OMPD_teams_distribute_parallel_for: 2446 case OMPD_target_teams: 2447 case OMPD_target_teams_distribute: 2448 case OMPD_target_teams_distribute_parallel_for: 2449 case OMPD_target_teams_distribute_parallel_for_simd: 2450 case OMPD_target_teams_distribute_simd: 2451 case OMPD_dispatch: 2452 case OMPD_masked: { 2453 // Special processing for flush and depobj clauses. 2454 Token ImplicitTok; 2455 bool ImplicitClauseAllowed = false; 2456 if (DKind == OMPD_flush || DKind == OMPD_depobj) { 2457 ImplicitTok = Tok; 2458 ImplicitClauseAllowed = true; 2459 } 2460 ConsumeToken(); 2461 // Parse directive name of the 'critical' directive if any. 2462 if (DKind == OMPD_critical) { 2463 BalancedDelimiterTracker T(*this, tok::l_paren, 2464 tok::annot_pragma_openmp_end); 2465 if (!T.consumeOpen()) { 2466 if (Tok.isAnyIdentifier()) { 2467 DirName = 2468 DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation()); 2469 ConsumeAnyToken(); 2470 } else { 2471 Diag(Tok, diag::err_omp_expected_identifier_for_critical); 2472 } 2473 T.consumeClose(); 2474 } 2475 } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) { 2476 CancelRegion = parseOpenMPDirectiveKind(*this); 2477 if (Tok.isNot(tok::annot_pragma_openmp_end)) 2478 ConsumeToken(); 2479 } 2480 2481 if (isOpenMPLoopDirective(DKind)) 2482 ScopeFlags |= Scope::OpenMPLoopDirectiveScope; 2483 if (isOpenMPSimdDirective(DKind)) 2484 ScopeFlags |= Scope::OpenMPSimdDirectiveScope; 2485 ParseScope OMPDirectiveScope(this, ScopeFlags); 2486 Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc); 2487 2488 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 2489 bool HasImplicitClause = false; 2490 if (ImplicitClauseAllowed && Tok.is(tok::l_paren)) { 2491 HasImplicitClause = true; 2492 // Push copy of the current token back to stream to properly parse 2493 // pseudo-clause OMPFlushClause or OMPDepobjClause. 2494 PP.EnterToken(Tok, /*IsReinject*/ true); 2495 PP.EnterToken(ImplicitTok, /*IsReinject*/ true); 2496 ConsumeAnyToken(); 2497 } 2498 OpenMPClauseKind CKind = Tok.isAnnotation() 2499 ? OMPC_unknown 2500 : getOpenMPClauseKind(PP.getSpelling(Tok)); 2501 if (HasImplicitClause) { 2502 assert(CKind == OMPC_unknown && "Must be unknown implicit clause."); 2503 if (DKind == OMPD_flush) { 2504 CKind = OMPC_flush; 2505 } else { 2506 assert(DKind == OMPD_depobj && 2507 "Expected flush or depobj directives."); 2508 CKind = OMPC_depobj; 2509 } 2510 } 2511 // No more implicit clauses allowed. 2512 ImplicitClauseAllowed = false; 2513 Actions.StartOpenMPClause(CKind); 2514 HasImplicitClause = false; 2515 OMPClause *Clause = ParseOpenMPClause( 2516 DKind, CKind, !FirstClauses[unsigned(CKind)].getInt()); 2517 FirstClauses[unsigned(CKind)].setInt(true); 2518 if (Clause) { 2519 FirstClauses[unsigned(CKind)].setPointer(Clause); 2520 Clauses.push_back(Clause); 2521 } 2522 2523 // Skip ',' if any. 2524 if (Tok.is(tok::comma)) 2525 ConsumeToken(); 2526 Actions.EndOpenMPClause(); 2527 } 2528 // End location of the directive. 2529 EndLoc = Tok.getLocation(); 2530 // Consume final annot_pragma_openmp_end. 2531 ConsumeAnnotationToken(); 2532 2533 // OpenMP [2.13.8, ordered Construct, Syntax] 2534 // If the depend clause is specified, the ordered construct is a stand-alone 2535 // directive. 2536 if (DKind == OMPD_ordered && FirstClauses[unsigned(OMPC_depend)].getInt()) { 2537 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) == 2538 ParsedStmtContext()) { 2539 Diag(Loc, diag::err_omp_immediate_directive) 2540 << getOpenMPDirectiveName(DKind) << 1 2541 << getOpenMPClauseName(OMPC_depend); 2542 } 2543 HasAssociatedStatement = false; 2544 } 2545 2546 if (DKind == OMPD_tile && !FirstClauses[unsigned(OMPC_sizes)].getInt()) { 2547 Diag(Loc, diag::err_omp_required_clause) 2548 << getOpenMPDirectiveName(OMPD_tile) << "sizes"; 2549 } 2550 2551 StmtResult AssociatedStmt; 2552 if (HasAssociatedStatement) { 2553 // The body is a block scope like in Lambdas and Blocks. 2554 Actions.ActOnOpenMPRegionStart(DKind, getCurScope()); 2555 // FIXME: We create a bogus CompoundStmt scope to hold the contents of 2556 // the captured region. Code elsewhere assumes that any FunctionScopeInfo 2557 // should have at least one compound statement scope within it. 2558 ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false); 2559 { 2560 Sema::CompoundScopeRAII Scope(Actions); 2561 AssociatedStmt = ParseStatement(); 2562 2563 if (AssociatedStmt.isUsable() && isOpenMPLoopDirective(DKind) && 2564 getLangOpts().OpenMPIRBuilder) 2565 AssociatedStmt = Actions.ActOnOpenMPLoopnest(AssociatedStmt.get()); 2566 } 2567 AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses); 2568 } else if (DKind == OMPD_target_update || DKind == OMPD_target_enter_data || 2569 DKind == OMPD_target_exit_data) { 2570 Actions.ActOnOpenMPRegionStart(DKind, getCurScope()); 2571 AssociatedStmt = (Sema::CompoundScopeRAII(Actions), 2572 Actions.ActOnCompoundStmt(Loc, Loc, llvm::None, 2573 /*isStmtExpr=*/false)); 2574 AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses); 2575 } 2576 Directive = Actions.ActOnOpenMPExecutableDirective( 2577 DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc, 2578 EndLoc); 2579 2580 // Exit scope. 2581 Actions.EndOpenMPDSABlock(Directive.get()); 2582 OMPDirectiveScope.Exit(); 2583 break; 2584 } 2585 case OMPD_declare_simd: 2586 case OMPD_declare_target: 2587 case OMPD_begin_declare_target: 2588 case OMPD_end_declare_target: 2589 case OMPD_requires: 2590 case OMPD_begin_declare_variant: 2591 case OMPD_end_declare_variant: 2592 case OMPD_declare_variant: 2593 Diag(Tok, diag::err_omp_unexpected_directive) 2594 << 1 << getOpenMPDirectiveName(DKind); 2595 SkipUntil(tok::annot_pragma_openmp_end); 2596 break; 2597 case OMPD_unknown: 2598 default: 2599 Diag(Tok, diag::err_omp_unknown_directive); 2600 SkipUntil(tok::annot_pragma_openmp_end); 2601 break; 2602 } 2603 return Directive; 2604 } 2605 2606 // Parses simple list: 2607 // simple-variable-list: 2608 // '(' id-expression {, id-expression} ')' 2609 // 2610 bool Parser::ParseOpenMPSimpleVarList( 2611 OpenMPDirectiveKind Kind, 2612 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> 2613 &Callback, 2614 bool AllowScopeSpecifier) { 2615 // Parse '('. 2616 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 2617 if (T.expectAndConsume(diag::err_expected_lparen_after, 2618 getOpenMPDirectiveName(Kind).data())) 2619 return true; 2620 bool IsCorrect = true; 2621 bool NoIdentIsFound = true; 2622 2623 // Read tokens while ')' or annot_pragma_openmp_end is not found. 2624 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) { 2625 CXXScopeSpec SS; 2626 UnqualifiedId Name; 2627 // Read var name. 2628 Token PrevTok = Tok; 2629 NoIdentIsFound = false; 2630 2631 if (AllowScopeSpecifier && getLangOpts().CPlusPlus && 2632 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 2633 /*ObjectHadErrors=*/false, false)) { 2634 IsCorrect = false; 2635 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 2636 StopBeforeMatch); 2637 } else if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr, 2638 /*ObjectHadErrors=*/false, false, false, 2639 false, false, nullptr, Name)) { 2640 IsCorrect = false; 2641 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 2642 StopBeforeMatch); 2643 } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) && 2644 Tok.isNot(tok::annot_pragma_openmp_end)) { 2645 IsCorrect = false; 2646 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 2647 StopBeforeMatch); 2648 Diag(PrevTok.getLocation(), diag::err_expected) 2649 << tok::identifier 2650 << SourceRange(PrevTok.getLocation(), PrevTokLocation); 2651 } else { 2652 Callback(SS, Actions.GetNameFromUnqualifiedId(Name)); 2653 } 2654 // Consume ','. 2655 if (Tok.is(tok::comma)) { 2656 ConsumeToken(); 2657 } 2658 } 2659 2660 if (NoIdentIsFound) { 2661 Diag(Tok, diag::err_expected) << tok::identifier; 2662 IsCorrect = false; 2663 } 2664 2665 // Parse ')'. 2666 IsCorrect = !T.consumeClose() && IsCorrect; 2667 2668 return !IsCorrect; 2669 } 2670 2671 OMPClause *Parser::ParseOpenMPSizesClause() { 2672 SourceLocation ClauseNameLoc = ConsumeToken(); 2673 SmallVector<Expr *, 4> ValExprs; 2674 2675 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 2676 if (T.consumeOpen()) { 2677 Diag(Tok, diag::err_expected) << tok::l_paren; 2678 return nullptr; 2679 } 2680 2681 while (true) { 2682 ExprResult Val = ParseConstantExpression(); 2683 if (!Val.isUsable()) { 2684 T.skipToEnd(); 2685 return nullptr; 2686 } 2687 2688 ValExprs.push_back(Val.get()); 2689 2690 if (Tok.is(tok::r_paren) || Tok.is(tok::annot_pragma_openmp_end)) 2691 break; 2692 2693 ExpectAndConsume(tok::comma); 2694 } 2695 2696 T.consumeClose(); 2697 2698 return Actions.ActOnOpenMPSizesClause( 2699 ValExprs, ClauseNameLoc, T.getOpenLocation(), T.getCloseLocation()); 2700 } 2701 2702 OMPClause *Parser::ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind) { 2703 SourceLocation Loc = Tok.getLocation(); 2704 ConsumeAnyToken(); 2705 2706 // Parse '('. 2707 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 2708 if (T.expectAndConsume(diag::err_expected_lparen_after, "uses_allocator")) 2709 return nullptr; 2710 SmallVector<Sema::UsesAllocatorsData, 4> Data; 2711 do { 2712 ExprResult Allocator = 2713 getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression(); 2714 if (Allocator.isInvalid()) { 2715 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 2716 StopBeforeMatch); 2717 break; 2718 } 2719 Sema::UsesAllocatorsData &D = Data.emplace_back(); 2720 D.Allocator = Allocator.get(); 2721 if (Tok.is(tok::l_paren)) { 2722 BalancedDelimiterTracker T(*this, tok::l_paren, 2723 tok::annot_pragma_openmp_end); 2724 T.consumeOpen(); 2725 ExprResult AllocatorTraits = 2726 getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression(); 2727 T.consumeClose(); 2728 if (AllocatorTraits.isInvalid()) { 2729 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 2730 StopBeforeMatch); 2731 break; 2732 } 2733 D.AllocatorTraits = AllocatorTraits.get(); 2734 D.LParenLoc = T.getOpenLocation(); 2735 D.RParenLoc = T.getCloseLocation(); 2736 } 2737 if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren)) 2738 Diag(Tok, diag::err_omp_expected_punc) << "uses_allocators" << 0; 2739 // Parse ',' 2740 if (Tok.is(tok::comma)) 2741 ConsumeAnyToken(); 2742 } while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)); 2743 T.consumeClose(); 2744 return Actions.ActOnOpenMPUsesAllocatorClause(Loc, T.getOpenLocation(), 2745 T.getCloseLocation(), Data); 2746 } 2747 2748 /// Parsing of OpenMP clauses. 2749 /// 2750 /// clause: 2751 /// if-clause | final-clause | num_threads-clause | safelen-clause | 2752 /// default-clause | private-clause | firstprivate-clause | shared-clause 2753 /// | linear-clause | aligned-clause | collapse-clause | 2754 /// lastprivate-clause | reduction-clause | proc_bind-clause | 2755 /// schedule-clause | copyin-clause | copyprivate-clause | untied-clause | 2756 /// mergeable-clause | flush-clause | read-clause | write-clause | 2757 /// update-clause | capture-clause | seq_cst-clause | device-clause | 2758 /// simdlen-clause | threads-clause | simd-clause | num_teams-clause | 2759 /// thread_limit-clause | priority-clause | grainsize-clause | 2760 /// nogroup-clause | num_tasks-clause | hint-clause | to-clause | 2761 /// from-clause | is_device_ptr-clause | task_reduction-clause | 2762 /// in_reduction-clause | allocator-clause | allocate-clause | 2763 /// acq_rel-clause | acquire-clause | release-clause | relaxed-clause | 2764 /// depobj-clause | destroy-clause | detach-clause | inclusive-clause | 2765 /// exclusive-clause | uses_allocators-clause | use_device_addr-clause 2766 /// 2767 OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind, 2768 OpenMPClauseKind CKind, bool FirstClause) { 2769 OMPClauseKind = CKind; 2770 OMPClause *Clause = nullptr; 2771 bool ErrorFound = false; 2772 bool WrongDirective = false; 2773 // Check if clause is allowed for the given directive. 2774 if (CKind != OMPC_unknown && 2775 !isAllowedClauseForDirective(DKind, CKind, getLangOpts().OpenMP)) { 2776 Diag(Tok, diag::err_omp_unexpected_clause) 2777 << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind); 2778 ErrorFound = true; 2779 WrongDirective = true; 2780 } 2781 2782 switch (CKind) { 2783 case OMPC_final: 2784 case OMPC_num_threads: 2785 case OMPC_safelen: 2786 case OMPC_simdlen: 2787 case OMPC_collapse: 2788 case OMPC_ordered: 2789 case OMPC_num_teams: 2790 case OMPC_thread_limit: 2791 case OMPC_priority: 2792 case OMPC_grainsize: 2793 case OMPC_num_tasks: 2794 case OMPC_hint: 2795 case OMPC_allocator: 2796 case OMPC_depobj: 2797 case OMPC_detach: 2798 case OMPC_novariants: 2799 case OMPC_nocontext: 2800 case OMPC_filter: 2801 case OMPC_partial: 2802 // OpenMP [2.5, Restrictions] 2803 // At most one num_threads clause can appear on the directive. 2804 // OpenMP [2.8.1, simd construct, Restrictions] 2805 // Only one safelen clause can appear on a simd directive. 2806 // Only one simdlen clause can appear on a simd directive. 2807 // Only one collapse clause can appear on a simd directive. 2808 // OpenMP [2.11.1, task Construct, Restrictions] 2809 // At most one if clause can appear on the directive. 2810 // At most one final clause can appear on the directive. 2811 // OpenMP [teams Construct, Restrictions] 2812 // At most one num_teams clause can appear on the directive. 2813 // At most one thread_limit clause can appear on the directive. 2814 // OpenMP [2.9.1, task Construct, Restrictions] 2815 // At most one priority clause can appear on the directive. 2816 // OpenMP [2.9.2, taskloop Construct, Restrictions] 2817 // At most one grainsize clause can appear on the directive. 2818 // OpenMP [2.9.2, taskloop Construct, Restrictions] 2819 // At most one num_tasks clause can appear on the directive. 2820 // OpenMP [2.11.3, allocate Directive, Restrictions] 2821 // At most one allocator clause can appear on the directive. 2822 // OpenMP 5.0, 2.10.1 task Construct, Restrictions. 2823 // At most one detach clause can appear on the directive. 2824 // OpenMP 5.1, 2.3.6 dispatch Construct, Restrictions. 2825 // At most one novariants clause can appear on a dispatch directive. 2826 // At most one nocontext clause can appear on a dispatch directive. 2827 if (!FirstClause) { 2828 Diag(Tok, diag::err_omp_more_one_clause) 2829 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 2830 ErrorFound = true; 2831 } 2832 2833 if ((CKind == OMPC_ordered || CKind == OMPC_partial) && 2834 PP.LookAhead(/*N=*/0).isNot(tok::l_paren)) 2835 Clause = ParseOpenMPClause(CKind, WrongDirective); 2836 else 2837 Clause = ParseOpenMPSingleExprClause(CKind, WrongDirective); 2838 break; 2839 case OMPC_default: 2840 case OMPC_proc_bind: 2841 case OMPC_atomic_default_mem_order: 2842 case OMPC_order: 2843 // OpenMP [2.14.3.1, Restrictions] 2844 // Only a single default clause may be specified on a parallel, task or 2845 // teams directive. 2846 // OpenMP [2.5, parallel Construct, Restrictions] 2847 // At most one proc_bind clause can appear on the directive. 2848 // OpenMP [5.0, Requires directive, Restrictions] 2849 // At most one atomic_default_mem_order clause can appear 2850 // on the directive 2851 if (!FirstClause && CKind != OMPC_order) { 2852 Diag(Tok, diag::err_omp_more_one_clause) 2853 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 2854 ErrorFound = true; 2855 } 2856 2857 Clause = ParseOpenMPSimpleClause(CKind, WrongDirective); 2858 break; 2859 case OMPC_device: 2860 case OMPC_schedule: 2861 case OMPC_dist_schedule: 2862 case OMPC_defaultmap: 2863 // OpenMP [2.7.1, Restrictions, p. 3] 2864 // Only one schedule clause can appear on a loop directive. 2865 // OpenMP 4.5 [2.10.4, Restrictions, p. 106] 2866 // At most one defaultmap clause can appear on the directive. 2867 // OpenMP 5.0 [2.12.5, target construct, Restrictions] 2868 // At most one device clause can appear on the directive. 2869 if ((getLangOpts().OpenMP < 50 || CKind != OMPC_defaultmap) && 2870 !FirstClause) { 2871 Diag(Tok, diag::err_omp_more_one_clause) 2872 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 2873 ErrorFound = true; 2874 } 2875 LLVM_FALLTHROUGH; 2876 case OMPC_if: 2877 Clause = ParseOpenMPSingleExprWithArgClause(DKind, CKind, WrongDirective); 2878 break; 2879 case OMPC_nowait: 2880 case OMPC_untied: 2881 case OMPC_mergeable: 2882 case OMPC_read: 2883 case OMPC_write: 2884 case OMPC_capture: 2885 case OMPC_seq_cst: 2886 case OMPC_acq_rel: 2887 case OMPC_acquire: 2888 case OMPC_release: 2889 case OMPC_relaxed: 2890 case OMPC_threads: 2891 case OMPC_simd: 2892 case OMPC_nogroup: 2893 case OMPC_unified_address: 2894 case OMPC_unified_shared_memory: 2895 case OMPC_reverse_offload: 2896 case OMPC_dynamic_allocators: 2897 case OMPC_full: 2898 // OpenMP [2.7.1, Restrictions, p. 9] 2899 // Only one ordered clause can appear on a loop directive. 2900 // OpenMP [2.7.1, Restrictions, C/C++, p. 4] 2901 // Only one nowait clause can appear on a for directive. 2902 // OpenMP [5.0, Requires directive, Restrictions] 2903 // Each of the requires clauses can appear at most once on the directive. 2904 if (!FirstClause) { 2905 Diag(Tok, diag::err_omp_more_one_clause) 2906 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 2907 ErrorFound = true; 2908 } 2909 2910 Clause = ParseOpenMPClause(CKind, WrongDirective); 2911 break; 2912 case OMPC_update: 2913 if (!FirstClause) { 2914 Diag(Tok, diag::err_omp_more_one_clause) 2915 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 2916 ErrorFound = true; 2917 } 2918 2919 Clause = (DKind == OMPD_depobj) 2920 ? ParseOpenMPSimpleClause(CKind, WrongDirective) 2921 : ParseOpenMPClause(CKind, WrongDirective); 2922 break; 2923 case OMPC_private: 2924 case OMPC_firstprivate: 2925 case OMPC_lastprivate: 2926 case OMPC_shared: 2927 case OMPC_reduction: 2928 case OMPC_task_reduction: 2929 case OMPC_in_reduction: 2930 case OMPC_linear: 2931 case OMPC_aligned: 2932 case OMPC_copyin: 2933 case OMPC_copyprivate: 2934 case OMPC_flush: 2935 case OMPC_depend: 2936 case OMPC_map: 2937 case OMPC_to: 2938 case OMPC_from: 2939 case OMPC_use_device_ptr: 2940 case OMPC_use_device_addr: 2941 case OMPC_is_device_ptr: 2942 case OMPC_allocate: 2943 case OMPC_nontemporal: 2944 case OMPC_inclusive: 2945 case OMPC_exclusive: 2946 case OMPC_affinity: 2947 Clause = ParseOpenMPVarListClause(DKind, CKind, WrongDirective); 2948 break; 2949 case OMPC_sizes: 2950 if (!FirstClause) { 2951 Diag(Tok, diag::err_omp_more_one_clause) 2952 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 2953 ErrorFound = true; 2954 } 2955 2956 Clause = ParseOpenMPSizesClause(); 2957 break; 2958 case OMPC_uses_allocators: 2959 Clause = ParseOpenMPUsesAllocatorClause(DKind); 2960 break; 2961 case OMPC_destroy: 2962 if (DKind != OMPD_interop) { 2963 if (!FirstClause) { 2964 Diag(Tok, diag::err_omp_more_one_clause) 2965 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 2966 ErrorFound = true; 2967 } 2968 Clause = ParseOpenMPClause(CKind, WrongDirective); 2969 break; 2970 } 2971 LLVM_FALLTHROUGH; 2972 case OMPC_init: 2973 case OMPC_use: 2974 Clause = ParseOpenMPInteropClause(CKind, WrongDirective); 2975 break; 2976 case OMPC_device_type: 2977 case OMPC_unknown: 2978 skipUntilPragmaOpenMPEnd(DKind); 2979 break; 2980 case OMPC_threadprivate: 2981 case OMPC_uniform: 2982 case OMPC_match: 2983 if (!WrongDirective) 2984 Diag(Tok, diag::err_omp_unexpected_clause) 2985 << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind); 2986 SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch); 2987 break; 2988 default: 2989 break; 2990 } 2991 return ErrorFound ? nullptr : Clause; 2992 } 2993 2994 /// Parses simple expression in parens for single-expression clauses of OpenMP 2995 /// constructs. 2996 /// \param RLoc Returned location of right paren. 2997 ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName, 2998 SourceLocation &RLoc, 2999 bool IsAddressOfOperand) { 3000 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 3001 if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data())) 3002 return ExprError(); 3003 3004 SourceLocation ELoc = Tok.getLocation(); 3005 ExprResult LHS( 3006 ParseCastExpression(AnyCastExpr, IsAddressOfOperand, NotTypeCast)); 3007 ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 3008 Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false); 3009 3010 // Parse ')'. 3011 RLoc = Tok.getLocation(); 3012 if (!T.consumeClose()) 3013 RLoc = T.getCloseLocation(); 3014 3015 return Val; 3016 } 3017 3018 /// Parsing of OpenMP clauses with single expressions like 'final', 3019 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams', 3020 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks', 'hint' or 3021 /// 'detach'. 3022 /// 3023 /// final-clause: 3024 /// 'final' '(' expression ')' 3025 /// 3026 /// num_threads-clause: 3027 /// 'num_threads' '(' expression ')' 3028 /// 3029 /// safelen-clause: 3030 /// 'safelen' '(' expression ')' 3031 /// 3032 /// simdlen-clause: 3033 /// 'simdlen' '(' expression ')' 3034 /// 3035 /// collapse-clause: 3036 /// 'collapse' '(' expression ')' 3037 /// 3038 /// priority-clause: 3039 /// 'priority' '(' expression ')' 3040 /// 3041 /// grainsize-clause: 3042 /// 'grainsize' '(' expression ')' 3043 /// 3044 /// num_tasks-clause: 3045 /// 'num_tasks' '(' expression ')' 3046 /// 3047 /// hint-clause: 3048 /// 'hint' '(' expression ')' 3049 /// 3050 /// allocator-clause: 3051 /// 'allocator' '(' expression ')' 3052 /// 3053 /// detach-clause: 3054 /// 'detach' '(' event-handler-expression ')' 3055 /// 3056 OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, 3057 bool ParseOnly) { 3058 SourceLocation Loc = ConsumeToken(); 3059 SourceLocation LLoc = Tok.getLocation(); 3060 SourceLocation RLoc; 3061 3062 ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc); 3063 3064 if (Val.isInvalid()) 3065 return nullptr; 3066 3067 if (ParseOnly) 3068 return nullptr; 3069 return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc); 3070 } 3071 3072 /// Parsing of OpenMP clauses that use an interop-var. 3073 /// 3074 /// init-clause: 3075 /// init([interop-modifier, ]interop-type[[, interop-type] ... ]:interop-var) 3076 /// 3077 /// destroy-clause: 3078 /// destroy(interop-var) 3079 /// 3080 /// use-clause: 3081 /// use(interop-var) 3082 /// 3083 /// interop-modifier: 3084 /// prefer_type(preference-list) 3085 /// 3086 /// preference-list: 3087 /// foreign-runtime-id [, foreign-runtime-id]... 3088 /// 3089 /// foreign-runtime-id: 3090 /// <string-literal> | <constant-integral-expression> 3091 /// 3092 /// interop-type: 3093 /// target | targetsync 3094 /// 3095 OMPClause *Parser::ParseOpenMPInteropClause(OpenMPClauseKind Kind, 3096 bool ParseOnly) { 3097 SourceLocation Loc = ConsumeToken(); 3098 // Parse '('. 3099 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 3100 if (T.expectAndConsume(diag::err_expected_lparen_after, 3101 getOpenMPClauseName(Kind).data())) 3102 return nullptr; 3103 3104 bool IsTarget = false; 3105 bool IsTargetSync = false; 3106 SmallVector<Expr *, 4> Prefs; 3107 3108 if (Kind == OMPC_init) { 3109 3110 // Parse optional interop-modifier. 3111 if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "prefer_type") { 3112 ConsumeToken(); 3113 BalancedDelimiterTracker PT(*this, tok::l_paren, 3114 tok::annot_pragma_openmp_end); 3115 if (PT.expectAndConsume(diag::err_expected_lparen_after, "prefer_type")) 3116 return nullptr; 3117 3118 while (Tok.isNot(tok::r_paren)) { 3119 SourceLocation Loc = Tok.getLocation(); 3120 ExprResult LHS = ParseCastExpression(AnyCastExpr); 3121 ExprResult PTExpr = Actions.CorrectDelayedTyposInExpr( 3122 ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 3123 PTExpr = Actions.ActOnFinishFullExpr(PTExpr.get(), Loc, 3124 /*DiscardedValue=*/false); 3125 if (PTExpr.isUsable()) 3126 Prefs.push_back(PTExpr.get()); 3127 else 3128 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 3129 StopBeforeMatch); 3130 3131 if (Tok.is(tok::comma)) 3132 ConsumeToken(); 3133 } 3134 PT.consumeClose(); 3135 } 3136 3137 if (!Prefs.empty()) { 3138 if (Tok.is(tok::comma)) 3139 ConsumeToken(); 3140 else 3141 Diag(Tok, diag::err_omp_expected_punc_after_interop_mod); 3142 } 3143 3144 // Parse the interop-types. 3145 bool HasError = false; 3146 while (Tok.is(tok::identifier)) { 3147 if (PP.getSpelling(Tok) == "target") { 3148 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 3149 // Each interop-type may be specified on an action-clause at most 3150 // once. 3151 if (IsTarget) 3152 Diag(Tok, diag::warn_omp_more_one_interop_type) << "target"; 3153 IsTarget = true; 3154 } else if (PP.getSpelling(Tok) == "targetsync") { 3155 if (IsTargetSync) 3156 Diag(Tok, diag::warn_omp_more_one_interop_type) << "targetsync"; 3157 IsTargetSync = true; 3158 } else { 3159 HasError = true; 3160 Diag(Tok, diag::err_omp_expected_interop_type); 3161 } 3162 ConsumeToken(); 3163 3164 if (!Tok.is(tok::comma)) 3165 break; 3166 ConsumeToken(); 3167 } 3168 if (!HasError && !IsTarget && !IsTargetSync) 3169 Diag(Tok, diag::err_omp_expected_interop_type); 3170 3171 if (Tok.is(tok::colon)) 3172 ConsumeToken(); 3173 else if (IsTarget || IsTargetSync) 3174 Diag(Tok, diag::warn_pragma_expected_colon) << "interop types"; 3175 } 3176 3177 // Parse the variable. 3178 SourceLocation VarLoc = Tok.getLocation(); 3179 ExprResult InteropVarExpr = 3180 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); 3181 if (!InteropVarExpr.isUsable()) { 3182 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 3183 StopBeforeMatch); 3184 } 3185 3186 // Parse ')'. 3187 SourceLocation RLoc = Tok.getLocation(); 3188 if (!T.consumeClose()) 3189 RLoc = T.getCloseLocation(); 3190 3191 if (ParseOnly || !InteropVarExpr.isUsable() || 3192 (Kind == OMPC_init && !IsTarget && !IsTargetSync)) 3193 return nullptr; 3194 3195 if (Kind == OMPC_init) 3196 return Actions.ActOnOpenMPInitClause(InteropVarExpr.get(), Prefs, IsTarget, 3197 IsTargetSync, Loc, T.getOpenLocation(), 3198 VarLoc, RLoc); 3199 if (Kind == OMPC_use) 3200 return Actions.ActOnOpenMPUseClause(InteropVarExpr.get(), Loc, 3201 T.getOpenLocation(), VarLoc, RLoc); 3202 3203 if (Kind == OMPC_destroy) 3204 return Actions.ActOnOpenMPDestroyClause(InteropVarExpr.get(), Loc, 3205 T.getOpenLocation(), VarLoc, RLoc); 3206 3207 llvm_unreachable("Unexpected interop variable clause."); 3208 } 3209 3210 /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'. 3211 /// 3212 /// default-clause: 3213 /// 'default' '(' 'none' | 'shared' | 'firstprivate' ')' 3214 /// 3215 /// proc_bind-clause: 3216 /// 'proc_bind' '(' 'master' | 'close' | 'spread' ')' 3217 /// 3218 /// update-clause: 3219 /// 'update' '(' 'in' | 'out' | 'inout' | 'mutexinoutset' ')' 3220 /// 3221 OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind, 3222 bool ParseOnly) { 3223 llvm::Optional<SimpleClauseData> Val = parseOpenMPSimpleClause(*this, Kind); 3224 if (!Val || ParseOnly) 3225 return nullptr; 3226 if (getLangOpts().OpenMP < 51 && Kind == OMPC_default && 3227 static_cast<DefaultKind>(Val.getValue().Type) == 3228 OMP_DEFAULT_firstprivate) { 3229 Diag(Val.getValue().LOpen, diag::err_omp_invalid_dsa) 3230 << getOpenMPClauseName(OMPC_firstprivate) 3231 << getOpenMPClauseName(OMPC_default) << "5.1"; 3232 return nullptr; 3233 } 3234 return Actions.ActOnOpenMPSimpleClause( 3235 Kind, Val.getValue().Type, Val.getValue().TypeLoc, Val.getValue().LOpen, 3236 Val.getValue().Loc, Val.getValue().RLoc); 3237 } 3238 3239 /// Parsing of OpenMP clauses like 'ordered'. 3240 /// 3241 /// ordered-clause: 3242 /// 'ordered' 3243 /// 3244 /// nowait-clause: 3245 /// 'nowait' 3246 /// 3247 /// untied-clause: 3248 /// 'untied' 3249 /// 3250 /// mergeable-clause: 3251 /// 'mergeable' 3252 /// 3253 /// read-clause: 3254 /// 'read' 3255 /// 3256 /// threads-clause: 3257 /// 'threads' 3258 /// 3259 /// simd-clause: 3260 /// 'simd' 3261 /// 3262 /// nogroup-clause: 3263 /// 'nogroup' 3264 /// 3265 OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly) { 3266 SourceLocation Loc = Tok.getLocation(); 3267 ConsumeAnyToken(); 3268 3269 if (ParseOnly) 3270 return nullptr; 3271 return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation()); 3272 } 3273 3274 /// Parsing of OpenMP clauses with single expressions and some additional 3275 /// argument like 'schedule' or 'dist_schedule'. 3276 /// 3277 /// schedule-clause: 3278 /// 'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ] 3279 /// ')' 3280 /// 3281 /// if-clause: 3282 /// 'if' '(' [ directive-name-modifier ':' ] expression ')' 3283 /// 3284 /// defaultmap: 3285 /// 'defaultmap' '(' modifier [ ':' kind ] ')' 3286 /// 3287 /// device-clause: 3288 /// 'device' '(' [ device-modifier ':' ] expression ')' 3289 /// 3290 OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind, 3291 OpenMPClauseKind Kind, 3292 bool ParseOnly) { 3293 SourceLocation Loc = ConsumeToken(); 3294 SourceLocation DelimLoc; 3295 // Parse '('. 3296 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 3297 if (T.expectAndConsume(diag::err_expected_lparen_after, 3298 getOpenMPClauseName(Kind).data())) 3299 return nullptr; 3300 3301 ExprResult Val; 3302 SmallVector<unsigned, 4> Arg; 3303 SmallVector<SourceLocation, 4> KLoc; 3304 if (Kind == OMPC_schedule) { 3305 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 3306 Arg.resize(NumberOfElements); 3307 KLoc.resize(NumberOfElements); 3308 Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown; 3309 Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown; 3310 Arg[ScheduleKind] = OMPC_SCHEDULE_unknown; 3311 unsigned KindModifier = getOpenMPSimpleClauseType( 3312 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()); 3313 if (KindModifier > OMPC_SCHEDULE_unknown) { 3314 // Parse 'modifier' 3315 Arg[Modifier1] = KindModifier; 3316 KLoc[Modifier1] = Tok.getLocation(); 3317 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 3318 Tok.isNot(tok::annot_pragma_openmp_end)) 3319 ConsumeAnyToken(); 3320 if (Tok.is(tok::comma)) { 3321 // Parse ',' 'modifier' 3322 ConsumeAnyToken(); 3323 KindModifier = getOpenMPSimpleClauseType( 3324 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()); 3325 Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown 3326 ? KindModifier 3327 : (unsigned)OMPC_SCHEDULE_unknown; 3328 KLoc[Modifier2] = Tok.getLocation(); 3329 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 3330 Tok.isNot(tok::annot_pragma_openmp_end)) 3331 ConsumeAnyToken(); 3332 } 3333 // Parse ':' 3334 if (Tok.is(tok::colon)) 3335 ConsumeAnyToken(); 3336 else 3337 Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier"; 3338 KindModifier = getOpenMPSimpleClauseType( 3339 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()); 3340 } 3341 Arg[ScheduleKind] = KindModifier; 3342 KLoc[ScheduleKind] = Tok.getLocation(); 3343 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 3344 Tok.isNot(tok::annot_pragma_openmp_end)) 3345 ConsumeAnyToken(); 3346 if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static || 3347 Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic || 3348 Arg[ScheduleKind] == OMPC_SCHEDULE_guided) && 3349 Tok.is(tok::comma)) 3350 DelimLoc = ConsumeAnyToken(); 3351 } else if (Kind == OMPC_dist_schedule) { 3352 Arg.push_back(getOpenMPSimpleClauseType( 3353 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts())); 3354 KLoc.push_back(Tok.getLocation()); 3355 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 3356 Tok.isNot(tok::annot_pragma_openmp_end)) 3357 ConsumeAnyToken(); 3358 if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma)) 3359 DelimLoc = ConsumeAnyToken(); 3360 } else if (Kind == OMPC_defaultmap) { 3361 // Get a defaultmap modifier 3362 unsigned Modifier = getOpenMPSimpleClauseType( 3363 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()); 3364 // Set defaultmap modifier to unknown if it is either scalar, aggregate, or 3365 // pointer 3366 if (Modifier < OMPC_DEFAULTMAP_MODIFIER_unknown) 3367 Modifier = OMPC_DEFAULTMAP_MODIFIER_unknown; 3368 Arg.push_back(Modifier); 3369 KLoc.push_back(Tok.getLocation()); 3370 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 3371 Tok.isNot(tok::annot_pragma_openmp_end)) 3372 ConsumeAnyToken(); 3373 // Parse ':' 3374 if (Tok.is(tok::colon) || getLangOpts().OpenMP < 50) { 3375 if (Tok.is(tok::colon)) 3376 ConsumeAnyToken(); 3377 else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown) 3378 Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier"; 3379 // Get a defaultmap kind 3380 Arg.push_back(getOpenMPSimpleClauseType( 3381 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts())); 3382 KLoc.push_back(Tok.getLocation()); 3383 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 3384 Tok.isNot(tok::annot_pragma_openmp_end)) 3385 ConsumeAnyToken(); 3386 } else { 3387 Arg.push_back(OMPC_DEFAULTMAP_unknown); 3388 KLoc.push_back(SourceLocation()); 3389 } 3390 } else if (Kind == OMPC_device) { 3391 // Only target executable directives support extended device construct. 3392 if (isOpenMPTargetExecutionDirective(DKind) && getLangOpts().OpenMP >= 50 && 3393 NextToken().is(tok::colon)) { 3394 // Parse optional <device modifier> ':' 3395 Arg.push_back(getOpenMPSimpleClauseType( 3396 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts())); 3397 KLoc.push_back(Tok.getLocation()); 3398 ConsumeAnyToken(); 3399 // Parse ':' 3400 ConsumeAnyToken(); 3401 } else { 3402 Arg.push_back(OMPC_DEVICE_unknown); 3403 KLoc.emplace_back(); 3404 } 3405 } else { 3406 assert(Kind == OMPC_if); 3407 KLoc.push_back(Tok.getLocation()); 3408 TentativeParsingAction TPA(*this); 3409 auto DK = parseOpenMPDirectiveKind(*this); 3410 Arg.push_back(DK); 3411 if (DK != OMPD_unknown) { 3412 ConsumeToken(); 3413 if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) { 3414 TPA.Commit(); 3415 DelimLoc = ConsumeToken(); 3416 } else { 3417 TPA.Revert(); 3418 Arg.back() = unsigned(OMPD_unknown); 3419 } 3420 } else { 3421 TPA.Revert(); 3422 } 3423 } 3424 3425 bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) || 3426 (Kind == OMPC_dist_schedule && DelimLoc.isValid()) || 3427 Kind == OMPC_if || Kind == OMPC_device; 3428 if (NeedAnExpression) { 3429 SourceLocation ELoc = Tok.getLocation(); 3430 ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast)); 3431 Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional); 3432 Val = 3433 Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false); 3434 } 3435 3436 // Parse ')'. 3437 SourceLocation RLoc = Tok.getLocation(); 3438 if (!T.consumeClose()) 3439 RLoc = T.getCloseLocation(); 3440 3441 if (NeedAnExpression && Val.isInvalid()) 3442 return nullptr; 3443 3444 if (ParseOnly) 3445 return nullptr; 3446 return Actions.ActOnOpenMPSingleExprWithArgClause( 3447 Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc, RLoc); 3448 } 3449 3450 static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec, 3451 UnqualifiedId &ReductionId) { 3452 if (ReductionIdScopeSpec.isEmpty()) { 3453 auto OOK = OO_None; 3454 switch (P.getCurToken().getKind()) { 3455 case tok::plus: 3456 OOK = OO_Plus; 3457 break; 3458 case tok::minus: 3459 OOK = OO_Minus; 3460 break; 3461 case tok::star: 3462 OOK = OO_Star; 3463 break; 3464 case tok::amp: 3465 OOK = OO_Amp; 3466 break; 3467 case tok::pipe: 3468 OOK = OO_Pipe; 3469 break; 3470 case tok::caret: 3471 OOK = OO_Caret; 3472 break; 3473 case tok::ampamp: 3474 OOK = OO_AmpAmp; 3475 break; 3476 case tok::pipepipe: 3477 OOK = OO_PipePipe; 3478 break; 3479 default: 3480 break; 3481 } 3482 if (OOK != OO_None) { 3483 SourceLocation OpLoc = P.ConsumeToken(); 3484 SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()}; 3485 ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations); 3486 return false; 3487 } 3488 } 3489 return P.ParseUnqualifiedId( 3490 ReductionIdScopeSpec, /*ObjectType=*/nullptr, 3491 /*ObjectHadErrors=*/false, /*EnteringContext*/ false, 3492 /*AllowDestructorName*/ false, 3493 /*AllowConstructorName*/ false, 3494 /*AllowDeductionGuide*/ false, nullptr, ReductionId); 3495 } 3496 3497 /// Checks if the token is a valid map-type-modifier. 3498 /// FIXME: It will return an OpenMPMapClauseKind if that's what it parses. 3499 static OpenMPMapModifierKind isMapModifier(Parser &P) { 3500 Token Tok = P.getCurToken(); 3501 if (!Tok.is(tok::identifier)) 3502 return OMPC_MAP_MODIFIER_unknown; 3503 3504 Preprocessor &PP = P.getPreprocessor(); 3505 OpenMPMapModifierKind TypeModifier = 3506 static_cast<OpenMPMapModifierKind>(getOpenMPSimpleClauseType( 3507 OMPC_map, PP.getSpelling(Tok), P.getLangOpts())); 3508 return TypeModifier; 3509 } 3510 3511 /// Parse the mapper modifier in map, to, and from clauses. 3512 bool Parser::parseMapperModifier(OpenMPVarListDataTy &Data) { 3513 // Parse '('. 3514 BalancedDelimiterTracker T(*this, tok::l_paren, tok::colon); 3515 if (T.expectAndConsume(diag::err_expected_lparen_after, "mapper")) { 3516 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 3517 StopBeforeMatch); 3518 return true; 3519 } 3520 // Parse mapper-identifier 3521 if (getLangOpts().CPlusPlus) 3522 ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec, 3523 /*ObjectType=*/nullptr, 3524 /*ObjectHadErrors=*/false, 3525 /*EnteringContext=*/false); 3526 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) { 3527 Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier); 3528 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 3529 StopBeforeMatch); 3530 return true; 3531 } 3532 auto &DeclNames = Actions.getASTContext().DeclarationNames; 3533 Data.ReductionOrMapperId = DeclarationNameInfo( 3534 DeclNames.getIdentifier(Tok.getIdentifierInfo()), Tok.getLocation()); 3535 ConsumeToken(); 3536 // Parse ')'. 3537 return T.consumeClose(); 3538 } 3539 3540 /// Parse map-type-modifiers in map clause. 3541 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) 3542 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) | 3543 /// present 3544 bool Parser::parseMapTypeModifiers(OpenMPVarListDataTy &Data) { 3545 while (getCurToken().isNot(tok::colon)) { 3546 OpenMPMapModifierKind TypeModifier = isMapModifier(*this); 3547 if (TypeModifier == OMPC_MAP_MODIFIER_always || 3548 TypeModifier == OMPC_MAP_MODIFIER_close || 3549 TypeModifier == OMPC_MAP_MODIFIER_present || 3550 TypeModifier == OMPC_MAP_MODIFIER_ompx_hold) { 3551 Data.MapTypeModifiers.push_back(TypeModifier); 3552 Data.MapTypeModifiersLoc.push_back(Tok.getLocation()); 3553 ConsumeToken(); 3554 } else if (TypeModifier == OMPC_MAP_MODIFIER_mapper) { 3555 Data.MapTypeModifiers.push_back(TypeModifier); 3556 Data.MapTypeModifiersLoc.push_back(Tok.getLocation()); 3557 ConsumeToken(); 3558 if (parseMapperModifier(Data)) 3559 return true; 3560 } else { 3561 // For the case of unknown map-type-modifier or a map-type. 3562 // Map-type is followed by a colon; the function returns when it 3563 // encounters a token followed by a colon. 3564 if (Tok.is(tok::comma)) { 3565 Diag(Tok, diag::err_omp_map_type_modifier_missing); 3566 ConsumeToken(); 3567 continue; 3568 } 3569 // Potential map-type token as it is followed by a colon. 3570 if (PP.LookAhead(0).is(tok::colon)) 3571 return false; 3572 Diag(Tok, diag::err_omp_unknown_map_type_modifier) 3573 << (getLangOpts().OpenMP >= 51 ? 1 : 0) 3574 << getLangOpts().OpenMPExtensions; 3575 ConsumeToken(); 3576 } 3577 if (getCurToken().is(tok::comma)) 3578 ConsumeToken(); 3579 } 3580 return false; 3581 } 3582 3583 /// Checks if the token is a valid map-type. 3584 /// FIXME: It will return an OpenMPMapModifierKind if that's what it parses. 3585 static OpenMPMapClauseKind isMapType(Parser &P) { 3586 Token Tok = P.getCurToken(); 3587 // The map-type token can be either an identifier or the C++ delete keyword. 3588 if (!Tok.isOneOf(tok::identifier, tok::kw_delete)) 3589 return OMPC_MAP_unknown; 3590 Preprocessor &PP = P.getPreprocessor(); 3591 OpenMPMapClauseKind MapType = 3592 static_cast<OpenMPMapClauseKind>(getOpenMPSimpleClauseType( 3593 OMPC_map, PP.getSpelling(Tok), P.getLangOpts())); 3594 return MapType; 3595 } 3596 3597 /// Parse map-type in map clause. 3598 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) 3599 /// where, map-type ::= to | from | tofrom | alloc | release | delete 3600 static void parseMapType(Parser &P, Parser::OpenMPVarListDataTy &Data) { 3601 Token Tok = P.getCurToken(); 3602 if (Tok.is(tok::colon)) { 3603 P.Diag(Tok, diag::err_omp_map_type_missing); 3604 return; 3605 } 3606 Data.ExtraModifier = isMapType(P); 3607 if (Data.ExtraModifier == OMPC_MAP_unknown) 3608 P.Diag(Tok, diag::err_omp_unknown_map_type); 3609 P.ConsumeToken(); 3610 } 3611 3612 /// Parses simple expression in parens for single-expression clauses of OpenMP 3613 /// constructs. 3614 ExprResult Parser::ParseOpenMPIteratorsExpr() { 3615 assert(Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator" && 3616 "Expected 'iterator' token."); 3617 SourceLocation IteratorKwLoc = ConsumeToken(); 3618 3619 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 3620 if (T.expectAndConsume(diag::err_expected_lparen_after, "iterator")) 3621 return ExprError(); 3622 3623 SourceLocation LLoc = T.getOpenLocation(); 3624 SmallVector<Sema::OMPIteratorData, 4> Data; 3625 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) { 3626 // Check if the type parsing is required. 3627 ParsedType IteratorType; 3628 if (Tok.isNot(tok::identifier) || NextToken().isNot(tok::equal)) { 3629 // identifier '=' is not found - parse type. 3630 TypeResult TR = ParseTypeName(); 3631 if (TR.isInvalid()) { 3632 T.skipToEnd(); 3633 return ExprError(); 3634 } 3635 IteratorType = TR.get(); 3636 } 3637 3638 // Parse identifier. 3639 IdentifierInfo *II = nullptr; 3640 SourceLocation IdLoc; 3641 if (Tok.is(tok::identifier)) { 3642 II = Tok.getIdentifierInfo(); 3643 IdLoc = ConsumeToken(); 3644 } else { 3645 Diag(Tok, diag::err_expected_unqualified_id) << 0; 3646 } 3647 3648 // Parse '='. 3649 SourceLocation AssignLoc; 3650 if (Tok.is(tok::equal)) 3651 AssignLoc = ConsumeToken(); 3652 else 3653 Diag(Tok, diag::err_omp_expected_equal_in_iterator); 3654 3655 // Parse range-specification - <begin> ':' <end> [ ':' <step> ] 3656 ColonProtectionRAIIObject ColonRAII(*this); 3657 // Parse <begin> 3658 SourceLocation Loc = Tok.getLocation(); 3659 ExprResult LHS = ParseCastExpression(AnyCastExpr); 3660 ExprResult Begin = Actions.CorrectDelayedTyposInExpr( 3661 ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 3662 Begin = Actions.ActOnFinishFullExpr(Begin.get(), Loc, 3663 /*DiscardedValue=*/false); 3664 // Parse ':'. 3665 SourceLocation ColonLoc; 3666 if (Tok.is(tok::colon)) 3667 ColonLoc = ConsumeToken(); 3668 3669 // Parse <end> 3670 Loc = Tok.getLocation(); 3671 LHS = ParseCastExpression(AnyCastExpr); 3672 ExprResult End = Actions.CorrectDelayedTyposInExpr( 3673 ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 3674 End = Actions.ActOnFinishFullExpr(End.get(), Loc, 3675 /*DiscardedValue=*/false); 3676 3677 SourceLocation SecColonLoc; 3678 ExprResult Step; 3679 // Parse optional step. 3680 if (Tok.is(tok::colon)) { 3681 // Parse ':' 3682 SecColonLoc = ConsumeToken(); 3683 // Parse <step> 3684 Loc = Tok.getLocation(); 3685 LHS = ParseCastExpression(AnyCastExpr); 3686 Step = Actions.CorrectDelayedTyposInExpr( 3687 ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 3688 Step = Actions.ActOnFinishFullExpr(Step.get(), Loc, 3689 /*DiscardedValue=*/false); 3690 } 3691 3692 // Parse ',' or ')' 3693 if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren)) 3694 Diag(Tok, diag::err_omp_expected_punc_after_iterator); 3695 if (Tok.is(tok::comma)) 3696 ConsumeToken(); 3697 3698 Sema::OMPIteratorData &D = Data.emplace_back(); 3699 D.DeclIdent = II; 3700 D.DeclIdentLoc = IdLoc; 3701 D.Type = IteratorType; 3702 D.AssignLoc = AssignLoc; 3703 D.ColonLoc = ColonLoc; 3704 D.SecColonLoc = SecColonLoc; 3705 D.Range.Begin = Begin.get(); 3706 D.Range.End = End.get(); 3707 D.Range.Step = Step.get(); 3708 } 3709 3710 // Parse ')'. 3711 SourceLocation RLoc = Tok.getLocation(); 3712 if (!T.consumeClose()) 3713 RLoc = T.getCloseLocation(); 3714 3715 return Actions.ActOnOMPIteratorExpr(getCurScope(), IteratorKwLoc, LLoc, RLoc, 3716 Data); 3717 } 3718 3719 /// Parses clauses with list. 3720 bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind, 3721 OpenMPClauseKind Kind, 3722 SmallVectorImpl<Expr *> &Vars, 3723 OpenMPVarListDataTy &Data) { 3724 UnqualifiedId UnqualifiedReductionId; 3725 bool InvalidReductionId = false; 3726 bool IsInvalidMapperModifier = false; 3727 3728 // Parse '('. 3729 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 3730 if (T.expectAndConsume(diag::err_expected_lparen_after, 3731 getOpenMPClauseName(Kind).data())) 3732 return true; 3733 3734 bool HasIterator = false; 3735 bool NeedRParenForLinear = false; 3736 BalancedDelimiterTracker LinearT(*this, tok::l_paren, 3737 tok::annot_pragma_openmp_end); 3738 // Handle reduction-identifier for reduction clause. 3739 if (Kind == OMPC_reduction || Kind == OMPC_task_reduction || 3740 Kind == OMPC_in_reduction) { 3741 Data.ExtraModifier = OMPC_REDUCTION_unknown; 3742 if (Kind == OMPC_reduction && getLangOpts().OpenMP >= 50 && 3743 (Tok.is(tok::identifier) || Tok.is(tok::kw_default)) && 3744 NextToken().is(tok::comma)) { 3745 // Parse optional reduction modifier. 3746 Data.ExtraModifier = 3747 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts()); 3748 Data.ExtraModifierLoc = Tok.getLocation(); 3749 ConsumeToken(); 3750 assert(Tok.is(tok::comma) && "Expected comma."); 3751 (void)ConsumeToken(); 3752 } 3753 ColonProtectionRAIIObject ColonRAII(*this); 3754 if (getLangOpts().CPlusPlus) 3755 ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec, 3756 /*ObjectType=*/nullptr, 3757 /*ObjectHadErrors=*/false, 3758 /*EnteringContext=*/false); 3759 InvalidReductionId = ParseReductionId( 3760 *this, Data.ReductionOrMapperIdScopeSpec, UnqualifiedReductionId); 3761 if (InvalidReductionId) { 3762 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 3763 StopBeforeMatch); 3764 } 3765 if (Tok.is(tok::colon)) 3766 Data.ColonLoc = ConsumeToken(); 3767 else 3768 Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier"; 3769 if (!InvalidReductionId) 3770 Data.ReductionOrMapperId = 3771 Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId); 3772 } else if (Kind == OMPC_depend) { 3773 if (getLangOpts().OpenMP >= 50) { 3774 if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator") { 3775 // Handle optional dependence modifier. 3776 // iterator(iterators-definition) 3777 // where iterators-definition is iterator-specifier [, 3778 // iterators-definition ] 3779 // where iterator-specifier is [ iterator-type ] identifier = 3780 // range-specification 3781 HasIterator = true; 3782 EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope); 3783 ExprResult IteratorRes = ParseOpenMPIteratorsExpr(); 3784 Data.DepModOrTailExpr = IteratorRes.get(); 3785 // Parse ',' 3786 ExpectAndConsume(tok::comma); 3787 } 3788 } 3789 // Handle dependency type for depend clause. 3790 ColonProtectionRAIIObject ColonRAII(*this); 3791 Data.ExtraModifier = getOpenMPSimpleClauseType( 3792 Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "", 3793 getLangOpts()); 3794 Data.ExtraModifierLoc = Tok.getLocation(); 3795 if (Data.ExtraModifier == OMPC_DEPEND_unknown) { 3796 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 3797 StopBeforeMatch); 3798 } else { 3799 ConsumeToken(); 3800 // Special processing for depend(source) clause. 3801 if (DKind == OMPD_ordered && Data.ExtraModifier == OMPC_DEPEND_source) { 3802 // Parse ')'. 3803 T.consumeClose(); 3804 return false; 3805 } 3806 } 3807 if (Tok.is(tok::colon)) { 3808 Data.ColonLoc = ConsumeToken(); 3809 } else { 3810 Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren 3811 : diag::warn_pragma_expected_colon) 3812 << "dependency type"; 3813 } 3814 } else if (Kind == OMPC_linear) { 3815 // Try to parse modifier if any. 3816 Data.ExtraModifier = OMPC_LINEAR_val; 3817 if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) { 3818 Data.ExtraModifier = 3819 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts()); 3820 Data.ExtraModifierLoc = ConsumeToken(); 3821 LinearT.consumeOpen(); 3822 NeedRParenForLinear = true; 3823 } 3824 } else if (Kind == OMPC_lastprivate) { 3825 // Try to parse modifier if any. 3826 Data.ExtraModifier = OMPC_LASTPRIVATE_unknown; 3827 // Conditional modifier allowed only in OpenMP 5.0 and not supported in 3828 // distribute and taskloop based directives. 3829 if ((getLangOpts().OpenMP >= 50 && !isOpenMPDistributeDirective(DKind) && 3830 !isOpenMPTaskLoopDirective(DKind)) && 3831 Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::colon)) { 3832 Data.ExtraModifier = 3833 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts()); 3834 Data.ExtraModifierLoc = Tok.getLocation(); 3835 ConsumeToken(); 3836 assert(Tok.is(tok::colon) && "Expected colon."); 3837 Data.ColonLoc = ConsumeToken(); 3838 } 3839 } else if (Kind == OMPC_map) { 3840 // Handle map type for map clause. 3841 ColonProtectionRAIIObject ColonRAII(*this); 3842 3843 // The first identifier may be a list item, a map-type or a 3844 // map-type-modifier. The map-type can also be delete which has the same 3845 // spelling of the C++ delete keyword. 3846 Data.ExtraModifier = OMPC_MAP_unknown; 3847 Data.ExtraModifierLoc = Tok.getLocation(); 3848 3849 // Check for presence of a colon in the map clause. 3850 TentativeParsingAction TPA(*this); 3851 bool ColonPresent = false; 3852 if (SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 3853 StopBeforeMatch)) { 3854 if (Tok.is(tok::colon)) 3855 ColonPresent = true; 3856 } 3857 TPA.Revert(); 3858 // Only parse map-type-modifier[s] and map-type if a colon is present in 3859 // the map clause. 3860 if (ColonPresent) { 3861 IsInvalidMapperModifier = parseMapTypeModifiers(Data); 3862 if (!IsInvalidMapperModifier) 3863 parseMapType(*this, Data); 3864 else 3865 SkipUntil(tok::colon, tok::annot_pragma_openmp_end, StopBeforeMatch); 3866 } 3867 if (Data.ExtraModifier == OMPC_MAP_unknown) { 3868 Data.ExtraModifier = OMPC_MAP_tofrom; 3869 Data.IsMapTypeImplicit = true; 3870 } 3871 3872 if (Tok.is(tok::colon)) 3873 Data.ColonLoc = ConsumeToken(); 3874 } else if (Kind == OMPC_to || Kind == OMPC_from) { 3875 while (Tok.is(tok::identifier)) { 3876 auto Modifier = static_cast<OpenMPMotionModifierKind>( 3877 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts())); 3878 if (Modifier == OMPC_MOTION_MODIFIER_unknown) 3879 break; 3880 Data.MotionModifiers.push_back(Modifier); 3881 Data.MotionModifiersLoc.push_back(Tok.getLocation()); 3882 ConsumeToken(); 3883 if (Modifier == OMPC_MOTION_MODIFIER_mapper) { 3884 IsInvalidMapperModifier = parseMapperModifier(Data); 3885 if (IsInvalidMapperModifier) 3886 break; 3887 } 3888 // OpenMP < 5.1 doesn't permit a ',' or additional modifiers. 3889 if (getLangOpts().OpenMP < 51) 3890 break; 3891 // OpenMP 5.1 accepts an optional ',' even if the next character is ':'. 3892 // TODO: Is that intentional? 3893 if (Tok.is(tok::comma)) 3894 ConsumeToken(); 3895 } 3896 if (!Data.MotionModifiers.empty() && Tok.isNot(tok::colon)) { 3897 if (!IsInvalidMapperModifier) { 3898 if (getLangOpts().OpenMP < 51) 3899 Diag(Tok, diag::warn_pragma_expected_colon) << ")"; 3900 else 3901 Diag(Tok, diag::warn_pragma_expected_colon) << "motion modifier"; 3902 } 3903 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 3904 StopBeforeMatch); 3905 } 3906 // OpenMP 5.1 permits a ':' even without a preceding modifier. TODO: Is 3907 // that intentional? 3908 if ((!Data.MotionModifiers.empty() || getLangOpts().OpenMP >= 51) && 3909 Tok.is(tok::colon)) 3910 Data.ColonLoc = ConsumeToken(); 3911 } else if (Kind == OMPC_allocate || 3912 (Kind == OMPC_affinity && Tok.is(tok::identifier) && 3913 PP.getSpelling(Tok) == "iterator")) { 3914 // Handle optional allocator expression followed by colon delimiter. 3915 ColonProtectionRAIIObject ColonRAII(*this); 3916 TentativeParsingAction TPA(*this); 3917 // OpenMP 5.0, 2.10.1, task Construct. 3918 // where aff-modifier is one of the following: 3919 // iterator(iterators-definition) 3920 ExprResult Tail; 3921 if (Kind == OMPC_allocate) { 3922 Tail = ParseAssignmentExpression(); 3923 } else { 3924 HasIterator = true; 3925 EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope); 3926 Tail = ParseOpenMPIteratorsExpr(); 3927 } 3928 Tail = Actions.CorrectDelayedTyposInExpr(Tail); 3929 Tail = Actions.ActOnFinishFullExpr(Tail.get(), T.getOpenLocation(), 3930 /*DiscardedValue=*/false); 3931 if (Tail.isUsable()) { 3932 if (Tok.is(tok::colon)) { 3933 Data.DepModOrTailExpr = Tail.get(); 3934 Data.ColonLoc = ConsumeToken(); 3935 TPA.Commit(); 3936 } else { 3937 // Colon not found, parse only list of variables. 3938 TPA.Revert(); 3939 } 3940 } else { 3941 // Parsing was unsuccessfull, revert and skip to the end of clause or 3942 // directive. 3943 TPA.Revert(); 3944 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 3945 StopBeforeMatch); 3946 } 3947 } 3948 3949 bool IsComma = 3950 (Kind != OMPC_reduction && Kind != OMPC_task_reduction && 3951 Kind != OMPC_in_reduction && Kind != OMPC_depend && Kind != OMPC_map) || 3952 (Kind == OMPC_reduction && !InvalidReductionId) || 3953 (Kind == OMPC_map && Data.ExtraModifier != OMPC_MAP_unknown) || 3954 (Kind == OMPC_depend && Data.ExtraModifier != OMPC_DEPEND_unknown); 3955 const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned); 3956 while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) && 3957 Tok.isNot(tok::annot_pragma_openmp_end))) { 3958 ParseScope OMPListScope(this, Scope::OpenMPDirectiveScope); 3959 ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail); 3960 // Parse variable 3961 ExprResult VarExpr = 3962 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); 3963 if (VarExpr.isUsable()) { 3964 Vars.push_back(VarExpr.get()); 3965 } else { 3966 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 3967 StopBeforeMatch); 3968 } 3969 // Skip ',' if any 3970 IsComma = Tok.is(tok::comma); 3971 if (IsComma) 3972 ConsumeToken(); 3973 else if (Tok.isNot(tok::r_paren) && 3974 Tok.isNot(tok::annot_pragma_openmp_end) && 3975 (!MayHaveTail || Tok.isNot(tok::colon))) 3976 Diag(Tok, diag::err_omp_expected_punc) 3977 << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush) 3978 : getOpenMPClauseName(Kind)) 3979 << (Kind == OMPC_flush); 3980 } 3981 3982 // Parse ')' for linear clause with modifier. 3983 if (NeedRParenForLinear) 3984 LinearT.consumeClose(); 3985 3986 // Parse ':' linear-step (or ':' alignment). 3987 const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon); 3988 if (MustHaveTail) { 3989 Data.ColonLoc = Tok.getLocation(); 3990 SourceLocation ELoc = ConsumeToken(); 3991 ExprResult Tail = ParseAssignmentExpression(); 3992 Tail = 3993 Actions.ActOnFinishFullExpr(Tail.get(), ELoc, /*DiscardedValue*/ false); 3994 if (Tail.isUsable()) 3995 Data.DepModOrTailExpr = Tail.get(); 3996 else 3997 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 3998 StopBeforeMatch); 3999 } 4000 4001 // Parse ')'. 4002 Data.RLoc = Tok.getLocation(); 4003 if (!T.consumeClose()) 4004 Data.RLoc = T.getCloseLocation(); 4005 // Exit from scope when the iterator is used in depend clause. 4006 if (HasIterator) 4007 ExitScope(); 4008 return (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) || 4009 (MustHaveTail && !Data.DepModOrTailExpr) || InvalidReductionId || 4010 IsInvalidMapperModifier; 4011 } 4012 4013 /// Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate', 4014 /// 'shared', 'copyin', 'copyprivate', 'flush', 'reduction', 'task_reduction', 4015 /// 'in_reduction', 'nontemporal', 'exclusive' or 'inclusive'. 4016 /// 4017 /// private-clause: 4018 /// 'private' '(' list ')' 4019 /// firstprivate-clause: 4020 /// 'firstprivate' '(' list ')' 4021 /// lastprivate-clause: 4022 /// 'lastprivate' '(' list ')' 4023 /// shared-clause: 4024 /// 'shared' '(' list ')' 4025 /// linear-clause: 4026 /// 'linear' '(' linear-list [ ':' linear-step ] ')' 4027 /// aligned-clause: 4028 /// 'aligned' '(' list [ ':' alignment ] ')' 4029 /// reduction-clause: 4030 /// 'reduction' '(' [ modifier ',' ] reduction-identifier ':' list ')' 4031 /// task_reduction-clause: 4032 /// 'task_reduction' '(' reduction-identifier ':' list ')' 4033 /// in_reduction-clause: 4034 /// 'in_reduction' '(' reduction-identifier ':' list ')' 4035 /// copyprivate-clause: 4036 /// 'copyprivate' '(' list ')' 4037 /// flush-clause: 4038 /// 'flush' '(' list ')' 4039 /// depend-clause: 4040 /// 'depend' '(' in | out | inout : list | source ')' 4041 /// map-clause: 4042 /// 'map' '(' [ [ always [,] ] [ close [,] ] 4043 /// [ mapper '(' mapper-identifier ')' [,] ] 4044 /// to | from | tofrom | alloc | release | delete ':' ] list ')'; 4045 /// to-clause: 4046 /// 'to' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')' 4047 /// from-clause: 4048 /// 'from' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')' 4049 /// use_device_ptr-clause: 4050 /// 'use_device_ptr' '(' list ')' 4051 /// use_device_addr-clause: 4052 /// 'use_device_addr' '(' list ')' 4053 /// is_device_ptr-clause: 4054 /// 'is_device_ptr' '(' list ')' 4055 /// allocate-clause: 4056 /// 'allocate' '(' [ allocator ':' ] list ')' 4057 /// nontemporal-clause: 4058 /// 'nontemporal' '(' list ')' 4059 /// inclusive-clause: 4060 /// 'inclusive' '(' list ')' 4061 /// exclusive-clause: 4062 /// 'exclusive' '(' list ')' 4063 /// 4064 /// For 'linear' clause linear-list may have the following forms: 4065 /// list 4066 /// modifier(list) 4067 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++). 4068 OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, 4069 OpenMPClauseKind Kind, 4070 bool ParseOnly) { 4071 SourceLocation Loc = Tok.getLocation(); 4072 SourceLocation LOpen = ConsumeToken(); 4073 SmallVector<Expr *, 4> Vars; 4074 OpenMPVarListDataTy Data; 4075 4076 if (ParseOpenMPVarList(DKind, Kind, Vars, Data)) 4077 return nullptr; 4078 4079 if (ParseOnly) 4080 return nullptr; 4081 OMPVarListLocTy Locs(Loc, LOpen, Data.RLoc); 4082 return Actions.ActOnOpenMPVarListClause( 4083 Kind, Vars, Data.DepModOrTailExpr, Locs, Data.ColonLoc, 4084 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId, 4085 Data.ExtraModifier, Data.MapTypeModifiers, Data.MapTypeModifiersLoc, 4086 Data.IsMapTypeImplicit, Data.ExtraModifierLoc, Data.MotionModifiers, 4087 Data.MotionModifiersLoc); 4088 } 4089