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