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