1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// \file 10 /// \brief This file implements semantic analysis for OpenMP directives and 11 /// clauses. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclOpenMP.h" 20 #include "clang/AST/StmtCXX.h" 21 #include "clang/AST/StmtOpenMP.h" 22 #include "clang/AST/StmtVisitor.h" 23 #include "clang/Basic/OpenMPKinds.h" 24 #include "clang/Lex/Preprocessor.h" 25 #include "clang/Sema/Initialization.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/Scope.h" 28 #include "clang/Sema/ScopeInfo.h" 29 #include "clang/Sema/SemaInternal.h" 30 using namespace clang; 31 32 //===----------------------------------------------------------------------===// 33 // Stack of data-sharing attributes for variables 34 //===----------------------------------------------------------------------===// 35 36 namespace { 37 /// \brief Default data sharing attributes, which can be applied to directive. 38 enum DefaultDataSharingAttributes { 39 DSA_unspecified = 0, /// \brief Data sharing attribute not specified. 40 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'. 41 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'. 42 }; 43 44 template <class T> struct MatchesAny { 45 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {} 46 bool operator()(T Kind) { 47 for (auto KindEl : Arr) 48 if (KindEl == Kind) 49 return true; 50 return false; 51 } 52 53 private: 54 ArrayRef<T> Arr; 55 }; 56 struct MatchesAlways { 57 MatchesAlways() {} 58 template <class T> bool operator()(T) { return true; } 59 }; 60 61 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause; 62 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective; 63 64 /// \brief Stack for tracking declarations used in OpenMP directives and 65 /// clauses and their data-sharing attributes. 66 class DSAStackTy { 67 public: 68 struct DSAVarData { 69 OpenMPDirectiveKind DKind; 70 OpenMPClauseKind CKind; 71 DeclRefExpr *RefExpr; 72 SourceLocation ImplicitDSALoc; 73 DSAVarData() 74 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr), 75 ImplicitDSALoc() {} 76 }; 77 78 private: 79 struct DSAInfo { 80 OpenMPClauseKind Attributes; 81 DeclRefExpr *RefExpr; 82 }; 83 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy; 84 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy; 85 86 struct SharingMapTy { 87 DeclSAMapTy SharingMap; 88 AlignedMapTy AlignedMap; 89 DefaultDataSharingAttributes DefaultAttr; 90 SourceLocation DefaultAttrLoc; 91 OpenMPDirectiveKind Directive; 92 DeclarationNameInfo DirectiveName; 93 Scope *CurScope; 94 SourceLocation ConstructLoc; 95 bool OrderedRegion; 96 SourceLocation InnerTeamsRegionLoc; 97 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 98 Scope *CurScope, SourceLocation Loc) 99 : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified), 100 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope), 101 ConstructLoc(Loc), OrderedRegion(false), InnerTeamsRegionLoc() {} 102 SharingMapTy() 103 : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified), 104 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr), 105 ConstructLoc(), OrderedRegion(false), InnerTeamsRegionLoc() {} 106 }; 107 108 typedef SmallVector<SharingMapTy, 64> StackTy; 109 110 /// \brief Stack of used declaration and their data-sharing attributes. 111 StackTy Stack; 112 Sema &SemaRef; 113 114 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; 115 116 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D); 117 118 /// \brief Checks if the variable is a local for OpenMP region. 119 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); 120 121 public: 122 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {} 123 124 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 125 Scope *CurScope, SourceLocation Loc) { 126 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc)); 127 Stack.back().DefaultAttrLoc = Loc; 128 } 129 130 void pop() { 131 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!"); 132 Stack.pop_back(); 133 } 134 135 /// \brief If 'aligned' declaration for given variable \a D was not seen yet, 136 /// add it and return NULL; otherwise return previous occurrence's expression 137 /// for diagnostics. 138 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE); 139 140 /// \brief Adds explicit data sharing attribute to the specified declaration. 141 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A); 142 143 /// \brief Returns data sharing attributes from top of the stack for the 144 /// specified declaration. 145 DSAVarData getTopDSA(VarDecl *D, bool FromParent); 146 /// \brief Returns data-sharing attributes for the specified declaration. 147 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent); 148 /// \brief Checks if the specified variables has data-sharing attributes which 149 /// match specified \a CPred predicate in any directive which matches \a DPred 150 /// predicate. 151 template <class ClausesPredicate, class DirectivesPredicate> 152 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred, 153 DirectivesPredicate DPred, bool FromParent); 154 /// \brief Checks if the specified variables has data-sharing attributes which 155 /// match specified \a CPred predicate in any innermost directive which 156 /// matches \a DPred predicate. 157 template <class ClausesPredicate, class DirectivesPredicate> 158 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred, 159 DirectivesPredicate DPred, 160 bool FromParent); 161 /// \brief Finds a directive which matches specified \a DPred predicate. 162 template <class NamedDirectivesPredicate> 163 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent); 164 165 /// \brief Returns currently analyzed directive. 166 OpenMPDirectiveKind getCurrentDirective() const { 167 return Stack.back().Directive; 168 } 169 /// \brief Returns parent directive. 170 OpenMPDirectiveKind getParentDirective() const { 171 if (Stack.size() > 2) 172 return Stack[Stack.size() - 2].Directive; 173 return OMPD_unknown; 174 } 175 176 /// \brief Set default data sharing attribute to none. 177 void setDefaultDSANone(SourceLocation Loc) { 178 Stack.back().DefaultAttr = DSA_none; 179 Stack.back().DefaultAttrLoc = Loc; 180 } 181 /// \brief Set default data sharing attribute to shared. 182 void setDefaultDSAShared(SourceLocation Loc) { 183 Stack.back().DefaultAttr = DSA_shared; 184 Stack.back().DefaultAttrLoc = Loc; 185 } 186 187 DefaultDataSharingAttributes getDefaultDSA() const { 188 return Stack.back().DefaultAttr; 189 } 190 SourceLocation getDefaultDSALocation() const { 191 return Stack.back().DefaultAttrLoc; 192 } 193 194 /// \brief Checks if the specified variable is a threadprivate. 195 bool isThreadPrivate(VarDecl *D) { 196 DSAVarData DVar = getTopDSA(D, false); 197 return isOpenMPThreadPrivate(DVar.CKind); 198 } 199 200 /// \brief Marks current region as ordered (it has an 'ordered' clause). 201 void setOrderedRegion(bool IsOrdered = true) { 202 Stack.back().OrderedRegion = IsOrdered; 203 } 204 /// \brief Returns true, if parent region is ordered (has associated 205 /// 'ordered' clause), false - otherwise. 206 bool isParentOrderedRegion() const { 207 if (Stack.size() > 2) 208 return Stack[Stack.size() - 2].OrderedRegion; 209 return false; 210 } 211 212 /// \brief Marks current target region as one with closely nested teams 213 /// region. 214 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 215 if (Stack.size() > 2) 216 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc; 217 } 218 /// \brief Returns true, if current region has closely nested teams region. 219 bool hasInnerTeamsRegion() const { 220 return getInnerTeamsRegionLoc().isValid(); 221 } 222 /// \brief Returns location of the nested teams region (if any). 223 SourceLocation getInnerTeamsRegionLoc() const { 224 if (Stack.size() > 1) 225 return Stack.back().InnerTeamsRegionLoc; 226 return SourceLocation(); 227 } 228 229 Scope *getCurScope() const { return Stack.back().CurScope; } 230 Scope *getCurScope() { return Stack.back().CurScope; } 231 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; } 232 }; 233 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 234 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task || 235 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 236 } 237 } // namespace 238 239 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter, 240 VarDecl *D) { 241 DSAVarData DVar; 242 if (Iter == std::prev(Stack.rend())) { 243 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 244 // in a region but not in construct] 245 // File-scope or namespace-scope variables referenced in called routines 246 // in the region are shared unless they appear in a threadprivate 247 // directive. 248 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 249 DVar.CKind = OMPC_shared; 250 251 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 252 // in a region but not in construct] 253 // Variables with static storage duration that are declared in called 254 // routines in the region are shared. 255 if (D->hasGlobalStorage()) 256 DVar.CKind = OMPC_shared; 257 258 return DVar; 259 } 260 261 DVar.DKind = Iter->Directive; 262 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 263 // in a Construct, C/C++, predetermined, p.1] 264 // Variables with automatic storage duration that are declared in a scope 265 // inside the construct are private. 266 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() && 267 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) { 268 DVar.CKind = OMPC_private; 269 return DVar; 270 } 271 272 // Explicitly specified attributes and local variables with predetermined 273 // attributes. 274 if (Iter->SharingMap.count(D)) { 275 DVar.RefExpr = Iter->SharingMap[D].RefExpr; 276 DVar.CKind = Iter->SharingMap[D].Attributes; 277 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 278 return DVar; 279 } 280 281 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 282 // in a Construct, C/C++, implicitly determined, p.1] 283 // In a parallel or task construct, the data-sharing attributes of these 284 // variables are determined by the default clause, if present. 285 switch (Iter->DefaultAttr) { 286 case DSA_shared: 287 DVar.CKind = OMPC_shared; 288 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 289 return DVar; 290 case DSA_none: 291 return DVar; 292 case DSA_unspecified: 293 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 294 // in a Construct, implicitly determined, p.2] 295 // In a parallel construct, if no default clause is present, these 296 // variables are shared. 297 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 298 if (isOpenMPParallelDirective(DVar.DKind) || 299 isOpenMPTeamsDirective(DVar.DKind)) { 300 DVar.CKind = OMPC_shared; 301 return DVar; 302 } 303 304 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 305 // in a Construct, implicitly determined, p.4] 306 // In a task construct, if no default clause is present, a variable that in 307 // the enclosing context is determined to be shared by all implicit tasks 308 // bound to the current team is shared. 309 if (DVar.DKind == OMPD_task) { 310 DSAVarData DVarTemp; 311 for (StackTy::reverse_iterator I = std::next(Iter), 312 EE = std::prev(Stack.rend()); 313 I != EE; ++I) { 314 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 315 // Referenced 316 // in a Construct, implicitly determined, p.6] 317 // In a task construct, if no default clause is present, a variable 318 // whose data-sharing attribute is not determined by the rules above is 319 // firstprivate. 320 DVarTemp = getDSA(I, D); 321 if (DVarTemp.CKind != OMPC_shared) { 322 DVar.RefExpr = nullptr; 323 DVar.DKind = OMPD_task; 324 DVar.CKind = OMPC_firstprivate; 325 return DVar; 326 } 327 if (isParallelOrTaskRegion(I->Directive)) 328 break; 329 } 330 DVar.DKind = OMPD_task; 331 DVar.CKind = 332 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 333 return DVar; 334 } 335 } 336 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 337 // in a Construct, implicitly determined, p.3] 338 // For constructs other than task, if no default clause is present, these 339 // variables inherit their data-sharing attributes from the enclosing 340 // context. 341 return getDSA(std::next(Iter), D); 342 } 343 344 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) { 345 assert(Stack.size() > 1 && "Data sharing attributes stack is empty"); 346 auto It = Stack.back().AlignedMap.find(D); 347 if (It == Stack.back().AlignedMap.end()) { 348 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 349 Stack.back().AlignedMap[D] = NewDE; 350 return nullptr; 351 } else { 352 assert(It->second && "Unexpected nullptr expr in the aligned map"); 353 return It->second; 354 } 355 return nullptr; 356 } 357 358 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) { 359 if (A == OMPC_threadprivate) { 360 Stack[0].SharingMap[D].Attributes = A; 361 Stack[0].SharingMap[D].RefExpr = E; 362 } else { 363 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 364 Stack.back().SharingMap[D].Attributes = A; 365 Stack.back().SharingMap[D].RefExpr = E; 366 } 367 } 368 369 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 370 if (Stack.size() > 2) { 371 reverse_iterator I = Iter, E = std::prev(Stack.rend()); 372 Scope *TopScope = nullptr; 373 while (I != E && !isParallelOrTaskRegion(I->Directive)) { 374 ++I; 375 } 376 if (I == E) 377 return false; 378 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 379 Scope *CurScope = getCurScope(); 380 while (CurScope != TopScope && !CurScope->isDeclScope(D)) { 381 CurScope = CurScope->getParent(); 382 } 383 return CurScope != TopScope; 384 } 385 return false; 386 } 387 388 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) { 389 DSAVarData DVar; 390 391 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 392 // in a Construct, C/C++, predetermined, p.1] 393 // Variables appearing in threadprivate directives are threadprivate. 394 if (D->getTLSKind() != VarDecl::TLS_None) { 395 DVar.CKind = OMPC_threadprivate; 396 return DVar; 397 } 398 if (Stack[0].SharingMap.count(D)) { 399 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr; 400 DVar.CKind = OMPC_threadprivate; 401 return DVar; 402 } 403 404 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 405 // in a Construct, C/C++, predetermined, p.1] 406 // Variables with automatic storage duration that are declared in a scope 407 // inside the construct are private. 408 OpenMPDirectiveKind Kind = 409 FromParent ? getParentDirective() : getCurrentDirective(); 410 auto StartI = std::next(Stack.rbegin()); 411 auto EndI = std::prev(Stack.rend()); 412 if (FromParent && StartI != EndI) { 413 StartI = std::next(StartI); 414 } 415 if (!isParallelOrTaskRegion(Kind)) { 416 if (isOpenMPLocal(D, StartI) && 417 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto || 418 D->getStorageClass() == SC_None)) || 419 isa<ParmVarDecl>(D))) { 420 DVar.CKind = OMPC_private; 421 return DVar; 422 } 423 } 424 425 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 426 // in a Construct, C/C++, predetermined, p.4] 427 // Static data members are shared. 428 if (D->isStaticDataMember()) { 429 // Variables with const-qualified type having no mutable member may be 430 // listed in a firstprivate clause, even if they are static data members. 431 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate), 432 MatchesAlways(), FromParent); 433 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 434 return DVar; 435 436 DVar.CKind = OMPC_shared; 437 return DVar; 438 } 439 440 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 441 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 442 while (Type->isArrayType()) { 443 QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType(); 444 Type = ElemType.getNonReferenceType().getCanonicalType(); 445 } 446 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 447 // in a Construct, C/C++, predetermined, p.6] 448 // Variables with const qualified type having no mutable member are 449 // shared. 450 CXXRecordDecl *RD = 451 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 452 if (IsConstant && 453 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) { 454 // Variables with const-qualified type having no mutable member may be 455 // listed in a firstprivate clause, even if they are static data members. 456 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate), 457 MatchesAlways(), FromParent); 458 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 459 return DVar; 460 461 DVar.CKind = OMPC_shared; 462 return DVar; 463 } 464 465 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 466 // in a Construct, C/C++, predetermined, p.7] 467 // Variables with static storage duration that are declared in a scope 468 // inside the construct are shared. 469 if (D->isStaticLocal()) { 470 DVar.CKind = OMPC_shared; 471 return DVar; 472 } 473 474 // Explicitly specified attributes and local variables with predetermined 475 // attributes. 476 auto I = std::prev(StartI); 477 if (I->SharingMap.count(D)) { 478 DVar.RefExpr = I->SharingMap[D].RefExpr; 479 DVar.CKind = I->SharingMap[D].Attributes; 480 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 481 } 482 483 return DVar; 484 } 485 486 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) { 487 auto StartI = Stack.rbegin(); 488 auto EndI = std::prev(Stack.rend()); 489 if (FromParent && StartI != EndI) { 490 StartI = std::next(StartI); 491 } 492 return getDSA(StartI, D); 493 } 494 495 template <class ClausesPredicate, class DirectivesPredicate> 496 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred, 497 DirectivesPredicate DPred, 498 bool FromParent) { 499 auto StartI = std::next(Stack.rbegin()); 500 auto EndI = std::prev(Stack.rend()); 501 if (FromParent && StartI != EndI) { 502 StartI = std::next(StartI); 503 } 504 for (auto I = StartI, EE = EndI; I != EE; ++I) { 505 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 506 continue; 507 DSAVarData DVar = getDSA(I, D); 508 if (CPred(DVar.CKind)) 509 return DVar; 510 } 511 return DSAVarData(); 512 } 513 514 template <class ClausesPredicate, class DirectivesPredicate> 515 DSAStackTy::DSAVarData 516 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred, 517 DirectivesPredicate DPred, bool FromParent) { 518 auto StartI = std::next(Stack.rbegin()); 519 auto EndI = std::prev(Stack.rend()); 520 if (FromParent && StartI != EndI) { 521 StartI = std::next(StartI); 522 } 523 for (auto I = StartI, EE = EndI; I != EE; ++I) { 524 if (!DPred(I->Directive)) 525 break; 526 DSAVarData DVar = getDSA(I, D); 527 if (CPred(DVar.CKind)) 528 return DVar; 529 return DSAVarData(); 530 } 531 return DSAVarData(); 532 } 533 534 template <class NamedDirectivesPredicate> 535 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) { 536 auto StartI = std::next(Stack.rbegin()); 537 auto EndI = std::prev(Stack.rend()); 538 if (FromParent && StartI != EndI) { 539 StartI = std::next(StartI); 540 } 541 for (auto I = StartI, EE = EndI; I != EE; ++I) { 542 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 543 return true; 544 } 545 return false; 546 } 547 548 void Sema::InitDataSharingAttributesStack() { 549 VarDataSharingAttributesStack = new DSAStackTy(*this); 550 } 551 552 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 553 554 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 555 556 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 557 const DeclarationNameInfo &DirName, 558 Scope *CurScope, SourceLocation Loc) { 559 DSAStack->push(DKind, DirName, CurScope, Loc); 560 PushExpressionEvaluationContext(PotentiallyEvaluated); 561 } 562 563 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 564 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 565 // A variable of class type (or array thereof) that appears in a lastprivate 566 // clause requires an accessible, unambiguous default constructor for the 567 // class type, unless the list item is also specified in a firstprivate 568 // clause. 569 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 570 for (auto C : D->clauses()) { 571 if (auto Clause = dyn_cast<OMPLastprivateClause>(C)) { 572 for (auto VarRef : Clause->varlists()) { 573 if (VarRef->isValueDependent() || VarRef->isTypeDependent()) 574 continue; 575 auto VD = cast<VarDecl>(cast<DeclRefExpr>(VarRef)->getDecl()); 576 auto DVar = DSAStack->getTopDSA(VD, false); 577 if (DVar.CKind == OMPC_lastprivate) { 578 SourceLocation ELoc = VarRef->getExprLoc(); 579 auto Type = VarRef->getType(); 580 if (Type->isArrayType()) 581 Type = QualType(Type->getArrayElementTypeNoTypeQual(), 0); 582 CXXRecordDecl *RD = 583 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 584 // FIXME This code must be replaced by actual constructing of the 585 // lastprivate variable. 586 if (RD) { 587 CXXConstructorDecl *CD = LookupDefaultConstructor(RD); 588 PartialDiagnostic PD = 589 PartialDiagnostic(PartialDiagnostic::NullDiagnostic()); 590 if (!CD || 591 CheckConstructorAccess( 592 ELoc, CD, InitializedEntity::InitializeTemporary(Type), 593 CD->getAccess(), PD) == AR_inaccessible || 594 CD->isDeleted()) { 595 Diag(ELoc, diag::err_omp_required_method) 596 << getOpenMPClauseName(OMPC_lastprivate) << 0; 597 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 598 VarDecl::DeclarationOnly; 599 Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl 600 : diag::note_defined_here) 601 << VD; 602 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 603 continue; 604 } 605 MarkFunctionReferenced(ELoc, CD); 606 DiagnoseUseOfDecl(CD, ELoc); 607 } 608 } 609 } 610 } 611 } 612 } 613 614 DSAStack->pop(); 615 DiscardCleanupsInEvaluationContext(); 616 PopExpressionEvaluationContext(); 617 } 618 619 namespace { 620 621 class VarDeclFilterCCC : public CorrectionCandidateCallback { 622 private: 623 Sema &SemaRef; 624 625 public: 626 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 627 bool ValidateCandidate(const TypoCorrection &Candidate) override { 628 NamedDecl *ND = Candidate.getCorrectionDecl(); 629 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) { 630 return VD->hasGlobalStorage() && 631 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 632 SemaRef.getCurScope()); 633 } 634 return false; 635 } 636 }; 637 } // namespace 638 639 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 640 CXXScopeSpec &ScopeSpec, 641 const DeclarationNameInfo &Id) { 642 LookupResult Lookup(*this, Id, LookupOrdinaryName); 643 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 644 645 if (Lookup.isAmbiguous()) 646 return ExprError(); 647 648 VarDecl *VD; 649 if (!Lookup.isSingleResult()) { 650 if (TypoCorrection Corrected = CorrectTypo( 651 Id, LookupOrdinaryName, CurScope, nullptr, 652 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 653 diagnoseTypo(Corrected, 654 PDiag(Lookup.empty() 655 ? diag::err_undeclared_var_use_suggest 656 : diag::err_omp_expected_var_arg_suggest) 657 << Id.getName()); 658 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 659 } else { 660 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 661 : diag::err_omp_expected_var_arg) 662 << Id.getName(); 663 return ExprError(); 664 } 665 } else { 666 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 667 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 668 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 669 return ExprError(); 670 } 671 } 672 Lookup.suppressDiagnostics(); 673 674 // OpenMP [2.9.2, Syntax, C/C++] 675 // Variables must be file-scope, namespace-scope, or static block-scope. 676 if (!VD->hasGlobalStorage()) { 677 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 678 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 679 bool IsDecl = 680 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 681 Diag(VD->getLocation(), 682 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 683 << VD; 684 return ExprError(); 685 } 686 687 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 688 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 689 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 690 // A threadprivate directive for file-scope variables must appear outside 691 // any definition or declaration. 692 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 693 !getCurLexicalContext()->isTranslationUnit()) { 694 Diag(Id.getLoc(), diag::err_omp_var_scope) 695 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 696 bool IsDecl = 697 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 698 Diag(VD->getLocation(), 699 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 700 << VD; 701 return ExprError(); 702 } 703 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 704 // A threadprivate directive for static class member variables must appear 705 // in the class definition, in the same scope in which the member 706 // variables are declared. 707 if (CanonicalVD->isStaticDataMember() && 708 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 709 Diag(Id.getLoc(), diag::err_omp_var_scope) 710 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 711 bool IsDecl = 712 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 713 Diag(VD->getLocation(), 714 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 715 << VD; 716 return ExprError(); 717 } 718 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 719 // A threadprivate directive for namespace-scope variables must appear 720 // outside any definition or declaration other than the namespace 721 // definition itself. 722 if (CanonicalVD->getDeclContext()->isNamespace() && 723 (!getCurLexicalContext()->isFileContext() || 724 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 725 Diag(Id.getLoc(), diag::err_omp_var_scope) 726 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 727 bool IsDecl = 728 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 729 Diag(VD->getLocation(), 730 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 731 << VD; 732 return ExprError(); 733 } 734 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 735 // A threadprivate directive for static block-scope variables must appear 736 // in the scope of the variable and not in a nested scope. 737 if (CanonicalVD->isStaticLocal() && CurScope && 738 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 739 Diag(Id.getLoc(), diag::err_omp_var_scope) 740 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 741 bool IsDecl = 742 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 743 Diag(VD->getLocation(), 744 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 745 << VD; 746 return ExprError(); 747 } 748 749 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 750 // A threadprivate directive must lexically precede all references to any 751 // of the variables in its list. 752 if (VD->isUsed()) { 753 Diag(Id.getLoc(), diag::err_omp_var_used) 754 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 755 return ExprError(); 756 } 757 758 QualType ExprType = VD->getType().getNonReferenceType(); 759 ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc()); 760 return DE; 761 } 762 763 Sema::DeclGroupPtrTy 764 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 765 ArrayRef<Expr *> VarList) { 766 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 767 CurContext->addDecl(D); 768 return DeclGroupPtrTy::make(DeclGroupRef(D)); 769 } 770 return DeclGroupPtrTy(); 771 } 772 773 namespace { 774 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 775 Sema &SemaRef; 776 777 public: 778 bool VisitDeclRefExpr(const DeclRefExpr *E) { 779 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) { 780 if (VD->hasLocalStorage()) { 781 SemaRef.Diag(E->getLocStart(), 782 diag::err_omp_local_var_in_threadprivate_init) 783 << E->getSourceRange(); 784 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 785 << VD << VD->getSourceRange(); 786 return true; 787 } 788 } 789 return false; 790 } 791 bool VisitStmt(const Stmt *S) { 792 for (auto Child : S->children()) { 793 if (Child && Visit(Child)) 794 return true; 795 } 796 return false; 797 } 798 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 799 }; 800 } // namespace 801 802 OMPThreadPrivateDecl * 803 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 804 SmallVector<Expr *, 8> Vars; 805 for (auto &RefExpr : VarList) { 806 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 807 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 808 SourceLocation ILoc = DE->getExprLoc(); 809 810 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 811 // A threadprivate variable must not have an incomplete type. 812 if (RequireCompleteType(ILoc, VD->getType(), 813 diag::err_omp_threadprivate_incomplete_type)) { 814 continue; 815 } 816 817 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 818 // A threadprivate variable must not have a reference type. 819 if (VD->getType()->isReferenceType()) { 820 Diag(ILoc, diag::err_omp_ref_type_arg) 821 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 822 bool IsDecl = 823 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 824 Diag(VD->getLocation(), 825 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 826 << VD; 827 continue; 828 } 829 830 // Check if this is a TLS variable. 831 if (VD->getTLSKind()) { 832 Diag(ILoc, diag::err_omp_var_thread_local) << VD; 833 bool IsDecl = 834 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 835 Diag(VD->getLocation(), 836 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 837 << VD; 838 continue; 839 } 840 841 // Check if initial value of threadprivate variable reference variable with 842 // local storage (it is not supported by runtime). 843 if (auto Init = VD->getAnyInitializer()) { 844 LocalVarRefChecker Checker(*this); 845 if (Checker.Visit(Init)) 846 continue; 847 } 848 849 Vars.push_back(RefExpr); 850 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 851 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 852 Context, SourceRange(Loc, Loc))); 853 if (auto *ML = Context.getASTMutationListener()) 854 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 855 } 856 OMPThreadPrivateDecl *D = nullptr; 857 if (!Vars.empty()) { 858 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 859 Vars); 860 D->setAccess(AS_public); 861 } 862 return D; 863 } 864 865 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 866 const VarDecl *VD, DSAStackTy::DSAVarData DVar, 867 bool IsLoopIterVar = false) { 868 if (DVar.RefExpr) { 869 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 870 << getOpenMPClauseName(DVar.CKind); 871 return; 872 } 873 enum { 874 PDSA_StaticMemberShared, 875 PDSA_StaticLocalVarShared, 876 PDSA_LoopIterVarPrivate, 877 PDSA_LoopIterVarLinear, 878 PDSA_LoopIterVarLastprivate, 879 PDSA_ConstVarShared, 880 PDSA_GlobalVarShared, 881 PDSA_TaskVarFirstprivate, 882 PDSA_LocalVarPrivate, 883 PDSA_Implicit 884 } Reason = PDSA_Implicit; 885 bool ReportHint = false; 886 auto ReportLoc = VD->getLocation(); 887 if (IsLoopIterVar) { 888 if (DVar.CKind == OMPC_private) 889 Reason = PDSA_LoopIterVarPrivate; 890 else if (DVar.CKind == OMPC_lastprivate) 891 Reason = PDSA_LoopIterVarLastprivate; 892 else 893 Reason = PDSA_LoopIterVarLinear; 894 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) { 895 Reason = PDSA_TaskVarFirstprivate; 896 ReportLoc = DVar.ImplicitDSALoc; 897 } else if (VD->isStaticLocal()) 898 Reason = PDSA_StaticLocalVarShared; 899 else if (VD->isStaticDataMember()) 900 Reason = PDSA_StaticMemberShared; 901 else if (VD->isFileVarDecl()) 902 Reason = PDSA_GlobalVarShared; 903 else if (VD->getType().isConstant(SemaRef.getASTContext())) 904 Reason = PDSA_ConstVarShared; 905 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 906 ReportHint = true; 907 Reason = PDSA_LocalVarPrivate; 908 } 909 if (Reason != PDSA_Implicit) { 910 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 911 << Reason << ReportHint 912 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 913 } else if (DVar.ImplicitDSALoc.isValid()) { 914 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 915 << getOpenMPClauseName(DVar.CKind); 916 } 917 } 918 919 namespace { 920 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 921 DSAStackTy *Stack; 922 Sema &SemaRef; 923 bool ErrorFound; 924 CapturedStmt *CS; 925 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 926 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA; 927 928 public: 929 void VisitDeclRefExpr(DeclRefExpr *E) { 930 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 931 // Skip internally declared variables. 932 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) 933 return; 934 935 auto DVar = Stack->getTopDSA(VD, false); 936 // Check if the variable has explicit DSA set and stop analysis if it so. 937 if (DVar.RefExpr) return; 938 939 auto ELoc = E->getExprLoc(); 940 auto DKind = Stack->getCurrentDirective(); 941 // The default(none) clause requires that each variable that is referenced 942 // in the construct, and does not have a predetermined data-sharing 943 // attribute, must have its data-sharing attribute explicitly determined 944 // by being listed in a data-sharing attribute clause. 945 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 946 isParallelOrTaskRegion(DKind) && 947 VarsWithInheritedDSA.count(VD) == 0) { 948 VarsWithInheritedDSA[VD] = E; 949 return; 950 } 951 952 // OpenMP [2.9.3.6, Restrictions, p.2] 953 // A list item that appears in a reduction clause of the innermost 954 // enclosing worksharing or parallel construct may not be accessed in an 955 // explicit task. 956 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction), 957 [](OpenMPDirectiveKind K) -> bool { 958 return isOpenMPParallelDirective(K) || 959 isOpenMPWorksharingDirective(K) || 960 isOpenMPTeamsDirective(K); 961 }, 962 false); 963 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) { 964 ErrorFound = true; 965 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 966 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 967 return; 968 } 969 970 // Define implicit data-sharing attributes for task. 971 DVar = Stack->getImplicitDSA(VD, false); 972 if (DKind == OMPD_task && DVar.CKind != OMPC_shared) 973 ImplicitFirstprivate.push_back(E); 974 } 975 } 976 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 977 for (auto *C : S->clauses()) { 978 // Skip analysis of arguments of implicitly defined firstprivate clause 979 // for task directives. 980 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid())) 981 for (auto *CC : C->children()) { 982 if (CC) 983 Visit(CC); 984 } 985 } 986 } 987 void VisitStmt(Stmt *S) { 988 for (auto *C : S->children()) { 989 if (C && !isa<OMPExecutableDirective>(C)) 990 Visit(C); 991 } 992 } 993 994 bool isErrorFound() { return ErrorFound; } 995 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; } 996 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() { 997 return VarsWithInheritedDSA; 998 } 999 1000 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 1001 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 1002 }; 1003 } // namespace 1004 1005 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 1006 switch (DKind) { 1007 case OMPD_parallel: { 1008 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1009 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty); 1010 Sema::CapturedParamNameType Params[] = { 1011 std::make_pair(".global_tid.", KmpInt32PtrTy), 1012 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1013 std::make_pair(StringRef(), QualType()) // __context with shared vars 1014 }; 1015 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1016 Params); 1017 break; 1018 } 1019 case OMPD_simd: { 1020 Sema::CapturedParamNameType Params[] = { 1021 std::make_pair(StringRef(), QualType()) // __context with shared vars 1022 }; 1023 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1024 Params); 1025 break; 1026 } 1027 case OMPD_for: { 1028 Sema::CapturedParamNameType Params[] = { 1029 std::make_pair(StringRef(), QualType()) // __context with shared vars 1030 }; 1031 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1032 Params); 1033 break; 1034 } 1035 case OMPD_for_simd: { 1036 Sema::CapturedParamNameType Params[] = { 1037 std::make_pair(StringRef(), QualType()) // __context with shared vars 1038 }; 1039 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1040 Params); 1041 break; 1042 } 1043 case OMPD_sections: { 1044 Sema::CapturedParamNameType Params[] = { 1045 std::make_pair(StringRef(), QualType()) // __context with shared vars 1046 }; 1047 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1048 Params); 1049 break; 1050 } 1051 case OMPD_section: { 1052 Sema::CapturedParamNameType Params[] = { 1053 std::make_pair(StringRef(), QualType()) // __context with shared vars 1054 }; 1055 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1056 Params); 1057 break; 1058 } 1059 case OMPD_single: { 1060 Sema::CapturedParamNameType Params[] = { 1061 std::make_pair(StringRef(), QualType()) // __context with shared vars 1062 }; 1063 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1064 Params); 1065 break; 1066 } 1067 case OMPD_master: { 1068 Sema::CapturedParamNameType Params[] = { 1069 std::make_pair(StringRef(), QualType()) // __context with shared vars 1070 }; 1071 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1072 Params); 1073 break; 1074 } 1075 case OMPD_critical: { 1076 Sema::CapturedParamNameType Params[] = { 1077 std::make_pair(StringRef(), QualType()) // __context with shared vars 1078 }; 1079 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1080 Params); 1081 break; 1082 } 1083 case OMPD_parallel_for: { 1084 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1085 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty); 1086 Sema::CapturedParamNameType Params[] = { 1087 std::make_pair(".global_tid.", KmpInt32PtrTy), 1088 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1089 std::make_pair(StringRef(), QualType()) // __context with shared vars 1090 }; 1091 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1092 Params); 1093 break; 1094 } 1095 case OMPD_parallel_for_simd: { 1096 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1097 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty); 1098 Sema::CapturedParamNameType Params[] = { 1099 std::make_pair(".global_tid.", KmpInt32PtrTy), 1100 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1101 std::make_pair(StringRef(), QualType()) // __context with shared vars 1102 }; 1103 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1104 Params); 1105 break; 1106 } 1107 case OMPD_parallel_sections: { 1108 Sema::CapturedParamNameType Params[] = { 1109 std::make_pair(StringRef(), QualType()) // __context with shared vars 1110 }; 1111 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1112 Params); 1113 break; 1114 } 1115 case OMPD_task: { 1116 Sema::CapturedParamNameType Params[] = { 1117 std::make_pair(StringRef(), QualType()) // __context with shared vars 1118 }; 1119 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1120 Params); 1121 break; 1122 } 1123 case OMPD_taskyield: { 1124 Sema::CapturedParamNameType Params[] = { 1125 std::make_pair(StringRef(), QualType()) // __context with shared vars 1126 }; 1127 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1128 Params); 1129 break; 1130 } 1131 case OMPD_barrier: { 1132 Sema::CapturedParamNameType Params[] = { 1133 std::make_pair(StringRef(), QualType()) // __context with shared vars 1134 }; 1135 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1136 Params); 1137 break; 1138 } 1139 case OMPD_taskwait: { 1140 Sema::CapturedParamNameType Params[] = { 1141 std::make_pair(StringRef(), QualType()) // __context with shared vars 1142 }; 1143 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1144 Params); 1145 break; 1146 } 1147 case OMPD_flush: { 1148 Sema::CapturedParamNameType Params[] = { 1149 std::make_pair(StringRef(), QualType()) // __context with shared vars 1150 }; 1151 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1152 Params); 1153 break; 1154 } 1155 case OMPD_ordered: { 1156 Sema::CapturedParamNameType Params[] = { 1157 std::make_pair(StringRef(), QualType()) // __context with shared vars 1158 }; 1159 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1160 Params); 1161 break; 1162 } 1163 case OMPD_atomic: { 1164 Sema::CapturedParamNameType Params[] = { 1165 std::make_pair(StringRef(), QualType()) // __context with shared vars 1166 }; 1167 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1168 Params); 1169 break; 1170 } 1171 case OMPD_target: { 1172 Sema::CapturedParamNameType Params[] = { 1173 std::make_pair(StringRef(), QualType()) // __context with shared vars 1174 }; 1175 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1176 Params); 1177 break; 1178 } 1179 case OMPD_teams: { 1180 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1181 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty); 1182 Sema::CapturedParamNameType Params[] = { 1183 std::make_pair(".global_tid.", KmpInt32PtrTy), 1184 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1185 std::make_pair(StringRef(), QualType()) // __context with shared vars 1186 }; 1187 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1188 Params); 1189 break; 1190 } 1191 case OMPD_threadprivate: 1192 llvm_unreachable("OpenMP Directive is not allowed"); 1193 case OMPD_unknown: 1194 llvm_unreachable("Unknown OpenMP directive"); 1195 } 1196 } 1197 1198 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 1199 OpenMPDirectiveKind CurrentRegion, 1200 const DeclarationNameInfo &CurrentName, 1201 SourceLocation StartLoc) { 1202 // Allowed nesting of constructs 1203 // +------------------+-----------------+------------------------------------+ 1204 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)| 1205 // +------------------+-----------------+------------------------------------+ 1206 // | parallel | parallel | * | 1207 // | parallel | for | * | 1208 // | parallel | for simd | * | 1209 // | parallel | master | * | 1210 // | parallel | critical | * | 1211 // | parallel | simd | * | 1212 // | parallel | sections | * | 1213 // | parallel | section | + | 1214 // | parallel | single | * | 1215 // | parallel | parallel for | * | 1216 // | parallel |parallel for simd| * | 1217 // | parallel |parallel sections| * | 1218 // | parallel | task | * | 1219 // | parallel | taskyield | * | 1220 // | parallel | barrier | * | 1221 // | parallel | taskwait | * | 1222 // | parallel | flush | * | 1223 // | parallel | ordered | + | 1224 // | parallel | atomic | * | 1225 // | parallel | target | * | 1226 // | parallel | teams | + | 1227 // +------------------+-----------------+------------------------------------+ 1228 // | for | parallel | * | 1229 // | for | for | + | 1230 // | for | for simd | + | 1231 // | for | master | + | 1232 // | for | critical | * | 1233 // | for | simd | * | 1234 // | for | sections | + | 1235 // | for | section | + | 1236 // | for | single | + | 1237 // | for | parallel for | * | 1238 // | for |parallel for simd| * | 1239 // | for |parallel sections| * | 1240 // | for | task | * | 1241 // | for | taskyield | * | 1242 // | for | barrier | + | 1243 // | for | taskwait | * | 1244 // | for | flush | * | 1245 // | for | ordered | * (if construct is ordered) | 1246 // | for | atomic | * | 1247 // | for | target | * | 1248 // | for | teams | + | 1249 // +------------------+-----------------+------------------------------------+ 1250 // | master | parallel | * | 1251 // | master | for | + | 1252 // | master | for simd | + | 1253 // | master | master | * | 1254 // | master | critical | * | 1255 // | master | simd | * | 1256 // | master | sections | + | 1257 // | master | section | + | 1258 // | master | single | + | 1259 // | master | parallel for | * | 1260 // | master |parallel for simd| * | 1261 // | master |parallel sections| * | 1262 // | master | task | * | 1263 // | master | taskyield | * | 1264 // | master | barrier | + | 1265 // | master | taskwait | * | 1266 // | master | flush | * | 1267 // | master | ordered | + | 1268 // | master | atomic | * | 1269 // | master | target | * | 1270 // | master | teams | + | 1271 // +------------------+-----------------+------------------------------------+ 1272 // | critical | parallel | * | 1273 // | critical | for | + | 1274 // | critical | for simd | + | 1275 // | critical | master | * | 1276 // | critical | critical | * (should have different names) | 1277 // | critical | simd | * | 1278 // | critical | sections | + | 1279 // | critical | section | + | 1280 // | critical | single | + | 1281 // | critical | parallel for | * | 1282 // | critical |parallel for simd| * | 1283 // | critical |parallel sections| * | 1284 // | critical | task | * | 1285 // | critical | taskyield | * | 1286 // | critical | barrier | + | 1287 // | critical | taskwait | * | 1288 // | critical | ordered | + | 1289 // | critical | atomic | * | 1290 // | critical | target | * | 1291 // | critical | teams | + | 1292 // +------------------+-----------------+------------------------------------+ 1293 // | simd | parallel | | 1294 // | simd | for | | 1295 // | simd | for simd | | 1296 // | simd | master | | 1297 // | simd | critical | | 1298 // | simd | simd | | 1299 // | simd | sections | | 1300 // | simd | section | | 1301 // | simd | single | | 1302 // | simd | parallel for | | 1303 // | simd |parallel for simd| | 1304 // | simd |parallel sections| | 1305 // | simd | task | | 1306 // | simd | taskyield | | 1307 // | simd | barrier | | 1308 // | simd | taskwait | | 1309 // | simd | flush | | 1310 // | simd | ordered | | 1311 // | simd | atomic | | 1312 // | simd | target | | 1313 // | simd | teams | | 1314 // +------------------+-----------------+------------------------------------+ 1315 // | for simd | parallel | | 1316 // | for simd | for | | 1317 // | for simd | for simd | | 1318 // | for simd | master | | 1319 // | for simd | critical | | 1320 // | for simd | simd | | 1321 // | for simd | sections | | 1322 // | for simd | section | | 1323 // | for simd | single | | 1324 // | for simd | parallel for | | 1325 // | for simd |parallel for simd| | 1326 // | for simd |parallel sections| | 1327 // | for simd | task | | 1328 // | for simd | taskyield | | 1329 // | for simd | barrier | | 1330 // | for simd | taskwait | | 1331 // | for simd | flush | | 1332 // | for simd | ordered | | 1333 // | for simd | atomic | | 1334 // | for simd | target | | 1335 // | for simd | teams | | 1336 // +------------------+-----------------+------------------------------------+ 1337 // | parallel for simd| parallel | | 1338 // | parallel for simd| for | | 1339 // | parallel for simd| for simd | | 1340 // | parallel for simd| master | | 1341 // | parallel for simd| critical | | 1342 // | parallel for simd| simd | | 1343 // | parallel for simd| sections | | 1344 // | parallel for simd| section | | 1345 // | parallel for simd| single | | 1346 // | parallel for simd| parallel for | | 1347 // | parallel for simd|parallel for simd| | 1348 // | parallel for simd|parallel sections| | 1349 // | parallel for simd| task | | 1350 // | parallel for simd| taskyield | | 1351 // | parallel for simd| barrier | | 1352 // | parallel for simd| taskwait | | 1353 // | parallel for simd| flush | | 1354 // | parallel for simd| ordered | | 1355 // | parallel for simd| atomic | | 1356 // | parallel for simd| target | | 1357 // | parallel for simd| teams | | 1358 // +------------------+-----------------+------------------------------------+ 1359 // | sections | parallel | * | 1360 // | sections | for | + | 1361 // | sections | for simd | + | 1362 // | sections | master | + | 1363 // | sections | critical | * | 1364 // | sections | simd | * | 1365 // | sections | sections | + | 1366 // | sections | section | * | 1367 // | sections | single | + | 1368 // | sections | parallel for | * | 1369 // | sections |parallel for simd| * | 1370 // | sections |parallel sections| * | 1371 // | sections | task | * | 1372 // | sections | taskyield | * | 1373 // | sections | barrier | + | 1374 // | sections | taskwait | * | 1375 // | sections | flush | * | 1376 // | sections | ordered | + | 1377 // | sections | atomic | * | 1378 // | sections | target | * | 1379 // | sections | teams | + | 1380 // +------------------+-----------------+------------------------------------+ 1381 // | section | parallel | * | 1382 // | section | for | + | 1383 // | section | for simd | + | 1384 // | section | master | + | 1385 // | section | critical | * | 1386 // | section | simd | * | 1387 // | section | sections | + | 1388 // | section | section | + | 1389 // | section | single | + | 1390 // | section | parallel for | * | 1391 // | section |parallel for simd| * | 1392 // | section |parallel sections| * | 1393 // | section | task | * | 1394 // | section | taskyield | * | 1395 // | section | barrier | + | 1396 // | section | taskwait | * | 1397 // | section | flush | * | 1398 // | section | ordered | + | 1399 // | section | atomic | * | 1400 // | section | target | * | 1401 // | section | teams | + | 1402 // +------------------+-----------------+------------------------------------+ 1403 // | single | parallel | * | 1404 // | single | for | + | 1405 // | single | for simd | + | 1406 // | single | master | + | 1407 // | single | critical | * | 1408 // | single | simd | * | 1409 // | single | sections | + | 1410 // | single | section | + | 1411 // | single | single | + | 1412 // | single | parallel for | * | 1413 // | single |parallel for simd| * | 1414 // | single |parallel sections| * | 1415 // | single | task | * | 1416 // | single | taskyield | * | 1417 // | single | barrier | + | 1418 // | single | taskwait | * | 1419 // | single | flush | * | 1420 // | single | ordered | + | 1421 // | single | atomic | * | 1422 // | single | target | * | 1423 // | single | teams | + | 1424 // +------------------+-----------------+------------------------------------+ 1425 // | parallel for | parallel | * | 1426 // | parallel for | for | + | 1427 // | parallel for | for simd | + | 1428 // | parallel for | master | + | 1429 // | parallel for | critical | * | 1430 // | parallel for | simd | * | 1431 // | parallel for | sections | + | 1432 // | parallel for | section | + | 1433 // | parallel for | single | + | 1434 // | parallel for | parallel for | * | 1435 // | parallel for |parallel for simd| * | 1436 // | parallel for |parallel sections| * | 1437 // | parallel for | task | * | 1438 // | parallel for | taskyield | * | 1439 // | parallel for | barrier | + | 1440 // | parallel for | taskwait | * | 1441 // | parallel for | flush | * | 1442 // | parallel for | ordered | * (if construct is ordered) | 1443 // | parallel for | atomic | * | 1444 // | parallel for | target | * | 1445 // | parallel for | teams | + | 1446 // +------------------+-----------------+------------------------------------+ 1447 // | parallel sections| parallel | * | 1448 // | parallel sections| for | + | 1449 // | parallel sections| for simd | + | 1450 // | parallel sections| master | + | 1451 // | parallel sections| critical | + | 1452 // | parallel sections| simd | * | 1453 // | parallel sections| sections | + | 1454 // | parallel sections| section | * | 1455 // | parallel sections| single | + | 1456 // | parallel sections| parallel for | * | 1457 // | parallel sections|parallel for simd| * | 1458 // | parallel sections|parallel sections| * | 1459 // | parallel sections| task | * | 1460 // | parallel sections| taskyield | * | 1461 // | parallel sections| barrier | + | 1462 // | parallel sections| taskwait | * | 1463 // | parallel sections| flush | * | 1464 // | parallel sections| ordered | + | 1465 // | parallel sections| atomic | * | 1466 // | parallel sections| target | * | 1467 // | parallel sections| teams | + | 1468 // +------------------+-----------------+------------------------------------+ 1469 // | task | parallel | * | 1470 // | task | for | + | 1471 // | task | for simd | + | 1472 // | task | master | + | 1473 // | task | critical | * | 1474 // | task | simd | * | 1475 // | task | sections | + | 1476 // | task | section | + | 1477 // | task | single | + | 1478 // | task | parallel for | * | 1479 // | task |parallel for simd| * | 1480 // | task |parallel sections| * | 1481 // | task | task | * | 1482 // | task | taskyield | * | 1483 // | task | barrier | + | 1484 // | task | taskwait | * | 1485 // | task | flush | * | 1486 // | task | ordered | + | 1487 // | task | atomic | * | 1488 // | task | target | * | 1489 // | task | teams | + | 1490 // +------------------+-----------------+------------------------------------+ 1491 // | ordered | parallel | * | 1492 // | ordered | for | + | 1493 // | ordered | for simd | + | 1494 // | ordered | master | * | 1495 // | ordered | critical | * | 1496 // | ordered | simd | * | 1497 // | ordered | sections | + | 1498 // | ordered | section | + | 1499 // | ordered | single | + | 1500 // | ordered | parallel for | * | 1501 // | ordered |parallel for simd| * | 1502 // | ordered |parallel sections| * | 1503 // | ordered | task | * | 1504 // | ordered | taskyield | * | 1505 // | ordered | barrier | + | 1506 // | ordered | taskwait | * | 1507 // | ordered | flush | * | 1508 // | ordered | ordered | + | 1509 // | ordered | atomic | * | 1510 // | ordered | target | * | 1511 // | ordered | teams | + | 1512 // +------------------+-----------------+------------------------------------+ 1513 // | atomic | parallel | | 1514 // | atomic | for | | 1515 // | atomic | for simd | | 1516 // | atomic | master | | 1517 // | atomic | critical | | 1518 // | atomic | simd | | 1519 // | atomic | sections | | 1520 // | atomic | section | | 1521 // | atomic | single | | 1522 // | atomic | parallel for | | 1523 // | atomic |parallel for simd| | 1524 // | atomic |parallel sections| | 1525 // | atomic | task | | 1526 // | atomic | taskyield | | 1527 // | atomic | barrier | | 1528 // | atomic | taskwait | | 1529 // | atomic | flush | | 1530 // | atomic | ordered | | 1531 // | atomic | atomic | | 1532 // | atomic | target | | 1533 // | atomic | teams | | 1534 // +------------------+-----------------+------------------------------------+ 1535 // | target | parallel | * | 1536 // | target | for | * | 1537 // | target | for simd | * | 1538 // | target | master | * | 1539 // | target | critical | * | 1540 // | target | simd | * | 1541 // | target | sections | * | 1542 // | target | section | * | 1543 // | target | single | * | 1544 // | target | parallel for | * | 1545 // | target |parallel for simd| * | 1546 // | target |parallel sections| * | 1547 // | target | task | * | 1548 // | target | taskyield | * | 1549 // | target | barrier | * | 1550 // | target | taskwait | * | 1551 // | target | flush | * | 1552 // | target | ordered | * | 1553 // | target | atomic | * | 1554 // | target | target | * | 1555 // | target | teams | * | 1556 // +------------------+-----------------+------------------------------------+ 1557 // | teams | parallel | * | 1558 // | teams | for | + | 1559 // | teams | for simd | + | 1560 // | teams | master | + | 1561 // | teams | critical | + | 1562 // | teams | simd | + | 1563 // | teams | sections | + | 1564 // | teams | section | + | 1565 // | teams | single | + | 1566 // | teams | parallel for | * | 1567 // | teams |parallel for simd| * | 1568 // | teams |parallel sections| * | 1569 // | teams | task | + | 1570 // | teams | taskyield | + | 1571 // | teams | barrier | + | 1572 // | teams | taskwait | + | 1573 // | teams | flush | + | 1574 // | teams | ordered | + | 1575 // | teams | atomic | + | 1576 // | teams | target | + | 1577 // | teams | teams | + | 1578 // +------------------+-----------------+------------------------------------+ 1579 if (Stack->getCurScope()) { 1580 auto ParentRegion = Stack->getParentDirective(); 1581 bool NestingProhibited = false; 1582 bool CloseNesting = true; 1583 enum { 1584 NoRecommend, 1585 ShouldBeInParallelRegion, 1586 ShouldBeInOrderedRegion, 1587 ShouldBeInTargetRegion 1588 } Recommend = NoRecommend; 1589 if (isOpenMPSimdDirective(ParentRegion)) { 1590 // OpenMP [2.16, Nesting of Regions] 1591 // OpenMP constructs may not be nested inside a simd region. 1592 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd); 1593 return true; 1594 } 1595 if (ParentRegion == OMPD_atomic) { 1596 // OpenMP [2.16, Nesting of Regions] 1597 // OpenMP constructs may not be nested inside an atomic region. 1598 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 1599 return true; 1600 } 1601 if (CurrentRegion == OMPD_section) { 1602 // OpenMP [2.7.2, sections Construct, Restrictions] 1603 // Orphaned section directives are prohibited. That is, the section 1604 // directives must appear within the sections construct and must not be 1605 // encountered elsewhere in the sections region. 1606 if (ParentRegion != OMPD_sections && 1607 ParentRegion != OMPD_parallel_sections) { 1608 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 1609 << (ParentRegion != OMPD_unknown) 1610 << getOpenMPDirectiveName(ParentRegion); 1611 return true; 1612 } 1613 return false; 1614 } 1615 // Allow some constructs to be orphaned (they could be used in functions, 1616 // called from OpenMP regions with the required preconditions). 1617 if (ParentRegion == OMPD_unknown) 1618 return false; 1619 if (CurrentRegion == OMPD_master) { 1620 // OpenMP [2.16, Nesting of Regions] 1621 // A master region may not be closely nested inside a worksharing, 1622 // atomic, or explicit task region. 1623 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 1624 ParentRegion == OMPD_task; 1625 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 1626 // OpenMP [2.16, Nesting of Regions] 1627 // A critical region may not be nested (closely or otherwise) inside a 1628 // critical region with the same name. Note that this restriction is not 1629 // sufficient to prevent deadlock. 1630 SourceLocation PreviousCriticalLoc; 1631 bool DeadLock = 1632 Stack->hasDirective([CurrentName, &PreviousCriticalLoc]( 1633 OpenMPDirectiveKind K, 1634 const DeclarationNameInfo &DNI, 1635 SourceLocation Loc) 1636 ->bool { 1637 if (K == OMPD_critical && 1638 DNI.getName() == CurrentName.getName()) { 1639 PreviousCriticalLoc = Loc; 1640 return true; 1641 } else 1642 return false; 1643 }, 1644 false /* skip top directive */); 1645 if (DeadLock) { 1646 SemaRef.Diag(StartLoc, 1647 diag::err_omp_prohibited_region_critical_same_name) 1648 << CurrentName.getName(); 1649 if (PreviousCriticalLoc.isValid()) 1650 SemaRef.Diag(PreviousCriticalLoc, 1651 diag::note_omp_previous_critical_region); 1652 return true; 1653 } 1654 } else if (CurrentRegion == OMPD_barrier) { 1655 // OpenMP [2.16, Nesting of Regions] 1656 // A barrier region may not be closely nested inside a worksharing, 1657 // explicit task, critical, ordered, atomic, or master region. 1658 NestingProhibited = 1659 isOpenMPWorksharingDirective(ParentRegion) || 1660 ParentRegion == OMPD_task || ParentRegion == OMPD_master || 1661 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 1662 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 1663 !isOpenMPParallelDirective(CurrentRegion)) { 1664 // OpenMP [2.16, Nesting of Regions] 1665 // A worksharing region may not be closely nested inside a worksharing, 1666 // explicit task, critical, ordered, atomic, or master region. 1667 NestingProhibited = 1668 isOpenMPWorksharingDirective(ParentRegion) || 1669 ParentRegion == OMPD_task || ParentRegion == OMPD_master || 1670 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 1671 Recommend = ShouldBeInParallelRegion; 1672 } else if (CurrentRegion == OMPD_ordered) { 1673 // OpenMP [2.16, Nesting of Regions] 1674 // An ordered region may not be closely nested inside a critical, 1675 // atomic, or explicit task region. 1676 // An ordered region must be closely nested inside a loop region (or 1677 // parallel loop region) with an ordered clause. 1678 NestingProhibited = ParentRegion == OMPD_critical || 1679 ParentRegion == OMPD_task || 1680 !Stack->isParentOrderedRegion(); 1681 Recommend = ShouldBeInOrderedRegion; 1682 } else if (isOpenMPTeamsDirective(CurrentRegion)) { 1683 // OpenMP [2.16, Nesting of Regions] 1684 // If specified, a teams construct must be contained within a target 1685 // construct. 1686 NestingProhibited = ParentRegion != OMPD_target; 1687 Recommend = ShouldBeInTargetRegion; 1688 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 1689 } 1690 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) { 1691 // OpenMP [2.16, Nesting of Regions] 1692 // distribute, parallel, parallel sections, parallel workshare, and the 1693 // parallel loop and parallel loop SIMD constructs are the only OpenMP 1694 // constructs that can be closely nested in the teams region. 1695 // TODO: add distribute directive. 1696 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion); 1697 Recommend = ShouldBeInParallelRegion; 1698 } 1699 if (NestingProhibited) { 1700 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 1701 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend 1702 << getOpenMPDirectiveName(CurrentRegion); 1703 return true; 1704 } 1705 } 1706 return false; 1707 } 1708 1709 StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind, 1710 const DeclarationNameInfo &DirName, 1711 ArrayRef<OMPClause *> Clauses, 1712 Stmt *AStmt, 1713 SourceLocation StartLoc, 1714 SourceLocation EndLoc) { 1715 StmtResult Res = StmtError(); 1716 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc)) 1717 return StmtError(); 1718 1719 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 1720 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA; 1721 bool ErrorFound = false; 1722 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 1723 if (AStmt) { 1724 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 1725 1726 // Check default data sharing attributes for referenced variables. 1727 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 1728 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt()); 1729 if (DSAChecker.isErrorFound()) 1730 return StmtError(); 1731 // Generate list of implicitly defined firstprivate variables. 1732 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 1733 1734 if (!DSAChecker.getImplicitFirstprivate().empty()) { 1735 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 1736 DSAChecker.getImplicitFirstprivate(), SourceLocation(), 1737 SourceLocation(), SourceLocation())) { 1738 ClausesWithImplicit.push_back(Implicit); 1739 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 1740 DSAChecker.getImplicitFirstprivate().size(); 1741 } else 1742 ErrorFound = true; 1743 } 1744 } 1745 1746 switch (Kind) { 1747 case OMPD_parallel: 1748 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 1749 EndLoc); 1750 break; 1751 case OMPD_simd: 1752 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 1753 VarsWithInheritedDSA); 1754 break; 1755 case OMPD_for: 1756 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 1757 VarsWithInheritedDSA); 1758 break; 1759 case OMPD_for_simd: 1760 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 1761 EndLoc, VarsWithInheritedDSA); 1762 break; 1763 case OMPD_sections: 1764 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 1765 EndLoc); 1766 break; 1767 case OMPD_section: 1768 assert(ClausesWithImplicit.empty() && 1769 "No clauses are allowed for 'omp section' directive"); 1770 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 1771 break; 1772 case OMPD_single: 1773 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 1774 EndLoc); 1775 break; 1776 case OMPD_master: 1777 assert(ClausesWithImplicit.empty() && 1778 "No clauses are allowed for 'omp master' directive"); 1779 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 1780 break; 1781 case OMPD_critical: 1782 assert(ClausesWithImplicit.empty() && 1783 "No clauses are allowed for 'omp critical' directive"); 1784 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc); 1785 break; 1786 case OMPD_parallel_for: 1787 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 1788 EndLoc, VarsWithInheritedDSA); 1789 break; 1790 case OMPD_parallel_for_simd: 1791 Res = ActOnOpenMPParallelForSimdDirective( 1792 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 1793 break; 1794 case OMPD_parallel_sections: 1795 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 1796 StartLoc, EndLoc); 1797 break; 1798 case OMPD_task: 1799 Res = 1800 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 1801 break; 1802 case OMPD_taskyield: 1803 assert(ClausesWithImplicit.empty() && 1804 "No clauses are allowed for 'omp taskyield' directive"); 1805 assert(AStmt == nullptr && 1806 "No associated statement allowed for 'omp taskyield' directive"); 1807 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 1808 break; 1809 case OMPD_barrier: 1810 assert(ClausesWithImplicit.empty() && 1811 "No clauses are allowed for 'omp barrier' directive"); 1812 assert(AStmt == nullptr && 1813 "No associated statement allowed for 'omp barrier' directive"); 1814 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 1815 break; 1816 case OMPD_taskwait: 1817 assert(ClausesWithImplicit.empty() && 1818 "No clauses are allowed for 'omp taskwait' directive"); 1819 assert(AStmt == nullptr && 1820 "No associated statement allowed for 'omp taskwait' directive"); 1821 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 1822 break; 1823 case OMPD_flush: 1824 assert(AStmt == nullptr && 1825 "No associated statement allowed for 'omp flush' directive"); 1826 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 1827 break; 1828 case OMPD_ordered: 1829 assert(ClausesWithImplicit.empty() && 1830 "No clauses are allowed for 'omp ordered' directive"); 1831 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc); 1832 break; 1833 case OMPD_atomic: 1834 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 1835 EndLoc); 1836 break; 1837 case OMPD_teams: 1838 Res = 1839 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 1840 break; 1841 case OMPD_target: 1842 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 1843 EndLoc); 1844 break; 1845 case OMPD_threadprivate: 1846 llvm_unreachable("OpenMP Directive is not allowed"); 1847 case OMPD_unknown: 1848 llvm_unreachable("Unknown OpenMP directive"); 1849 } 1850 1851 for (auto P : VarsWithInheritedDSA) { 1852 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 1853 << P.first << P.second->getSourceRange(); 1854 } 1855 if (!VarsWithInheritedDSA.empty()) 1856 return StmtError(); 1857 1858 if (ErrorFound) 1859 return StmtError(); 1860 return Res; 1861 } 1862 1863 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 1864 Stmt *AStmt, 1865 SourceLocation StartLoc, 1866 SourceLocation EndLoc) { 1867 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 1868 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 1869 // 1.2.2 OpenMP Language Terminology 1870 // Structured block - An executable statement with a single entry at the 1871 // top and a single exit at the bottom. 1872 // The point of exit cannot be a branch out of the structured block. 1873 // longjmp() and throw() must not violate the entry/exit criteria. 1874 CS->getCapturedDecl()->setNothrow(); 1875 1876 getCurFunction()->setHasBranchProtectedScope(); 1877 1878 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 1879 AStmt); 1880 } 1881 1882 namespace { 1883 /// \brief Helper class for checking canonical form of the OpenMP loops and 1884 /// extracting iteration space of each loop in the loop nest, that will be used 1885 /// for IR generation. 1886 class OpenMPIterationSpaceChecker { 1887 /// \brief Reference to Sema. 1888 Sema &SemaRef; 1889 /// \brief A location for diagnostics (when there is no some better location). 1890 SourceLocation DefaultLoc; 1891 /// \brief A location for diagnostics (when increment is not compatible). 1892 SourceLocation ConditionLoc; 1893 /// \brief A source location for referring to loop init later. 1894 SourceRange InitSrcRange; 1895 /// \brief A source location for referring to condition later. 1896 SourceRange ConditionSrcRange; 1897 /// \brief A source location for referring to increment later. 1898 SourceRange IncrementSrcRange; 1899 /// \brief Loop variable. 1900 VarDecl *Var; 1901 /// \brief Reference to loop variable. 1902 DeclRefExpr *VarRef; 1903 /// \brief Lower bound (initializer for the var). 1904 Expr *LB; 1905 /// \brief Upper bound. 1906 Expr *UB; 1907 /// \brief Loop step (increment). 1908 Expr *Step; 1909 /// \brief This flag is true when condition is one of: 1910 /// Var < UB 1911 /// Var <= UB 1912 /// UB > Var 1913 /// UB >= Var 1914 bool TestIsLessOp; 1915 /// \brief This flag is true when condition is strict ( < or > ). 1916 bool TestIsStrictOp; 1917 /// \brief This flag is true when step is subtracted on each iteration. 1918 bool SubtractStep; 1919 1920 public: 1921 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 1922 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc), 1923 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()), 1924 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr), 1925 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false), 1926 TestIsStrictOp(false), SubtractStep(false) {} 1927 /// \brief Check init-expr for canonical loop form and save loop counter 1928 /// variable - #Var and its initialization value - #LB. 1929 bool CheckInit(Stmt *S); 1930 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 1931 /// for less/greater and for strict/non-strict comparison. 1932 bool CheckCond(Expr *S); 1933 /// \brief Check incr-expr for canonical loop form and return true if it 1934 /// does not conform, otherwise save loop step (#Step). 1935 bool CheckInc(Expr *S); 1936 /// \brief Return the loop counter variable. 1937 VarDecl *GetLoopVar() const { return Var; } 1938 /// \brief Return the reference expression to loop counter variable. 1939 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; } 1940 /// \brief Source range of the loop init. 1941 SourceRange GetInitSrcRange() const { return InitSrcRange; } 1942 /// \brief Source range of the loop condition. 1943 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 1944 /// \brief Source range of the loop increment. 1945 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 1946 /// \brief True if the step should be subtracted. 1947 bool ShouldSubtractStep() const { return SubtractStep; } 1948 /// \brief Build the expression to calculate the number of iterations. 1949 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const; 1950 /// \brief Build reference expression to the counter be used for codegen. 1951 Expr *BuildCounterVar() const; 1952 /// \brief Build initization of the counter be used for codegen. 1953 Expr *BuildCounterInit() const; 1954 /// \brief Build step of the counter be used for codegen. 1955 Expr *BuildCounterStep() const; 1956 /// \brief Return true if any expression is dependent. 1957 bool Dependent() const; 1958 1959 private: 1960 /// \brief Check the right-hand side of an assignment in the increment 1961 /// expression. 1962 bool CheckIncRHS(Expr *RHS); 1963 /// \brief Helper to set loop counter variable and its initializer. 1964 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB); 1965 /// \brief Helper to set upper bound. 1966 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR, 1967 const SourceLocation &SL); 1968 /// \brief Helper to set loop increment. 1969 bool SetStep(Expr *NewStep, bool Subtract); 1970 }; 1971 1972 bool OpenMPIterationSpaceChecker::Dependent() const { 1973 if (!Var) { 1974 assert(!LB && !UB && !Step); 1975 return false; 1976 } 1977 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) || 1978 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent()); 1979 } 1980 1981 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar, 1982 DeclRefExpr *NewVarRefExpr, 1983 Expr *NewLB) { 1984 // State consistency checking to ensure correct usage. 1985 assert(Var == nullptr && LB == nullptr && VarRef == nullptr && 1986 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 1987 if (!NewVar || !NewLB) 1988 return true; 1989 Var = NewVar; 1990 VarRef = NewVarRefExpr; 1991 LB = NewLB; 1992 return false; 1993 } 1994 1995 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 1996 const SourceRange &SR, 1997 const SourceLocation &SL) { 1998 // State consistency checking to ensure correct usage. 1999 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && 2000 !TestIsLessOp && !TestIsStrictOp); 2001 if (!NewUB) 2002 return true; 2003 UB = NewUB; 2004 TestIsLessOp = LessOp; 2005 TestIsStrictOp = StrictOp; 2006 ConditionSrcRange = SR; 2007 ConditionLoc = SL; 2008 return false; 2009 } 2010 2011 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 2012 // State consistency checking to ensure correct usage. 2013 assert(Var != nullptr && LB != nullptr && Step == nullptr); 2014 if (!NewStep) 2015 return true; 2016 if (!NewStep->isValueDependent()) { 2017 // Check that the step is integer expression. 2018 SourceLocation StepLoc = NewStep->getLocStart(); 2019 ExprResult Val = 2020 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep); 2021 if (Val.isInvalid()) 2022 return true; 2023 NewStep = Val.get(); 2024 2025 // OpenMP [2.6, Canonical Loop Form, Restrictions] 2026 // If test-expr is of form var relational-op b and relational-op is < or 2027 // <= then incr-expr must cause var to increase on each iteration of the 2028 // loop. If test-expr is of form var relational-op b and relational-op is 2029 // > or >= then incr-expr must cause var to decrease on each iteration of 2030 // the loop. 2031 // If test-expr is of form b relational-op var and relational-op is < or 2032 // <= then incr-expr must cause var to decrease on each iteration of the 2033 // loop. If test-expr is of form b relational-op var and relational-op is 2034 // > or >= then incr-expr must cause var to increase on each iteration of 2035 // the loop. 2036 llvm::APSInt Result; 2037 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 2038 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 2039 bool IsConstNeg = 2040 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 2041 bool IsConstPos = 2042 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 2043 bool IsConstZero = IsConstant && !Result.getBoolValue(); 2044 if (UB && (IsConstZero || 2045 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 2046 : (IsConstPos || (IsUnsigned && !Subtract))))) { 2047 SemaRef.Diag(NewStep->getExprLoc(), 2048 diag::err_omp_loop_incr_not_compatible) 2049 << Var << TestIsLessOp << NewStep->getSourceRange(); 2050 SemaRef.Diag(ConditionLoc, 2051 diag::note_omp_loop_cond_requres_compatible_incr) 2052 << TestIsLessOp << ConditionSrcRange; 2053 return true; 2054 } 2055 if (TestIsLessOp == Subtract) { 2056 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, 2057 NewStep).get(); 2058 Subtract = !Subtract; 2059 } 2060 } 2061 2062 Step = NewStep; 2063 SubtractStep = Subtract; 2064 return false; 2065 } 2066 2067 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) { 2068 // Check init-expr for canonical loop form and save loop counter 2069 // variable - #Var and its initialization value - #LB. 2070 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 2071 // var = lb 2072 // integer-type var = lb 2073 // random-access-iterator-type var = lb 2074 // pointer-type var = lb 2075 // 2076 if (!S) { 2077 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 2078 return true; 2079 } 2080 InitSrcRange = S->getSourceRange(); 2081 if (Expr *E = dyn_cast<Expr>(S)) 2082 S = E->IgnoreParens(); 2083 if (auto BO = dyn_cast<BinaryOperator>(S)) { 2084 if (BO->getOpcode() == BO_Assign) 2085 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) 2086 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE, 2087 BO->getRHS()); 2088 } else if (auto DS = dyn_cast<DeclStmt>(S)) { 2089 if (DS->isSingleDecl()) { 2090 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 2091 if (Var->hasInit()) { 2092 // Accept non-canonical init form here but emit ext. warning. 2093 if (Var->getInitStyle() != VarDecl::CInit) 2094 SemaRef.Diag(S->getLocStart(), 2095 diag::ext_omp_loop_not_canonical_init) 2096 << S->getSourceRange(); 2097 return SetVarAndLB(Var, nullptr, Var->getInit()); 2098 } 2099 } 2100 } 2101 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) 2102 if (CE->getOperator() == OO_Equal) 2103 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0))) 2104 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE, 2105 CE->getArg(1)); 2106 2107 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 2108 << S->getSourceRange(); 2109 return true; 2110 } 2111 2112 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 2113 /// variable (which may be the loop variable) if possible. 2114 static const VarDecl *GetInitVarDecl(const Expr *E) { 2115 if (!E) 2116 return nullptr; 2117 E = E->IgnoreParenImpCasts(); 2118 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 2119 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 2120 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 && 2121 CE->getArg(0) != nullptr) 2122 E = CE->getArg(0)->IgnoreParenImpCasts(); 2123 auto DRE = dyn_cast_or_null<DeclRefExpr>(E); 2124 if (!DRE) 2125 return nullptr; 2126 return dyn_cast<VarDecl>(DRE->getDecl()); 2127 } 2128 2129 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 2130 // Check test-expr for canonical form, save upper-bound UB, flags for 2131 // less/greater and for strict/non-strict comparison. 2132 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 2133 // var relational-op b 2134 // b relational-op var 2135 // 2136 if (!S) { 2137 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var; 2138 return true; 2139 } 2140 S = S->IgnoreParenImpCasts(); 2141 SourceLocation CondLoc = S->getLocStart(); 2142 if (auto BO = dyn_cast<BinaryOperator>(S)) { 2143 if (BO->isRelationalOp()) { 2144 if (GetInitVarDecl(BO->getLHS()) == Var) 2145 return SetUB(BO->getRHS(), 2146 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 2147 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 2148 BO->getSourceRange(), BO->getOperatorLoc()); 2149 if (GetInitVarDecl(BO->getRHS()) == Var) 2150 return SetUB(BO->getLHS(), 2151 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 2152 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 2153 BO->getSourceRange(), BO->getOperatorLoc()); 2154 } 2155 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) { 2156 if (CE->getNumArgs() == 2) { 2157 auto Op = CE->getOperator(); 2158 switch (Op) { 2159 case OO_Greater: 2160 case OO_GreaterEqual: 2161 case OO_Less: 2162 case OO_LessEqual: 2163 if (GetInitVarDecl(CE->getArg(0)) == Var) 2164 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 2165 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 2166 CE->getOperatorLoc()); 2167 if (GetInitVarDecl(CE->getArg(1)) == Var) 2168 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 2169 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 2170 CE->getOperatorLoc()); 2171 break; 2172 default: 2173 break; 2174 } 2175 } 2176 } 2177 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 2178 << S->getSourceRange() << Var; 2179 return true; 2180 } 2181 2182 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 2183 // RHS of canonical loop form increment can be: 2184 // var + incr 2185 // incr + var 2186 // var - incr 2187 // 2188 RHS = RHS->IgnoreParenImpCasts(); 2189 if (auto BO = dyn_cast<BinaryOperator>(RHS)) { 2190 if (BO->isAdditiveOp()) { 2191 bool IsAdd = BO->getOpcode() == BO_Add; 2192 if (GetInitVarDecl(BO->getLHS()) == Var) 2193 return SetStep(BO->getRHS(), !IsAdd); 2194 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var) 2195 return SetStep(BO->getLHS(), false); 2196 } 2197 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 2198 bool IsAdd = CE->getOperator() == OO_Plus; 2199 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 2200 if (GetInitVarDecl(CE->getArg(0)) == Var) 2201 return SetStep(CE->getArg(1), !IsAdd); 2202 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var) 2203 return SetStep(CE->getArg(0), false); 2204 } 2205 } 2206 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 2207 << RHS->getSourceRange() << Var; 2208 return true; 2209 } 2210 2211 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 2212 // Check incr-expr for canonical loop form and return true if it 2213 // does not conform. 2214 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 2215 // ++var 2216 // var++ 2217 // --var 2218 // var-- 2219 // var += incr 2220 // var -= incr 2221 // var = var + incr 2222 // var = incr + var 2223 // var = var - incr 2224 // 2225 if (!S) { 2226 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var; 2227 return true; 2228 } 2229 IncrementSrcRange = S->getSourceRange(); 2230 S = S->IgnoreParens(); 2231 if (auto UO = dyn_cast<UnaryOperator>(S)) { 2232 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var) 2233 return SetStep( 2234 SemaRef.ActOnIntegerConstant(UO->getLocStart(), 2235 (UO->isDecrementOp() ? -1 : 1)).get(), 2236 false); 2237 } else if (auto BO = dyn_cast<BinaryOperator>(S)) { 2238 switch (BO->getOpcode()) { 2239 case BO_AddAssign: 2240 case BO_SubAssign: 2241 if (GetInitVarDecl(BO->getLHS()) == Var) 2242 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 2243 break; 2244 case BO_Assign: 2245 if (GetInitVarDecl(BO->getLHS()) == Var) 2246 return CheckIncRHS(BO->getRHS()); 2247 break; 2248 default: 2249 break; 2250 } 2251 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) { 2252 switch (CE->getOperator()) { 2253 case OO_PlusPlus: 2254 case OO_MinusMinus: 2255 if (GetInitVarDecl(CE->getArg(0)) == Var) 2256 return SetStep( 2257 SemaRef.ActOnIntegerConstant( 2258 CE->getLocStart(), 2259 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(), 2260 false); 2261 break; 2262 case OO_PlusEqual: 2263 case OO_MinusEqual: 2264 if (GetInitVarDecl(CE->getArg(0)) == Var) 2265 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 2266 break; 2267 case OO_Equal: 2268 if (GetInitVarDecl(CE->getArg(0)) == Var) 2269 return CheckIncRHS(CE->getArg(1)); 2270 break; 2271 default: 2272 break; 2273 } 2274 } 2275 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 2276 << S->getSourceRange() << Var; 2277 return true; 2278 } 2279 2280 /// \brief Build the expression to calculate the number of iterations. 2281 Expr * 2282 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S, 2283 const bool LimitedType) const { 2284 ExprResult Diff; 2285 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() || 2286 SemaRef.getLangOpts().CPlusPlus) { 2287 // Upper - Lower 2288 Expr *Upper = TestIsLessOp ? UB : LB; 2289 Expr *Lower = TestIsLessOp ? LB : UB; 2290 2291 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 2292 2293 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) { 2294 // BuildBinOp already emitted error, this one is to point user to upper 2295 // and lower bound, and to tell what is passed to 'operator-'. 2296 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 2297 << Upper->getSourceRange() << Lower->getSourceRange(); 2298 return nullptr; 2299 } 2300 } 2301 2302 if (!Diff.isUsable()) 2303 return nullptr; 2304 2305 // Upper - Lower [- 1] 2306 if (TestIsStrictOp) 2307 Diff = SemaRef.BuildBinOp( 2308 S, DefaultLoc, BO_Sub, Diff.get(), 2309 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 2310 if (!Diff.isUsable()) 2311 return nullptr; 2312 2313 // Upper - Lower [- 1] + Step 2314 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), 2315 Step->IgnoreImplicit()); 2316 if (!Diff.isUsable()) 2317 return nullptr; 2318 2319 // Parentheses (for dumping/debugging purposes only). 2320 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 2321 if (!Diff.isUsable()) 2322 return nullptr; 2323 2324 // (Upper - Lower [- 1] + Step) / Step 2325 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), 2326 Step->IgnoreImplicit()); 2327 if (!Diff.isUsable()) 2328 return nullptr; 2329 2330 // OpenMP runtime requires 32-bit or 64-bit loop variables. 2331 if (LimitedType) { 2332 auto &C = SemaRef.Context; 2333 QualType Type = Diff.get()->getType(); 2334 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 2335 if (NewSize != C.getTypeSize(Type)) { 2336 if (NewSize < C.getTypeSize(Type)) { 2337 assert(NewSize == 64 && "incorrect loop var size"); 2338 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 2339 << InitSrcRange << ConditionSrcRange; 2340 } 2341 QualType NewType = C.getIntTypeForBitwidth( 2342 NewSize, Type->hasSignedIntegerRepresentation()); 2343 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 2344 Sema::AA_Converting, true); 2345 if (!Diff.isUsable()) 2346 return nullptr; 2347 } 2348 } 2349 2350 return Diff.get(); 2351 } 2352 2353 /// \brief Build reference expression to the counter be used for codegen. 2354 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const { 2355 return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2356 GetIncrementSrcRange().getBegin(), Var, false, 2357 DefaultLoc, Var->getType(), VK_LValue); 2358 } 2359 2360 /// \brief Build initization of the counter be used for codegen. 2361 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 2362 2363 /// \brief Build step of the counter be used for codegen. 2364 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 2365 2366 /// \brief Iteration space of a single for loop. 2367 struct LoopIterationSpace { 2368 /// \brief This expression calculates the number of iterations in the loop. 2369 /// It is always possible to calculate it before starting the loop. 2370 Expr *NumIterations; 2371 /// \brief The loop counter variable. 2372 Expr *CounterVar; 2373 /// \brief This is initializer for the initial value of #CounterVar. 2374 Expr *CounterInit; 2375 /// \brief This is step for the #CounterVar used to generate its update: 2376 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 2377 Expr *CounterStep; 2378 /// \brief Should step be subtracted? 2379 bool Subtract; 2380 /// \brief Source range of the loop init. 2381 SourceRange InitSrcRange; 2382 /// \brief Source range of the loop condition. 2383 SourceRange CondSrcRange; 2384 /// \brief Source range of the loop increment. 2385 SourceRange IncSrcRange; 2386 }; 2387 2388 /// \brief The resulting expressions built for the OpenMP loop CodeGen for the 2389 /// whole collapsed loop nest. See class OMPLoopDirective for their description. 2390 struct BuiltLoopExprs { 2391 Expr *IterationVarRef; 2392 Expr *LastIteration; 2393 Expr *CalcLastIteration; 2394 Expr *PreCond; 2395 Expr *Cond; 2396 Expr *SeparatedCond; 2397 Expr *Init; 2398 Expr *Inc; 2399 SmallVector<Expr *, 4> Counters; 2400 SmallVector<Expr *, 4> Updates; 2401 SmallVector<Expr *, 4> Finals; 2402 2403 bool builtAll() { 2404 return IterationVarRef != nullptr && LastIteration != nullptr && 2405 PreCond != nullptr && Cond != nullptr && SeparatedCond != nullptr && 2406 Init != nullptr && Inc != nullptr; 2407 } 2408 void clear(unsigned size) { 2409 IterationVarRef = nullptr; 2410 LastIteration = nullptr; 2411 CalcLastIteration = nullptr; 2412 PreCond = nullptr; 2413 Cond = nullptr; 2414 SeparatedCond = nullptr; 2415 Init = nullptr; 2416 Inc = nullptr; 2417 Counters.resize(size); 2418 Updates.resize(size); 2419 Finals.resize(size); 2420 for (unsigned i = 0; i < size; ++i) { 2421 Counters[i] = nullptr; 2422 Updates[i] = nullptr; 2423 Finals[i] = nullptr; 2424 } 2425 } 2426 }; 2427 2428 } // namespace 2429 2430 /// \brief Called on a for stmt to check and extract its iteration space 2431 /// for further processing (such as collapsing). 2432 static bool CheckOpenMPIterationSpace( 2433 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 2434 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 2435 Expr *NestedLoopCountExpr, 2436 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA, 2437 LoopIterationSpace &ResultIterSpace) { 2438 // OpenMP [2.6, Canonical Loop Form] 2439 // for (init-expr; test-expr; incr-expr) structured-block 2440 auto For = dyn_cast_or_null<ForStmt>(S); 2441 if (!For) { 2442 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 2443 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind) 2444 << NestedLoopCount << (CurrentNestedLoopCount > 0) 2445 << CurrentNestedLoopCount; 2446 if (NestedLoopCount > 1) 2447 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(), 2448 diag::note_omp_collapse_expr) 2449 << NestedLoopCountExpr->getSourceRange(); 2450 return true; 2451 } 2452 assert(For->getBody()); 2453 2454 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 2455 2456 // Check init. 2457 auto Init = For->getInit(); 2458 if (ISC.CheckInit(Init)) { 2459 return true; 2460 } 2461 2462 bool HasErrors = false; 2463 2464 // Check loop variable's type. 2465 auto Var = ISC.GetLoopVar(); 2466 2467 // OpenMP [2.6, Canonical Loop Form] 2468 // Var is one of the following: 2469 // A variable of signed or unsigned integer type. 2470 // For C++, a variable of a random access iterator type. 2471 // For C, a variable of a pointer type. 2472 auto VarType = Var->getType(); 2473 if (!VarType->isDependentType() && !VarType->isIntegerType() && 2474 !VarType->isPointerType() && 2475 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 2476 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 2477 << SemaRef.getLangOpts().CPlusPlus; 2478 HasErrors = true; 2479 } 2480 2481 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a 2482 // Construct 2483 // The loop iteration variable(s) in the associated for-loop(s) of a for or 2484 // parallel for construct is (are) private. 2485 // The loop iteration variable in the associated for-loop of a simd construct 2486 // with just one associated for-loop is linear with a constant-linear-step 2487 // that is the increment of the associated for-loop. 2488 // Exclude loop var from the list of variables with implicitly defined data 2489 // sharing attributes. 2490 VarsWithImplicitDSA.erase(Var); 2491 2492 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in 2493 // a Construct, C/C++]. 2494 // The loop iteration variable in the associated for-loop of a simd construct 2495 // with just one associated for-loop may be listed in a linear clause with a 2496 // constant-linear-step that is the increment of the associated for-loop. 2497 // The loop iteration variable(s) in the associated for-loop(s) of a for or 2498 // parallel for construct may be listed in a private or lastprivate clause. 2499 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false); 2500 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr(); 2501 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 2502 // declared in the loop and it is predetermined as a private. 2503 auto PredeterminedCKind = 2504 isOpenMPSimdDirective(DKind) 2505 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 2506 : OMPC_private; 2507 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 2508 DVar.CKind != PredeterminedCKind) || 2509 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) && 2510 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private && 2511 DVar.CKind != OMPC_lastprivate)) && 2512 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 2513 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 2514 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 2515 << getOpenMPClauseName(PredeterminedCKind); 2516 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true); 2517 HasErrors = true; 2518 } else if (LoopVarRefExpr != nullptr) { 2519 // Make the loop iteration variable private (for worksharing constructs), 2520 // linear (for simd directives with the only one associated loop) or 2521 // lastprivate (for simd directives with several collapsed loops). 2522 // FIXME: the next check and error message must be removed once the 2523 // capturing of global variables in loops is fixed. 2524 if (DVar.CKind == OMPC_unknown) 2525 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(), 2526 /*FromParent=*/false); 2527 if (!Var->hasLocalStorage() && DVar.CKind == OMPC_unknown) { 2528 SemaRef.Diag(Init->getLocStart(), diag::err_omp_global_loop_var_dsa) 2529 << getOpenMPClauseName(PredeterminedCKind) 2530 << getOpenMPDirectiveName(DKind); 2531 HasErrors = true; 2532 } else 2533 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind); 2534 } 2535 2536 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 2537 2538 // Check test-expr. 2539 HasErrors |= ISC.CheckCond(For->getCond()); 2540 2541 // Check incr-expr. 2542 HasErrors |= ISC.CheckInc(For->getInc()); 2543 2544 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 2545 return HasErrors; 2546 2547 // Build the loop's iteration space representation. 2548 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 2549 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind)); 2550 ResultIterSpace.CounterVar = ISC.BuildCounterVar(); 2551 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 2552 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 2553 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 2554 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 2555 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 2556 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 2557 2558 HasErrors |= (ResultIterSpace.NumIterations == nullptr || 2559 ResultIterSpace.CounterVar == nullptr || 2560 ResultIterSpace.CounterInit == nullptr || 2561 ResultIterSpace.CounterStep == nullptr); 2562 2563 return HasErrors; 2564 } 2565 2566 /// \brief Build a variable declaration for OpenMP loop iteration variable. 2567 static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 2568 StringRef Name) { 2569 DeclContext *DC = SemaRef.CurContext; 2570 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 2571 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 2572 VarDecl *Decl = 2573 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 2574 Decl->setImplicit(); 2575 return Decl; 2576 } 2577 2578 /// \brief Build 'VarRef = Start + Iter * Step'. 2579 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S, 2580 SourceLocation Loc, ExprResult VarRef, 2581 ExprResult Start, ExprResult Iter, 2582 ExprResult Step, bool Subtract) { 2583 // Add parentheses (for debugging purposes only). 2584 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 2585 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 2586 !Step.isUsable()) 2587 return ExprError(); 2588 2589 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), 2590 Step.get()->IgnoreImplicit()); 2591 if (!Update.isUsable()) 2592 return ExprError(); 2593 2594 // Build 'VarRef = Start + Iter * Step'. 2595 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add), 2596 Start.get()->IgnoreImplicit(), Update.get()); 2597 if (!Update.isUsable()) 2598 return ExprError(); 2599 2600 Update = SemaRef.PerformImplicitConversion( 2601 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 2602 if (!Update.isUsable()) 2603 return ExprError(); 2604 2605 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 2606 return Update; 2607 } 2608 2609 /// \brief Convert integer expression \a E to make it have at least \a Bits 2610 /// bits. 2611 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, 2612 Sema &SemaRef) { 2613 if (E == nullptr) 2614 return ExprError(); 2615 auto &C = SemaRef.Context; 2616 QualType OldType = E->getType(); 2617 unsigned HasBits = C.getTypeSize(OldType); 2618 if (HasBits >= Bits) 2619 return ExprResult(E); 2620 // OK to convert to signed, because new type has more bits than old. 2621 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 2622 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 2623 true); 2624 } 2625 2626 /// \brief Check if the given expression \a E is a constant integer that fits 2627 /// into \a Bits bits. 2628 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 2629 if (E == nullptr) 2630 return false; 2631 llvm::APSInt Result; 2632 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 2633 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 2634 return false; 2635 } 2636 2637 /// \brief Called on a for stmt to check itself and nested loops (if any). 2638 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 2639 /// number of collapsed loops otherwise. 2640 static unsigned 2641 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr, 2642 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA, 2643 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA, 2644 BuiltLoopExprs &Built) { 2645 unsigned NestedLoopCount = 1; 2646 if (NestedLoopCountExpr) { 2647 // Found 'collapse' clause - calculate collapse number. 2648 llvm::APSInt Result; 2649 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 2650 NestedLoopCount = Result.getLimitedValue(); 2651 } 2652 // This is helper routine for loop directives (e.g., 'for', 'simd', 2653 // 'for simd', etc.). 2654 SmallVector<LoopIterationSpace, 4> IterSpaces; 2655 IterSpaces.resize(NestedLoopCount); 2656 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 2657 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 2658 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 2659 NestedLoopCount, NestedLoopCountExpr, 2660 VarsWithImplicitDSA, IterSpaces[Cnt])) 2661 return 0; 2662 // Move on to the next nested for loop, or to the loop body. 2663 // OpenMP [2.8.1, simd construct, Restrictions] 2664 // All loops associated with the construct must be perfectly nested; that 2665 // is, there must be no intervening code nor any OpenMP directive between 2666 // any two loops. 2667 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 2668 } 2669 2670 Built.clear(/* size */ NestedLoopCount); 2671 2672 if (SemaRef.CurContext->isDependentContext()) 2673 return NestedLoopCount; 2674 2675 // An example of what is generated for the following code: 2676 // 2677 // #pragma omp simd collapse(2) 2678 // for (i = 0; i < NI; ++i) 2679 // for (j = J0; j < NJ; j+=2) { 2680 // <loop body> 2681 // } 2682 // 2683 // We generate the code below. 2684 // Note: the loop body may be outlined in CodeGen. 2685 // Note: some counters may be C++ classes, operator- is used to find number of 2686 // iterations and operator+= to calculate counter value. 2687 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 2688 // or i64 is currently supported). 2689 // 2690 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 2691 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 2692 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 2693 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 2694 // // similar updates for vars in clauses (e.g. 'linear') 2695 // <loop body (using local i and j)> 2696 // } 2697 // i = NI; // assign final values of counters 2698 // j = NJ; 2699 // 2700 2701 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 2702 // the iteration counts of the collapsed for loops. 2703 auto N0 = IterSpaces[0].NumIterations; 2704 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef); 2705 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef); 2706 2707 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 2708 return NestedLoopCount; 2709 2710 auto &C = SemaRef.Context; 2711 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 2712 2713 Scope *CurScope = DSA.getCurScope(); 2714 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 2715 auto N = IterSpaces[Cnt].NumIterations; 2716 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 2717 if (LastIteration32.isUsable()) 2718 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul, 2719 LastIteration32.get(), N); 2720 if (LastIteration64.isUsable()) 2721 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul, 2722 LastIteration64.get(), N); 2723 } 2724 2725 // Choose either the 32-bit or 64-bit version. 2726 ExprResult LastIteration = LastIteration64; 2727 if (LastIteration32.isUsable() && 2728 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 2729 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 2730 FitsInto( 2731 32 /* Bits */, 2732 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 2733 LastIteration64.get(), SemaRef))) 2734 LastIteration = LastIteration32; 2735 2736 if (!LastIteration.isUsable()) 2737 return 0; 2738 2739 // Save the number of iterations. 2740 ExprResult NumIterations = LastIteration; 2741 { 2742 LastIteration = SemaRef.BuildBinOp( 2743 CurScope, SourceLocation(), BO_Sub, LastIteration.get(), 2744 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 2745 if (!LastIteration.isUsable()) 2746 return 0; 2747 } 2748 2749 // Calculate the last iteration number beforehand instead of doing this on 2750 // each iteration. Do not do this if the number of iterations may be kfold-ed. 2751 llvm::APSInt Result; 2752 bool IsConstant = 2753 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 2754 ExprResult CalcLastIteration; 2755 if (!IsConstant) { 2756 SourceLocation SaveLoc; 2757 VarDecl *SaveVar = 2758 BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(), 2759 ".omp.last.iteration"); 2760 ExprResult SaveRef = SemaRef.BuildDeclRefExpr( 2761 SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc); 2762 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign, 2763 SaveRef.get(), LastIteration.get()); 2764 LastIteration = SaveRef; 2765 2766 // Prepare SaveRef + 1. 2767 NumIterations = SemaRef.BuildBinOp( 2768 CurScope, SaveLoc, BO_Add, SaveRef.get(), 2769 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 2770 if (!NumIterations.isUsable()) 2771 return 0; 2772 } 2773 2774 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 2775 2776 // Precondition tests if there is at least one iteration (LastIteration > 0). 2777 ExprResult PreCond = SemaRef.BuildBinOp( 2778 CurScope, InitLoc, BO_GT, LastIteration.get(), 2779 SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get()); 2780 2781 // Build the iteration variable and its initialization to zero before loop. 2782 ExprResult IV; 2783 ExprResult Init; 2784 { 2785 VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, 2786 LastIteration.get()->getType(), ".omp.iv"); 2787 IV = SemaRef.BuildDeclRefExpr(IVDecl, LastIteration.get()->getType(), 2788 VK_LValue, InitLoc); 2789 Init = SemaRef.BuildBinOp( 2790 CurScope, InitLoc, BO_Assign, IV.get(), 2791 SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get()); 2792 } 2793 2794 // Loop condition (IV < NumIterations) 2795 SourceLocation CondLoc; 2796 ExprResult Cond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 2797 NumIterations.get()); 2798 // Loop condition with 1 iteration separated (IV < LastIteration) 2799 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, 2800 IV.get(), LastIteration.get()); 2801 2802 // Loop increment (IV = IV + 1) 2803 SourceLocation IncLoc; 2804 ExprResult Inc = 2805 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 2806 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 2807 if (!Inc.isUsable()) 2808 return 0; 2809 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 2810 2811 // Build updates and final values of the loop counters. 2812 bool HasErrors = false; 2813 Built.Counters.resize(NestedLoopCount); 2814 Built.Updates.resize(NestedLoopCount); 2815 Built.Finals.resize(NestedLoopCount); 2816 { 2817 ExprResult Div; 2818 // Go from inner nested loop to outer. 2819 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 2820 LoopIterationSpace &IS = IterSpaces[Cnt]; 2821 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 2822 // Build: Iter = (IV / Div) % IS.NumIters 2823 // where Div is product of previous iterations' IS.NumIters. 2824 ExprResult Iter; 2825 if (Div.isUsable()) { 2826 Iter = 2827 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 2828 } else { 2829 Iter = IV; 2830 assert((Cnt == (int)NestedLoopCount - 1) && 2831 "unusable div expected on first iteration only"); 2832 } 2833 2834 if (Cnt != 0 && Iter.isUsable()) 2835 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 2836 IS.NumIterations); 2837 if (!Iter.isUsable()) { 2838 HasErrors = true; 2839 break; 2840 } 2841 2842 // Build update: IS.CounterVar = IS.Start + Iter * IS.Step 2843 ExprResult Update = 2844 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar, 2845 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract); 2846 if (!Update.isUsable()) { 2847 HasErrors = true; 2848 break; 2849 } 2850 2851 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 2852 ExprResult Final = BuildCounterUpdate( 2853 SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit, 2854 IS.NumIterations, IS.CounterStep, IS.Subtract); 2855 if (!Final.isUsable()) { 2856 HasErrors = true; 2857 break; 2858 } 2859 2860 // Build Div for the next iteration: Div <- Div * IS.NumIters 2861 if (Cnt != 0) { 2862 if (Div.isUnset()) 2863 Div = IS.NumIterations; 2864 else 2865 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 2866 IS.NumIterations); 2867 2868 // Add parentheses (for debugging purposes only). 2869 if (Div.isUsable()) 2870 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get()); 2871 if (!Div.isUsable()) { 2872 HasErrors = true; 2873 break; 2874 } 2875 } 2876 if (!Update.isUsable() || !Final.isUsable()) { 2877 HasErrors = true; 2878 break; 2879 } 2880 // Save results 2881 Built.Counters[Cnt] = IS.CounterVar; 2882 Built.Updates[Cnt] = Update.get(); 2883 Built.Finals[Cnt] = Final.get(); 2884 } 2885 } 2886 2887 if (HasErrors) 2888 return 0; 2889 2890 // Save results 2891 Built.IterationVarRef = IV.get(); 2892 Built.LastIteration = LastIteration.get(); 2893 Built.CalcLastIteration = CalcLastIteration.get(); 2894 Built.PreCond = PreCond.get(); 2895 Built.Cond = Cond.get(); 2896 Built.SeparatedCond = SeparatedCond.get(); 2897 Built.Init = Init.get(); 2898 Built.Inc = Inc.get(); 2899 2900 return NestedLoopCount; 2901 } 2902 2903 static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 2904 auto CollapseFilter = [](const OMPClause *C) -> bool { 2905 return C->getClauseKind() == OMPC_collapse; 2906 }; 2907 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I( 2908 Clauses, CollapseFilter); 2909 if (I) 2910 return cast<OMPCollapseClause>(*I)->getNumForLoops(); 2911 return nullptr; 2912 } 2913 2914 StmtResult Sema::ActOnOpenMPSimdDirective( 2915 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 2916 SourceLocation EndLoc, 2917 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 2918 BuiltLoopExprs B; 2919 // In presence of clause 'collapse', it will define the nested loops number. 2920 unsigned NestedLoopCount = 2921 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this, 2922 *DSAStack, VarsWithImplicitDSA, B); 2923 if (NestedLoopCount == 0) 2924 return StmtError(); 2925 2926 assert((CurContext->isDependentContext() || B.builtAll()) && 2927 "omp simd loop exprs were not built"); 2928 2929 getCurFunction()->setHasBranchProtectedScope(); 2930 return OMPSimdDirective::Create( 2931 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, 2932 B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond, 2933 B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals); 2934 } 2935 2936 StmtResult Sema::ActOnOpenMPForDirective( 2937 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 2938 SourceLocation EndLoc, 2939 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 2940 BuiltLoopExprs B; 2941 // In presence of clause 'collapse', it will define the nested loops number. 2942 unsigned NestedLoopCount = 2943 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this, 2944 *DSAStack, VarsWithImplicitDSA, B); 2945 if (NestedLoopCount == 0) 2946 return StmtError(); 2947 2948 assert((CurContext->isDependentContext() || B.builtAll()) && 2949 "omp for loop exprs were not built"); 2950 2951 getCurFunction()->setHasBranchProtectedScope(); 2952 return OMPForDirective::Create( 2953 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, 2954 B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond, 2955 B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals); 2956 } 2957 2958 StmtResult Sema::ActOnOpenMPForSimdDirective( 2959 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 2960 SourceLocation EndLoc, 2961 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 2962 BuiltLoopExprs B; 2963 // In presence of clause 'collapse', it will define the nested loops number. 2964 unsigned NestedLoopCount = 2965 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt, 2966 *this, *DSAStack, VarsWithImplicitDSA, B); 2967 if (NestedLoopCount == 0) 2968 return StmtError(); 2969 2970 getCurFunction()->setHasBranchProtectedScope(); 2971 return OMPForSimdDirective::Create( 2972 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, 2973 B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond, 2974 B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals); 2975 } 2976 2977 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 2978 Stmt *AStmt, 2979 SourceLocation StartLoc, 2980 SourceLocation EndLoc) { 2981 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2982 auto BaseStmt = AStmt; 2983 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 2984 BaseStmt = CS->getCapturedStmt(); 2985 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 2986 auto S = C->children(); 2987 if (!S) 2988 return StmtError(); 2989 // All associated statements must be '#pragma omp section' except for 2990 // the first one. 2991 for (++S; S; ++S) { 2992 auto SectionStmt = *S; 2993 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 2994 if (SectionStmt) 2995 Diag(SectionStmt->getLocStart(), 2996 diag::err_omp_sections_substmt_not_section); 2997 return StmtError(); 2998 } 2999 } 3000 } else { 3001 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 3002 return StmtError(); 3003 } 3004 3005 getCurFunction()->setHasBranchProtectedScope(); 3006 3007 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, 3008 AStmt); 3009 } 3010 3011 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 3012 SourceLocation StartLoc, 3013 SourceLocation EndLoc) { 3014 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3015 3016 getCurFunction()->setHasBranchProtectedScope(); 3017 3018 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt); 3019 } 3020 3021 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 3022 Stmt *AStmt, 3023 SourceLocation StartLoc, 3024 SourceLocation EndLoc) { 3025 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3026 3027 getCurFunction()->setHasBranchProtectedScope(); 3028 3029 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 3030 } 3031 3032 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 3033 SourceLocation StartLoc, 3034 SourceLocation EndLoc) { 3035 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3036 3037 getCurFunction()->setHasBranchProtectedScope(); 3038 3039 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 3040 } 3041 3042 StmtResult 3043 Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, 3044 Stmt *AStmt, SourceLocation StartLoc, 3045 SourceLocation EndLoc) { 3046 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3047 3048 getCurFunction()->setHasBranchProtectedScope(); 3049 3050 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 3051 AStmt); 3052 } 3053 3054 StmtResult Sema::ActOnOpenMPParallelForDirective( 3055 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 3056 SourceLocation EndLoc, 3057 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 3058 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3059 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3060 // 1.2.2 OpenMP Language Terminology 3061 // Structured block - An executable statement with a single entry at the 3062 // top and a single exit at the bottom. 3063 // The point of exit cannot be a branch out of the structured block. 3064 // longjmp() and throw() must not violate the entry/exit criteria. 3065 CS->getCapturedDecl()->setNothrow(); 3066 3067 BuiltLoopExprs B; 3068 // In presence of clause 'collapse', it will define the nested loops number. 3069 unsigned NestedLoopCount = 3070 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt, 3071 *this, *DSAStack, VarsWithImplicitDSA, B); 3072 if (NestedLoopCount == 0) 3073 return StmtError(); 3074 3075 assert((CurContext->isDependentContext() || B.builtAll()) && 3076 "omp parallel for loop exprs were not built"); 3077 3078 getCurFunction()->setHasBranchProtectedScope(); 3079 return OMPParallelForDirective::Create( 3080 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, 3081 B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond, 3082 B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals); 3083 } 3084 3085 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 3086 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 3087 SourceLocation EndLoc, 3088 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 3089 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3090 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3091 // 1.2.2 OpenMP Language Terminology 3092 // Structured block - An executable statement with a single entry at the 3093 // top and a single exit at the bottom. 3094 // The point of exit cannot be a branch out of the structured block. 3095 // longjmp() and throw() must not violate the entry/exit criteria. 3096 CS->getCapturedDecl()->setNothrow(); 3097 3098 BuiltLoopExprs B; 3099 // In presence of clause 'collapse', it will define the nested loops number. 3100 unsigned NestedLoopCount = 3101 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses), 3102 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 3103 if (NestedLoopCount == 0) 3104 return StmtError(); 3105 3106 getCurFunction()->setHasBranchProtectedScope(); 3107 return OMPParallelForSimdDirective::Create( 3108 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, 3109 B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond, 3110 B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals); 3111 } 3112 3113 StmtResult 3114 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 3115 Stmt *AStmt, SourceLocation StartLoc, 3116 SourceLocation EndLoc) { 3117 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3118 auto BaseStmt = AStmt; 3119 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 3120 BaseStmt = CS->getCapturedStmt(); 3121 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 3122 auto S = C->children(); 3123 if (!S) 3124 return StmtError(); 3125 // All associated statements must be '#pragma omp section' except for 3126 // the first one. 3127 for (++S; S; ++S) { 3128 auto SectionStmt = *S; 3129 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 3130 if (SectionStmt) 3131 Diag(SectionStmt->getLocStart(), 3132 diag::err_omp_parallel_sections_substmt_not_section); 3133 return StmtError(); 3134 } 3135 } 3136 } else { 3137 Diag(AStmt->getLocStart(), 3138 diag::err_omp_parallel_sections_not_compound_stmt); 3139 return StmtError(); 3140 } 3141 3142 getCurFunction()->setHasBranchProtectedScope(); 3143 3144 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc, 3145 Clauses, AStmt); 3146 } 3147 3148 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 3149 Stmt *AStmt, SourceLocation StartLoc, 3150 SourceLocation EndLoc) { 3151 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3152 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3153 // 1.2.2 OpenMP Language Terminology 3154 // Structured block - An executable statement with a single entry at the 3155 // top and a single exit at the bottom. 3156 // The point of exit cannot be a branch out of the structured block. 3157 // longjmp() and throw() must not violate the entry/exit criteria. 3158 CS->getCapturedDecl()->setNothrow(); 3159 3160 getCurFunction()->setHasBranchProtectedScope(); 3161 3162 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 3163 } 3164 3165 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 3166 SourceLocation EndLoc) { 3167 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 3168 } 3169 3170 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 3171 SourceLocation EndLoc) { 3172 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 3173 } 3174 3175 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 3176 SourceLocation EndLoc) { 3177 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 3178 } 3179 3180 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 3181 SourceLocation StartLoc, 3182 SourceLocation EndLoc) { 3183 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 3184 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 3185 } 3186 3187 StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt, 3188 SourceLocation StartLoc, 3189 SourceLocation EndLoc) { 3190 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3191 3192 getCurFunction()->setHasBranchProtectedScope(); 3193 3194 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt); 3195 } 3196 3197 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 3198 Stmt *AStmt, 3199 SourceLocation StartLoc, 3200 SourceLocation EndLoc) { 3201 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3202 auto CS = cast<CapturedStmt>(AStmt); 3203 // 1.2.2 OpenMP Language Terminology 3204 // Structured block - An executable statement with a single entry at the 3205 // top and a single exit at the bottom. 3206 // The point of exit cannot be a branch out of the structured block. 3207 // longjmp() and throw() must not violate the entry/exit criteria. 3208 // TODO further analysis of associated statements and clauses. 3209 OpenMPClauseKind AtomicKind = OMPC_unknown; 3210 SourceLocation AtomicKindLoc; 3211 for (auto *C : Clauses) { 3212 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 3213 C->getClauseKind() == OMPC_update || 3214 C->getClauseKind() == OMPC_capture) { 3215 if (AtomicKind != OMPC_unknown) { 3216 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 3217 << SourceRange(C->getLocStart(), C->getLocEnd()); 3218 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 3219 << getOpenMPClauseName(AtomicKind); 3220 } else { 3221 AtomicKind = C->getClauseKind(); 3222 AtomicKindLoc = C->getLocStart(); 3223 } 3224 } 3225 } 3226 3227 auto Body = CS->getCapturedStmt(); 3228 Expr *X = nullptr; 3229 Expr *V = nullptr; 3230 Expr *E = nullptr; 3231 // OpenMP [2.12.6, atomic Construct] 3232 // In the next expressions: 3233 // * x and v (as applicable) are both l-value expressions with scalar type. 3234 // * During the execution of an atomic region, multiple syntactic 3235 // occurrences of x must designate the same storage location. 3236 // * Neither of v and expr (as applicable) may access the storage location 3237 // designated by x. 3238 // * Neither of x and expr (as applicable) may access the storage location 3239 // designated by v. 3240 // * expr is an expression with scalar type. 3241 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 3242 // * binop, binop=, ++, and -- are not overloaded operators. 3243 // * The expression x binop expr must be numerically equivalent to x binop 3244 // (expr). This requirement is satisfied if the operators in expr have 3245 // precedence greater than binop, or by using parentheses around expr or 3246 // subexpressions of expr. 3247 // * The expression expr binop x must be numerically equivalent to (expr) 3248 // binop x. This requirement is satisfied if the operators in expr have 3249 // precedence equal to or greater than binop, or by using parentheses around 3250 // expr or subexpressions of expr. 3251 // * For forms that allow multiple occurrences of x, the number of times 3252 // that x is evaluated is unspecified. 3253 if (AtomicKind == OMPC_read) { 3254 enum { 3255 NotAnExpression, 3256 NotAnAssignmentOp, 3257 NotAScalarType, 3258 NotAnLValue, 3259 NoError 3260 } ErrorFound = NoError; 3261 SourceLocation ErrorLoc, NoteLoc; 3262 SourceRange ErrorRange, NoteRange; 3263 // If clause is read: 3264 // v = x; 3265 if (auto AtomicBody = dyn_cast<Expr>(Body)) { 3266 auto AtomicBinOp = 3267 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 3268 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 3269 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 3270 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 3271 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 3272 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 3273 if (!X->isLValue() || !V->isLValue()) { 3274 auto NotLValueExpr = X->isLValue() ? V : X; 3275 ErrorFound = NotAnLValue; 3276 ErrorLoc = AtomicBinOp->getExprLoc(); 3277 ErrorRange = AtomicBinOp->getSourceRange(); 3278 NoteLoc = NotLValueExpr->getExprLoc(); 3279 NoteRange = NotLValueExpr->getSourceRange(); 3280 } 3281 } else if (!X->isInstantiationDependent() || 3282 !V->isInstantiationDependent()) { 3283 auto NotScalarExpr = 3284 (X->isInstantiationDependent() || X->getType()->isScalarType()) 3285 ? V 3286 : X; 3287 ErrorFound = NotAScalarType; 3288 ErrorLoc = AtomicBinOp->getExprLoc(); 3289 ErrorRange = AtomicBinOp->getSourceRange(); 3290 NoteLoc = NotScalarExpr->getExprLoc(); 3291 NoteRange = NotScalarExpr->getSourceRange(); 3292 } 3293 } else { 3294 ErrorFound = NotAnAssignmentOp; 3295 ErrorLoc = AtomicBody->getExprLoc(); 3296 ErrorRange = AtomicBody->getSourceRange(); 3297 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 3298 : AtomicBody->getExprLoc(); 3299 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 3300 : AtomicBody->getSourceRange(); 3301 } 3302 } else { 3303 ErrorFound = NotAnExpression; 3304 NoteLoc = ErrorLoc = Body->getLocStart(); 3305 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 3306 } 3307 if (ErrorFound != NoError) { 3308 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 3309 << ErrorRange; 3310 Diag(NoteLoc, diag::note_omp_atomic_read) << ErrorFound << NoteRange; 3311 return StmtError(); 3312 } else if (CurContext->isDependentContext()) 3313 V = X = nullptr; 3314 } else if (AtomicKind == OMPC_write) { 3315 if (!isa<Expr>(Body)) { 3316 Diag(Body->getLocStart(), 3317 diag::err_omp_atomic_write_not_expression_statement); 3318 return StmtError(); 3319 } 3320 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 3321 if (!isa<Expr>(Body)) { 3322 Diag(Body->getLocStart(), 3323 diag::err_omp_atomic_update_not_expression_statement) 3324 << (AtomicKind == OMPC_update); 3325 return StmtError(); 3326 } 3327 } else if (AtomicKind == OMPC_capture) { 3328 if (isa<Expr>(Body) && !isa<BinaryOperator>(Body)) { 3329 Diag(Body->getLocStart(), 3330 diag::err_omp_atomic_capture_not_expression_statement); 3331 return StmtError(); 3332 } else if (!isa<Expr>(Body) && !isa<CompoundStmt>(Body)) { 3333 Diag(Body->getLocStart(), 3334 diag::err_omp_atomic_capture_not_compound_statement); 3335 return StmtError(); 3336 } 3337 } 3338 3339 getCurFunction()->setHasBranchProtectedScope(); 3340 3341 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 3342 X, V, E); 3343 } 3344 3345 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 3346 Stmt *AStmt, 3347 SourceLocation StartLoc, 3348 SourceLocation EndLoc) { 3349 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3350 3351 // OpenMP [2.16, Nesting of Regions] 3352 // If specified, a teams construct must be contained within a target 3353 // construct. That target construct must contain no statements or directives 3354 // outside of the teams construct. 3355 if (DSAStack->hasInnerTeamsRegion()) { 3356 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 3357 bool OMPTeamsFound = true; 3358 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 3359 auto I = CS->body_begin(); 3360 while (I != CS->body_end()) { 3361 auto OED = dyn_cast<OMPExecutableDirective>(*I); 3362 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 3363 OMPTeamsFound = false; 3364 break; 3365 } 3366 ++I; 3367 } 3368 assert(I != CS->body_end() && "Not found statement"); 3369 S = *I; 3370 } 3371 if (!OMPTeamsFound) { 3372 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 3373 Diag(DSAStack->getInnerTeamsRegionLoc(), 3374 diag::note_omp_nested_teams_construct_here); 3375 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 3376 << isa<OMPExecutableDirective>(S); 3377 return StmtError(); 3378 } 3379 } 3380 3381 getCurFunction()->setHasBranchProtectedScope(); 3382 3383 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 3384 } 3385 3386 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 3387 Stmt *AStmt, SourceLocation StartLoc, 3388 SourceLocation EndLoc) { 3389 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3390 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3391 // 1.2.2 OpenMP Language Terminology 3392 // Structured block - An executable statement with a single entry at the 3393 // top and a single exit at the bottom. 3394 // The point of exit cannot be a branch out of the structured block. 3395 // longjmp() and throw() must not violate the entry/exit criteria. 3396 CS->getCapturedDecl()->setNothrow(); 3397 3398 getCurFunction()->setHasBranchProtectedScope(); 3399 3400 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 3401 } 3402 3403 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 3404 SourceLocation StartLoc, 3405 SourceLocation LParenLoc, 3406 SourceLocation EndLoc) { 3407 OMPClause *Res = nullptr; 3408 switch (Kind) { 3409 case OMPC_if: 3410 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc); 3411 break; 3412 case OMPC_final: 3413 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 3414 break; 3415 case OMPC_num_threads: 3416 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 3417 break; 3418 case OMPC_safelen: 3419 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 3420 break; 3421 case OMPC_collapse: 3422 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 3423 break; 3424 case OMPC_default: 3425 case OMPC_proc_bind: 3426 case OMPC_schedule: 3427 case OMPC_private: 3428 case OMPC_firstprivate: 3429 case OMPC_lastprivate: 3430 case OMPC_shared: 3431 case OMPC_reduction: 3432 case OMPC_linear: 3433 case OMPC_aligned: 3434 case OMPC_copyin: 3435 case OMPC_copyprivate: 3436 case OMPC_ordered: 3437 case OMPC_nowait: 3438 case OMPC_untied: 3439 case OMPC_mergeable: 3440 case OMPC_threadprivate: 3441 case OMPC_flush: 3442 case OMPC_read: 3443 case OMPC_write: 3444 case OMPC_update: 3445 case OMPC_capture: 3446 case OMPC_seq_cst: 3447 case OMPC_unknown: 3448 llvm_unreachable("Clause is not allowed."); 3449 } 3450 return Res; 3451 } 3452 3453 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc, 3454 SourceLocation LParenLoc, 3455 SourceLocation EndLoc) { 3456 Expr *ValExpr = Condition; 3457 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 3458 !Condition->isInstantiationDependent() && 3459 !Condition->containsUnexpandedParameterPack()) { 3460 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(), 3461 Condition->getExprLoc(), Condition); 3462 if (Val.isInvalid()) 3463 return nullptr; 3464 3465 ValExpr = Val.get(); 3466 } 3467 3468 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc); 3469 } 3470 3471 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 3472 SourceLocation StartLoc, 3473 SourceLocation LParenLoc, 3474 SourceLocation EndLoc) { 3475 Expr *ValExpr = Condition; 3476 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 3477 !Condition->isInstantiationDependent() && 3478 !Condition->containsUnexpandedParameterPack()) { 3479 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(), 3480 Condition->getExprLoc(), Condition); 3481 if (Val.isInvalid()) 3482 return nullptr; 3483 3484 ValExpr = Val.get(); 3485 } 3486 3487 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 3488 } 3489 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 3490 Expr *Op) { 3491 if (!Op) 3492 return ExprError(); 3493 3494 class IntConvertDiagnoser : public ICEConvertDiagnoser { 3495 public: 3496 IntConvertDiagnoser() 3497 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 3498 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 3499 QualType T) override { 3500 return S.Diag(Loc, diag::err_omp_not_integral) << T; 3501 } 3502 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 3503 QualType T) override { 3504 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 3505 } 3506 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 3507 QualType T, 3508 QualType ConvTy) override { 3509 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 3510 } 3511 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 3512 QualType ConvTy) override { 3513 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 3514 << ConvTy->isEnumeralType() << ConvTy; 3515 } 3516 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 3517 QualType T) override { 3518 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 3519 } 3520 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 3521 QualType ConvTy) override { 3522 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 3523 << ConvTy->isEnumeralType() << ConvTy; 3524 } 3525 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 3526 QualType) override { 3527 llvm_unreachable("conversion functions are permitted"); 3528 } 3529 } ConvertDiagnoser; 3530 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 3531 } 3532 3533 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 3534 SourceLocation StartLoc, 3535 SourceLocation LParenLoc, 3536 SourceLocation EndLoc) { 3537 Expr *ValExpr = NumThreads; 3538 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() && 3539 !NumThreads->containsUnexpandedParameterPack()) { 3540 SourceLocation NumThreadsLoc = NumThreads->getLocStart(); 3541 ExprResult Val = 3542 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads); 3543 if (Val.isInvalid()) 3544 return nullptr; 3545 3546 ValExpr = Val.get(); 3547 3548 // OpenMP [2.5, Restrictions] 3549 // The num_threads expression must evaluate to a positive integer value. 3550 llvm::APSInt Result; 3551 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() && 3552 !Result.isStrictlyPositive()) { 3553 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause) 3554 << "num_threads" << NumThreads->getSourceRange(); 3555 return nullptr; 3556 } 3557 } 3558 3559 return new (Context) 3560 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc); 3561 } 3562 3563 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 3564 OpenMPClauseKind CKind) { 3565 if (!E) 3566 return ExprError(); 3567 if (E->isValueDependent() || E->isTypeDependent() || 3568 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3569 return E; 3570 llvm::APSInt Result; 3571 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 3572 if (ICE.isInvalid()) 3573 return ExprError(); 3574 if (!Result.isStrictlyPositive()) { 3575 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 3576 << getOpenMPClauseName(CKind) << E->getSourceRange(); 3577 return ExprError(); 3578 } 3579 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 3580 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 3581 << E->getSourceRange(); 3582 return ExprError(); 3583 } 3584 return ICE; 3585 } 3586 3587 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 3588 SourceLocation LParenLoc, 3589 SourceLocation EndLoc) { 3590 // OpenMP [2.8.1, simd construct, Description] 3591 // The parameter of the safelen clause must be a constant 3592 // positive integer expression. 3593 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 3594 if (Safelen.isInvalid()) 3595 return nullptr; 3596 return new (Context) 3597 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 3598 } 3599 3600 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 3601 SourceLocation StartLoc, 3602 SourceLocation LParenLoc, 3603 SourceLocation EndLoc) { 3604 // OpenMP [2.7.1, loop construct, Description] 3605 // OpenMP [2.8.1, simd construct, Description] 3606 // OpenMP [2.9.6, distribute construct, Description] 3607 // The parameter of the collapse clause must be a constant 3608 // positive integer expression. 3609 ExprResult NumForLoopsResult = 3610 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 3611 if (NumForLoopsResult.isInvalid()) 3612 return nullptr; 3613 return new (Context) 3614 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 3615 } 3616 3617 OMPClause *Sema::ActOnOpenMPSimpleClause( 3618 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 3619 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 3620 OMPClause *Res = nullptr; 3621 switch (Kind) { 3622 case OMPC_default: 3623 Res = 3624 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 3625 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 3626 break; 3627 case OMPC_proc_bind: 3628 Res = ActOnOpenMPProcBindClause( 3629 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 3630 LParenLoc, EndLoc); 3631 break; 3632 case OMPC_if: 3633 case OMPC_final: 3634 case OMPC_num_threads: 3635 case OMPC_safelen: 3636 case OMPC_collapse: 3637 case OMPC_schedule: 3638 case OMPC_private: 3639 case OMPC_firstprivate: 3640 case OMPC_lastprivate: 3641 case OMPC_shared: 3642 case OMPC_reduction: 3643 case OMPC_linear: 3644 case OMPC_aligned: 3645 case OMPC_copyin: 3646 case OMPC_copyprivate: 3647 case OMPC_ordered: 3648 case OMPC_nowait: 3649 case OMPC_untied: 3650 case OMPC_mergeable: 3651 case OMPC_threadprivate: 3652 case OMPC_flush: 3653 case OMPC_read: 3654 case OMPC_write: 3655 case OMPC_update: 3656 case OMPC_capture: 3657 case OMPC_seq_cst: 3658 case OMPC_unknown: 3659 llvm_unreachable("Clause is not allowed."); 3660 } 3661 return Res; 3662 } 3663 3664 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 3665 SourceLocation KindKwLoc, 3666 SourceLocation StartLoc, 3667 SourceLocation LParenLoc, 3668 SourceLocation EndLoc) { 3669 if (Kind == OMPC_DEFAULT_unknown) { 3670 std::string Values; 3671 static_assert(OMPC_DEFAULT_unknown > 0, 3672 "OMPC_DEFAULT_unknown not greater than 0"); 3673 std::string Sep(", "); 3674 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) { 3675 Values += "'"; 3676 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i); 3677 Values += "'"; 3678 switch (i) { 3679 case OMPC_DEFAULT_unknown - 2: 3680 Values += " or "; 3681 break; 3682 case OMPC_DEFAULT_unknown - 1: 3683 break; 3684 default: 3685 Values += Sep; 3686 break; 3687 } 3688 } 3689 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 3690 << Values << getOpenMPClauseName(OMPC_default); 3691 return nullptr; 3692 } 3693 switch (Kind) { 3694 case OMPC_DEFAULT_none: 3695 DSAStack->setDefaultDSANone(KindKwLoc); 3696 break; 3697 case OMPC_DEFAULT_shared: 3698 DSAStack->setDefaultDSAShared(KindKwLoc); 3699 break; 3700 case OMPC_DEFAULT_unknown: 3701 llvm_unreachable("Clause kind is not allowed."); 3702 break; 3703 } 3704 return new (Context) 3705 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 3706 } 3707 3708 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 3709 SourceLocation KindKwLoc, 3710 SourceLocation StartLoc, 3711 SourceLocation LParenLoc, 3712 SourceLocation EndLoc) { 3713 if (Kind == OMPC_PROC_BIND_unknown) { 3714 std::string Values; 3715 std::string Sep(", "); 3716 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) { 3717 Values += "'"; 3718 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i); 3719 Values += "'"; 3720 switch (i) { 3721 case OMPC_PROC_BIND_unknown - 2: 3722 Values += " or "; 3723 break; 3724 case OMPC_PROC_BIND_unknown - 1: 3725 break; 3726 default: 3727 Values += Sep; 3728 break; 3729 } 3730 } 3731 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 3732 << Values << getOpenMPClauseName(OMPC_proc_bind); 3733 return nullptr; 3734 } 3735 return new (Context) 3736 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 3737 } 3738 3739 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 3740 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr, 3741 SourceLocation StartLoc, SourceLocation LParenLoc, 3742 SourceLocation ArgumentLoc, SourceLocation CommaLoc, 3743 SourceLocation EndLoc) { 3744 OMPClause *Res = nullptr; 3745 switch (Kind) { 3746 case OMPC_schedule: 3747 Res = ActOnOpenMPScheduleClause( 3748 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc, 3749 LParenLoc, ArgumentLoc, CommaLoc, EndLoc); 3750 break; 3751 case OMPC_if: 3752 case OMPC_final: 3753 case OMPC_num_threads: 3754 case OMPC_safelen: 3755 case OMPC_collapse: 3756 case OMPC_default: 3757 case OMPC_proc_bind: 3758 case OMPC_private: 3759 case OMPC_firstprivate: 3760 case OMPC_lastprivate: 3761 case OMPC_shared: 3762 case OMPC_reduction: 3763 case OMPC_linear: 3764 case OMPC_aligned: 3765 case OMPC_copyin: 3766 case OMPC_copyprivate: 3767 case OMPC_ordered: 3768 case OMPC_nowait: 3769 case OMPC_untied: 3770 case OMPC_mergeable: 3771 case OMPC_threadprivate: 3772 case OMPC_flush: 3773 case OMPC_read: 3774 case OMPC_write: 3775 case OMPC_update: 3776 case OMPC_capture: 3777 case OMPC_seq_cst: 3778 case OMPC_unknown: 3779 llvm_unreachable("Clause is not allowed."); 3780 } 3781 return Res; 3782 } 3783 3784 OMPClause *Sema::ActOnOpenMPScheduleClause( 3785 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 3786 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 3787 SourceLocation EndLoc) { 3788 if (Kind == OMPC_SCHEDULE_unknown) { 3789 std::string Values; 3790 std::string Sep(", "); 3791 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) { 3792 Values += "'"; 3793 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i); 3794 Values += "'"; 3795 switch (i) { 3796 case OMPC_SCHEDULE_unknown - 2: 3797 Values += " or "; 3798 break; 3799 case OMPC_SCHEDULE_unknown - 1: 3800 break; 3801 default: 3802 Values += Sep; 3803 break; 3804 } 3805 } 3806 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 3807 << Values << getOpenMPClauseName(OMPC_schedule); 3808 return nullptr; 3809 } 3810 Expr *ValExpr = ChunkSize; 3811 if (ChunkSize) { 3812 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 3813 !ChunkSize->isInstantiationDependent() && 3814 !ChunkSize->containsUnexpandedParameterPack()) { 3815 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 3816 ExprResult Val = 3817 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 3818 if (Val.isInvalid()) 3819 return nullptr; 3820 3821 ValExpr = Val.get(); 3822 3823 // OpenMP [2.7.1, Restrictions] 3824 // chunk_size must be a loop invariant integer expression with a positive 3825 // value. 3826 llvm::APSInt Result; 3827 if (ValExpr->isIntegerConstantExpr(Result, Context) && 3828 Result.isSigned() && !Result.isStrictlyPositive()) { 3829 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 3830 << "schedule" << ChunkSize->getSourceRange(); 3831 return nullptr; 3832 } 3833 } 3834 } 3835 3836 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, 3837 EndLoc, Kind, ValExpr); 3838 } 3839 3840 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 3841 SourceLocation StartLoc, 3842 SourceLocation EndLoc) { 3843 OMPClause *Res = nullptr; 3844 switch (Kind) { 3845 case OMPC_ordered: 3846 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 3847 break; 3848 case OMPC_nowait: 3849 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 3850 break; 3851 case OMPC_untied: 3852 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 3853 break; 3854 case OMPC_mergeable: 3855 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 3856 break; 3857 case OMPC_read: 3858 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 3859 break; 3860 case OMPC_write: 3861 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 3862 break; 3863 case OMPC_update: 3864 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 3865 break; 3866 case OMPC_capture: 3867 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 3868 break; 3869 case OMPC_seq_cst: 3870 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 3871 break; 3872 case OMPC_if: 3873 case OMPC_final: 3874 case OMPC_num_threads: 3875 case OMPC_safelen: 3876 case OMPC_collapse: 3877 case OMPC_schedule: 3878 case OMPC_private: 3879 case OMPC_firstprivate: 3880 case OMPC_lastprivate: 3881 case OMPC_shared: 3882 case OMPC_reduction: 3883 case OMPC_linear: 3884 case OMPC_aligned: 3885 case OMPC_copyin: 3886 case OMPC_copyprivate: 3887 case OMPC_default: 3888 case OMPC_proc_bind: 3889 case OMPC_threadprivate: 3890 case OMPC_flush: 3891 case OMPC_unknown: 3892 llvm_unreachable("Clause is not allowed."); 3893 } 3894 return Res; 3895 } 3896 3897 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 3898 SourceLocation EndLoc) { 3899 DSAStack->setOrderedRegion(); 3900 return new (Context) OMPOrderedClause(StartLoc, EndLoc); 3901 } 3902 3903 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 3904 SourceLocation EndLoc) { 3905 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 3906 } 3907 3908 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 3909 SourceLocation EndLoc) { 3910 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 3911 } 3912 3913 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 3914 SourceLocation EndLoc) { 3915 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 3916 } 3917 3918 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 3919 SourceLocation EndLoc) { 3920 return new (Context) OMPReadClause(StartLoc, EndLoc); 3921 } 3922 3923 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 3924 SourceLocation EndLoc) { 3925 return new (Context) OMPWriteClause(StartLoc, EndLoc); 3926 } 3927 3928 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 3929 SourceLocation EndLoc) { 3930 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 3931 } 3932 3933 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 3934 SourceLocation EndLoc) { 3935 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 3936 } 3937 3938 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 3939 SourceLocation EndLoc) { 3940 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 3941 } 3942 3943 OMPClause *Sema::ActOnOpenMPVarListClause( 3944 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 3945 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 3946 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 3947 const DeclarationNameInfo &ReductionId) { 3948 OMPClause *Res = nullptr; 3949 switch (Kind) { 3950 case OMPC_private: 3951 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 3952 break; 3953 case OMPC_firstprivate: 3954 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 3955 break; 3956 case OMPC_lastprivate: 3957 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 3958 break; 3959 case OMPC_shared: 3960 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 3961 break; 3962 case OMPC_reduction: 3963 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 3964 EndLoc, ReductionIdScopeSpec, ReductionId); 3965 break; 3966 case OMPC_linear: 3967 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 3968 ColonLoc, EndLoc); 3969 break; 3970 case OMPC_aligned: 3971 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 3972 ColonLoc, EndLoc); 3973 break; 3974 case OMPC_copyin: 3975 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 3976 break; 3977 case OMPC_copyprivate: 3978 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 3979 break; 3980 case OMPC_flush: 3981 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 3982 break; 3983 case OMPC_if: 3984 case OMPC_final: 3985 case OMPC_num_threads: 3986 case OMPC_safelen: 3987 case OMPC_collapse: 3988 case OMPC_default: 3989 case OMPC_proc_bind: 3990 case OMPC_schedule: 3991 case OMPC_ordered: 3992 case OMPC_nowait: 3993 case OMPC_untied: 3994 case OMPC_mergeable: 3995 case OMPC_threadprivate: 3996 case OMPC_read: 3997 case OMPC_write: 3998 case OMPC_update: 3999 case OMPC_capture: 4000 case OMPC_seq_cst: 4001 case OMPC_unknown: 4002 llvm_unreachable("Clause is not allowed."); 4003 } 4004 return Res; 4005 } 4006 4007 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 4008 SourceLocation StartLoc, 4009 SourceLocation LParenLoc, 4010 SourceLocation EndLoc) { 4011 SmallVector<Expr *, 8> Vars; 4012 SmallVector<Expr *, 8> PrivateCopies; 4013 for (auto &RefExpr : VarList) { 4014 assert(RefExpr && "NULL expr in OpenMP private clause."); 4015 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 4016 // It will be analyzed later. 4017 Vars.push_back(RefExpr); 4018 PrivateCopies.push_back(nullptr); 4019 continue; 4020 } 4021 4022 SourceLocation ELoc = RefExpr->getExprLoc(); 4023 // OpenMP [2.1, C/C++] 4024 // A list item is a variable name. 4025 // OpenMP [2.9.3.3, Restrictions, p.1] 4026 // A variable that is part of another variable (as an array or 4027 // structure element) cannot appear in a private clause. 4028 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 4029 if (!DE || !isa<VarDecl>(DE->getDecl())) { 4030 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 4031 continue; 4032 } 4033 Decl *D = DE->getDecl(); 4034 VarDecl *VD = cast<VarDecl>(D); 4035 4036 QualType Type = VD->getType(); 4037 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 4038 // It will be analyzed later. 4039 Vars.push_back(DE); 4040 PrivateCopies.push_back(nullptr); 4041 continue; 4042 } 4043 4044 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 4045 // A variable that appears in a private clause must not have an incomplete 4046 // type or a reference type. 4047 if (RequireCompleteType(ELoc, Type, 4048 diag::err_omp_private_incomplete_type)) { 4049 continue; 4050 } 4051 if (Type->isReferenceType()) { 4052 Diag(ELoc, diag::err_omp_clause_ref_type_arg) 4053 << getOpenMPClauseName(OMPC_private) << Type; 4054 bool IsDecl = 4055 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4056 Diag(VD->getLocation(), 4057 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4058 << VD; 4059 continue; 4060 } 4061 4062 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 4063 // A variable of class type (or array thereof) that appears in a private 4064 // clause requires an accessible, unambiguous default constructor for the 4065 // class type. 4066 while (Type->isArrayType()) { 4067 Type = cast<ArrayType>(Type.getTypePtr())->getElementType(); 4068 } 4069 4070 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 4071 // in a Construct] 4072 // Variables with the predetermined data-sharing attributes may not be 4073 // listed in data-sharing attributes clauses, except for the cases 4074 // listed below. For these exceptions only, listing a predetermined 4075 // variable in a data-sharing attribute clause is allowed and overrides 4076 // the variable's predetermined data-sharing attributes. 4077 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 4078 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 4079 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 4080 << getOpenMPClauseName(OMPC_private); 4081 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4082 continue; 4083 } 4084 4085 // Generate helper private variable and initialize it with the default 4086 // value. The address of the original variable is replaced by the address of 4087 // the new private variable in CodeGen. This new variable is not added to 4088 // IdResolver, so the code in the OpenMP region uses original variable for 4089 // proper diagnostics. 4090 auto VDPrivate = 4091 VarDecl::Create(Context, CurContext, DE->getLocStart(), 4092 DE->getExprLoc(), VD->getIdentifier(), VD->getType(), 4093 VD->getTypeSourceInfo(), /*S*/ SC_Auto); 4094 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false); 4095 if (VDPrivate->isInvalidDecl()) 4096 continue; 4097 CurContext->addDecl(VDPrivate); 4098 auto VDPrivateRefExpr = DeclRefExpr::Create( 4099 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(), 4100 /*TemplateKWLoc*/ SourceLocation(), VDPrivate, 4101 /*isEnclosingLocal*/ false, /*NameLoc*/ SourceLocation(), DE->getType(), 4102 /*VK*/ VK_LValue); 4103 4104 DSAStack->addDSA(VD, DE, OMPC_private); 4105 Vars.push_back(DE); 4106 PrivateCopies.push_back(VDPrivateRefExpr); 4107 } 4108 4109 if (Vars.empty()) 4110 return nullptr; 4111 4112 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 4113 PrivateCopies); 4114 } 4115 4116 namespace { 4117 class DiagsUninitializedSeveretyRAII { 4118 private: 4119 DiagnosticsEngine &Diags; 4120 SourceLocation SavedLoc; 4121 bool IsIgnored; 4122 4123 public: 4124 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 4125 bool IsIgnored) 4126 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 4127 if (!IsIgnored) { 4128 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 4129 /*Map*/ diag::Severity::Ignored, Loc); 4130 } 4131 } 4132 ~DiagsUninitializedSeveretyRAII() { 4133 if (!IsIgnored) 4134 Diags.popMappings(SavedLoc); 4135 } 4136 }; 4137 } 4138 4139 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 4140 SourceLocation StartLoc, 4141 SourceLocation LParenLoc, 4142 SourceLocation EndLoc) { 4143 SmallVector<Expr *, 8> Vars; 4144 SmallVector<Expr *, 8> PrivateCopies; 4145 SmallVector<Expr *, 8> Inits; 4146 bool IsImplicitClause = 4147 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 4148 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 4149 4150 for (auto &RefExpr : VarList) { 4151 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 4152 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 4153 // It will be analyzed later. 4154 Vars.push_back(RefExpr); 4155 PrivateCopies.push_back(nullptr); 4156 Inits.push_back(nullptr); 4157 continue; 4158 } 4159 4160 SourceLocation ELoc = 4161 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc(); 4162 // OpenMP [2.1, C/C++] 4163 // A list item is a variable name. 4164 // OpenMP [2.9.3.3, Restrictions, p.1] 4165 // A variable that is part of another variable (as an array or 4166 // structure element) cannot appear in a private clause. 4167 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 4168 if (!DE || !isa<VarDecl>(DE->getDecl())) { 4169 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 4170 continue; 4171 } 4172 Decl *D = DE->getDecl(); 4173 VarDecl *VD = cast<VarDecl>(D); 4174 4175 QualType Type = VD->getType(); 4176 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 4177 // It will be analyzed later. 4178 Vars.push_back(DE); 4179 PrivateCopies.push_back(nullptr); 4180 Inits.push_back(nullptr); 4181 continue; 4182 } 4183 4184 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 4185 // A variable that appears in a private clause must not have an incomplete 4186 // type or a reference type. 4187 if (RequireCompleteType(ELoc, Type, 4188 diag::err_omp_firstprivate_incomplete_type)) { 4189 continue; 4190 } 4191 if (Type->isReferenceType()) { 4192 if (IsImplicitClause) { 4193 Diag(ImplicitClauseLoc, 4194 diag::err_omp_task_predetermined_firstprivate_ref_type_arg) 4195 << Type; 4196 Diag(RefExpr->getExprLoc(), diag::note_used_here); 4197 } else { 4198 Diag(ELoc, diag::err_omp_clause_ref_type_arg) 4199 << getOpenMPClauseName(OMPC_firstprivate) << Type; 4200 } 4201 bool IsDecl = 4202 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4203 Diag(VD->getLocation(), 4204 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4205 << VD; 4206 continue; 4207 } 4208 4209 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 4210 // A variable of class type (or array thereof) that appears in a private 4211 // clause requires an accessible, unambiguous copy constructor for the 4212 // class type. 4213 Type = Context.getBaseElementType(Type); 4214 4215 // If an implicit firstprivate variable found it was checked already. 4216 if (!IsImplicitClause) { 4217 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 4218 Type = Type.getNonReferenceType().getCanonicalType(); 4219 bool IsConstant = Type.isConstant(Context); 4220 Type = Context.getBaseElementType(Type); 4221 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 4222 // A list item that specifies a given variable may not appear in more 4223 // than one clause on the same directive, except that a variable may be 4224 // specified in both firstprivate and lastprivate clauses. 4225 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 4226 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) { 4227 Diag(ELoc, diag::err_omp_wrong_dsa) 4228 << getOpenMPClauseName(DVar.CKind) 4229 << getOpenMPClauseName(OMPC_firstprivate); 4230 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4231 continue; 4232 } 4233 4234 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 4235 // in a Construct] 4236 // Variables with the predetermined data-sharing attributes may not be 4237 // listed in data-sharing attributes clauses, except for the cases 4238 // listed below. For these exceptions only, listing a predetermined 4239 // variable in a data-sharing attribute clause is allowed and overrides 4240 // the variable's predetermined data-sharing attributes. 4241 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 4242 // in a Construct, C/C++, p.2] 4243 // Variables with const-qualified type having no mutable member may be 4244 // listed in a firstprivate clause, even if they are static data members. 4245 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr && 4246 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 4247 Diag(ELoc, diag::err_omp_wrong_dsa) 4248 << getOpenMPClauseName(DVar.CKind) 4249 << getOpenMPClauseName(OMPC_firstprivate); 4250 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4251 continue; 4252 } 4253 4254 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 4255 // OpenMP [2.9.3.4, Restrictions, p.2] 4256 // A list item that is private within a parallel region must not appear 4257 // in a firstprivate clause on a worksharing construct if any of the 4258 // worksharing regions arising from the worksharing construct ever bind 4259 // to any of the parallel regions arising from the parallel construct. 4260 if (isOpenMPWorksharingDirective(CurrDir) && 4261 !isOpenMPParallelDirective(CurrDir)) { 4262 DVar = DSAStack->getImplicitDSA(VD, true); 4263 if (DVar.CKind != OMPC_shared && 4264 (isOpenMPParallelDirective(DVar.DKind) || 4265 DVar.DKind == OMPD_unknown)) { 4266 Diag(ELoc, diag::err_omp_required_access) 4267 << getOpenMPClauseName(OMPC_firstprivate) 4268 << getOpenMPClauseName(OMPC_shared); 4269 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4270 continue; 4271 } 4272 } 4273 // OpenMP [2.9.3.4, Restrictions, p.3] 4274 // A list item that appears in a reduction clause of a parallel construct 4275 // must not appear in a firstprivate clause on a worksharing or task 4276 // construct if any of the worksharing or task regions arising from the 4277 // worksharing or task construct ever bind to any of the parallel regions 4278 // arising from the parallel construct. 4279 // OpenMP [2.9.3.4, Restrictions, p.4] 4280 // A list item that appears in a reduction clause in worksharing 4281 // construct must not appear in a firstprivate clause in a task construct 4282 // encountered during execution of any of the worksharing regions arising 4283 // from the worksharing construct. 4284 if (CurrDir == OMPD_task) { 4285 DVar = 4286 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction), 4287 [](OpenMPDirectiveKind K) -> bool { 4288 return isOpenMPParallelDirective(K) || 4289 isOpenMPWorksharingDirective(K); 4290 }, 4291 false); 4292 if (DVar.CKind == OMPC_reduction && 4293 (isOpenMPParallelDirective(DVar.DKind) || 4294 isOpenMPWorksharingDirective(DVar.DKind))) { 4295 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 4296 << getOpenMPDirectiveName(DVar.DKind); 4297 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4298 continue; 4299 } 4300 } 4301 } 4302 4303 Type = Type.getUnqualifiedType(); 4304 auto VDPrivate = VarDecl::Create(Context, CurContext, DE->getLocStart(), 4305 ELoc, VD->getIdentifier(), VD->getType(), 4306 VD->getTypeSourceInfo(), /*S*/ SC_Auto); 4307 // Generate helper private variable and initialize it with the value of the 4308 // original variable. The address of the original variable is replaced by 4309 // the address of the new private variable in the CodeGen. This new variable 4310 // is not added to IdResolver, so the code in the OpenMP region uses 4311 // original variable for proper diagnostics and variable capturing. 4312 Expr *VDInitRefExpr = nullptr; 4313 // For arrays generate initializer for single element and replace it by the 4314 // original array element in CodeGen. 4315 if (DE->getType()->isArrayType()) { 4316 auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(), 4317 ELoc, VD->getIdentifier(), Type, 4318 VD->getTypeSourceInfo(), /*S*/ SC_Auto); 4319 CurContext->addHiddenDecl(VDInit); 4320 VDInitRefExpr = DeclRefExpr::Create( 4321 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(), 4322 /*TemplateKWLoc*/ SourceLocation(), VDInit, 4323 /*isEnclosingLocal*/ false, ELoc, Type, 4324 /*VK*/ VK_LValue); 4325 VDInit->setIsUsed(); 4326 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 4327 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDInit); 4328 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 4329 4330 InitializationSequence InitSeq(*this, Entity, Kind, Init); 4331 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 4332 if (Result.isInvalid()) 4333 VDPrivate->setInvalidDecl(); 4334 else 4335 VDPrivate->setInit(Result.getAs<Expr>()); 4336 } else { 4337 AddInitializerToDecl(VDPrivate, DefaultLvalueConversion(DE).get(), 4338 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 4339 } 4340 if (VDPrivate->isInvalidDecl()) { 4341 if (IsImplicitClause) { 4342 Diag(DE->getExprLoc(), 4343 diag::note_omp_task_predetermined_firstprivate_here); 4344 } 4345 continue; 4346 } 4347 CurContext->addDecl(VDPrivate); 4348 auto VDPrivateRefExpr = DeclRefExpr::Create( 4349 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(), 4350 /*TemplateKWLoc*/ SourceLocation(), VDPrivate, 4351 /*isEnclosingLocal*/ false, DE->getLocStart(), DE->getType(), 4352 /*VK*/ VK_LValue); 4353 DSAStack->addDSA(VD, DE, OMPC_firstprivate); 4354 Vars.push_back(DE); 4355 PrivateCopies.push_back(VDPrivateRefExpr); 4356 Inits.push_back(VDInitRefExpr); 4357 } 4358 4359 if (Vars.empty()) 4360 return nullptr; 4361 4362 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 4363 Vars, PrivateCopies, Inits); 4364 } 4365 4366 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 4367 SourceLocation StartLoc, 4368 SourceLocation LParenLoc, 4369 SourceLocation EndLoc) { 4370 SmallVector<Expr *, 8> Vars; 4371 for (auto &RefExpr : VarList) { 4372 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 4373 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 4374 // It will be analyzed later. 4375 Vars.push_back(RefExpr); 4376 continue; 4377 } 4378 4379 SourceLocation ELoc = RefExpr->getExprLoc(); 4380 // OpenMP [2.1, C/C++] 4381 // A list item is a variable name. 4382 // OpenMP [2.14.3.5, Restrictions, p.1] 4383 // A variable that is part of another variable (as an array or structure 4384 // element) cannot appear in a lastprivate clause. 4385 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 4386 if (!DE || !isa<VarDecl>(DE->getDecl())) { 4387 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 4388 continue; 4389 } 4390 Decl *D = DE->getDecl(); 4391 VarDecl *VD = cast<VarDecl>(D); 4392 4393 QualType Type = VD->getType(); 4394 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 4395 // It will be analyzed later. 4396 Vars.push_back(DE); 4397 continue; 4398 } 4399 4400 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 4401 // A variable that appears in a lastprivate clause must not have an 4402 // incomplete type or a reference type. 4403 if (RequireCompleteType(ELoc, Type, 4404 diag::err_omp_lastprivate_incomplete_type)) { 4405 continue; 4406 } 4407 if (Type->isReferenceType()) { 4408 Diag(ELoc, diag::err_omp_clause_ref_type_arg) 4409 << getOpenMPClauseName(OMPC_lastprivate) << Type; 4410 bool IsDecl = 4411 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4412 Diag(VD->getLocation(), 4413 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4414 << VD; 4415 continue; 4416 } 4417 4418 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4419 // in a Construct] 4420 // Variables with the predetermined data-sharing attributes may not be 4421 // listed in data-sharing attributes clauses, except for the cases 4422 // listed below. 4423 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 4424 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 4425 DVar.CKind != OMPC_firstprivate && 4426 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 4427 Diag(ELoc, diag::err_omp_wrong_dsa) 4428 << getOpenMPClauseName(DVar.CKind) 4429 << getOpenMPClauseName(OMPC_lastprivate); 4430 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4431 continue; 4432 } 4433 4434 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 4435 // OpenMP [2.14.3.5, Restrictions, p.2] 4436 // A list item that is private within a parallel region, or that appears in 4437 // the reduction clause of a parallel construct, must not appear in a 4438 // lastprivate clause on a worksharing construct if any of the corresponding 4439 // worksharing regions ever binds to any of the corresponding parallel 4440 // regions. 4441 if (isOpenMPWorksharingDirective(CurrDir) && 4442 !isOpenMPParallelDirective(CurrDir)) { 4443 DVar = DSAStack->getImplicitDSA(VD, true); 4444 if (DVar.CKind != OMPC_shared) { 4445 Diag(ELoc, diag::err_omp_required_access) 4446 << getOpenMPClauseName(OMPC_lastprivate) 4447 << getOpenMPClauseName(OMPC_shared); 4448 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4449 continue; 4450 } 4451 } 4452 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 4453 // A variable of class type (or array thereof) that appears in a 4454 // lastprivate clause requires an accessible, unambiguous default 4455 // constructor for the class type, unless the list item is also specified 4456 // in a firstprivate clause. 4457 // A variable of class type (or array thereof) that appears in a 4458 // lastprivate clause requires an accessible, unambiguous copy assignment 4459 // operator for the class type. 4460 while (Type.getNonReferenceType()->isArrayType()) 4461 Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr()) 4462 ->getElementType(); 4463 CXXRecordDecl *RD = getLangOpts().CPlusPlus 4464 ? Type.getNonReferenceType()->getAsCXXRecordDecl() 4465 : nullptr; 4466 // FIXME This code must be replaced by actual copying and destructing of the 4467 // lastprivate variable. 4468 if (RD) { 4469 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0); 4470 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess()); 4471 if (MD) { 4472 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible || 4473 MD->isDeleted()) { 4474 Diag(ELoc, diag::err_omp_required_method) 4475 << getOpenMPClauseName(OMPC_lastprivate) << 2; 4476 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 4477 VarDecl::DeclarationOnly; 4478 Diag(VD->getLocation(), 4479 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4480 << VD; 4481 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 4482 continue; 4483 } 4484 MarkFunctionReferenced(ELoc, MD); 4485 DiagnoseUseOfDecl(MD, ELoc); 4486 } 4487 4488 CXXDestructorDecl *DD = RD->getDestructor(); 4489 if (DD) { 4490 PartialDiagnostic PD = 4491 PartialDiagnostic(PartialDiagnostic::NullDiagnostic()); 4492 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible || 4493 DD->isDeleted()) { 4494 Diag(ELoc, diag::err_omp_required_method) 4495 << getOpenMPClauseName(OMPC_lastprivate) << 4; 4496 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 4497 VarDecl::DeclarationOnly; 4498 Diag(VD->getLocation(), 4499 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4500 << VD; 4501 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 4502 continue; 4503 } 4504 MarkFunctionReferenced(ELoc, DD); 4505 DiagnoseUseOfDecl(DD, ELoc); 4506 } 4507 } 4508 4509 if (DVar.CKind != OMPC_firstprivate) 4510 DSAStack->addDSA(VD, DE, OMPC_lastprivate); 4511 Vars.push_back(DE); 4512 } 4513 4514 if (Vars.empty()) 4515 return nullptr; 4516 4517 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 4518 Vars); 4519 } 4520 4521 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 4522 SourceLocation StartLoc, 4523 SourceLocation LParenLoc, 4524 SourceLocation EndLoc) { 4525 SmallVector<Expr *, 8> Vars; 4526 for (auto &RefExpr : VarList) { 4527 assert(RefExpr && "NULL expr in OpenMP shared clause."); 4528 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 4529 // It will be analyzed later. 4530 Vars.push_back(RefExpr); 4531 continue; 4532 } 4533 4534 SourceLocation ELoc = RefExpr->getExprLoc(); 4535 // OpenMP [2.1, C/C++] 4536 // A list item is a variable name. 4537 // OpenMP [2.14.3.2, Restrictions, p.1] 4538 // A variable that is part of another variable (as an array or structure 4539 // element) cannot appear in a shared unless it is a static data member 4540 // of a C++ class. 4541 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 4542 if (!DE || !isa<VarDecl>(DE->getDecl())) { 4543 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 4544 continue; 4545 } 4546 Decl *D = DE->getDecl(); 4547 VarDecl *VD = cast<VarDecl>(D); 4548 4549 QualType Type = VD->getType(); 4550 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 4551 // It will be analyzed later. 4552 Vars.push_back(DE); 4553 continue; 4554 } 4555 4556 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 4557 // in a Construct] 4558 // Variables with the predetermined data-sharing attributes may not be 4559 // listed in data-sharing attributes clauses, except for the cases 4560 // listed below. For these exceptions only, listing a predetermined 4561 // variable in a data-sharing attribute clause is allowed and overrides 4562 // the variable's predetermined data-sharing attributes. 4563 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 4564 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 4565 DVar.RefExpr) { 4566 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 4567 << getOpenMPClauseName(OMPC_shared); 4568 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4569 continue; 4570 } 4571 4572 DSAStack->addDSA(VD, DE, OMPC_shared); 4573 Vars.push_back(DE); 4574 } 4575 4576 if (Vars.empty()) 4577 return nullptr; 4578 4579 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 4580 } 4581 4582 namespace { 4583 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 4584 DSAStackTy *Stack; 4585 4586 public: 4587 bool VisitDeclRefExpr(DeclRefExpr *E) { 4588 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 4589 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 4590 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 4591 return false; 4592 if (DVar.CKind != OMPC_unknown) 4593 return true; 4594 DSAStackTy::DSAVarData DVarPrivate = 4595 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false); 4596 if (DVarPrivate.CKind != OMPC_unknown) 4597 return true; 4598 return false; 4599 } 4600 return false; 4601 } 4602 bool VisitStmt(Stmt *S) { 4603 for (auto Child : S->children()) { 4604 if (Child && Visit(Child)) 4605 return true; 4606 } 4607 return false; 4608 } 4609 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 4610 }; 4611 } // namespace 4612 4613 OMPClause *Sema::ActOnOpenMPReductionClause( 4614 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 4615 SourceLocation ColonLoc, SourceLocation EndLoc, 4616 CXXScopeSpec &ReductionIdScopeSpec, 4617 const DeclarationNameInfo &ReductionId) { 4618 // TODO: Allow scope specification search when 'declare reduction' is 4619 // supported. 4620 assert(ReductionIdScopeSpec.isEmpty() && 4621 "No support for scoped reduction identifiers yet."); 4622 4623 auto DN = ReductionId.getName(); 4624 auto OOK = DN.getCXXOverloadedOperator(); 4625 BinaryOperatorKind BOK = BO_Comma; 4626 4627 // OpenMP [2.14.3.6, reduction clause] 4628 // C 4629 // reduction-identifier is either an identifier or one of the following 4630 // operators: +, -, *, &, |, ^, && and || 4631 // C++ 4632 // reduction-identifier is either an id-expression or one of the following 4633 // operators: +, -, *, &, |, ^, && and || 4634 // FIXME: Only 'min' and 'max' identifiers are supported for now. 4635 switch (OOK) { 4636 case OO_Plus: 4637 case OO_Minus: 4638 BOK = BO_AddAssign; 4639 break; 4640 case OO_Star: 4641 BOK = BO_MulAssign; 4642 break; 4643 case OO_Amp: 4644 BOK = BO_AndAssign; 4645 break; 4646 case OO_Pipe: 4647 BOK = BO_OrAssign; 4648 break; 4649 case OO_Caret: 4650 BOK = BO_XorAssign; 4651 break; 4652 case OO_AmpAmp: 4653 BOK = BO_LAnd; 4654 break; 4655 case OO_PipePipe: 4656 BOK = BO_LOr; 4657 break; 4658 default: 4659 if (auto II = DN.getAsIdentifierInfo()) { 4660 if (II->isStr("max")) 4661 BOK = BO_GT; 4662 else if (II->isStr("min")) 4663 BOK = BO_LT; 4664 } 4665 break; 4666 } 4667 SourceRange ReductionIdRange; 4668 if (ReductionIdScopeSpec.isValid()) { 4669 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 4670 } 4671 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 4672 if (BOK == BO_Comma) { 4673 // Not allowed reduction identifier is found. 4674 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier) 4675 << ReductionIdRange; 4676 return nullptr; 4677 } 4678 4679 SmallVector<Expr *, 8> Vars; 4680 for (auto RefExpr : VarList) { 4681 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 4682 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 4683 // It will be analyzed later. 4684 Vars.push_back(RefExpr); 4685 continue; 4686 } 4687 4688 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 4689 RefExpr->isInstantiationDependent() || 4690 RefExpr->containsUnexpandedParameterPack()) { 4691 // It will be analyzed later. 4692 Vars.push_back(RefExpr); 4693 continue; 4694 } 4695 4696 auto ELoc = RefExpr->getExprLoc(); 4697 auto ERange = RefExpr->getSourceRange(); 4698 // OpenMP [2.1, C/C++] 4699 // A list item is a variable or array section, subject to the restrictions 4700 // specified in Section 2.4 on page 42 and in each of the sections 4701 // describing clauses and directives for which a list appears. 4702 // OpenMP [2.14.3.3, Restrictions, p.1] 4703 // A variable that is part of another variable (as an array or 4704 // structure element) cannot appear in a private clause. 4705 auto DE = dyn_cast<DeclRefExpr>(RefExpr); 4706 if (!DE || !isa<VarDecl>(DE->getDecl())) { 4707 Diag(ELoc, diag::err_omp_expected_var_name) << ERange; 4708 continue; 4709 } 4710 auto D = DE->getDecl(); 4711 auto VD = cast<VarDecl>(D); 4712 auto Type = VD->getType(); 4713 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 4714 // A variable that appears in a private clause must not have an incomplete 4715 // type or a reference type. 4716 if (RequireCompleteType(ELoc, Type, 4717 diag::err_omp_reduction_incomplete_type)) 4718 continue; 4719 // OpenMP [2.14.3.6, reduction clause, Restrictions] 4720 // Arrays may not appear in a reduction clause. 4721 if (Type.getNonReferenceType()->isArrayType()) { 4722 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange; 4723 bool IsDecl = 4724 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4725 Diag(VD->getLocation(), 4726 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4727 << VD; 4728 continue; 4729 } 4730 // OpenMP [2.14.3.6, reduction clause, Restrictions] 4731 // A list item that appears in a reduction clause must not be 4732 // const-qualified. 4733 if (Type.getNonReferenceType().isConstant(Context)) { 4734 Diag(ELoc, diag::err_omp_const_variable) 4735 << getOpenMPClauseName(OMPC_reduction) << Type << ERange; 4736 bool IsDecl = 4737 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4738 Diag(VD->getLocation(), 4739 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4740 << VD; 4741 continue; 4742 } 4743 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 4744 // If a list-item is a reference type then it must bind to the same object 4745 // for all threads of the team. 4746 VarDecl *VDDef = VD->getDefinition(); 4747 if (Type->isReferenceType() && VDDef) { 4748 DSARefChecker Check(DSAStack); 4749 if (Check.Visit(VDDef->getInit())) { 4750 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange; 4751 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 4752 continue; 4753 } 4754 } 4755 // OpenMP [2.14.3.6, reduction clause, Restrictions] 4756 // The type of a list item that appears in a reduction clause must be valid 4757 // for the reduction-identifier. For a max or min reduction in C, the type 4758 // of the list item must be an allowed arithmetic data type: char, int, 4759 // float, double, or _Bool, possibly modified with long, short, signed, or 4760 // unsigned. For a max or min reduction in C++, the type of the list item 4761 // must be an allowed arithmetic data type: char, wchar_t, int, float, 4762 // double, or bool, possibly modified with long, short, signed, or unsigned. 4763 if ((BOK == BO_GT || BOK == BO_LT) && 4764 !(Type->isScalarType() || 4765 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 4766 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 4767 << getLangOpts().CPlusPlus; 4768 bool IsDecl = 4769 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4770 Diag(VD->getLocation(), 4771 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4772 << VD; 4773 continue; 4774 } 4775 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 4776 !getLangOpts().CPlusPlus && Type->isFloatingType()) { 4777 Diag(ELoc, diag::err_omp_clause_floating_type_arg); 4778 bool IsDecl = 4779 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4780 Diag(VD->getLocation(), 4781 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4782 << VD; 4783 continue; 4784 } 4785 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 4786 getDiagnostics().setSuppressAllDiagnostics(true); 4787 ExprResult ReductionOp = 4788 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK, 4789 RefExpr, RefExpr); 4790 getDiagnostics().setSuppressAllDiagnostics(Suppress); 4791 if (ReductionOp.isInvalid()) { 4792 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type 4793 << ReductionIdRange; 4794 bool IsDecl = 4795 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4796 Diag(VD->getLocation(), 4797 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4798 << VD; 4799 continue; 4800 } 4801 4802 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4803 // in a Construct] 4804 // Variables with the predetermined data-sharing attributes may not be 4805 // listed in data-sharing attributes clauses, except for the cases 4806 // listed below. For these exceptions only, listing a predetermined 4807 // variable in a data-sharing attribute clause is allowed and overrides 4808 // the variable's predetermined data-sharing attributes. 4809 // OpenMP [2.14.3.6, Restrictions, p.3] 4810 // Any number of reduction clauses can be specified on the directive, 4811 // but a list item can appear only once in the reduction clauses for that 4812 // directive. 4813 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 4814 if (DVar.CKind == OMPC_reduction) { 4815 Diag(ELoc, diag::err_omp_once_referenced) 4816 << getOpenMPClauseName(OMPC_reduction); 4817 if (DVar.RefExpr) { 4818 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 4819 } 4820 } else if (DVar.CKind != OMPC_unknown) { 4821 Diag(ELoc, diag::err_omp_wrong_dsa) 4822 << getOpenMPClauseName(DVar.CKind) 4823 << getOpenMPClauseName(OMPC_reduction); 4824 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4825 continue; 4826 } 4827 4828 // OpenMP [2.14.3.6, Restrictions, p.1] 4829 // A list item that appears in a reduction clause of a worksharing 4830 // construct must be shared in the parallel regions to which any of the 4831 // worksharing regions arising from the worksharing construct bind. 4832 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 4833 if (isOpenMPWorksharingDirective(CurrDir) && 4834 !isOpenMPParallelDirective(CurrDir)) { 4835 DVar = DSAStack->getImplicitDSA(VD, true); 4836 if (DVar.CKind != OMPC_shared) { 4837 Diag(ELoc, diag::err_omp_required_access) 4838 << getOpenMPClauseName(OMPC_reduction) 4839 << getOpenMPClauseName(OMPC_shared); 4840 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4841 continue; 4842 } 4843 } 4844 4845 CXXRecordDecl *RD = getLangOpts().CPlusPlus 4846 ? Type.getNonReferenceType()->getAsCXXRecordDecl() 4847 : nullptr; 4848 // FIXME This code must be replaced by actual constructing/destructing of 4849 // the reduction variable. 4850 if (RD) { 4851 CXXConstructorDecl *CD = LookupDefaultConstructor(RD); 4852 PartialDiagnostic PD = 4853 PartialDiagnostic(PartialDiagnostic::NullDiagnostic()); 4854 if (!CD || 4855 CheckConstructorAccess(ELoc, CD, 4856 InitializedEntity::InitializeTemporary(Type), 4857 CD->getAccess(), PD) == AR_inaccessible || 4858 CD->isDeleted()) { 4859 Diag(ELoc, diag::err_omp_required_method) 4860 << getOpenMPClauseName(OMPC_reduction) << 0; 4861 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 4862 VarDecl::DeclarationOnly; 4863 Diag(VD->getLocation(), 4864 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4865 << VD; 4866 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 4867 continue; 4868 } 4869 MarkFunctionReferenced(ELoc, CD); 4870 DiagnoseUseOfDecl(CD, ELoc); 4871 4872 CXXDestructorDecl *DD = RD->getDestructor(); 4873 if (DD) { 4874 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible || 4875 DD->isDeleted()) { 4876 Diag(ELoc, diag::err_omp_required_method) 4877 << getOpenMPClauseName(OMPC_reduction) << 4; 4878 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 4879 VarDecl::DeclarationOnly; 4880 Diag(VD->getLocation(), 4881 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4882 << VD; 4883 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 4884 continue; 4885 } 4886 MarkFunctionReferenced(ELoc, DD); 4887 DiagnoseUseOfDecl(DD, ELoc); 4888 } 4889 } 4890 4891 DSAStack->addDSA(VD, DE, OMPC_reduction); 4892 Vars.push_back(DE); 4893 } 4894 4895 if (Vars.empty()) 4896 return nullptr; 4897 4898 return OMPReductionClause::Create( 4899 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars, 4900 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId); 4901 } 4902 4903 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, 4904 SourceLocation StartLoc, 4905 SourceLocation LParenLoc, 4906 SourceLocation ColonLoc, 4907 SourceLocation EndLoc) { 4908 SmallVector<Expr *, 8> Vars; 4909 for (auto &RefExpr : VarList) { 4910 assert(RefExpr && "NULL expr in OpenMP linear clause."); 4911 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 4912 // It will be analyzed later. 4913 Vars.push_back(RefExpr); 4914 continue; 4915 } 4916 4917 // OpenMP [2.14.3.7, linear clause] 4918 // A list item that appears in a linear clause is subject to the private 4919 // clause semantics described in Section 2.14.3.3 on page 159 except as 4920 // noted. In addition, the value of the new list item on each iteration 4921 // of the associated loop(s) corresponds to the value of the original 4922 // list item before entering the construct plus the logical number of 4923 // the iteration times linear-step. 4924 4925 SourceLocation ELoc = RefExpr->getExprLoc(); 4926 // OpenMP [2.1, C/C++] 4927 // A list item is a variable name. 4928 // OpenMP [2.14.3.3, Restrictions, p.1] 4929 // A variable that is part of another variable (as an array or 4930 // structure element) cannot appear in a private clause. 4931 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 4932 if (!DE || !isa<VarDecl>(DE->getDecl())) { 4933 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 4934 continue; 4935 } 4936 4937 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 4938 4939 // OpenMP [2.14.3.7, linear clause] 4940 // A list-item cannot appear in more than one linear clause. 4941 // A list-item that appears in a linear clause cannot appear in any 4942 // other data-sharing attribute clause. 4943 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 4944 if (DVar.RefExpr) { 4945 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 4946 << getOpenMPClauseName(OMPC_linear); 4947 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4948 continue; 4949 } 4950 4951 QualType QType = VD->getType(); 4952 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 4953 // It will be analyzed later. 4954 Vars.push_back(DE); 4955 continue; 4956 } 4957 4958 // A variable must not have an incomplete type or a reference type. 4959 if (RequireCompleteType(ELoc, QType, 4960 diag::err_omp_linear_incomplete_type)) { 4961 continue; 4962 } 4963 if (QType->isReferenceType()) { 4964 Diag(ELoc, diag::err_omp_clause_ref_type_arg) 4965 << getOpenMPClauseName(OMPC_linear) << QType; 4966 bool IsDecl = 4967 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4968 Diag(VD->getLocation(), 4969 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4970 << VD; 4971 continue; 4972 } 4973 4974 // A list item must not be const-qualified. 4975 if (QType.isConstant(Context)) { 4976 Diag(ELoc, diag::err_omp_const_variable) 4977 << getOpenMPClauseName(OMPC_linear); 4978 bool IsDecl = 4979 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4980 Diag(VD->getLocation(), 4981 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4982 << VD; 4983 continue; 4984 } 4985 4986 // A list item must be of integral or pointer type. 4987 QType = QType.getUnqualifiedType().getCanonicalType(); 4988 const Type *Ty = QType.getTypePtrOrNull(); 4989 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 4990 !Ty->isPointerType())) { 4991 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType; 4992 bool IsDecl = 4993 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4994 Diag(VD->getLocation(), 4995 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4996 << VD; 4997 continue; 4998 } 4999 5000 DSAStack->addDSA(VD, DE, OMPC_linear); 5001 Vars.push_back(DE); 5002 } 5003 5004 if (Vars.empty()) 5005 return nullptr; 5006 5007 Expr *StepExpr = Step; 5008 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 5009 !Step->isInstantiationDependent() && 5010 !Step->containsUnexpandedParameterPack()) { 5011 SourceLocation StepLoc = Step->getLocStart(); 5012 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 5013 if (Val.isInvalid()) 5014 return nullptr; 5015 StepExpr = Val.get(); 5016 5017 // Warn about zero linear step (it would be probably better specified as 5018 // making corresponding variables 'const'). 5019 llvm::APSInt Result; 5020 if (StepExpr->isIntegerConstantExpr(Result, Context) && 5021 !Result.isNegative() && !Result.isStrictlyPositive()) 5022 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 5023 << (Vars.size() > 1); 5024 } 5025 5026 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc, 5027 Vars, StepExpr); 5028 } 5029 5030 OMPClause *Sema::ActOnOpenMPAlignedClause( 5031 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 5032 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 5033 5034 SmallVector<Expr *, 8> Vars; 5035 for (auto &RefExpr : VarList) { 5036 assert(RefExpr && "NULL expr in OpenMP aligned clause."); 5037 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 5038 // It will be analyzed later. 5039 Vars.push_back(RefExpr); 5040 continue; 5041 } 5042 5043 SourceLocation ELoc = RefExpr->getExprLoc(); 5044 // OpenMP [2.1, C/C++] 5045 // A list item is a variable name. 5046 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 5047 if (!DE || !isa<VarDecl>(DE->getDecl())) { 5048 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 5049 continue; 5050 } 5051 5052 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 5053 5054 // OpenMP [2.8.1, simd construct, Restrictions] 5055 // The type of list items appearing in the aligned clause must be 5056 // array, pointer, reference to array, or reference to pointer. 5057 QualType QType = DE->getType() 5058 .getNonReferenceType() 5059 .getUnqualifiedType() 5060 .getCanonicalType(); 5061 const Type *Ty = QType.getTypePtrOrNull(); 5062 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() && 5063 !Ty->isPointerType())) { 5064 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 5065 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange(); 5066 bool IsDecl = 5067 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 5068 Diag(VD->getLocation(), 5069 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 5070 << VD; 5071 continue; 5072 } 5073 5074 // OpenMP [2.8.1, simd construct, Restrictions] 5075 // A list-item cannot appear in more than one aligned clause. 5076 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) { 5077 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange(); 5078 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 5079 << getOpenMPClauseName(OMPC_aligned); 5080 continue; 5081 } 5082 5083 Vars.push_back(DE); 5084 } 5085 5086 // OpenMP [2.8.1, simd construct, Description] 5087 // The parameter of the aligned clause, alignment, must be a constant 5088 // positive integer expression. 5089 // If no optional parameter is specified, implementation-defined default 5090 // alignments for SIMD instructions on the target platforms are assumed. 5091 if (Alignment != nullptr) { 5092 ExprResult AlignResult = 5093 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 5094 if (AlignResult.isInvalid()) 5095 return nullptr; 5096 Alignment = AlignResult.get(); 5097 } 5098 if (Vars.empty()) 5099 return nullptr; 5100 5101 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 5102 EndLoc, Vars, Alignment); 5103 } 5104 5105 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 5106 SourceLocation StartLoc, 5107 SourceLocation LParenLoc, 5108 SourceLocation EndLoc) { 5109 SmallVector<Expr *, 8> Vars; 5110 for (auto &RefExpr : VarList) { 5111 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 5112 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 5113 // It will be analyzed later. 5114 Vars.push_back(RefExpr); 5115 continue; 5116 } 5117 5118 SourceLocation ELoc = RefExpr->getExprLoc(); 5119 // OpenMP [2.1, C/C++] 5120 // A list item is a variable name. 5121 // OpenMP [2.14.4.1, Restrictions, p.1] 5122 // A list item that appears in a copyin clause must be threadprivate. 5123 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 5124 if (!DE || !isa<VarDecl>(DE->getDecl())) { 5125 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 5126 continue; 5127 } 5128 5129 Decl *D = DE->getDecl(); 5130 VarDecl *VD = cast<VarDecl>(D); 5131 5132 QualType Type = VD->getType(); 5133 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 5134 // It will be analyzed later. 5135 Vars.push_back(DE); 5136 continue; 5137 } 5138 5139 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 5140 // A list item that appears in a copyin clause must be threadprivate. 5141 if (!DSAStack->isThreadPrivate(VD)) { 5142 Diag(ELoc, diag::err_omp_required_access) 5143 << getOpenMPClauseName(OMPC_copyin) 5144 << getOpenMPDirectiveName(OMPD_threadprivate); 5145 continue; 5146 } 5147 5148 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 5149 // A variable of class type (or array thereof) that appears in a 5150 // copyin clause requires an accessible, unambiguous copy assignment 5151 // operator for the class type. 5152 Type = Context.getBaseElementType(Type); 5153 CXXRecordDecl *RD = 5154 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 5155 // FIXME This code must be replaced by actual assignment of the 5156 // threadprivate variable. 5157 if (RD) { 5158 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0); 5159 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess()); 5160 if (MD) { 5161 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible || 5162 MD->isDeleted()) { 5163 Diag(ELoc, diag::err_omp_required_method) 5164 << getOpenMPClauseName(OMPC_copyin) << 2; 5165 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 5166 VarDecl::DeclarationOnly; 5167 Diag(VD->getLocation(), 5168 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 5169 << VD; 5170 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 5171 continue; 5172 } 5173 MarkFunctionReferenced(ELoc, MD); 5174 DiagnoseUseOfDecl(MD, ELoc); 5175 } 5176 } 5177 5178 DSAStack->addDSA(VD, DE, OMPC_copyin); 5179 Vars.push_back(DE); 5180 } 5181 5182 if (Vars.empty()) 5183 return nullptr; 5184 5185 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 5186 } 5187 5188 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 5189 SourceLocation StartLoc, 5190 SourceLocation LParenLoc, 5191 SourceLocation EndLoc) { 5192 SmallVector<Expr *, 8> Vars; 5193 for (auto &RefExpr : VarList) { 5194 assert(RefExpr && "NULL expr in OpenMP copyprivate clause."); 5195 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 5196 // It will be analyzed later. 5197 Vars.push_back(RefExpr); 5198 continue; 5199 } 5200 5201 SourceLocation ELoc = RefExpr->getExprLoc(); 5202 // OpenMP [2.1, C/C++] 5203 // A list item is a variable name. 5204 // OpenMP [2.14.4.1, Restrictions, p.1] 5205 // A list item that appears in a copyin clause must be threadprivate. 5206 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 5207 if (!DE || !isa<VarDecl>(DE->getDecl())) { 5208 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 5209 continue; 5210 } 5211 5212 Decl *D = DE->getDecl(); 5213 VarDecl *VD = cast<VarDecl>(D); 5214 5215 QualType Type = VD->getType(); 5216 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 5217 // It will be analyzed later. 5218 Vars.push_back(DE); 5219 continue; 5220 } 5221 5222 // OpenMP [2.14.4.2, Restrictions, p.2] 5223 // A list item that appears in a copyprivate clause may not appear in a 5224 // private or firstprivate clause on the single construct. 5225 if (!DSAStack->isThreadPrivate(VD)) { 5226 auto DVar = DSAStack->getTopDSA(VD, false); 5227 if (DVar.CKind != OMPC_copyprivate && DVar.CKind != OMPC_unknown && 5228 !(DVar.CKind == OMPC_private && !DVar.RefExpr)) { 5229 Diag(ELoc, diag::err_omp_wrong_dsa) 5230 << getOpenMPClauseName(DVar.CKind) 5231 << getOpenMPClauseName(OMPC_copyprivate); 5232 ReportOriginalDSA(*this, DSAStack, VD, DVar); 5233 continue; 5234 } 5235 5236 // OpenMP [2.11.4.2, Restrictions, p.1] 5237 // All list items that appear in a copyprivate clause must be either 5238 // threadprivate or private in the enclosing context. 5239 if (DVar.CKind == OMPC_unknown) { 5240 DVar = DSAStack->getImplicitDSA(VD, false); 5241 if (DVar.CKind == OMPC_shared) { 5242 Diag(ELoc, diag::err_omp_required_access) 5243 << getOpenMPClauseName(OMPC_copyprivate) 5244 << "threadprivate or private in the enclosing context"; 5245 ReportOriginalDSA(*this, DSAStack, VD, DVar); 5246 continue; 5247 } 5248 } 5249 } 5250 5251 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 5252 // A variable of class type (or array thereof) that appears in a 5253 // copyin clause requires an accessible, unambiguous copy assignment 5254 // operator for the class type. 5255 Type = Context.getBaseElementType(Type); 5256 CXXRecordDecl *RD = 5257 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 5258 // FIXME This code must be replaced by actual assignment of the 5259 // threadprivate variable. 5260 if (RD) { 5261 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0); 5262 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess()); 5263 if (MD) { 5264 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible || 5265 MD->isDeleted()) { 5266 Diag(ELoc, diag::err_omp_required_method) 5267 << getOpenMPClauseName(OMPC_copyprivate) << 2; 5268 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 5269 VarDecl::DeclarationOnly; 5270 Diag(VD->getLocation(), 5271 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 5272 << VD; 5273 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 5274 continue; 5275 } 5276 MarkFunctionReferenced(ELoc, MD); 5277 DiagnoseUseOfDecl(MD, ELoc); 5278 } 5279 } 5280 5281 // No need to mark vars as copyprivate, they are already threadprivate or 5282 // implicitly private. 5283 Vars.push_back(DE); 5284 } 5285 5286 if (Vars.empty()) 5287 return nullptr; 5288 5289 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 5290 } 5291 5292 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 5293 SourceLocation StartLoc, 5294 SourceLocation LParenLoc, 5295 SourceLocation EndLoc) { 5296 if (VarList.empty()) 5297 return nullptr; 5298 5299 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 5300 } 5301 5302