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