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