1 //===-- lib/Semantics/check-omp-structure.cpp -----------------------------===// 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 9 #include "check-omp-structure.h" 10 #include "flang/Parser/parse-tree.h" 11 #include "flang/Semantics/tools.h" 12 #include <algorithm> 13 14 namespace Fortran::semantics { 15 16 // Use when clause falls under 'struct OmpClause' in 'parse-tree.h'. 17 #define CHECK_SIMPLE_CLAUSE(X, Y) \ 18 void OmpStructureChecker::Enter(const parser::OmpClause::X &) { \ 19 CheckAllowed(llvm::omp::Clause::Y); \ 20 } 21 22 #define CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(X, Y) \ 23 void OmpStructureChecker::Enter(const parser::OmpClause::X &c) { \ 24 CheckAllowed(llvm::omp::Clause::Y); \ 25 RequiresConstantPositiveParameter(llvm::omp::Clause::Y, c.v); \ 26 } 27 28 #define CHECK_REQ_SCALAR_INT_CLAUSE(X, Y) \ 29 void OmpStructureChecker::Enter(const parser::OmpClause::X &c) { \ 30 CheckAllowed(llvm::omp::Clause::Y); \ 31 RequiresPositiveParameter(llvm::omp::Clause::Y, c.v); \ 32 } 33 34 // Use when clause don't falls under 'struct OmpClause' in 'parse-tree.h'. 35 #define CHECK_SIMPLE_PARSER_CLAUSE(X, Y) \ 36 void OmpStructureChecker::Enter(const parser::X &) { \ 37 CheckAllowed(llvm::omp::Y); \ 38 } 39 40 // 'OmpWorkshareBlockChecker' is used to check the validity of the assignment 41 // statements and the expressions enclosed in an OpenMP Workshare construct 42 class OmpWorkshareBlockChecker { 43 public: 44 OmpWorkshareBlockChecker(SemanticsContext &context, parser::CharBlock source) 45 : context_{context}, source_{source} {} 46 47 template <typename T> bool Pre(const T &) { return true; } 48 template <typename T> void Post(const T &) {} 49 50 bool Pre(const parser::AssignmentStmt &assignment) { 51 const auto &var{std::get<parser::Variable>(assignment.t)}; 52 const auto &expr{std::get<parser::Expr>(assignment.t)}; 53 const auto *lhs{GetExpr(var)}; 54 const auto *rhs{GetExpr(expr)}; 55 if (lhs && rhs) { 56 Tristate isDefined{semantics::IsDefinedAssignment( 57 lhs->GetType(), lhs->Rank(), rhs->GetType(), rhs->Rank())}; 58 if (isDefined == Tristate::Yes) { 59 context_.Say(expr.source, 60 "Defined assignment statement is not " 61 "allowed in a WORKSHARE construct"_err_en_US); 62 } 63 } 64 return true; 65 } 66 67 bool Pre(const parser::Expr &expr) { 68 if (const auto *e{GetExpr(expr)}) { 69 for (const Symbol &symbol : evaluate::CollectSymbols(*e)) { 70 const Symbol &root{GetAssociationRoot(symbol)}; 71 if (IsFunction(root) && 72 !(root.attrs().test(Attr::ELEMENTAL) || 73 root.attrs().test(Attr::INTRINSIC))) { 74 context_.Say(expr.source, 75 "User defined non-ELEMENTAL function " 76 "'%s' is not allowed in a WORKSHARE construct"_err_en_US, 77 root.name()); 78 } 79 } 80 } 81 return false; 82 } 83 84 private: 85 SemanticsContext &context_; 86 parser::CharBlock source_; 87 }; 88 89 class OmpCycleChecker { 90 public: 91 OmpCycleChecker(SemanticsContext &context, std::int64_t cycleLevel) 92 : context_{context}, cycleLevel_{cycleLevel} {} 93 94 template <typename T> bool Pre(const T &) { return true; } 95 template <typename T> void Post(const T &) {} 96 97 bool Pre(const parser::DoConstruct &dc) { 98 cycleLevel_--; 99 const auto &labelName{std::get<0>(std::get<0>(dc.t).statement.t)}; 100 if (labelName) { 101 labelNamesandLevels_.emplace(labelName.value().ToString(), cycleLevel_); 102 } 103 return true; 104 } 105 106 bool Pre(const parser::CycleStmt &cyclestmt) { 107 std::map<std::string, std::int64_t>::iterator it; 108 bool err{false}; 109 if (cyclestmt.v) { 110 it = labelNamesandLevels_.find(cyclestmt.v->source.ToString()); 111 err = (it != labelNamesandLevels_.end() && it->second > 0); 112 } 113 if (cycleLevel_ > 0 || err) { 114 context_.Say(*cycleSource_, 115 "CYCLE statement to non-innermost associated loop of an OpenMP DO construct"_err_en_US); 116 } 117 return true; 118 } 119 120 bool Pre(const parser::Statement<parser::ActionStmt> &actionstmt) { 121 cycleSource_ = &actionstmt.source; 122 return true; 123 } 124 125 private: 126 SemanticsContext &context_; 127 const parser::CharBlock *cycleSource_; 128 std::int64_t cycleLevel_; 129 std::map<std::string, std::int64_t> labelNamesandLevels_; 130 }; 131 132 bool OmpStructureChecker::IsCloselyNestedRegion(const OmpDirectiveSet &set) { 133 // Definition of close nesting: 134 // 135 // `A region nested inside another region with no parallel region nested 136 // between them` 137 // 138 // Examples: 139 // non-parallel construct 1 140 // non-parallel construct 2 141 // parallel construct 142 // construct 3 143 // In the above example, construct 3 is NOT closely nested inside construct 1 144 // or 2 145 // 146 // non-parallel construct 1 147 // non-parallel construct 2 148 // construct 3 149 // In the above example, construct 3 is closely nested inside BOTH construct 1 150 // and 2 151 // 152 // Algorithm: 153 // Starting from the parent context, Check in a bottom-up fashion, each level 154 // of the context stack. If we have a match for one of the (supplied) 155 // violating directives, `close nesting` is satisfied. If no match is there in 156 // the entire stack, `close nesting` is not satisfied. If at any level, a 157 // `parallel` region is found, `close nesting` is not satisfied. 158 159 if (CurrentDirectiveIsNested()) { 160 int index = dirContext_.size() - 2; 161 while (index != -1) { 162 if (set.test(dirContext_[index].directive)) { 163 return true; 164 } else if (llvm::omp::parallelSet.test(dirContext_[index].directive)) { 165 return false; 166 } 167 index--; 168 } 169 } 170 return false; 171 } 172 173 bool OmpStructureChecker::HasInvalidWorksharingNesting( 174 const parser::CharBlock &source, const OmpDirectiveSet &set) { 175 // set contains all the invalid closely nested directives 176 // for the given directive (`source` here) 177 if (IsCloselyNestedRegion(set)) { 178 context_.Say(source, 179 "A worksharing region may not be closely nested inside a " 180 "worksharing, explicit task, taskloop, critical, ordered, atomic, or " 181 "master region"_err_en_US); 182 return true; 183 } 184 return false; 185 } 186 187 void OmpStructureChecker::HasInvalidDistributeNesting( 188 const parser::OpenMPLoopConstruct &x) { 189 bool violation{false}; 190 191 OmpDirectiveSet distributeSet{llvm::omp::Directive::OMPD_distribute, 192 llvm::omp::Directive::OMPD_distribute_parallel_do, 193 llvm::omp::Directive::OMPD_distribute_parallel_do_simd, 194 llvm::omp::Directive::OMPD_distribute_parallel_for, 195 llvm::omp::Directive::OMPD_distribute_parallel_for_simd, 196 llvm::omp::Directive::OMPD_distribute_simd}; 197 198 const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)}; 199 const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)}; 200 if (distributeSet.test(beginDir.v)) { 201 // `distribute` region has to be nested 202 if (!CurrentDirectiveIsNested()) { 203 violation = true; 204 } else { 205 // `distribute` region has to be strictly nested inside `teams` 206 if (!llvm::omp::teamSet.test(GetContextParent().directive)) { 207 violation = true; 208 } 209 } 210 } 211 if (violation) { 212 context_.Say(beginDir.source, 213 "`DISTRIBUTE` region has to be strictly nested inside `TEAMS` region."_err_en_US); 214 } 215 } 216 217 void OmpStructureChecker::HasInvalidTeamsNesting( 218 const llvm::omp::Directive &dir, const parser::CharBlock &source) { 219 OmpDirectiveSet allowedSet{llvm::omp::Directive::OMPD_parallel, 220 llvm::omp::Directive::OMPD_parallel_do, 221 llvm::omp::Directive::OMPD_parallel_do_simd, 222 llvm::omp::Directive::OMPD_parallel_for, 223 llvm::omp::Directive::OMPD_parallel_for_simd, 224 llvm::omp::Directive::OMPD_parallel_master, 225 llvm::omp::Directive::OMPD_parallel_master_taskloop, 226 llvm::omp::Directive::OMPD_parallel_master_taskloop_simd, 227 llvm::omp::Directive::OMPD_parallel_sections, 228 llvm::omp::Directive::OMPD_parallel_workshare, 229 llvm::omp::Directive::OMPD_distribute, 230 llvm::omp::Directive::OMPD_distribute_parallel_do, 231 llvm::omp::Directive::OMPD_distribute_parallel_do_simd, 232 llvm::omp::Directive::OMPD_distribute_parallel_for, 233 llvm::omp::Directive::OMPD_distribute_parallel_for_simd, 234 llvm::omp::Directive::OMPD_distribute_simd}; 235 236 if (!allowedSet.test(dir)) { 237 context_.Say(source, 238 "Only `DISTRIBUTE` or `PARALLEL` regions are allowed to be strictly nested inside `TEAMS` region."_err_en_US); 239 } 240 } 241 242 void OmpStructureChecker::CheckPredefinedAllocatorRestriction( 243 const parser::CharBlock &source, const parser::Name &name) { 244 if (const auto *symbol{name.symbol}) { 245 const auto *commonBlock{FindCommonBlockContaining(*symbol)}; 246 const auto &scope{context_.FindScope(symbol->name())}; 247 const Scope &containingScope{GetProgramUnitContaining(scope)}; 248 if (!isPredefinedAllocator && 249 (IsSave(*symbol) || commonBlock || 250 containingScope.kind() == Scope::Kind::Module)) { 251 context_.Say(source, 252 "If list items within the ALLOCATE directive have the " 253 "SAVE attribute, are a common block name, or are " 254 "declared in the scope of a module, then only " 255 "predefined memory allocator parameters can be used " 256 "in the allocator clause"_err_en_US); 257 } 258 } 259 } 260 261 void OmpStructureChecker::CheckPredefinedAllocatorRestriction( 262 const parser::CharBlock &source, 263 const parser::OmpObjectList &ompObjectList) { 264 for (const auto &ompObject : ompObjectList.v) { 265 std::visit( 266 common::visitors{ 267 [&](const parser::Designator &designator) { 268 if (const auto *dataRef{ 269 std::get_if<parser::DataRef>(&designator.u)}) { 270 if (const auto *name{std::get_if<parser::Name>(&dataRef->u)}) { 271 CheckPredefinedAllocatorRestriction(source, *name); 272 } 273 } 274 }, 275 [&](const parser::Name &name) { 276 CheckPredefinedAllocatorRestriction(source, name); 277 }, 278 }, 279 ompObject.u); 280 } 281 } 282 283 void OmpStructureChecker::Enter(const parser::OpenMPConstruct &x) { 284 // Simd Construct with Ordered Construct Nesting check 285 // We cannot use CurrentDirectiveIsNested() here because 286 // PushContextAndClauseSets() has not been called yet, it is 287 // called individually for each construct. Therefore a 288 // dirContext_ size `1` means the current construct is nested 289 if (dirContext_.size() >= 1) { 290 if (GetDirectiveNest(SIMDNest) > 0) { 291 CheckSIMDNest(x); 292 } 293 if (GetDirectiveNest(TargetNest) > 0) { 294 CheckTargetNest(x); 295 } 296 } 297 } 298 299 void OmpStructureChecker::Enter(const parser::OpenMPLoopConstruct &x) { 300 const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)}; 301 const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)}; 302 303 // check matching, End directive is optional 304 if (const auto &endLoopDir{ 305 std::get<std::optional<parser::OmpEndLoopDirective>>(x.t)}) { 306 const auto &endDir{ 307 std::get<parser::OmpLoopDirective>(endLoopDir.value().t)}; 308 309 CheckMatching<parser::OmpLoopDirective>(beginDir, endDir); 310 } 311 312 PushContextAndClauseSets(beginDir.source, beginDir.v); 313 if (llvm::omp::simdSet.test(GetContext().directive)) { 314 EnterDirectiveNest(SIMDNest); 315 } 316 317 if (beginDir.v == llvm::omp::Directive::OMPD_do) { 318 // 2.7.1 do-clause -> private-clause | 319 // firstprivate-clause | 320 // lastprivate-clause | 321 // linear-clause | 322 // reduction-clause | 323 // schedule-clause | 324 // collapse-clause | 325 // ordered-clause 326 327 // nesting check 328 HasInvalidWorksharingNesting( 329 beginDir.source, llvm::omp::nestedWorkshareErrSet); 330 } 331 SetLoopInfo(x); 332 333 if (const auto &doConstruct{ 334 std::get<std::optional<parser::DoConstruct>>(x.t)}) { 335 const auto &doBlock{std::get<parser::Block>(doConstruct->t)}; 336 CheckNoBranching(doBlock, beginDir.v, beginDir.source); 337 } 338 CheckDoWhile(x); 339 CheckLoopItrVariableIsInt(x); 340 CheckCycleConstraints(x); 341 HasInvalidDistributeNesting(x); 342 if (CurrentDirectiveIsNested() && 343 llvm::omp::teamSet.test(GetContextParent().directive)) { 344 HasInvalidTeamsNesting(beginDir.v, beginDir.source); 345 } 346 if ((beginDir.v == llvm::omp::Directive::OMPD_distribute_parallel_do_simd) || 347 (beginDir.v == llvm::omp::Directive::OMPD_distribute_simd)) { 348 CheckDistLinear(x); 349 } 350 } 351 const parser::Name OmpStructureChecker::GetLoopIndex( 352 const parser::DoConstruct *x) { 353 using Bounds = parser::LoopControl::Bounds; 354 return std::get<Bounds>(x->GetLoopControl()->u).name.thing; 355 } 356 void OmpStructureChecker::SetLoopInfo(const parser::OpenMPLoopConstruct &x) { 357 if (const auto &loopConstruct{ 358 std::get<std::optional<parser::DoConstruct>>(x.t)}) { 359 const parser::DoConstruct *loop{&*loopConstruct}; 360 if (loop && loop->IsDoNormal()) { 361 const parser::Name &itrVal{GetLoopIndex(loop)}; 362 SetLoopIv(itrVal.symbol); 363 } 364 } 365 } 366 void OmpStructureChecker::CheckDoWhile(const parser::OpenMPLoopConstruct &x) { 367 const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)}; 368 const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)}; 369 if (beginDir.v == llvm::omp::Directive::OMPD_do) { 370 if (const auto &doConstruct{ 371 std::get<std::optional<parser::DoConstruct>>(x.t)}) { 372 if (doConstruct.value().IsDoWhile()) { 373 const auto &doStmt{std::get<parser::Statement<parser::NonLabelDoStmt>>( 374 doConstruct.value().t)}; 375 context_.Say(doStmt.source, 376 "The DO loop cannot be a DO WHILE with DO directive."_err_en_US); 377 } 378 } 379 } 380 } 381 382 void OmpStructureChecker::CheckLoopItrVariableIsInt( 383 const parser::OpenMPLoopConstruct &x) { 384 if (const auto &loopConstruct{ 385 std::get<std::optional<parser::DoConstruct>>(x.t)}) { 386 387 for (const parser::DoConstruct *loop{&*loopConstruct}; loop;) { 388 if (loop->IsDoNormal()) { 389 const parser::Name &itrVal{GetLoopIndex(loop)}; 390 if (itrVal.symbol) { 391 const auto *type{itrVal.symbol->GetType()}; 392 if (!type->IsNumeric(TypeCategory::Integer)) { 393 context_.Say(itrVal.source, 394 "The DO loop iteration" 395 " variable must be of the type integer."_err_en_US, 396 itrVal.ToString()); 397 } 398 } 399 } 400 // Get the next DoConstruct if block is not empty. 401 const auto &block{std::get<parser::Block>(loop->t)}; 402 const auto it{block.begin()}; 403 loop = it != block.end() ? parser::Unwrap<parser::DoConstruct>(*it) 404 : nullptr; 405 } 406 } 407 } 408 409 void OmpStructureChecker::CheckSIMDNest(const parser::OpenMPConstruct &c) { 410 // Check the following: 411 // The only OpenMP constructs that can be encountered during execution of 412 // a simd region are the `atomic` construct, the `loop` construct, the `simd` 413 // construct and the `ordered` construct with the `simd` clause. 414 // TODO: Expand the check to include `LOOP` construct as well when it is 415 // supported. 416 417 // Check if the parent context has the SIMD clause 418 // Please note that we use GetContext() instead of GetContextParent() 419 // because PushContextAndClauseSets() has not been called on the 420 // current context yet. 421 // TODO: Check for declare simd regions. 422 bool eligibleSIMD{false}; 423 std::visit(Fortran::common::visitors{ 424 // Allow `!$OMP ORDERED SIMD` 425 [&](const parser::OpenMPBlockConstruct &c) { 426 const auto &beginBlockDir{ 427 std::get<parser::OmpBeginBlockDirective>(c.t)}; 428 const auto &beginDir{ 429 std::get<parser::OmpBlockDirective>(beginBlockDir.t)}; 430 if (beginDir.v == llvm::omp::Directive::OMPD_ordered) { 431 const auto &clauses{ 432 std::get<parser::OmpClauseList>(beginBlockDir.t)}; 433 for (const auto &clause : clauses.v) { 434 if (std::get_if<parser::OmpClause::Simd>(&clause.u)) { 435 eligibleSIMD = true; 436 break; 437 } 438 } 439 } 440 }, 441 [&](const parser::OpenMPSimpleStandaloneConstruct &c) { 442 const auto &dir{ 443 std::get<parser::OmpSimpleStandaloneDirective>(c.t)}; 444 if (dir.v == llvm::omp::Directive::OMPD_ordered) { 445 const auto &clauses{std::get<parser::OmpClauseList>(c.t)}; 446 for (const auto &clause : clauses.v) { 447 if (std::get_if<parser::OmpClause::Simd>(&clause.u)) { 448 eligibleSIMD = true; 449 break; 450 } 451 } 452 } 453 }, 454 // Allowing SIMD construct 455 [&](const parser::OpenMPLoopConstruct &c) { 456 const auto &beginLoopDir{ 457 std::get<parser::OmpBeginLoopDirective>(c.t)}; 458 const auto &beginDir{ 459 std::get<parser::OmpLoopDirective>(beginLoopDir.t)}; 460 if ((beginDir.v == llvm::omp::Directive::OMPD_simd) || 461 (beginDir.v == llvm::omp::Directive::OMPD_do_simd)) { 462 eligibleSIMD = true; 463 } 464 }, 465 [&](const parser::OpenMPAtomicConstruct &c) { 466 // Allow `!$OMP ATOMIC` 467 eligibleSIMD = true; 468 }, 469 [&](const auto &c) {}, 470 }, 471 c.u); 472 if (!eligibleSIMD) { 473 context_.Say(parser::FindSourceLocation(c), 474 "The only OpenMP constructs that can be encountered during execution " 475 "of a 'SIMD'" 476 " region are the `ATOMIC` construct, the `LOOP` construct, the `SIMD`" 477 " construct and the `ORDERED` construct with the `SIMD` clause."_err_en_US); 478 } 479 } 480 481 void OmpStructureChecker::CheckTargetNest(const parser::OpenMPConstruct &c) { 482 // 2.12.5 Target Construct Restriction 483 bool eligibleTarget{true}; 484 llvm::omp::Directive ineligibleTargetDir; 485 std::visit( 486 common::visitors{ 487 [&](const parser::OpenMPBlockConstruct &c) { 488 const auto &beginBlockDir{ 489 std::get<parser::OmpBeginBlockDirective>(c.t)}; 490 const auto &beginDir{ 491 std::get<parser::OmpBlockDirective>(beginBlockDir.t)}; 492 if (beginDir.v == llvm::omp::Directive::OMPD_target_data) { 493 eligibleTarget = false; 494 ineligibleTargetDir = beginDir.v; 495 } 496 }, 497 [&](const parser::OpenMPStandaloneConstruct &c) { 498 std::visit( 499 common::visitors{ 500 [&](const parser::OpenMPSimpleStandaloneConstruct &c) { 501 const auto &dir{ 502 std::get<parser::OmpSimpleStandaloneDirective>(c.t)}; 503 if (dir.v == llvm::omp::Directive::OMPD_target_update || 504 dir.v == 505 llvm::omp::Directive::OMPD_target_enter_data || 506 dir.v == 507 llvm::omp::Directive::OMPD_target_exit_data) { 508 eligibleTarget = false; 509 ineligibleTargetDir = dir.v; 510 } 511 }, 512 [&](const auto &c) {}, 513 }, 514 c.u); 515 }, 516 [&](const auto &c) {}, 517 }, 518 c.u); 519 if (!eligibleTarget) { 520 context_.Say(parser::FindSourceLocation(c), 521 "If %s directive is nested inside TARGET region, the behaviour " 522 "is unspecified"_en_US, 523 parser::ToUpperCaseLetters( 524 getDirectiveName(ineligibleTargetDir).str())); 525 } 526 } 527 528 std::int64_t OmpStructureChecker::GetOrdCollapseLevel( 529 const parser::OpenMPLoopConstruct &x) { 530 const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)}; 531 const auto &clauseList{std::get<parser::OmpClauseList>(beginLoopDir.t)}; 532 std::int64_t orderedCollapseLevel{1}; 533 std::int64_t orderedLevel{0}; 534 std::int64_t collapseLevel{0}; 535 536 for (const auto &clause : clauseList.v) { 537 if (const auto *collapseClause{ 538 std::get_if<parser::OmpClause::Collapse>(&clause.u)}) { 539 if (const auto v{GetIntValue(collapseClause->v)}) { 540 collapseLevel = *v; 541 } 542 } 543 if (const auto *orderedClause{ 544 std::get_if<parser::OmpClause::Ordered>(&clause.u)}) { 545 if (const auto v{GetIntValue(orderedClause->v)}) { 546 orderedLevel = *v; 547 } 548 } 549 } 550 if (orderedLevel >= collapseLevel) { 551 orderedCollapseLevel = orderedLevel; 552 } else { 553 orderedCollapseLevel = collapseLevel; 554 } 555 return orderedCollapseLevel; 556 } 557 558 void OmpStructureChecker::CheckCycleConstraints( 559 const parser::OpenMPLoopConstruct &x) { 560 std::int64_t ordCollapseLevel{GetOrdCollapseLevel(x)}; 561 OmpCycleChecker ompCycleChecker{context_, ordCollapseLevel}; 562 parser::Walk(x, ompCycleChecker); 563 } 564 565 void OmpStructureChecker::CheckDistLinear( 566 const parser::OpenMPLoopConstruct &x) { 567 568 const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)}; 569 const auto &clauses{std::get<parser::OmpClauseList>(beginLoopDir.t)}; 570 571 semantics::UnorderedSymbolSet indexVars; 572 573 // Collect symbols of all the variables from linear clauses 574 for (const auto &clause : clauses.v) { 575 if (const auto *linearClause{ 576 std::get_if<parser::OmpClause::Linear>(&clause.u)}) { 577 578 std::list<parser::Name> values; 579 // Get the variant type 580 if (std::holds_alternative<parser::OmpLinearClause::WithModifier>( 581 linearClause->v.u)) { 582 const auto &withM{ 583 std::get<parser::OmpLinearClause::WithModifier>(linearClause->v.u)}; 584 values = withM.names; 585 } else { 586 const auto &withOutM{std::get<parser::OmpLinearClause::WithoutModifier>( 587 linearClause->v.u)}; 588 values = withOutM.names; 589 } 590 for (auto const &v : values) { 591 indexVars.insert(*(v.symbol)); 592 } 593 } 594 } 595 596 if (!indexVars.empty()) { 597 // Get collapse level, if given, to find which loops are "associated." 598 std::int64_t collapseVal{GetOrdCollapseLevel(x)}; 599 // Include the top loop if no collapse is specified 600 if (collapseVal == 0) { 601 collapseVal = 1; 602 } 603 604 // Match the loop index variables with the collected symbols from linear 605 // clauses. 606 if (const auto &loopConstruct{ 607 std::get<std::optional<parser::DoConstruct>>(x.t)}) { 608 for (const parser::DoConstruct *loop{&*loopConstruct}; loop;) { 609 if (loop->IsDoNormal()) { 610 const parser::Name &itrVal{GetLoopIndex(loop)}; 611 if (itrVal.symbol) { 612 // Remove the symbol from the collcted set 613 indexVars.erase(*(itrVal.symbol)); 614 } 615 collapseVal--; 616 if (collapseVal == 0) { 617 break; 618 } 619 } 620 // Get the next DoConstruct if block is not empty. 621 const auto &block{std::get<parser::Block>(loop->t)}; 622 const auto it{block.begin()}; 623 loop = it != block.end() ? parser::Unwrap<parser::DoConstruct>(*it) 624 : nullptr; 625 } 626 } 627 628 // Show error for the remaining variables 629 for (auto var : indexVars) { 630 const Symbol &root{GetAssociationRoot(var)}; 631 context_.Say(parser::FindSourceLocation(x), 632 "Variable '%s' not allowed in `LINEAR` clause, only loop iterator can be specified in `LINEAR` clause of a construct combined with `DISTRIBUTE`"_err_en_US, 633 root.name()); 634 } 635 } 636 } 637 638 void OmpStructureChecker::Leave(const parser::OpenMPLoopConstruct &) { 639 if (llvm::omp::simdSet.test(GetContext().directive)) { 640 ExitDirectiveNest(SIMDNest); 641 } 642 dirContext_.pop_back(); 643 } 644 645 void OmpStructureChecker::Enter(const parser::OmpEndLoopDirective &x) { 646 const auto &dir{std::get<parser::OmpLoopDirective>(x.t)}; 647 ResetPartialContext(dir.source); 648 switch (dir.v) { 649 // 2.7.1 end-do -> END DO [nowait-clause] 650 // 2.8.3 end-do-simd -> END DO SIMD [nowait-clause] 651 case llvm::omp::Directive::OMPD_do: 652 case llvm::omp::Directive::OMPD_do_simd: 653 SetClauseSets(dir.v); 654 break; 655 default: 656 // no clauses are allowed 657 break; 658 } 659 } 660 661 void OmpStructureChecker::Enter(const parser::OpenMPBlockConstruct &x) { 662 const auto &beginBlockDir{std::get<parser::OmpBeginBlockDirective>(x.t)}; 663 const auto &endBlockDir{std::get<parser::OmpEndBlockDirective>(x.t)}; 664 const auto &beginDir{std::get<parser::OmpBlockDirective>(beginBlockDir.t)}; 665 const auto &endDir{std::get<parser::OmpBlockDirective>(endBlockDir.t)}; 666 const parser::Block &block{std::get<parser::Block>(x.t)}; 667 668 CheckMatching<parser::OmpBlockDirective>(beginDir, endDir); 669 670 PushContextAndClauseSets(beginDir.source, beginDir.v); 671 if (GetContext().directive == llvm::omp::Directive::OMPD_target) { 672 EnterDirectiveNest(TargetNest); 673 } 674 675 if (CurrentDirectiveIsNested()) { 676 CheckIfDoOrderedClause(beginDir); 677 if (llvm::omp::teamSet.test(GetContextParent().directive)) { 678 HasInvalidTeamsNesting(beginDir.v, beginDir.source); 679 } 680 if (GetContext().directive == llvm::omp::Directive::OMPD_master) { 681 CheckMasterNesting(x); 682 } 683 // A teams region can only be strictly nested within the implicit parallel 684 // region or a target region. 685 if (GetContext().directive == llvm::omp::Directive::OMPD_teams && 686 GetContextParent().directive != llvm::omp::Directive::OMPD_target) { 687 context_.Say(parser::FindSourceLocation(x), 688 "%s region can only be strictly nested within the implicit parallel " 689 "region or TARGET region"_err_en_US, 690 ContextDirectiveAsFortran()); 691 } 692 // If a teams construct is nested within a target construct, that target 693 // construct must contain no statements, declarations or directives outside 694 // of the teams construct. 695 if (GetContext().directive == llvm::omp::Directive::OMPD_teams && 696 GetContextParent().directive == llvm::omp::Directive::OMPD_target && 697 !GetDirectiveNest(TargetBlockOnlyTeams)) { 698 context_.Say(GetContextParent().directiveSource, 699 "TARGET construct with nested TEAMS region contains statements or " 700 "directives outside of the TEAMS construct"_err_en_US); 701 } 702 } 703 704 CheckNoBranching(block, beginDir.v, beginDir.source); 705 706 switch (beginDir.v) { 707 case llvm::omp::Directive::OMPD_target: 708 if (CheckTargetBlockOnlyTeams(block)) { 709 EnterDirectiveNest(TargetBlockOnlyTeams); 710 } 711 break; 712 case llvm::omp::OMPD_workshare: 713 case llvm::omp::OMPD_parallel_workshare: 714 CheckWorkshareBlockStmts(block, beginDir.source); 715 HasInvalidWorksharingNesting( 716 beginDir.source, llvm::omp::nestedWorkshareErrSet); 717 break; 718 case llvm::omp::Directive::OMPD_single: 719 // TODO: This check needs to be extended while implementing nesting of 720 // regions checks. 721 HasInvalidWorksharingNesting( 722 beginDir.source, llvm::omp::nestedWorkshareErrSet); 723 break; 724 default: 725 break; 726 } 727 } 728 729 void OmpStructureChecker::CheckMasterNesting( 730 const parser::OpenMPBlockConstruct &x) { 731 // A MASTER region may not be `closely nested` inside a worksharing, loop, 732 // task, taskloop, or atomic region. 733 // TODO: Expand the check to include `LOOP` construct as well when it is 734 // supported. 735 if (IsCloselyNestedRegion(llvm::omp::nestedMasterErrSet)) { 736 context_.Say(parser::FindSourceLocation(x), 737 "`MASTER` region may not be closely nested inside of `WORKSHARING`, " 738 "`LOOP`, `TASK`, `TASKLOOP`," 739 " or `ATOMIC` region."_err_en_US); 740 } 741 } 742 743 void OmpStructureChecker::CheckIfDoOrderedClause( 744 const parser::OmpBlockDirective &blkDirective) { 745 if (blkDirective.v == llvm::omp::OMPD_ordered) { 746 // Loops 747 if (llvm::omp::doSet.test(GetContextParent().directive) && 748 !FindClauseParent(llvm::omp::Clause::OMPC_ordered)) { 749 context_.Say(blkDirective.source, 750 "The ORDERED clause must be present on the loop" 751 " construct if any ORDERED region ever binds" 752 " to a loop region arising from the loop construct."_err_en_US); 753 } 754 // Other disallowed nestings, these directives do not support 755 // ordered clause in them, so no need to check 756 else if (IsCloselyNestedRegion(llvm::omp::nestedOrderedErrSet)) { 757 context_.Say(blkDirective.source, 758 "`ORDERED` region may not be closely nested inside of " 759 "`CRITICAL`, `ORDERED`, explicit `TASK` or `TASKLOOP` region."_err_en_US); 760 } 761 } 762 } 763 764 void OmpStructureChecker::Leave(const parser::OpenMPBlockConstruct &) { 765 if (GetDirectiveNest(TargetBlockOnlyTeams)) { 766 ExitDirectiveNest(TargetBlockOnlyTeams); 767 } 768 if (GetContext().directive == llvm::omp::Directive::OMPD_target) { 769 ExitDirectiveNest(TargetNest); 770 } 771 dirContext_.pop_back(); 772 } 773 774 void OmpStructureChecker::ChecksOnOrderedAsBlock() { 775 if (FindClause(llvm::omp::Clause::OMPC_depend)) { 776 context_.Say(GetContext().clauseSource, 777 "DEPEND(*) clauses are not allowed when ORDERED construct is a block" 778 " construct with an ORDERED region"_err_en_US); 779 } 780 } 781 782 void OmpStructureChecker::Leave(const parser::OmpBeginBlockDirective &) { 783 switch (GetContext().directive) { 784 case llvm::omp::Directive::OMPD_ordered: 785 // [5.1] 2.19.9 Ordered Construct Restriction 786 ChecksOnOrderedAsBlock(); 787 break; 788 default: 789 break; 790 } 791 } 792 793 void OmpStructureChecker::Enter(const parser::OpenMPSectionsConstruct &x) { 794 const auto &beginSectionsDir{ 795 std::get<parser::OmpBeginSectionsDirective>(x.t)}; 796 const auto &endSectionsDir{std::get<parser::OmpEndSectionsDirective>(x.t)}; 797 const auto &beginDir{ 798 std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)}; 799 const auto &endDir{std::get<parser::OmpSectionsDirective>(endSectionsDir.t)}; 800 CheckMatching<parser::OmpSectionsDirective>(beginDir, endDir); 801 802 PushContextAndClauseSets(beginDir.source, beginDir.v); 803 const auto §ionBlocks{std::get<parser::OmpSectionBlocks>(x.t)}; 804 for (const auto &block : sectionBlocks.v) { 805 CheckNoBranching(block, beginDir.v, beginDir.source); 806 } 807 HasInvalidWorksharingNesting( 808 beginDir.source, llvm::omp::nestedWorkshareErrSet); 809 } 810 811 void OmpStructureChecker::Leave(const parser::OpenMPSectionsConstruct &) { 812 dirContext_.pop_back(); 813 } 814 815 void OmpStructureChecker::Enter(const parser::OmpEndSectionsDirective &x) { 816 const auto &dir{std::get<parser::OmpSectionsDirective>(x.t)}; 817 ResetPartialContext(dir.source); 818 switch (dir.v) { 819 // 2.7.2 end-sections -> END SECTIONS [nowait-clause] 820 case llvm::omp::Directive::OMPD_sections: 821 PushContextAndClauseSets( 822 dir.source, llvm::omp::Directive::OMPD_end_sections); 823 break; 824 default: 825 // no clauses are allowed 826 break; 827 } 828 } 829 830 // TODO: Verify the popping of dirContext requirement after nowait 831 // implementation, as there is an implicit barrier at the end of the worksharing 832 // constructs unless a nowait clause is specified. Only OMPD_end_sections is 833 // popped becuase it is pushed while entering the EndSectionsDirective. 834 void OmpStructureChecker::Leave(const parser::OmpEndSectionsDirective &x) { 835 if (GetContext().directive == llvm::omp::Directive::OMPD_end_sections) { 836 dirContext_.pop_back(); 837 } 838 } 839 840 void OmpStructureChecker::CheckThreadprivateOrDeclareTargetVar( 841 const parser::OmpObjectList &objList) { 842 for (const auto &ompObject : objList.v) { 843 std::visit( 844 common::visitors{ 845 [&](const parser::Designator &) { 846 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) { 847 const auto &declScope{ 848 GetProgramUnitContaining(name->symbol->GetUltimate())}; 849 const auto *sym = 850 declScope.parent().FindSymbol(name->symbol->name()); 851 if (sym && 852 (sym->has<MainProgramDetails>() || 853 sym->has<ModuleDetails>())) { 854 context_.Say(name->source, 855 "The module name or main program name cannot be in a %s " 856 "directive"_err_en_US, 857 ContextDirectiveAsFortran()); 858 } else if (name->symbol->GetUltimate().IsSubprogram()) { 859 if (GetContext().directive == 860 llvm::omp::Directive::OMPD_threadprivate) 861 context_.Say(name->source, 862 "The procedure name cannot be in a %s " 863 "directive"_err_en_US, 864 ContextDirectiveAsFortran()); 865 // TODO: Check for procedure name in declare target directive. 866 } else if (name->symbol->attrs().test(Attr::PARAMETER)) { 867 if (GetContext().directive == 868 llvm::omp::Directive::OMPD_threadprivate) 869 context_.Say(name->source, 870 "The entity with PARAMETER attribute cannot be in a %s " 871 "directive"_err_en_US, 872 ContextDirectiveAsFortran()); 873 else if (GetContext().directive == 874 llvm::omp::Directive::OMPD_declare_target) 875 context_.Say(name->source, 876 "The entity with PARAMETER attribute is used in a %s " 877 "directive"_en_US, 878 ContextDirectiveAsFortran()); 879 } else if (FindCommonBlockContaining(*name->symbol)) { 880 context_.Say(name->source, 881 "A variable in a %s directive cannot be an element of a " 882 "common block"_err_en_US, 883 ContextDirectiveAsFortran()); 884 } else if (!IsSave(*name->symbol) && 885 declScope.kind() != Scope::Kind::MainProgram && 886 declScope.kind() != Scope::Kind::Module) { 887 context_.Say(name->source, 888 "A variable that appears in a %s directive must be " 889 "declared in the scope of a module or have the SAVE " 890 "attribute, either explicitly or implicitly"_err_en_US, 891 ContextDirectiveAsFortran()); 892 } else if (FindEquivalenceSet(*name->symbol)) { 893 context_.Say(name->source, 894 "A variable in a %s directive cannot appear in an " 895 "EQUIVALENCE statement"_err_en_US, 896 ContextDirectiveAsFortran()); 897 } else if (name->symbol->test(Symbol::Flag::OmpThreadprivate) && 898 GetContext().directive == 899 llvm::omp::Directive::OMPD_declare_target) { 900 context_.Say(name->source, 901 "A THREADPRIVATE variable cannot appear in a %s " 902 "directive"_err_en_US, 903 ContextDirectiveAsFortran()); 904 } 905 } 906 }, 907 [&](const parser::Name &) {}, // common block 908 }, 909 ompObject.u); 910 } 911 } 912 913 void OmpStructureChecker::Enter(const parser::OpenMPThreadprivate &c) { 914 const auto &dir{std::get<parser::Verbatim>(c.t)}; 915 PushContextAndClauseSets( 916 dir.source, llvm::omp::Directive::OMPD_threadprivate); 917 } 918 919 void OmpStructureChecker::Leave(const parser::OpenMPThreadprivate &c) { 920 const auto &dir{std::get<parser::Verbatim>(c.t)}; 921 const auto &objectList{std::get<parser::OmpObjectList>(c.t)}; 922 CheckIsVarPartOfAnotherVar(dir.source, objectList); 923 CheckThreadprivateOrDeclareTargetVar(objectList); 924 dirContext_.pop_back(); 925 } 926 927 void OmpStructureChecker::Enter(const parser::OpenMPDeclareSimdConstruct &x) { 928 const auto &dir{std::get<parser::Verbatim>(x.t)}; 929 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_declare_simd); 930 } 931 932 void OmpStructureChecker::Leave(const parser::OpenMPDeclareSimdConstruct &) { 933 dirContext_.pop_back(); 934 } 935 936 void OmpStructureChecker::Enter(const parser::OpenMPDeclarativeAllocate &x) { 937 isPredefinedAllocator = true; 938 const auto &dir{std::get<parser::Verbatim>(x.t)}; 939 const auto &objectList{std::get<parser::OmpObjectList>(x.t)}; 940 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate); 941 CheckIsVarPartOfAnotherVar(dir.source, objectList); 942 } 943 944 void OmpStructureChecker::Leave(const parser::OpenMPDeclarativeAllocate &x) { 945 const auto &dir{std::get<parser::Verbatim>(x.t)}; 946 const auto &objectList{std::get<parser::OmpObjectList>(x.t)}; 947 CheckPredefinedAllocatorRestriction(dir.source, objectList); 948 dirContext_.pop_back(); 949 } 950 951 void OmpStructureChecker::Enter(const parser::OmpClause::Allocator &x) { 952 CheckAllowed(llvm::omp::Clause::OMPC_allocator); 953 // Note: Predefined allocators are stored in ScalarExpr as numbers 954 // whereas custom allocators are stored as strings, so if the ScalarExpr 955 // actually has an int value, then it must be a predefined allocator 956 isPredefinedAllocator = GetIntValue(x.v).has_value(); 957 RequiresPositiveParameter(llvm::omp::Clause::OMPC_allocator, x.v); 958 } 959 960 void OmpStructureChecker::Enter(const parser::OpenMPDeclareTargetConstruct &x) { 961 const auto &dir{std::get<parser::Verbatim>(x.t)}; 962 PushContext(dir.source, llvm::omp::Directive::OMPD_declare_target); 963 const auto &spec{std::get<parser::OmpDeclareTargetSpecifier>(x.t)}; 964 if (std::holds_alternative<parser::OmpDeclareTargetWithClause>(spec.u)) { 965 SetClauseSets(llvm::omp::Directive::OMPD_declare_target); 966 } 967 } 968 969 void OmpStructureChecker::Leave(const parser::OpenMPDeclareTargetConstruct &x) { 970 const auto &dir{std::get<parser::Verbatim>(x.t)}; 971 const auto &spec{std::get<parser::OmpDeclareTargetSpecifier>(x.t)}; 972 if (const auto *objectList{parser::Unwrap<parser::OmpObjectList>(spec.u)}) { 973 CheckIsVarPartOfAnotherVar(dir.source, *objectList); 974 CheckThreadprivateOrDeclareTargetVar(*objectList); 975 } else if (const auto *clauseList{ 976 parser::Unwrap<parser::OmpClauseList>(spec.u)}) { 977 for (const auto &clause : clauseList->v) { 978 if (const auto *toClause{std::get_if<parser::OmpClause::To>(&clause.u)}) { 979 CheckIsVarPartOfAnotherVar(dir.source, toClause->v); 980 CheckThreadprivateOrDeclareTargetVar(toClause->v); 981 } else if (const auto *linkClause{ 982 std::get_if<parser::OmpClause::Link>(&clause.u)}) { 983 CheckIsVarPartOfAnotherVar(dir.source, linkClause->v); 984 CheckThreadprivateOrDeclareTargetVar(linkClause->v); 985 } 986 } 987 } 988 dirContext_.pop_back(); 989 } 990 991 void OmpStructureChecker::Enter(const parser::OpenMPExecutableAllocate &x) { 992 isPredefinedAllocator = true; 993 const auto &dir{std::get<parser::Verbatim>(x.t)}; 994 const auto &objectList{std::get<std::optional<parser::OmpObjectList>>(x.t)}; 995 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate); 996 if (objectList) { 997 CheckIsVarPartOfAnotherVar(dir.source, *objectList); 998 } 999 } 1000 1001 void OmpStructureChecker::Leave(const parser::OpenMPExecutableAllocate &x) { 1002 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1003 const auto &objectList{std::get<std::optional<parser::OmpObjectList>>(x.t)}; 1004 if (objectList) 1005 CheckPredefinedAllocatorRestriction(dir.source, *objectList); 1006 dirContext_.pop_back(); 1007 } 1008 1009 void OmpStructureChecker::CheckBarrierNesting( 1010 const parser::OpenMPSimpleStandaloneConstruct &x) { 1011 // A barrier region may not be `closely nested` inside a worksharing, loop, 1012 // task, taskloop, critical, ordered, atomic, or master region. 1013 // TODO: Expand the check to include `LOOP` construct as well when it is 1014 // supported. 1015 if (GetContext().directive == llvm::omp::Directive::OMPD_barrier) { 1016 if (IsCloselyNestedRegion(llvm::omp::nestedBarrierErrSet)) { 1017 context_.Say(parser::FindSourceLocation(x), 1018 "`BARRIER` region may not be closely nested inside of `WORKSHARING`, " 1019 "`LOOP`, `TASK`, `TASKLOOP`," 1020 "`CRITICAL`, `ORDERED`, `ATOMIC` or `MASTER` region."_err_en_US); 1021 } 1022 } 1023 } 1024 1025 void OmpStructureChecker::ChecksOnOrderedAsStandalone() { 1026 if (FindClause(llvm::omp::Clause::OMPC_threads) || 1027 FindClause(llvm::omp::Clause::OMPC_simd)) { 1028 context_.Say(GetContext().clauseSource, 1029 "THREADS, SIMD clauses are not allowed when ORDERED construct is a " 1030 "standalone construct with no ORDERED region"_err_en_US); 1031 } 1032 1033 bool isSinkPresent{false}; 1034 int dependSourceCount{0}; 1035 auto clauseAll = FindClauses(llvm::omp::Clause::OMPC_depend); 1036 for (auto itr = clauseAll.first; itr != clauseAll.second; ++itr) { 1037 const auto &dependClause{ 1038 std::get<parser::OmpClause::Depend>(itr->second->u)}; 1039 if (std::get_if<parser::OmpDependClause::Source>(&dependClause.v.u)) { 1040 dependSourceCount++; 1041 if (isSinkPresent) { 1042 context_.Say(itr->second->source, 1043 "DEPEND(SOURCE) is not allowed when DEPEND(SINK: vec) is present " 1044 "on ORDERED directive"_err_en_US); 1045 } 1046 if (dependSourceCount > 1) { 1047 context_.Say(itr->second->source, 1048 "At most one DEPEND(SOURCE) clause can appear on the ORDERED " 1049 "directive"_err_en_US); 1050 } 1051 } else if (std::get_if<parser::OmpDependClause::Sink>(&dependClause.v.u)) { 1052 isSinkPresent = true; 1053 if (dependSourceCount > 0) { 1054 context_.Say(itr->second->source, 1055 "DEPEND(SINK: vec) is not allowed when DEPEND(SOURCE) is present " 1056 "on ORDERED directive"_err_en_US); 1057 } 1058 } else { 1059 context_.Say(itr->second->source, 1060 "Only DEPEND(SOURCE) or DEPEND(SINK: vec) are allowed when ORDERED " 1061 "construct is a standalone construct with no ORDERED " 1062 "region"_err_en_US); 1063 } 1064 } 1065 } 1066 1067 void OmpStructureChecker::Enter( 1068 const parser::OpenMPSimpleStandaloneConstruct &x) { 1069 const auto &dir{std::get<parser::OmpSimpleStandaloneDirective>(x.t)}; 1070 PushContextAndClauseSets(dir.source, dir.v); 1071 CheckBarrierNesting(x); 1072 } 1073 1074 void OmpStructureChecker::Leave( 1075 const parser::OpenMPSimpleStandaloneConstruct &) { 1076 switch (GetContext().directive) { 1077 case llvm::omp::Directive::OMPD_ordered: 1078 // [5.1] 2.19.9 Ordered Construct Restriction 1079 ChecksOnOrderedAsStandalone(); 1080 break; 1081 default: 1082 break; 1083 } 1084 dirContext_.pop_back(); 1085 } 1086 1087 void OmpStructureChecker::Enter(const parser::OpenMPFlushConstruct &x) { 1088 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1089 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_flush); 1090 } 1091 1092 void OmpStructureChecker::Leave(const parser::OpenMPFlushConstruct &x) { 1093 if (FindClause(llvm::omp::Clause::OMPC_acquire) || 1094 FindClause(llvm::omp::Clause::OMPC_release) || 1095 FindClause(llvm::omp::Clause::OMPC_acq_rel)) { 1096 if (const auto &flushList{ 1097 std::get<std::optional<parser::OmpObjectList>>(x.t)}) { 1098 context_.Say(parser::FindSourceLocation(flushList), 1099 "If memory-order-clause is RELEASE, ACQUIRE, or ACQ_REL, list items " 1100 "must not be specified on the FLUSH directive"_err_en_US); 1101 } 1102 } 1103 dirContext_.pop_back(); 1104 } 1105 1106 void OmpStructureChecker::Enter(const parser::OpenMPCancelConstruct &x) { 1107 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1108 const auto &type{std::get<parser::OmpCancelType>(x.t)}; 1109 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_cancel); 1110 CheckCancellationNest(dir.source, type.v); 1111 } 1112 1113 void OmpStructureChecker::Leave(const parser::OpenMPCancelConstruct &) { 1114 dirContext_.pop_back(); 1115 } 1116 1117 void OmpStructureChecker::Enter(const parser::OpenMPCriticalConstruct &x) { 1118 const auto &dir{std::get<parser::OmpCriticalDirective>(x.t)}; 1119 const auto &endDir{std::get<parser::OmpEndCriticalDirective>(x.t)}; 1120 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_critical); 1121 const auto &block{std::get<parser::Block>(x.t)}; 1122 CheckNoBranching(block, llvm::omp::Directive::OMPD_critical, dir.source); 1123 const auto &dirName{std::get<std::optional<parser::Name>>(dir.t)}; 1124 const auto &endDirName{std::get<std::optional<parser::Name>>(endDir.t)}; 1125 const auto &ompClause{std::get<parser::OmpClauseList>(dir.t)}; 1126 if (dirName && endDirName && 1127 dirName->ToString().compare(endDirName->ToString())) { 1128 context_ 1129 .Say(endDirName->source, 1130 parser::MessageFormattedText{ 1131 "CRITICAL directive names do not match"_err_en_US}) 1132 .Attach(dirName->source, "should be "_en_US); 1133 } else if (dirName && !endDirName) { 1134 context_ 1135 .Say(dirName->source, 1136 parser::MessageFormattedText{ 1137 "CRITICAL directive names do not match"_err_en_US}) 1138 .Attach(dirName->source, "should be NULL"_en_US); 1139 } else if (!dirName && endDirName) { 1140 context_ 1141 .Say(endDirName->source, 1142 parser::MessageFormattedText{ 1143 "CRITICAL directive names do not match"_err_en_US}) 1144 .Attach(endDirName->source, "should be NULL"_en_US); 1145 } 1146 if (!dirName && !ompClause.source.empty() && 1147 ompClause.source.NULTerminatedToString() != "hint(omp_sync_hint_none)") { 1148 context_.Say(dir.source, 1149 parser::MessageFormattedText{ 1150 "Hint clause other than omp_sync_hint_none cannot be specified for an unnamed CRITICAL directive"_err_en_US}); 1151 } 1152 } 1153 1154 void OmpStructureChecker::Leave(const parser::OpenMPCriticalConstruct &) { 1155 dirContext_.pop_back(); 1156 } 1157 1158 void OmpStructureChecker::Enter( 1159 const parser::OpenMPCancellationPointConstruct &x) { 1160 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1161 const auto &type{std::get<parser::OmpCancelType>(x.t)}; 1162 PushContextAndClauseSets( 1163 dir.source, llvm::omp::Directive::OMPD_cancellation_point); 1164 CheckCancellationNest(dir.source, type.v); 1165 } 1166 1167 void OmpStructureChecker::Leave( 1168 const parser::OpenMPCancellationPointConstruct &) { 1169 dirContext_.pop_back(); 1170 } 1171 1172 void OmpStructureChecker::CheckCancellationNest( 1173 const parser::CharBlock &source, const parser::OmpCancelType::Type &type) { 1174 if (CurrentDirectiveIsNested()) { 1175 // If construct-type-clause is taskgroup, the cancellation construct must be 1176 // closely nested inside a task or a taskloop construct and the cancellation 1177 // region must be closely nested inside a taskgroup region. If 1178 // construct-type-clause is sections, the cancellation construct must be 1179 // closely nested inside a sections or section construct. Otherwise, the 1180 // cancellation construct must be closely nested inside an OpenMP construct 1181 // that matches the type specified in construct-type-clause of the 1182 // cancellation construct. 1183 1184 OmpDirectiveSet allowedTaskgroupSet{ 1185 llvm::omp::Directive::OMPD_task, llvm::omp::Directive::OMPD_taskloop}; 1186 OmpDirectiveSet allowedSectionsSet{llvm::omp::Directive::OMPD_sections, 1187 llvm::omp::Directive::OMPD_parallel_sections}; 1188 OmpDirectiveSet allowedDoSet{llvm::omp::Directive::OMPD_do, 1189 llvm::omp::Directive::OMPD_distribute_parallel_do, 1190 llvm::omp::Directive::OMPD_parallel_do, 1191 llvm::omp::Directive::OMPD_target_parallel_do, 1192 llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do, 1193 llvm::omp::Directive::OMPD_teams_distribute_parallel_do}; 1194 OmpDirectiveSet allowedParallelSet{llvm::omp::Directive::OMPD_parallel, 1195 llvm::omp::Directive::OMPD_target_parallel}; 1196 1197 bool eligibleCancellation{false}; 1198 switch (type) { 1199 case parser::OmpCancelType::Type::Taskgroup: 1200 if (allowedTaskgroupSet.test(GetContextParent().directive)) { 1201 eligibleCancellation = true; 1202 if (dirContext_.size() >= 3) { 1203 // Check if the cancellation region is closely nested inside a 1204 // taskgroup region when there are more than two levels of directives 1205 // in the directive context stack. 1206 if (GetContextParent().directive == llvm::omp::Directive::OMPD_task || 1207 FindClauseParent(llvm::omp::Clause::OMPC_nogroup)) { 1208 for (int i = dirContext_.size() - 3; i >= 0; i--) { 1209 if (dirContext_[i].directive == 1210 llvm::omp::Directive::OMPD_taskgroup) { 1211 break; 1212 } 1213 if (allowedParallelSet.test(dirContext_[i].directive)) { 1214 eligibleCancellation = false; 1215 break; 1216 } 1217 } 1218 } 1219 } 1220 } 1221 if (!eligibleCancellation) { 1222 context_.Say(source, 1223 "With %s clause, %s construct must be closely nested inside TASK " 1224 "or TASKLOOP construct and %s region must be closely nested inside " 1225 "TASKGROUP region"_err_en_US, 1226 parser::ToUpperCaseLetters( 1227 parser::OmpCancelType::EnumToString(type)), 1228 ContextDirectiveAsFortran(), ContextDirectiveAsFortran()); 1229 } 1230 return; 1231 case parser::OmpCancelType::Type::Sections: 1232 if (allowedSectionsSet.test(GetContextParent().directive)) { 1233 eligibleCancellation = true; 1234 } 1235 break; 1236 case Fortran::parser::OmpCancelType::Type::Do: 1237 if (allowedDoSet.test(GetContextParent().directive)) { 1238 eligibleCancellation = true; 1239 } 1240 break; 1241 case parser::OmpCancelType::Type::Parallel: 1242 if (allowedParallelSet.test(GetContextParent().directive)) { 1243 eligibleCancellation = true; 1244 } 1245 break; 1246 } 1247 if (!eligibleCancellation) { 1248 context_.Say(source, 1249 "With %s clause, %s construct cannot be closely nested inside %s " 1250 "construct"_err_en_US, 1251 parser::ToUpperCaseLetters(parser::OmpCancelType::EnumToString(type)), 1252 ContextDirectiveAsFortran(), 1253 parser::ToUpperCaseLetters( 1254 getDirectiveName(GetContextParent().directive).str())); 1255 } 1256 } else { 1257 // The cancellation directive cannot be orphaned. 1258 switch (type) { 1259 case parser::OmpCancelType::Type::Taskgroup: 1260 context_.Say(source, 1261 "%s %s directive is not closely nested inside " 1262 "TASK or TASKLOOP"_err_en_US, 1263 ContextDirectiveAsFortran(), 1264 parser::ToUpperCaseLetters( 1265 parser::OmpCancelType::EnumToString(type))); 1266 break; 1267 case parser::OmpCancelType::Type::Sections: 1268 context_.Say(source, 1269 "%s %s directive is not closely nested inside " 1270 "SECTION or SECTIONS"_err_en_US, 1271 ContextDirectiveAsFortran(), 1272 parser::ToUpperCaseLetters( 1273 parser::OmpCancelType::EnumToString(type))); 1274 break; 1275 case Fortran::parser::OmpCancelType::Type::Do: 1276 context_.Say(source, 1277 "%s %s directive is not closely nested inside " 1278 "the construct that matches the DO clause type"_err_en_US, 1279 ContextDirectiveAsFortran(), 1280 parser::ToUpperCaseLetters( 1281 parser::OmpCancelType::EnumToString(type))); 1282 break; 1283 case parser::OmpCancelType::Type::Parallel: 1284 context_.Say(source, 1285 "%s %s directive is not closely nested inside " 1286 "the construct that matches the PARALLEL clause type"_err_en_US, 1287 ContextDirectiveAsFortran(), 1288 parser::ToUpperCaseLetters( 1289 parser::OmpCancelType::EnumToString(type))); 1290 break; 1291 } 1292 } 1293 } 1294 1295 void OmpStructureChecker::Enter(const parser::OmpEndBlockDirective &x) { 1296 const auto &dir{std::get<parser::OmpBlockDirective>(x.t)}; 1297 ResetPartialContext(dir.source); 1298 switch (dir.v) { 1299 // 2.7.3 end-single-clause -> copyprivate-clause | 1300 // nowait-clause 1301 case llvm::omp::Directive::OMPD_single: 1302 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_end_single); 1303 break; 1304 // 2.7.4 end-workshare -> END WORKSHARE [nowait-clause] 1305 case llvm::omp::Directive::OMPD_workshare: 1306 PushContextAndClauseSets( 1307 dir.source, llvm::omp::Directive::OMPD_end_workshare); 1308 break; 1309 default: 1310 // no clauses are allowed 1311 break; 1312 } 1313 } 1314 1315 // TODO: Verify the popping of dirContext requirement after nowait 1316 // implementation, as there is an implicit barrier at the end of the worksharing 1317 // constructs unless a nowait clause is specified. Only OMPD_end_single and 1318 // end_workshareare popped as they are pushed while entering the 1319 // EndBlockDirective. 1320 void OmpStructureChecker::Leave(const parser::OmpEndBlockDirective &x) { 1321 if ((GetContext().directive == llvm::omp::Directive::OMPD_end_single) || 1322 (GetContext().directive == llvm::omp::Directive::OMPD_end_workshare)) { 1323 dirContext_.pop_back(); 1324 } 1325 } 1326 1327 template <typename T, typename D> 1328 bool OmpStructureChecker::IsOperatorValid(const T &node, const D &variable) { 1329 using AllowedBinaryOperators = 1330 std::variant<parser::Expr::Add, parser::Expr::Multiply, 1331 parser::Expr::Subtract, parser::Expr::Divide, parser::Expr::AND, 1332 parser::Expr::OR, parser::Expr::EQV, parser::Expr::NEQV>; 1333 using BinaryOperators = std::variant<parser::Expr::Add, 1334 parser::Expr::Multiply, parser::Expr::Subtract, parser::Expr::Divide, 1335 parser::Expr::AND, parser::Expr::OR, parser::Expr::EQV, 1336 parser::Expr::NEQV, parser::Expr::Power, parser::Expr::Concat, 1337 parser::Expr::LT, parser::Expr::LE, parser::Expr::EQ, parser::Expr::NE, 1338 parser::Expr::GE, parser::Expr::GT>; 1339 1340 if constexpr (common::HasMember<T, BinaryOperators>) { 1341 const auto &variableName{variable.GetSource().ToString()}; 1342 const auto &exprLeft{std::get<0>(node.t)}; 1343 const auto &exprRight{std::get<1>(node.t)}; 1344 if ((exprLeft.value().source.ToString() != variableName) && 1345 (exprRight.value().source.ToString() != variableName)) { 1346 context_.Say(variable.GetSource(), 1347 "Atomic update variable '%s' not found in the RHS of the assignment statement in an ATOMIC (UPDATE) construct"_err_en_US, 1348 variableName); 1349 } 1350 return common::HasMember<T, AllowedBinaryOperators>; 1351 } 1352 return true; 1353 } 1354 1355 void OmpStructureChecker::CheckAtomicUpdateAssignmentStmt( 1356 const parser::AssignmentStmt &assignment) { 1357 const auto &expr{std::get<parser::Expr>(assignment.t)}; 1358 const auto &var{std::get<parser::Variable>(assignment.t)}; 1359 std::visit( 1360 common::visitors{ 1361 [&](const common::Indirection<parser::FunctionReference> &x) { 1362 const auto &procedureDesignator{ 1363 std::get<parser::ProcedureDesignator>(x.value().v.t)}; 1364 const parser::Name *name{ 1365 std::get_if<parser::Name>(&procedureDesignator.u)}; 1366 if (name && 1367 !(name->source == "max" || name->source == "min" || 1368 name->source == "iand" || name->source == "ior" || 1369 name->source == "ieor")) { 1370 context_.Say(expr.source, 1371 "Invalid intrinsic procedure name in OpenMP ATOMIC (UPDATE) statement"_err_en_US); 1372 } else if (name) { 1373 bool foundMatch{false}; 1374 if (auto varDesignatorIndirection = 1375 std::get_if<Fortran::common::Indirection< 1376 Fortran::parser::Designator>>(&var.u)) { 1377 const auto &varDesignator = varDesignatorIndirection->value(); 1378 if (const auto *dataRef = std::get_if<Fortran::parser::DataRef>( 1379 &varDesignator.u)) { 1380 if (const auto *name = 1381 std::get_if<Fortran::parser::Name>(&dataRef->u)) { 1382 const auto &varSymbol = *name->symbol; 1383 if (const auto *e{GetExpr(expr)}) { 1384 for (const Symbol &symbol : 1385 evaluate::CollectSymbols(*e)) { 1386 if (symbol == varSymbol) { 1387 foundMatch = true; 1388 break; 1389 } 1390 } 1391 } 1392 } 1393 } 1394 } 1395 if (!foundMatch) { 1396 context_.Say(expr.source, 1397 "Atomic update variable '%s' not found in the argument list of intrinsic procedure"_err_en_US, 1398 var.GetSource().ToString()); 1399 } 1400 } 1401 }, 1402 [&](const auto &x) { 1403 if (!IsOperatorValid(x, var)) { 1404 context_.Say(expr.source, 1405 "Invalid operator in OpenMP ATOMIC (UPDATE) statement"_err_en_US); 1406 } 1407 }, 1408 }, 1409 expr.u); 1410 } 1411 1412 void OmpStructureChecker::CheckAtomicMemoryOrderClause( 1413 const parser::OmpAtomicClauseList &clauseList) { 1414 int numMemoryOrderClause = 0; 1415 for (const auto &clause : clauseList.v) { 1416 if (std::get_if<Fortran::parser::OmpMemoryOrderClause>(&clause.u)) { 1417 numMemoryOrderClause++; 1418 if (numMemoryOrderClause > 1) { 1419 context_.Say(clause.source, 1420 "More than one memory order clause not allowed on OpenMP Atomic construct"_err_en_US); 1421 return; 1422 } 1423 } 1424 } 1425 } 1426 1427 void OmpStructureChecker::CheckAtomicMemoryOrderClause( 1428 const parser::OmpAtomicClauseList &leftHandClauseList, 1429 const parser::OmpAtomicClauseList &rightHandClauseList) { 1430 int numMemoryOrderClause = 0; 1431 for (const auto &clause : leftHandClauseList.v) { 1432 if (std::get_if<Fortran::parser::OmpMemoryOrderClause>(&clause.u)) { 1433 numMemoryOrderClause++; 1434 if (numMemoryOrderClause > 1) { 1435 context_.Say(clause.source, 1436 "More than one memory order clause not allowed on OpenMP Atomic construct"_err_en_US); 1437 return; 1438 } 1439 } 1440 } 1441 for (const auto &clause : rightHandClauseList.v) { 1442 if (std::get_if<Fortran::parser::OmpMemoryOrderClause>(&clause.u)) { 1443 numMemoryOrderClause++; 1444 if (numMemoryOrderClause > 1) { 1445 context_.Say(clause.source, 1446 "More than one memory order clause not allowed on OpenMP Atomic construct"_err_en_US); 1447 return; 1448 } 1449 } 1450 } 1451 } 1452 1453 void OmpStructureChecker::Enter(const parser::OpenMPAtomicConstruct &x) { 1454 std::visit( 1455 common::visitors{ 1456 [&](const parser::OmpAtomic &atomicConstruct) { 1457 const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)}; 1458 PushContextAndClauseSets( 1459 dir.source, llvm::omp::Directive::OMPD_atomic); 1460 CheckAtomicUpdateAssignmentStmt( 1461 std::get<parser::Statement<parser::AssignmentStmt>>( 1462 atomicConstruct.t) 1463 .statement); 1464 CheckAtomicMemoryOrderClause( 1465 std::get<parser::OmpAtomicClauseList>(atomicConstruct.t)); 1466 }, 1467 [&](const parser::OmpAtomicUpdate &atomicConstruct) { 1468 const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)}; 1469 PushContextAndClauseSets( 1470 dir.source, llvm::omp::Directive::OMPD_atomic); 1471 CheckAtomicUpdateAssignmentStmt( 1472 std::get<parser::Statement<parser::AssignmentStmt>>( 1473 atomicConstruct.t) 1474 .statement); 1475 CheckAtomicMemoryOrderClause( 1476 std::get<0>(atomicConstruct.t), std::get<2>(atomicConstruct.t)); 1477 }, 1478 [&](const auto &atomicConstruct) { 1479 const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)}; 1480 PushContextAndClauseSets( 1481 dir.source, llvm::omp::Directive::OMPD_atomic); 1482 CheckAtomicMemoryOrderClause( 1483 std::get<0>(atomicConstruct.t), std::get<2>(atomicConstruct.t)); 1484 }, 1485 }, 1486 x.u); 1487 } 1488 1489 void OmpStructureChecker::Leave(const parser::OpenMPAtomicConstruct &) { 1490 dirContext_.pop_back(); 1491 } 1492 1493 // Clauses 1494 // Mainly categorized as 1495 // 1. Checks on 'OmpClauseList' from 'parse-tree.h'. 1496 // 2. Checks on clauses which fall under 'struct OmpClause' from parse-tree.h. 1497 // 3. Checks on clauses which are not in 'struct OmpClause' from parse-tree.h. 1498 1499 void OmpStructureChecker::Leave(const parser::OmpClauseList &) { 1500 // 2.7.1 Loop Construct Restriction 1501 if (llvm::omp::doSet.test(GetContext().directive)) { 1502 if (auto *clause{FindClause(llvm::omp::Clause::OMPC_schedule)}) { 1503 // only one schedule clause is allowed 1504 const auto &schedClause{std::get<parser::OmpClause::Schedule>(clause->u)}; 1505 if (ScheduleModifierHasType(schedClause.v, 1506 parser::OmpScheduleModifierType::ModType::Nonmonotonic)) { 1507 if (FindClause(llvm::omp::Clause::OMPC_ordered)) { 1508 context_.Say(clause->source, 1509 "The NONMONOTONIC modifier cannot be specified " 1510 "if an ORDERED clause is specified"_err_en_US); 1511 } 1512 if (ScheduleModifierHasType(schedClause.v, 1513 parser::OmpScheduleModifierType::ModType::Monotonic)) { 1514 context_.Say(clause->source, 1515 "The MONOTONIC and NONMONOTONIC modifiers " 1516 "cannot be both specified"_err_en_US); 1517 } 1518 } 1519 } 1520 1521 if (auto *clause{FindClause(llvm::omp::Clause::OMPC_ordered)}) { 1522 // only one ordered clause is allowed 1523 const auto &orderedClause{ 1524 std::get<parser::OmpClause::Ordered>(clause->u)}; 1525 1526 if (orderedClause.v) { 1527 CheckNotAllowedIfClause( 1528 llvm::omp::Clause::OMPC_ordered, {llvm::omp::Clause::OMPC_linear}); 1529 1530 if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_collapse)}) { 1531 const auto &collapseClause{ 1532 std::get<parser::OmpClause::Collapse>(clause2->u)}; 1533 // ordered and collapse both have parameters 1534 if (const auto orderedValue{GetIntValue(orderedClause.v)}) { 1535 if (const auto collapseValue{GetIntValue(collapseClause.v)}) { 1536 if (*orderedValue > 0 && *orderedValue < *collapseValue) { 1537 context_.Say(clause->source, 1538 "The parameter of the ORDERED clause must be " 1539 "greater than or equal to " 1540 "the parameter of the COLLAPSE clause"_err_en_US); 1541 } 1542 } 1543 } 1544 } 1545 } 1546 1547 // TODO: ordered region binding check (requires nesting implementation) 1548 } 1549 } // doSet 1550 1551 // 2.8.1 Simd Construct Restriction 1552 if (llvm::omp::simdSet.test(GetContext().directive)) { 1553 if (auto *clause{FindClause(llvm::omp::Clause::OMPC_simdlen)}) { 1554 if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_safelen)}) { 1555 const auto &simdlenClause{ 1556 std::get<parser::OmpClause::Simdlen>(clause->u)}; 1557 const auto &safelenClause{ 1558 std::get<parser::OmpClause::Safelen>(clause2->u)}; 1559 // simdlen and safelen both have parameters 1560 if (const auto simdlenValue{GetIntValue(simdlenClause.v)}) { 1561 if (const auto safelenValue{GetIntValue(safelenClause.v)}) { 1562 if (*safelenValue > 0 && *simdlenValue > *safelenValue) { 1563 context_.Say(clause->source, 1564 "The parameter of the SIMDLEN clause must be less than or " 1565 "equal to the parameter of the SAFELEN clause"_err_en_US); 1566 } 1567 } 1568 } 1569 } 1570 } 1571 // A list-item cannot appear in more than one aligned clause 1572 semantics::UnorderedSymbolSet alignedVars; 1573 auto clauseAll = FindClauses(llvm::omp::Clause::OMPC_aligned); 1574 for (auto itr = clauseAll.first; itr != clauseAll.second; ++itr) { 1575 const auto &alignedClause{ 1576 std::get<parser::OmpClause::Aligned>(itr->second->u)}; 1577 const auto &alignedNameList{ 1578 std::get<std::list<parser::Name>>(alignedClause.v.t)}; 1579 for (auto const &var : alignedNameList) { 1580 if (alignedVars.count(*(var.symbol)) == 1) { 1581 context_.Say(itr->second->source, 1582 "List item '%s' present at multiple ALIGNED clauses"_err_en_US, 1583 var.ToString()); 1584 break; 1585 } 1586 alignedVars.insert(*(var.symbol)); 1587 } 1588 } 1589 } // SIMD 1590 1591 // 2.7.3 Single Construct Restriction 1592 if (GetContext().directive == llvm::omp::Directive::OMPD_end_single) { 1593 CheckNotAllowedIfClause( 1594 llvm::omp::Clause::OMPC_copyprivate, {llvm::omp::Clause::OMPC_nowait}); 1595 } 1596 1597 auto testThreadprivateVarErr = [&](Symbol sym, parser::Name name, 1598 llvmOmpClause clauseTy) { 1599 if (sym.test(Symbol::Flag::OmpThreadprivate)) 1600 context_.Say(name.source, 1601 "A THREADPRIVATE variable cannot be in %s clause"_err_en_US, 1602 parser::ToUpperCaseLetters(getClauseName(clauseTy).str())); 1603 }; 1604 1605 // [5.1] 2.21.2 Threadprivate Directive Restriction 1606 OmpClauseSet threadprivateAllowedSet{llvm::omp::Clause::OMPC_copyin, 1607 llvm::omp::Clause::OMPC_copyprivate, llvm::omp::Clause::OMPC_schedule, 1608 llvm::omp::Clause::OMPC_num_threads, llvm::omp::Clause::OMPC_thread_limit, 1609 llvm::omp::Clause::OMPC_if}; 1610 for (auto it : GetContext().clauseInfo) { 1611 llvmOmpClause type = it.first; 1612 const auto *clause = it.second; 1613 if (!threadprivateAllowedSet.test(type)) { 1614 if (const auto *objList{GetOmpObjectList(*clause)}) { 1615 for (const auto &ompObject : objList->v) { 1616 std::visit( 1617 common::visitors{ 1618 [&](const parser::Designator &) { 1619 if (const auto *name{ 1620 parser::Unwrap<parser::Name>(ompObject)}) 1621 testThreadprivateVarErr( 1622 name->symbol->GetUltimate(), *name, type); 1623 }, 1624 [&](const parser::Name &name) { 1625 if (name.symbol) { 1626 for (const auto &mem : 1627 name.symbol->get<CommonBlockDetails>().objects()) { 1628 testThreadprivateVarErr(mem->GetUltimate(), name, type); 1629 break; 1630 } 1631 } 1632 }, 1633 }, 1634 ompObject.u); 1635 } 1636 } 1637 } 1638 } 1639 1640 CheckRequireAtLeastOneOf(); 1641 } 1642 1643 void OmpStructureChecker::Enter(const parser::OmpClause &x) { 1644 SetContextClause(x); 1645 } 1646 1647 // Following clauses do not have a separate node in parse-tree.h. 1648 CHECK_SIMPLE_CLAUSE(AcqRel, OMPC_acq_rel) 1649 CHECK_SIMPLE_CLAUSE(Acquire, OMPC_acquire) 1650 CHECK_SIMPLE_CLAUSE(AtomicDefaultMemOrder, OMPC_atomic_default_mem_order) 1651 CHECK_SIMPLE_CLAUSE(Affinity, OMPC_affinity) 1652 CHECK_SIMPLE_CLAUSE(Allocate, OMPC_allocate) 1653 CHECK_SIMPLE_CLAUSE(Capture, OMPC_capture) 1654 CHECK_SIMPLE_CLAUSE(Copyin, OMPC_copyin) 1655 CHECK_SIMPLE_CLAUSE(Default, OMPC_default) 1656 CHECK_SIMPLE_CLAUSE(Depobj, OMPC_depobj) 1657 CHECK_SIMPLE_CLAUSE(Destroy, OMPC_destroy) 1658 CHECK_SIMPLE_CLAUSE(Detach, OMPC_detach) 1659 CHECK_SIMPLE_CLAUSE(Device, OMPC_device) 1660 CHECK_SIMPLE_CLAUSE(DeviceType, OMPC_device_type) 1661 CHECK_SIMPLE_CLAUSE(DistSchedule, OMPC_dist_schedule) 1662 CHECK_SIMPLE_CLAUSE(DynamicAllocators, OMPC_dynamic_allocators) 1663 CHECK_SIMPLE_CLAUSE(Exclusive, OMPC_exclusive) 1664 CHECK_SIMPLE_CLAUSE(Final, OMPC_final) 1665 CHECK_SIMPLE_CLAUSE(Flush, OMPC_flush) 1666 CHECK_SIMPLE_CLAUSE(From, OMPC_from) 1667 CHECK_SIMPLE_CLAUSE(Full, OMPC_full) 1668 CHECK_SIMPLE_CLAUSE(Hint, OMPC_hint) 1669 CHECK_SIMPLE_CLAUSE(InReduction, OMPC_in_reduction) 1670 CHECK_SIMPLE_CLAUSE(Inclusive, OMPC_inclusive) 1671 CHECK_SIMPLE_CLAUSE(Match, OMPC_match) 1672 CHECK_SIMPLE_CLAUSE(Nontemporal, OMPC_nontemporal) 1673 CHECK_SIMPLE_CLAUSE(Order, OMPC_order) 1674 CHECK_SIMPLE_CLAUSE(Read, OMPC_read) 1675 CHECK_SIMPLE_CLAUSE(ReverseOffload, OMPC_reverse_offload) 1676 CHECK_SIMPLE_CLAUSE(Threadprivate, OMPC_threadprivate) 1677 CHECK_SIMPLE_CLAUSE(Threads, OMPC_threads) 1678 CHECK_SIMPLE_CLAUSE(Inbranch, OMPC_inbranch) 1679 CHECK_SIMPLE_CLAUSE(IsDevicePtr, OMPC_is_device_ptr) 1680 CHECK_SIMPLE_CLAUSE(Link, OMPC_link) 1681 CHECK_SIMPLE_CLAUSE(Indirect, OMPC_indirect) 1682 CHECK_SIMPLE_CLAUSE(Mergeable, OMPC_mergeable) 1683 CHECK_SIMPLE_CLAUSE(Nogroup, OMPC_nogroup) 1684 CHECK_SIMPLE_CLAUSE(Notinbranch, OMPC_notinbranch) 1685 CHECK_SIMPLE_CLAUSE(Nowait, OMPC_nowait) 1686 CHECK_SIMPLE_CLAUSE(Partial, OMPC_partial) 1687 CHECK_SIMPLE_CLAUSE(ProcBind, OMPC_proc_bind) 1688 CHECK_SIMPLE_CLAUSE(Release, OMPC_release) 1689 CHECK_SIMPLE_CLAUSE(Relaxed, OMPC_relaxed) 1690 CHECK_SIMPLE_CLAUSE(SeqCst, OMPC_seq_cst) 1691 CHECK_SIMPLE_CLAUSE(Simd, OMPC_simd) 1692 CHECK_SIMPLE_CLAUSE(Sizes, OMPC_sizes) 1693 CHECK_SIMPLE_CLAUSE(TaskReduction, OMPC_task_reduction) 1694 CHECK_SIMPLE_CLAUSE(To, OMPC_to) 1695 CHECK_SIMPLE_CLAUSE(UnifiedAddress, OMPC_unified_address) 1696 CHECK_SIMPLE_CLAUSE(UnifiedSharedMemory, OMPC_unified_shared_memory) 1697 CHECK_SIMPLE_CLAUSE(Uniform, OMPC_uniform) 1698 CHECK_SIMPLE_CLAUSE(Unknown, OMPC_unknown) 1699 CHECK_SIMPLE_CLAUSE(Untied, OMPC_untied) 1700 CHECK_SIMPLE_CLAUSE(UseDevicePtr, OMPC_use_device_ptr) 1701 CHECK_SIMPLE_CLAUSE(UsesAllocators, OMPC_uses_allocators) 1702 CHECK_SIMPLE_CLAUSE(Update, OMPC_update) 1703 CHECK_SIMPLE_CLAUSE(UseDeviceAddr, OMPC_use_device_addr) 1704 CHECK_SIMPLE_CLAUSE(Write, OMPC_write) 1705 CHECK_SIMPLE_CLAUSE(Init, OMPC_init) 1706 CHECK_SIMPLE_CLAUSE(Use, OMPC_use) 1707 CHECK_SIMPLE_CLAUSE(Novariants, OMPC_novariants) 1708 CHECK_SIMPLE_CLAUSE(Nocontext, OMPC_nocontext) 1709 CHECK_SIMPLE_CLAUSE(Filter, OMPC_filter) 1710 CHECK_SIMPLE_CLAUSE(When, OMPC_when) 1711 CHECK_SIMPLE_CLAUSE(AdjustArgs, OMPC_adjust_args) 1712 CHECK_SIMPLE_CLAUSE(AppendArgs, OMPC_append_args) 1713 CHECK_SIMPLE_CLAUSE(MemoryOrder, OMPC_memory_order) 1714 CHECK_SIMPLE_CLAUSE(Bind, OMPC_bind) 1715 CHECK_SIMPLE_CLAUSE(Align, OMPC_align) 1716 CHECK_SIMPLE_CLAUSE(Compare, OMPC_compare) 1717 1718 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize) 1719 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks) 1720 CHECK_REQ_SCALAR_INT_CLAUSE(NumTeams, OMPC_num_teams) 1721 CHECK_REQ_SCALAR_INT_CLAUSE(NumThreads, OMPC_num_threads) 1722 CHECK_REQ_SCALAR_INT_CLAUSE(Priority, OMPC_priority) 1723 CHECK_REQ_SCALAR_INT_CLAUSE(ThreadLimit, OMPC_thread_limit) 1724 1725 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Collapse, OMPC_collapse) 1726 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Safelen, OMPC_safelen) 1727 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Simdlen, OMPC_simdlen) 1728 1729 // Restrictions specific to each clause are implemented apart from the 1730 // generalized restrictions. 1731 void OmpStructureChecker::Enter(const parser::OmpClause::Reduction &x) { 1732 CheckAllowed(llvm::omp::Clause::OMPC_reduction); 1733 if (CheckReductionOperators(x)) { 1734 CheckReductionTypeList(x); 1735 } 1736 } 1737 bool OmpStructureChecker::CheckReductionOperators( 1738 const parser::OmpClause::Reduction &x) { 1739 1740 const auto &definedOp{std::get<0>(x.v.t)}; 1741 bool ok = false; 1742 std::visit( 1743 common::visitors{ 1744 [&](const parser::DefinedOperator &dOpr) { 1745 const auto &intrinsicOp{ 1746 std::get<parser::DefinedOperator::IntrinsicOperator>(dOpr.u)}; 1747 ok = CheckIntrinsicOperator(intrinsicOp); 1748 }, 1749 [&](const parser::ProcedureDesignator &procD) { 1750 const parser::Name *name{std::get_if<parser::Name>(&procD.u)}; 1751 if (name) { 1752 if (name->source == "max" || name->source == "min" || 1753 name->source == "iand" || name->source == "ior" || 1754 name->source == "ieor") { 1755 ok = true; 1756 } else { 1757 context_.Say(GetContext().clauseSource, 1758 "Invalid reduction identifier in REDUCTION clause."_err_en_US, 1759 ContextDirectiveAsFortran()); 1760 } 1761 } 1762 }, 1763 }, 1764 definedOp.u); 1765 1766 return ok; 1767 } 1768 bool OmpStructureChecker::CheckIntrinsicOperator( 1769 const parser::DefinedOperator::IntrinsicOperator &op) { 1770 1771 switch (op) { 1772 case parser::DefinedOperator::IntrinsicOperator::Add: 1773 case parser::DefinedOperator::IntrinsicOperator::Subtract: 1774 case parser::DefinedOperator::IntrinsicOperator::Multiply: 1775 case parser::DefinedOperator::IntrinsicOperator::AND: 1776 case parser::DefinedOperator::IntrinsicOperator::OR: 1777 case parser::DefinedOperator::IntrinsicOperator::EQV: 1778 case parser::DefinedOperator::IntrinsicOperator::NEQV: 1779 return true; 1780 default: 1781 context_.Say(GetContext().clauseSource, 1782 "Invalid reduction operator in REDUCTION clause."_err_en_US, 1783 ContextDirectiveAsFortran()); 1784 } 1785 return false; 1786 } 1787 1788 void OmpStructureChecker::CheckReductionTypeList( 1789 const parser::OmpClause::Reduction &x) { 1790 const auto &ompObjectList{std::get<parser::OmpObjectList>(x.v.t)}; 1791 CheckIntentInPointerAndDefinable( 1792 ompObjectList, llvm::omp::Clause::OMPC_reduction); 1793 CheckReductionArraySection(ompObjectList); 1794 CheckMultipleAppearanceAcrossContext(ompObjectList); 1795 } 1796 1797 void OmpStructureChecker::CheckIntentInPointerAndDefinable( 1798 const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) { 1799 for (const auto &ompObject : objectList.v) { 1800 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) { 1801 if (const auto *symbol{name->symbol}) { 1802 if (IsPointer(symbol->GetUltimate()) && 1803 IsIntentIn(symbol->GetUltimate())) { 1804 context_.Say(GetContext().clauseSource, 1805 "Pointer '%s' with the INTENT(IN) attribute may not appear " 1806 "in a %s clause"_err_en_US, 1807 symbol->name(), 1808 parser::ToUpperCaseLetters(getClauseName(clause).str())); 1809 } 1810 if (auto msg{ 1811 WhyNotModifiable(*symbol, context_.FindScope(name->source))}) { 1812 context_.Say(GetContext().clauseSource, 1813 "Variable '%s' on the %s clause is not definable"_err_en_US, 1814 symbol->name(), 1815 parser::ToUpperCaseLetters(getClauseName(clause).str())); 1816 } 1817 } 1818 } 1819 } 1820 } 1821 1822 void OmpStructureChecker::CheckReductionArraySection( 1823 const parser::OmpObjectList &ompObjectList) { 1824 for (const auto &ompObject : ompObjectList.v) { 1825 if (const auto *dataRef{parser::Unwrap<parser::DataRef>(ompObject)}) { 1826 if (const auto *arrayElement{ 1827 parser::Unwrap<parser::ArrayElement>(ompObject)}) { 1828 if (arrayElement) { 1829 CheckArraySection(*arrayElement, GetLastName(*dataRef), 1830 llvm::omp::Clause::OMPC_reduction); 1831 } 1832 } 1833 } 1834 } 1835 } 1836 1837 void OmpStructureChecker::CheckMultipleAppearanceAcrossContext( 1838 const parser::OmpObjectList &redObjectList) { 1839 // TODO: Verify the assumption here that the immediately enclosing region is 1840 // the parallel region to which the worksharing construct having reduction 1841 // binds to. 1842 if (auto *enclosingContext{GetEnclosingDirContext()}) { 1843 for (auto it : enclosingContext->clauseInfo) { 1844 llvmOmpClause type = it.first; 1845 const auto *clause = it.second; 1846 if (llvm::omp::privateReductionSet.test(type)) { 1847 if (const auto *objList{GetOmpObjectList(*clause)}) { 1848 for (const auto &ompObject : objList->v) { 1849 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) { 1850 if (const auto *symbol{name->symbol}) { 1851 for (const auto &redOmpObject : redObjectList.v) { 1852 if (const auto *rname{ 1853 parser::Unwrap<parser::Name>(redOmpObject)}) { 1854 if (const auto *rsymbol{rname->symbol}) { 1855 if (rsymbol->name() == symbol->name()) { 1856 context_.Say(GetContext().clauseSource, 1857 "%s variable '%s' is %s in outer context must" 1858 " be shared in the parallel regions to which any" 1859 " of the worksharing regions arising from the " 1860 "worksharing" 1861 " construct bind."_err_en_US, 1862 parser::ToUpperCaseLetters( 1863 getClauseName(llvm::omp::Clause::OMPC_reduction) 1864 .str()), 1865 symbol->name(), 1866 parser::ToUpperCaseLetters( 1867 getClauseName(type).str())); 1868 } 1869 } 1870 } 1871 } 1872 } 1873 } 1874 } 1875 } 1876 } 1877 } 1878 } 1879 } 1880 1881 void OmpStructureChecker::Enter(const parser::OmpClause::Ordered &x) { 1882 CheckAllowed(llvm::omp::Clause::OMPC_ordered); 1883 // the parameter of ordered clause is optional 1884 if (const auto &expr{x.v}) { 1885 RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_ordered, *expr); 1886 // 2.8.3 Loop SIMD Construct Restriction 1887 if (llvm::omp::doSimdSet.test(GetContext().directive)) { 1888 context_.Say(GetContext().clauseSource, 1889 "No ORDERED clause with a parameter can be specified " 1890 "on the %s directive"_err_en_US, 1891 ContextDirectiveAsFortran()); 1892 } 1893 } 1894 } 1895 1896 void OmpStructureChecker::Enter(const parser::OmpClause::Shared &x) { 1897 CheckAllowed(llvm::omp::Clause::OMPC_shared); 1898 CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v); 1899 } 1900 void OmpStructureChecker::Enter(const parser::OmpClause::Private &x) { 1901 CheckAllowed(llvm::omp::Clause::OMPC_private); 1902 CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v); 1903 CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_private); 1904 } 1905 1906 bool OmpStructureChecker::IsDataRefTypeParamInquiry( 1907 const parser::DataRef *dataRef) { 1908 bool dataRefIsTypeParamInquiry{false}; 1909 if (const auto *structComp{ 1910 parser::Unwrap<parser::StructureComponent>(dataRef)}) { 1911 if (const auto *compSymbol{structComp->component.symbol}) { 1912 if (const auto *compSymbolMiscDetails{ 1913 std::get_if<MiscDetails>(&compSymbol->details())}) { 1914 const auto detailsKind = compSymbolMiscDetails->kind(); 1915 dataRefIsTypeParamInquiry = 1916 (detailsKind == MiscDetails::Kind::KindParamInquiry || 1917 detailsKind == MiscDetails::Kind::LenParamInquiry); 1918 } else if (compSymbol->has<TypeParamDetails>()) { 1919 dataRefIsTypeParamInquiry = true; 1920 } 1921 } 1922 } 1923 return dataRefIsTypeParamInquiry; 1924 } 1925 1926 void OmpStructureChecker::CheckIsVarPartOfAnotherVar( 1927 const parser::CharBlock &source, const parser::OmpObjectList &objList) { 1928 OmpDirectiveSet nonPartialVarSet{llvm::omp::Directive::OMPD_allocate, 1929 llvm::omp::Directive::OMPD_threadprivate, 1930 llvm::omp::Directive::OMPD_declare_target}; 1931 for (const auto &ompObject : objList.v) { 1932 std::visit( 1933 common::visitors{ 1934 [&](const parser::Designator &designator) { 1935 if (const auto *dataRef{ 1936 std::get_if<parser::DataRef>(&designator.u)}) { 1937 if (IsDataRefTypeParamInquiry(dataRef)) { 1938 context_.Say(source, 1939 "A type parameter inquiry cannot appear on the %s " 1940 "directive"_err_en_US, 1941 ContextDirectiveAsFortran()); 1942 } else if (parser::Unwrap<parser::StructureComponent>( 1943 ompObject) || 1944 parser::Unwrap<parser::ArrayElement>(ompObject)) { 1945 if (nonPartialVarSet.test(GetContext().directive)) { 1946 context_.Say(source, 1947 "A variable that is part of another variable (as an " 1948 "array or structure element) cannot appear on the %s " 1949 "directive"_err_en_US, 1950 ContextDirectiveAsFortran()); 1951 } else { 1952 context_.Say(source, 1953 "A variable that is part of another variable (as an " 1954 "array or structure element) cannot appear in a " 1955 "PRIVATE or SHARED clause"_err_en_US); 1956 } 1957 } 1958 } 1959 }, 1960 [&](const parser::Name &name) {}, 1961 }, 1962 ompObject.u); 1963 } 1964 } 1965 1966 void OmpStructureChecker::Enter(const parser::OmpClause::Firstprivate &x) { 1967 CheckAllowed(llvm::omp::Clause::OMPC_firstprivate); 1968 CheckIsLoopIvPartOfClause(llvmOmpClause::OMPC_firstprivate, x.v); 1969 1970 SymbolSourceMap currSymbols; 1971 GetSymbolsInObjectList(x.v, currSymbols); 1972 1973 DirectivesClauseTriple dirClauseTriple; 1974 // Check firstprivate variables in worksharing constructs 1975 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do, 1976 std::make_pair( 1977 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet)); 1978 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections, 1979 std::make_pair( 1980 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet)); 1981 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_single, 1982 std::make_pair( 1983 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet)); 1984 // Check firstprivate variables in distribute construct 1985 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute, 1986 std::make_pair( 1987 llvm::omp::Directive::OMPD_teams, llvm::omp::privateReductionSet)); 1988 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute, 1989 std::make_pair(llvm::omp::Directive::OMPD_target_teams, 1990 llvm::omp::privateReductionSet)); 1991 // Check firstprivate variables in task and taskloop constructs 1992 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_task, 1993 std::make_pair(llvm::omp::Directive::OMPD_parallel, 1994 OmpClauseSet{llvm::omp::Clause::OMPC_reduction})); 1995 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_taskloop, 1996 std::make_pair(llvm::omp::Directive::OMPD_parallel, 1997 OmpClauseSet{llvm::omp::Clause::OMPC_reduction})); 1998 1999 CheckPrivateSymbolsInOuterCxt( 2000 currSymbols, dirClauseTriple, llvm::omp::Clause::OMPC_firstprivate); 2001 } 2002 2003 void OmpStructureChecker::CheckIsLoopIvPartOfClause( 2004 llvmOmpClause clause, const parser::OmpObjectList &ompObjectList) { 2005 for (const auto &ompObject : ompObjectList.v) { 2006 if (const parser::Name * name{parser::Unwrap<parser::Name>(ompObject)}) { 2007 if (name->symbol == GetContext().loopIV) { 2008 context_.Say(name->source, 2009 "DO iteration variable %s is not allowed in %s clause."_err_en_US, 2010 name->ToString(), 2011 parser::ToUpperCaseLetters(getClauseName(clause).str())); 2012 } 2013 } 2014 } 2015 } 2016 // Following clauses have a seperate node in parse-tree.h. 2017 // Atomic-clause 2018 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicRead, OMPC_read) 2019 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicWrite, OMPC_write) 2020 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicUpdate, OMPC_update) 2021 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicCapture, OMPC_capture) 2022 2023 void OmpStructureChecker::Leave(const parser::OmpAtomicRead &) { 2024 CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_read, 2025 {llvm::omp::Clause::OMPC_release, llvm::omp::Clause::OMPC_acq_rel}); 2026 } 2027 void OmpStructureChecker::Leave(const parser::OmpAtomicWrite &) { 2028 CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_write, 2029 {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel}); 2030 } 2031 void OmpStructureChecker::Leave(const parser::OmpAtomicUpdate &) { 2032 CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_update, 2033 {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel}); 2034 } 2035 // OmpAtomic node represents atomic directive without atomic-clause. 2036 // atomic-clause - READ,WRITE,UPDATE,CAPTURE. 2037 void OmpStructureChecker::Leave(const parser::OmpAtomic &) { 2038 if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acquire)}) { 2039 context_.Say(clause->source, 2040 "Clause ACQUIRE is not allowed on the ATOMIC directive"_err_en_US); 2041 } 2042 if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acq_rel)}) { 2043 context_.Say(clause->source, 2044 "Clause ACQ_REL is not allowed on the ATOMIC directive"_err_en_US); 2045 } 2046 } 2047 // Restrictions specific to each clause are implemented apart from the 2048 // generalized restrictions. 2049 void OmpStructureChecker::Enter(const parser::OmpClause::Aligned &x) { 2050 CheckAllowed(llvm::omp::Clause::OMPC_aligned); 2051 2052 if (const auto &expr{ 2053 std::get<std::optional<parser::ScalarIntConstantExpr>>(x.v.t)}) { 2054 RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_aligned, *expr); 2055 } 2056 // 2.8.1 TODO: list-item attribute check 2057 } 2058 void OmpStructureChecker::Enter(const parser::OmpClause::Defaultmap &x) { 2059 CheckAllowed(llvm::omp::Clause::OMPC_defaultmap); 2060 using VariableCategory = parser::OmpDefaultmapClause::VariableCategory; 2061 if (!std::get<std::optional<VariableCategory>>(x.v.t)) { 2062 context_.Say(GetContext().clauseSource, 2063 "The argument TOFROM:SCALAR must be specified on the DEFAULTMAP " 2064 "clause"_err_en_US); 2065 } 2066 } 2067 void OmpStructureChecker::Enter(const parser::OmpClause::If &x) { 2068 CheckAllowed(llvm::omp::Clause::OMPC_if); 2069 using dirNameModifier = parser::OmpIfClause::DirectiveNameModifier; 2070 static std::unordered_map<dirNameModifier, OmpDirectiveSet> 2071 dirNameModifierMap{{dirNameModifier::Parallel, llvm::omp::parallelSet}, 2072 {dirNameModifier::Target, llvm::omp::targetSet}, 2073 {dirNameModifier::TargetEnterData, 2074 {llvm::omp::Directive::OMPD_target_enter_data}}, 2075 {dirNameModifier::TargetExitData, 2076 {llvm::omp::Directive::OMPD_target_exit_data}}, 2077 {dirNameModifier::TargetData, 2078 {llvm::omp::Directive::OMPD_target_data}}, 2079 {dirNameModifier::TargetUpdate, 2080 {llvm::omp::Directive::OMPD_target_update}}, 2081 {dirNameModifier::Task, {llvm::omp::Directive::OMPD_task}}, 2082 {dirNameModifier::Taskloop, llvm::omp::taskloopSet}}; 2083 if (const auto &directiveName{ 2084 std::get<std::optional<dirNameModifier>>(x.v.t)}) { 2085 auto search{dirNameModifierMap.find(*directiveName)}; 2086 if (search == dirNameModifierMap.end() || 2087 !search->second.test(GetContext().directive)) { 2088 context_ 2089 .Say(GetContext().clauseSource, 2090 "Unmatched directive name modifier %s on the IF clause"_err_en_US, 2091 parser::ToUpperCaseLetters( 2092 parser::OmpIfClause::EnumToString(*directiveName))) 2093 .Attach( 2094 GetContext().directiveSource, "Cannot apply to directive"_en_US); 2095 } 2096 } 2097 } 2098 2099 void OmpStructureChecker::Enter(const parser::OmpClause::Linear &x) { 2100 CheckAllowed(llvm::omp::Clause::OMPC_linear); 2101 2102 // 2.7 Loop Construct Restriction 2103 if ((llvm::omp::doSet | llvm::omp::simdSet).test(GetContext().directive)) { 2104 if (std::holds_alternative<parser::OmpLinearClause::WithModifier>(x.v.u)) { 2105 context_.Say(GetContext().clauseSource, 2106 "A modifier may not be specified in a LINEAR clause " 2107 "on the %s directive"_err_en_US, 2108 ContextDirectiveAsFortran()); 2109 } 2110 } 2111 } 2112 2113 void OmpStructureChecker::CheckAllowedMapTypes( 2114 const parser::OmpMapType::Type &type, 2115 const std::list<parser::OmpMapType::Type> &allowedMapTypeList) { 2116 const auto found{std::find( 2117 std::begin(allowedMapTypeList), std::end(allowedMapTypeList), type)}; 2118 if (found == std::end(allowedMapTypeList)) { 2119 std::string commaSeperatedMapTypes; 2120 llvm::interleave( 2121 allowedMapTypeList.begin(), allowedMapTypeList.end(), 2122 [&](const parser::OmpMapType::Type &mapType) { 2123 commaSeperatedMapTypes.append(parser::ToUpperCaseLetters( 2124 parser::OmpMapType::EnumToString(mapType))); 2125 }, 2126 [&] { commaSeperatedMapTypes.append(", "); }); 2127 context_.Say(GetContext().clauseSource, 2128 "Only the %s map types are permitted " 2129 "for MAP clauses on the %s directive"_err_en_US, 2130 commaSeperatedMapTypes, ContextDirectiveAsFortran()); 2131 } 2132 } 2133 2134 void OmpStructureChecker::Enter(const parser::OmpClause::Map &x) { 2135 CheckAllowed(llvm::omp::Clause::OMPC_map); 2136 2137 if (const auto &maptype{std::get<std::optional<parser::OmpMapType>>(x.v.t)}) { 2138 using Type = parser::OmpMapType::Type; 2139 const Type &type{std::get<Type>(maptype->t)}; 2140 switch (GetContext().directive) { 2141 case llvm::omp::Directive::OMPD_target: 2142 case llvm::omp::Directive::OMPD_target_teams: 2143 case llvm::omp::Directive::OMPD_target_teams_distribute: 2144 case llvm::omp::Directive::OMPD_target_teams_distribute_simd: 2145 case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do: 2146 case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do_simd: 2147 case llvm::omp::Directive::OMPD_target_data: 2148 CheckAllowedMapTypes( 2149 type, {Type::To, Type::From, Type::Tofrom, Type::Alloc}); 2150 break; 2151 case llvm::omp::Directive::OMPD_target_enter_data: 2152 CheckAllowedMapTypes(type, {Type::To, Type::Alloc}); 2153 break; 2154 case llvm::omp::Directive::OMPD_target_exit_data: 2155 CheckAllowedMapTypes(type, {Type::From, Type::Release, Type::Delete}); 2156 break; 2157 default: 2158 break; 2159 } 2160 } 2161 } 2162 2163 bool OmpStructureChecker::ScheduleModifierHasType( 2164 const parser::OmpScheduleClause &x, 2165 const parser::OmpScheduleModifierType::ModType &type) { 2166 const auto &modifier{ 2167 std::get<std::optional<parser::OmpScheduleModifier>>(x.t)}; 2168 if (modifier) { 2169 const auto &modType1{ 2170 std::get<parser::OmpScheduleModifier::Modifier1>(modifier->t)}; 2171 const auto &modType2{ 2172 std::get<std::optional<parser::OmpScheduleModifier::Modifier2>>( 2173 modifier->t)}; 2174 if (modType1.v.v == type || (modType2 && modType2->v.v == type)) { 2175 return true; 2176 } 2177 } 2178 return false; 2179 } 2180 void OmpStructureChecker::Enter(const parser::OmpClause::Schedule &x) { 2181 CheckAllowed(llvm::omp::Clause::OMPC_schedule); 2182 const parser::OmpScheduleClause &scheduleClause = x.v; 2183 2184 // 2.7 Loop Construct Restriction 2185 if (llvm::omp::doSet.test(GetContext().directive)) { 2186 const auto &kind{std::get<1>(scheduleClause.t)}; 2187 const auto &chunk{std::get<2>(scheduleClause.t)}; 2188 if (chunk) { 2189 if (kind == parser::OmpScheduleClause::ScheduleType::Runtime || 2190 kind == parser::OmpScheduleClause::ScheduleType::Auto) { 2191 context_.Say(GetContext().clauseSource, 2192 "When SCHEDULE clause has %s specified, " 2193 "it must not have chunk size specified"_err_en_US, 2194 parser::ToUpperCaseLetters( 2195 parser::OmpScheduleClause::EnumToString(kind))); 2196 } 2197 if (const auto &chunkExpr{std::get<std::optional<parser::ScalarIntExpr>>( 2198 scheduleClause.t)}) { 2199 RequiresPositiveParameter( 2200 llvm::omp::Clause::OMPC_schedule, *chunkExpr, "chunk size"); 2201 } 2202 } 2203 2204 if (ScheduleModifierHasType(scheduleClause, 2205 parser::OmpScheduleModifierType::ModType::Nonmonotonic)) { 2206 if (kind != parser::OmpScheduleClause::ScheduleType::Dynamic && 2207 kind != parser::OmpScheduleClause::ScheduleType::Guided) { 2208 context_.Say(GetContext().clauseSource, 2209 "The NONMONOTONIC modifier can only be specified with " 2210 "SCHEDULE(DYNAMIC) or SCHEDULE(GUIDED)"_err_en_US); 2211 } 2212 } 2213 } 2214 } 2215 2216 void OmpStructureChecker::Enter(const parser::OmpClause::Depend &x) { 2217 CheckAllowed(llvm::omp::Clause::OMPC_depend); 2218 if (const auto *inOut{std::get_if<parser::OmpDependClause::InOut>(&x.v.u)}) { 2219 const auto &designators{std::get<std::list<parser::Designator>>(inOut->t)}; 2220 for (const auto &ele : designators) { 2221 if (const auto *dataRef{std::get_if<parser::DataRef>(&ele.u)}) { 2222 CheckDependList(*dataRef); 2223 if (const auto *arr{ 2224 std::get_if<common::Indirection<parser::ArrayElement>>( 2225 &dataRef->u)}) { 2226 CheckArraySection(arr->value(), GetLastName(*dataRef), 2227 llvm::omp::Clause::OMPC_depend); 2228 } 2229 } 2230 } 2231 } 2232 } 2233 2234 void OmpStructureChecker::Enter(const parser::OmpClause::Copyprivate &x) { 2235 CheckAllowed(llvm::omp::Clause::OMPC_copyprivate); 2236 CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_copyprivate); 2237 } 2238 2239 void OmpStructureChecker::Enter(const parser::OmpClause::Lastprivate &x) { 2240 CheckAllowed(llvm::omp::Clause::OMPC_lastprivate); 2241 2242 DirectivesClauseTriple dirClauseTriple; 2243 SymbolSourceMap currSymbols; 2244 GetSymbolsInObjectList(x.v, currSymbols); 2245 CheckDefinableObjects(currSymbols, GetClauseKindForParserClass(x)); 2246 2247 // Check lastprivate variables in worksharing constructs 2248 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do, 2249 std::make_pair( 2250 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet)); 2251 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections, 2252 std::make_pair( 2253 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet)); 2254 2255 CheckPrivateSymbolsInOuterCxt( 2256 currSymbols, dirClauseTriple, GetClauseKindForParserClass(x)); 2257 } 2258 2259 llvm::StringRef OmpStructureChecker::getClauseName(llvm::omp::Clause clause) { 2260 return llvm::omp::getOpenMPClauseName(clause); 2261 } 2262 2263 llvm::StringRef OmpStructureChecker::getDirectiveName( 2264 llvm::omp::Directive directive) { 2265 return llvm::omp::getOpenMPDirectiveName(directive); 2266 } 2267 2268 void OmpStructureChecker::CheckDependList(const parser::DataRef &d) { 2269 std::visit( 2270 common::visitors{ 2271 [&](const common::Indirection<parser::ArrayElement> &elem) { 2272 // Check if the base element is valid on Depend Clause 2273 CheckDependList(elem.value().base); 2274 }, 2275 [&](const common::Indirection<parser::StructureComponent> &) { 2276 context_.Say(GetContext().clauseSource, 2277 "A variable that is part of another variable " 2278 "(such as an element of a structure) but is not an array " 2279 "element or an array section cannot appear in a DEPEND " 2280 "clause"_err_en_US); 2281 }, 2282 [&](const common::Indirection<parser::CoindexedNamedObject> &) { 2283 context_.Say(GetContext().clauseSource, 2284 "Coarrays are not supported in DEPEND clause"_err_en_US); 2285 }, 2286 [&](const parser::Name &) { return; }, 2287 }, 2288 d.u); 2289 } 2290 2291 // Called from both Reduction and Depend clause. 2292 void OmpStructureChecker::CheckArraySection( 2293 const parser::ArrayElement &arrayElement, const parser::Name &name, 2294 const llvm::omp::Clause clause) { 2295 if (!arrayElement.subscripts.empty()) { 2296 for (const auto &subscript : arrayElement.subscripts) { 2297 if (const auto *triplet{ 2298 std::get_if<parser::SubscriptTriplet>(&subscript.u)}) { 2299 if (std::get<0>(triplet->t) && std::get<1>(triplet->t)) { 2300 const auto &lower{std::get<0>(triplet->t)}; 2301 const auto &upper{std::get<1>(triplet->t)}; 2302 if (lower && upper) { 2303 const auto lval{GetIntValue(lower)}; 2304 const auto uval{GetIntValue(upper)}; 2305 if (lval && uval && *uval < *lval) { 2306 context_.Say(GetContext().clauseSource, 2307 "'%s' in %s clause" 2308 " is a zero size array section"_err_en_US, 2309 name.ToString(), 2310 parser::ToUpperCaseLetters(getClauseName(clause).str())); 2311 break; 2312 } else if (std::get<2>(triplet->t)) { 2313 const auto &strideExpr{std::get<2>(triplet->t)}; 2314 if (strideExpr) { 2315 if (clause == llvm::omp::Clause::OMPC_depend) { 2316 context_.Say(GetContext().clauseSource, 2317 "Stride should not be specified for array section in " 2318 "DEPEND " 2319 "clause"_err_en_US); 2320 } 2321 const auto stride{GetIntValue(strideExpr)}; 2322 if ((stride && stride != 1)) { 2323 context_.Say(GetContext().clauseSource, 2324 "A list item that appears in a REDUCTION clause" 2325 " should have a contiguous storage array section."_err_en_US, 2326 ContextDirectiveAsFortran()); 2327 break; 2328 } 2329 } 2330 } 2331 } 2332 } 2333 } 2334 } 2335 } 2336 } 2337 2338 void OmpStructureChecker::CheckIntentInPointer( 2339 const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) { 2340 SymbolSourceMap symbols; 2341 GetSymbolsInObjectList(objectList, symbols); 2342 for (auto it{symbols.begin()}; it != symbols.end(); ++it) { 2343 const auto *symbol{it->first}; 2344 const auto source{it->second}; 2345 if (IsPointer(*symbol) && IsIntentIn(*symbol)) { 2346 context_.Say(source, 2347 "Pointer '%s' with the INTENT(IN) attribute may not appear " 2348 "in a %s clause"_err_en_US, 2349 symbol->name(), 2350 parser::ToUpperCaseLetters(getClauseName(clause).str())); 2351 } 2352 } 2353 } 2354 2355 void OmpStructureChecker::GetSymbolsInObjectList( 2356 const parser::OmpObjectList &objectList, SymbolSourceMap &symbols) { 2357 for (const auto &ompObject : objectList.v) { 2358 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) { 2359 if (const auto *symbol{name->symbol}) { 2360 if (const auto *commonBlockDetails{ 2361 symbol->detailsIf<CommonBlockDetails>()}) { 2362 for (const auto &object : commonBlockDetails->objects()) { 2363 symbols.emplace(&object->GetUltimate(), name->source); 2364 } 2365 } else { 2366 symbols.emplace(&symbol->GetUltimate(), name->source); 2367 } 2368 } 2369 } 2370 } 2371 } 2372 2373 void OmpStructureChecker::CheckDefinableObjects( 2374 SymbolSourceMap &symbols, const llvm::omp::Clause clause) { 2375 for (auto it{symbols.begin()}; it != symbols.end(); ++it) { 2376 const auto *symbol{it->first}; 2377 const auto source{it->second}; 2378 if (auto msg{WhyNotModifiable(*symbol, context_.FindScope(source))}) { 2379 context_ 2380 .Say(source, 2381 "Variable '%s' on the %s clause is not definable"_err_en_US, 2382 symbol->name(), 2383 parser::ToUpperCaseLetters(getClauseName(clause).str())) 2384 .Attach(source, std::move(*msg), symbol->name()); 2385 } 2386 } 2387 } 2388 2389 void OmpStructureChecker::CheckPrivateSymbolsInOuterCxt( 2390 SymbolSourceMap &currSymbols, DirectivesClauseTriple &dirClauseTriple, 2391 const llvm::omp::Clause currClause) { 2392 SymbolSourceMap enclosingSymbols; 2393 auto range{dirClauseTriple.equal_range(GetContext().directive)}; 2394 for (auto dirIter{range.first}; dirIter != range.second; ++dirIter) { 2395 auto enclosingDir{dirIter->second.first}; 2396 auto enclosingClauseSet{dirIter->second.second}; 2397 if (auto *enclosingContext{GetEnclosingContextWithDir(enclosingDir)}) { 2398 for (auto it{enclosingContext->clauseInfo.begin()}; 2399 it != enclosingContext->clauseInfo.end(); ++it) { 2400 if (enclosingClauseSet.test(it->first)) { 2401 if (const auto *ompObjectList{GetOmpObjectList(*it->second)}) { 2402 GetSymbolsInObjectList(*ompObjectList, enclosingSymbols); 2403 } 2404 } 2405 } 2406 2407 // Check if the symbols in current context are private in outer context 2408 for (auto iter{currSymbols.begin()}; iter != currSymbols.end(); ++iter) { 2409 const auto *symbol{iter->first}; 2410 const auto source{iter->second}; 2411 if (enclosingSymbols.find(symbol) != enclosingSymbols.end()) { 2412 context_.Say(source, 2413 "%s variable '%s' is PRIVATE in outer context"_err_en_US, 2414 parser::ToUpperCaseLetters(getClauseName(currClause).str()), 2415 symbol->name()); 2416 } 2417 } 2418 } 2419 } 2420 } 2421 2422 bool OmpStructureChecker::CheckTargetBlockOnlyTeams( 2423 const parser::Block &block) { 2424 bool nestedTeams{false}; 2425 auto it{block.begin()}; 2426 2427 if (const auto *ompConstruct{parser::Unwrap<parser::OpenMPConstruct>(*it)}) { 2428 if (const auto *ompBlockConstruct{ 2429 std::get_if<parser::OpenMPBlockConstruct>(&ompConstruct->u)}) { 2430 const auto &beginBlockDir{ 2431 std::get<parser::OmpBeginBlockDirective>(ompBlockConstruct->t)}; 2432 const auto &beginDir{ 2433 std::get<parser::OmpBlockDirective>(beginBlockDir.t)}; 2434 if (beginDir.v == llvm::omp::Directive::OMPD_teams) { 2435 nestedTeams = true; 2436 } 2437 } 2438 } 2439 2440 if (nestedTeams && ++it == block.end()) { 2441 return true; 2442 } 2443 return false; 2444 } 2445 2446 void OmpStructureChecker::CheckWorkshareBlockStmts( 2447 const parser::Block &block, parser::CharBlock source) { 2448 OmpWorkshareBlockChecker ompWorkshareBlockChecker{context_, source}; 2449 2450 for (auto it{block.begin()}; it != block.end(); ++it) { 2451 if (parser::Unwrap<parser::AssignmentStmt>(*it) || 2452 parser::Unwrap<parser::ForallStmt>(*it) || 2453 parser::Unwrap<parser::ForallConstruct>(*it) || 2454 parser::Unwrap<parser::WhereStmt>(*it) || 2455 parser::Unwrap<parser::WhereConstruct>(*it)) { 2456 parser::Walk(*it, ompWorkshareBlockChecker); 2457 } else if (const auto *ompConstruct{ 2458 parser::Unwrap<parser::OpenMPConstruct>(*it)}) { 2459 if (const auto *ompAtomicConstruct{ 2460 std::get_if<parser::OpenMPAtomicConstruct>(&ompConstruct->u)}) { 2461 // Check if assignment statements in the enclosing OpenMP Atomic 2462 // construct are allowed in the Workshare construct 2463 parser::Walk(*ompAtomicConstruct, ompWorkshareBlockChecker); 2464 } else if (const auto *ompCriticalConstruct{ 2465 std::get_if<parser::OpenMPCriticalConstruct>( 2466 &ompConstruct->u)}) { 2467 // All the restrictions on the Workshare construct apply to the 2468 // statements in the enclosing critical constructs 2469 const auto &criticalBlock{ 2470 std::get<parser::Block>(ompCriticalConstruct->t)}; 2471 CheckWorkshareBlockStmts(criticalBlock, source); 2472 } else { 2473 // Check if OpenMP constructs enclosed in the Workshare construct are 2474 // 'Parallel' constructs 2475 auto currentDir{llvm::omp::Directive::OMPD_unknown}; 2476 const OmpDirectiveSet parallelDirSet{ 2477 llvm::omp::Directive::OMPD_parallel, 2478 llvm::omp::Directive::OMPD_parallel_do, 2479 llvm::omp::Directive::OMPD_parallel_sections, 2480 llvm::omp::Directive::OMPD_parallel_workshare, 2481 llvm::omp::Directive::OMPD_parallel_do_simd}; 2482 2483 if (const auto *ompBlockConstruct{ 2484 std::get_if<parser::OpenMPBlockConstruct>(&ompConstruct->u)}) { 2485 const auto &beginBlockDir{ 2486 std::get<parser::OmpBeginBlockDirective>(ompBlockConstruct->t)}; 2487 const auto &beginDir{ 2488 std::get<parser::OmpBlockDirective>(beginBlockDir.t)}; 2489 currentDir = beginDir.v; 2490 } else if (const auto *ompLoopConstruct{ 2491 std::get_if<parser::OpenMPLoopConstruct>( 2492 &ompConstruct->u)}) { 2493 const auto &beginLoopDir{ 2494 std::get<parser::OmpBeginLoopDirective>(ompLoopConstruct->t)}; 2495 const auto &beginDir{ 2496 std::get<parser::OmpLoopDirective>(beginLoopDir.t)}; 2497 currentDir = beginDir.v; 2498 } else if (const auto *ompSectionsConstruct{ 2499 std::get_if<parser::OpenMPSectionsConstruct>( 2500 &ompConstruct->u)}) { 2501 const auto &beginSectionsDir{ 2502 std::get<parser::OmpBeginSectionsDirective>( 2503 ompSectionsConstruct->t)}; 2504 const auto &beginDir{ 2505 std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)}; 2506 currentDir = beginDir.v; 2507 } 2508 2509 if (!parallelDirSet.test(currentDir)) { 2510 context_.Say(source, 2511 "OpenMP constructs enclosed in WORKSHARE construct may consist " 2512 "of ATOMIC, CRITICAL or PARALLEL constructs only"_err_en_US); 2513 } 2514 } 2515 } else { 2516 context_.Say(source, 2517 "The structured block in a WORKSHARE construct may consist of only " 2518 "SCALAR or ARRAY assignments, FORALL or WHERE statements, " 2519 "FORALL, WHERE, ATOMIC, CRITICAL or PARALLEL constructs"_err_en_US); 2520 } 2521 } 2522 } 2523 2524 const parser::OmpObjectList *OmpStructureChecker::GetOmpObjectList( 2525 const parser::OmpClause &clause) { 2526 2527 // Clauses with OmpObjectList as its data member 2528 using MemberObjectListClauses = std::tuple<parser::OmpClause::Copyprivate, 2529 parser::OmpClause::Copyin, parser::OmpClause::Firstprivate, 2530 parser::OmpClause::From, parser::OmpClause::Lastprivate, 2531 parser::OmpClause::Link, parser::OmpClause::Private, 2532 parser::OmpClause::Shared, parser::OmpClause::To>; 2533 2534 // Clauses with OmpObjectList in the tuple 2535 using TupleObjectListClauses = std::tuple<parser::OmpClause::Allocate, 2536 parser::OmpClause::Map, parser::OmpClause::Reduction>; 2537 2538 // TODO:: Generate the tuples using TableGen. 2539 // Handle other constructs with OmpObjectList such as OpenMPThreadprivate. 2540 return std::visit( 2541 common::visitors{ 2542 [&](const auto &x) -> const parser::OmpObjectList * { 2543 using Ty = std::decay_t<decltype(x)>; 2544 if constexpr (common::HasMember<Ty, MemberObjectListClauses>) { 2545 return &x.v; 2546 } else if constexpr (common::HasMember<Ty, 2547 TupleObjectListClauses>) { 2548 return &(std::get<parser::OmpObjectList>(x.v.t)); 2549 } else { 2550 return nullptr; 2551 } 2552 }, 2553 }, 2554 clause.u); 2555 } 2556 2557 } // namespace Fortran::semantics 2558