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