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/CXXInheritance.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclOpenMP.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeOrdering.h" 26 #include "clang/Basic/OpenMPKinds.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Sema/Initialization.h" 30 #include "clang/Sema/Lookup.h" 31 #include "clang/Sema/Scope.h" 32 #include "clang/Sema/ScopeInfo.h" 33 #include "clang/Sema/SemaInternal.h" 34 using namespace clang; 35 36 //===----------------------------------------------------------------------===// 37 // Stack of data-sharing attributes for variables 38 //===----------------------------------------------------------------------===// 39 40 namespace { 41 /// \brief Default data sharing attributes, which can be applied to directive. 42 enum DefaultDataSharingAttributes { 43 DSA_unspecified = 0, /// \brief Data sharing attribute not specified. 44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'. 45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'. 46 }; 47 48 /// \brief Stack for tracking declarations used in OpenMP directives and 49 /// clauses and their data-sharing attributes. 50 class DSAStackTy final { 51 public: 52 struct DSAVarData final { 53 OpenMPDirectiveKind DKind = OMPD_unknown; 54 OpenMPClauseKind CKind = OMPC_unknown; 55 Expr *RefExpr = nullptr; 56 DeclRefExpr *PrivateCopy = nullptr; 57 SourceLocation ImplicitDSALoc; 58 DSAVarData() {} 59 }; 60 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4> 61 OperatorOffsetTy; 62 63 private: 64 struct DSAInfo final { 65 OpenMPClauseKind Attributes = OMPC_unknown; 66 /// Pointer to a reference expression and a flag which shows that the 67 /// variable is marked as lastprivate(true) or not (false). 68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr; 69 DeclRefExpr *PrivateCopy = nullptr; 70 }; 71 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy; 72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy; 73 typedef std::pair<unsigned, VarDecl *> LCDeclInfo; 74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy; 75 typedef llvm::DenseMap< 76 ValueDecl *, OMPClauseMappableExprCommon::MappableExprComponentLists> 77 MappedExprComponentsTy; 78 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>> 79 CriticalsWithHintsTy; 80 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy> 81 DoacrossDependMapTy; 82 83 struct SharingMapTy final { 84 DeclSAMapTy SharingMap; 85 AlignedMapTy AlignedMap; 86 MappedExprComponentsTy MappedExprComponents; 87 LoopControlVariablesMapTy LCVMap; 88 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 89 SourceLocation DefaultAttrLoc; 90 OpenMPDirectiveKind Directive = OMPD_unknown; 91 DeclarationNameInfo DirectiveName; 92 Scope *CurScope = nullptr; 93 SourceLocation ConstructLoc; 94 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 95 /// get the data (loop counters etc.) about enclosing loop-based construct. 96 /// This data is required during codegen. 97 DoacrossDependMapTy DoacrossDepends; 98 /// \brief first argument (Expr *) contains optional argument of the 99 /// 'ordered' clause, the second one is true if the regions has 'ordered' 100 /// clause, false otherwise. 101 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion; 102 bool NowaitRegion = false; 103 bool CancelRegion = false; 104 unsigned AssociatedLoops = 1; 105 SourceLocation InnerTeamsRegionLoc; 106 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 107 Scope *CurScope, SourceLocation Loc) 108 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 109 ConstructLoc(Loc) {} 110 SharingMapTy() {} 111 }; 112 113 typedef SmallVector<SharingMapTy, 4> StackTy; 114 115 /// \brief Stack of used declaration and their data-sharing attributes. 116 StackTy Stack; 117 /// \brief true, if check for DSA must be from parent directive, false, if 118 /// from current directive. 119 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 120 Sema &SemaRef; 121 bool ForceCapturing = false; 122 CriticalsWithHintsTy Criticals; 123 124 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; 125 126 DSAVarData getDSA(StackTy::reverse_iterator& Iter, ValueDecl *D); 127 128 /// \brief Checks if the variable is a local for OpenMP region. 129 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); 130 131 public: 132 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {} 133 134 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 135 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 136 137 bool isForceVarCapturing() const { return ForceCapturing; } 138 void setForceVarCapturing(bool V) { ForceCapturing = V; } 139 140 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 141 Scope *CurScope, SourceLocation Loc) { 142 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc)); 143 Stack.back().DefaultAttrLoc = Loc; 144 } 145 146 void pop() { 147 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!"); 148 Stack.pop_back(); 149 } 150 151 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) { 152 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint); 153 } 154 const std::pair<OMPCriticalDirective *, llvm::APSInt> 155 getCriticalWithHint(const DeclarationNameInfo &Name) const { 156 auto I = Criticals.find(Name.getAsString()); 157 if (I != Criticals.end()) 158 return I->second; 159 return std::make_pair(nullptr, llvm::APSInt()); 160 } 161 /// \brief If 'aligned' declaration for given variable \a D was not seen yet, 162 /// add it and return NULL; otherwise return previous occurrence's expression 163 /// for diagnostics. 164 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE); 165 166 /// \brief Register specified variable as loop control variable. 167 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture); 168 /// \brief Check if the specified variable is a loop control variable for 169 /// current region. 170 /// \return The index of the loop control variable in the list of associated 171 /// for-loops (from outer to inner). 172 LCDeclInfo isLoopControlVariable(ValueDecl *D); 173 /// \brief Check if the specified variable is a loop control variable for 174 /// parent region. 175 /// \return The index of the loop control variable in the list of associated 176 /// for-loops (from outer to inner). 177 LCDeclInfo isParentLoopControlVariable(ValueDecl *D); 178 /// \brief Get the loop control variable for the I-th loop (or nullptr) in 179 /// parent directive. 180 ValueDecl *getParentLoopControlVariable(unsigned I); 181 182 /// \brief Adds explicit data sharing attribute to the specified declaration. 183 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 184 DeclRefExpr *PrivateCopy = nullptr); 185 186 /// \brief Returns data sharing attributes from top of the stack for the 187 /// specified declaration. 188 DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 189 /// \brief Returns data-sharing attributes for the specified declaration. 190 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent); 191 /// \brief Checks if the specified variables has data-sharing attributes which 192 /// match specified \a CPred predicate in any directive which matches \a DPred 193 /// predicate. 194 DSAVarData hasDSA(ValueDecl *D, 195 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 196 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 197 bool FromParent); 198 /// \brief Checks if the specified variables has data-sharing attributes which 199 /// match specified \a CPred predicate in any innermost directive which 200 /// matches \a DPred predicate. 201 DSAVarData 202 hasInnermostDSA(ValueDecl *D, 203 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 204 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 205 bool FromParent); 206 /// \brief Checks if the specified variables has explicit data-sharing 207 /// attributes which match specified \a CPred predicate at the specified 208 /// OpenMP region. 209 bool hasExplicitDSA(ValueDecl *D, 210 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 211 unsigned Level, bool NotLastprivate = false); 212 213 /// \brief Returns true if the directive at level \Level matches in the 214 /// specified \a DPred predicate. 215 bool hasExplicitDirective( 216 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 217 unsigned Level); 218 219 /// \brief Finds a directive which matches specified \a DPred predicate. 220 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind, 221 const DeclarationNameInfo &, 222 SourceLocation)> &DPred, 223 bool FromParent); 224 225 /// \brief Returns currently analyzed directive. 226 OpenMPDirectiveKind getCurrentDirective() const { 227 return Stack.back().Directive; 228 } 229 /// \brief Returns parent directive. 230 OpenMPDirectiveKind getParentDirective() const { 231 if (Stack.size() > 2) 232 return Stack[Stack.size() - 2].Directive; 233 return OMPD_unknown; 234 } 235 236 /// \brief Set default data sharing attribute to none. 237 void setDefaultDSANone(SourceLocation Loc) { 238 Stack.back().DefaultAttr = DSA_none; 239 Stack.back().DefaultAttrLoc = Loc; 240 } 241 /// \brief Set default data sharing attribute to shared. 242 void setDefaultDSAShared(SourceLocation Loc) { 243 Stack.back().DefaultAttr = DSA_shared; 244 Stack.back().DefaultAttrLoc = Loc; 245 } 246 247 DefaultDataSharingAttributes getDefaultDSA() const { 248 return Stack.back().DefaultAttr; 249 } 250 SourceLocation getDefaultDSALocation() const { 251 return Stack.back().DefaultAttrLoc; 252 } 253 254 /// \brief Checks if the specified variable is a threadprivate. 255 bool isThreadPrivate(VarDecl *D) { 256 DSAVarData DVar = getTopDSA(D, false); 257 return isOpenMPThreadPrivate(DVar.CKind); 258 } 259 260 /// \brief Marks current region as ordered (it has an 'ordered' clause). 261 void setOrderedRegion(bool IsOrdered, Expr *Param) { 262 Stack.back().OrderedRegion.setInt(IsOrdered); 263 Stack.back().OrderedRegion.setPointer(Param); 264 } 265 /// \brief Returns true, if parent region is ordered (has associated 266 /// 'ordered' clause), false - otherwise. 267 bool isParentOrderedRegion() const { 268 if (Stack.size() > 2) 269 return Stack[Stack.size() - 2].OrderedRegion.getInt(); 270 return false; 271 } 272 /// \brief Returns optional parameter for the ordered region. 273 Expr *getParentOrderedRegionParam() const { 274 if (Stack.size() > 2) 275 return Stack[Stack.size() - 2].OrderedRegion.getPointer(); 276 return nullptr; 277 } 278 /// \brief Marks current region as nowait (it has a 'nowait' clause). 279 void setNowaitRegion(bool IsNowait = true) { 280 Stack.back().NowaitRegion = IsNowait; 281 } 282 /// \brief Returns true, if parent region is nowait (has associated 283 /// 'nowait' clause), false - otherwise. 284 bool isParentNowaitRegion() const { 285 if (Stack.size() > 2) 286 return Stack[Stack.size() - 2].NowaitRegion; 287 return false; 288 } 289 /// \brief Marks parent region as cancel region. 290 void setParentCancelRegion(bool Cancel = true) { 291 if (Stack.size() > 2) 292 Stack[Stack.size() - 2].CancelRegion = 293 Stack[Stack.size() - 2].CancelRegion || Cancel; 294 } 295 /// \brief Return true if current region has inner cancel construct. 296 bool isCancelRegion() const { 297 return Stack.back().CancelRegion; 298 } 299 300 /// \brief Set collapse value for the region. 301 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; } 302 /// \brief Return collapse value for region. 303 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; } 304 305 /// \brief Marks current target region as one with closely nested teams 306 /// region. 307 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 308 if (Stack.size() > 2) 309 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc; 310 } 311 /// \brief Returns true, if current region has closely nested teams region. 312 bool hasInnerTeamsRegion() const { 313 return getInnerTeamsRegionLoc().isValid(); 314 } 315 /// \brief Returns location of the nested teams region (if any). 316 SourceLocation getInnerTeamsRegionLoc() const { 317 if (Stack.size() > 1) 318 return Stack.back().InnerTeamsRegionLoc; 319 return SourceLocation(); 320 } 321 322 Scope *getCurScope() const { return Stack.back().CurScope; } 323 Scope *getCurScope() { return Stack.back().CurScope; } 324 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; } 325 326 // Do the check specified in \a Check to all component lists and return true 327 // if any issue is found. 328 bool checkMappableExprComponentListsForDecl( 329 ValueDecl *VD, bool CurrentRegionOnly, 330 const llvm::function_ref<bool( 331 OMPClauseMappableExprCommon::MappableExprComponentListRef)> &Check) { 332 auto SI = Stack.rbegin(); 333 auto SE = Stack.rend(); 334 335 if (SI == SE) 336 return false; 337 338 if (CurrentRegionOnly) { 339 SE = std::next(SI); 340 } else { 341 ++SI; 342 } 343 344 for (; SI != SE; ++SI) { 345 auto MI = SI->MappedExprComponents.find(VD); 346 if (MI != SI->MappedExprComponents.end()) 347 for (auto &L : MI->second) 348 if (Check(L)) 349 return true; 350 } 351 return false; 352 } 353 354 // Create a new mappable expression component list associated with a given 355 // declaration and initialize it with the provided list of components. 356 void addMappableExpressionComponents( 357 ValueDecl *VD, 358 OMPClauseMappableExprCommon::MappableExprComponentListRef Components) { 359 assert(Stack.size() > 1 && 360 "Not expecting to retrieve components from a empty stack!"); 361 auto &MEC = Stack.back().MappedExprComponents[VD]; 362 // Create new entry and append the new components there. 363 MEC.resize(MEC.size() + 1); 364 MEC.back().append(Components.begin(), Components.end()); 365 } 366 367 unsigned getNestingLevel() const { 368 assert(Stack.size() > 1); 369 return Stack.size() - 2; 370 } 371 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) { 372 assert(Stack.size() > 2); 373 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive)); 374 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs}); 375 } 376 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 377 getDoacrossDependClauses() const { 378 assert(Stack.size() > 1); 379 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) { 380 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends; 381 return llvm::make_range(Ref.begin(), Ref.end()); 382 } 383 return llvm::make_range(Stack[0].DoacrossDepends.end(), 384 Stack[0].DoacrossDepends.end()); 385 } 386 }; 387 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 388 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || 389 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 390 } 391 } // namespace 392 393 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 394 auto *VD = dyn_cast<VarDecl>(D); 395 auto *FD = dyn_cast<FieldDecl>(D); 396 if (VD != nullptr) { 397 VD = VD->getCanonicalDecl(); 398 D = VD; 399 } else { 400 assert(FD); 401 FD = FD->getCanonicalDecl(); 402 D = FD; 403 } 404 return D; 405 } 406 407 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator& Iter, 408 ValueDecl *D) { 409 D = getCanonicalDecl(D); 410 auto *VD = dyn_cast<VarDecl>(D); 411 auto *FD = dyn_cast<FieldDecl>(D); 412 DSAVarData DVar; 413 if (Iter == std::prev(Stack.rend())) { 414 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 415 // in a region but not in construct] 416 // File-scope or namespace-scope variables referenced in called routines 417 // in the region are shared unless they appear in a threadprivate 418 // directive. 419 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 420 DVar.CKind = OMPC_shared; 421 422 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 423 // in a region but not in construct] 424 // Variables with static storage duration that are declared in called 425 // routines in the region are shared. 426 if (VD && VD->hasGlobalStorage()) 427 DVar.CKind = OMPC_shared; 428 429 // Non-static data members are shared by default. 430 if (FD) 431 DVar.CKind = OMPC_shared; 432 433 return DVar; 434 } 435 436 DVar.DKind = Iter->Directive; 437 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 438 // in a Construct, C/C++, predetermined, p.1] 439 // Variables with automatic storage duration that are declared in a scope 440 // inside the construct are private. 441 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 442 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 443 DVar.CKind = OMPC_private; 444 return DVar; 445 } 446 447 // Explicitly specified attributes and local variables with predetermined 448 // attributes. 449 if (Iter->SharingMap.count(D)) { 450 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer(); 451 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy; 452 DVar.CKind = Iter->SharingMap[D].Attributes; 453 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 454 return DVar; 455 } 456 457 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 458 // in a Construct, C/C++, implicitly determined, p.1] 459 // In a parallel or task construct, the data-sharing attributes of these 460 // variables are determined by the default clause, if present. 461 switch (Iter->DefaultAttr) { 462 case DSA_shared: 463 DVar.CKind = OMPC_shared; 464 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 465 return DVar; 466 case DSA_none: 467 return DVar; 468 case DSA_unspecified: 469 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 470 // in a Construct, implicitly determined, p.2] 471 // In a parallel construct, if no default clause is present, these 472 // variables are shared. 473 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 474 if (isOpenMPParallelDirective(DVar.DKind) || 475 isOpenMPTeamsDirective(DVar.DKind)) { 476 DVar.CKind = OMPC_shared; 477 return DVar; 478 } 479 480 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 481 // in a Construct, implicitly determined, p.4] 482 // In a task construct, if no default clause is present, a variable that in 483 // the enclosing context is determined to be shared by all implicit tasks 484 // bound to the current team is shared. 485 if (isOpenMPTaskingDirective(DVar.DKind)) { 486 DSAVarData DVarTemp; 487 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend(); 488 I != EE; ++I) { 489 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 490 // Referenced in a Construct, implicitly determined, p.6] 491 // In a task construct, if no default clause is present, a variable 492 // whose data-sharing attribute is not determined by the rules above is 493 // firstprivate. 494 DVarTemp = getDSA(I, D); 495 if (DVarTemp.CKind != OMPC_shared) { 496 DVar.RefExpr = nullptr; 497 DVar.CKind = OMPC_firstprivate; 498 return DVar; 499 } 500 if (isParallelOrTaskRegion(I->Directive)) 501 break; 502 } 503 DVar.CKind = 504 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 505 return DVar; 506 } 507 } 508 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 509 // in a Construct, implicitly determined, p.3] 510 // For constructs other than task, if no default clause is present, these 511 // variables inherit their data-sharing attributes from the enclosing 512 // context. 513 return getDSA(++Iter, D); 514 } 515 516 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) { 517 assert(Stack.size() > 1 && "Data sharing attributes stack is empty"); 518 D = getCanonicalDecl(D); 519 auto It = Stack.back().AlignedMap.find(D); 520 if (It == Stack.back().AlignedMap.end()) { 521 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 522 Stack.back().AlignedMap[D] = NewDE; 523 return nullptr; 524 } else { 525 assert(It->second && "Unexpected nullptr expr in the aligned map"); 526 return It->second; 527 } 528 return nullptr; 529 } 530 531 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) { 532 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 533 D = getCanonicalDecl(D); 534 Stack.back().LCVMap.insert( 535 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture))); 536 } 537 538 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) { 539 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 540 D = getCanonicalDecl(D); 541 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D] 542 : LCDeclInfo(0, nullptr); 543 } 544 545 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) { 546 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty"); 547 D = getCanonicalDecl(D); 548 return Stack[Stack.size() - 2].LCVMap.count(D) > 0 549 ? Stack[Stack.size() - 2].LCVMap[D] 550 : LCDeclInfo(0, nullptr); 551 } 552 553 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) { 554 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty"); 555 if (Stack[Stack.size() - 2].LCVMap.size() < I) 556 return nullptr; 557 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) { 558 if (Pair.second.first == I) 559 return Pair.first; 560 } 561 return nullptr; 562 } 563 564 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 565 DeclRefExpr *PrivateCopy) { 566 D = getCanonicalDecl(D); 567 if (A == OMPC_threadprivate) { 568 auto &Data = Stack[0].SharingMap[D]; 569 Data.Attributes = A; 570 Data.RefExpr.setPointer(E); 571 Data.PrivateCopy = nullptr; 572 } else { 573 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 574 auto &Data = Stack.back().SharingMap[D]; 575 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 576 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 577 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 578 (isLoopControlVariable(D).first && A == OMPC_private)); 579 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 580 Data.RefExpr.setInt(/*IntVal=*/true); 581 return; 582 } 583 const bool IsLastprivate = 584 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 585 Data.Attributes = A; 586 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 587 Data.PrivateCopy = PrivateCopy; 588 if (PrivateCopy) { 589 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()]; 590 Data.Attributes = A; 591 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 592 Data.PrivateCopy = nullptr; 593 } 594 } 595 } 596 597 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 598 D = D->getCanonicalDecl(); 599 if (Stack.size() > 2) { 600 reverse_iterator I = Iter, E = std::prev(Stack.rend()); 601 Scope *TopScope = nullptr; 602 while (I != E && !isParallelOrTaskRegion(I->Directive)) { 603 ++I; 604 } 605 if (I == E) 606 return false; 607 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 608 Scope *CurScope = getCurScope(); 609 while (CurScope != TopScope && !CurScope->isDeclScope(D)) { 610 CurScope = CurScope->getParent(); 611 } 612 return CurScope != TopScope; 613 } 614 return false; 615 } 616 617 /// \brief Build a variable declaration for OpenMP loop iteration variable. 618 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 619 StringRef Name, const AttrVec *Attrs = nullptr) { 620 DeclContext *DC = SemaRef.CurContext; 621 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 622 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 623 VarDecl *Decl = 624 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 625 if (Attrs) { 626 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 627 I != E; ++I) 628 Decl->addAttr(*I); 629 } 630 Decl->setImplicit(); 631 return Decl; 632 } 633 634 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 635 SourceLocation Loc, 636 bool RefersToCapture = false) { 637 D->setReferenced(); 638 D->markUsed(S.Context); 639 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 640 SourceLocation(), D, RefersToCapture, Loc, Ty, 641 VK_LValue); 642 } 643 644 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) { 645 D = getCanonicalDecl(D); 646 DSAVarData DVar; 647 648 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 649 // in a Construct, C/C++, predetermined, p.1] 650 // Variables appearing in threadprivate directives are threadprivate. 651 auto *VD = dyn_cast<VarDecl>(D); 652 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 653 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 654 SemaRef.getLangOpts().OpenMPUseTLS && 655 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 656 (VD && VD->getStorageClass() == SC_Register && 657 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 658 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 659 D->getLocation()), 660 OMPC_threadprivate); 661 } 662 if (Stack[0].SharingMap.count(D)) { 663 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer(); 664 DVar.CKind = OMPC_threadprivate; 665 return DVar; 666 } 667 668 if (Stack.size() == 1) { 669 // Not in OpenMP execution region and top scope was already checked. 670 return DVar; 671 } 672 673 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 674 // in a Construct, C/C++, predetermined, p.4] 675 // Static data members are shared. 676 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 677 // in a Construct, C/C++, predetermined, p.7] 678 // Variables with static storage duration that are declared in a scope 679 // inside the construct are shared. 680 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; 681 if (VD && VD->isStaticDataMember()) { 682 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 683 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 684 return DVar; 685 686 DVar.CKind = OMPC_shared; 687 return DVar; 688 } 689 690 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 691 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 692 Type = SemaRef.getASTContext().getBaseElementType(Type); 693 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 694 // in a Construct, C/C++, predetermined, p.6] 695 // Variables with const qualified type having no mutable member are 696 // shared. 697 CXXRecordDecl *RD = 698 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 699 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 700 if (auto *CTD = CTSD->getSpecializedTemplate()) 701 RD = CTD->getTemplatedDecl(); 702 if (IsConstant && 703 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && 704 RD->hasMutableFields())) { 705 // Variables with const-qualified type having no mutable member may be 706 // listed in a firstprivate clause, even if they are static data members. 707 DSAVarData DVarTemp = hasDSA( 708 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, 709 MatchesAlways, FromParent); 710 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 711 return DVar; 712 713 DVar.CKind = OMPC_shared; 714 return DVar; 715 } 716 717 // Explicitly specified attributes and local variables with predetermined 718 // attributes. 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 auto I = std::prev(StartI); 725 if (I->SharingMap.count(D)) { 726 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); 727 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; 728 DVar.CKind = I->SharingMap[D].Attributes; 729 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 730 } 731 732 return DVar; 733 } 734 735 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 736 bool FromParent) { 737 D = getCanonicalDecl(D); 738 auto StartI = Stack.rbegin(); 739 auto EndI = std::prev(Stack.rend()); 740 if (FromParent && StartI != EndI) { 741 StartI = std::next(StartI); 742 } 743 return getDSA(StartI, D); 744 } 745 746 DSAStackTy::DSAVarData 747 DSAStackTy::hasDSA(ValueDecl *D, 748 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 749 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 750 bool FromParent) { 751 D = getCanonicalDecl(D); 752 auto StartI = std::next(Stack.rbegin()); 753 auto EndI = Stack.rend(); 754 if (FromParent && StartI != EndI) { 755 StartI = std::next(StartI); 756 } 757 for (auto I = StartI, EE = EndI; I != EE; ++I) { 758 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 759 continue; 760 DSAVarData DVar = getDSA(I, D); 761 if (CPred(DVar.CKind)) 762 return DVar; 763 } 764 return DSAVarData(); 765 } 766 767 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 768 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 769 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 770 bool FromParent) { 771 D = getCanonicalDecl(D); 772 auto StartI = std::next(Stack.rbegin()); 773 auto EndI = Stack.rend(); 774 if (FromParent && StartI != EndI) 775 StartI = std::next(StartI); 776 if (StartI == EndI || !DPred(StartI->Directive)) 777 return DSAVarData(); 778 DSAVarData DVar = getDSA(StartI, D); 779 return CPred(DVar.CKind) ? DVar : DSAVarData(); 780 } 781 782 bool DSAStackTy::hasExplicitDSA( 783 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 784 unsigned Level, bool NotLastprivate) { 785 if (CPred(ClauseKindMode)) 786 return true; 787 D = getCanonicalDecl(D); 788 auto StartI = std::next(Stack.begin()); 789 auto EndI = Stack.end(); 790 if (std::distance(StartI, EndI) <= (int)Level) 791 return false; 792 std::advance(StartI, Level); 793 return (StartI->SharingMap.count(D) > 0) && 794 StartI->SharingMap[D].RefExpr.getPointer() && 795 CPred(StartI->SharingMap[D].Attributes) && 796 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt()); 797 } 798 799 bool DSAStackTy::hasExplicitDirective( 800 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 801 unsigned Level) { 802 auto StartI = std::next(Stack.begin()); 803 auto EndI = Stack.end(); 804 if (std::distance(StartI, EndI) <= (int)Level) 805 return false; 806 std::advance(StartI, Level); 807 return DPred(StartI->Directive); 808 } 809 810 bool DSAStackTy::hasDirective( 811 const llvm::function_ref<bool(OpenMPDirectiveKind, 812 const DeclarationNameInfo &, SourceLocation)> 813 &DPred, 814 bool FromParent) { 815 // We look only in the enclosing region. 816 if (Stack.size() < 2) 817 return false; 818 auto StartI = std::next(Stack.rbegin()); 819 auto EndI = std::prev(Stack.rend()); 820 if (FromParent && StartI != EndI) { 821 StartI = std::next(StartI); 822 } 823 for (auto I = StartI, EE = EndI; I != EE; ++I) { 824 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 825 return true; 826 } 827 return false; 828 } 829 830 void Sema::InitDataSharingAttributesStack() { 831 VarDataSharingAttributesStack = new DSAStackTy(*this); 832 } 833 834 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 835 836 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { 837 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 838 839 auto &Ctx = getASTContext(); 840 bool IsByRef = true; 841 842 // Find the directive that is associated with the provided scope. 843 auto Ty = D->getType(); 844 845 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 846 // This table summarizes how a given variable should be passed to the device 847 // given its type and the clauses where it appears. This table is based on 848 // the description in OpenMP 4.5 [2.10.4, target Construct] and 849 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 850 // 851 // ========================================================================= 852 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 853 // | |(tofrom:scalar)| | pvt | | | | 854 // ========================================================================= 855 // | scl | | | | - | | bycopy| 856 // | scl | | - | x | - | - | bycopy| 857 // | scl | | x | - | - | - | null | 858 // | scl | x | | | - | | byref | 859 // | scl | x | - | x | - | - | bycopy| 860 // | scl | x | x | - | - | - | null | 861 // | scl | | - | - | - | x | byref | 862 // | scl | x | - | - | - | x | byref | 863 // 864 // | agg | n.a. | | | - | | byref | 865 // | agg | n.a. | - | x | - | - | byref | 866 // | agg | n.a. | x | - | - | - | null | 867 // | agg | n.a. | - | - | - | x | byref | 868 // | agg | n.a. | - | - | - | x[] | byref | 869 // 870 // | ptr | n.a. | | | - | | bycopy| 871 // | ptr | n.a. | - | x | - | - | bycopy| 872 // | ptr | n.a. | x | - | - | - | null | 873 // | ptr | n.a. | - | - | - | x | byref | 874 // | ptr | n.a. | - | - | - | x[] | bycopy| 875 // | ptr | n.a. | - | - | x | | bycopy| 876 // | ptr | n.a. | - | - | x | x | bycopy| 877 // | ptr | n.a. | - | - | x | x[] | bycopy| 878 // ========================================================================= 879 // Legend: 880 // scl - scalar 881 // ptr - pointer 882 // agg - aggregate 883 // x - applies 884 // - - invalid in this combination 885 // [] - mapped with an array section 886 // byref - should be mapped by reference 887 // byval - should be mapped by value 888 // null - initialize a local variable to null on the device 889 // 890 // Observations: 891 // - All scalar declarations that show up in a map clause have to be passed 892 // by reference, because they may have been mapped in the enclosing data 893 // environment. 894 // - If the scalar value does not fit the size of uintptr, it has to be 895 // passed by reference, regardless the result in the table above. 896 // - For pointers mapped by value that have either an implicit map or an 897 // array section, the runtime library may pass the NULL value to the 898 // device instead of the value passed to it by the compiler. 899 900 901 if (Ty->isReferenceType()) 902 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 903 904 // Locate map clauses and see if the variable being captured is referred to 905 // in any of those clauses. Here we only care about variables, not fields, 906 // because fields are part of aggregates. 907 bool IsVariableUsedInMapClause = false; 908 bool IsVariableAssociatedWithSection = false; 909 910 DSAStack->checkMappableExprComponentListsForDecl( 911 D, /*CurrentRegionOnly=*/true, 912 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 913 MapExprComponents) { 914 915 auto EI = MapExprComponents.rbegin(); 916 auto EE = MapExprComponents.rend(); 917 918 assert(EI != EE && "Invalid map expression!"); 919 920 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 921 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 922 923 ++EI; 924 if (EI == EE) 925 return false; 926 927 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 928 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 929 isa<MemberExpr>(EI->getAssociatedExpression())) { 930 IsVariableAssociatedWithSection = true; 931 // There is nothing more we need to know about this variable. 932 return true; 933 } 934 935 // Keep looking for more map info. 936 return false; 937 }); 938 939 if (IsVariableUsedInMapClause) { 940 // If variable is identified in a map clause it is always captured by 941 // reference except if it is a pointer that is dereferenced somehow. 942 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 943 } else { 944 // By default, all the data that has a scalar type is mapped by copy. 945 IsByRef = !Ty->isScalarType(); 946 } 947 } 948 949 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 950 IsByRef = !DSAStack->hasExplicitDSA( 951 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 952 Level, /*NotLastprivate=*/true); 953 } 954 955 // When passing data by copy, we need to make sure it fits the uintptr size 956 // and alignment, because the runtime library only deals with uintptr types. 957 // If it does not fit the uintptr size, we need to pass the data by reference 958 // instead. 959 if (!IsByRef && 960 (Ctx.getTypeSizeInChars(Ty) > 961 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 962 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 963 IsByRef = true; 964 } 965 966 return IsByRef; 967 } 968 969 unsigned Sema::getOpenMPNestingLevel() const { 970 assert(getLangOpts().OpenMP); 971 return DSAStack->getNestingLevel(); 972 } 973 974 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { 975 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 976 D = getCanonicalDecl(D); 977 978 // If we are attempting to capture a global variable in a directive with 979 // 'target' we return true so that this global is also mapped to the device. 980 // 981 // FIXME: If the declaration is enclosed in a 'declare target' directive, 982 // then it should not be captured. Therefore, an extra check has to be 983 // inserted here once support for 'declare target' is added. 984 // 985 auto *VD = dyn_cast<VarDecl>(D); 986 if (VD && !VD->hasLocalStorage()) { 987 if (DSAStack->getCurrentDirective() == OMPD_target && 988 !DSAStack->isClauseParsingMode()) 989 return VD; 990 if (DSAStack->hasDirective( 991 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 992 SourceLocation) -> bool { 993 return isOpenMPTargetExecutionDirective(K); 994 }, 995 false)) 996 return VD; 997 } 998 999 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1000 (!DSAStack->isClauseParsingMode() || 1001 DSAStack->getParentDirective() != OMPD_unknown)) { 1002 auto &&Info = DSAStack->isLoopControlVariable(D); 1003 if (Info.first || 1004 (VD && VD->hasLocalStorage() && 1005 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 1006 (VD && DSAStack->isForceVarCapturing())) 1007 return VD ? VD : Info.second; 1008 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1009 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1010 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1011 DVarPrivate = DSAStack->hasDSA( 1012 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 1013 DSAStack->isClauseParsingMode()); 1014 if (DVarPrivate.CKind != OMPC_unknown) 1015 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1016 } 1017 return nullptr; 1018 } 1019 1020 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { 1021 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1022 return DSAStack->hasExplicitDSA( 1023 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level); 1024 } 1025 1026 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { 1027 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1028 // Return true if the current level is no longer enclosed in a target region. 1029 1030 auto *VD = dyn_cast<VarDecl>(D); 1031 return VD && !VD->hasLocalStorage() && 1032 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1033 Level); 1034 } 1035 1036 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1037 1038 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1039 const DeclarationNameInfo &DirName, 1040 Scope *CurScope, SourceLocation Loc) { 1041 DSAStack->push(DKind, DirName, CurScope, Loc); 1042 PushExpressionEvaluationContext(PotentiallyEvaluated); 1043 } 1044 1045 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1046 DSAStack->setClauseParsingMode(K); 1047 } 1048 1049 void Sema::EndOpenMPClause() { 1050 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1051 } 1052 1053 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1054 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1055 // A variable of class type (or array thereof) that appears in a lastprivate 1056 // clause requires an accessible, unambiguous default constructor for the 1057 // class type, unless the list item is also specified in a firstprivate 1058 // clause. 1059 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1060 for (auto *C : D->clauses()) { 1061 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1062 SmallVector<Expr *, 8> PrivateCopies; 1063 for (auto *DE : Clause->varlists()) { 1064 if (DE->isValueDependent() || DE->isTypeDependent()) { 1065 PrivateCopies.push_back(nullptr); 1066 continue; 1067 } 1068 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1069 VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1070 QualType Type = VD->getType().getNonReferenceType(); 1071 auto DVar = DSAStack->getTopDSA(VD, false); 1072 if (DVar.CKind == OMPC_lastprivate) { 1073 // Generate helper private variable and initialize it with the 1074 // default value. The address of the original variable is replaced 1075 // by the address of the new private variable in CodeGen. This new 1076 // variable is not added to IdResolver, so the code in the OpenMP 1077 // region uses original variable for proper diagnostics. 1078 auto *VDPrivate = buildVarDecl( 1079 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1080 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); 1081 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false); 1082 if (VDPrivate->isInvalidDecl()) 1083 continue; 1084 PrivateCopies.push_back(buildDeclRefExpr( 1085 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1086 } else { 1087 // The variable is also a firstprivate, so initialization sequence 1088 // for private copy is generated already. 1089 PrivateCopies.push_back(nullptr); 1090 } 1091 } 1092 // Set initializers to private copies if no errors were found. 1093 if (PrivateCopies.size() == Clause->varlist_size()) 1094 Clause->setPrivateCopies(PrivateCopies); 1095 } 1096 } 1097 } 1098 1099 DSAStack->pop(); 1100 DiscardCleanupsInEvaluationContext(); 1101 PopExpressionEvaluationContext(); 1102 } 1103 1104 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1105 Expr *NumIterations, Sema &SemaRef, 1106 Scope *S, DSAStackTy *Stack); 1107 1108 namespace { 1109 1110 class VarDeclFilterCCC : public CorrectionCandidateCallback { 1111 private: 1112 Sema &SemaRef; 1113 1114 public: 1115 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1116 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1117 NamedDecl *ND = Candidate.getCorrectionDecl(); 1118 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) { 1119 return VD->hasGlobalStorage() && 1120 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1121 SemaRef.getCurScope()); 1122 } 1123 return false; 1124 } 1125 }; 1126 1127 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { 1128 private: 1129 Sema &SemaRef; 1130 1131 public: 1132 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1133 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1134 NamedDecl *ND = Candidate.getCorrectionDecl(); 1135 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 1136 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1137 SemaRef.getCurScope()); 1138 } 1139 return false; 1140 } 1141 }; 1142 1143 } // namespace 1144 1145 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1146 CXXScopeSpec &ScopeSpec, 1147 const DeclarationNameInfo &Id) { 1148 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1149 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1150 1151 if (Lookup.isAmbiguous()) 1152 return ExprError(); 1153 1154 VarDecl *VD; 1155 if (!Lookup.isSingleResult()) { 1156 if (TypoCorrection Corrected = CorrectTypo( 1157 Id, LookupOrdinaryName, CurScope, nullptr, 1158 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1159 diagnoseTypo(Corrected, 1160 PDiag(Lookup.empty() 1161 ? diag::err_undeclared_var_use_suggest 1162 : diag::err_omp_expected_var_arg_suggest) 1163 << Id.getName()); 1164 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1165 } else { 1166 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1167 : diag::err_omp_expected_var_arg) 1168 << Id.getName(); 1169 return ExprError(); 1170 } 1171 } else { 1172 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1173 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1174 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1175 return ExprError(); 1176 } 1177 } 1178 Lookup.suppressDiagnostics(); 1179 1180 // OpenMP [2.9.2, Syntax, C/C++] 1181 // Variables must be file-scope, namespace-scope, or static block-scope. 1182 if (!VD->hasGlobalStorage()) { 1183 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1184 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1185 bool IsDecl = 1186 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1187 Diag(VD->getLocation(), 1188 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1189 << VD; 1190 return ExprError(); 1191 } 1192 1193 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1194 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 1195 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1196 // A threadprivate directive for file-scope variables must appear outside 1197 // any definition or declaration. 1198 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1199 !getCurLexicalContext()->isTranslationUnit()) { 1200 Diag(Id.getLoc(), diag::err_omp_var_scope) 1201 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1202 bool IsDecl = 1203 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1204 Diag(VD->getLocation(), 1205 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1206 << VD; 1207 return ExprError(); 1208 } 1209 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1210 // A threadprivate directive for static class member variables must appear 1211 // in the class definition, in the same scope in which the member 1212 // variables are declared. 1213 if (CanonicalVD->isStaticDataMember() && 1214 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1215 Diag(Id.getLoc(), diag::err_omp_var_scope) 1216 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1217 bool IsDecl = 1218 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1219 Diag(VD->getLocation(), 1220 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1221 << VD; 1222 return ExprError(); 1223 } 1224 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1225 // A threadprivate directive for namespace-scope variables must appear 1226 // outside any definition or declaration other than the namespace 1227 // definition itself. 1228 if (CanonicalVD->getDeclContext()->isNamespace() && 1229 (!getCurLexicalContext()->isFileContext() || 1230 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1231 Diag(Id.getLoc(), diag::err_omp_var_scope) 1232 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1233 bool IsDecl = 1234 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1235 Diag(VD->getLocation(), 1236 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1237 << VD; 1238 return ExprError(); 1239 } 1240 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1241 // A threadprivate directive for static block-scope variables must appear 1242 // in the scope of the variable and not in a nested scope. 1243 if (CanonicalVD->isStaticLocal() && CurScope && 1244 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1245 Diag(Id.getLoc(), diag::err_omp_var_scope) 1246 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1247 bool IsDecl = 1248 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1249 Diag(VD->getLocation(), 1250 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1251 << VD; 1252 return ExprError(); 1253 } 1254 1255 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1256 // A threadprivate directive must lexically precede all references to any 1257 // of the variables in its list. 1258 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1259 Diag(Id.getLoc(), diag::err_omp_var_used) 1260 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1261 return ExprError(); 1262 } 1263 1264 QualType ExprType = VD->getType().getNonReferenceType(); 1265 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1266 SourceLocation(), VD, 1267 /*RefersToEnclosingVariableOrCapture=*/false, 1268 Id.getLoc(), ExprType, VK_LValue); 1269 } 1270 1271 Sema::DeclGroupPtrTy 1272 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1273 ArrayRef<Expr *> VarList) { 1274 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1275 CurContext->addDecl(D); 1276 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1277 } 1278 return nullptr; 1279 } 1280 1281 namespace { 1282 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1283 Sema &SemaRef; 1284 1285 public: 1286 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1287 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) { 1288 if (VD->hasLocalStorage()) { 1289 SemaRef.Diag(E->getLocStart(), 1290 diag::err_omp_local_var_in_threadprivate_init) 1291 << E->getSourceRange(); 1292 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1293 << VD << VD->getSourceRange(); 1294 return true; 1295 } 1296 } 1297 return false; 1298 } 1299 bool VisitStmt(const Stmt *S) { 1300 for (auto Child : S->children()) { 1301 if (Child && Visit(Child)) 1302 return true; 1303 } 1304 return false; 1305 } 1306 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1307 }; 1308 } // namespace 1309 1310 OMPThreadPrivateDecl * 1311 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1312 SmallVector<Expr *, 8> Vars; 1313 for (auto &RefExpr : VarList) { 1314 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 1315 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 1316 SourceLocation ILoc = DE->getExprLoc(); 1317 1318 // Mark variable as used. 1319 VD->setReferenced(); 1320 VD->markUsed(Context); 1321 1322 QualType QType = VD->getType(); 1323 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1324 // It will be analyzed later. 1325 Vars.push_back(DE); 1326 continue; 1327 } 1328 1329 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1330 // A threadprivate variable must not have an incomplete type. 1331 if (RequireCompleteType(ILoc, VD->getType(), 1332 diag::err_omp_threadprivate_incomplete_type)) { 1333 continue; 1334 } 1335 1336 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1337 // A threadprivate variable must not have a reference type. 1338 if (VD->getType()->isReferenceType()) { 1339 Diag(ILoc, diag::err_omp_ref_type_arg) 1340 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1341 bool IsDecl = 1342 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1343 Diag(VD->getLocation(), 1344 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1345 << VD; 1346 continue; 1347 } 1348 1349 // Check if this is a TLS variable. If TLS is not being supported, produce 1350 // the corresponding diagnostic. 1351 if ((VD->getTLSKind() != VarDecl::TLS_None && 1352 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1353 getLangOpts().OpenMPUseTLS && 1354 getASTContext().getTargetInfo().isTLSSupported())) || 1355 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1356 !VD->isLocalVarDecl())) { 1357 Diag(ILoc, diag::err_omp_var_thread_local) 1358 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1359 bool IsDecl = 1360 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1361 Diag(VD->getLocation(), 1362 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1363 << VD; 1364 continue; 1365 } 1366 1367 // Check if initial value of threadprivate variable reference variable with 1368 // local storage (it is not supported by runtime). 1369 if (auto Init = VD->getAnyInitializer()) { 1370 LocalVarRefChecker Checker(*this); 1371 if (Checker.Visit(Init)) 1372 continue; 1373 } 1374 1375 Vars.push_back(RefExpr); 1376 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1377 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1378 Context, SourceRange(Loc, Loc))); 1379 if (auto *ML = Context.getASTMutationListener()) 1380 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1381 } 1382 OMPThreadPrivateDecl *D = nullptr; 1383 if (!Vars.empty()) { 1384 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1385 Vars); 1386 D->setAccess(AS_public); 1387 } 1388 return D; 1389 } 1390 1391 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 1392 const ValueDecl *D, DSAStackTy::DSAVarData DVar, 1393 bool IsLoopIterVar = false) { 1394 if (DVar.RefExpr) { 1395 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1396 << getOpenMPClauseName(DVar.CKind); 1397 return; 1398 } 1399 enum { 1400 PDSA_StaticMemberShared, 1401 PDSA_StaticLocalVarShared, 1402 PDSA_LoopIterVarPrivate, 1403 PDSA_LoopIterVarLinear, 1404 PDSA_LoopIterVarLastprivate, 1405 PDSA_ConstVarShared, 1406 PDSA_GlobalVarShared, 1407 PDSA_TaskVarFirstprivate, 1408 PDSA_LocalVarPrivate, 1409 PDSA_Implicit 1410 } Reason = PDSA_Implicit; 1411 bool ReportHint = false; 1412 auto ReportLoc = D->getLocation(); 1413 auto *VD = dyn_cast<VarDecl>(D); 1414 if (IsLoopIterVar) { 1415 if (DVar.CKind == OMPC_private) 1416 Reason = PDSA_LoopIterVarPrivate; 1417 else if (DVar.CKind == OMPC_lastprivate) 1418 Reason = PDSA_LoopIterVarLastprivate; 1419 else 1420 Reason = PDSA_LoopIterVarLinear; 1421 } else if (isOpenMPTaskingDirective(DVar.DKind) && 1422 DVar.CKind == OMPC_firstprivate) { 1423 Reason = PDSA_TaskVarFirstprivate; 1424 ReportLoc = DVar.ImplicitDSALoc; 1425 } else if (VD && VD->isStaticLocal()) 1426 Reason = PDSA_StaticLocalVarShared; 1427 else if (VD && VD->isStaticDataMember()) 1428 Reason = PDSA_StaticMemberShared; 1429 else if (VD && VD->isFileVarDecl()) 1430 Reason = PDSA_GlobalVarShared; 1431 else if (D->getType().isConstant(SemaRef.getASTContext())) 1432 Reason = PDSA_ConstVarShared; 1433 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 1434 ReportHint = true; 1435 Reason = PDSA_LocalVarPrivate; 1436 } 1437 if (Reason != PDSA_Implicit) { 1438 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 1439 << Reason << ReportHint 1440 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 1441 } else if (DVar.ImplicitDSALoc.isValid()) { 1442 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 1443 << getOpenMPClauseName(DVar.CKind); 1444 } 1445 } 1446 1447 namespace { 1448 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 1449 DSAStackTy *Stack; 1450 Sema &SemaRef; 1451 bool ErrorFound; 1452 CapturedStmt *CS; 1453 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 1454 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 1455 1456 public: 1457 void VisitDeclRefExpr(DeclRefExpr *E) { 1458 if (E->isTypeDependent() || E->isValueDependent() || 1459 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1460 return; 1461 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1462 // Skip internally declared variables. 1463 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) 1464 return; 1465 1466 auto DVar = Stack->getTopDSA(VD, false); 1467 // Check if the variable has explicit DSA set and stop analysis if it so. 1468 if (DVar.RefExpr) return; 1469 1470 auto ELoc = E->getExprLoc(); 1471 auto DKind = Stack->getCurrentDirective(); 1472 // The default(none) clause requires that each variable that is referenced 1473 // in the construct, and does not have a predetermined data-sharing 1474 // attribute, must have its data-sharing attribute explicitly determined 1475 // by being listed in a data-sharing attribute clause. 1476 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 1477 isParallelOrTaskRegion(DKind) && 1478 VarsWithInheritedDSA.count(VD) == 0) { 1479 VarsWithInheritedDSA[VD] = E; 1480 return; 1481 } 1482 1483 // OpenMP [2.9.3.6, Restrictions, p.2] 1484 // A list item that appears in a reduction clause of the innermost 1485 // enclosing worksharing or parallel construct may not be accessed in an 1486 // explicit task. 1487 DVar = Stack->hasInnermostDSA( 1488 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1489 [](OpenMPDirectiveKind K) -> bool { 1490 return isOpenMPParallelDirective(K) || 1491 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1492 }, 1493 false); 1494 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1495 ErrorFound = true; 1496 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1497 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 1498 return; 1499 } 1500 1501 // Define implicit data-sharing attributes for task. 1502 DVar = Stack->getImplicitDSA(VD, false); 1503 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1504 !Stack->isLoopControlVariable(VD).first) 1505 ImplicitFirstprivate.push_back(E); 1506 } 1507 } 1508 void VisitMemberExpr(MemberExpr *E) { 1509 if (E->isTypeDependent() || E->isValueDependent() || 1510 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1511 return; 1512 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 1513 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 1514 auto DVar = Stack->getTopDSA(FD, false); 1515 // Check if the variable has explicit DSA set and stop analysis if it 1516 // so. 1517 if (DVar.RefExpr) 1518 return; 1519 1520 auto ELoc = E->getExprLoc(); 1521 auto DKind = Stack->getCurrentDirective(); 1522 // OpenMP [2.9.3.6, Restrictions, p.2] 1523 // A list item that appears in a reduction clause of the innermost 1524 // enclosing worksharing or parallel construct may not be accessed in 1525 // an explicit task. 1526 DVar = Stack->hasInnermostDSA( 1527 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1528 [](OpenMPDirectiveKind K) -> bool { 1529 return isOpenMPParallelDirective(K) || 1530 isOpenMPWorksharingDirective(K) || 1531 isOpenMPTeamsDirective(K); 1532 }, 1533 false); 1534 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1535 ErrorFound = true; 1536 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1537 ReportOriginalDSA(SemaRef, Stack, FD, DVar); 1538 return; 1539 } 1540 1541 // Define implicit data-sharing attributes for task. 1542 DVar = Stack->getImplicitDSA(FD, false); 1543 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1544 !Stack->isLoopControlVariable(FD).first) 1545 ImplicitFirstprivate.push_back(E); 1546 } 1547 } 1548 } 1549 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 1550 for (auto *C : S->clauses()) { 1551 // Skip analysis of arguments of implicitly defined firstprivate clause 1552 // for task directives. 1553 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid())) 1554 for (auto *CC : C->children()) { 1555 if (CC) 1556 Visit(CC); 1557 } 1558 } 1559 } 1560 void VisitStmt(Stmt *S) { 1561 for (auto *C : S->children()) { 1562 if (C && !isa<OMPExecutableDirective>(C)) 1563 Visit(C); 1564 } 1565 } 1566 1567 bool isErrorFound() { return ErrorFound; } 1568 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; } 1569 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() { 1570 return VarsWithInheritedDSA; 1571 } 1572 1573 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 1574 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 1575 }; 1576 } // namespace 1577 1578 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 1579 switch (DKind) { 1580 case OMPD_parallel: 1581 case OMPD_parallel_for: 1582 case OMPD_parallel_for_simd: 1583 case OMPD_parallel_sections: 1584 case OMPD_teams: { 1585 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1586 QualType KmpInt32PtrTy = 1587 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1588 Sema::CapturedParamNameType Params[] = { 1589 std::make_pair(".global_tid.", KmpInt32PtrTy), 1590 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1591 std::make_pair(StringRef(), QualType()) // __context with shared vars 1592 }; 1593 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1594 Params); 1595 break; 1596 } 1597 case OMPD_simd: 1598 case OMPD_for: 1599 case OMPD_for_simd: 1600 case OMPD_sections: 1601 case OMPD_section: 1602 case OMPD_single: 1603 case OMPD_master: 1604 case OMPD_critical: 1605 case OMPD_taskgroup: 1606 case OMPD_distribute: 1607 case OMPD_ordered: 1608 case OMPD_atomic: 1609 case OMPD_target_data: 1610 case OMPD_target: 1611 case OMPD_target_parallel: 1612 case OMPD_target_parallel_for: 1613 case OMPD_target_parallel_for_simd: 1614 case OMPD_target_simd: { 1615 Sema::CapturedParamNameType Params[] = { 1616 std::make_pair(StringRef(), QualType()) // __context with shared vars 1617 }; 1618 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1619 Params); 1620 break; 1621 } 1622 case OMPD_task: { 1623 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1624 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1625 FunctionProtoType::ExtProtoInfo EPI; 1626 EPI.Variadic = true; 1627 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1628 Sema::CapturedParamNameType Params[] = { 1629 std::make_pair(".global_tid.", KmpInt32Ty), 1630 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1631 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 1632 std::make_pair(".copy_fn.", 1633 Context.getPointerType(CopyFnType).withConst()), 1634 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1635 std::make_pair(StringRef(), QualType()) // __context with shared vars 1636 }; 1637 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1638 Params); 1639 // Mark this captured region as inlined, because we don't use outlined 1640 // function directly. 1641 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1642 AlwaysInlineAttr::CreateImplicit( 1643 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1644 break; 1645 } 1646 case OMPD_taskloop: 1647 case OMPD_taskloop_simd: { 1648 QualType KmpInt32Ty = 1649 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1650 QualType KmpUInt64Ty = 1651 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 1652 QualType KmpInt64Ty = 1653 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 1654 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1655 FunctionProtoType::ExtProtoInfo EPI; 1656 EPI.Variadic = true; 1657 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1658 Sema::CapturedParamNameType Params[] = { 1659 std::make_pair(".global_tid.", KmpInt32Ty), 1660 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1661 std::make_pair(".privates.", 1662 Context.VoidPtrTy.withConst().withRestrict()), 1663 std::make_pair( 1664 ".copy_fn.", 1665 Context.getPointerType(CopyFnType).withConst().withRestrict()), 1666 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1667 std::make_pair(".lb.", KmpUInt64Ty), 1668 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 1669 std::make_pair(".liter.", KmpInt32Ty), 1670 std::make_pair(StringRef(), QualType()) // __context with shared vars 1671 }; 1672 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1673 Params); 1674 // Mark this captured region as inlined, because we don't use outlined 1675 // function directly. 1676 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1677 AlwaysInlineAttr::CreateImplicit( 1678 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1679 break; 1680 } 1681 case OMPD_distribute_parallel_for_simd: 1682 case OMPD_distribute_simd: 1683 case OMPD_distribute_parallel_for: { 1684 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1685 QualType KmpInt32PtrTy = 1686 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1687 Sema::CapturedParamNameType Params[] = { 1688 std::make_pair(".global_tid.", KmpInt32PtrTy), 1689 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1690 std::make_pair(".previous.lb.", Context.getSizeType()), 1691 std::make_pair(".previous.ub.", Context.getSizeType()), 1692 std::make_pair(StringRef(), QualType()) // __context with shared vars 1693 }; 1694 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1695 Params); 1696 break; 1697 } 1698 case OMPD_threadprivate: 1699 case OMPD_taskyield: 1700 case OMPD_barrier: 1701 case OMPD_taskwait: 1702 case OMPD_cancellation_point: 1703 case OMPD_cancel: 1704 case OMPD_flush: 1705 case OMPD_target_enter_data: 1706 case OMPD_target_exit_data: 1707 case OMPD_declare_reduction: 1708 case OMPD_declare_simd: 1709 case OMPD_declare_target: 1710 case OMPD_end_declare_target: 1711 case OMPD_target_update: 1712 llvm_unreachable("OpenMP Directive is not allowed"); 1713 case OMPD_unknown: 1714 llvm_unreachable("Unknown OpenMP directive"); 1715 } 1716 } 1717 1718 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 1719 Expr *CaptureExpr, bool WithInit, 1720 bool AsExpression) { 1721 assert(CaptureExpr); 1722 ASTContext &C = S.getASTContext(); 1723 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 1724 QualType Ty = Init->getType(); 1725 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 1726 if (S.getLangOpts().CPlusPlus) 1727 Ty = C.getLValueReferenceType(Ty); 1728 else { 1729 Ty = C.getPointerType(Ty); 1730 ExprResult Res = 1731 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 1732 if (!Res.isUsable()) 1733 return nullptr; 1734 Init = Res.get(); 1735 } 1736 WithInit = true; 1737 } 1738 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty); 1739 if (!WithInit) 1740 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 1741 S.CurContext->addHiddenDecl(CED); 1742 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false, 1743 /*TypeMayContainAuto=*/true); 1744 return CED; 1745 } 1746 1747 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 1748 bool WithInit) { 1749 OMPCapturedExprDecl *CD; 1750 if (auto *VD = S.IsOpenMPCapturedDecl(D)) 1751 CD = cast<OMPCapturedExprDecl>(VD); 1752 else 1753 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 1754 /*AsExpression=*/false); 1755 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1756 CaptureExpr->getExprLoc()); 1757 } 1758 1759 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 1760 if (!Ref) { 1761 auto *CD = 1762 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), 1763 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); 1764 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1765 CaptureExpr->getExprLoc()); 1766 } 1767 ExprResult Res = Ref; 1768 if (!S.getLangOpts().CPlusPlus && 1769 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 1770 Ref->getType()->isPointerType()) 1771 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 1772 if (!Res.isUsable()) 1773 return ExprError(); 1774 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); 1775 } 1776 1777 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 1778 ArrayRef<OMPClause *> Clauses) { 1779 if (!S.isUsable()) { 1780 ActOnCapturedRegionError(); 1781 return StmtError(); 1782 } 1783 1784 OMPOrderedClause *OC = nullptr; 1785 OMPScheduleClause *SC = nullptr; 1786 SmallVector<OMPLinearClause *, 4> LCs; 1787 // This is required for proper codegen. 1788 for (auto *Clause : Clauses) { 1789 if (isOpenMPPrivate(Clause->getClauseKind()) || 1790 Clause->getClauseKind() == OMPC_copyprivate || 1791 (getLangOpts().OpenMPUseTLS && 1792 getASTContext().getTargetInfo().isTLSSupported() && 1793 Clause->getClauseKind() == OMPC_copyin)) { 1794 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 1795 // Mark all variables in private list clauses as used in inner region. 1796 for (auto *VarRef : Clause->children()) { 1797 if (auto *E = cast_or_null<Expr>(VarRef)) { 1798 MarkDeclarationsReferencedInExpr(E); 1799 } 1800 } 1801 DSAStack->setForceVarCapturing(/*V=*/false); 1802 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 1803 // Mark all variables in private list clauses as used in inner region. 1804 // Required for proper codegen of combined directives. 1805 // TODO: add processing for other clauses. 1806 if (auto *C = OMPClauseWithPreInit::get(Clause)) { 1807 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 1808 for (auto *D : DS->decls()) 1809 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 1810 } 1811 } 1812 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 1813 if (auto *E = C->getPostUpdateExpr()) 1814 MarkDeclarationsReferencedInExpr(E); 1815 } 1816 } 1817 if (Clause->getClauseKind() == OMPC_schedule) 1818 SC = cast<OMPScheduleClause>(Clause); 1819 else if (Clause->getClauseKind() == OMPC_ordered) 1820 OC = cast<OMPOrderedClause>(Clause); 1821 else if (Clause->getClauseKind() == OMPC_linear) 1822 LCs.push_back(cast<OMPLinearClause>(Clause)); 1823 } 1824 bool ErrorFound = false; 1825 // OpenMP, 2.7.1 Loop Construct, Restrictions 1826 // The nonmonotonic modifier cannot be specified if an ordered clause is 1827 // specified. 1828 if (SC && 1829 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 1830 SC->getSecondScheduleModifier() == 1831 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 1832 OC) { 1833 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 1834 ? SC->getFirstScheduleModifierLoc() 1835 : SC->getSecondScheduleModifierLoc(), 1836 diag::err_omp_schedule_nonmonotonic_ordered) 1837 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1838 ErrorFound = true; 1839 } 1840 if (!LCs.empty() && OC && OC->getNumForLoops()) { 1841 for (auto *C : LCs) { 1842 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 1843 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1844 } 1845 ErrorFound = true; 1846 } 1847 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 1848 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 1849 OC->getNumForLoops()) { 1850 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 1851 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 1852 ErrorFound = true; 1853 } 1854 if (ErrorFound) { 1855 ActOnCapturedRegionError(); 1856 return StmtError(); 1857 } 1858 return ActOnCapturedRegionEnd(S.get()); 1859 } 1860 1861 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 1862 OpenMPDirectiveKind CurrentRegion, 1863 const DeclarationNameInfo &CurrentName, 1864 OpenMPDirectiveKind CancelRegion, 1865 SourceLocation StartLoc) { 1866 // Allowed nesting of constructs 1867 // +------------------+-----------------+------------------------------------+ 1868 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)| 1869 // +------------------+-----------------+------------------------------------+ 1870 // | parallel | parallel | * | 1871 // | parallel | for | * | 1872 // | parallel | for simd | * | 1873 // | parallel | master | * | 1874 // | parallel | critical | * | 1875 // | parallel | simd | * | 1876 // | parallel | sections | * | 1877 // | parallel | section | + | 1878 // | parallel | single | * | 1879 // | parallel | parallel for | * | 1880 // | parallel |parallel for simd| * | 1881 // | parallel |parallel sections| * | 1882 // | parallel | task | * | 1883 // | parallel | taskyield | * | 1884 // | parallel | barrier | * | 1885 // | parallel | taskwait | * | 1886 // | parallel | taskgroup | * | 1887 // | parallel | flush | * | 1888 // | parallel | ordered | + | 1889 // | parallel | atomic | * | 1890 // | parallel | target | * | 1891 // | parallel | target parallel | * | 1892 // | parallel | target parallel | * | 1893 // | | for | | 1894 // | parallel | target enter | * | 1895 // | | data | | 1896 // | parallel | target exit | * | 1897 // | | data | | 1898 // | parallel | teams | + | 1899 // | parallel | cancellation | | 1900 // | | point | ! | 1901 // | parallel | cancel | ! | 1902 // | parallel | taskloop | * | 1903 // | parallel | taskloop simd | * | 1904 // | parallel | distribute | + | 1905 // | parallel | distribute | + | 1906 // | | parallel for | | 1907 // | parallel | distribute | + | 1908 // | |parallel for simd| | 1909 // | parallel | distribute simd | + | 1910 // | parallel | target simd | * | 1911 // +------------------+-----------------+------------------------------------+ 1912 // | for | parallel | * | 1913 // | for | for | + | 1914 // | for | for simd | + | 1915 // | for | master | + | 1916 // | for | critical | * | 1917 // | for | simd | * | 1918 // | for | sections | + | 1919 // | for | section | + | 1920 // | for | single | + | 1921 // | for | parallel for | * | 1922 // | for |parallel for simd| * | 1923 // | for |parallel sections| * | 1924 // | for | task | * | 1925 // | for | taskyield | * | 1926 // | for | barrier | + | 1927 // | for | taskwait | * | 1928 // | for | taskgroup | * | 1929 // | for | flush | * | 1930 // | for | ordered | * (if construct is ordered) | 1931 // | for | atomic | * | 1932 // | for | target | * | 1933 // | for | target parallel | * | 1934 // | for | target parallel | * | 1935 // | | for | | 1936 // | for | target enter | * | 1937 // | | data | | 1938 // | for | target exit | * | 1939 // | | data | | 1940 // | for | teams | + | 1941 // | for | cancellation | | 1942 // | | point | ! | 1943 // | for | cancel | ! | 1944 // | for | taskloop | * | 1945 // | for | taskloop simd | * | 1946 // | for | distribute | + | 1947 // | for | distribute | + | 1948 // | | parallel for | | 1949 // | for | distribute | + | 1950 // | |parallel for simd| | 1951 // | for | distribute simd | + | 1952 // | for | target parallel | + | 1953 // | | for simd | | 1954 // | for | target simd | * | 1955 // +------------------+-----------------+------------------------------------+ 1956 // | master | parallel | * | 1957 // | master | for | + | 1958 // | master | for simd | + | 1959 // | master | master | * | 1960 // | master | critical | * | 1961 // | master | simd | * | 1962 // | master | sections | + | 1963 // | master | section | + | 1964 // | master | single | + | 1965 // | master | parallel for | * | 1966 // | master |parallel for simd| * | 1967 // | master |parallel sections| * | 1968 // | master | task | * | 1969 // | master | taskyield | * | 1970 // | master | barrier | + | 1971 // | master | taskwait | * | 1972 // | master | taskgroup | * | 1973 // | master | flush | * | 1974 // | master | ordered | + | 1975 // | master | atomic | * | 1976 // | master | target | * | 1977 // | master | target parallel | * | 1978 // | master | target parallel | * | 1979 // | | for | | 1980 // | master | target enter | * | 1981 // | | data | | 1982 // | master | target exit | * | 1983 // | | data | | 1984 // | master | teams | + | 1985 // | master | cancellation | | 1986 // | | point | | 1987 // | master | cancel | | 1988 // | master | taskloop | * | 1989 // | master | taskloop simd | * | 1990 // | master | distribute | + | 1991 // | master | distribute | + | 1992 // | | parallel for | | 1993 // | master | distribute | + | 1994 // | |parallel for simd| | 1995 // | master | distribute simd | + | 1996 // | master | target parallel | + | 1997 // | | for simd | | 1998 // | master | target simd | * | 1999 // +------------------+-----------------+------------------------------------+ 2000 // | critical | parallel | * | 2001 // | critical | for | + | 2002 // | critical | for simd | + | 2003 // | critical | master | * | 2004 // | critical | critical | * (should have different names) | 2005 // | critical | simd | * | 2006 // | critical | sections | + | 2007 // | critical | section | + | 2008 // | critical | single | + | 2009 // | critical | parallel for | * | 2010 // | critical |parallel for simd| * | 2011 // | critical |parallel sections| * | 2012 // | critical | task | * | 2013 // | critical | taskyield | * | 2014 // | critical | barrier | + | 2015 // | critical | taskwait | * | 2016 // | critical | taskgroup | * | 2017 // | critical | ordered | + | 2018 // | critical | atomic | * | 2019 // | critical | target | * | 2020 // | critical | target parallel | * | 2021 // | critical | target parallel | * | 2022 // | | for | | 2023 // | critical | target enter | * | 2024 // | | data | | 2025 // | critical | target exit | * | 2026 // | | data | | 2027 // | critical | teams | + | 2028 // | critical | cancellation | | 2029 // | | point | | 2030 // | critical | cancel | | 2031 // | critical | taskloop | * | 2032 // | critical | taskloop simd | * | 2033 // | critical | distribute | + | 2034 // | critical | distribute | + | 2035 // | | parallel for | | 2036 // | critical | distribute | + | 2037 // | |parallel for simd| | 2038 // | critical | distribute simd | + | 2039 // | critical | target parallel | + | 2040 // | | for simd | | 2041 // | critical | target simd | * | 2042 // +------------------+-----------------+------------------------------------+ 2043 // | simd | parallel | | 2044 // | simd | for | | 2045 // | simd | for simd | | 2046 // | simd | master | | 2047 // | simd | critical | | 2048 // | simd | simd | * | 2049 // | simd | sections | | 2050 // | simd | section | | 2051 // | simd | single | | 2052 // | simd | parallel for | | 2053 // | simd |parallel for simd| | 2054 // | simd |parallel sections| | 2055 // | simd | task | | 2056 // | simd | taskyield | | 2057 // | simd | barrier | | 2058 // | simd | taskwait | | 2059 // | simd | taskgroup | | 2060 // | simd | flush | | 2061 // | simd | ordered | + (with simd clause) | 2062 // | simd | atomic | | 2063 // | simd | target | | 2064 // | simd | target parallel | | 2065 // | simd | target parallel | | 2066 // | | for | | 2067 // | simd | target enter | | 2068 // | | data | | 2069 // | simd | target exit | | 2070 // | | data | | 2071 // | simd | teams | | 2072 // | simd | cancellation | | 2073 // | | point | | 2074 // | simd | cancel | | 2075 // | simd | taskloop | | 2076 // | simd | taskloop simd | | 2077 // | simd | distribute | | 2078 // | simd | distribute | | 2079 // | | parallel for | | 2080 // | simd | distribute | | 2081 // | |parallel for simd| | 2082 // | simd | distribute simd | | 2083 // | simd | target parallel | | 2084 // | | for simd | | 2085 // | simd | target simd | | 2086 // +------------------+-----------------+------------------------------------+ 2087 // | for simd | parallel | | 2088 // | for simd | for | | 2089 // | for simd | for simd | | 2090 // | for simd | master | | 2091 // | for simd | critical | | 2092 // | for simd | simd | * | 2093 // | for simd | sections | | 2094 // | for simd | section | | 2095 // | for simd | single | | 2096 // | for simd | parallel for | | 2097 // | for simd |parallel for simd| | 2098 // | for simd |parallel sections| | 2099 // | for simd | task | | 2100 // | for simd | taskyield | | 2101 // | for simd | barrier | | 2102 // | for simd | taskwait | | 2103 // | for simd | taskgroup | | 2104 // | for simd | flush | | 2105 // | for simd | ordered | + (with simd clause) | 2106 // | for simd | atomic | | 2107 // | for simd | target | | 2108 // | for simd | target parallel | | 2109 // | for simd | target parallel | | 2110 // | | for | | 2111 // | for simd | target enter | | 2112 // | | data | | 2113 // | for simd | target exit | | 2114 // | | data | | 2115 // | for simd | teams | | 2116 // | for simd | cancellation | | 2117 // | | point | | 2118 // | for simd | cancel | | 2119 // | for simd | taskloop | | 2120 // | for simd | taskloop simd | | 2121 // | for simd | distribute | | 2122 // | for simd | distribute | | 2123 // | | parallel for | | 2124 // | for simd | distribute | | 2125 // | |parallel for simd| | 2126 // | for simd | distribute simd | | 2127 // | for simd | target parallel | | 2128 // | | for simd | | 2129 // | for simd | target simd | | 2130 // +------------------+-----------------+------------------------------------+ 2131 // | parallel for simd| parallel | | 2132 // | parallel for simd| for | | 2133 // | parallel for simd| for simd | | 2134 // | parallel for simd| master | | 2135 // | parallel for simd| critical | | 2136 // | parallel for simd| simd | * | 2137 // | parallel for simd| sections | | 2138 // | parallel for simd| section | | 2139 // | parallel for simd| single | | 2140 // | parallel for simd| parallel for | | 2141 // | parallel for simd|parallel for simd| | 2142 // | parallel for simd|parallel sections| | 2143 // | parallel for simd| task | | 2144 // | parallel for simd| taskyield | | 2145 // | parallel for simd| barrier | | 2146 // | parallel for simd| taskwait | | 2147 // | parallel for simd| taskgroup | | 2148 // | parallel for simd| flush | | 2149 // | parallel for simd| ordered | + (with simd clause) | 2150 // | parallel for simd| atomic | | 2151 // | parallel for simd| target | | 2152 // | parallel for simd| target parallel | | 2153 // | parallel for simd| target parallel | | 2154 // | | for | | 2155 // | parallel for simd| target enter | | 2156 // | | data | | 2157 // | parallel for simd| target exit | | 2158 // | | data | | 2159 // | parallel for simd| teams | | 2160 // | parallel for simd| cancellation | | 2161 // | | point | | 2162 // | parallel for simd| cancel | | 2163 // | parallel for simd| taskloop | | 2164 // | parallel for simd| taskloop simd | | 2165 // | parallel for simd| distribute | | 2166 // | parallel for simd| distribute | | 2167 // | | parallel for | | 2168 // | parallel for simd| distribute | | 2169 // | |parallel for simd| | 2170 // | parallel for simd| distribute simd | | 2171 // | | for simd | | 2172 // | parallel for simd| target simd | | 2173 // +------------------+-----------------+------------------------------------+ 2174 // | sections | parallel | * | 2175 // | sections | for | + | 2176 // | sections | for simd | + | 2177 // | sections | master | + | 2178 // | sections | critical | * | 2179 // | sections | simd | * | 2180 // | sections | sections | + | 2181 // | sections | section | * | 2182 // | sections | single | + | 2183 // | sections | parallel for | * | 2184 // | sections |parallel for simd| * | 2185 // | sections |parallel sections| * | 2186 // | sections | task | * | 2187 // | sections | taskyield | * | 2188 // | sections | barrier | + | 2189 // | sections | taskwait | * | 2190 // | sections | taskgroup | * | 2191 // | sections | flush | * | 2192 // | sections | ordered | + | 2193 // | sections | atomic | * | 2194 // | sections | target | * | 2195 // | sections | target parallel | * | 2196 // | sections | target parallel | * | 2197 // | | for | | 2198 // | sections | target enter | * | 2199 // | | data | | 2200 // | sections | target exit | * | 2201 // | | data | | 2202 // | sections | teams | + | 2203 // | sections | cancellation | | 2204 // | | point | ! | 2205 // | sections | cancel | ! | 2206 // | sections | taskloop | * | 2207 // | sections | taskloop simd | * | 2208 // | sections | distribute | + | 2209 // | sections | distribute | + | 2210 // | | parallel for | | 2211 // | sections | distribute | + | 2212 // | |parallel for simd| | 2213 // | sections | distribute simd | + | 2214 // | sections | target parallel | + | 2215 // | | for simd | | 2216 // | sections | target simd | * | 2217 // +------------------+-----------------+------------------------------------+ 2218 // | section | parallel | * | 2219 // | section | for | + | 2220 // | section | for simd | + | 2221 // | section | master | + | 2222 // | section | critical | * | 2223 // | section | simd | * | 2224 // | section | sections | + | 2225 // | section | section | + | 2226 // | section | single | + | 2227 // | section | parallel for | * | 2228 // | section |parallel for simd| * | 2229 // | section |parallel sections| * | 2230 // | section | task | * | 2231 // | section | taskyield | * | 2232 // | section | barrier | + | 2233 // | section | taskwait | * | 2234 // | section | taskgroup | * | 2235 // | section | flush | * | 2236 // | section | ordered | + | 2237 // | section | atomic | * | 2238 // | section | target | * | 2239 // | section | target parallel | * | 2240 // | section | target parallel | * | 2241 // | | for | | 2242 // | section | target enter | * | 2243 // | | data | | 2244 // | section | target exit | * | 2245 // | | data | | 2246 // | section | teams | + | 2247 // | section | cancellation | | 2248 // | | point | ! | 2249 // | section | cancel | ! | 2250 // | section | taskloop | * | 2251 // | section | taskloop simd | * | 2252 // | section | distribute | + | 2253 // | section | distribute | + | 2254 // | | parallel for | | 2255 // | section | distribute | + | 2256 // | |parallel for simd| | 2257 // | section | distribute simd | + | 2258 // | section | target parallel | + | 2259 // | | for simd | | 2260 // | section | target simd | * | 2261 // +------------------+-----------------+------------------------------------+ 2262 // | single | parallel | * | 2263 // | single | for | + | 2264 // | single | for simd | + | 2265 // | single | master | + | 2266 // | single | critical | * | 2267 // | single | simd | * | 2268 // | single | sections | + | 2269 // | single | section | + | 2270 // | single | single | + | 2271 // | single | parallel for | * | 2272 // | single |parallel for simd| * | 2273 // | single |parallel sections| * | 2274 // | single | task | * | 2275 // | single | taskyield | * | 2276 // | single | barrier | + | 2277 // | single | taskwait | * | 2278 // | single | taskgroup | * | 2279 // | single | flush | * | 2280 // | single | ordered | + | 2281 // | single | atomic | * | 2282 // | single | target | * | 2283 // | single | target parallel | * | 2284 // | single | target parallel | * | 2285 // | | for | | 2286 // | single | target enter | * | 2287 // | | data | | 2288 // | single | target exit | * | 2289 // | | data | | 2290 // | single | teams | + | 2291 // | single | cancellation | | 2292 // | | point | | 2293 // | single | cancel | | 2294 // | single | taskloop | * | 2295 // | single | taskloop simd | * | 2296 // | single | distribute | + | 2297 // | single | distribute | + | 2298 // | | parallel for | | 2299 // | single | distribute | + | 2300 // | |parallel for simd| | 2301 // | single | distribute simd | + | 2302 // | single | target parallel | + | 2303 // | | for simd | | 2304 // | single | target simd | * | 2305 // +------------------+-----------------+------------------------------------+ 2306 // | parallel for | parallel | * | 2307 // | parallel for | for | + | 2308 // | parallel for | for simd | + | 2309 // | parallel for | master | + | 2310 // | parallel for | critical | * | 2311 // | parallel for | simd | * | 2312 // | parallel for | sections | + | 2313 // | parallel for | section | + | 2314 // | parallel for | single | + | 2315 // | parallel for | parallel for | * | 2316 // | parallel for |parallel for simd| * | 2317 // | parallel for |parallel sections| * | 2318 // | parallel for | task | * | 2319 // | parallel for | taskyield | * | 2320 // | parallel for | barrier | + | 2321 // | parallel for | taskwait | * | 2322 // | parallel for | taskgroup | * | 2323 // | parallel for | flush | * | 2324 // | parallel for | ordered | * (if construct is ordered) | 2325 // | parallel for | atomic | * | 2326 // | parallel for | target | * | 2327 // | parallel for | target parallel | * | 2328 // | parallel for | target parallel | * | 2329 // | | for | | 2330 // | parallel for | target enter | * | 2331 // | | data | | 2332 // | parallel for | target exit | * | 2333 // | | data | | 2334 // | parallel for | teams | + | 2335 // | parallel for | cancellation | | 2336 // | | point | ! | 2337 // | parallel for | cancel | ! | 2338 // | parallel for | taskloop | * | 2339 // | parallel for | taskloop simd | * | 2340 // | parallel for | distribute | + | 2341 // | parallel for | distribute | + | 2342 // | | parallel for | | 2343 // | parallel for | distribute | + | 2344 // | |parallel for simd| | 2345 // | parallel for | distribute simd | + | 2346 // | parallel for | target parallel | + | 2347 // | | for simd | | 2348 // | parallel for | target simd | * | 2349 // +------------------+-----------------+------------------------------------+ 2350 // | parallel sections| parallel | * | 2351 // | parallel sections| for | + | 2352 // | parallel sections| for simd | + | 2353 // | parallel sections| master | + | 2354 // | parallel sections| critical | + | 2355 // | parallel sections| simd | * | 2356 // | parallel sections| sections | + | 2357 // | parallel sections| section | * | 2358 // | parallel sections| single | + | 2359 // | parallel sections| parallel for | * | 2360 // | parallel sections|parallel for simd| * | 2361 // | parallel sections|parallel sections| * | 2362 // | parallel sections| task | * | 2363 // | parallel sections| taskyield | * | 2364 // | parallel sections| barrier | + | 2365 // | parallel sections| taskwait | * | 2366 // | parallel sections| taskgroup | * | 2367 // | parallel sections| flush | * | 2368 // | parallel sections| ordered | + | 2369 // | parallel sections| atomic | * | 2370 // | parallel sections| target | * | 2371 // | parallel sections| target parallel | * | 2372 // | parallel sections| target parallel | * | 2373 // | | for | | 2374 // | parallel sections| target enter | * | 2375 // | | data | | 2376 // | parallel sections| target exit | * | 2377 // | | data | | 2378 // | parallel sections| teams | + | 2379 // | parallel sections| cancellation | | 2380 // | | point | ! | 2381 // | parallel sections| cancel | ! | 2382 // | parallel sections| taskloop | * | 2383 // | parallel sections| taskloop simd | * | 2384 // | parallel sections| distribute | + | 2385 // | parallel sections| distribute | + | 2386 // | | parallel for | | 2387 // | parallel sections| distribute | + | 2388 // | |parallel for simd| | 2389 // | parallel sections| distribute simd | + | 2390 // | parallel sections| target parallel | + | 2391 // | | for simd | | 2392 // | parallel sections| target simd | * | 2393 // +------------------+-----------------+------------------------------------+ 2394 // | task | parallel | * | 2395 // | task | for | + | 2396 // | task | for simd | + | 2397 // | task | master | + | 2398 // | task | critical | * | 2399 // | task | simd | * | 2400 // | task | sections | + | 2401 // | task | section | + | 2402 // | task | single | + | 2403 // | task | parallel for | * | 2404 // | task |parallel for simd| * | 2405 // | task |parallel sections| * | 2406 // | task | task | * | 2407 // | task | taskyield | * | 2408 // | task | barrier | + | 2409 // | task | taskwait | * | 2410 // | task | taskgroup | * | 2411 // | task | flush | * | 2412 // | task | ordered | + | 2413 // | task | atomic | * | 2414 // | task | target | * | 2415 // | task | target parallel | * | 2416 // | task | target parallel | * | 2417 // | | for | | 2418 // | task | target enter | * | 2419 // | | data | | 2420 // | task | target exit | * | 2421 // | | data | | 2422 // | task | teams | + | 2423 // | task | cancellation | | 2424 // | | point | ! | 2425 // | task | cancel | ! | 2426 // | task | taskloop | * | 2427 // | task | taskloop simd | * | 2428 // | task | distribute | + | 2429 // | task | distribute | + | 2430 // | | parallel for | | 2431 // | task | distribute | + | 2432 // | |parallel for simd| | 2433 // | task | distribute simd | + | 2434 // | task | target parallel | + | 2435 // | | for simd | | 2436 // | task | target simd | * | 2437 // +------------------+-----------------+------------------------------------+ 2438 // | ordered | parallel | * | 2439 // | ordered | for | + | 2440 // | ordered | for simd | + | 2441 // | ordered | master | * | 2442 // | ordered | critical | * | 2443 // | ordered | simd | * | 2444 // | ordered | sections | + | 2445 // | ordered | section | + | 2446 // | ordered | single | + | 2447 // | ordered | parallel for | * | 2448 // | ordered |parallel for simd| * | 2449 // | ordered |parallel sections| * | 2450 // | ordered | task | * | 2451 // | ordered | taskyield | * | 2452 // | ordered | barrier | + | 2453 // | ordered | taskwait | * | 2454 // | ordered | taskgroup | * | 2455 // | ordered | flush | * | 2456 // | ordered | ordered | + | 2457 // | ordered | atomic | * | 2458 // | ordered | target | * | 2459 // | ordered | target parallel | * | 2460 // | ordered | target parallel | * | 2461 // | | for | | 2462 // | ordered | target enter | * | 2463 // | | data | | 2464 // | ordered | target exit | * | 2465 // | | data | | 2466 // | ordered | teams | + | 2467 // | ordered | cancellation | | 2468 // | | point | | 2469 // | ordered | cancel | | 2470 // | ordered | taskloop | * | 2471 // | ordered | taskloop simd | * | 2472 // | ordered | distribute | + | 2473 // | ordered | distribute | + | 2474 // | | parallel for | | 2475 // | ordered | distribute | + | 2476 // | |parallel for simd| | 2477 // | ordered | distribute simd | + | 2478 // | ordered | target parallel | + | 2479 // | | for simd | | 2480 // | ordered | target simd | * | 2481 // +------------------+-----------------+------------------------------------+ 2482 // | atomic | parallel | | 2483 // | atomic | for | | 2484 // | atomic | for simd | | 2485 // | atomic | master | | 2486 // | atomic | critical | | 2487 // | atomic | simd | | 2488 // | atomic | sections | | 2489 // | atomic | section | | 2490 // | atomic | single | | 2491 // | atomic | parallel for | | 2492 // | atomic |parallel for simd| | 2493 // | atomic |parallel sections| | 2494 // | atomic | task | | 2495 // | atomic | taskyield | | 2496 // | atomic | barrier | | 2497 // | atomic | taskwait | | 2498 // | atomic | taskgroup | | 2499 // | atomic | flush | | 2500 // | atomic | ordered | | 2501 // | atomic | atomic | | 2502 // | atomic | target | | 2503 // | atomic | target parallel | | 2504 // | atomic | target parallel | | 2505 // | | for | | 2506 // | atomic | target enter | | 2507 // | | data | | 2508 // | atomic | target exit | | 2509 // | | data | | 2510 // | atomic | teams | | 2511 // | atomic | cancellation | | 2512 // | | point | | 2513 // | atomic | cancel | | 2514 // | atomic | taskloop | | 2515 // | atomic | taskloop simd | | 2516 // | atomic | distribute | | 2517 // | atomic | distribute | | 2518 // | | parallel for | | 2519 // | atomic | distribute | | 2520 // | |parallel for simd| | 2521 // | atomic | distribute simd | | 2522 // | atomic | target parallel | | 2523 // | | for simd | | 2524 // | atomic | target simd | | 2525 // +------------------+-----------------+------------------------------------+ 2526 // | target | parallel | * | 2527 // | target | for | * | 2528 // | target | for simd | * | 2529 // | target | master | * | 2530 // | target | critical | * | 2531 // | target | simd | * | 2532 // | target | sections | * | 2533 // | target | section | * | 2534 // | target | single | * | 2535 // | target | parallel for | * | 2536 // | target |parallel for simd| * | 2537 // | target |parallel sections| * | 2538 // | target | task | * | 2539 // | target | taskyield | * | 2540 // | target | barrier | * | 2541 // | target | taskwait | * | 2542 // | target | taskgroup | * | 2543 // | target | flush | * | 2544 // | target | ordered | * | 2545 // | target | atomic | * | 2546 // | target | target | | 2547 // | target | target parallel | | 2548 // | target | target parallel | | 2549 // | | for | | 2550 // | target | target enter | | 2551 // | | data | | 2552 // | target | target exit | | 2553 // | | data | | 2554 // | target | teams | * | 2555 // | target | cancellation | | 2556 // | | point | | 2557 // | target | cancel | | 2558 // | target | taskloop | * | 2559 // | target | taskloop simd | * | 2560 // | target | distribute | + | 2561 // | target | distribute | + | 2562 // | | parallel for | | 2563 // | target | distribute | + | 2564 // | |parallel for simd| | 2565 // | target | distribute simd | + | 2566 // | target | target parallel | | 2567 // | | for simd | | 2568 // | target | target simd | | 2569 // +------------------+-----------------+------------------------------------+ 2570 // | target parallel | parallel | * | 2571 // | target parallel | for | * | 2572 // | target parallel | for simd | * | 2573 // | target parallel | master | * | 2574 // | target parallel | critical | * | 2575 // | target parallel | simd | * | 2576 // | target parallel | sections | * | 2577 // | target parallel | section | * | 2578 // | target parallel | single | * | 2579 // | target parallel | parallel for | * | 2580 // | target parallel |parallel for simd| * | 2581 // | target parallel |parallel sections| * | 2582 // | target parallel | task | * | 2583 // | target parallel | taskyield | * | 2584 // | target parallel | barrier | * | 2585 // | target parallel | taskwait | * | 2586 // | target parallel | taskgroup | * | 2587 // | target parallel | flush | * | 2588 // | target parallel | ordered | * | 2589 // | target parallel | atomic | * | 2590 // | target parallel | target | | 2591 // | target parallel | target parallel | | 2592 // | target parallel | target parallel | | 2593 // | | for | | 2594 // | target parallel | target enter | | 2595 // | | data | | 2596 // | target parallel | target exit | | 2597 // | | data | | 2598 // | target parallel | teams | | 2599 // | target parallel | cancellation | | 2600 // | | point | ! | 2601 // | target parallel | cancel | ! | 2602 // | target parallel | taskloop | * | 2603 // | target parallel | taskloop simd | * | 2604 // | target parallel | distribute | | 2605 // | target parallel | distribute | | 2606 // | | parallel for | | 2607 // | target parallel | distribute | | 2608 // | |parallel for simd| | 2609 // | target parallel | distribute simd | | 2610 // | target parallel | target parallel | | 2611 // | | for simd | | 2612 // | target parallel | target simd | | 2613 // +------------------+-----------------+------------------------------------+ 2614 // | target parallel | parallel | * | 2615 // | for | | | 2616 // | target parallel | for | * | 2617 // | for | | | 2618 // | target parallel | for simd | * | 2619 // | for | | | 2620 // | target parallel | master | * | 2621 // | for | | | 2622 // | target parallel | critical | * | 2623 // | for | | | 2624 // | target parallel | simd | * | 2625 // | for | | | 2626 // | target parallel | sections | * | 2627 // | for | | | 2628 // | target parallel | section | * | 2629 // | for | | | 2630 // | target parallel | single | * | 2631 // | for | | | 2632 // | target parallel | parallel for | * | 2633 // | for | | | 2634 // | target parallel |parallel for simd| * | 2635 // | for | | | 2636 // | target parallel |parallel sections| * | 2637 // | for | | | 2638 // | target parallel | task | * | 2639 // | for | | | 2640 // | target parallel | taskyield | * | 2641 // | for | | | 2642 // | target parallel | barrier | * | 2643 // | for | | | 2644 // | target parallel | taskwait | * | 2645 // | for | | | 2646 // | target parallel | taskgroup | * | 2647 // | for | | | 2648 // | target parallel | flush | * | 2649 // | for | | | 2650 // | target parallel | ordered | * | 2651 // | for | | | 2652 // | target parallel | atomic | * | 2653 // | for | | | 2654 // | target parallel | target | | 2655 // | for | | | 2656 // | target parallel | target parallel | | 2657 // | for | | | 2658 // | target parallel | target parallel | | 2659 // | for | for | | 2660 // | target parallel | target enter | | 2661 // | for | data | | 2662 // | target parallel | target exit | | 2663 // | for | data | | 2664 // | target parallel | teams | | 2665 // | for | | | 2666 // | target parallel | cancellation | | 2667 // | for | point | ! | 2668 // | target parallel | cancel | ! | 2669 // | for | | | 2670 // | target parallel | taskloop | * | 2671 // | for | | | 2672 // | target parallel | taskloop simd | * | 2673 // | for | | | 2674 // | target parallel | distribute | | 2675 // | for | | | 2676 // | target parallel | distribute | | 2677 // | for | parallel for | | 2678 // | target parallel | distribute | | 2679 // | for |parallel for simd| | 2680 // | target parallel | distribute simd | | 2681 // | for | | | 2682 // | target parallel | target parallel | | 2683 // | for | for simd | | 2684 // | target parallel | target simd | | 2685 // | for | | | 2686 // +------------------+-----------------+------------------------------------+ 2687 // | teams | parallel | * | 2688 // | teams | for | + | 2689 // | teams | for simd | + | 2690 // | teams | master | + | 2691 // | teams | critical | + | 2692 // | teams | simd | + | 2693 // | teams | sections | + | 2694 // | teams | section | + | 2695 // | teams | single | + | 2696 // | teams | parallel for | * | 2697 // | teams |parallel for simd| * | 2698 // | teams |parallel sections| * | 2699 // | teams | task | + | 2700 // | teams | taskyield | + | 2701 // | teams | barrier | + | 2702 // | teams | taskwait | + | 2703 // | teams | taskgroup | + | 2704 // | teams | flush | + | 2705 // | teams | ordered | + | 2706 // | teams | atomic | + | 2707 // | teams | target | + | 2708 // | teams | target parallel | + | 2709 // | teams | target parallel | + | 2710 // | | for | | 2711 // | teams | target enter | + | 2712 // | | data | | 2713 // | teams | target exit | + | 2714 // | | data | | 2715 // | teams | teams | + | 2716 // | teams | cancellation | | 2717 // | | point | | 2718 // | teams | cancel | | 2719 // | teams | taskloop | + | 2720 // | teams | taskloop simd | + | 2721 // | teams | distribute | ! | 2722 // | teams | distribute | ! | 2723 // | | parallel for | | 2724 // | teams | distribute | ! | 2725 // | |parallel for simd| | 2726 // | teams | distribute simd | ! | 2727 // | teams | target parallel | + | 2728 // | | for simd | | 2729 // | teams | target simd | + | 2730 // +------------------+-----------------+------------------------------------+ 2731 // | taskloop | parallel | * | 2732 // | taskloop | for | + | 2733 // | taskloop | for simd | + | 2734 // | taskloop | master | + | 2735 // | taskloop | critical | * | 2736 // | taskloop | simd | * | 2737 // | taskloop | sections | + | 2738 // | taskloop | section | + | 2739 // | taskloop | single | + | 2740 // | taskloop | parallel for | * | 2741 // | taskloop |parallel for simd| * | 2742 // | taskloop |parallel sections| * | 2743 // | taskloop | task | * | 2744 // | taskloop | taskyield | * | 2745 // | taskloop | barrier | + | 2746 // | taskloop | taskwait | * | 2747 // | taskloop | taskgroup | * | 2748 // | taskloop | flush | * | 2749 // | taskloop | ordered | + | 2750 // | taskloop | atomic | * | 2751 // | taskloop | target | * | 2752 // | taskloop | target parallel | * | 2753 // | taskloop | target parallel | * | 2754 // | | for | | 2755 // | taskloop | target enter | * | 2756 // | | data | | 2757 // | taskloop | target exit | * | 2758 // | | data | | 2759 // | taskloop | teams | + | 2760 // | taskloop | cancellation | | 2761 // | | point | | 2762 // | taskloop | cancel | | 2763 // | taskloop | taskloop | * | 2764 // | taskloop | distribute | + | 2765 // | taskloop | distribute | + | 2766 // | | parallel for | | 2767 // | taskloop | distribute | + | 2768 // | |parallel for simd| | 2769 // | taskloop | distribute simd | + | 2770 // | taskloop | target parallel | * | 2771 // | | for simd | | 2772 // | taskloop | target simd | * | 2773 // +------------------+-----------------+------------------------------------+ 2774 // | taskloop simd | parallel | | 2775 // | taskloop simd | for | | 2776 // | taskloop simd | for simd | | 2777 // | taskloop simd | master | | 2778 // | taskloop simd | critical | | 2779 // | taskloop simd | simd | * | 2780 // | taskloop simd | sections | | 2781 // | taskloop simd | section | | 2782 // | taskloop simd | single | | 2783 // | taskloop simd | parallel for | | 2784 // | taskloop simd |parallel for simd| | 2785 // | taskloop simd |parallel sections| | 2786 // | taskloop simd | task | | 2787 // | taskloop simd | taskyield | | 2788 // | taskloop simd | barrier | | 2789 // | taskloop simd | taskwait | | 2790 // | taskloop simd | taskgroup | | 2791 // | taskloop simd | flush | | 2792 // | taskloop simd | ordered | + (with simd clause) | 2793 // | taskloop simd | atomic | | 2794 // | taskloop simd | target | | 2795 // | taskloop simd | target parallel | | 2796 // | taskloop simd | target parallel | | 2797 // | | for | | 2798 // | taskloop simd | target enter | | 2799 // | | data | | 2800 // | taskloop simd | target exit | | 2801 // | | data | | 2802 // | taskloop simd | teams | | 2803 // | taskloop simd | cancellation | | 2804 // | | point | | 2805 // | taskloop simd | cancel | | 2806 // | taskloop simd | taskloop | | 2807 // | taskloop simd | taskloop simd | | 2808 // | taskloop simd | distribute | | 2809 // | taskloop simd | distribute | | 2810 // | | parallel for | | 2811 // | taskloop simd | distribute | | 2812 // | |parallel for simd| | 2813 // | taskloop simd | distribute simd | | 2814 // | taskloop simd | target parallel | | 2815 // | | for simd | | 2816 // | taskloop simd | target simd | | 2817 // +------------------+-----------------+------------------------------------+ 2818 // | distribute | parallel | * | 2819 // | distribute | for | * | 2820 // | distribute | for simd | * | 2821 // | distribute | master | * | 2822 // | distribute | critical | * | 2823 // | distribute | simd | * | 2824 // | distribute | sections | * | 2825 // | distribute | section | * | 2826 // | distribute | single | * | 2827 // | distribute | parallel for | * | 2828 // | distribute |parallel for simd| * | 2829 // | distribute |parallel sections| * | 2830 // | distribute | task | * | 2831 // | distribute | taskyield | * | 2832 // | distribute | barrier | * | 2833 // | distribute | taskwait | * | 2834 // | distribute | taskgroup | * | 2835 // | distribute | flush | * | 2836 // | distribute | ordered | + | 2837 // | distribute | atomic | * | 2838 // | distribute | target | | 2839 // | distribute | target parallel | | 2840 // | distribute | target parallel | | 2841 // | | for | | 2842 // | distribute | target enter | | 2843 // | | data | | 2844 // | distribute | target exit | | 2845 // | | data | | 2846 // | distribute | teams | | 2847 // | distribute | cancellation | + | 2848 // | | point | | 2849 // | distribute | cancel | + | 2850 // | distribute | taskloop | * | 2851 // | distribute | taskloop simd | * | 2852 // | distribute | distribute | | 2853 // | distribute | distribute | | 2854 // | | parallel for | | 2855 // | distribute | distribute | | 2856 // | |parallel for simd| | 2857 // | distribute | distribute simd | | 2858 // | distribute | target parallel | | 2859 // | | for simd | | 2860 // | distribute | target simd | | 2861 // +------------------+-----------------+------------------------------------+ 2862 // | distribute | parallel | * | 2863 // | parallel for | | | 2864 // | distribute | for | * | 2865 // | parallel for | | | 2866 // | distribute | for simd | * | 2867 // | parallel for | | | 2868 // | distribute | master | * | 2869 // | parallel for | | | 2870 // | distribute | critical | * | 2871 // | parallel for | | | 2872 // | distribute | simd | * | 2873 // | parallel for | | | 2874 // | distribute | sections | * | 2875 // | parallel for | | | 2876 // | distribute | section | * | 2877 // | parallel for | | | 2878 // | distribute | single | * | 2879 // | parallel for | | | 2880 // | distribute | parallel for | * | 2881 // | parallel for | | | 2882 // | distribute |parallel for simd| * | 2883 // | parallel for | | | 2884 // | distribute |parallel sections| * | 2885 // | parallel for | | | 2886 // | distribute | task | * | 2887 // | parallel for | | | 2888 // | parallel for | | | 2889 // | distribute | taskyield | * | 2890 // | parallel for | | | 2891 // | distribute | barrier | * | 2892 // | parallel for | | | 2893 // | distribute | taskwait | * | 2894 // | parallel for | | | 2895 // | distribute | taskgroup | * | 2896 // | parallel for | | | 2897 // | distribute | flush | * | 2898 // | parallel for | | | 2899 // | distribute | ordered | + | 2900 // | parallel for | | | 2901 // | distribute | atomic | * | 2902 // | parallel for | | | 2903 // | distribute | target | | 2904 // | parallel for | | | 2905 // | distribute | target parallel | | 2906 // | parallel for | | | 2907 // | distribute | target parallel | | 2908 // | parallel for | for | | 2909 // | distribute | target enter | | 2910 // | parallel for | data | | 2911 // | distribute | target exit | | 2912 // | parallel for | data | | 2913 // | distribute | teams | | 2914 // | parallel for | | | 2915 // | distribute | cancellation | + | 2916 // | parallel for | point | | 2917 // | distribute | cancel | + | 2918 // | parallel for | | | 2919 // | distribute | taskloop | * | 2920 // | parallel for | | | 2921 // | distribute | taskloop simd | * | 2922 // | parallel for | | | 2923 // | distribute | distribute | | 2924 // | parallel for | | | 2925 // | distribute | distribute | | 2926 // | parallel for | parallel for | | 2927 // | distribute | distribute | | 2928 // | parallel for |parallel for simd| | 2929 // | distribute | distribute simd | | 2930 // | parallel for | | | 2931 // | distribute | target parallel | | 2932 // | parallel for | for simd | | 2933 // | distribute | target simd | | 2934 // | parallel for | | | 2935 // +------------------+-----------------+------------------------------------+ 2936 // | distribute | parallel | * | 2937 // | parallel for simd| | | 2938 // | distribute | for | * | 2939 // | parallel for simd| | | 2940 // | distribute | for simd | * | 2941 // | parallel for simd| | | 2942 // | distribute | master | * | 2943 // | parallel for simd| | | 2944 // | distribute | critical | * | 2945 // | parallel for simd| | | 2946 // | distribute | simd | * | 2947 // | parallel for simd| | | 2948 // | distribute | sections | * | 2949 // | parallel for simd| | | 2950 // | distribute | section | * | 2951 // | parallel for simd| | | 2952 // | distribute | single | * | 2953 // | parallel for simd| | | 2954 // | distribute | parallel for | * | 2955 // | parallel for simd| | | 2956 // | distribute |parallel for simd| * | 2957 // | parallel for simd| | | 2958 // | distribute |parallel sections| * | 2959 // | parallel for simd| | | 2960 // | distribute | task | * | 2961 // | parallel for simd| | | 2962 // | distribute | taskyield | * | 2963 // | parallel for simd| | | 2964 // | distribute | barrier | * | 2965 // | parallel for simd| | | 2966 // | distribute | taskwait | * | 2967 // | parallel for simd| | | 2968 // | distribute | taskgroup | * | 2969 // | parallel for simd| | | 2970 // | distribute | flush | * | 2971 // | parallel for simd| | | 2972 // | distribute | ordered | + | 2973 // | parallel for simd| | | 2974 // | distribute | atomic | * | 2975 // | parallel for simd| | | 2976 // | distribute | target | | 2977 // | parallel for simd| | | 2978 // | distribute | target parallel | | 2979 // | parallel for simd| | | 2980 // | distribute | target parallel | | 2981 // | parallel for simd| for | | 2982 // | distribute | target enter | | 2983 // | parallel for simd| data | | 2984 // | distribute | target exit | | 2985 // | parallel for simd| data | | 2986 // | distribute | teams | | 2987 // | parallel for simd| | | 2988 // | distribute | cancellation | + | 2989 // | parallel for simd| point | | 2990 // | distribute | cancel | + | 2991 // | parallel for simd| | | 2992 // | distribute | taskloop | * | 2993 // | parallel for simd| | | 2994 // | distribute | taskloop simd | * | 2995 // | parallel for simd| | | 2996 // | distribute | distribute | | 2997 // | parallel for simd| | | 2998 // | distribute | distribute | * | 2999 // | parallel for simd| parallel for | | 3000 // | distribute | distribute | * | 3001 // | parallel for simd|parallel for simd| | 3002 // | distribute | distribute simd | * | 3003 // | parallel for simd| | | 3004 // | distribute | target parallel | | 3005 // | parallel for simd| for simd | | 3006 // | distribute | target simd | | 3007 // | parallel for simd| | | 3008 // +------------------+-----------------+------------------------------------+ 3009 // | distribute simd | parallel | * | 3010 // | distribute simd | for | * | 3011 // | distribute simd | for simd | * | 3012 // | distribute simd | master | * | 3013 // | distribute simd | critical | * | 3014 // | distribute simd | simd | * | 3015 // | distribute simd | sections | * | 3016 // | distribute simd | section | * | 3017 // | distribute simd | single | * | 3018 // | distribute simd | parallel for | * | 3019 // | distribute simd |parallel for simd| * | 3020 // | distribute simd |parallel sections| * | 3021 // | distribute simd | task | * | 3022 // | distribute simd | taskyield | * | 3023 // | distribute simd | barrier | * | 3024 // | distribute simd | taskwait | * | 3025 // | distribute simd | taskgroup | * | 3026 // | distribute simd | flush | * | 3027 // | distribute simd | ordered | + | 3028 // | distribute simd | atomic | * | 3029 // | distribute simd | target | * | 3030 // | distribute simd | target parallel | * | 3031 // | distribute simd | target parallel | * | 3032 // | | for | | 3033 // | distribute simd | target enter | * | 3034 // | | data | | 3035 // | distribute simd | target exit | * | 3036 // | | data | | 3037 // | distribute simd | teams | * | 3038 // | distribute simd | cancellation | + | 3039 // | | point | | 3040 // | distribute simd | cancel | + | 3041 // | distribute simd | taskloop | * | 3042 // | distribute simd | taskloop simd | * | 3043 // | distribute simd | distribute | | 3044 // | distribute simd | distribute | * | 3045 // | | parallel for | | 3046 // | distribute simd | distribute | * | 3047 // | |parallel for simd| | 3048 // | distribute simd | distribute simd | * | 3049 // | distribute simd | target parallel | * | 3050 // | | for simd | | 3051 // | distribute simd | target simd | * | 3052 // +------------------+-----------------+------------------------------------+ 3053 // | target parallel | parallel | * | 3054 // | for simd | | | 3055 // | target parallel | for | * | 3056 // | for simd | | | 3057 // | target parallel | for simd | * | 3058 // | for simd | | | 3059 // | target parallel | master | * | 3060 // | for simd | | | 3061 // | target parallel | critical | * | 3062 // | for simd | | | 3063 // | target parallel | simd | ! | 3064 // | for simd | | | 3065 // | target parallel | sections | * | 3066 // | for simd | | | 3067 // | target parallel | section | * | 3068 // | for simd | | | 3069 // | target parallel | single | * | 3070 // | for simd | | | 3071 // | target parallel | parallel for | * | 3072 // | for simd | | | 3073 // | target parallel |parallel for simd| * | 3074 // | for simd | | | 3075 // | target parallel |parallel sections| * | 3076 // | for simd | | | 3077 // | target parallel | task | * | 3078 // | for simd | | | 3079 // | target parallel | taskyield | * | 3080 // | for simd | | | 3081 // | target parallel | barrier | * | 3082 // | for simd | | | 3083 // | target parallel | taskwait | * | 3084 // | for simd | | | 3085 // | target parallel | taskgroup | * | 3086 // | for simd | | | 3087 // | target parallel | flush | * | 3088 // | for simd | | | 3089 // | target parallel | ordered | + (with simd clause) | 3090 // | for simd | | | 3091 // | target parallel | atomic | * | 3092 // | for simd | | | 3093 // | target parallel | target | * | 3094 // | for simd | | | 3095 // | target parallel | target parallel | * | 3096 // | for simd | | | 3097 // | target parallel | target parallel | * | 3098 // | for simd | for | | 3099 // | target parallel | target enter | * | 3100 // | for simd | data | | 3101 // | target parallel | target exit | * | 3102 // | for simd | data | | 3103 // | target parallel | teams | * | 3104 // | for simd | | | 3105 // | target parallel | cancellation | * | 3106 // | for simd | point | | 3107 // | target parallel | cancel | * | 3108 // | for simd | | | 3109 // | target parallel | taskloop | * | 3110 // | for simd | | | 3111 // | target parallel | taskloop simd | * | 3112 // | for simd | | | 3113 // | target parallel | distribute | * | 3114 // | for simd | | | 3115 // | target parallel | distribute | * | 3116 // | for simd | parallel for | | 3117 // | target parallel | distribute | * | 3118 // | for simd |parallel for simd| | 3119 // | target parallel | distribute simd | * | 3120 // | for simd | | | 3121 // | target parallel | target parallel | * | 3122 // | for simd | for simd | | 3123 // | target parallel | target simd | * | 3124 // | for simd | | | 3125 // +------------------+-----------------+------------------------------------+ 3126 // | target simd | parallel | | 3127 // | target simd | for | | 3128 // | target simd | for simd | | 3129 // | target simd | master | | 3130 // | target simd | critical | | 3131 // | target simd | simd | | 3132 // | target simd | sections | | 3133 // | target simd | section | | 3134 // | target simd | single | | 3135 // | target simd | parallel for | | 3136 // | target simd |parallel for simd| | 3137 // | target simd |parallel sections| | 3138 // | target simd | task | | 3139 // | target simd | taskyield | | 3140 // | target simd | barrier | | 3141 // | target simd | taskwait | | 3142 // | target simd | taskgroup | | 3143 // | target simd | flush | | 3144 // | target simd | ordered | + (with simd clause) | 3145 // | target simd | atomic | | 3146 // | target simd | target | | 3147 // | target simd | target parallel | | 3148 // | target simd | target parallel | | 3149 // | | for | | 3150 // | target simd | target enter | | 3151 // | | data | | 3152 // | target simd | target exit | | 3153 // | | data | | 3154 // | target simd | teams | | 3155 // | target simd | cancellation | | 3156 // | | point | | 3157 // | target simd | cancel | | 3158 // | target simd | taskloop | | 3159 // | target simd | taskloop simd | | 3160 // | target simd | distribute | | 3161 // | target simd | distribute | | 3162 // | | parallel for | | 3163 // | target simd | distribute | | 3164 // | |parallel for simd| | 3165 // | target simd | distribute simd | | 3166 // | target simd | target parallel | | 3167 // | | for simd | | 3168 // | target simd | target simd | | 3169 // +------------------+-----------------+------------------------------------+ 3170 if (Stack->getCurScope()) { 3171 auto ParentRegion = Stack->getParentDirective(); 3172 auto OffendingRegion = ParentRegion; 3173 bool NestingProhibited = false; 3174 bool CloseNesting = true; 3175 enum { 3176 NoRecommend, 3177 ShouldBeInParallelRegion, 3178 ShouldBeInOrderedRegion, 3179 ShouldBeInTargetRegion, 3180 ShouldBeInTeamsRegion 3181 } Recommend = NoRecommend; 3182 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 3183 // OpenMP [2.16, Nesting of Regions] 3184 // OpenMP constructs may not be nested inside a simd region. 3185 // OpenMP [2.8.1,simd Construct, Restrictions] 3186 // An ordered construct with the simd clause is the only OpenMP 3187 // construct that can appear in the simd region. 3188 // Allowing a SIMD consruct nested in another SIMD construct is an 3189 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 3190 // message. 3191 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 3192 ? diag::err_omp_prohibited_region_simd 3193 : diag::warn_omp_nesting_simd); 3194 return CurrentRegion != OMPD_simd; 3195 } 3196 if (ParentRegion == OMPD_atomic) { 3197 // OpenMP [2.16, Nesting of Regions] 3198 // OpenMP constructs may not be nested inside an atomic region. 3199 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 3200 return true; 3201 } 3202 if (CurrentRegion == OMPD_section) { 3203 // OpenMP [2.7.2, sections Construct, Restrictions] 3204 // Orphaned section directives are prohibited. That is, the section 3205 // directives must appear within the sections construct and must not be 3206 // encountered elsewhere in the sections region. 3207 if (ParentRegion != OMPD_sections && 3208 ParentRegion != OMPD_parallel_sections) { 3209 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 3210 << (ParentRegion != OMPD_unknown) 3211 << getOpenMPDirectiveName(ParentRegion); 3212 return true; 3213 } 3214 return false; 3215 } 3216 // Allow some constructs to be orphaned (they could be used in functions, 3217 // called from OpenMP regions with the required preconditions). 3218 if (ParentRegion == OMPD_unknown) 3219 return false; 3220 if (CurrentRegion == OMPD_cancellation_point || 3221 CurrentRegion == OMPD_cancel) { 3222 // OpenMP [2.16, Nesting of Regions] 3223 // A cancellation point construct for which construct-type-clause is 3224 // taskgroup must be nested inside a task construct. A cancellation 3225 // point construct for which construct-type-clause is not taskgroup must 3226 // be closely nested inside an OpenMP construct that matches the type 3227 // specified in construct-type-clause. 3228 // A cancel construct for which construct-type-clause is taskgroup must be 3229 // nested inside a task construct. A cancel construct for which 3230 // construct-type-clause is not taskgroup must be closely nested inside an 3231 // OpenMP construct that matches the type specified in 3232 // construct-type-clause. 3233 NestingProhibited = 3234 !((CancelRegion == OMPD_parallel && 3235 (ParentRegion == OMPD_parallel || 3236 ParentRegion == OMPD_target_parallel)) || 3237 (CancelRegion == OMPD_for && 3238 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 3239 ParentRegion == OMPD_target_parallel_for)) || 3240 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 3241 (CancelRegion == OMPD_sections && 3242 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 3243 ParentRegion == OMPD_parallel_sections))); 3244 } else if (CurrentRegion == OMPD_master) { 3245 // OpenMP [2.16, Nesting of Regions] 3246 // A master region may not be closely nested inside a worksharing, 3247 // atomic, or explicit task region. 3248 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3249 isOpenMPTaskingDirective(ParentRegion); 3250 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 3251 // OpenMP [2.16, Nesting of Regions] 3252 // A critical region may not be nested (closely or otherwise) inside a 3253 // critical region with the same name. Note that this restriction is not 3254 // sufficient to prevent deadlock. 3255 SourceLocation PreviousCriticalLoc; 3256 bool DeadLock = 3257 Stack->hasDirective([CurrentName, &PreviousCriticalLoc]( 3258 OpenMPDirectiveKind K, 3259 const DeclarationNameInfo &DNI, 3260 SourceLocation Loc) 3261 ->bool { 3262 if (K == OMPD_critical && 3263 DNI.getName() == CurrentName.getName()) { 3264 PreviousCriticalLoc = Loc; 3265 return true; 3266 } else 3267 return false; 3268 }, 3269 false /* skip top directive */); 3270 if (DeadLock) { 3271 SemaRef.Diag(StartLoc, 3272 diag::err_omp_prohibited_region_critical_same_name) 3273 << CurrentName.getName(); 3274 if (PreviousCriticalLoc.isValid()) 3275 SemaRef.Diag(PreviousCriticalLoc, 3276 diag::note_omp_previous_critical_region); 3277 return true; 3278 } 3279 } else if (CurrentRegion == OMPD_barrier) { 3280 // OpenMP [2.16, Nesting of Regions] 3281 // A barrier region may not be closely nested inside a worksharing, 3282 // explicit task, critical, ordered, atomic, or master region. 3283 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3284 isOpenMPTaskingDirective(ParentRegion) || 3285 ParentRegion == OMPD_master || 3286 ParentRegion == OMPD_critical || 3287 ParentRegion == OMPD_ordered; 3288 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 3289 !isOpenMPParallelDirective(CurrentRegion)) { 3290 // OpenMP [2.16, Nesting of Regions] 3291 // A worksharing region may not be closely nested inside a worksharing, 3292 // explicit task, critical, ordered, atomic, or master region. 3293 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3294 isOpenMPTaskingDirective(ParentRegion) || 3295 ParentRegion == OMPD_master || 3296 ParentRegion == OMPD_critical || 3297 ParentRegion == OMPD_ordered; 3298 Recommend = ShouldBeInParallelRegion; 3299 } else if (CurrentRegion == OMPD_ordered) { 3300 // OpenMP [2.16, Nesting of Regions] 3301 // An ordered region may not be closely nested inside a critical, 3302 // atomic, or explicit task region. 3303 // An ordered region must be closely nested inside a loop region (or 3304 // parallel loop region) with an ordered clause. 3305 // OpenMP [2.8.1,simd Construct, Restrictions] 3306 // An ordered construct with the simd clause is the only OpenMP construct 3307 // that can appear in the simd region. 3308 NestingProhibited = ParentRegion == OMPD_critical || 3309 isOpenMPTaskingDirective(ParentRegion) || 3310 !(isOpenMPSimdDirective(ParentRegion) || 3311 Stack->isParentOrderedRegion()); 3312 Recommend = ShouldBeInOrderedRegion; 3313 } else if (isOpenMPTeamsDirective(CurrentRegion)) { 3314 // OpenMP [2.16, Nesting of Regions] 3315 // If specified, a teams construct must be contained within a target 3316 // construct. 3317 NestingProhibited = ParentRegion != OMPD_target; 3318 Recommend = ShouldBeInTargetRegion; 3319 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 3320 } 3321 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) { 3322 // OpenMP [2.16, Nesting of Regions] 3323 // distribute, parallel, parallel sections, parallel workshare, and the 3324 // parallel loop and parallel loop SIMD constructs are the only OpenMP 3325 // constructs that can be closely nested in the teams region. 3326 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 3327 !isOpenMPDistributeDirective(CurrentRegion); 3328 Recommend = ShouldBeInParallelRegion; 3329 } 3330 if (!NestingProhibited && isOpenMPDistributeDirective(CurrentRegion)) { 3331 // OpenMP 4.5 [2.17 Nesting of Regions] 3332 // The region associated with the distribute construct must be strictly 3333 // nested inside a teams region 3334 NestingProhibited = !isOpenMPTeamsDirective(ParentRegion); 3335 Recommend = ShouldBeInTeamsRegion; 3336 } 3337 if (!NestingProhibited && 3338 (isOpenMPTargetExecutionDirective(CurrentRegion) || 3339 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 3340 // OpenMP 4.5 [2.17 Nesting of Regions] 3341 // If a target, target update, target data, target enter data, or 3342 // target exit data construct is encountered during execution of a 3343 // target region, the behavior is unspecified. 3344 NestingProhibited = Stack->hasDirective( 3345 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 3346 SourceLocation) -> bool { 3347 if (isOpenMPTargetExecutionDirective(K)) { 3348 OffendingRegion = K; 3349 return true; 3350 } else 3351 return false; 3352 }, 3353 false /* don't skip top directive */); 3354 CloseNesting = false; 3355 } 3356 if (NestingProhibited) { 3357 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 3358 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 3359 << Recommend << getOpenMPDirectiveName(CurrentRegion); 3360 return true; 3361 } 3362 } 3363 return false; 3364 } 3365 3366 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 3367 ArrayRef<OMPClause *> Clauses, 3368 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 3369 bool ErrorFound = false; 3370 unsigned NamedModifiersNumber = 0; 3371 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 3372 OMPD_unknown + 1); 3373 SmallVector<SourceLocation, 4> NameModifierLoc; 3374 for (const auto *C : Clauses) { 3375 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 3376 // At most one if clause without a directive-name-modifier can appear on 3377 // the directive. 3378 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 3379 if (FoundNameModifiers[CurNM]) { 3380 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 3381 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 3382 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 3383 ErrorFound = true; 3384 } else if (CurNM != OMPD_unknown) { 3385 NameModifierLoc.push_back(IC->getNameModifierLoc()); 3386 ++NamedModifiersNumber; 3387 } 3388 FoundNameModifiers[CurNM] = IC; 3389 if (CurNM == OMPD_unknown) 3390 continue; 3391 // Check if the specified name modifier is allowed for the current 3392 // directive. 3393 // At most one if clause with the particular directive-name-modifier can 3394 // appear on the directive. 3395 bool MatchFound = false; 3396 for (auto NM : AllowedNameModifiers) { 3397 if (CurNM == NM) { 3398 MatchFound = true; 3399 break; 3400 } 3401 } 3402 if (!MatchFound) { 3403 S.Diag(IC->getNameModifierLoc(), 3404 diag::err_omp_wrong_if_directive_name_modifier) 3405 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 3406 ErrorFound = true; 3407 } 3408 } 3409 } 3410 // If any if clause on the directive includes a directive-name-modifier then 3411 // all if clauses on the directive must include a directive-name-modifier. 3412 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 3413 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 3414 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 3415 diag::err_omp_no_more_if_clause); 3416 } else { 3417 std::string Values; 3418 std::string Sep(", "); 3419 unsigned AllowedCnt = 0; 3420 unsigned TotalAllowedNum = 3421 AllowedNameModifiers.size() - NamedModifiersNumber; 3422 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 3423 ++Cnt) { 3424 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 3425 if (!FoundNameModifiers[NM]) { 3426 Values += "'"; 3427 Values += getOpenMPDirectiveName(NM); 3428 Values += "'"; 3429 if (AllowedCnt + 2 == TotalAllowedNum) 3430 Values += " or "; 3431 else if (AllowedCnt + 1 != TotalAllowedNum) 3432 Values += Sep; 3433 ++AllowedCnt; 3434 } 3435 } 3436 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 3437 diag::err_omp_unnamed_if_clause) 3438 << (TotalAllowedNum > 1) << Values; 3439 } 3440 for (auto Loc : NameModifierLoc) { 3441 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 3442 } 3443 ErrorFound = true; 3444 } 3445 return ErrorFound; 3446 } 3447 3448 StmtResult Sema::ActOnOpenMPExecutableDirective( 3449 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 3450 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 3451 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 3452 StmtResult Res = StmtError(); 3453 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 3454 StartLoc)) 3455 return StmtError(); 3456 3457 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 3458 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 3459 bool ErrorFound = false; 3460 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 3461 if (AStmt) { 3462 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3463 3464 // Check default data sharing attributes for referenced variables. 3465 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 3466 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt()); 3467 if (DSAChecker.isErrorFound()) 3468 return StmtError(); 3469 // Generate list of implicitly defined firstprivate variables. 3470 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 3471 3472 if (!DSAChecker.getImplicitFirstprivate().empty()) { 3473 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 3474 DSAChecker.getImplicitFirstprivate(), SourceLocation(), 3475 SourceLocation(), SourceLocation())) { 3476 ClausesWithImplicit.push_back(Implicit); 3477 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 3478 DSAChecker.getImplicitFirstprivate().size(); 3479 } else 3480 ErrorFound = true; 3481 } 3482 } 3483 3484 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 3485 switch (Kind) { 3486 case OMPD_parallel: 3487 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 3488 EndLoc); 3489 AllowedNameModifiers.push_back(OMPD_parallel); 3490 break; 3491 case OMPD_simd: 3492 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3493 VarsWithInheritedDSA); 3494 break; 3495 case OMPD_for: 3496 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3497 VarsWithInheritedDSA); 3498 break; 3499 case OMPD_for_simd: 3500 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3501 EndLoc, VarsWithInheritedDSA); 3502 break; 3503 case OMPD_sections: 3504 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 3505 EndLoc); 3506 break; 3507 case OMPD_section: 3508 assert(ClausesWithImplicit.empty() && 3509 "No clauses are allowed for 'omp section' directive"); 3510 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 3511 break; 3512 case OMPD_single: 3513 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 3514 EndLoc); 3515 break; 3516 case OMPD_master: 3517 assert(ClausesWithImplicit.empty() && 3518 "No clauses are allowed for 'omp master' directive"); 3519 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 3520 break; 3521 case OMPD_critical: 3522 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 3523 StartLoc, EndLoc); 3524 break; 3525 case OMPD_parallel_for: 3526 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 3527 EndLoc, VarsWithInheritedDSA); 3528 AllowedNameModifiers.push_back(OMPD_parallel); 3529 break; 3530 case OMPD_parallel_for_simd: 3531 Res = ActOnOpenMPParallelForSimdDirective( 3532 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3533 AllowedNameModifiers.push_back(OMPD_parallel); 3534 break; 3535 case OMPD_parallel_sections: 3536 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 3537 StartLoc, EndLoc); 3538 AllowedNameModifiers.push_back(OMPD_parallel); 3539 break; 3540 case OMPD_task: 3541 Res = 3542 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3543 AllowedNameModifiers.push_back(OMPD_task); 3544 break; 3545 case OMPD_taskyield: 3546 assert(ClausesWithImplicit.empty() && 3547 "No clauses are allowed for 'omp taskyield' directive"); 3548 assert(AStmt == nullptr && 3549 "No associated statement allowed for 'omp taskyield' directive"); 3550 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 3551 break; 3552 case OMPD_barrier: 3553 assert(ClausesWithImplicit.empty() && 3554 "No clauses are allowed for 'omp barrier' directive"); 3555 assert(AStmt == nullptr && 3556 "No associated statement allowed for 'omp barrier' directive"); 3557 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 3558 break; 3559 case OMPD_taskwait: 3560 assert(ClausesWithImplicit.empty() && 3561 "No clauses are allowed for 'omp taskwait' directive"); 3562 assert(AStmt == nullptr && 3563 "No associated statement allowed for 'omp taskwait' directive"); 3564 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 3565 break; 3566 case OMPD_taskgroup: 3567 assert(ClausesWithImplicit.empty() && 3568 "No clauses are allowed for 'omp taskgroup' directive"); 3569 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc); 3570 break; 3571 case OMPD_flush: 3572 assert(AStmt == nullptr && 3573 "No associated statement allowed for 'omp flush' directive"); 3574 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 3575 break; 3576 case OMPD_ordered: 3577 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 3578 EndLoc); 3579 break; 3580 case OMPD_atomic: 3581 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 3582 EndLoc); 3583 break; 3584 case OMPD_teams: 3585 Res = 3586 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3587 break; 3588 case OMPD_target: 3589 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 3590 EndLoc); 3591 AllowedNameModifiers.push_back(OMPD_target); 3592 break; 3593 case OMPD_target_parallel: 3594 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 3595 StartLoc, EndLoc); 3596 AllowedNameModifiers.push_back(OMPD_target); 3597 AllowedNameModifiers.push_back(OMPD_parallel); 3598 break; 3599 case OMPD_target_parallel_for: 3600 Res = ActOnOpenMPTargetParallelForDirective( 3601 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3602 AllowedNameModifiers.push_back(OMPD_target); 3603 AllowedNameModifiers.push_back(OMPD_parallel); 3604 break; 3605 case OMPD_cancellation_point: 3606 assert(ClausesWithImplicit.empty() && 3607 "No clauses are allowed for 'omp cancellation point' directive"); 3608 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 3609 "cancellation point' directive"); 3610 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 3611 break; 3612 case OMPD_cancel: 3613 assert(AStmt == nullptr && 3614 "No associated statement allowed for 'omp cancel' directive"); 3615 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 3616 CancelRegion); 3617 AllowedNameModifiers.push_back(OMPD_cancel); 3618 break; 3619 case OMPD_target_data: 3620 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 3621 EndLoc); 3622 AllowedNameModifiers.push_back(OMPD_target_data); 3623 break; 3624 case OMPD_target_enter_data: 3625 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 3626 EndLoc); 3627 AllowedNameModifiers.push_back(OMPD_target_enter_data); 3628 break; 3629 case OMPD_target_exit_data: 3630 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 3631 EndLoc); 3632 AllowedNameModifiers.push_back(OMPD_target_exit_data); 3633 break; 3634 case OMPD_taskloop: 3635 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 3636 EndLoc, VarsWithInheritedDSA); 3637 AllowedNameModifiers.push_back(OMPD_taskloop); 3638 break; 3639 case OMPD_taskloop_simd: 3640 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3641 EndLoc, VarsWithInheritedDSA); 3642 AllowedNameModifiers.push_back(OMPD_taskloop); 3643 break; 3644 case OMPD_distribute: 3645 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 3646 EndLoc, VarsWithInheritedDSA); 3647 break; 3648 case OMPD_target_update: 3649 assert(!AStmt && "Statement is not allowed for target update"); 3650 Res = 3651 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); 3652 AllowedNameModifiers.push_back(OMPD_target_update); 3653 break; 3654 case OMPD_distribute_parallel_for: 3655 Res = ActOnOpenMPDistributeParallelForDirective( 3656 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3657 AllowedNameModifiers.push_back(OMPD_parallel); 3658 break; 3659 case OMPD_distribute_parallel_for_simd: 3660 Res = ActOnOpenMPDistributeParallelForSimdDirective( 3661 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3662 AllowedNameModifiers.push_back(OMPD_parallel); 3663 break; 3664 case OMPD_distribute_simd: 3665 Res = ActOnOpenMPDistributeSimdDirective( 3666 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3667 break; 3668 case OMPD_target_parallel_for_simd: 3669 Res = ActOnOpenMPTargetParallelForSimdDirective( 3670 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3671 AllowedNameModifiers.push_back(OMPD_target); 3672 AllowedNameModifiers.push_back(OMPD_parallel); 3673 break; 3674 case OMPD_target_simd: 3675 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3676 EndLoc, VarsWithInheritedDSA); 3677 AllowedNameModifiers.push_back(OMPD_target); 3678 break; 3679 case OMPD_declare_target: 3680 case OMPD_end_declare_target: 3681 case OMPD_threadprivate: 3682 case OMPD_declare_reduction: 3683 case OMPD_declare_simd: 3684 llvm_unreachable("OpenMP Directive is not allowed"); 3685 case OMPD_unknown: 3686 llvm_unreachable("Unknown OpenMP directive"); 3687 } 3688 3689 for (auto P : VarsWithInheritedDSA) { 3690 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 3691 << P.first << P.second->getSourceRange(); 3692 } 3693 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 3694 3695 if (!AllowedNameModifiers.empty()) 3696 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 3697 ErrorFound; 3698 3699 if (ErrorFound) 3700 return StmtError(); 3701 return Res; 3702 } 3703 3704 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 3705 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 3706 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 3707 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 3708 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 3709 assert(Aligneds.size() == Alignments.size()); 3710 assert(Linears.size() == LinModifiers.size()); 3711 assert(Linears.size() == Steps.size()); 3712 if (!DG || DG.get().isNull()) 3713 return DeclGroupPtrTy(); 3714 3715 if (!DG.get().isSingleDecl()) { 3716 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 3717 return DG; 3718 } 3719 auto *ADecl = DG.get().getSingleDecl(); 3720 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 3721 ADecl = FTD->getTemplatedDecl(); 3722 3723 auto *FD = dyn_cast<FunctionDecl>(ADecl); 3724 if (!FD) { 3725 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 3726 return DeclGroupPtrTy(); 3727 } 3728 3729 // OpenMP [2.8.2, declare simd construct, Description] 3730 // The parameter of the simdlen clause must be a constant positive integer 3731 // expression. 3732 ExprResult SL; 3733 if (Simdlen) 3734 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 3735 // OpenMP [2.8.2, declare simd construct, Description] 3736 // The special this pointer can be used as if was one of the arguments to the 3737 // function in any of the linear, aligned, or uniform clauses. 3738 // The uniform clause declares one or more arguments to have an invariant 3739 // value for all concurrent invocations of the function in the execution of a 3740 // single SIMD loop. 3741 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 3742 Expr *UniformedLinearThis = nullptr; 3743 for (auto *E : Uniforms) { 3744 E = E->IgnoreParenImpCasts(); 3745 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3746 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 3747 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3748 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3749 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 3750 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 3751 continue; 3752 } 3753 if (isa<CXXThisExpr>(E)) { 3754 UniformedLinearThis = E; 3755 continue; 3756 } 3757 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3758 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3759 } 3760 // OpenMP [2.8.2, declare simd construct, Description] 3761 // The aligned clause declares that the object to which each list item points 3762 // is aligned to the number of bytes expressed in the optional parameter of 3763 // the aligned clause. 3764 // The special this pointer can be used as if was one of the arguments to the 3765 // function in any of the linear, aligned, or uniform clauses. 3766 // The type of list items appearing in the aligned clause must be array, 3767 // pointer, reference to array, or reference to pointer. 3768 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 3769 Expr *AlignedThis = nullptr; 3770 for (auto *E : Aligneds) { 3771 E = E->IgnoreParenImpCasts(); 3772 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3773 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3774 auto *CanonPVD = PVD->getCanonicalDecl(); 3775 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3776 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3777 ->getCanonicalDecl() == CanonPVD) { 3778 // OpenMP [2.8.1, simd construct, Restrictions] 3779 // A list-item cannot appear in more than one aligned clause. 3780 if (AlignedArgs.count(CanonPVD) > 0) { 3781 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3782 << 1 << E->getSourceRange(); 3783 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 3784 diag::note_omp_explicit_dsa) 3785 << getOpenMPClauseName(OMPC_aligned); 3786 continue; 3787 } 3788 AlignedArgs[CanonPVD] = E; 3789 QualType QTy = PVD->getType() 3790 .getNonReferenceType() 3791 .getUnqualifiedType() 3792 .getCanonicalType(); 3793 const Type *Ty = QTy.getTypePtrOrNull(); 3794 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 3795 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 3796 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 3797 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 3798 } 3799 continue; 3800 } 3801 } 3802 if (isa<CXXThisExpr>(E)) { 3803 if (AlignedThis) { 3804 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3805 << 2 << E->getSourceRange(); 3806 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 3807 << getOpenMPClauseName(OMPC_aligned); 3808 } 3809 AlignedThis = E; 3810 continue; 3811 } 3812 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3813 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3814 } 3815 // The optional parameter of the aligned clause, alignment, must be a constant 3816 // positive integer expression. If no optional parameter is specified, 3817 // implementation-defined default alignments for SIMD instructions on the 3818 // target platforms are assumed. 3819 SmallVector<Expr *, 4> NewAligns; 3820 for (auto *E : Alignments) { 3821 ExprResult Align; 3822 if (E) 3823 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 3824 NewAligns.push_back(Align.get()); 3825 } 3826 // OpenMP [2.8.2, declare simd construct, Description] 3827 // The linear clause declares one or more list items to be private to a SIMD 3828 // lane and to have a linear relationship with respect to the iteration space 3829 // of a loop. 3830 // The special this pointer can be used as if was one of the arguments to the 3831 // function in any of the linear, aligned, or uniform clauses. 3832 // When a linear-step expression is specified in a linear clause it must be 3833 // either a constant integer expression or an integer-typed parameter that is 3834 // specified in a uniform clause on the directive. 3835 llvm::DenseMap<Decl *, Expr *> LinearArgs; 3836 const bool IsUniformedThis = UniformedLinearThis != nullptr; 3837 auto MI = LinModifiers.begin(); 3838 for (auto *E : Linears) { 3839 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 3840 ++MI; 3841 E = E->IgnoreParenImpCasts(); 3842 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3843 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3844 auto *CanonPVD = PVD->getCanonicalDecl(); 3845 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3846 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3847 ->getCanonicalDecl() == CanonPVD) { 3848 // OpenMP [2.15.3.7, linear Clause, Restrictions] 3849 // A list-item cannot appear in more than one linear clause. 3850 if (LinearArgs.count(CanonPVD) > 0) { 3851 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3852 << getOpenMPClauseName(OMPC_linear) 3853 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 3854 Diag(LinearArgs[CanonPVD]->getExprLoc(), 3855 diag::note_omp_explicit_dsa) 3856 << getOpenMPClauseName(OMPC_linear); 3857 continue; 3858 } 3859 // Each argument can appear in at most one uniform or linear clause. 3860 if (UniformedArgs.count(CanonPVD) > 0) { 3861 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3862 << getOpenMPClauseName(OMPC_linear) 3863 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 3864 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 3865 diag::note_omp_explicit_dsa) 3866 << getOpenMPClauseName(OMPC_uniform); 3867 continue; 3868 } 3869 LinearArgs[CanonPVD] = E; 3870 if (E->isValueDependent() || E->isTypeDependent() || 3871 E->isInstantiationDependent() || 3872 E->containsUnexpandedParameterPack()) 3873 continue; 3874 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 3875 PVD->getOriginalType()); 3876 continue; 3877 } 3878 } 3879 if (isa<CXXThisExpr>(E)) { 3880 if (UniformedLinearThis) { 3881 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3882 << getOpenMPClauseName(OMPC_linear) 3883 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 3884 << E->getSourceRange(); 3885 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 3886 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 3887 : OMPC_linear); 3888 continue; 3889 } 3890 UniformedLinearThis = E; 3891 if (E->isValueDependent() || E->isTypeDependent() || 3892 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3893 continue; 3894 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 3895 E->getType()); 3896 continue; 3897 } 3898 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3899 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3900 } 3901 Expr *Step = nullptr; 3902 Expr *NewStep = nullptr; 3903 SmallVector<Expr *, 4> NewSteps; 3904 for (auto *E : Steps) { 3905 // Skip the same step expression, it was checked already. 3906 if (Step == E || !E) { 3907 NewSteps.push_back(E ? NewStep : nullptr); 3908 continue; 3909 } 3910 Step = E; 3911 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 3912 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3913 auto *CanonPVD = PVD->getCanonicalDecl(); 3914 if (UniformedArgs.count(CanonPVD) == 0) { 3915 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 3916 << Step->getSourceRange(); 3917 } else if (E->isValueDependent() || E->isTypeDependent() || 3918 E->isInstantiationDependent() || 3919 E->containsUnexpandedParameterPack() || 3920 CanonPVD->getType()->hasIntegerRepresentation()) 3921 NewSteps.push_back(Step); 3922 else { 3923 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 3924 << Step->getSourceRange(); 3925 } 3926 continue; 3927 } 3928 NewStep = Step; 3929 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 3930 !Step->isInstantiationDependent() && 3931 !Step->containsUnexpandedParameterPack()) { 3932 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 3933 .get(); 3934 if (NewStep) 3935 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 3936 } 3937 NewSteps.push_back(NewStep); 3938 } 3939 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 3940 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 3941 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 3942 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 3943 const_cast<Expr **>(Linears.data()), Linears.size(), 3944 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 3945 NewSteps.data(), NewSteps.size(), SR); 3946 ADecl->addAttr(NewAttr); 3947 return ConvertDeclToDeclGroup(ADecl); 3948 } 3949 3950 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 3951 Stmt *AStmt, 3952 SourceLocation StartLoc, 3953 SourceLocation EndLoc) { 3954 if (!AStmt) 3955 return StmtError(); 3956 3957 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3958 // 1.2.2 OpenMP Language Terminology 3959 // Structured block - An executable statement with a single entry at the 3960 // top and a single exit at the bottom. 3961 // The point of exit cannot be a branch out of the structured block. 3962 // longjmp() and throw() must not violate the entry/exit criteria. 3963 CS->getCapturedDecl()->setNothrow(); 3964 3965 getCurFunction()->setHasBranchProtectedScope(); 3966 3967 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 3968 DSAStack->isCancelRegion()); 3969 } 3970 3971 namespace { 3972 /// \brief Helper class for checking canonical form of the OpenMP loops and 3973 /// extracting iteration space of each loop in the loop nest, that will be used 3974 /// for IR generation. 3975 class OpenMPIterationSpaceChecker { 3976 /// \brief Reference to Sema. 3977 Sema &SemaRef; 3978 /// \brief A location for diagnostics (when there is no some better location). 3979 SourceLocation DefaultLoc; 3980 /// \brief A location for diagnostics (when increment is not compatible). 3981 SourceLocation ConditionLoc; 3982 /// \brief A source location for referring to loop init later. 3983 SourceRange InitSrcRange; 3984 /// \brief A source location for referring to condition later. 3985 SourceRange ConditionSrcRange; 3986 /// \brief A source location for referring to increment later. 3987 SourceRange IncrementSrcRange; 3988 /// \brief Loop variable. 3989 ValueDecl *LCDecl = nullptr; 3990 /// \brief Reference to loop variable. 3991 Expr *LCRef = nullptr; 3992 /// \brief Lower bound (initializer for the var). 3993 Expr *LB = nullptr; 3994 /// \brief Upper bound. 3995 Expr *UB = nullptr; 3996 /// \brief Loop step (increment). 3997 Expr *Step = nullptr; 3998 /// \brief This flag is true when condition is one of: 3999 /// Var < UB 4000 /// Var <= UB 4001 /// UB > Var 4002 /// UB >= Var 4003 bool TestIsLessOp = false; 4004 /// \brief This flag is true when condition is strict ( < or > ). 4005 bool TestIsStrictOp = false; 4006 /// \brief This flag is true when step is subtracted on each iteration. 4007 bool SubtractStep = false; 4008 4009 public: 4010 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 4011 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 4012 /// \brief Check init-expr for canonical loop form and save loop counter 4013 /// variable - #Var and its initialization value - #LB. 4014 bool CheckInit(Stmt *S, bool EmitDiags = true); 4015 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 4016 /// for less/greater and for strict/non-strict comparison. 4017 bool CheckCond(Expr *S); 4018 /// \brief Check incr-expr for canonical loop form and return true if it 4019 /// does not conform, otherwise save loop step (#Step). 4020 bool CheckInc(Expr *S); 4021 /// \brief Return the loop counter variable. 4022 ValueDecl *GetLoopDecl() const { return LCDecl; } 4023 /// \brief Return the reference expression to loop counter variable. 4024 Expr *GetLoopDeclRefExpr() const { return LCRef; } 4025 /// \brief Source range of the loop init. 4026 SourceRange GetInitSrcRange() const { return InitSrcRange; } 4027 /// \brief Source range of the loop condition. 4028 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 4029 /// \brief Source range of the loop increment. 4030 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 4031 /// \brief True if the step should be subtracted. 4032 bool ShouldSubtractStep() const { return SubtractStep; } 4033 /// \brief Build the expression to calculate the number of iterations. 4034 Expr * 4035 BuildNumIterations(Scope *S, const bool LimitedType, 4036 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 4037 /// \brief Build the precondition expression for the loops. 4038 Expr *BuildPreCond(Scope *S, Expr *Cond, 4039 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 4040 /// \brief Build reference expression to the counter be used for codegen. 4041 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 4042 DSAStackTy &DSA) const; 4043 /// \brief Build reference expression to the private counter be used for 4044 /// codegen. 4045 Expr *BuildPrivateCounterVar() const; 4046 /// \brief Build initization of the counter be used for codegen. 4047 Expr *BuildCounterInit() const; 4048 /// \brief Build step of the counter be used for codegen. 4049 Expr *BuildCounterStep() const; 4050 /// \brief Return true if any expression is dependent. 4051 bool Dependent() const; 4052 4053 private: 4054 /// \brief Check the right-hand side of an assignment in the increment 4055 /// expression. 4056 bool CheckIncRHS(Expr *RHS); 4057 /// \brief Helper to set loop counter variable and its initializer. 4058 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 4059 /// \brief Helper to set upper bound. 4060 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 4061 SourceLocation SL); 4062 /// \brief Helper to set loop increment. 4063 bool SetStep(Expr *NewStep, bool Subtract); 4064 }; 4065 4066 bool OpenMPIterationSpaceChecker::Dependent() const { 4067 if (!LCDecl) { 4068 assert(!LB && !UB && !Step); 4069 return false; 4070 } 4071 return LCDecl->getType()->isDependentType() || 4072 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 4073 (Step && Step->isValueDependent()); 4074 } 4075 4076 static Expr *getExprAsWritten(Expr *E) { 4077 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 4078 E = ExprTemp->getSubExpr(); 4079 4080 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 4081 E = MTE->GetTemporaryExpr(); 4082 4083 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 4084 E = Binder->getSubExpr(); 4085 4086 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 4087 E = ICE->getSubExprAsWritten(); 4088 return E->IgnoreParens(); 4089 } 4090 4091 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 4092 Expr *NewLCRefExpr, 4093 Expr *NewLB) { 4094 // State consistency checking to ensure correct usage. 4095 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 4096 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 4097 if (!NewLCDecl || !NewLB) 4098 return true; 4099 LCDecl = getCanonicalDecl(NewLCDecl); 4100 LCRef = NewLCRefExpr; 4101 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 4102 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 4103 if ((Ctor->isCopyOrMoveConstructor() || 4104 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 4105 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 4106 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 4107 LB = NewLB; 4108 return false; 4109 } 4110 4111 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 4112 SourceRange SR, SourceLocation SL) { 4113 // State consistency checking to ensure correct usage. 4114 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 4115 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 4116 if (!NewUB) 4117 return true; 4118 UB = NewUB; 4119 TestIsLessOp = LessOp; 4120 TestIsStrictOp = StrictOp; 4121 ConditionSrcRange = SR; 4122 ConditionLoc = SL; 4123 return false; 4124 } 4125 4126 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 4127 // State consistency checking to ensure correct usage. 4128 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 4129 if (!NewStep) 4130 return true; 4131 if (!NewStep->isValueDependent()) { 4132 // Check that the step is integer expression. 4133 SourceLocation StepLoc = NewStep->getLocStart(); 4134 ExprResult Val = 4135 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep); 4136 if (Val.isInvalid()) 4137 return true; 4138 NewStep = Val.get(); 4139 4140 // OpenMP [2.6, Canonical Loop Form, Restrictions] 4141 // If test-expr is of form var relational-op b and relational-op is < or 4142 // <= then incr-expr must cause var to increase on each iteration of the 4143 // loop. If test-expr is of form var relational-op b and relational-op is 4144 // > or >= then incr-expr must cause var to decrease on each iteration of 4145 // the loop. 4146 // If test-expr is of form b relational-op var and relational-op is < or 4147 // <= then incr-expr must cause var to decrease on each iteration of the 4148 // loop. If test-expr is of form b relational-op var and relational-op is 4149 // > or >= then incr-expr must cause var to increase on each iteration of 4150 // the loop. 4151 llvm::APSInt Result; 4152 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 4153 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 4154 bool IsConstNeg = 4155 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 4156 bool IsConstPos = 4157 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 4158 bool IsConstZero = IsConstant && !Result.getBoolValue(); 4159 if (UB && (IsConstZero || 4160 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 4161 : (IsConstPos || (IsUnsigned && !Subtract))))) { 4162 SemaRef.Diag(NewStep->getExprLoc(), 4163 diag::err_omp_loop_incr_not_compatible) 4164 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 4165 SemaRef.Diag(ConditionLoc, 4166 diag::note_omp_loop_cond_requres_compatible_incr) 4167 << TestIsLessOp << ConditionSrcRange; 4168 return true; 4169 } 4170 if (TestIsLessOp == Subtract) { 4171 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, 4172 NewStep).get(); 4173 Subtract = !Subtract; 4174 } 4175 } 4176 4177 Step = NewStep; 4178 SubtractStep = Subtract; 4179 return false; 4180 } 4181 4182 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 4183 // Check init-expr for canonical loop form and save loop counter 4184 // variable - #Var and its initialization value - #LB. 4185 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 4186 // var = lb 4187 // integer-type var = lb 4188 // random-access-iterator-type var = lb 4189 // pointer-type var = lb 4190 // 4191 if (!S) { 4192 if (EmitDiags) { 4193 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 4194 } 4195 return true; 4196 } 4197 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 4198 if (!ExprTemp->cleanupsHaveSideEffects()) 4199 S = ExprTemp->getSubExpr(); 4200 4201 InitSrcRange = S->getSourceRange(); 4202 if (Expr *E = dyn_cast<Expr>(S)) 4203 S = E->IgnoreParens(); 4204 if (auto BO = dyn_cast<BinaryOperator>(S)) { 4205 if (BO->getOpcode() == BO_Assign) { 4206 auto *LHS = BO->getLHS()->IgnoreParens(); 4207 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 4208 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 4209 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4210 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4211 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 4212 } 4213 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 4214 if (ME->isArrow() && 4215 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4216 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4217 } 4218 } 4219 } else if (auto DS = dyn_cast<DeclStmt>(S)) { 4220 if (DS->isSingleDecl()) { 4221 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 4222 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 4223 // Accept non-canonical init form here but emit ext. warning. 4224 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 4225 SemaRef.Diag(S->getLocStart(), 4226 diag::ext_omp_loop_not_canonical_init) 4227 << S->getSourceRange(); 4228 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 4229 } 4230 } 4231 } 4232 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4233 if (CE->getOperator() == OO_Equal) { 4234 auto *LHS = CE->getArg(0); 4235 if (auto DRE = dyn_cast<DeclRefExpr>(LHS)) { 4236 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 4237 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4238 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4239 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 4240 } 4241 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 4242 if (ME->isArrow() && 4243 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4244 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4245 } 4246 } 4247 } 4248 4249 if (Dependent() || SemaRef.CurContext->isDependentContext()) 4250 return false; 4251 if (EmitDiags) { 4252 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 4253 << S->getSourceRange(); 4254 } 4255 return true; 4256 } 4257 4258 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 4259 /// variable (which may be the loop variable) if possible. 4260 static const ValueDecl *GetInitLCDecl(Expr *E) { 4261 if (!E) 4262 return nullptr; 4263 E = getExprAsWritten(E); 4264 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 4265 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 4266 if ((Ctor->isCopyOrMoveConstructor() || 4267 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 4268 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 4269 E = CE->getArg(0)->IgnoreParenImpCasts(); 4270 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 4271 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 4272 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 4273 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4274 return getCanonicalDecl(ME->getMemberDecl()); 4275 return getCanonicalDecl(VD); 4276 } 4277 } 4278 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 4279 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4280 return getCanonicalDecl(ME->getMemberDecl()); 4281 return nullptr; 4282 } 4283 4284 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 4285 // Check test-expr for canonical form, save upper-bound UB, flags for 4286 // less/greater and for strict/non-strict comparison. 4287 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 4288 // var relational-op b 4289 // b relational-op var 4290 // 4291 if (!S) { 4292 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 4293 return true; 4294 } 4295 S = getExprAsWritten(S); 4296 SourceLocation CondLoc = S->getLocStart(); 4297 if (auto BO = dyn_cast<BinaryOperator>(S)) { 4298 if (BO->isRelationalOp()) { 4299 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 4300 return SetUB(BO->getRHS(), 4301 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 4302 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 4303 BO->getSourceRange(), BO->getOperatorLoc()); 4304 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 4305 return SetUB(BO->getLHS(), 4306 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 4307 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 4308 BO->getSourceRange(), BO->getOperatorLoc()); 4309 } 4310 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4311 if (CE->getNumArgs() == 2) { 4312 auto Op = CE->getOperator(); 4313 switch (Op) { 4314 case OO_Greater: 4315 case OO_GreaterEqual: 4316 case OO_Less: 4317 case OO_LessEqual: 4318 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4319 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 4320 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 4321 CE->getOperatorLoc()); 4322 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 4323 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 4324 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 4325 CE->getOperatorLoc()); 4326 break; 4327 default: 4328 break; 4329 } 4330 } 4331 } 4332 if (Dependent() || SemaRef.CurContext->isDependentContext()) 4333 return false; 4334 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 4335 << S->getSourceRange() << LCDecl; 4336 return true; 4337 } 4338 4339 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 4340 // RHS of canonical loop form increment can be: 4341 // var + incr 4342 // incr + var 4343 // var - incr 4344 // 4345 RHS = RHS->IgnoreParenImpCasts(); 4346 if (auto BO = dyn_cast<BinaryOperator>(RHS)) { 4347 if (BO->isAdditiveOp()) { 4348 bool IsAdd = BO->getOpcode() == BO_Add; 4349 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 4350 return SetStep(BO->getRHS(), !IsAdd); 4351 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 4352 return SetStep(BO->getLHS(), false); 4353 } 4354 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 4355 bool IsAdd = CE->getOperator() == OO_Plus; 4356 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 4357 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4358 return SetStep(CE->getArg(1), !IsAdd); 4359 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 4360 return SetStep(CE->getArg(0), false); 4361 } 4362 } 4363 if (Dependent() || SemaRef.CurContext->isDependentContext()) 4364 return false; 4365 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 4366 << RHS->getSourceRange() << LCDecl; 4367 return true; 4368 } 4369 4370 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 4371 // Check incr-expr for canonical loop form and return true if it 4372 // does not conform. 4373 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 4374 // ++var 4375 // var++ 4376 // --var 4377 // var-- 4378 // var += incr 4379 // var -= incr 4380 // var = var + incr 4381 // var = incr + var 4382 // var = var - incr 4383 // 4384 if (!S) { 4385 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 4386 return true; 4387 } 4388 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 4389 if (!ExprTemp->cleanupsHaveSideEffects()) 4390 S = ExprTemp->getSubExpr(); 4391 4392 IncrementSrcRange = S->getSourceRange(); 4393 S = S->IgnoreParens(); 4394 if (auto UO = dyn_cast<UnaryOperator>(S)) { 4395 if (UO->isIncrementDecrementOp() && 4396 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 4397 return SetStep( 4398 SemaRef.ActOnIntegerConstant(UO->getLocStart(), 4399 (UO->isDecrementOp() ? -1 : 1)).get(), 4400 false); 4401 } else if (auto BO = dyn_cast<BinaryOperator>(S)) { 4402 switch (BO->getOpcode()) { 4403 case BO_AddAssign: 4404 case BO_SubAssign: 4405 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 4406 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 4407 break; 4408 case BO_Assign: 4409 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 4410 return CheckIncRHS(BO->getRHS()); 4411 break; 4412 default: 4413 break; 4414 } 4415 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4416 switch (CE->getOperator()) { 4417 case OO_PlusPlus: 4418 case OO_MinusMinus: 4419 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4420 return SetStep( 4421 SemaRef.ActOnIntegerConstant( 4422 CE->getLocStart(), 4423 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(), 4424 false); 4425 break; 4426 case OO_PlusEqual: 4427 case OO_MinusEqual: 4428 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4429 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 4430 break; 4431 case OO_Equal: 4432 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4433 return CheckIncRHS(CE->getArg(1)); 4434 break; 4435 default: 4436 break; 4437 } 4438 } 4439 if (Dependent() || SemaRef.CurContext->isDependentContext()) 4440 return false; 4441 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 4442 << S->getSourceRange() << LCDecl; 4443 return true; 4444 } 4445 4446 static ExprResult 4447 tryBuildCapture(Sema &SemaRef, Expr *Capture, 4448 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4449 if (SemaRef.CurContext->isDependentContext()) 4450 return ExprResult(Capture); 4451 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 4452 return SemaRef.PerformImplicitConversion( 4453 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 4454 /*AllowExplicit=*/true); 4455 auto I = Captures.find(Capture); 4456 if (I != Captures.end()) 4457 return buildCapture(SemaRef, Capture, I->second); 4458 DeclRefExpr *Ref = nullptr; 4459 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 4460 Captures[Capture] = Ref; 4461 return Res; 4462 } 4463 4464 /// \brief Build the expression to calculate the number of iterations. 4465 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 4466 Scope *S, const bool LimitedType, 4467 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 4468 ExprResult Diff; 4469 auto VarType = LCDecl->getType().getNonReferenceType(); 4470 if (VarType->isIntegerType() || VarType->isPointerType() || 4471 SemaRef.getLangOpts().CPlusPlus) { 4472 // Upper - Lower 4473 auto *UBExpr = TestIsLessOp ? UB : LB; 4474 auto *LBExpr = TestIsLessOp ? LB : UB; 4475 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 4476 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 4477 if (!Upper || !Lower) 4478 return nullptr; 4479 4480 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 4481 4482 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 4483 // BuildBinOp already emitted error, this one is to point user to upper 4484 // and lower bound, and to tell what is passed to 'operator-'. 4485 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 4486 << Upper->getSourceRange() << Lower->getSourceRange(); 4487 return nullptr; 4488 } 4489 } 4490 4491 if (!Diff.isUsable()) 4492 return nullptr; 4493 4494 // Upper - Lower [- 1] 4495 if (TestIsStrictOp) 4496 Diff = SemaRef.BuildBinOp( 4497 S, DefaultLoc, BO_Sub, Diff.get(), 4498 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4499 if (!Diff.isUsable()) 4500 return nullptr; 4501 4502 // Upper - Lower [- 1] + Step 4503 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 4504 if (!NewStep.isUsable()) 4505 return nullptr; 4506 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 4507 if (!Diff.isUsable()) 4508 return nullptr; 4509 4510 // Parentheses (for dumping/debugging purposes only). 4511 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 4512 if (!Diff.isUsable()) 4513 return nullptr; 4514 4515 // (Upper - Lower [- 1] + Step) / Step 4516 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 4517 if (!Diff.isUsable()) 4518 return nullptr; 4519 4520 // OpenMP runtime requires 32-bit or 64-bit loop variables. 4521 QualType Type = Diff.get()->getType(); 4522 auto &C = SemaRef.Context; 4523 bool UseVarType = VarType->hasIntegerRepresentation() && 4524 C.getTypeSize(Type) > C.getTypeSize(VarType); 4525 if (!Type->isIntegerType() || UseVarType) { 4526 unsigned NewSize = 4527 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 4528 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 4529 : Type->hasSignedIntegerRepresentation(); 4530 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 4531 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 4532 Diff = SemaRef.PerformImplicitConversion( 4533 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 4534 if (!Diff.isUsable()) 4535 return nullptr; 4536 } 4537 } 4538 if (LimitedType) { 4539 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 4540 if (NewSize != C.getTypeSize(Type)) { 4541 if (NewSize < C.getTypeSize(Type)) { 4542 assert(NewSize == 64 && "incorrect loop var size"); 4543 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 4544 << InitSrcRange << ConditionSrcRange; 4545 } 4546 QualType NewType = C.getIntTypeForBitwidth( 4547 NewSize, Type->hasSignedIntegerRepresentation() || 4548 C.getTypeSize(Type) < NewSize); 4549 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 4550 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 4551 Sema::AA_Converting, true); 4552 if (!Diff.isUsable()) 4553 return nullptr; 4554 } 4555 } 4556 } 4557 4558 return Diff.get(); 4559 } 4560 4561 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 4562 Scope *S, Expr *Cond, 4563 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 4564 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 4565 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4566 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4567 4568 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 4569 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 4570 if (!NewLB.isUsable() || !NewUB.isUsable()) 4571 return nullptr; 4572 4573 auto CondExpr = SemaRef.BuildBinOp( 4574 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 4575 : (TestIsStrictOp ? BO_GT : BO_GE), 4576 NewLB.get(), NewUB.get()); 4577 if (CondExpr.isUsable()) { 4578 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 4579 SemaRef.Context.BoolTy)) 4580 CondExpr = SemaRef.PerformImplicitConversion( 4581 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 4582 /*AllowExplicit=*/true); 4583 } 4584 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4585 // Otherwise use original loop conditon and evaluate it in runtime. 4586 return CondExpr.isUsable() ? CondExpr.get() : Cond; 4587 } 4588 4589 /// \brief Build reference expression to the counter be used for codegen. 4590 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 4591 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 4592 auto *VD = dyn_cast<VarDecl>(LCDecl); 4593 if (!VD) { 4594 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 4595 auto *Ref = buildDeclRefExpr( 4596 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 4597 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 4598 // If the loop control decl is explicitly marked as private, do not mark it 4599 // as captured again. 4600 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 4601 Captures.insert(std::make_pair(LCRef, Ref)); 4602 return Ref; 4603 } 4604 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 4605 DefaultLoc); 4606 } 4607 4608 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 4609 if (LCDecl && !LCDecl->isInvalidDecl()) { 4610 auto Type = LCDecl->getType().getNonReferenceType(); 4611 auto *PrivateVar = 4612 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 4613 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 4614 if (PrivateVar->isInvalidDecl()) 4615 return nullptr; 4616 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 4617 } 4618 return nullptr; 4619 } 4620 4621 /// \brief Build initization of the counter be used for codegen. 4622 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 4623 4624 /// \brief Build step of the counter be used for codegen. 4625 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 4626 4627 /// \brief Iteration space of a single for loop. 4628 struct LoopIterationSpace final { 4629 /// \brief Condition of the loop. 4630 Expr *PreCond = nullptr; 4631 /// \brief This expression calculates the number of iterations in the loop. 4632 /// It is always possible to calculate it before starting the loop. 4633 Expr *NumIterations = nullptr; 4634 /// \brief The loop counter variable. 4635 Expr *CounterVar = nullptr; 4636 /// \brief Private loop counter variable. 4637 Expr *PrivateCounterVar = nullptr; 4638 /// \brief This is initializer for the initial value of #CounterVar. 4639 Expr *CounterInit = nullptr; 4640 /// \brief This is step for the #CounterVar used to generate its update: 4641 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 4642 Expr *CounterStep = nullptr; 4643 /// \brief Should step be subtracted? 4644 bool Subtract = false; 4645 /// \brief Source range of the loop init. 4646 SourceRange InitSrcRange; 4647 /// \brief Source range of the loop condition. 4648 SourceRange CondSrcRange; 4649 /// \brief Source range of the loop increment. 4650 SourceRange IncSrcRange; 4651 }; 4652 4653 } // namespace 4654 4655 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 4656 assert(getLangOpts().OpenMP && "OpenMP is not active."); 4657 assert(Init && "Expected loop in canonical form."); 4658 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 4659 if (AssociatedLoops > 0 && 4660 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 4661 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 4662 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 4663 if (auto *D = ISC.GetLoopDecl()) { 4664 auto *VD = dyn_cast<VarDecl>(D); 4665 if (!VD) { 4666 if (auto *Private = IsOpenMPCapturedDecl(D)) 4667 VD = Private; 4668 else { 4669 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 4670 /*WithInit=*/false); 4671 VD = cast<VarDecl>(Ref->getDecl()); 4672 } 4673 } 4674 DSAStack->addLoopControlVariable(D, VD); 4675 } 4676 } 4677 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 4678 } 4679 } 4680 4681 /// \brief Called on a for stmt to check and extract its iteration space 4682 /// for further processing (such as collapsing). 4683 static bool CheckOpenMPIterationSpace( 4684 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 4685 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 4686 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 4687 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 4688 LoopIterationSpace &ResultIterSpace, 4689 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4690 // OpenMP [2.6, Canonical Loop Form] 4691 // for (init-expr; test-expr; incr-expr) structured-block 4692 auto For = dyn_cast_or_null<ForStmt>(S); 4693 if (!For) { 4694 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 4695 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 4696 << getOpenMPDirectiveName(DKind) << NestedLoopCount 4697 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 4698 if (NestedLoopCount > 1) { 4699 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 4700 SemaRef.Diag(DSA.getConstructLoc(), 4701 diag::note_omp_collapse_ordered_expr) 4702 << 2 << CollapseLoopCountExpr->getSourceRange() 4703 << OrderedLoopCountExpr->getSourceRange(); 4704 else if (CollapseLoopCountExpr) 4705 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4706 diag::note_omp_collapse_ordered_expr) 4707 << 0 << CollapseLoopCountExpr->getSourceRange(); 4708 else 4709 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4710 diag::note_omp_collapse_ordered_expr) 4711 << 1 << OrderedLoopCountExpr->getSourceRange(); 4712 } 4713 return true; 4714 } 4715 assert(For->getBody()); 4716 4717 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 4718 4719 // Check init. 4720 auto Init = For->getInit(); 4721 if (ISC.CheckInit(Init)) 4722 return true; 4723 4724 bool HasErrors = false; 4725 4726 // Check loop variable's type. 4727 if (auto *LCDecl = ISC.GetLoopDecl()) { 4728 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 4729 4730 // OpenMP [2.6, Canonical Loop Form] 4731 // Var is one of the following: 4732 // A variable of signed or unsigned integer type. 4733 // For C++, a variable of a random access iterator type. 4734 // For C, a variable of a pointer type. 4735 auto VarType = LCDecl->getType().getNonReferenceType(); 4736 if (!VarType->isDependentType() && !VarType->isIntegerType() && 4737 !VarType->isPointerType() && 4738 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 4739 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 4740 << SemaRef.getLangOpts().CPlusPlus; 4741 HasErrors = true; 4742 } 4743 4744 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 4745 // a Construct 4746 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4747 // parallel for construct is (are) private. 4748 // The loop iteration variable in the associated for-loop of a simd 4749 // construct with just one associated for-loop is linear with a 4750 // constant-linear-step that is the increment of the associated for-loop. 4751 // Exclude loop var from the list of variables with implicitly defined data 4752 // sharing attributes. 4753 VarsWithImplicitDSA.erase(LCDecl); 4754 4755 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4756 // in a Construct, C/C++]. 4757 // The loop iteration variable in the associated for-loop of a simd 4758 // construct with just one associated for-loop may be listed in a linear 4759 // clause with a constant-linear-step that is the increment of the 4760 // associated for-loop. 4761 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4762 // parallel for construct may be listed in a private or lastprivate clause. 4763 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 4764 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 4765 // declared in the loop and it is predetermined as a private. 4766 auto PredeterminedCKind = 4767 isOpenMPSimdDirective(DKind) 4768 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 4769 : OMPC_private; 4770 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4771 DVar.CKind != PredeterminedCKind) || 4772 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 4773 isOpenMPDistributeDirective(DKind)) && 4774 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4775 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 4776 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 4777 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 4778 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 4779 << getOpenMPClauseName(PredeterminedCKind); 4780 if (DVar.RefExpr == nullptr) 4781 DVar.CKind = PredeterminedCKind; 4782 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 4783 HasErrors = true; 4784 } else if (LoopDeclRefExpr != nullptr) { 4785 // Make the loop iteration variable private (for worksharing constructs), 4786 // linear (for simd directives with the only one associated loop) or 4787 // lastprivate (for simd directives with several collapsed or ordered 4788 // loops). 4789 if (DVar.CKind == OMPC_unknown) 4790 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 4791 [](OpenMPDirectiveKind) -> bool { return true; }, 4792 /*FromParent=*/false); 4793 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 4794 } 4795 4796 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 4797 4798 // Check test-expr. 4799 HasErrors |= ISC.CheckCond(For->getCond()); 4800 4801 // Check incr-expr. 4802 HasErrors |= ISC.CheckInc(For->getInc()); 4803 } 4804 4805 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 4806 return HasErrors; 4807 4808 // Build the loop's iteration space representation. 4809 ResultIterSpace.PreCond = 4810 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 4811 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 4812 DSA.getCurScope(), 4813 (isOpenMPWorksharingDirective(DKind) || 4814 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 4815 Captures); 4816 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 4817 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 4818 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 4819 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 4820 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 4821 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 4822 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 4823 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 4824 4825 HasErrors |= (ResultIterSpace.PreCond == nullptr || 4826 ResultIterSpace.NumIterations == nullptr || 4827 ResultIterSpace.CounterVar == nullptr || 4828 ResultIterSpace.PrivateCounterVar == nullptr || 4829 ResultIterSpace.CounterInit == nullptr || 4830 ResultIterSpace.CounterStep == nullptr); 4831 4832 return HasErrors; 4833 } 4834 4835 /// \brief Build 'VarRef = Start. 4836 static ExprResult 4837 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 4838 ExprResult Start, 4839 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4840 // Build 'VarRef = Start. 4841 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 4842 if (!NewStart.isUsable()) 4843 return ExprError(); 4844 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 4845 VarRef.get()->getType())) { 4846 NewStart = SemaRef.PerformImplicitConversion( 4847 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 4848 /*AllowExplicit=*/true); 4849 if (!NewStart.isUsable()) 4850 return ExprError(); 4851 } 4852 4853 auto Init = 4854 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4855 return Init; 4856 } 4857 4858 /// \brief Build 'VarRef = Start + Iter * Step'. 4859 static ExprResult 4860 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 4861 ExprResult VarRef, ExprResult Start, ExprResult Iter, 4862 ExprResult Step, bool Subtract, 4863 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 4864 // Add parentheses (for debugging purposes only). 4865 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 4866 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 4867 !Step.isUsable()) 4868 return ExprError(); 4869 4870 ExprResult NewStep = Step; 4871 if (Captures) 4872 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 4873 if (NewStep.isInvalid()) 4874 return ExprError(); 4875 ExprResult Update = 4876 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 4877 if (!Update.isUsable()) 4878 return ExprError(); 4879 4880 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 4881 // 'VarRef = Start (+|-) Iter * Step'. 4882 ExprResult NewStart = Start; 4883 if (Captures) 4884 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 4885 if (NewStart.isInvalid()) 4886 return ExprError(); 4887 4888 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 4889 ExprResult SavedUpdate = Update; 4890 ExprResult UpdateVal; 4891 if (VarRef.get()->getType()->isOverloadableType() || 4892 NewStart.get()->getType()->isOverloadableType() || 4893 Update.get()->getType()->isOverloadableType()) { 4894 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4895 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4896 Update = 4897 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4898 if (Update.isUsable()) { 4899 UpdateVal = 4900 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 4901 VarRef.get(), SavedUpdate.get()); 4902 if (UpdateVal.isUsable()) { 4903 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 4904 UpdateVal.get()); 4905 } 4906 } 4907 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4908 } 4909 4910 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 4911 if (!Update.isUsable() || !UpdateVal.isUsable()) { 4912 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 4913 NewStart.get(), SavedUpdate.get()); 4914 if (!Update.isUsable()) 4915 return ExprError(); 4916 4917 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 4918 VarRef.get()->getType())) { 4919 Update = SemaRef.PerformImplicitConversion( 4920 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 4921 if (!Update.isUsable()) 4922 return ExprError(); 4923 } 4924 4925 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 4926 } 4927 return Update; 4928 } 4929 4930 /// \brief Convert integer expression \a E to make it have at least \a Bits 4931 /// bits. 4932 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, 4933 Sema &SemaRef) { 4934 if (E == nullptr) 4935 return ExprError(); 4936 auto &C = SemaRef.Context; 4937 QualType OldType = E->getType(); 4938 unsigned HasBits = C.getTypeSize(OldType); 4939 if (HasBits >= Bits) 4940 return ExprResult(E); 4941 // OK to convert to signed, because new type has more bits than old. 4942 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 4943 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 4944 true); 4945 } 4946 4947 /// \brief Check if the given expression \a E is a constant integer that fits 4948 /// into \a Bits bits. 4949 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 4950 if (E == nullptr) 4951 return false; 4952 llvm::APSInt Result; 4953 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 4954 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 4955 return false; 4956 } 4957 4958 /// Build preinits statement for the given declarations. 4959 static Stmt *buildPreInits(ASTContext &Context, 4960 SmallVectorImpl<Decl *> &PreInits) { 4961 if (!PreInits.empty()) { 4962 return new (Context) DeclStmt( 4963 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 4964 SourceLocation(), SourceLocation()); 4965 } 4966 return nullptr; 4967 } 4968 4969 /// Build preinits statement for the given declarations. 4970 static Stmt *buildPreInits(ASTContext &Context, 4971 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4972 if (!Captures.empty()) { 4973 SmallVector<Decl *, 16> PreInits; 4974 for (auto &Pair : Captures) 4975 PreInits.push_back(Pair.second->getDecl()); 4976 return buildPreInits(Context, PreInits); 4977 } 4978 return nullptr; 4979 } 4980 4981 /// Build postupdate expression for the given list of postupdates expressions. 4982 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 4983 Expr *PostUpdate = nullptr; 4984 if (!PostUpdates.empty()) { 4985 for (auto *E : PostUpdates) { 4986 Expr *ConvE = S.BuildCStyleCastExpr( 4987 E->getExprLoc(), 4988 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 4989 E->getExprLoc(), E) 4990 .get(); 4991 PostUpdate = PostUpdate 4992 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 4993 PostUpdate, ConvE) 4994 .get() 4995 : ConvE; 4996 } 4997 } 4998 return PostUpdate; 4999 } 5000 5001 /// \brief Called on a for stmt to check itself and nested loops (if any). 5002 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 5003 /// number of collapsed loops otherwise. 5004 static unsigned 5005 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 5006 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 5007 DSAStackTy &DSA, 5008 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 5009 OMPLoopDirective::HelperExprs &Built) { 5010 unsigned NestedLoopCount = 1; 5011 if (CollapseLoopCountExpr) { 5012 // Found 'collapse' clause - calculate collapse number. 5013 llvm::APSInt Result; 5014 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 5015 NestedLoopCount = Result.getLimitedValue(); 5016 } 5017 if (OrderedLoopCountExpr) { 5018 // Found 'ordered' clause - calculate collapse number. 5019 llvm::APSInt Result; 5020 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 5021 if (Result.getLimitedValue() < NestedLoopCount) { 5022 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 5023 diag::err_omp_wrong_ordered_loop_count) 5024 << OrderedLoopCountExpr->getSourceRange(); 5025 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 5026 diag::note_collapse_loop_count) 5027 << CollapseLoopCountExpr->getSourceRange(); 5028 } 5029 NestedLoopCount = Result.getLimitedValue(); 5030 } 5031 } 5032 // This is helper routine for loop directives (e.g., 'for', 'simd', 5033 // 'for simd', etc.). 5034 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 5035 SmallVector<LoopIterationSpace, 4> IterSpaces; 5036 IterSpaces.resize(NestedLoopCount); 5037 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 5038 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 5039 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 5040 NestedLoopCount, CollapseLoopCountExpr, 5041 OrderedLoopCountExpr, VarsWithImplicitDSA, 5042 IterSpaces[Cnt], Captures)) 5043 return 0; 5044 // Move on to the next nested for loop, or to the loop body. 5045 // OpenMP [2.8.1, simd construct, Restrictions] 5046 // All loops associated with the construct must be perfectly nested; that 5047 // is, there must be no intervening code nor any OpenMP directive between 5048 // any two loops. 5049 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 5050 } 5051 5052 Built.clear(/* size */ NestedLoopCount); 5053 5054 if (SemaRef.CurContext->isDependentContext()) 5055 return NestedLoopCount; 5056 5057 // An example of what is generated for the following code: 5058 // 5059 // #pragma omp simd collapse(2) ordered(2) 5060 // for (i = 0; i < NI; ++i) 5061 // for (k = 0; k < NK; ++k) 5062 // for (j = J0; j < NJ; j+=2) { 5063 // <loop body> 5064 // } 5065 // 5066 // We generate the code below. 5067 // Note: the loop body may be outlined in CodeGen. 5068 // Note: some counters may be C++ classes, operator- is used to find number of 5069 // iterations and operator+= to calculate counter value. 5070 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 5071 // or i64 is currently supported). 5072 // 5073 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 5074 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 5075 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 5076 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 5077 // // similar updates for vars in clauses (e.g. 'linear') 5078 // <loop body (using local i and j)> 5079 // } 5080 // i = NI; // assign final values of counters 5081 // j = NJ; 5082 // 5083 5084 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 5085 // the iteration counts of the collapsed for loops. 5086 // Precondition tests if there is at least one iteration (all conditions are 5087 // true). 5088 auto PreCond = ExprResult(IterSpaces[0].PreCond); 5089 auto N0 = IterSpaces[0].NumIterations; 5090 ExprResult LastIteration32 = WidenIterationCount( 5091 32 /* Bits */, SemaRef.PerformImplicitConversion( 5092 N0->IgnoreImpCasts(), N0->getType(), 5093 Sema::AA_Converting, /*AllowExplicit=*/true) 5094 .get(), 5095 SemaRef); 5096 ExprResult LastIteration64 = WidenIterationCount( 5097 64 /* Bits */, SemaRef.PerformImplicitConversion( 5098 N0->IgnoreImpCasts(), N0->getType(), 5099 Sema::AA_Converting, /*AllowExplicit=*/true) 5100 .get(), 5101 SemaRef); 5102 5103 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 5104 return NestedLoopCount; 5105 5106 auto &C = SemaRef.Context; 5107 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 5108 5109 Scope *CurScope = DSA.getCurScope(); 5110 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 5111 if (PreCond.isUsable()) { 5112 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd, 5113 PreCond.get(), IterSpaces[Cnt].PreCond); 5114 } 5115 auto N = IterSpaces[Cnt].NumIterations; 5116 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 5117 if (LastIteration32.isUsable()) 5118 LastIteration32 = SemaRef.BuildBinOp( 5119 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(), 5120 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 5121 Sema::AA_Converting, 5122 /*AllowExplicit=*/true) 5123 .get()); 5124 if (LastIteration64.isUsable()) 5125 LastIteration64 = SemaRef.BuildBinOp( 5126 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(), 5127 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 5128 Sema::AA_Converting, 5129 /*AllowExplicit=*/true) 5130 .get()); 5131 } 5132 5133 // Choose either the 32-bit or 64-bit version. 5134 ExprResult LastIteration = LastIteration64; 5135 if (LastIteration32.isUsable() && 5136 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 5137 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 5138 FitsInto( 5139 32 /* Bits */, 5140 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 5141 LastIteration64.get(), SemaRef))) 5142 LastIteration = LastIteration32; 5143 QualType VType = LastIteration.get()->getType(); 5144 QualType RealVType = VType; 5145 QualType StrideVType = VType; 5146 if (isOpenMPTaskLoopDirective(DKind)) { 5147 VType = 5148 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 5149 StrideVType = 5150 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 5151 } 5152 5153 if (!LastIteration.isUsable()) 5154 return 0; 5155 5156 // Save the number of iterations. 5157 ExprResult NumIterations = LastIteration; 5158 { 5159 LastIteration = SemaRef.BuildBinOp( 5160 CurScope, SourceLocation(), BO_Sub, LastIteration.get(), 5161 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5162 if (!LastIteration.isUsable()) 5163 return 0; 5164 } 5165 5166 // Calculate the last iteration number beforehand instead of doing this on 5167 // each iteration. Do not do this if the number of iterations may be kfold-ed. 5168 llvm::APSInt Result; 5169 bool IsConstant = 5170 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 5171 ExprResult CalcLastIteration; 5172 if (!IsConstant) { 5173 ExprResult SaveRef = 5174 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 5175 LastIteration = SaveRef; 5176 5177 // Prepare SaveRef + 1. 5178 NumIterations = SemaRef.BuildBinOp( 5179 CurScope, SourceLocation(), BO_Add, SaveRef.get(), 5180 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5181 if (!NumIterations.isUsable()) 5182 return 0; 5183 } 5184 5185 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 5186 5187 // Build variables passed into runtime, nesessary for worksharing directives. 5188 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB; 5189 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 5190 isOpenMPDistributeDirective(DKind)) { 5191 // Lower bound variable, initialized with zero. 5192 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 5193 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 5194 SemaRef.AddInitializerToDecl( 5195 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5196 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 5197 5198 // Upper bound variable, initialized with last iteration number. 5199 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 5200 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 5201 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 5202 /*DirectInit*/ false, 5203 /*TypeMayContainAuto*/ false); 5204 5205 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 5206 // This will be used to implement clause 'lastprivate'. 5207 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 5208 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 5209 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 5210 SemaRef.AddInitializerToDecl( 5211 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5212 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 5213 5214 // Stride variable returned by runtime (we initialize it to 1 by default). 5215 VarDecl *STDecl = 5216 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 5217 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 5218 SemaRef.AddInitializerToDecl( 5219 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 5220 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 5221 5222 // Build expression: UB = min(UB, LastIteration) 5223 // It is nesessary for CodeGen of directives with static scheduling. 5224 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 5225 UB.get(), LastIteration.get()); 5226 ExprResult CondOp = SemaRef.ActOnConditionalOp( 5227 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 5228 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 5229 CondOp.get()); 5230 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 5231 5232 // If we have a combined directive that combines 'distribute', 'for' or 5233 // 'simd' we need to be able to access the bounds of the schedule of the 5234 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 5235 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 5236 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5237 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 5238 5239 // We expect to have at least 2 more parameters than the 'parallel' 5240 // directive does - the lower and upper bounds of the previous schedule. 5241 assert(CD->getNumParams() >= 4 && 5242 "Unexpected number of parameters in loop combined directive"); 5243 5244 // Set the proper type for the bounds given what we learned from the 5245 // enclosed loops. 5246 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 5247 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 5248 5249 // Previous lower and upper bounds are obtained from the region 5250 // parameters. 5251 PrevLB = 5252 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 5253 PrevUB = 5254 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 5255 } 5256 } 5257 5258 // Build the iteration variable and its initialization before loop. 5259 ExprResult IV; 5260 ExprResult Init; 5261 { 5262 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 5263 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 5264 Expr *RHS = (isOpenMPWorksharingDirective(DKind) || 5265 isOpenMPTaskLoopDirective(DKind) || 5266 isOpenMPDistributeDirective(DKind)) 5267 ? LB.get() 5268 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 5269 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 5270 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 5271 } 5272 5273 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 5274 SourceLocation CondLoc; 5275 ExprResult Cond = 5276 (isOpenMPWorksharingDirective(DKind) || 5277 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 5278 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 5279 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 5280 NumIterations.get()); 5281 5282 // Loop increment (IV = IV + 1) 5283 SourceLocation IncLoc; 5284 ExprResult Inc = 5285 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 5286 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 5287 if (!Inc.isUsable()) 5288 return 0; 5289 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 5290 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 5291 if (!Inc.isUsable()) 5292 return 0; 5293 5294 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 5295 // Used for directives with static scheduling. 5296 ExprResult NextLB, NextUB; 5297 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 5298 isOpenMPDistributeDirective(DKind)) { 5299 // LB + ST 5300 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 5301 if (!NextLB.isUsable()) 5302 return 0; 5303 // LB = LB + ST 5304 NextLB = 5305 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 5306 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 5307 if (!NextLB.isUsable()) 5308 return 0; 5309 // UB + ST 5310 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 5311 if (!NextUB.isUsable()) 5312 return 0; 5313 // UB = UB + ST 5314 NextUB = 5315 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 5316 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 5317 if (!NextUB.isUsable()) 5318 return 0; 5319 } 5320 5321 // Build updates and final values of the loop counters. 5322 bool HasErrors = false; 5323 Built.Counters.resize(NestedLoopCount); 5324 Built.Inits.resize(NestedLoopCount); 5325 Built.Updates.resize(NestedLoopCount); 5326 Built.Finals.resize(NestedLoopCount); 5327 SmallVector<Expr *, 4> LoopMultipliers; 5328 { 5329 ExprResult Div; 5330 // Go from inner nested loop to outer. 5331 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 5332 LoopIterationSpace &IS = IterSpaces[Cnt]; 5333 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 5334 // Build: Iter = (IV / Div) % IS.NumIters 5335 // where Div is product of previous iterations' IS.NumIters. 5336 ExprResult Iter; 5337 if (Div.isUsable()) { 5338 Iter = 5339 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 5340 } else { 5341 Iter = IV; 5342 assert((Cnt == (int)NestedLoopCount - 1) && 5343 "unusable div expected on first iteration only"); 5344 } 5345 5346 if (Cnt != 0 && Iter.isUsable()) 5347 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 5348 IS.NumIterations); 5349 if (!Iter.isUsable()) { 5350 HasErrors = true; 5351 break; 5352 } 5353 5354 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 5355 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 5356 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 5357 IS.CounterVar->getExprLoc(), 5358 /*RefersToCapture=*/true); 5359 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 5360 IS.CounterInit, Captures); 5361 if (!Init.isUsable()) { 5362 HasErrors = true; 5363 break; 5364 } 5365 ExprResult Update = BuildCounterUpdate( 5366 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 5367 IS.CounterStep, IS.Subtract, &Captures); 5368 if (!Update.isUsable()) { 5369 HasErrors = true; 5370 break; 5371 } 5372 5373 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 5374 ExprResult Final = BuildCounterUpdate( 5375 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 5376 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 5377 if (!Final.isUsable()) { 5378 HasErrors = true; 5379 break; 5380 } 5381 5382 // Build Div for the next iteration: Div <- Div * IS.NumIters 5383 if (Cnt != 0) { 5384 if (Div.isUnset()) 5385 Div = IS.NumIterations; 5386 else 5387 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 5388 IS.NumIterations); 5389 5390 // Add parentheses (for debugging purposes only). 5391 if (Div.isUsable()) 5392 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 5393 if (!Div.isUsable()) { 5394 HasErrors = true; 5395 break; 5396 } 5397 LoopMultipliers.push_back(Div.get()); 5398 } 5399 if (!Update.isUsable() || !Final.isUsable()) { 5400 HasErrors = true; 5401 break; 5402 } 5403 // Save results 5404 Built.Counters[Cnt] = IS.CounterVar; 5405 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 5406 Built.Inits[Cnt] = Init.get(); 5407 Built.Updates[Cnt] = Update.get(); 5408 Built.Finals[Cnt] = Final.get(); 5409 } 5410 } 5411 5412 if (HasErrors) 5413 return 0; 5414 5415 // Save results 5416 Built.IterationVarRef = IV.get(); 5417 Built.LastIteration = LastIteration.get(); 5418 Built.NumIterations = NumIterations.get(); 5419 Built.CalcLastIteration = 5420 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 5421 Built.PreCond = PreCond.get(); 5422 Built.PreInits = buildPreInits(C, Captures); 5423 Built.Cond = Cond.get(); 5424 Built.Init = Init.get(); 5425 Built.Inc = Inc.get(); 5426 Built.LB = LB.get(); 5427 Built.UB = UB.get(); 5428 Built.IL = IL.get(); 5429 Built.ST = ST.get(); 5430 Built.EUB = EUB.get(); 5431 Built.NLB = NextLB.get(); 5432 Built.NUB = NextUB.get(); 5433 Built.PrevLB = PrevLB.get(); 5434 Built.PrevUB = PrevUB.get(); 5435 5436 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 5437 // Fill data for doacross depend clauses. 5438 for (auto Pair : DSA.getDoacrossDependClauses()) { 5439 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 5440 Pair.first->setCounterValue(CounterVal); 5441 else { 5442 if (NestedLoopCount != Pair.second.size() || 5443 NestedLoopCount != LoopMultipliers.size() + 1) { 5444 // Erroneous case - clause has some problems. 5445 Pair.first->setCounterValue(CounterVal); 5446 continue; 5447 } 5448 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 5449 auto I = Pair.second.rbegin(); 5450 auto IS = IterSpaces.rbegin(); 5451 auto ILM = LoopMultipliers.rbegin(); 5452 Expr *UpCounterVal = CounterVal; 5453 Expr *Multiplier = nullptr; 5454 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 5455 if (I->first) { 5456 assert(IS->CounterStep); 5457 Expr *NormalizedOffset = 5458 SemaRef 5459 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 5460 I->first, IS->CounterStep) 5461 .get(); 5462 if (Multiplier) { 5463 NormalizedOffset = 5464 SemaRef 5465 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 5466 NormalizedOffset, Multiplier) 5467 .get(); 5468 } 5469 assert(I->second == OO_Plus || I->second == OO_Minus); 5470 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 5471 UpCounterVal = 5472 SemaRef.BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 5473 UpCounterVal, NormalizedOffset).get(); 5474 } 5475 Multiplier = *ILM; 5476 ++I; 5477 ++IS; 5478 ++ILM; 5479 } 5480 Pair.first->setCounterValue(UpCounterVal); 5481 } 5482 } 5483 5484 return NestedLoopCount; 5485 } 5486 5487 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 5488 auto CollapseClauses = 5489 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 5490 if (CollapseClauses.begin() != CollapseClauses.end()) 5491 return (*CollapseClauses.begin())->getNumForLoops(); 5492 return nullptr; 5493 } 5494 5495 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 5496 auto OrderedClauses = 5497 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 5498 if (OrderedClauses.begin() != OrderedClauses.end()) 5499 return (*OrderedClauses.begin())->getNumForLoops(); 5500 return nullptr; 5501 } 5502 5503 static bool checkSimdlenSafelenSpecified(Sema &S, 5504 const ArrayRef<OMPClause *> Clauses) { 5505 OMPSafelenClause *Safelen = nullptr; 5506 OMPSimdlenClause *Simdlen = nullptr; 5507 5508 for (auto *Clause : Clauses) { 5509 if (Clause->getClauseKind() == OMPC_safelen) 5510 Safelen = cast<OMPSafelenClause>(Clause); 5511 else if (Clause->getClauseKind() == OMPC_simdlen) 5512 Simdlen = cast<OMPSimdlenClause>(Clause); 5513 if (Safelen && Simdlen) 5514 break; 5515 } 5516 5517 if (Simdlen && Safelen) { 5518 llvm::APSInt SimdlenRes, SafelenRes; 5519 auto SimdlenLength = Simdlen->getSimdlen(); 5520 auto SafelenLength = Safelen->getSafelen(); 5521 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 5522 SimdlenLength->isInstantiationDependent() || 5523 SimdlenLength->containsUnexpandedParameterPack()) 5524 return false; 5525 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 5526 SafelenLength->isInstantiationDependent() || 5527 SafelenLength->containsUnexpandedParameterPack()) 5528 return false; 5529 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 5530 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 5531 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 5532 // If both simdlen and safelen clauses are specified, the value of the 5533 // simdlen parameter must be less than or equal to the value of the safelen 5534 // parameter. 5535 if (SimdlenRes > SafelenRes) { 5536 S.Diag(SimdlenLength->getExprLoc(), 5537 diag::err_omp_wrong_simdlen_safelen_values) 5538 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 5539 return true; 5540 } 5541 } 5542 return false; 5543 } 5544 5545 StmtResult Sema::ActOnOpenMPSimdDirective( 5546 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5547 SourceLocation EndLoc, 5548 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5549 if (!AStmt) 5550 return StmtError(); 5551 5552 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5553 OMPLoopDirective::HelperExprs B; 5554 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5555 // define the nested loops number. 5556 unsigned NestedLoopCount = CheckOpenMPLoop( 5557 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5558 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5559 if (NestedLoopCount == 0) 5560 return StmtError(); 5561 5562 assert((CurContext->isDependentContext() || B.builtAll()) && 5563 "omp simd loop exprs were not built"); 5564 5565 if (!CurContext->isDependentContext()) { 5566 // Finalize the clauses that need pre-built expressions for CodeGen. 5567 for (auto C : Clauses) { 5568 if (auto LC = dyn_cast<OMPLinearClause>(C)) 5569 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5570 B.NumIterations, *this, CurScope, 5571 DSAStack)) 5572 return StmtError(); 5573 } 5574 } 5575 5576 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5577 return StmtError(); 5578 5579 getCurFunction()->setHasBranchProtectedScope(); 5580 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5581 Clauses, AStmt, B); 5582 } 5583 5584 StmtResult Sema::ActOnOpenMPForDirective( 5585 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5586 SourceLocation EndLoc, 5587 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5588 if (!AStmt) 5589 return StmtError(); 5590 5591 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5592 OMPLoopDirective::HelperExprs B; 5593 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5594 // define the nested loops number. 5595 unsigned NestedLoopCount = CheckOpenMPLoop( 5596 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5597 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5598 if (NestedLoopCount == 0) 5599 return StmtError(); 5600 5601 assert((CurContext->isDependentContext() || B.builtAll()) && 5602 "omp for loop exprs were not built"); 5603 5604 if (!CurContext->isDependentContext()) { 5605 // Finalize the clauses that need pre-built expressions for CodeGen. 5606 for (auto C : Clauses) { 5607 if (auto LC = dyn_cast<OMPLinearClause>(C)) 5608 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5609 B.NumIterations, *this, CurScope, 5610 DSAStack)) 5611 return StmtError(); 5612 } 5613 } 5614 5615 getCurFunction()->setHasBranchProtectedScope(); 5616 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5617 Clauses, AStmt, B, DSAStack->isCancelRegion()); 5618 } 5619 5620 StmtResult Sema::ActOnOpenMPForSimdDirective( 5621 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5622 SourceLocation EndLoc, 5623 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5624 if (!AStmt) 5625 return StmtError(); 5626 5627 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5628 OMPLoopDirective::HelperExprs B; 5629 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5630 // define the nested loops number. 5631 unsigned NestedLoopCount = 5632 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 5633 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5634 VarsWithImplicitDSA, B); 5635 if (NestedLoopCount == 0) 5636 return StmtError(); 5637 5638 assert((CurContext->isDependentContext() || B.builtAll()) && 5639 "omp for simd loop exprs were not built"); 5640 5641 if (!CurContext->isDependentContext()) { 5642 // Finalize the clauses that need pre-built expressions for CodeGen. 5643 for (auto C : Clauses) { 5644 if (auto LC = dyn_cast<OMPLinearClause>(C)) 5645 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5646 B.NumIterations, *this, CurScope, 5647 DSAStack)) 5648 return StmtError(); 5649 } 5650 } 5651 5652 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5653 return StmtError(); 5654 5655 getCurFunction()->setHasBranchProtectedScope(); 5656 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5657 Clauses, AStmt, B); 5658 } 5659 5660 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 5661 Stmt *AStmt, 5662 SourceLocation StartLoc, 5663 SourceLocation EndLoc) { 5664 if (!AStmt) 5665 return StmtError(); 5666 5667 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5668 auto BaseStmt = AStmt; 5669 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5670 BaseStmt = CS->getCapturedStmt(); 5671 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5672 auto S = C->children(); 5673 if (S.begin() == S.end()) 5674 return StmtError(); 5675 // All associated statements must be '#pragma omp section' except for 5676 // the first one. 5677 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5678 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5679 if (SectionStmt) 5680 Diag(SectionStmt->getLocStart(), 5681 diag::err_omp_sections_substmt_not_section); 5682 return StmtError(); 5683 } 5684 cast<OMPSectionDirective>(SectionStmt) 5685 ->setHasCancel(DSAStack->isCancelRegion()); 5686 } 5687 } else { 5688 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 5689 return StmtError(); 5690 } 5691 5692 getCurFunction()->setHasBranchProtectedScope(); 5693 5694 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5695 DSAStack->isCancelRegion()); 5696 } 5697 5698 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 5699 SourceLocation StartLoc, 5700 SourceLocation EndLoc) { 5701 if (!AStmt) 5702 return StmtError(); 5703 5704 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5705 5706 getCurFunction()->setHasBranchProtectedScope(); 5707 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 5708 5709 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 5710 DSAStack->isCancelRegion()); 5711 } 5712 5713 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 5714 Stmt *AStmt, 5715 SourceLocation StartLoc, 5716 SourceLocation EndLoc) { 5717 if (!AStmt) 5718 return StmtError(); 5719 5720 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5721 5722 getCurFunction()->setHasBranchProtectedScope(); 5723 5724 // OpenMP [2.7.3, single Construct, Restrictions] 5725 // The copyprivate clause must not be used with the nowait clause. 5726 OMPClause *Nowait = nullptr; 5727 OMPClause *Copyprivate = nullptr; 5728 for (auto *Clause : Clauses) { 5729 if (Clause->getClauseKind() == OMPC_nowait) 5730 Nowait = Clause; 5731 else if (Clause->getClauseKind() == OMPC_copyprivate) 5732 Copyprivate = Clause; 5733 if (Copyprivate && Nowait) { 5734 Diag(Copyprivate->getLocStart(), 5735 diag::err_omp_single_copyprivate_with_nowait); 5736 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 5737 return StmtError(); 5738 } 5739 } 5740 5741 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5742 } 5743 5744 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 5745 SourceLocation StartLoc, 5746 SourceLocation EndLoc) { 5747 if (!AStmt) 5748 return StmtError(); 5749 5750 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5751 5752 getCurFunction()->setHasBranchProtectedScope(); 5753 5754 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 5755 } 5756 5757 StmtResult Sema::ActOnOpenMPCriticalDirective( 5758 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 5759 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5760 if (!AStmt) 5761 return StmtError(); 5762 5763 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5764 5765 bool ErrorFound = false; 5766 llvm::APSInt Hint; 5767 SourceLocation HintLoc; 5768 bool DependentHint = false; 5769 for (auto *C : Clauses) { 5770 if (C->getClauseKind() == OMPC_hint) { 5771 if (!DirName.getName()) { 5772 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 5773 ErrorFound = true; 5774 } 5775 Expr *E = cast<OMPHintClause>(C)->getHint(); 5776 if (E->isTypeDependent() || E->isValueDependent() || 5777 E->isInstantiationDependent()) 5778 DependentHint = true; 5779 else { 5780 Hint = E->EvaluateKnownConstInt(Context); 5781 HintLoc = C->getLocStart(); 5782 } 5783 } 5784 } 5785 if (ErrorFound) 5786 return StmtError(); 5787 auto Pair = DSAStack->getCriticalWithHint(DirName); 5788 if (Pair.first && DirName.getName() && !DependentHint) { 5789 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 5790 Diag(StartLoc, diag::err_omp_critical_with_hint); 5791 if (HintLoc.isValid()) { 5792 Diag(HintLoc, diag::note_omp_critical_hint_here) 5793 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 5794 } else 5795 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 5796 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 5797 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 5798 << 1 5799 << C->getHint()->EvaluateKnownConstInt(Context).toString( 5800 /*Radix=*/10, /*Signed=*/false); 5801 } else 5802 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 5803 } 5804 } 5805 5806 getCurFunction()->setHasBranchProtectedScope(); 5807 5808 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 5809 Clauses, AStmt); 5810 if (!Pair.first && DirName.getName() && !DependentHint) 5811 DSAStack->addCriticalWithHint(Dir, Hint); 5812 return Dir; 5813 } 5814 5815 StmtResult Sema::ActOnOpenMPParallelForDirective( 5816 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5817 SourceLocation EndLoc, 5818 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5819 if (!AStmt) 5820 return StmtError(); 5821 5822 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5823 // 1.2.2 OpenMP Language Terminology 5824 // Structured block - An executable statement with a single entry at the 5825 // top and a single exit at the bottom. 5826 // The point of exit cannot be a branch out of the structured block. 5827 // longjmp() and throw() must not violate the entry/exit criteria. 5828 CS->getCapturedDecl()->setNothrow(); 5829 5830 OMPLoopDirective::HelperExprs B; 5831 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5832 // define the nested loops number. 5833 unsigned NestedLoopCount = 5834 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 5835 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5836 VarsWithImplicitDSA, B); 5837 if (NestedLoopCount == 0) 5838 return StmtError(); 5839 5840 assert((CurContext->isDependentContext() || B.builtAll()) && 5841 "omp parallel for loop exprs were not built"); 5842 5843 if (!CurContext->isDependentContext()) { 5844 // Finalize the clauses that need pre-built expressions for CodeGen. 5845 for (auto C : Clauses) { 5846 if (auto LC = dyn_cast<OMPLinearClause>(C)) 5847 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5848 B.NumIterations, *this, CurScope, 5849 DSAStack)) 5850 return StmtError(); 5851 } 5852 } 5853 5854 getCurFunction()->setHasBranchProtectedScope(); 5855 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 5856 NestedLoopCount, Clauses, AStmt, B, 5857 DSAStack->isCancelRegion()); 5858 } 5859 5860 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 5861 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5862 SourceLocation EndLoc, 5863 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5864 if (!AStmt) 5865 return StmtError(); 5866 5867 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5868 // 1.2.2 OpenMP Language Terminology 5869 // Structured block - An executable statement with a single entry at the 5870 // top and a single exit at the bottom. 5871 // The point of exit cannot be a branch out of the structured block. 5872 // longjmp() and throw() must not violate the entry/exit criteria. 5873 CS->getCapturedDecl()->setNothrow(); 5874 5875 OMPLoopDirective::HelperExprs B; 5876 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5877 // define the nested loops number. 5878 unsigned NestedLoopCount = 5879 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 5880 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5881 VarsWithImplicitDSA, B); 5882 if (NestedLoopCount == 0) 5883 return StmtError(); 5884 5885 if (!CurContext->isDependentContext()) { 5886 // Finalize the clauses that need pre-built expressions for CodeGen. 5887 for (auto C : Clauses) { 5888 if (auto LC = dyn_cast<OMPLinearClause>(C)) 5889 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5890 B.NumIterations, *this, CurScope, 5891 DSAStack)) 5892 return StmtError(); 5893 } 5894 } 5895 5896 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5897 return StmtError(); 5898 5899 getCurFunction()->setHasBranchProtectedScope(); 5900 return OMPParallelForSimdDirective::Create( 5901 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 5902 } 5903 5904 StmtResult 5905 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 5906 Stmt *AStmt, SourceLocation StartLoc, 5907 SourceLocation EndLoc) { 5908 if (!AStmt) 5909 return StmtError(); 5910 5911 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5912 auto BaseStmt = AStmt; 5913 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5914 BaseStmt = CS->getCapturedStmt(); 5915 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5916 auto S = C->children(); 5917 if (S.begin() == S.end()) 5918 return StmtError(); 5919 // All associated statements must be '#pragma omp section' except for 5920 // the first one. 5921 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5922 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5923 if (SectionStmt) 5924 Diag(SectionStmt->getLocStart(), 5925 diag::err_omp_parallel_sections_substmt_not_section); 5926 return StmtError(); 5927 } 5928 cast<OMPSectionDirective>(SectionStmt) 5929 ->setHasCancel(DSAStack->isCancelRegion()); 5930 } 5931 } else { 5932 Diag(AStmt->getLocStart(), 5933 diag::err_omp_parallel_sections_not_compound_stmt); 5934 return StmtError(); 5935 } 5936 5937 getCurFunction()->setHasBranchProtectedScope(); 5938 5939 return OMPParallelSectionsDirective::Create( 5940 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 5941 } 5942 5943 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 5944 Stmt *AStmt, SourceLocation StartLoc, 5945 SourceLocation EndLoc) { 5946 if (!AStmt) 5947 return StmtError(); 5948 5949 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5950 // 1.2.2 OpenMP Language Terminology 5951 // Structured block - An executable statement with a single entry at the 5952 // top and a single exit at the bottom. 5953 // The point of exit cannot be a branch out of the structured block. 5954 // longjmp() and throw() must not violate the entry/exit criteria. 5955 CS->getCapturedDecl()->setNothrow(); 5956 5957 getCurFunction()->setHasBranchProtectedScope(); 5958 5959 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5960 DSAStack->isCancelRegion()); 5961 } 5962 5963 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 5964 SourceLocation EndLoc) { 5965 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 5966 } 5967 5968 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 5969 SourceLocation EndLoc) { 5970 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 5971 } 5972 5973 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 5974 SourceLocation EndLoc) { 5975 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 5976 } 5977 5978 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt, 5979 SourceLocation StartLoc, 5980 SourceLocation EndLoc) { 5981 if (!AStmt) 5982 return StmtError(); 5983 5984 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5985 5986 getCurFunction()->setHasBranchProtectedScope(); 5987 5988 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt); 5989 } 5990 5991 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 5992 SourceLocation StartLoc, 5993 SourceLocation EndLoc) { 5994 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 5995 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 5996 } 5997 5998 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 5999 Stmt *AStmt, 6000 SourceLocation StartLoc, 6001 SourceLocation EndLoc) { 6002 OMPClause *DependFound = nullptr; 6003 OMPClause *DependSourceClause = nullptr; 6004 OMPClause *DependSinkClause = nullptr; 6005 bool ErrorFound = false; 6006 OMPThreadsClause *TC = nullptr; 6007 OMPSIMDClause *SC = nullptr; 6008 for (auto *C : Clauses) { 6009 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 6010 DependFound = C; 6011 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 6012 if (DependSourceClause) { 6013 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 6014 << getOpenMPDirectiveName(OMPD_ordered) 6015 << getOpenMPClauseName(OMPC_depend) << 2; 6016 ErrorFound = true; 6017 } else 6018 DependSourceClause = C; 6019 if (DependSinkClause) { 6020 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 6021 << 0; 6022 ErrorFound = true; 6023 } 6024 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 6025 if (DependSourceClause) { 6026 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 6027 << 1; 6028 ErrorFound = true; 6029 } 6030 DependSinkClause = C; 6031 } 6032 } else if (C->getClauseKind() == OMPC_threads) 6033 TC = cast<OMPThreadsClause>(C); 6034 else if (C->getClauseKind() == OMPC_simd) 6035 SC = cast<OMPSIMDClause>(C); 6036 } 6037 if (!ErrorFound && !SC && 6038 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 6039 // OpenMP [2.8.1,simd Construct, Restrictions] 6040 // An ordered construct with the simd clause is the only OpenMP construct 6041 // that can appear in the simd region. 6042 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 6043 ErrorFound = true; 6044 } else if (DependFound && (TC || SC)) { 6045 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 6046 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 6047 ErrorFound = true; 6048 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 6049 Diag(DependFound->getLocStart(), 6050 diag::err_omp_ordered_directive_without_param); 6051 ErrorFound = true; 6052 } else if (TC || Clauses.empty()) { 6053 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 6054 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 6055 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 6056 << (TC != nullptr); 6057 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 6058 ErrorFound = true; 6059 } 6060 } 6061 if ((!AStmt && !DependFound) || ErrorFound) 6062 return StmtError(); 6063 6064 if (AStmt) { 6065 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6066 6067 getCurFunction()->setHasBranchProtectedScope(); 6068 } 6069 6070 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6071 } 6072 6073 namespace { 6074 /// \brief Helper class for checking expression in 'omp atomic [update]' 6075 /// construct. 6076 class OpenMPAtomicUpdateChecker { 6077 /// \brief Error results for atomic update expressions. 6078 enum ExprAnalysisErrorCode { 6079 /// \brief A statement is not an expression statement. 6080 NotAnExpression, 6081 /// \brief Expression is not builtin binary or unary operation. 6082 NotABinaryOrUnaryExpression, 6083 /// \brief Unary operation is not post-/pre- increment/decrement operation. 6084 NotAnUnaryIncDecExpression, 6085 /// \brief An expression is not of scalar type. 6086 NotAScalarType, 6087 /// \brief A binary operation is not an assignment operation. 6088 NotAnAssignmentOp, 6089 /// \brief RHS part of the binary operation is not a binary expression. 6090 NotABinaryExpression, 6091 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 6092 /// expression. 6093 NotABinaryOperator, 6094 /// \brief RHS binary operation does not have reference to the updated LHS 6095 /// part. 6096 NotAnUpdateExpression, 6097 /// \brief No errors is found. 6098 NoError 6099 }; 6100 /// \brief Reference to Sema. 6101 Sema &SemaRef; 6102 /// \brief A location for note diagnostics (when error is found). 6103 SourceLocation NoteLoc; 6104 /// \brief 'x' lvalue part of the source atomic expression. 6105 Expr *X; 6106 /// \brief 'expr' rvalue part of the source atomic expression. 6107 Expr *E; 6108 /// \brief Helper expression of the form 6109 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 6110 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 6111 Expr *UpdateExpr; 6112 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 6113 /// important for non-associative operations. 6114 bool IsXLHSInRHSPart; 6115 BinaryOperatorKind Op; 6116 SourceLocation OpLoc; 6117 /// \brief true if the source expression is a postfix unary operation, false 6118 /// if it is a prefix unary operation. 6119 bool IsPostfixUpdate; 6120 6121 public: 6122 OpenMPAtomicUpdateChecker(Sema &SemaRef) 6123 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 6124 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 6125 /// \brief Check specified statement that it is suitable for 'atomic update' 6126 /// constructs and extract 'x', 'expr' and Operation from the original 6127 /// expression. If DiagId and NoteId == 0, then only check is performed 6128 /// without error notification. 6129 /// \param DiagId Diagnostic which should be emitted if error is found. 6130 /// \param NoteId Diagnostic note for the main error message. 6131 /// \return true if statement is not an update expression, false otherwise. 6132 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 6133 /// \brief Return the 'x' lvalue part of the source atomic expression. 6134 Expr *getX() const { return X; } 6135 /// \brief Return the 'expr' rvalue part of the source atomic expression. 6136 Expr *getExpr() const { return E; } 6137 /// \brief Return the update expression used in calculation of the updated 6138 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 6139 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 6140 Expr *getUpdateExpr() const { return UpdateExpr; } 6141 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 6142 /// false otherwise. 6143 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 6144 6145 /// \brief true if the source expression is a postfix unary operation, false 6146 /// if it is a prefix unary operation. 6147 bool isPostfixUpdate() const { return IsPostfixUpdate; } 6148 6149 private: 6150 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 6151 unsigned NoteId = 0); 6152 }; 6153 } // namespace 6154 6155 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 6156 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 6157 ExprAnalysisErrorCode ErrorFound = NoError; 6158 SourceLocation ErrorLoc, NoteLoc; 6159 SourceRange ErrorRange, NoteRange; 6160 // Allowed constructs are: 6161 // x = x binop expr; 6162 // x = expr binop x; 6163 if (AtomicBinOp->getOpcode() == BO_Assign) { 6164 X = AtomicBinOp->getLHS(); 6165 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 6166 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 6167 if (AtomicInnerBinOp->isMultiplicativeOp() || 6168 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 6169 AtomicInnerBinOp->isBitwiseOp()) { 6170 Op = AtomicInnerBinOp->getOpcode(); 6171 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 6172 auto *LHS = AtomicInnerBinOp->getLHS(); 6173 auto *RHS = AtomicInnerBinOp->getRHS(); 6174 llvm::FoldingSetNodeID XId, LHSId, RHSId; 6175 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 6176 /*Canonical=*/true); 6177 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 6178 /*Canonical=*/true); 6179 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 6180 /*Canonical=*/true); 6181 if (XId == LHSId) { 6182 E = RHS; 6183 IsXLHSInRHSPart = true; 6184 } else if (XId == RHSId) { 6185 E = LHS; 6186 IsXLHSInRHSPart = false; 6187 } else { 6188 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 6189 ErrorRange = AtomicInnerBinOp->getSourceRange(); 6190 NoteLoc = X->getExprLoc(); 6191 NoteRange = X->getSourceRange(); 6192 ErrorFound = NotAnUpdateExpression; 6193 } 6194 } else { 6195 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 6196 ErrorRange = AtomicInnerBinOp->getSourceRange(); 6197 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 6198 NoteRange = SourceRange(NoteLoc, NoteLoc); 6199 ErrorFound = NotABinaryOperator; 6200 } 6201 } else { 6202 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 6203 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 6204 ErrorFound = NotABinaryExpression; 6205 } 6206 } else { 6207 ErrorLoc = AtomicBinOp->getExprLoc(); 6208 ErrorRange = AtomicBinOp->getSourceRange(); 6209 NoteLoc = AtomicBinOp->getOperatorLoc(); 6210 NoteRange = SourceRange(NoteLoc, NoteLoc); 6211 ErrorFound = NotAnAssignmentOp; 6212 } 6213 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 6214 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 6215 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 6216 return true; 6217 } else if (SemaRef.CurContext->isDependentContext()) 6218 E = X = UpdateExpr = nullptr; 6219 return ErrorFound != NoError; 6220 } 6221 6222 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 6223 unsigned NoteId) { 6224 ExprAnalysisErrorCode ErrorFound = NoError; 6225 SourceLocation ErrorLoc, NoteLoc; 6226 SourceRange ErrorRange, NoteRange; 6227 // Allowed constructs are: 6228 // x++; 6229 // x--; 6230 // ++x; 6231 // --x; 6232 // x binop= expr; 6233 // x = x binop expr; 6234 // x = expr binop x; 6235 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 6236 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 6237 if (AtomicBody->getType()->isScalarType() || 6238 AtomicBody->isInstantiationDependent()) { 6239 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 6240 AtomicBody->IgnoreParenImpCasts())) { 6241 // Check for Compound Assignment Operation 6242 Op = BinaryOperator::getOpForCompoundAssignment( 6243 AtomicCompAssignOp->getOpcode()); 6244 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 6245 E = AtomicCompAssignOp->getRHS(); 6246 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 6247 IsXLHSInRHSPart = true; 6248 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 6249 AtomicBody->IgnoreParenImpCasts())) { 6250 // Check for Binary Operation 6251 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 6252 return true; 6253 } else if (auto *AtomicUnaryOp = 6254 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) { 6255 // Check for Unary Operation 6256 if (AtomicUnaryOp->isIncrementDecrementOp()) { 6257 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 6258 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 6259 OpLoc = AtomicUnaryOp->getOperatorLoc(); 6260 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 6261 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 6262 IsXLHSInRHSPart = true; 6263 } else { 6264 ErrorFound = NotAnUnaryIncDecExpression; 6265 ErrorLoc = AtomicUnaryOp->getExprLoc(); 6266 ErrorRange = AtomicUnaryOp->getSourceRange(); 6267 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 6268 NoteRange = SourceRange(NoteLoc, NoteLoc); 6269 } 6270 } else if (!AtomicBody->isInstantiationDependent()) { 6271 ErrorFound = NotABinaryOrUnaryExpression; 6272 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 6273 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 6274 } 6275 } else { 6276 ErrorFound = NotAScalarType; 6277 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 6278 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6279 } 6280 } else { 6281 ErrorFound = NotAnExpression; 6282 NoteLoc = ErrorLoc = S->getLocStart(); 6283 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6284 } 6285 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 6286 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 6287 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 6288 return true; 6289 } else if (SemaRef.CurContext->isDependentContext()) 6290 E = X = UpdateExpr = nullptr; 6291 if (ErrorFound == NoError && E && X) { 6292 // Build an update expression of form 'OpaqueValueExpr(x) binop 6293 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 6294 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 6295 auto *OVEX = new (SemaRef.getASTContext()) 6296 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 6297 auto *OVEExpr = new (SemaRef.getASTContext()) 6298 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 6299 auto Update = 6300 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 6301 IsXLHSInRHSPart ? OVEExpr : OVEX); 6302 if (Update.isInvalid()) 6303 return true; 6304 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 6305 Sema::AA_Casting); 6306 if (Update.isInvalid()) 6307 return true; 6308 UpdateExpr = Update.get(); 6309 } 6310 return ErrorFound != NoError; 6311 } 6312 6313 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 6314 Stmt *AStmt, 6315 SourceLocation StartLoc, 6316 SourceLocation EndLoc) { 6317 if (!AStmt) 6318 return StmtError(); 6319 6320 auto CS = cast<CapturedStmt>(AStmt); 6321 // 1.2.2 OpenMP Language Terminology 6322 // Structured block - An executable statement with a single entry at the 6323 // top and a single exit at the bottom. 6324 // The point of exit cannot be a branch out of the structured block. 6325 // longjmp() and throw() must not violate the entry/exit criteria. 6326 OpenMPClauseKind AtomicKind = OMPC_unknown; 6327 SourceLocation AtomicKindLoc; 6328 for (auto *C : Clauses) { 6329 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 6330 C->getClauseKind() == OMPC_update || 6331 C->getClauseKind() == OMPC_capture) { 6332 if (AtomicKind != OMPC_unknown) { 6333 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 6334 << SourceRange(C->getLocStart(), C->getLocEnd()); 6335 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 6336 << getOpenMPClauseName(AtomicKind); 6337 } else { 6338 AtomicKind = C->getClauseKind(); 6339 AtomicKindLoc = C->getLocStart(); 6340 } 6341 } 6342 } 6343 6344 auto Body = CS->getCapturedStmt(); 6345 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 6346 Body = EWC->getSubExpr(); 6347 6348 Expr *X = nullptr; 6349 Expr *V = nullptr; 6350 Expr *E = nullptr; 6351 Expr *UE = nullptr; 6352 bool IsXLHSInRHSPart = false; 6353 bool IsPostfixUpdate = false; 6354 // OpenMP [2.12.6, atomic Construct] 6355 // In the next expressions: 6356 // * x and v (as applicable) are both l-value expressions with scalar type. 6357 // * During the execution of an atomic region, multiple syntactic 6358 // occurrences of x must designate the same storage location. 6359 // * Neither of v and expr (as applicable) may access the storage location 6360 // designated by x. 6361 // * Neither of x and expr (as applicable) may access the storage location 6362 // designated by v. 6363 // * expr is an expression with scalar type. 6364 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 6365 // * binop, binop=, ++, and -- are not overloaded operators. 6366 // * The expression x binop expr must be numerically equivalent to x binop 6367 // (expr). This requirement is satisfied if the operators in expr have 6368 // precedence greater than binop, or by using parentheses around expr or 6369 // subexpressions of expr. 6370 // * The expression expr binop x must be numerically equivalent to (expr) 6371 // binop x. This requirement is satisfied if the operators in expr have 6372 // precedence equal to or greater than binop, or by using parentheses around 6373 // expr or subexpressions of expr. 6374 // * For forms that allow multiple occurrences of x, the number of times 6375 // that x is evaluated is unspecified. 6376 if (AtomicKind == OMPC_read) { 6377 enum { 6378 NotAnExpression, 6379 NotAnAssignmentOp, 6380 NotAScalarType, 6381 NotAnLValue, 6382 NoError 6383 } ErrorFound = NoError; 6384 SourceLocation ErrorLoc, NoteLoc; 6385 SourceRange ErrorRange, NoteRange; 6386 // If clause is read: 6387 // v = x; 6388 if (auto AtomicBody = dyn_cast<Expr>(Body)) { 6389 auto AtomicBinOp = 6390 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6391 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6392 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6393 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 6394 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6395 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 6396 if (!X->isLValue() || !V->isLValue()) { 6397 auto NotLValueExpr = X->isLValue() ? V : X; 6398 ErrorFound = NotAnLValue; 6399 ErrorLoc = AtomicBinOp->getExprLoc(); 6400 ErrorRange = AtomicBinOp->getSourceRange(); 6401 NoteLoc = NotLValueExpr->getExprLoc(); 6402 NoteRange = NotLValueExpr->getSourceRange(); 6403 } 6404 } else if (!X->isInstantiationDependent() || 6405 !V->isInstantiationDependent()) { 6406 auto NotScalarExpr = 6407 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6408 ? V 6409 : X; 6410 ErrorFound = NotAScalarType; 6411 ErrorLoc = AtomicBinOp->getExprLoc(); 6412 ErrorRange = AtomicBinOp->getSourceRange(); 6413 NoteLoc = NotScalarExpr->getExprLoc(); 6414 NoteRange = NotScalarExpr->getSourceRange(); 6415 } 6416 } else if (!AtomicBody->isInstantiationDependent()) { 6417 ErrorFound = NotAnAssignmentOp; 6418 ErrorLoc = AtomicBody->getExprLoc(); 6419 ErrorRange = AtomicBody->getSourceRange(); 6420 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6421 : AtomicBody->getExprLoc(); 6422 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6423 : AtomicBody->getSourceRange(); 6424 } 6425 } else { 6426 ErrorFound = NotAnExpression; 6427 NoteLoc = ErrorLoc = Body->getLocStart(); 6428 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6429 } 6430 if (ErrorFound != NoError) { 6431 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 6432 << ErrorRange; 6433 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6434 << NoteRange; 6435 return StmtError(); 6436 } else if (CurContext->isDependentContext()) 6437 V = X = nullptr; 6438 } else if (AtomicKind == OMPC_write) { 6439 enum { 6440 NotAnExpression, 6441 NotAnAssignmentOp, 6442 NotAScalarType, 6443 NotAnLValue, 6444 NoError 6445 } ErrorFound = NoError; 6446 SourceLocation ErrorLoc, NoteLoc; 6447 SourceRange ErrorRange, NoteRange; 6448 // If clause is write: 6449 // x = expr; 6450 if (auto AtomicBody = dyn_cast<Expr>(Body)) { 6451 auto AtomicBinOp = 6452 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6453 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6454 X = AtomicBinOp->getLHS(); 6455 E = AtomicBinOp->getRHS(); 6456 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6457 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 6458 if (!X->isLValue()) { 6459 ErrorFound = NotAnLValue; 6460 ErrorLoc = AtomicBinOp->getExprLoc(); 6461 ErrorRange = AtomicBinOp->getSourceRange(); 6462 NoteLoc = X->getExprLoc(); 6463 NoteRange = X->getSourceRange(); 6464 } 6465 } else if (!X->isInstantiationDependent() || 6466 !E->isInstantiationDependent()) { 6467 auto NotScalarExpr = 6468 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6469 ? E 6470 : X; 6471 ErrorFound = NotAScalarType; 6472 ErrorLoc = AtomicBinOp->getExprLoc(); 6473 ErrorRange = AtomicBinOp->getSourceRange(); 6474 NoteLoc = NotScalarExpr->getExprLoc(); 6475 NoteRange = NotScalarExpr->getSourceRange(); 6476 } 6477 } else if (!AtomicBody->isInstantiationDependent()) { 6478 ErrorFound = NotAnAssignmentOp; 6479 ErrorLoc = AtomicBody->getExprLoc(); 6480 ErrorRange = AtomicBody->getSourceRange(); 6481 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6482 : AtomicBody->getExprLoc(); 6483 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6484 : AtomicBody->getSourceRange(); 6485 } 6486 } else { 6487 ErrorFound = NotAnExpression; 6488 NoteLoc = ErrorLoc = Body->getLocStart(); 6489 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6490 } 6491 if (ErrorFound != NoError) { 6492 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 6493 << ErrorRange; 6494 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6495 << NoteRange; 6496 return StmtError(); 6497 } else if (CurContext->isDependentContext()) 6498 E = X = nullptr; 6499 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 6500 // If clause is update: 6501 // x++; 6502 // x--; 6503 // ++x; 6504 // --x; 6505 // x binop= expr; 6506 // x = x binop expr; 6507 // x = expr binop x; 6508 OpenMPAtomicUpdateChecker Checker(*this); 6509 if (Checker.checkStatement( 6510 Body, (AtomicKind == OMPC_update) 6511 ? diag::err_omp_atomic_update_not_expression_statement 6512 : diag::err_omp_atomic_not_expression_statement, 6513 diag::note_omp_atomic_update)) 6514 return StmtError(); 6515 if (!CurContext->isDependentContext()) { 6516 E = Checker.getExpr(); 6517 X = Checker.getX(); 6518 UE = Checker.getUpdateExpr(); 6519 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6520 } 6521 } else if (AtomicKind == OMPC_capture) { 6522 enum { 6523 NotAnAssignmentOp, 6524 NotACompoundStatement, 6525 NotTwoSubstatements, 6526 NotASpecificExpression, 6527 NoError 6528 } ErrorFound = NoError; 6529 SourceLocation ErrorLoc, NoteLoc; 6530 SourceRange ErrorRange, NoteRange; 6531 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 6532 // If clause is a capture: 6533 // v = x++; 6534 // v = x--; 6535 // v = ++x; 6536 // v = --x; 6537 // v = x binop= expr; 6538 // v = x = x binop expr; 6539 // v = x = expr binop x; 6540 auto *AtomicBinOp = 6541 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6542 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6543 V = AtomicBinOp->getLHS(); 6544 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6545 OpenMPAtomicUpdateChecker Checker(*this); 6546 if (Checker.checkStatement( 6547 Body, diag::err_omp_atomic_capture_not_expression_statement, 6548 diag::note_omp_atomic_update)) 6549 return StmtError(); 6550 E = Checker.getExpr(); 6551 X = Checker.getX(); 6552 UE = Checker.getUpdateExpr(); 6553 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6554 IsPostfixUpdate = Checker.isPostfixUpdate(); 6555 } else if (!AtomicBody->isInstantiationDependent()) { 6556 ErrorLoc = AtomicBody->getExprLoc(); 6557 ErrorRange = AtomicBody->getSourceRange(); 6558 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6559 : AtomicBody->getExprLoc(); 6560 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6561 : AtomicBody->getSourceRange(); 6562 ErrorFound = NotAnAssignmentOp; 6563 } 6564 if (ErrorFound != NoError) { 6565 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 6566 << ErrorRange; 6567 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6568 return StmtError(); 6569 } else if (CurContext->isDependentContext()) { 6570 UE = V = E = X = nullptr; 6571 } 6572 } else { 6573 // If clause is a capture: 6574 // { v = x; x = expr; } 6575 // { v = x; x++; } 6576 // { v = x; x--; } 6577 // { v = x; ++x; } 6578 // { v = x; --x; } 6579 // { v = x; x binop= expr; } 6580 // { v = x; x = x binop expr; } 6581 // { v = x; x = expr binop x; } 6582 // { x++; v = x; } 6583 // { x--; v = x; } 6584 // { ++x; v = x; } 6585 // { --x; v = x; } 6586 // { x binop= expr; v = x; } 6587 // { x = x binop expr; v = x; } 6588 // { x = expr binop x; v = x; } 6589 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 6590 // Check that this is { expr1; expr2; } 6591 if (CS->size() == 2) { 6592 auto *First = CS->body_front(); 6593 auto *Second = CS->body_back(); 6594 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 6595 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 6596 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 6597 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 6598 // Need to find what subexpression is 'v' and what is 'x'. 6599 OpenMPAtomicUpdateChecker Checker(*this); 6600 bool IsUpdateExprFound = !Checker.checkStatement(Second); 6601 BinaryOperator *BinOp = nullptr; 6602 if (IsUpdateExprFound) { 6603 BinOp = dyn_cast<BinaryOperator>(First); 6604 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6605 } 6606 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6607 // { v = x; x++; } 6608 // { v = x; x--; } 6609 // { v = x; ++x; } 6610 // { v = x; --x; } 6611 // { v = x; x binop= expr; } 6612 // { v = x; x = x binop expr; } 6613 // { v = x; x = expr binop x; } 6614 // Check that the first expression has form v = x. 6615 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6616 llvm::FoldingSetNodeID XId, PossibleXId; 6617 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6618 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6619 IsUpdateExprFound = XId == PossibleXId; 6620 if (IsUpdateExprFound) { 6621 V = BinOp->getLHS(); 6622 X = Checker.getX(); 6623 E = Checker.getExpr(); 6624 UE = Checker.getUpdateExpr(); 6625 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6626 IsPostfixUpdate = true; 6627 } 6628 } 6629 if (!IsUpdateExprFound) { 6630 IsUpdateExprFound = !Checker.checkStatement(First); 6631 BinOp = nullptr; 6632 if (IsUpdateExprFound) { 6633 BinOp = dyn_cast<BinaryOperator>(Second); 6634 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6635 } 6636 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6637 // { x++; v = x; } 6638 // { x--; v = x; } 6639 // { ++x; v = x; } 6640 // { --x; v = x; } 6641 // { x binop= expr; v = x; } 6642 // { x = x binop expr; v = x; } 6643 // { x = expr binop x; v = x; } 6644 // Check that the second expression has form v = x. 6645 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6646 llvm::FoldingSetNodeID XId, PossibleXId; 6647 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6648 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6649 IsUpdateExprFound = XId == PossibleXId; 6650 if (IsUpdateExprFound) { 6651 V = BinOp->getLHS(); 6652 X = Checker.getX(); 6653 E = Checker.getExpr(); 6654 UE = Checker.getUpdateExpr(); 6655 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6656 IsPostfixUpdate = false; 6657 } 6658 } 6659 } 6660 if (!IsUpdateExprFound) { 6661 // { v = x; x = expr; } 6662 auto *FirstExpr = dyn_cast<Expr>(First); 6663 auto *SecondExpr = dyn_cast<Expr>(Second); 6664 if (!FirstExpr || !SecondExpr || 6665 !(FirstExpr->isInstantiationDependent() || 6666 SecondExpr->isInstantiationDependent())) { 6667 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 6668 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 6669 ErrorFound = NotAnAssignmentOp; 6670 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 6671 : First->getLocStart(); 6672 NoteRange = ErrorRange = FirstBinOp 6673 ? FirstBinOp->getSourceRange() 6674 : SourceRange(ErrorLoc, ErrorLoc); 6675 } else { 6676 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 6677 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 6678 ErrorFound = NotAnAssignmentOp; 6679 NoteLoc = ErrorLoc = SecondBinOp 6680 ? SecondBinOp->getOperatorLoc() 6681 : Second->getLocStart(); 6682 NoteRange = ErrorRange = 6683 SecondBinOp ? SecondBinOp->getSourceRange() 6684 : SourceRange(ErrorLoc, ErrorLoc); 6685 } else { 6686 auto *PossibleXRHSInFirst = 6687 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 6688 auto *PossibleXLHSInSecond = 6689 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 6690 llvm::FoldingSetNodeID X1Id, X2Id; 6691 PossibleXRHSInFirst->Profile(X1Id, Context, 6692 /*Canonical=*/true); 6693 PossibleXLHSInSecond->Profile(X2Id, Context, 6694 /*Canonical=*/true); 6695 IsUpdateExprFound = X1Id == X2Id; 6696 if (IsUpdateExprFound) { 6697 V = FirstBinOp->getLHS(); 6698 X = SecondBinOp->getLHS(); 6699 E = SecondBinOp->getRHS(); 6700 UE = nullptr; 6701 IsXLHSInRHSPart = false; 6702 IsPostfixUpdate = true; 6703 } else { 6704 ErrorFound = NotASpecificExpression; 6705 ErrorLoc = FirstBinOp->getExprLoc(); 6706 ErrorRange = FirstBinOp->getSourceRange(); 6707 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 6708 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 6709 } 6710 } 6711 } 6712 } 6713 } 6714 } else { 6715 NoteLoc = ErrorLoc = Body->getLocStart(); 6716 NoteRange = ErrorRange = 6717 SourceRange(Body->getLocStart(), Body->getLocStart()); 6718 ErrorFound = NotTwoSubstatements; 6719 } 6720 } else { 6721 NoteLoc = ErrorLoc = Body->getLocStart(); 6722 NoteRange = ErrorRange = 6723 SourceRange(Body->getLocStart(), Body->getLocStart()); 6724 ErrorFound = NotACompoundStatement; 6725 } 6726 if (ErrorFound != NoError) { 6727 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 6728 << ErrorRange; 6729 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6730 return StmtError(); 6731 } else if (CurContext->isDependentContext()) { 6732 UE = V = E = X = nullptr; 6733 } 6734 } 6735 } 6736 6737 getCurFunction()->setHasBranchProtectedScope(); 6738 6739 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6740 X, V, E, UE, IsXLHSInRHSPart, 6741 IsPostfixUpdate); 6742 } 6743 6744 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 6745 Stmt *AStmt, 6746 SourceLocation StartLoc, 6747 SourceLocation EndLoc) { 6748 if (!AStmt) 6749 return StmtError(); 6750 6751 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6752 // 1.2.2 OpenMP Language Terminology 6753 // Structured block - An executable statement with a single entry at the 6754 // top and a single exit at the bottom. 6755 // The point of exit cannot be a branch out of the structured block. 6756 // longjmp() and throw() must not violate the entry/exit criteria. 6757 CS->getCapturedDecl()->setNothrow(); 6758 6759 // OpenMP [2.16, Nesting of Regions] 6760 // If specified, a teams construct must be contained within a target 6761 // construct. That target construct must contain no statements or directives 6762 // outside of the teams construct. 6763 if (DSAStack->hasInnerTeamsRegion()) { 6764 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 6765 bool OMPTeamsFound = true; 6766 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 6767 auto I = CS->body_begin(); 6768 while (I != CS->body_end()) { 6769 auto OED = dyn_cast<OMPExecutableDirective>(*I); 6770 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 6771 OMPTeamsFound = false; 6772 break; 6773 } 6774 ++I; 6775 } 6776 assert(I != CS->body_end() && "Not found statement"); 6777 S = *I; 6778 } else { 6779 auto *OED = dyn_cast<OMPExecutableDirective>(S); 6780 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 6781 } 6782 if (!OMPTeamsFound) { 6783 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 6784 Diag(DSAStack->getInnerTeamsRegionLoc(), 6785 diag::note_omp_nested_teams_construct_here); 6786 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 6787 << isa<OMPExecutableDirective>(S); 6788 return StmtError(); 6789 } 6790 } 6791 6792 getCurFunction()->setHasBranchProtectedScope(); 6793 6794 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6795 } 6796 6797 StmtResult 6798 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 6799 Stmt *AStmt, SourceLocation StartLoc, 6800 SourceLocation EndLoc) { 6801 if (!AStmt) 6802 return StmtError(); 6803 6804 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6805 // 1.2.2 OpenMP Language Terminology 6806 // Structured block - An executable statement with a single entry at the 6807 // top and a single exit at the bottom. 6808 // The point of exit cannot be a branch out of the structured block. 6809 // longjmp() and throw() must not violate the entry/exit criteria. 6810 CS->getCapturedDecl()->setNothrow(); 6811 6812 getCurFunction()->setHasBranchProtectedScope(); 6813 6814 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6815 AStmt); 6816 } 6817 6818 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 6819 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6820 SourceLocation EndLoc, 6821 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6822 if (!AStmt) 6823 return StmtError(); 6824 6825 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6826 // 1.2.2 OpenMP Language Terminology 6827 // Structured block - An executable statement with a single entry at the 6828 // top and a single exit at the bottom. 6829 // The point of exit cannot be a branch out of the structured block. 6830 // longjmp() and throw() must not violate the entry/exit criteria. 6831 CS->getCapturedDecl()->setNothrow(); 6832 6833 OMPLoopDirective::HelperExprs B; 6834 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6835 // define the nested loops number. 6836 unsigned NestedLoopCount = 6837 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 6838 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6839 VarsWithImplicitDSA, B); 6840 if (NestedLoopCount == 0) 6841 return StmtError(); 6842 6843 assert((CurContext->isDependentContext() || B.builtAll()) && 6844 "omp target parallel for loop exprs were not built"); 6845 6846 if (!CurContext->isDependentContext()) { 6847 // Finalize the clauses that need pre-built expressions for CodeGen. 6848 for (auto C : Clauses) { 6849 if (auto LC = dyn_cast<OMPLinearClause>(C)) 6850 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6851 B.NumIterations, *this, CurScope, 6852 DSAStack)) 6853 return StmtError(); 6854 } 6855 } 6856 6857 getCurFunction()->setHasBranchProtectedScope(); 6858 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 6859 NestedLoopCount, Clauses, AStmt, 6860 B, DSAStack->isCancelRegion()); 6861 } 6862 6863 /// \brief Check for existence of a map clause in the list of clauses. 6864 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) { 6865 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end(); 6866 I != E; ++I) { 6867 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) { 6868 return true; 6869 } 6870 } 6871 6872 return false; 6873 } 6874 6875 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 6876 Stmt *AStmt, 6877 SourceLocation StartLoc, 6878 SourceLocation EndLoc) { 6879 if (!AStmt) 6880 return StmtError(); 6881 6882 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6883 6884 // OpenMP [2.10.1, Restrictions, p. 97] 6885 // At least one map clause must appear on the directive. 6886 if (!HasMapClause(Clauses)) { 6887 Diag(StartLoc, diag::err_omp_no_map_for_directive) << 6888 getOpenMPDirectiveName(OMPD_target_data); 6889 return StmtError(); 6890 } 6891 6892 getCurFunction()->setHasBranchProtectedScope(); 6893 6894 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6895 AStmt); 6896 } 6897 6898 StmtResult 6899 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 6900 SourceLocation StartLoc, 6901 SourceLocation EndLoc) { 6902 // OpenMP [2.10.2, Restrictions, p. 99] 6903 // At least one map clause must appear on the directive. 6904 if (!HasMapClause(Clauses)) { 6905 Diag(StartLoc, diag::err_omp_no_map_for_directive) 6906 << getOpenMPDirectiveName(OMPD_target_enter_data); 6907 return StmtError(); 6908 } 6909 6910 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, 6911 Clauses); 6912 } 6913 6914 StmtResult 6915 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 6916 SourceLocation StartLoc, 6917 SourceLocation EndLoc) { 6918 // OpenMP [2.10.3, Restrictions, p. 102] 6919 // At least one map clause must appear on the directive. 6920 if (!HasMapClause(Clauses)) { 6921 Diag(StartLoc, diag::err_omp_no_map_for_directive) 6922 << getOpenMPDirectiveName(OMPD_target_exit_data); 6923 return StmtError(); 6924 } 6925 6926 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses); 6927 } 6928 6929 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 6930 SourceLocation StartLoc, 6931 SourceLocation EndLoc) { 6932 bool seenMotionClause = false; 6933 for (auto *C : Clauses) { 6934 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from) 6935 seenMotionClause = true; 6936 } 6937 if (!seenMotionClause) { 6938 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 6939 return StmtError(); 6940 } 6941 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses); 6942 } 6943 6944 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 6945 Stmt *AStmt, SourceLocation StartLoc, 6946 SourceLocation EndLoc) { 6947 if (!AStmt) 6948 return StmtError(); 6949 6950 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6951 // 1.2.2 OpenMP Language Terminology 6952 // Structured block - An executable statement with a single entry at the 6953 // top and a single exit at the bottom. 6954 // The point of exit cannot be a branch out of the structured block. 6955 // longjmp() and throw() must not violate the entry/exit criteria. 6956 CS->getCapturedDecl()->setNothrow(); 6957 6958 getCurFunction()->setHasBranchProtectedScope(); 6959 6960 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6961 } 6962 6963 StmtResult 6964 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 6965 SourceLocation EndLoc, 6966 OpenMPDirectiveKind CancelRegion) { 6967 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for && 6968 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) { 6969 Diag(StartLoc, diag::err_omp_wrong_cancel_region) 6970 << getOpenMPDirectiveName(CancelRegion); 6971 return StmtError(); 6972 } 6973 if (DSAStack->isParentNowaitRegion()) { 6974 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 6975 return StmtError(); 6976 } 6977 if (DSAStack->isParentOrderedRegion()) { 6978 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 6979 return StmtError(); 6980 } 6981 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 6982 CancelRegion); 6983 } 6984 6985 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 6986 SourceLocation StartLoc, 6987 SourceLocation EndLoc, 6988 OpenMPDirectiveKind CancelRegion) { 6989 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for && 6990 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) { 6991 Diag(StartLoc, diag::err_omp_wrong_cancel_region) 6992 << getOpenMPDirectiveName(CancelRegion); 6993 return StmtError(); 6994 } 6995 if (DSAStack->isParentNowaitRegion()) { 6996 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 6997 return StmtError(); 6998 } 6999 if (DSAStack->isParentOrderedRegion()) { 7000 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 7001 return StmtError(); 7002 } 7003 DSAStack->setParentCancelRegion(/*Cancel=*/true); 7004 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 7005 CancelRegion); 7006 } 7007 7008 static bool checkGrainsizeNumTasksClauses(Sema &S, 7009 ArrayRef<OMPClause *> Clauses) { 7010 OMPClause *PrevClause = nullptr; 7011 bool ErrorFound = false; 7012 for (auto *C : Clauses) { 7013 if (C->getClauseKind() == OMPC_grainsize || 7014 C->getClauseKind() == OMPC_num_tasks) { 7015 if (!PrevClause) 7016 PrevClause = C; 7017 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 7018 S.Diag(C->getLocStart(), 7019 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 7020 << getOpenMPClauseName(C->getClauseKind()) 7021 << getOpenMPClauseName(PrevClause->getClauseKind()); 7022 S.Diag(PrevClause->getLocStart(), 7023 diag::note_omp_previous_grainsize_num_tasks) 7024 << getOpenMPClauseName(PrevClause->getClauseKind()); 7025 ErrorFound = true; 7026 } 7027 } 7028 } 7029 return ErrorFound; 7030 } 7031 7032 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 7033 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7034 SourceLocation EndLoc, 7035 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7036 if (!AStmt) 7037 return StmtError(); 7038 7039 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7040 OMPLoopDirective::HelperExprs B; 7041 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7042 // define the nested loops number. 7043 unsigned NestedLoopCount = 7044 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 7045 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 7046 VarsWithImplicitDSA, B); 7047 if (NestedLoopCount == 0) 7048 return StmtError(); 7049 7050 assert((CurContext->isDependentContext() || B.builtAll()) && 7051 "omp for loop exprs were not built"); 7052 7053 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7054 // The grainsize clause and num_tasks clause are mutually exclusive and may 7055 // not appear on the same taskloop directive. 7056 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 7057 return StmtError(); 7058 7059 getCurFunction()->setHasBranchProtectedScope(); 7060 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 7061 NestedLoopCount, Clauses, AStmt, B); 7062 } 7063 7064 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 7065 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7066 SourceLocation EndLoc, 7067 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7068 if (!AStmt) 7069 return StmtError(); 7070 7071 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7072 OMPLoopDirective::HelperExprs B; 7073 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7074 // define the nested loops number. 7075 unsigned NestedLoopCount = 7076 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 7077 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 7078 VarsWithImplicitDSA, B); 7079 if (NestedLoopCount == 0) 7080 return StmtError(); 7081 7082 assert((CurContext->isDependentContext() || B.builtAll()) && 7083 "omp for loop exprs were not built"); 7084 7085 if (!CurContext->isDependentContext()) { 7086 // Finalize the clauses that need pre-built expressions for CodeGen. 7087 for (auto C : Clauses) { 7088 if (auto LC = dyn_cast<OMPLinearClause>(C)) 7089 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7090 B.NumIterations, *this, CurScope, 7091 DSAStack)) 7092 return StmtError(); 7093 } 7094 } 7095 7096 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7097 // The grainsize clause and num_tasks clause are mutually exclusive and may 7098 // not appear on the same taskloop directive. 7099 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 7100 return StmtError(); 7101 7102 getCurFunction()->setHasBranchProtectedScope(); 7103 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 7104 NestedLoopCount, Clauses, AStmt, B); 7105 } 7106 7107 StmtResult Sema::ActOnOpenMPDistributeDirective( 7108 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7109 SourceLocation EndLoc, 7110 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7111 if (!AStmt) 7112 return StmtError(); 7113 7114 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7115 OMPLoopDirective::HelperExprs B; 7116 // In presence of clause 'collapse' with number of loops, it will 7117 // define the nested loops number. 7118 unsigned NestedLoopCount = 7119 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 7120 nullptr /*ordered not a clause on distribute*/, AStmt, 7121 *this, *DSAStack, VarsWithImplicitDSA, B); 7122 if (NestedLoopCount == 0) 7123 return StmtError(); 7124 7125 assert((CurContext->isDependentContext() || B.builtAll()) && 7126 "omp for loop exprs were not built"); 7127 7128 getCurFunction()->setHasBranchProtectedScope(); 7129 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 7130 NestedLoopCount, Clauses, AStmt, B); 7131 } 7132 7133 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 7134 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7135 SourceLocation EndLoc, 7136 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7137 if (!AStmt) 7138 return StmtError(); 7139 7140 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7141 // 1.2.2 OpenMP Language Terminology 7142 // Structured block - An executable statement with a single entry at the 7143 // top and a single exit at the bottom. 7144 // The point of exit cannot be a branch out of the structured block. 7145 // longjmp() and throw() must not violate the entry/exit criteria. 7146 CS->getCapturedDecl()->setNothrow(); 7147 7148 OMPLoopDirective::HelperExprs B; 7149 // In presence of clause 'collapse' with number of loops, it will 7150 // define the nested loops number. 7151 unsigned NestedLoopCount = CheckOpenMPLoop( 7152 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7153 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7154 VarsWithImplicitDSA, B); 7155 if (NestedLoopCount == 0) 7156 return StmtError(); 7157 7158 assert((CurContext->isDependentContext() || B.builtAll()) && 7159 "omp for loop exprs were not built"); 7160 7161 getCurFunction()->setHasBranchProtectedScope(); 7162 return OMPDistributeParallelForDirective::Create( 7163 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7164 } 7165 7166 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 7167 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7168 SourceLocation EndLoc, 7169 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7170 if (!AStmt) 7171 return StmtError(); 7172 7173 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7174 // 1.2.2 OpenMP Language Terminology 7175 // Structured block - An executable statement with a single entry at the 7176 // top and a single exit at the bottom. 7177 // The point of exit cannot be a branch out of the structured block. 7178 // longjmp() and throw() must not violate the entry/exit criteria. 7179 CS->getCapturedDecl()->setNothrow(); 7180 7181 OMPLoopDirective::HelperExprs B; 7182 // In presence of clause 'collapse' with number of loops, it will 7183 // define the nested loops number. 7184 unsigned NestedLoopCount = CheckOpenMPLoop( 7185 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 7186 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7187 VarsWithImplicitDSA, B); 7188 if (NestedLoopCount == 0) 7189 return StmtError(); 7190 7191 assert((CurContext->isDependentContext() || B.builtAll()) && 7192 "omp for loop exprs were not built"); 7193 7194 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7195 return StmtError(); 7196 7197 getCurFunction()->setHasBranchProtectedScope(); 7198 return OMPDistributeParallelForSimdDirective::Create( 7199 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7200 } 7201 7202 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 7203 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7204 SourceLocation EndLoc, 7205 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7206 if (!AStmt) 7207 return StmtError(); 7208 7209 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7210 // 1.2.2 OpenMP Language Terminology 7211 // Structured block - An executable statement with a single entry at the 7212 // top and a single exit at the bottom. 7213 // The point of exit cannot be a branch out of the structured block. 7214 // longjmp() and throw() must not violate the entry/exit criteria. 7215 CS->getCapturedDecl()->setNothrow(); 7216 7217 OMPLoopDirective::HelperExprs B; 7218 // In presence of clause 'collapse' with number of loops, it will 7219 // define the nested loops number. 7220 unsigned NestedLoopCount = 7221 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 7222 nullptr /*ordered not a clause on distribute*/, AStmt, 7223 *this, *DSAStack, VarsWithImplicitDSA, B); 7224 if (NestedLoopCount == 0) 7225 return StmtError(); 7226 7227 assert((CurContext->isDependentContext() || B.builtAll()) && 7228 "omp for loop exprs were not built"); 7229 7230 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7231 return StmtError(); 7232 7233 getCurFunction()->setHasBranchProtectedScope(); 7234 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 7235 NestedLoopCount, Clauses, AStmt, B); 7236 } 7237 7238 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 7239 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7240 SourceLocation EndLoc, 7241 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7242 if (!AStmt) 7243 return StmtError(); 7244 7245 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7246 // 1.2.2 OpenMP Language Terminology 7247 // Structured block - An executable statement with a single entry at the 7248 // top and a single exit at the bottom. 7249 // The point of exit cannot be a branch out of the structured block. 7250 // longjmp() and throw() must not violate the entry/exit criteria. 7251 CS->getCapturedDecl()->setNothrow(); 7252 7253 OMPLoopDirective::HelperExprs B; 7254 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7255 // define the nested loops number. 7256 unsigned NestedLoopCount = CheckOpenMPLoop( 7257 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 7258 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 7259 VarsWithImplicitDSA, B); 7260 if (NestedLoopCount == 0) 7261 return StmtError(); 7262 7263 assert((CurContext->isDependentContext() || B.builtAll()) && 7264 "omp target parallel for simd loop exprs were not built"); 7265 7266 if (!CurContext->isDependentContext()) { 7267 // Finalize the clauses that need pre-built expressions for CodeGen. 7268 for (auto C : Clauses) { 7269 if (auto LC = dyn_cast<OMPLinearClause>(C)) 7270 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7271 B.NumIterations, *this, CurScope, 7272 DSAStack)) 7273 return StmtError(); 7274 } 7275 } 7276 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7277 return StmtError(); 7278 7279 getCurFunction()->setHasBranchProtectedScope(); 7280 return OMPTargetParallelForSimdDirective::Create( 7281 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7282 } 7283 7284 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 7285 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7286 SourceLocation EndLoc, 7287 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7288 if (!AStmt) 7289 return StmtError(); 7290 7291 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7292 // 1.2.2 OpenMP Language Terminology 7293 // Structured block - An executable statement with a single entry at the 7294 // top and a single exit at the bottom. 7295 // The point of exit cannot be a branch out of the structured block. 7296 // longjmp() and throw() must not violate the entry/exit criteria. 7297 CS->getCapturedDecl()->setNothrow(); 7298 7299 OMPLoopDirective::HelperExprs B; 7300 // In presence of clause 'collapse' with number of loops, it will define the 7301 // nested loops number. 7302 unsigned NestedLoopCount = 7303 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 7304 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 7305 VarsWithImplicitDSA, B); 7306 if (NestedLoopCount == 0) 7307 return StmtError(); 7308 7309 assert((CurContext->isDependentContext() || B.builtAll()) && 7310 "omp target simd loop exprs were not built"); 7311 7312 if (!CurContext->isDependentContext()) { 7313 // Finalize the clauses that need pre-built expressions for CodeGen. 7314 for (auto C : Clauses) { 7315 if (auto LC = dyn_cast<OMPLinearClause>(C)) 7316 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7317 B.NumIterations, *this, CurScope, 7318 DSAStack)) 7319 return StmtError(); 7320 } 7321 } 7322 7323 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7324 return StmtError(); 7325 7326 getCurFunction()->setHasBranchProtectedScope(); 7327 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 7328 NestedLoopCount, Clauses, AStmt, B); 7329 } 7330 7331 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 7332 SourceLocation StartLoc, 7333 SourceLocation LParenLoc, 7334 SourceLocation EndLoc) { 7335 OMPClause *Res = nullptr; 7336 switch (Kind) { 7337 case OMPC_final: 7338 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 7339 break; 7340 case OMPC_num_threads: 7341 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 7342 break; 7343 case OMPC_safelen: 7344 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 7345 break; 7346 case OMPC_simdlen: 7347 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 7348 break; 7349 case OMPC_collapse: 7350 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 7351 break; 7352 case OMPC_ordered: 7353 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 7354 break; 7355 case OMPC_device: 7356 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 7357 break; 7358 case OMPC_num_teams: 7359 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 7360 break; 7361 case OMPC_thread_limit: 7362 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 7363 break; 7364 case OMPC_priority: 7365 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 7366 break; 7367 case OMPC_grainsize: 7368 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 7369 break; 7370 case OMPC_num_tasks: 7371 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 7372 break; 7373 case OMPC_hint: 7374 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 7375 break; 7376 case OMPC_if: 7377 case OMPC_default: 7378 case OMPC_proc_bind: 7379 case OMPC_schedule: 7380 case OMPC_private: 7381 case OMPC_firstprivate: 7382 case OMPC_lastprivate: 7383 case OMPC_shared: 7384 case OMPC_reduction: 7385 case OMPC_linear: 7386 case OMPC_aligned: 7387 case OMPC_copyin: 7388 case OMPC_copyprivate: 7389 case OMPC_nowait: 7390 case OMPC_untied: 7391 case OMPC_mergeable: 7392 case OMPC_threadprivate: 7393 case OMPC_flush: 7394 case OMPC_read: 7395 case OMPC_write: 7396 case OMPC_update: 7397 case OMPC_capture: 7398 case OMPC_seq_cst: 7399 case OMPC_depend: 7400 case OMPC_threads: 7401 case OMPC_simd: 7402 case OMPC_map: 7403 case OMPC_nogroup: 7404 case OMPC_dist_schedule: 7405 case OMPC_defaultmap: 7406 case OMPC_unknown: 7407 case OMPC_uniform: 7408 case OMPC_to: 7409 case OMPC_from: 7410 case OMPC_use_device_ptr: 7411 case OMPC_is_device_ptr: 7412 llvm_unreachable("Clause is not allowed."); 7413 } 7414 return Res; 7415 } 7416 7417 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 7418 Expr *Condition, SourceLocation StartLoc, 7419 SourceLocation LParenLoc, 7420 SourceLocation NameModifierLoc, 7421 SourceLocation ColonLoc, 7422 SourceLocation EndLoc) { 7423 Expr *ValExpr = Condition; 7424 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7425 !Condition->isInstantiationDependent() && 7426 !Condition->containsUnexpandedParameterPack()) { 7427 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7428 if (Val.isInvalid()) 7429 return nullptr; 7430 7431 ValExpr = MakeFullExpr(Val.get()).get(); 7432 } 7433 7434 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc, 7435 NameModifierLoc, ColonLoc, EndLoc); 7436 } 7437 7438 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 7439 SourceLocation StartLoc, 7440 SourceLocation LParenLoc, 7441 SourceLocation EndLoc) { 7442 Expr *ValExpr = Condition; 7443 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7444 !Condition->isInstantiationDependent() && 7445 !Condition->containsUnexpandedParameterPack()) { 7446 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7447 if (Val.isInvalid()) 7448 return nullptr; 7449 7450 ValExpr = MakeFullExpr(Val.get()).get(); 7451 } 7452 7453 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 7454 } 7455 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 7456 Expr *Op) { 7457 if (!Op) 7458 return ExprError(); 7459 7460 class IntConvertDiagnoser : public ICEConvertDiagnoser { 7461 public: 7462 IntConvertDiagnoser() 7463 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 7464 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 7465 QualType T) override { 7466 return S.Diag(Loc, diag::err_omp_not_integral) << T; 7467 } 7468 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 7469 QualType T) override { 7470 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 7471 } 7472 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 7473 QualType T, 7474 QualType ConvTy) override { 7475 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 7476 } 7477 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 7478 QualType ConvTy) override { 7479 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7480 << ConvTy->isEnumeralType() << ConvTy; 7481 } 7482 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 7483 QualType T) override { 7484 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 7485 } 7486 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 7487 QualType ConvTy) override { 7488 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7489 << ConvTy->isEnumeralType() << ConvTy; 7490 } 7491 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 7492 QualType) override { 7493 llvm_unreachable("conversion functions are permitted"); 7494 } 7495 } ConvertDiagnoser; 7496 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 7497 } 7498 7499 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 7500 OpenMPClauseKind CKind, 7501 bool StrictlyPositive) { 7502 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 7503 !ValExpr->isInstantiationDependent()) { 7504 SourceLocation Loc = ValExpr->getExprLoc(); 7505 ExprResult Value = 7506 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 7507 if (Value.isInvalid()) 7508 return false; 7509 7510 ValExpr = Value.get(); 7511 // The expression must evaluate to a non-negative integer value. 7512 llvm::APSInt Result; 7513 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 7514 Result.isSigned() && 7515 !((!StrictlyPositive && Result.isNonNegative()) || 7516 (StrictlyPositive && Result.isStrictlyPositive()))) { 7517 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 7518 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7519 << ValExpr->getSourceRange(); 7520 return false; 7521 } 7522 } 7523 return true; 7524 } 7525 7526 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 7527 SourceLocation StartLoc, 7528 SourceLocation LParenLoc, 7529 SourceLocation EndLoc) { 7530 Expr *ValExpr = NumThreads; 7531 7532 // OpenMP [2.5, Restrictions] 7533 // The num_threads expression must evaluate to a positive integer value. 7534 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 7535 /*StrictlyPositive=*/true)) 7536 return nullptr; 7537 7538 return new (Context) 7539 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc); 7540 } 7541 7542 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 7543 OpenMPClauseKind CKind, 7544 bool StrictlyPositive) { 7545 if (!E) 7546 return ExprError(); 7547 if (E->isValueDependent() || E->isTypeDependent() || 7548 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 7549 return E; 7550 llvm::APSInt Result; 7551 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 7552 if (ICE.isInvalid()) 7553 return ExprError(); 7554 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 7555 (!StrictlyPositive && !Result.isNonNegative())) { 7556 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 7557 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7558 << E->getSourceRange(); 7559 return ExprError(); 7560 } 7561 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 7562 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 7563 << E->getSourceRange(); 7564 return ExprError(); 7565 } 7566 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 7567 DSAStack->setAssociatedLoops(Result.getExtValue()); 7568 else if (CKind == OMPC_ordered) 7569 DSAStack->setAssociatedLoops(Result.getExtValue()); 7570 return ICE; 7571 } 7572 7573 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 7574 SourceLocation LParenLoc, 7575 SourceLocation EndLoc) { 7576 // OpenMP [2.8.1, simd construct, Description] 7577 // The parameter of the safelen clause must be a constant 7578 // positive integer expression. 7579 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 7580 if (Safelen.isInvalid()) 7581 return nullptr; 7582 return new (Context) 7583 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 7584 } 7585 7586 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 7587 SourceLocation LParenLoc, 7588 SourceLocation EndLoc) { 7589 // OpenMP [2.8.1, simd construct, Description] 7590 // The parameter of the simdlen clause must be a constant 7591 // positive integer expression. 7592 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 7593 if (Simdlen.isInvalid()) 7594 return nullptr; 7595 return new (Context) 7596 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 7597 } 7598 7599 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 7600 SourceLocation StartLoc, 7601 SourceLocation LParenLoc, 7602 SourceLocation EndLoc) { 7603 // OpenMP [2.7.1, loop construct, Description] 7604 // OpenMP [2.8.1, simd construct, Description] 7605 // OpenMP [2.9.6, distribute construct, Description] 7606 // The parameter of the collapse clause must be a constant 7607 // positive integer expression. 7608 ExprResult NumForLoopsResult = 7609 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 7610 if (NumForLoopsResult.isInvalid()) 7611 return nullptr; 7612 return new (Context) 7613 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 7614 } 7615 7616 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 7617 SourceLocation EndLoc, 7618 SourceLocation LParenLoc, 7619 Expr *NumForLoops) { 7620 // OpenMP [2.7.1, loop construct, Description] 7621 // OpenMP [2.8.1, simd construct, Description] 7622 // OpenMP [2.9.6, distribute construct, Description] 7623 // The parameter of the ordered clause must be a constant 7624 // positive integer expression if any. 7625 if (NumForLoops && LParenLoc.isValid()) { 7626 ExprResult NumForLoopsResult = 7627 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 7628 if (NumForLoopsResult.isInvalid()) 7629 return nullptr; 7630 NumForLoops = NumForLoopsResult.get(); 7631 } else 7632 NumForLoops = nullptr; 7633 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 7634 return new (Context) 7635 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 7636 } 7637 7638 OMPClause *Sema::ActOnOpenMPSimpleClause( 7639 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 7640 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 7641 OMPClause *Res = nullptr; 7642 switch (Kind) { 7643 case OMPC_default: 7644 Res = 7645 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 7646 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 7647 break; 7648 case OMPC_proc_bind: 7649 Res = ActOnOpenMPProcBindClause( 7650 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 7651 LParenLoc, EndLoc); 7652 break; 7653 case OMPC_if: 7654 case OMPC_final: 7655 case OMPC_num_threads: 7656 case OMPC_safelen: 7657 case OMPC_simdlen: 7658 case OMPC_collapse: 7659 case OMPC_schedule: 7660 case OMPC_private: 7661 case OMPC_firstprivate: 7662 case OMPC_lastprivate: 7663 case OMPC_shared: 7664 case OMPC_reduction: 7665 case OMPC_linear: 7666 case OMPC_aligned: 7667 case OMPC_copyin: 7668 case OMPC_copyprivate: 7669 case OMPC_ordered: 7670 case OMPC_nowait: 7671 case OMPC_untied: 7672 case OMPC_mergeable: 7673 case OMPC_threadprivate: 7674 case OMPC_flush: 7675 case OMPC_read: 7676 case OMPC_write: 7677 case OMPC_update: 7678 case OMPC_capture: 7679 case OMPC_seq_cst: 7680 case OMPC_depend: 7681 case OMPC_device: 7682 case OMPC_threads: 7683 case OMPC_simd: 7684 case OMPC_map: 7685 case OMPC_num_teams: 7686 case OMPC_thread_limit: 7687 case OMPC_priority: 7688 case OMPC_grainsize: 7689 case OMPC_nogroup: 7690 case OMPC_num_tasks: 7691 case OMPC_hint: 7692 case OMPC_dist_schedule: 7693 case OMPC_defaultmap: 7694 case OMPC_unknown: 7695 case OMPC_uniform: 7696 case OMPC_to: 7697 case OMPC_from: 7698 case OMPC_use_device_ptr: 7699 case OMPC_is_device_ptr: 7700 llvm_unreachable("Clause is not allowed."); 7701 } 7702 return Res; 7703 } 7704 7705 static std::string 7706 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 7707 ArrayRef<unsigned> Exclude = llvm::None) { 7708 std::string Values; 7709 unsigned Bound = Last >= 2 ? Last - 2 : 0; 7710 unsigned Skipped = Exclude.size(); 7711 auto S = Exclude.begin(), E = Exclude.end(); 7712 for (unsigned i = First; i < Last; ++i) { 7713 if (std::find(S, E, i) != E) { 7714 --Skipped; 7715 continue; 7716 } 7717 Values += "'"; 7718 Values += getOpenMPSimpleClauseTypeName(K, i); 7719 Values += "'"; 7720 if (i == Bound - Skipped) 7721 Values += " or "; 7722 else if (i != Bound + 1 - Skipped) 7723 Values += ", "; 7724 } 7725 return Values; 7726 } 7727 7728 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 7729 SourceLocation KindKwLoc, 7730 SourceLocation StartLoc, 7731 SourceLocation LParenLoc, 7732 SourceLocation EndLoc) { 7733 if (Kind == OMPC_DEFAULT_unknown) { 7734 static_assert(OMPC_DEFAULT_unknown > 0, 7735 "OMPC_DEFAULT_unknown not greater than 0"); 7736 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7737 << getListOfPossibleValues(OMPC_default, /*First=*/0, 7738 /*Last=*/OMPC_DEFAULT_unknown) 7739 << getOpenMPClauseName(OMPC_default); 7740 return nullptr; 7741 } 7742 switch (Kind) { 7743 case OMPC_DEFAULT_none: 7744 DSAStack->setDefaultDSANone(KindKwLoc); 7745 break; 7746 case OMPC_DEFAULT_shared: 7747 DSAStack->setDefaultDSAShared(KindKwLoc); 7748 break; 7749 case OMPC_DEFAULT_unknown: 7750 llvm_unreachable("Clause kind is not allowed."); 7751 break; 7752 } 7753 return new (Context) 7754 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7755 } 7756 7757 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 7758 SourceLocation KindKwLoc, 7759 SourceLocation StartLoc, 7760 SourceLocation LParenLoc, 7761 SourceLocation EndLoc) { 7762 if (Kind == OMPC_PROC_BIND_unknown) { 7763 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7764 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 7765 /*Last=*/OMPC_PROC_BIND_unknown) 7766 << getOpenMPClauseName(OMPC_proc_bind); 7767 return nullptr; 7768 } 7769 return new (Context) 7770 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7771 } 7772 7773 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 7774 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 7775 SourceLocation StartLoc, SourceLocation LParenLoc, 7776 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 7777 SourceLocation EndLoc) { 7778 OMPClause *Res = nullptr; 7779 switch (Kind) { 7780 case OMPC_schedule: 7781 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 7782 assert(Argument.size() == NumberOfElements && 7783 ArgumentLoc.size() == NumberOfElements); 7784 Res = ActOnOpenMPScheduleClause( 7785 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 7786 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 7787 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 7788 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 7789 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 7790 break; 7791 case OMPC_if: 7792 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 7793 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 7794 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 7795 DelimLoc, EndLoc); 7796 break; 7797 case OMPC_dist_schedule: 7798 Res = ActOnOpenMPDistScheduleClause( 7799 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 7800 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 7801 break; 7802 case OMPC_defaultmap: 7803 enum { Modifier, DefaultmapKind }; 7804 Res = ActOnOpenMPDefaultmapClause( 7805 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 7806 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 7807 StartLoc, LParenLoc, ArgumentLoc[Modifier], 7808 ArgumentLoc[DefaultmapKind], EndLoc); 7809 break; 7810 case OMPC_final: 7811 case OMPC_num_threads: 7812 case OMPC_safelen: 7813 case OMPC_simdlen: 7814 case OMPC_collapse: 7815 case OMPC_default: 7816 case OMPC_proc_bind: 7817 case OMPC_private: 7818 case OMPC_firstprivate: 7819 case OMPC_lastprivate: 7820 case OMPC_shared: 7821 case OMPC_reduction: 7822 case OMPC_linear: 7823 case OMPC_aligned: 7824 case OMPC_copyin: 7825 case OMPC_copyprivate: 7826 case OMPC_ordered: 7827 case OMPC_nowait: 7828 case OMPC_untied: 7829 case OMPC_mergeable: 7830 case OMPC_threadprivate: 7831 case OMPC_flush: 7832 case OMPC_read: 7833 case OMPC_write: 7834 case OMPC_update: 7835 case OMPC_capture: 7836 case OMPC_seq_cst: 7837 case OMPC_depend: 7838 case OMPC_device: 7839 case OMPC_threads: 7840 case OMPC_simd: 7841 case OMPC_map: 7842 case OMPC_num_teams: 7843 case OMPC_thread_limit: 7844 case OMPC_priority: 7845 case OMPC_grainsize: 7846 case OMPC_nogroup: 7847 case OMPC_num_tasks: 7848 case OMPC_hint: 7849 case OMPC_unknown: 7850 case OMPC_uniform: 7851 case OMPC_to: 7852 case OMPC_from: 7853 case OMPC_use_device_ptr: 7854 case OMPC_is_device_ptr: 7855 llvm_unreachable("Clause is not allowed."); 7856 } 7857 return Res; 7858 } 7859 7860 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 7861 OpenMPScheduleClauseModifier M2, 7862 SourceLocation M1Loc, SourceLocation M2Loc) { 7863 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 7864 SmallVector<unsigned, 2> Excluded; 7865 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 7866 Excluded.push_back(M2); 7867 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 7868 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 7869 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 7870 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 7871 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 7872 << getListOfPossibleValues(OMPC_schedule, 7873 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 7874 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7875 Excluded) 7876 << getOpenMPClauseName(OMPC_schedule); 7877 return true; 7878 } 7879 return false; 7880 } 7881 7882 OMPClause *Sema::ActOnOpenMPScheduleClause( 7883 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 7884 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 7885 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 7886 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 7887 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 7888 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 7889 return nullptr; 7890 // OpenMP, 2.7.1, Loop Construct, Restrictions 7891 // Either the monotonic modifier or the nonmonotonic modifier can be specified 7892 // but not both. 7893 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 7894 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 7895 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 7896 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 7897 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 7898 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 7899 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 7900 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 7901 return nullptr; 7902 } 7903 if (Kind == OMPC_SCHEDULE_unknown) { 7904 std::string Values; 7905 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 7906 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 7907 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7908 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7909 Exclude); 7910 } else { 7911 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7912 /*Last=*/OMPC_SCHEDULE_unknown); 7913 } 7914 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 7915 << Values << getOpenMPClauseName(OMPC_schedule); 7916 return nullptr; 7917 } 7918 // OpenMP, 2.7.1, Loop Construct, Restrictions 7919 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 7920 // schedule(guided). 7921 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 7922 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 7923 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 7924 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 7925 diag::err_omp_schedule_nonmonotonic_static); 7926 return nullptr; 7927 } 7928 Expr *ValExpr = ChunkSize; 7929 Stmt *HelperValStmt = nullptr; 7930 if (ChunkSize) { 7931 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 7932 !ChunkSize->isInstantiationDependent() && 7933 !ChunkSize->containsUnexpandedParameterPack()) { 7934 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 7935 ExprResult Val = 7936 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 7937 if (Val.isInvalid()) 7938 return nullptr; 7939 7940 ValExpr = Val.get(); 7941 7942 // OpenMP [2.7.1, Restrictions] 7943 // chunk_size must be a loop invariant integer expression with a positive 7944 // value. 7945 llvm::APSInt Result; 7946 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 7947 if (Result.isSigned() && !Result.isStrictlyPositive()) { 7948 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 7949 << "schedule" << 1 << ChunkSize->getSourceRange(); 7950 return nullptr; 7951 } 7952 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 7953 !CurContext->isDependentContext()) { 7954 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7955 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7956 HelperValStmt = buildPreInits(Context, Captures); 7957 } 7958 } 7959 } 7960 7961 return new (Context) 7962 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 7963 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 7964 } 7965 7966 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 7967 SourceLocation StartLoc, 7968 SourceLocation EndLoc) { 7969 OMPClause *Res = nullptr; 7970 switch (Kind) { 7971 case OMPC_ordered: 7972 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 7973 break; 7974 case OMPC_nowait: 7975 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 7976 break; 7977 case OMPC_untied: 7978 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 7979 break; 7980 case OMPC_mergeable: 7981 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 7982 break; 7983 case OMPC_read: 7984 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 7985 break; 7986 case OMPC_write: 7987 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 7988 break; 7989 case OMPC_update: 7990 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 7991 break; 7992 case OMPC_capture: 7993 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 7994 break; 7995 case OMPC_seq_cst: 7996 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 7997 break; 7998 case OMPC_threads: 7999 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 8000 break; 8001 case OMPC_simd: 8002 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 8003 break; 8004 case OMPC_nogroup: 8005 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 8006 break; 8007 case OMPC_if: 8008 case OMPC_final: 8009 case OMPC_num_threads: 8010 case OMPC_safelen: 8011 case OMPC_simdlen: 8012 case OMPC_collapse: 8013 case OMPC_schedule: 8014 case OMPC_private: 8015 case OMPC_firstprivate: 8016 case OMPC_lastprivate: 8017 case OMPC_shared: 8018 case OMPC_reduction: 8019 case OMPC_linear: 8020 case OMPC_aligned: 8021 case OMPC_copyin: 8022 case OMPC_copyprivate: 8023 case OMPC_default: 8024 case OMPC_proc_bind: 8025 case OMPC_threadprivate: 8026 case OMPC_flush: 8027 case OMPC_depend: 8028 case OMPC_device: 8029 case OMPC_map: 8030 case OMPC_num_teams: 8031 case OMPC_thread_limit: 8032 case OMPC_priority: 8033 case OMPC_grainsize: 8034 case OMPC_num_tasks: 8035 case OMPC_hint: 8036 case OMPC_dist_schedule: 8037 case OMPC_defaultmap: 8038 case OMPC_unknown: 8039 case OMPC_uniform: 8040 case OMPC_to: 8041 case OMPC_from: 8042 case OMPC_use_device_ptr: 8043 case OMPC_is_device_ptr: 8044 llvm_unreachable("Clause is not allowed."); 8045 } 8046 return Res; 8047 } 8048 8049 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 8050 SourceLocation EndLoc) { 8051 DSAStack->setNowaitRegion(); 8052 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 8053 } 8054 8055 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 8056 SourceLocation EndLoc) { 8057 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 8058 } 8059 8060 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 8061 SourceLocation EndLoc) { 8062 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 8063 } 8064 8065 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 8066 SourceLocation EndLoc) { 8067 return new (Context) OMPReadClause(StartLoc, EndLoc); 8068 } 8069 8070 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 8071 SourceLocation EndLoc) { 8072 return new (Context) OMPWriteClause(StartLoc, EndLoc); 8073 } 8074 8075 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 8076 SourceLocation EndLoc) { 8077 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 8078 } 8079 8080 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 8081 SourceLocation EndLoc) { 8082 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 8083 } 8084 8085 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 8086 SourceLocation EndLoc) { 8087 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 8088 } 8089 8090 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 8091 SourceLocation EndLoc) { 8092 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 8093 } 8094 8095 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 8096 SourceLocation EndLoc) { 8097 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 8098 } 8099 8100 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 8101 SourceLocation EndLoc) { 8102 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 8103 } 8104 8105 OMPClause *Sema::ActOnOpenMPVarListClause( 8106 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 8107 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 8108 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 8109 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 8110 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 8111 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 8112 SourceLocation DepLinMapLoc) { 8113 OMPClause *Res = nullptr; 8114 switch (Kind) { 8115 case OMPC_private: 8116 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8117 break; 8118 case OMPC_firstprivate: 8119 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8120 break; 8121 case OMPC_lastprivate: 8122 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8123 break; 8124 case OMPC_shared: 8125 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 8126 break; 8127 case OMPC_reduction: 8128 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8129 EndLoc, ReductionIdScopeSpec, ReductionId); 8130 break; 8131 case OMPC_linear: 8132 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 8133 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 8134 break; 8135 case OMPC_aligned: 8136 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 8137 ColonLoc, EndLoc); 8138 break; 8139 case OMPC_copyin: 8140 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 8141 break; 8142 case OMPC_copyprivate: 8143 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8144 break; 8145 case OMPC_flush: 8146 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 8147 break; 8148 case OMPC_depend: 8149 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 8150 StartLoc, LParenLoc, EndLoc); 8151 break; 8152 case OMPC_map: 8153 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 8154 DepLinMapLoc, ColonLoc, VarList, StartLoc, 8155 LParenLoc, EndLoc); 8156 break; 8157 case OMPC_to: 8158 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 8159 break; 8160 case OMPC_from: 8161 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 8162 break; 8163 case OMPC_use_device_ptr: 8164 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 8165 break; 8166 case OMPC_is_device_ptr: 8167 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 8168 break; 8169 case OMPC_if: 8170 case OMPC_final: 8171 case OMPC_num_threads: 8172 case OMPC_safelen: 8173 case OMPC_simdlen: 8174 case OMPC_collapse: 8175 case OMPC_default: 8176 case OMPC_proc_bind: 8177 case OMPC_schedule: 8178 case OMPC_ordered: 8179 case OMPC_nowait: 8180 case OMPC_untied: 8181 case OMPC_mergeable: 8182 case OMPC_threadprivate: 8183 case OMPC_read: 8184 case OMPC_write: 8185 case OMPC_update: 8186 case OMPC_capture: 8187 case OMPC_seq_cst: 8188 case OMPC_device: 8189 case OMPC_threads: 8190 case OMPC_simd: 8191 case OMPC_num_teams: 8192 case OMPC_thread_limit: 8193 case OMPC_priority: 8194 case OMPC_grainsize: 8195 case OMPC_nogroup: 8196 case OMPC_num_tasks: 8197 case OMPC_hint: 8198 case OMPC_dist_schedule: 8199 case OMPC_defaultmap: 8200 case OMPC_unknown: 8201 case OMPC_uniform: 8202 llvm_unreachable("Clause is not allowed."); 8203 } 8204 return Res; 8205 } 8206 8207 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 8208 ExprObjectKind OK, SourceLocation Loc) { 8209 ExprResult Res = BuildDeclRefExpr( 8210 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 8211 if (!Res.isUsable()) 8212 return ExprError(); 8213 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 8214 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 8215 if (!Res.isUsable()) 8216 return ExprError(); 8217 } 8218 if (VK != VK_LValue && Res.get()->isGLValue()) { 8219 Res = DefaultLvalueConversion(Res.get()); 8220 if (!Res.isUsable()) 8221 return ExprError(); 8222 } 8223 return Res; 8224 } 8225 8226 static std::pair<ValueDecl *, bool> 8227 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 8228 SourceRange &ERange, bool AllowArraySection = false) { 8229 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 8230 RefExpr->containsUnexpandedParameterPack()) 8231 return std::make_pair(nullptr, true); 8232 8233 // OpenMP [3.1, C/C++] 8234 // A list item is a variable name. 8235 // OpenMP [2.9.3.3, Restrictions, p.1] 8236 // A variable that is part of another variable (as an array or 8237 // structure element) cannot appear in a private clause. 8238 RefExpr = RefExpr->IgnoreParens(); 8239 enum { 8240 NoArrayExpr = -1, 8241 ArraySubscript = 0, 8242 OMPArraySection = 1 8243 } IsArrayExpr = NoArrayExpr; 8244 if (AllowArraySection) { 8245 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 8246 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 8247 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 8248 Base = TempASE->getBase()->IgnoreParenImpCasts(); 8249 RefExpr = Base; 8250 IsArrayExpr = ArraySubscript; 8251 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 8252 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 8253 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 8254 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 8255 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 8256 Base = TempASE->getBase()->IgnoreParenImpCasts(); 8257 RefExpr = Base; 8258 IsArrayExpr = OMPArraySection; 8259 } 8260 } 8261 ELoc = RefExpr->getExprLoc(); 8262 ERange = RefExpr->getSourceRange(); 8263 RefExpr = RefExpr->IgnoreParenImpCasts(); 8264 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 8265 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 8266 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 8267 (S.getCurrentThisType().isNull() || !ME || 8268 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 8269 !isa<FieldDecl>(ME->getMemberDecl()))) { 8270 if (IsArrayExpr != NoArrayExpr) 8271 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 8272 << ERange; 8273 else { 8274 S.Diag(ELoc, 8275 AllowArraySection 8276 ? diag::err_omp_expected_var_name_member_expr_or_array_item 8277 : diag::err_omp_expected_var_name_member_expr) 8278 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 8279 } 8280 return std::make_pair(nullptr, false); 8281 } 8282 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false); 8283 } 8284 8285 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 8286 SourceLocation StartLoc, 8287 SourceLocation LParenLoc, 8288 SourceLocation EndLoc) { 8289 SmallVector<Expr *, 8> Vars; 8290 SmallVector<Expr *, 8> PrivateCopies; 8291 for (auto &RefExpr : VarList) { 8292 assert(RefExpr && "NULL expr in OpenMP private clause."); 8293 SourceLocation ELoc; 8294 SourceRange ERange; 8295 Expr *SimpleRefExpr = RefExpr; 8296 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8297 if (Res.second) { 8298 // It will be analyzed later. 8299 Vars.push_back(RefExpr); 8300 PrivateCopies.push_back(nullptr); 8301 } 8302 ValueDecl *D = Res.first; 8303 if (!D) 8304 continue; 8305 8306 QualType Type = D->getType(); 8307 auto *VD = dyn_cast<VarDecl>(D); 8308 8309 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8310 // A variable that appears in a private clause must not have an incomplete 8311 // type or a reference type. 8312 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 8313 continue; 8314 Type = Type.getNonReferenceType(); 8315 8316 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8317 // in a Construct] 8318 // Variables with the predetermined data-sharing attributes may not be 8319 // listed in data-sharing attributes clauses, except for the cases 8320 // listed below. For these exceptions only, listing a predetermined 8321 // variable in a data-sharing attribute clause is allowed and overrides 8322 // the variable's predetermined data-sharing attributes. 8323 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8324 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 8325 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8326 << getOpenMPClauseName(OMPC_private); 8327 ReportOriginalDSA(*this, DSAStack, D, DVar); 8328 continue; 8329 } 8330 8331 // Variably modified types are not supported for tasks. 8332 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8333 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 8334 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8335 << getOpenMPClauseName(OMPC_private) << Type 8336 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8337 bool IsDecl = 8338 !VD || 8339 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8340 Diag(D->getLocation(), 8341 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8342 << D; 8343 continue; 8344 } 8345 8346 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8347 // A list item cannot appear in both a map clause and a data-sharing 8348 // attribute clause on the same construct 8349 if (DSAStack->getCurrentDirective() == OMPD_target) { 8350 if (DSAStack->checkMappableExprComponentListsForDecl( 8351 VD, /* CurrentRegionOnly = */ true, 8352 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef) 8353 -> bool { return true; })) { 8354 Diag(ELoc, diag::err_omp_variable_in_map_and_dsa) 8355 << getOpenMPClauseName(OMPC_private) 8356 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8357 ReportOriginalDSA(*this, DSAStack, D, DVar); 8358 continue; 8359 } 8360 } 8361 8362 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 8363 // A variable of class type (or array thereof) that appears in a private 8364 // clause requires an accessible, unambiguous default constructor for the 8365 // class type. 8366 // Generate helper private variable and initialize it with the default 8367 // value. The address of the original variable is replaced by the address of 8368 // the new private variable in CodeGen. This new variable is not added to 8369 // IdResolver, so the code in the OpenMP region uses original variable for 8370 // proper diagnostics. 8371 Type = Type.getUnqualifiedType(); 8372 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8373 D->hasAttrs() ? &D->getAttrs() : nullptr); 8374 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false); 8375 if (VDPrivate->isInvalidDecl()) 8376 continue; 8377 auto VDPrivateRefExpr = buildDeclRefExpr( 8378 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 8379 8380 DeclRefExpr *Ref = nullptr; 8381 if (!VD && !CurContext->isDependentContext()) 8382 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8383 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 8384 Vars.push_back((VD || CurContext->isDependentContext()) 8385 ? RefExpr->IgnoreParens() 8386 : Ref); 8387 PrivateCopies.push_back(VDPrivateRefExpr); 8388 } 8389 8390 if (Vars.empty()) 8391 return nullptr; 8392 8393 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 8394 PrivateCopies); 8395 } 8396 8397 namespace { 8398 class DiagsUninitializedSeveretyRAII { 8399 private: 8400 DiagnosticsEngine &Diags; 8401 SourceLocation SavedLoc; 8402 bool IsIgnored; 8403 8404 public: 8405 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 8406 bool IsIgnored) 8407 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 8408 if (!IsIgnored) { 8409 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 8410 /*Map*/ diag::Severity::Ignored, Loc); 8411 } 8412 } 8413 ~DiagsUninitializedSeveretyRAII() { 8414 if (!IsIgnored) 8415 Diags.popMappings(SavedLoc); 8416 } 8417 }; 8418 } 8419 8420 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 8421 SourceLocation StartLoc, 8422 SourceLocation LParenLoc, 8423 SourceLocation EndLoc) { 8424 SmallVector<Expr *, 8> Vars; 8425 SmallVector<Expr *, 8> PrivateCopies; 8426 SmallVector<Expr *, 8> Inits; 8427 SmallVector<Decl *, 4> ExprCaptures; 8428 bool IsImplicitClause = 8429 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 8430 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 8431 8432 for (auto &RefExpr : VarList) { 8433 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 8434 SourceLocation ELoc; 8435 SourceRange ERange; 8436 Expr *SimpleRefExpr = RefExpr; 8437 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8438 if (Res.second) { 8439 // It will be analyzed later. 8440 Vars.push_back(RefExpr); 8441 PrivateCopies.push_back(nullptr); 8442 Inits.push_back(nullptr); 8443 } 8444 ValueDecl *D = Res.first; 8445 if (!D) 8446 continue; 8447 8448 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 8449 QualType Type = D->getType(); 8450 auto *VD = dyn_cast<VarDecl>(D); 8451 8452 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8453 // A variable that appears in a private clause must not have an incomplete 8454 // type or a reference type. 8455 if (RequireCompleteType(ELoc, Type, 8456 diag::err_omp_firstprivate_incomplete_type)) 8457 continue; 8458 Type = Type.getNonReferenceType(); 8459 8460 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 8461 // A variable of class type (or array thereof) that appears in a private 8462 // clause requires an accessible, unambiguous copy constructor for the 8463 // class type. 8464 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 8465 8466 // If an implicit firstprivate variable found it was checked already. 8467 DSAStackTy::DSAVarData TopDVar; 8468 if (!IsImplicitClause) { 8469 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8470 TopDVar = DVar; 8471 bool IsConstant = ElemType.isConstant(Context); 8472 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 8473 // A list item that specifies a given variable may not appear in more 8474 // than one clause on the same directive, except that a variable may be 8475 // specified in both firstprivate and lastprivate clauses. 8476 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 8477 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) { 8478 Diag(ELoc, diag::err_omp_wrong_dsa) 8479 << getOpenMPClauseName(DVar.CKind) 8480 << getOpenMPClauseName(OMPC_firstprivate); 8481 ReportOriginalDSA(*this, DSAStack, D, DVar); 8482 continue; 8483 } 8484 8485 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8486 // in a Construct] 8487 // Variables with the predetermined data-sharing attributes may not be 8488 // listed in data-sharing attributes clauses, except for the cases 8489 // listed below. For these exceptions only, listing a predetermined 8490 // variable in a data-sharing attribute clause is allowed and overrides 8491 // the variable's predetermined data-sharing attributes. 8492 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8493 // in a Construct, C/C++, p.2] 8494 // Variables with const-qualified type having no mutable member may be 8495 // listed in a firstprivate clause, even if they are static data members. 8496 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 8497 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 8498 Diag(ELoc, diag::err_omp_wrong_dsa) 8499 << getOpenMPClauseName(DVar.CKind) 8500 << getOpenMPClauseName(OMPC_firstprivate); 8501 ReportOriginalDSA(*this, DSAStack, D, DVar); 8502 continue; 8503 } 8504 8505 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8506 // OpenMP [2.9.3.4, Restrictions, p.2] 8507 // A list item that is private within a parallel region must not appear 8508 // in a firstprivate clause on a worksharing construct if any of the 8509 // worksharing regions arising from the worksharing construct ever bind 8510 // to any of the parallel regions arising from the parallel construct. 8511 if (isOpenMPWorksharingDirective(CurrDir) && 8512 !isOpenMPParallelDirective(CurrDir)) { 8513 DVar = DSAStack->getImplicitDSA(D, true); 8514 if (DVar.CKind != OMPC_shared && 8515 (isOpenMPParallelDirective(DVar.DKind) || 8516 DVar.DKind == OMPD_unknown)) { 8517 Diag(ELoc, diag::err_omp_required_access) 8518 << getOpenMPClauseName(OMPC_firstprivate) 8519 << getOpenMPClauseName(OMPC_shared); 8520 ReportOriginalDSA(*this, DSAStack, D, DVar); 8521 continue; 8522 } 8523 } 8524 // OpenMP [2.9.3.4, Restrictions, p.3] 8525 // A list item that appears in a reduction clause of a parallel construct 8526 // must not appear in a firstprivate clause on a worksharing or task 8527 // construct if any of the worksharing or task regions arising from the 8528 // worksharing or task construct ever bind to any of the parallel regions 8529 // arising from the parallel construct. 8530 // OpenMP [2.9.3.4, Restrictions, p.4] 8531 // A list item that appears in a reduction clause in worksharing 8532 // construct must not appear in a firstprivate clause in a task construct 8533 // encountered during execution of any of the worksharing regions arising 8534 // from the worksharing construct. 8535 if (isOpenMPTaskingDirective(CurrDir)) { 8536 DVar = DSAStack->hasInnermostDSA( 8537 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8538 [](OpenMPDirectiveKind K) -> bool { 8539 return isOpenMPParallelDirective(K) || 8540 isOpenMPWorksharingDirective(K); 8541 }, 8542 false); 8543 if (DVar.CKind == OMPC_reduction && 8544 (isOpenMPParallelDirective(DVar.DKind) || 8545 isOpenMPWorksharingDirective(DVar.DKind))) { 8546 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 8547 << getOpenMPDirectiveName(DVar.DKind); 8548 ReportOriginalDSA(*this, DSAStack, D, DVar); 8549 continue; 8550 } 8551 } 8552 8553 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8554 // A list item that is private within a teams region must not appear in a 8555 // firstprivate clause on a distribute construct if any of the distribute 8556 // regions arising from the distribute construct ever bind to any of the 8557 // teams regions arising from the teams construct. 8558 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8559 // A list item that appears in a reduction clause of a teams construct 8560 // must not appear in a firstprivate clause on a distribute construct if 8561 // any of the distribute regions arising from the distribute construct 8562 // ever bind to any of the teams regions arising from the teams construct. 8563 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8564 // A list item may appear in a firstprivate or lastprivate clause but not 8565 // both. 8566 if (CurrDir == OMPD_distribute) { 8567 DVar = DSAStack->hasInnermostDSA( 8568 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; }, 8569 [](OpenMPDirectiveKind K) -> bool { 8570 return isOpenMPTeamsDirective(K); 8571 }, 8572 false); 8573 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) { 8574 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams); 8575 ReportOriginalDSA(*this, DSAStack, D, DVar); 8576 continue; 8577 } 8578 DVar = DSAStack->hasInnermostDSA( 8579 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8580 [](OpenMPDirectiveKind K) -> bool { 8581 return isOpenMPTeamsDirective(K); 8582 }, 8583 false); 8584 if (DVar.CKind == OMPC_reduction && 8585 isOpenMPTeamsDirective(DVar.DKind)) { 8586 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction); 8587 ReportOriginalDSA(*this, DSAStack, D, DVar); 8588 continue; 8589 } 8590 DVar = DSAStack->getTopDSA(D, false); 8591 if (DVar.CKind == OMPC_lastprivate) { 8592 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8593 ReportOriginalDSA(*this, DSAStack, D, DVar); 8594 continue; 8595 } 8596 } 8597 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8598 // A list item cannot appear in both a map clause and a data-sharing 8599 // attribute clause on the same construct 8600 if (CurrDir == OMPD_target) { 8601 if (DSAStack->checkMappableExprComponentListsForDecl( 8602 VD, /* CurrentRegionOnly = */ true, 8603 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef) 8604 -> bool { return true; })) { 8605 Diag(ELoc, diag::err_omp_variable_in_map_and_dsa) 8606 << getOpenMPClauseName(OMPC_firstprivate) 8607 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8608 ReportOriginalDSA(*this, DSAStack, D, DVar); 8609 continue; 8610 } 8611 } 8612 } 8613 8614 // Variably modified types are not supported for tasks. 8615 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8616 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 8617 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8618 << getOpenMPClauseName(OMPC_firstprivate) << Type 8619 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8620 bool IsDecl = 8621 !VD || 8622 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8623 Diag(D->getLocation(), 8624 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8625 << D; 8626 continue; 8627 } 8628 8629 Type = Type.getUnqualifiedType(); 8630 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8631 D->hasAttrs() ? &D->getAttrs() : nullptr); 8632 // Generate helper private variable and initialize it with the value of the 8633 // original variable. The address of the original variable is replaced by 8634 // the address of the new private variable in the CodeGen. This new variable 8635 // is not added to IdResolver, so the code in the OpenMP region uses 8636 // original variable for proper diagnostics and variable capturing. 8637 Expr *VDInitRefExpr = nullptr; 8638 // For arrays generate initializer for single element and replace it by the 8639 // original array element in CodeGen. 8640 if (Type->isArrayType()) { 8641 auto VDInit = 8642 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 8643 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 8644 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 8645 ElemType = ElemType.getUnqualifiedType(); 8646 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 8647 ".firstprivate.temp"); 8648 InitializedEntity Entity = 8649 InitializedEntity::InitializeVariable(VDInitTemp); 8650 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 8651 8652 InitializationSequence InitSeq(*this, Entity, Kind, Init); 8653 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 8654 if (Result.isInvalid()) 8655 VDPrivate->setInvalidDecl(); 8656 else 8657 VDPrivate->setInit(Result.getAs<Expr>()); 8658 // Remove temp variable declaration. 8659 Context.Deallocate(VDInitTemp); 8660 } else { 8661 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 8662 ".firstprivate.temp"); 8663 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 8664 RefExpr->getExprLoc()); 8665 AddInitializerToDecl(VDPrivate, 8666 DefaultLvalueConversion(VDInitRefExpr).get(), 8667 /*DirectInit=*/false, /*TypeMayContainAuto=*/false); 8668 } 8669 if (VDPrivate->isInvalidDecl()) { 8670 if (IsImplicitClause) { 8671 Diag(RefExpr->getExprLoc(), 8672 diag::note_omp_task_predetermined_firstprivate_here); 8673 } 8674 continue; 8675 } 8676 CurContext->addDecl(VDPrivate); 8677 auto VDPrivateRefExpr = buildDeclRefExpr( 8678 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 8679 RefExpr->getExprLoc()); 8680 DeclRefExpr *Ref = nullptr; 8681 if (!VD && !CurContext->isDependentContext()) { 8682 if (TopDVar.CKind == OMPC_lastprivate) 8683 Ref = TopDVar.PrivateCopy; 8684 else { 8685 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8686 if (!IsOpenMPCapturedDecl(D)) 8687 ExprCaptures.push_back(Ref->getDecl()); 8688 } 8689 } 8690 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 8691 Vars.push_back((VD || CurContext->isDependentContext()) 8692 ? RefExpr->IgnoreParens() 8693 : Ref); 8694 PrivateCopies.push_back(VDPrivateRefExpr); 8695 Inits.push_back(VDInitRefExpr); 8696 } 8697 8698 if (Vars.empty()) 8699 return nullptr; 8700 8701 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8702 Vars, PrivateCopies, Inits, 8703 buildPreInits(Context, ExprCaptures)); 8704 } 8705 8706 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 8707 SourceLocation StartLoc, 8708 SourceLocation LParenLoc, 8709 SourceLocation EndLoc) { 8710 SmallVector<Expr *, 8> Vars; 8711 SmallVector<Expr *, 8> SrcExprs; 8712 SmallVector<Expr *, 8> DstExprs; 8713 SmallVector<Expr *, 8> AssignmentOps; 8714 SmallVector<Decl *, 4> ExprCaptures; 8715 SmallVector<Expr *, 4> ExprPostUpdates; 8716 for (auto &RefExpr : VarList) { 8717 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8718 SourceLocation ELoc; 8719 SourceRange ERange; 8720 Expr *SimpleRefExpr = RefExpr; 8721 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8722 if (Res.second) { 8723 // It will be analyzed later. 8724 Vars.push_back(RefExpr); 8725 SrcExprs.push_back(nullptr); 8726 DstExprs.push_back(nullptr); 8727 AssignmentOps.push_back(nullptr); 8728 } 8729 ValueDecl *D = Res.first; 8730 if (!D) 8731 continue; 8732 8733 QualType Type = D->getType(); 8734 auto *VD = dyn_cast<VarDecl>(D); 8735 8736 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 8737 // A variable that appears in a lastprivate clause must not have an 8738 // incomplete type or a reference type. 8739 if (RequireCompleteType(ELoc, Type, 8740 diag::err_omp_lastprivate_incomplete_type)) 8741 continue; 8742 Type = Type.getNonReferenceType(); 8743 8744 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8745 // in a Construct] 8746 // Variables with the predetermined data-sharing attributes may not be 8747 // listed in data-sharing attributes clauses, except for the cases 8748 // listed below. 8749 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8750 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 8751 DVar.CKind != OMPC_firstprivate && 8752 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 8753 Diag(ELoc, diag::err_omp_wrong_dsa) 8754 << getOpenMPClauseName(DVar.CKind) 8755 << getOpenMPClauseName(OMPC_lastprivate); 8756 ReportOriginalDSA(*this, DSAStack, D, DVar); 8757 continue; 8758 } 8759 8760 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8761 // OpenMP [2.14.3.5, Restrictions, p.2] 8762 // A list item that is private within a parallel region, or that appears in 8763 // the reduction clause of a parallel construct, must not appear in a 8764 // lastprivate clause on a worksharing construct if any of the corresponding 8765 // worksharing regions ever binds to any of the corresponding parallel 8766 // regions. 8767 DSAStackTy::DSAVarData TopDVar = DVar; 8768 if (isOpenMPWorksharingDirective(CurrDir) && 8769 !isOpenMPParallelDirective(CurrDir)) { 8770 DVar = DSAStack->getImplicitDSA(D, true); 8771 if (DVar.CKind != OMPC_shared) { 8772 Diag(ELoc, diag::err_omp_required_access) 8773 << getOpenMPClauseName(OMPC_lastprivate) 8774 << getOpenMPClauseName(OMPC_shared); 8775 ReportOriginalDSA(*this, DSAStack, D, DVar); 8776 continue; 8777 } 8778 } 8779 8780 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8781 // A list item may appear in a firstprivate or lastprivate clause but not 8782 // both. 8783 if (CurrDir == OMPD_distribute) { 8784 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8785 if (DVar.CKind == OMPC_firstprivate) { 8786 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8787 ReportOriginalDSA(*this, DSAStack, D, DVar); 8788 continue; 8789 } 8790 } 8791 8792 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 8793 // A variable of class type (or array thereof) that appears in a 8794 // lastprivate clause requires an accessible, unambiguous default 8795 // constructor for the class type, unless the list item is also specified 8796 // in a firstprivate clause. 8797 // A variable of class type (or array thereof) that appears in a 8798 // lastprivate clause requires an accessible, unambiguous copy assignment 8799 // operator for the class type. 8800 Type = Context.getBaseElementType(Type).getNonReferenceType(); 8801 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 8802 Type.getUnqualifiedType(), ".lastprivate.src", 8803 D->hasAttrs() ? &D->getAttrs() : nullptr); 8804 auto *PseudoSrcExpr = 8805 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 8806 auto *DstVD = 8807 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 8808 D->hasAttrs() ? &D->getAttrs() : nullptr); 8809 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 8810 // For arrays generate assignment operation for single element and replace 8811 // it by the original array element in CodeGen. 8812 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 8813 PseudoDstExpr, PseudoSrcExpr); 8814 if (AssignmentOp.isInvalid()) 8815 continue; 8816 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 8817 /*DiscardedValue=*/true); 8818 if (AssignmentOp.isInvalid()) 8819 continue; 8820 8821 DeclRefExpr *Ref = nullptr; 8822 if (!VD && !CurContext->isDependentContext()) { 8823 if (TopDVar.CKind == OMPC_firstprivate) 8824 Ref = TopDVar.PrivateCopy; 8825 else { 8826 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8827 if (!IsOpenMPCapturedDecl(D)) 8828 ExprCaptures.push_back(Ref->getDecl()); 8829 } 8830 if (TopDVar.CKind == OMPC_firstprivate || 8831 (!IsOpenMPCapturedDecl(D) && 8832 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 8833 ExprResult RefRes = DefaultLvalueConversion(Ref); 8834 if (!RefRes.isUsable()) 8835 continue; 8836 ExprResult PostUpdateRes = 8837 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 8838 RefRes.get()); 8839 if (!PostUpdateRes.isUsable()) 8840 continue; 8841 ExprPostUpdates.push_back( 8842 IgnoredValueConversions(PostUpdateRes.get()).get()); 8843 } 8844 } 8845 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 8846 Vars.push_back((VD || CurContext->isDependentContext()) 8847 ? RefExpr->IgnoreParens() 8848 : Ref); 8849 SrcExprs.push_back(PseudoSrcExpr); 8850 DstExprs.push_back(PseudoDstExpr); 8851 AssignmentOps.push_back(AssignmentOp.get()); 8852 } 8853 8854 if (Vars.empty()) 8855 return nullptr; 8856 8857 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8858 Vars, SrcExprs, DstExprs, AssignmentOps, 8859 buildPreInits(Context, ExprCaptures), 8860 buildPostUpdate(*this, ExprPostUpdates)); 8861 } 8862 8863 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 8864 SourceLocation StartLoc, 8865 SourceLocation LParenLoc, 8866 SourceLocation EndLoc) { 8867 SmallVector<Expr *, 8> Vars; 8868 for (auto &RefExpr : VarList) { 8869 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8870 SourceLocation ELoc; 8871 SourceRange ERange; 8872 Expr *SimpleRefExpr = RefExpr; 8873 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8874 if (Res.second) { 8875 // It will be analyzed later. 8876 Vars.push_back(RefExpr); 8877 } 8878 ValueDecl *D = Res.first; 8879 if (!D) 8880 continue; 8881 8882 auto *VD = dyn_cast<VarDecl>(D); 8883 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8884 // in a Construct] 8885 // Variables with the predetermined data-sharing attributes may not be 8886 // listed in data-sharing attributes clauses, except for the cases 8887 // listed below. For these exceptions only, listing a predetermined 8888 // variable in a data-sharing attribute clause is allowed and overrides 8889 // the variable's predetermined data-sharing attributes. 8890 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8891 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 8892 DVar.RefExpr) { 8893 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8894 << getOpenMPClauseName(OMPC_shared); 8895 ReportOriginalDSA(*this, DSAStack, D, DVar); 8896 continue; 8897 } 8898 8899 DeclRefExpr *Ref = nullptr; 8900 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 8901 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8902 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 8903 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 8904 ? RefExpr->IgnoreParens() 8905 : Ref); 8906 } 8907 8908 if (Vars.empty()) 8909 return nullptr; 8910 8911 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 8912 } 8913 8914 namespace { 8915 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 8916 DSAStackTy *Stack; 8917 8918 public: 8919 bool VisitDeclRefExpr(DeclRefExpr *E) { 8920 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 8921 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 8922 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 8923 return false; 8924 if (DVar.CKind != OMPC_unknown) 8925 return true; 8926 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 8927 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 8928 false); 8929 if (DVarPrivate.CKind != OMPC_unknown) 8930 return true; 8931 return false; 8932 } 8933 return false; 8934 } 8935 bool VisitStmt(Stmt *S) { 8936 for (auto Child : S->children()) { 8937 if (Child && Visit(Child)) 8938 return true; 8939 } 8940 return false; 8941 } 8942 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 8943 }; 8944 } // namespace 8945 8946 namespace { 8947 // Transform MemberExpression for specified FieldDecl of current class to 8948 // DeclRefExpr to specified OMPCapturedExprDecl. 8949 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 8950 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 8951 ValueDecl *Field; 8952 DeclRefExpr *CapturedExpr; 8953 8954 public: 8955 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 8956 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 8957 8958 ExprResult TransformMemberExpr(MemberExpr *E) { 8959 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 8960 E->getMemberDecl() == Field) { 8961 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 8962 return CapturedExpr; 8963 } 8964 return BaseTransform::TransformMemberExpr(E); 8965 } 8966 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 8967 }; 8968 } // namespace 8969 8970 template <typename T> 8971 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 8972 const llvm::function_ref<T(ValueDecl *)> &Gen) { 8973 for (auto &Set : Lookups) { 8974 for (auto *D : Set) { 8975 if (auto Res = Gen(cast<ValueDecl>(D))) 8976 return Res; 8977 } 8978 } 8979 return T(); 8980 } 8981 8982 static ExprResult 8983 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 8984 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 8985 const DeclarationNameInfo &ReductionId, QualType Ty, 8986 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 8987 if (ReductionIdScopeSpec.isInvalid()) 8988 return ExprError(); 8989 SmallVector<UnresolvedSet<8>, 4> Lookups; 8990 if (S) { 8991 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 8992 Lookup.suppressDiagnostics(); 8993 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 8994 auto *D = Lookup.getRepresentativeDecl(); 8995 do { 8996 S = S->getParent(); 8997 } while (S && !S->isDeclScope(D)); 8998 if (S) 8999 S = S->getParent(); 9000 Lookups.push_back(UnresolvedSet<8>()); 9001 Lookups.back().append(Lookup.begin(), Lookup.end()); 9002 Lookup.clear(); 9003 } 9004 } else if (auto *ULE = 9005 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 9006 Lookups.push_back(UnresolvedSet<8>()); 9007 Decl *PrevD = nullptr; 9008 for(auto *D : ULE->decls()) { 9009 if (D == PrevD) 9010 Lookups.push_back(UnresolvedSet<8>()); 9011 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 9012 Lookups.back().addDecl(DRD); 9013 PrevD = D; 9014 } 9015 } 9016 if (Ty->isDependentType() || Ty->isInstantiationDependentType() || 9017 Ty->containsUnexpandedParameterPack() || 9018 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 9019 return !D->isInvalidDecl() && 9020 (D->getType()->isDependentType() || 9021 D->getType()->isInstantiationDependentType() || 9022 D->getType()->containsUnexpandedParameterPack()); 9023 })) { 9024 UnresolvedSet<8> ResSet; 9025 for (auto &Set : Lookups) { 9026 ResSet.append(Set.begin(), Set.end()); 9027 // The last item marks the end of all declarations at the specified scope. 9028 ResSet.addDecl(Set[Set.size() - 1]); 9029 } 9030 return UnresolvedLookupExpr::Create( 9031 SemaRef.Context, /*NamingClass=*/nullptr, 9032 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 9033 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 9034 } 9035 if (auto *VD = filterLookupForUDR<ValueDecl *>( 9036 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 9037 if (!D->isInvalidDecl() && 9038 SemaRef.Context.hasSameType(D->getType(), Ty)) 9039 return D; 9040 return nullptr; 9041 })) 9042 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 9043 if (auto *VD = filterLookupForUDR<ValueDecl *>( 9044 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 9045 if (!D->isInvalidDecl() && 9046 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 9047 !Ty.isMoreQualifiedThan(D->getType())) 9048 return D; 9049 return nullptr; 9050 })) { 9051 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9052 /*DetectVirtual=*/false); 9053 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 9054 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 9055 VD->getType().getUnqualifiedType()))) { 9056 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 9057 /*DiagID=*/0) != 9058 Sema::AR_inaccessible) { 9059 SemaRef.BuildBasePathArray(Paths, BasePath); 9060 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 9061 } 9062 } 9063 } 9064 } 9065 if (ReductionIdScopeSpec.isSet()) { 9066 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 9067 return ExprError(); 9068 } 9069 return ExprEmpty(); 9070 } 9071 9072 OMPClause *Sema::ActOnOpenMPReductionClause( 9073 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 9074 SourceLocation ColonLoc, SourceLocation EndLoc, 9075 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 9076 ArrayRef<Expr *> UnresolvedReductions) { 9077 auto DN = ReductionId.getName(); 9078 auto OOK = DN.getCXXOverloadedOperator(); 9079 BinaryOperatorKind BOK = BO_Comma; 9080 9081 // OpenMP [2.14.3.6, reduction clause] 9082 // C 9083 // reduction-identifier is either an identifier or one of the following 9084 // operators: +, -, *, &, |, ^, && and || 9085 // C++ 9086 // reduction-identifier is either an id-expression or one of the following 9087 // operators: +, -, *, &, |, ^, && and || 9088 // FIXME: Only 'min' and 'max' identifiers are supported for now. 9089 switch (OOK) { 9090 case OO_Plus: 9091 case OO_Minus: 9092 BOK = BO_Add; 9093 break; 9094 case OO_Star: 9095 BOK = BO_Mul; 9096 break; 9097 case OO_Amp: 9098 BOK = BO_And; 9099 break; 9100 case OO_Pipe: 9101 BOK = BO_Or; 9102 break; 9103 case OO_Caret: 9104 BOK = BO_Xor; 9105 break; 9106 case OO_AmpAmp: 9107 BOK = BO_LAnd; 9108 break; 9109 case OO_PipePipe: 9110 BOK = BO_LOr; 9111 break; 9112 case OO_New: 9113 case OO_Delete: 9114 case OO_Array_New: 9115 case OO_Array_Delete: 9116 case OO_Slash: 9117 case OO_Percent: 9118 case OO_Tilde: 9119 case OO_Exclaim: 9120 case OO_Equal: 9121 case OO_Less: 9122 case OO_Greater: 9123 case OO_LessEqual: 9124 case OO_GreaterEqual: 9125 case OO_PlusEqual: 9126 case OO_MinusEqual: 9127 case OO_StarEqual: 9128 case OO_SlashEqual: 9129 case OO_PercentEqual: 9130 case OO_CaretEqual: 9131 case OO_AmpEqual: 9132 case OO_PipeEqual: 9133 case OO_LessLess: 9134 case OO_GreaterGreater: 9135 case OO_LessLessEqual: 9136 case OO_GreaterGreaterEqual: 9137 case OO_EqualEqual: 9138 case OO_ExclaimEqual: 9139 case OO_PlusPlus: 9140 case OO_MinusMinus: 9141 case OO_Comma: 9142 case OO_ArrowStar: 9143 case OO_Arrow: 9144 case OO_Call: 9145 case OO_Subscript: 9146 case OO_Conditional: 9147 case OO_Coawait: 9148 case NUM_OVERLOADED_OPERATORS: 9149 llvm_unreachable("Unexpected reduction identifier"); 9150 case OO_None: 9151 if (auto II = DN.getAsIdentifierInfo()) { 9152 if (II->isStr("max")) 9153 BOK = BO_GT; 9154 else if (II->isStr("min")) 9155 BOK = BO_LT; 9156 } 9157 break; 9158 } 9159 SourceRange ReductionIdRange; 9160 if (ReductionIdScopeSpec.isValid()) 9161 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 9162 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 9163 9164 SmallVector<Expr *, 8> Vars; 9165 SmallVector<Expr *, 8> Privates; 9166 SmallVector<Expr *, 8> LHSs; 9167 SmallVector<Expr *, 8> RHSs; 9168 SmallVector<Expr *, 8> ReductionOps; 9169 SmallVector<Decl *, 4> ExprCaptures; 9170 SmallVector<Expr *, 4> ExprPostUpdates; 9171 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 9172 bool FirstIter = true; 9173 for (auto RefExpr : VarList) { 9174 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 9175 // OpenMP [2.1, C/C++] 9176 // A list item is a variable or array section, subject to the restrictions 9177 // specified in Section 2.4 on page 42 and in each of the sections 9178 // describing clauses and directives for which a list appears. 9179 // OpenMP [2.14.3.3, Restrictions, p.1] 9180 // A variable that is part of another variable (as an array or 9181 // structure element) cannot appear in a private clause. 9182 if (!FirstIter && IR != ER) 9183 ++IR; 9184 FirstIter = false; 9185 SourceLocation ELoc; 9186 SourceRange ERange; 9187 Expr *SimpleRefExpr = RefExpr; 9188 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9189 /*AllowArraySection=*/true); 9190 if (Res.second) { 9191 // It will be analyzed later. 9192 Vars.push_back(RefExpr); 9193 Privates.push_back(nullptr); 9194 LHSs.push_back(nullptr); 9195 RHSs.push_back(nullptr); 9196 // Try to find 'declare reduction' corresponding construct before using 9197 // builtin/overloaded operators. 9198 QualType Type = Context.DependentTy; 9199 CXXCastPath BasePath; 9200 ExprResult DeclareReductionRef = buildDeclareReductionRef( 9201 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 9202 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 9203 if (CurContext->isDependentContext() && 9204 (DeclareReductionRef.isUnset() || 9205 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 9206 ReductionOps.push_back(DeclareReductionRef.get()); 9207 else 9208 ReductionOps.push_back(nullptr); 9209 } 9210 ValueDecl *D = Res.first; 9211 if (!D) 9212 continue; 9213 9214 QualType Type; 9215 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 9216 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 9217 if (ASE) 9218 Type = ASE->getType().getNonReferenceType(); 9219 else if (OASE) { 9220 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 9221 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 9222 Type = ATy->getElementType(); 9223 else 9224 Type = BaseType->getPointeeType(); 9225 Type = Type.getNonReferenceType(); 9226 } else 9227 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 9228 auto *VD = dyn_cast<VarDecl>(D); 9229 9230 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9231 // A variable that appears in a private clause must not have an incomplete 9232 // type or a reference type. 9233 if (RequireCompleteType(ELoc, Type, 9234 diag::err_omp_reduction_incomplete_type)) 9235 continue; 9236 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9237 // A list item that appears in a reduction clause must not be 9238 // const-qualified. 9239 if (Type.getNonReferenceType().isConstant(Context)) { 9240 Diag(ELoc, diag::err_omp_const_reduction_list_item) 9241 << getOpenMPClauseName(OMPC_reduction) << Type << ERange; 9242 if (!ASE && !OASE) { 9243 bool IsDecl = !VD || 9244 VD->isThisDeclarationADefinition(Context) == 9245 VarDecl::DeclarationOnly; 9246 Diag(D->getLocation(), 9247 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9248 << D; 9249 } 9250 continue; 9251 } 9252 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 9253 // If a list-item is a reference type then it must bind to the same object 9254 // for all threads of the team. 9255 if (!ASE && !OASE && VD) { 9256 VarDecl *VDDef = VD->getDefinition(); 9257 if (VD->getType()->isReferenceType() && VDDef) { 9258 DSARefChecker Check(DSAStack); 9259 if (Check.Visit(VDDef->getInit())) { 9260 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange; 9261 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 9262 continue; 9263 } 9264 } 9265 } 9266 9267 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 9268 // in a Construct] 9269 // Variables with the predetermined data-sharing attributes may not be 9270 // listed in data-sharing attributes clauses, except for the cases 9271 // listed below. For these exceptions only, listing a predetermined 9272 // variable in a data-sharing attribute clause is allowed and overrides 9273 // the variable's predetermined data-sharing attributes. 9274 // OpenMP [2.14.3.6, Restrictions, p.3] 9275 // Any number of reduction clauses can be specified on the directive, 9276 // but a list item can appear only once in the reduction clauses for that 9277 // directive. 9278 DSAStackTy::DSAVarData DVar; 9279 DVar = DSAStack->getTopDSA(D, false); 9280 if (DVar.CKind == OMPC_reduction) { 9281 Diag(ELoc, diag::err_omp_once_referenced) 9282 << getOpenMPClauseName(OMPC_reduction); 9283 if (DVar.RefExpr) 9284 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 9285 } else if (DVar.CKind != OMPC_unknown) { 9286 Diag(ELoc, diag::err_omp_wrong_dsa) 9287 << getOpenMPClauseName(DVar.CKind) 9288 << getOpenMPClauseName(OMPC_reduction); 9289 ReportOriginalDSA(*this, DSAStack, D, DVar); 9290 continue; 9291 } 9292 9293 // OpenMP [2.14.3.6, Restrictions, p.1] 9294 // A list item that appears in a reduction clause of a worksharing 9295 // construct must be shared in the parallel regions to which any of the 9296 // worksharing regions arising from the worksharing construct bind. 9297 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9298 if (isOpenMPWorksharingDirective(CurrDir) && 9299 !isOpenMPParallelDirective(CurrDir)) { 9300 DVar = DSAStack->getImplicitDSA(D, true); 9301 if (DVar.CKind != OMPC_shared) { 9302 Diag(ELoc, diag::err_omp_required_access) 9303 << getOpenMPClauseName(OMPC_reduction) 9304 << getOpenMPClauseName(OMPC_shared); 9305 ReportOriginalDSA(*this, DSAStack, D, DVar); 9306 continue; 9307 } 9308 } 9309 9310 // Try to find 'declare reduction' corresponding construct before using 9311 // builtin/overloaded operators. 9312 CXXCastPath BasePath; 9313 ExprResult DeclareReductionRef = buildDeclareReductionRef( 9314 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 9315 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 9316 if (DeclareReductionRef.isInvalid()) 9317 continue; 9318 if (CurContext->isDependentContext() && 9319 (DeclareReductionRef.isUnset() || 9320 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 9321 Vars.push_back(RefExpr); 9322 Privates.push_back(nullptr); 9323 LHSs.push_back(nullptr); 9324 RHSs.push_back(nullptr); 9325 ReductionOps.push_back(DeclareReductionRef.get()); 9326 continue; 9327 } 9328 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 9329 // Not allowed reduction identifier is found. 9330 Diag(ReductionId.getLocStart(), 9331 diag::err_omp_unknown_reduction_identifier) 9332 << Type << ReductionIdRange; 9333 continue; 9334 } 9335 9336 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9337 // The type of a list item that appears in a reduction clause must be valid 9338 // for the reduction-identifier. For a max or min reduction in C, the type 9339 // of the list item must be an allowed arithmetic data type: char, int, 9340 // float, double, or _Bool, possibly modified with long, short, signed, or 9341 // unsigned. For a max or min reduction in C++, the type of the list item 9342 // must be an allowed arithmetic data type: char, wchar_t, int, float, 9343 // double, or bool, possibly modified with long, short, signed, or unsigned. 9344 if (DeclareReductionRef.isUnset()) { 9345 if ((BOK == BO_GT || BOK == BO_LT) && 9346 !(Type->isScalarType() || 9347 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 9348 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 9349 << getLangOpts().CPlusPlus; 9350 if (!ASE && !OASE) { 9351 bool IsDecl = !VD || 9352 VD->isThisDeclarationADefinition(Context) == 9353 VarDecl::DeclarationOnly; 9354 Diag(D->getLocation(), 9355 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9356 << D; 9357 } 9358 continue; 9359 } 9360 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 9361 !getLangOpts().CPlusPlus && Type->isFloatingType()) { 9362 Diag(ELoc, diag::err_omp_clause_floating_type_arg); 9363 if (!ASE && !OASE) { 9364 bool IsDecl = !VD || 9365 VD->isThisDeclarationADefinition(Context) == 9366 VarDecl::DeclarationOnly; 9367 Diag(D->getLocation(), 9368 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9369 << D; 9370 } 9371 continue; 9372 } 9373 } 9374 9375 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 9376 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs", 9377 D->hasAttrs() ? &D->getAttrs() : nullptr); 9378 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(), 9379 D->hasAttrs() ? &D->getAttrs() : nullptr); 9380 auto PrivateTy = Type; 9381 if (OASE || 9382 (!ASE && 9383 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 9384 // For arays/array sections only: 9385 // Create pseudo array type for private copy. The size for this array will 9386 // be generated during codegen. 9387 // For array subscripts or single variables Private Ty is the same as Type 9388 // (type of the variable or single array element). 9389 PrivateTy = Context.getVariableArrayType( 9390 Type, new (Context) OpaqueValueExpr(SourceLocation(), 9391 Context.getSizeType(), VK_RValue), 9392 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 9393 } else if (!ASE && !OASE && 9394 Context.getAsArrayType(D->getType().getNonReferenceType())) 9395 PrivateTy = D->getType().getNonReferenceType(); 9396 // Private copy. 9397 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(), 9398 D->hasAttrs() ? &D->getAttrs() : nullptr); 9399 // Add initializer for private variable. 9400 Expr *Init = nullptr; 9401 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc); 9402 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc); 9403 if (DeclareReductionRef.isUsable()) { 9404 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 9405 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 9406 if (DRD->getInitializer()) { 9407 Init = DRDRef; 9408 RHSVD->setInit(DRDRef); 9409 RHSVD->setInitStyle(VarDecl::CallInit); 9410 } 9411 } else { 9412 switch (BOK) { 9413 case BO_Add: 9414 case BO_Xor: 9415 case BO_Or: 9416 case BO_LOr: 9417 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 9418 if (Type->isScalarType() || Type->isAnyComplexType()) 9419 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 9420 break; 9421 case BO_Mul: 9422 case BO_LAnd: 9423 if (Type->isScalarType() || Type->isAnyComplexType()) { 9424 // '*' and '&&' reduction ops - initializer is '1'. 9425 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 9426 } 9427 break; 9428 case BO_And: { 9429 // '&' reduction op - initializer is '~0'. 9430 QualType OrigType = Type; 9431 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 9432 Type = ComplexTy->getElementType(); 9433 if (Type->isRealFloatingType()) { 9434 llvm::APFloat InitValue = 9435 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 9436 /*isIEEE=*/true); 9437 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9438 Type, ELoc); 9439 } else if (Type->isScalarType()) { 9440 auto Size = Context.getTypeSize(Type); 9441 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 9442 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 9443 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9444 } 9445 if (Init && OrigType->isAnyComplexType()) { 9446 // Init = 0xFFFF + 0xFFFFi; 9447 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 9448 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 9449 } 9450 Type = OrigType; 9451 break; 9452 } 9453 case BO_LT: 9454 case BO_GT: { 9455 // 'min' reduction op - initializer is 'Largest representable number in 9456 // the reduction list item type'. 9457 // 'max' reduction op - initializer is 'Least representable number in 9458 // the reduction list item type'. 9459 if (Type->isIntegerType() || Type->isPointerType()) { 9460 bool IsSigned = Type->hasSignedIntegerRepresentation(); 9461 auto Size = Context.getTypeSize(Type); 9462 QualType IntTy = 9463 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 9464 llvm::APInt InitValue = 9465 (BOK != BO_LT) 9466 ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 9467 : llvm::APInt::getMinValue(Size) 9468 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 9469 : llvm::APInt::getMaxValue(Size); 9470 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9471 if (Type->isPointerType()) { 9472 // Cast to pointer type. 9473 auto CastExpr = BuildCStyleCastExpr( 9474 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc), 9475 SourceLocation(), Init); 9476 if (CastExpr.isInvalid()) 9477 continue; 9478 Init = CastExpr.get(); 9479 } 9480 } else if (Type->isRealFloatingType()) { 9481 llvm::APFloat InitValue = llvm::APFloat::getLargest( 9482 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 9483 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9484 Type, ELoc); 9485 } 9486 break; 9487 } 9488 case BO_PtrMemD: 9489 case BO_PtrMemI: 9490 case BO_MulAssign: 9491 case BO_Div: 9492 case BO_Rem: 9493 case BO_Sub: 9494 case BO_Shl: 9495 case BO_Shr: 9496 case BO_LE: 9497 case BO_GE: 9498 case BO_EQ: 9499 case BO_NE: 9500 case BO_AndAssign: 9501 case BO_XorAssign: 9502 case BO_OrAssign: 9503 case BO_Assign: 9504 case BO_AddAssign: 9505 case BO_SubAssign: 9506 case BO_DivAssign: 9507 case BO_RemAssign: 9508 case BO_ShlAssign: 9509 case BO_ShrAssign: 9510 case BO_Comma: 9511 llvm_unreachable("Unexpected reduction operation"); 9512 } 9513 } 9514 if (Init && DeclareReductionRef.isUnset()) { 9515 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false, 9516 /*TypeMayContainAuto=*/false); 9517 } else if (!Init) 9518 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false); 9519 if (RHSVD->isInvalidDecl()) 9520 continue; 9521 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 9522 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type 9523 << ReductionIdRange; 9524 bool IsDecl = 9525 !VD || 9526 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9527 Diag(D->getLocation(), 9528 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9529 << D; 9530 continue; 9531 } 9532 // Store initializer for single element in private copy. Will be used during 9533 // codegen. 9534 PrivateVD->setInit(RHSVD->getInit()); 9535 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 9536 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc); 9537 ExprResult ReductionOp; 9538 if (DeclareReductionRef.isUsable()) { 9539 QualType RedTy = DeclareReductionRef.get()->getType(); 9540 QualType PtrRedTy = Context.getPointerType(RedTy); 9541 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 9542 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 9543 if (!BasePath.empty()) { 9544 LHS = DefaultLvalueConversion(LHS.get()); 9545 RHS = DefaultLvalueConversion(RHS.get()); 9546 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9547 CK_UncheckedDerivedToBase, LHS.get(), 9548 &BasePath, LHS.get()->getValueKind()); 9549 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9550 CK_UncheckedDerivedToBase, RHS.get(), 9551 &BasePath, RHS.get()->getValueKind()); 9552 } 9553 FunctionProtoType::ExtProtoInfo EPI; 9554 QualType Params[] = {PtrRedTy, PtrRedTy}; 9555 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 9556 auto *OVE = new (Context) OpaqueValueExpr( 9557 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 9558 DefaultLvalueConversion(DeclareReductionRef.get()).get()); 9559 Expr *Args[] = {LHS.get(), RHS.get()}; 9560 ReductionOp = new (Context) 9561 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 9562 } else { 9563 ReductionOp = BuildBinOp(DSAStack->getCurScope(), 9564 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 9565 if (ReductionOp.isUsable()) { 9566 if (BOK != BO_LT && BOK != BO_GT) { 9567 ReductionOp = 9568 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 9569 BO_Assign, LHSDRE, ReductionOp.get()); 9570 } else { 9571 auto *ConditionalOp = new (Context) ConditionalOperator( 9572 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(), 9573 RHSDRE, Type, VK_LValue, OK_Ordinary); 9574 ReductionOp = 9575 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 9576 BO_Assign, LHSDRE, ConditionalOp); 9577 } 9578 ReductionOp = ActOnFinishFullExpr(ReductionOp.get()); 9579 } 9580 if (ReductionOp.isInvalid()) 9581 continue; 9582 } 9583 9584 DeclRefExpr *Ref = nullptr; 9585 Expr *VarsExpr = RefExpr->IgnoreParens(); 9586 if (!VD && !CurContext->isDependentContext()) { 9587 if (ASE || OASE) { 9588 TransformExprToCaptures RebuildToCapture(*this, D); 9589 VarsExpr = 9590 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 9591 Ref = RebuildToCapture.getCapturedExpr(); 9592 } else { 9593 VarsExpr = Ref = 9594 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9595 } 9596 if (!IsOpenMPCapturedDecl(D)) { 9597 ExprCaptures.push_back(Ref->getDecl()); 9598 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9599 ExprResult RefRes = DefaultLvalueConversion(Ref); 9600 if (!RefRes.isUsable()) 9601 continue; 9602 ExprResult PostUpdateRes = 9603 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9604 SimpleRefExpr, RefRes.get()); 9605 if (!PostUpdateRes.isUsable()) 9606 continue; 9607 ExprPostUpdates.push_back( 9608 IgnoredValueConversions(PostUpdateRes.get()).get()); 9609 } 9610 } 9611 } 9612 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 9613 Vars.push_back(VarsExpr); 9614 Privates.push_back(PrivateDRE); 9615 LHSs.push_back(LHSDRE); 9616 RHSs.push_back(RHSDRE); 9617 ReductionOps.push_back(ReductionOp.get()); 9618 } 9619 9620 if (Vars.empty()) 9621 return nullptr; 9622 9623 return OMPReductionClause::Create( 9624 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars, 9625 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates, 9626 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures), 9627 buildPostUpdate(*this, ExprPostUpdates)); 9628 } 9629 9630 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 9631 SourceLocation LinLoc) { 9632 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 9633 LinKind == OMPC_LINEAR_unknown) { 9634 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 9635 return true; 9636 } 9637 return false; 9638 } 9639 9640 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 9641 OpenMPLinearClauseKind LinKind, 9642 QualType Type) { 9643 auto *VD = dyn_cast_or_null<VarDecl>(D); 9644 // A variable must not have an incomplete type or a reference type. 9645 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 9646 return true; 9647 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 9648 !Type->isReferenceType()) { 9649 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 9650 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 9651 return true; 9652 } 9653 Type = Type.getNonReferenceType(); 9654 9655 // A list item must not be const-qualified. 9656 if (Type.isConstant(Context)) { 9657 Diag(ELoc, diag::err_omp_const_variable) 9658 << getOpenMPClauseName(OMPC_linear); 9659 if (D) { 9660 bool IsDecl = 9661 !VD || 9662 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9663 Diag(D->getLocation(), 9664 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9665 << D; 9666 } 9667 return true; 9668 } 9669 9670 // A list item must be of integral or pointer type. 9671 Type = Type.getUnqualifiedType().getCanonicalType(); 9672 const auto *Ty = Type.getTypePtrOrNull(); 9673 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 9674 !Ty->isPointerType())) { 9675 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 9676 if (D) { 9677 bool IsDecl = 9678 !VD || 9679 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9680 Diag(D->getLocation(), 9681 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9682 << D; 9683 } 9684 return true; 9685 } 9686 return false; 9687 } 9688 9689 OMPClause *Sema::ActOnOpenMPLinearClause( 9690 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 9691 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 9692 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9693 SmallVector<Expr *, 8> Vars; 9694 SmallVector<Expr *, 8> Privates; 9695 SmallVector<Expr *, 8> Inits; 9696 SmallVector<Decl *, 4> ExprCaptures; 9697 SmallVector<Expr *, 4> ExprPostUpdates; 9698 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 9699 LinKind = OMPC_LINEAR_val; 9700 for (auto &RefExpr : VarList) { 9701 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9702 SourceLocation ELoc; 9703 SourceRange ERange; 9704 Expr *SimpleRefExpr = RefExpr; 9705 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9706 /*AllowArraySection=*/false); 9707 if (Res.second) { 9708 // It will be analyzed later. 9709 Vars.push_back(RefExpr); 9710 Privates.push_back(nullptr); 9711 Inits.push_back(nullptr); 9712 } 9713 ValueDecl *D = Res.first; 9714 if (!D) 9715 continue; 9716 9717 QualType Type = D->getType(); 9718 auto *VD = dyn_cast<VarDecl>(D); 9719 9720 // OpenMP [2.14.3.7, linear clause] 9721 // A list-item cannot appear in more than one linear clause. 9722 // A list-item that appears in a linear clause cannot appear in any 9723 // other data-sharing attribute clause. 9724 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9725 if (DVar.RefExpr) { 9726 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9727 << getOpenMPClauseName(OMPC_linear); 9728 ReportOriginalDSA(*this, DSAStack, D, DVar); 9729 continue; 9730 } 9731 9732 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 9733 continue; 9734 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9735 9736 // Build private copy of original var. 9737 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 9738 D->hasAttrs() ? &D->getAttrs() : nullptr); 9739 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 9740 // Build var to save initial value. 9741 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 9742 Expr *InitExpr; 9743 DeclRefExpr *Ref = nullptr; 9744 if (!VD && !CurContext->isDependentContext()) { 9745 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9746 if (!IsOpenMPCapturedDecl(D)) { 9747 ExprCaptures.push_back(Ref->getDecl()); 9748 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9749 ExprResult RefRes = DefaultLvalueConversion(Ref); 9750 if (!RefRes.isUsable()) 9751 continue; 9752 ExprResult PostUpdateRes = 9753 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9754 SimpleRefExpr, RefRes.get()); 9755 if (!PostUpdateRes.isUsable()) 9756 continue; 9757 ExprPostUpdates.push_back( 9758 IgnoredValueConversions(PostUpdateRes.get()).get()); 9759 } 9760 } 9761 } 9762 if (LinKind == OMPC_LINEAR_uval) 9763 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 9764 else 9765 InitExpr = VD ? SimpleRefExpr : Ref; 9766 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 9767 /*DirectInit=*/false, /*TypeMayContainAuto=*/false); 9768 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 9769 9770 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 9771 Vars.push_back((VD || CurContext->isDependentContext()) 9772 ? RefExpr->IgnoreParens() 9773 : Ref); 9774 Privates.push_back(PrivateRef); 9775 Inits.push_back(InitRef); 9776 } 9777 9778 if (Vars.empty()) 9779 return nullptr; 9780 9781 Expr *StepExpr = Step; 9782 Expr *CalcStepExpr = nullptr; 9783 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 9784 !Step->isInstantiationDependent() && 9785 !Step->containsUnexpandedParameterPack()) { 9786 SourceLocation StepLoc = Step->getLocStart(); 9787 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 9788 if (Val.isInvalid()) 9789 return nullptr; 9790 StepExpr = Val.get(); 9791 9792 // Build var to save the step value. 9793 VarDecl *SaveVar = 9794 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 9795 ExprResult SaveRef = 9796 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 9797 ExprResult CalcStep = 9798 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 9799 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 9800 9801 // Warn about zero linear step (it would be probably better specified as 9802 // making corresponding variables 'const'). 9803 llvm::APSInt Result; 9804 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 9805 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 9806 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 9807 << (Vars.size() > 1); 9808 if (!IsConstant && CalcStep.isUsable()) { 9809 // Calculate the step beforehand instead of doing this on each iteration. 9810 // (This is not used if the number of iterations may be kfold-ed). 9811 CalcStepExpr = CalcStep.get(); 9812 } 9813 } 9814 9815 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 9816 ColonLoc, EndLoc, Vars, Privates, Inits, 9817 StepExpr, CalcStepExpr, 9818 buildPreInits(Context, ExprCaptures), 9819 buildPostUpdate(*this, ExprPostUpdates)); 9820 } 9821 9822 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 9823 Expr *NumIterations, Sema &SemaRef, 9824 Scope *S, DSAStackTy *Stack) { 9825 // Walk the vars and build update/final expressions for the CodeGen. 9826 SmallVector<Expr *, 8> Updates; 9827 SmallVector<Expr *, 8> Finals; 9828 Expr *Step = Clause.getStep(); 9829 Expr *CalcStep = Clause.getCalcStep(); 9830 // OpenMP [2.14.3.7, linear clause] 9831 // If linear-step is not specified it is assumed to be 1. 9832 if (Step == nullptr) 9833 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9834 else if (CalcStep) { 9835 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 9836 } 9837 bool HasErrors = false; 9838 auto CurInit = Clause.inits().begin(); 9839 auto CurPrivate = Clause.privates().begin(); 9840 auto LinKind = Clause.getModifier(); 9841 for (auto &RefExpr : Clause.varlists()) { 9842 SourceLocation ELoc; 9843 SourceRange ERange; 9844 Expr *SimpleRefExpr = RefExpr; 9845 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 9846 /*AllowArraySection=*/false); 9847 ValueDecl *D = Res.first; 9848 if (Res.second || !D) { 9849 Updates.push_back(nullptr); 9850 Finals.push_back(nullptr); 9851 HasErrors = true; 9852 continue; 9853 } 9854 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) { 9855 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts()) 9856 ->getMemberDecl(); 9857 } 9858 auto &&Info = Stack->isLoopControlVariable(D); 9859 Expr *InitExpr = *CurInit; 9860 9861 // Build privatized reference to the current linear var. 9862 auto DE = cast<DeclRefExpr>(SimpleRefExpr); 9863 Expr *CapturedRef; 9864 if (LinKind == OMPC_LINEAR_uval) 9865 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 9866 else 9867 CapturedRef = 9868 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 9869 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 9870 /*RefersToCapture=*/true); 9871 9872 // Build update: Var = InitExpr + IV * Step 9873 ExprResult Update; 9874 if (!Info.first) { 9875 Update = 9876 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 9877 InitExpr, IV, Step, /* Subtract */ false); 9878 } else 9879 Update = *CurPrivate; 9880 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 9881 /*DiscardedValue=*/true); 9882 9883 // Build final: Var = InitExpr + NumIterations * Step 9884 ExprResult Final; 9885 if (!Info.first) { 9886 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 9887 InitExpr, NumIterations, Step, 9888 /* Subtract */ false); 9889 } else 9890 Final = *CurPrivate; 9891 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 9892 /*DiscardedValue=*/true); 9893 9894 if (!Update.isUsable() || !Final.isUsable()) { 9895 Updates.push_back(nullptr); 9896 Finals.push_back(nullptr); 9897 HasErrors = true; 9898 } else { 9899 Updates.push_back(Update.get()); 9900 Finals.push_back(Final.get()); 9901 } 9902 ++CurInit; 9903 ++CurPrivate; 9904 } 9905 Clause.setUpdates(Updates); 9906 Clause.setFinals(Finals); 9907 return HasErrors; 9908 } 9909 9910 OMPClause *Sema::ActOnOpenMPAlignedClause( 9911 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 9912 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9913 9914 SmallVector<Expr *, 8> Vars; 9915 for (auto &RefExpr : VarList) { 9916 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9917 SourceLocation ELoc; 9918 SourceRange ERange; 9919 Expr *SimpleRefExpr = RefExpr; 9920 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9921 /*AllowArraySection=*/false); 9922 if (Res.second) { 9923 // It will be analyzed later. 9924 Vars.push_back(RefExpr); 9925 } 9926 ValueDecl *D = Res.first; 9927 if (!D) 9928 continue; 9929 9930 QualType QType = D->getType(); 9931 auto *VD = dyn_cast<VarDecl>(D); 9932 9933 // OpenMP [2.8.1, simd construct, Restrictions] 9934 // The type of list items appearing in the aligned clause must be 9935 // array, pointer, reference to array, or reference to pointer. 9936 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9937 const Type *Ty = QType.getTypePtrOrNull(); 9938 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 9939 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 9940 << QType << getLangOpts().CPlusPlus << ERange; 9941 bool IsDecl = 9942 !VD || 9943 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9944 Diag(D->getLocation(), 9945 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9946 << D; 9947 continue; 9948 } 9949 9950 // OpenMP [2.8.1, simd construct, Restrictions] 9951 // A list-item cannot appear in more than one aligned clause. 9952 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 9953 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 9954 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 9955 << getOpenMPClauseName(OMPC_aligned); 9956 continue; 9957 } 9958 9959 DeclRefExpr *Ref = nullptr; 9960 if (!VD && IsOpenMPCapturedDecl(D)) 9961 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9962 Vars.push_back(DefaultFunctionArrayConversion( 9963 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 9964 .get()); 9965 } 9966 9967 // OpenMP [2.8.1, simd construct, Description] 9968 // The parameter of the aligned clause, alignment, must be a constant 9969 // positive integer expression. 9970 // If no optional parameter is specified, implementation-defined default 9971 // alignments for SIMD instructions on the target platforms are assumed. 9972 if (Alignment != nullptr) { 9973 ExprResult AlignResult = 9974 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 9975 if (AlignResult.isInvalid()) 9976 return nullptr; 9977 Alignment = AlignResult.get(); 9978 } 9979 if (Vars.empty()) 9980 return nullptr; 9981 9982 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 9983 EndLoc, Vars, Alignment); 9984 } 9985 9986 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 9987 SourceLocation StartLoc, 9988 SourceLocation LParenLoc, 9989 SourceLocation EndLoc) { 9990 SmallVector<Expr *, 8> Vars; 9991 SmallVector<Expr *, 8> SrcExprs; 9992 SmallVector<Expr *, 8> DstExprs; 9993 SmallVector<Expr *, 8> AssignmentOps; 9994 for (auto &RefExpr : VarList) { 9995 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 9996 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 9997 // It will be analyzed later. 9998 Vars.push_back(RefExpr); 9999 SrcExprs.push_back(nullptr); 10000 DstExprs.push_back(nullptr); 10001 AssignmentOps.push_back(nullptr); 10002 continue; 10003 } 10004 10005 SourceLocation ELoc = RefExpr->getExprLoc(); 10006 // OpenMP [2.1, C/C++] 10007 // A list item is a variable name. 10008 // OpenMP [2.14.4.1, Restrictions, p.1] 10009 // A list item that appears in a copyin clause must be threadprivate. 10010 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 10011 if (!DE || !isa<VarDecl>(DE->getDecl())) { 10012 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 10013 << 0 << RefExpr->getSourceRange(); 10014 continue; 10015 } 10016 10017 Decl *D = DE->getDecl(); 10018 VarDecl *VD = cast<VarDecl>(D); 10019 10020 QualType Type = VD->getType(); 10021 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 10022 // It will be analyzed later. 10023 Vars.push_back(DE); 10024 SrcExprs.push_back(nullptr); 10025 DstExprs.push_back(nullptr); 10026 AssignmentOps.push_back(nullptr); 10027 continue; 10028 } 10029 10030 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 10031 // A list item that appears in a copyin clause must be threadprivate. 10032 if (!DSAStack->isThreadPrivate(VD)) { 10033 Diag(ELoc, diag::err_omp_required_access) 10034 << getOpenMPClauseName(OMPC_copyin) 10035 << getOpenMPDirectiveName(OMPD_threadprivate); 10036 continue; 10037 } 10038 10039 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 10040 // A variable of class type (or array thereof) that appears in a 10041 // copyin clause requires an accessible, unambiguous copy assignment 10042 // operator for the class type. 10043 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 10044 auto *SrcVD = 10045 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 10046 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 10047 auto *PseudoSrcExpr = buildDeclRefExpr( 10048 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 10049 auto *DstVD = 10050 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 10051 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 10052 auto *PseudoDstExpr = 10053 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 10054 // For arrays generate assignment operation for single element and replace 10055 // it by the original array element in CodeGen. 10056 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 10057 PseudoDstExpr, PseudoSrcExpr); 10058 if (AssignmentOp.isInvalid()) 10059 continue; 10060 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 10061 /*DiscardedValue=*/true); 10062 if (AssignmentOp.isInvalid()) 10063 continue; 10064 10065 DSAStack->addDSA(VD, DE, OMPC_copyin); 10066 Vars.push_back(DE); 10067 SrcExprs.push_back(PseudoSrcExpr); 10068 DstExprs.push_back(PseudoDstExpr); 10069 AssignmentOps.push_back(AssignmentOp.get()); 10070 } 10071 10072 if (Vars.empty()) 10073 return nullptr; 10074 10075 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 10076 SrcExprs, DstExprs, AssignmentOps); 10077 } 10078 10079 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 10080 SourceLocation StartLoc, 10081 SourceLocation LParenLoc, 10082 SourceLocation EndLoc) { 10083 SmallVector<Expr *, 8> Vars; 10084 SmallVector<Expr *, 8> SrcExprs; 10085 SmallVector<Expr *, 8> DstExprs; 10086 SmallVector<Expr *, 8> AssignmentOps; 10087 for (auto &RefExpr : VarList) { 10088 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10089 SourceLocation ELoc; 10090 SourceRange ERange; 10091 Expr *SimpleRefExpr = RefExpr; 10092 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10093 /*AllowArraySection=*/false); 10094 if (Res.second) { 10095 // It will be analyzed later. 10096 Vars.push_back(RefExpr); 10097 SrcExprs.push_back(nullptr); 10098 DstExprs.push_back(nullptr); 10099 AssignmentOps.push_back(nullptr); 10100 } 10101 ValueDecl *D = Res.first; 10102 if (!D) 10103 continue; 10104 10105 QualType Type = D->getType(); 10106 auto *VD = dyn_cast<VarDecl>(D); 10107 10108 // OpenMP [2.14.4.2, Restrictions, p.2] 10109 // A list item that appears in a copyprivate clause may not appear in a 10110 // private or firstprivate clause on the single construct. 10111 if (!VD || !DSAStack->isThreadPrivate(VD)) { 10112 auto DVar = DSAStack->getTopDSA(D, false); 10113 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 10114 DVar.RefExpr) { 10115 Diag(ELoc, diag::err_omp_wrong_dsa) 10116 << getOpenMPClauseName(DVar.CKind) 10117 << getOpenMPClauseName(OMPC_copyprivate); 10118 ReportOriginalDSA(*this, DSAStack, D, DVar); 10119 continue; 10120 } 10121 10122 // OpenMP [2.11.4.2, Restrictions, p.1] 10123 // All list items that appear in a copyprivate clause must be either 10124 // threadprivate or private in the enclosing context. 10125 if (DVar.CKind == OMPC_unknown) { 10126 DVar = DSAStack->getImplicitDSA(D, false); 10127 if (DVar.CKind == OMPC_shared) { 10128 Diag(ELoc, diag::err_omp_required_access) 10129 << getOpenMPClauseName(OMPC_copyprivate) 10130 << "threadprivate or private in the enclosing context"; 10131 ReportOriginalDSA(*this, DSAStack, D, DVar); 10132 continue; 10133 } 10134 } 10135 } 10136 10137 // Variably modified types are not supported. 10138 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 10139 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 10140 << getOpenMPClauseName(OMPC_copyprivate) << Type 10141 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 10142 bool IsDecl = 10143 !VD || 10144 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10145 Diag(D->getLocation(), 10146 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10147 << D; 10148 continue; 10149 } 10150 10151 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 10152 // A variable of class type (or array thereof) that appears in a 10153 // copyin clause requires an accessible, unambiguous copy assignment 10154 // operator for the class type. 10155 Type = Context.getBaseElementType(Type.getNonReferenceType()) 10156 .getUnqualifiedType(); 10157 auto *SrcVD = 10158 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 10159 D->hasAttrs() ? &D->getAttrs() : nullptr); 10160 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 10161 auto *DstVD = 10162 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 10163 D->hasAttrs() ? &D->getAttrs() : nullptr); 10164 auto *PseudoDstExpr = 10165 buildDeclRefExpr(*this, DstVD, Type, ELoc); 10166 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 10167 PseudoDstExpr, PseudoSrcExpr); 10168 if (AssignmentOp.isInvalid()) 10169 continue; 10170 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 10171 /*DiscardedValue=*/true); 10172 if (AssignmentOp.isInvalid()) 10173 continue; 10174 10175 // No need to mark vars as copyprivate, they are already threadprivate or 10176 // implicitly private. 10177 assert(VD || IsOpenMPCapturedDecl(D)); 10178 Vars.push_back( 10179 VD ? RefExpr->IgnoreParens() 10180 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 10181 SrcExprs.push_back(PseudoSrcExpr); 10182 DstExprs.push_back(PseudoDstExpr); 10183 AssignmentOps.push_back(AssignmentOp.get()); 10184 } 10185 10186 if (Vars.empty()) 10187 return nullptr; 10188 10189 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10190 Vars, SrcExprs, DstExprs, AssignmentOps); 10191 } 10192 10193 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 10194 SourceLocation StartLoc, 10195 SourceLocation LParenLoc, 10196 SourceLocation EndLoc) { 10197 if (VarList.empty()) 10198 return nullptr; 10199 10200 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 10201 } 10202 10203 OMPClause * 10204 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 10205 SourceLocation DepLoc, SourceLocation ColonLoc, 10206 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10207 SourceLocation LParenLoc, SourceLocation EndLoc) { 10208 if (DSAStack->getCurrentDirective() == OMPD_ordered && 10209 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 10210 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 10211 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 10212 return nullptr; 10213 } 10214 if (DSAStack->getCurrentDirective() != OMPD_ordered && 10215 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 10216 DepKind == OMPC_DEPEND_sink)) { 10217 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 10218 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 10219 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 10220 /*Last=*/OMPC_DEPEND_unknown, Except) 10221 << getOpenMPClauseName(OMPC_depend); 10222 return nullptr; 10223 } 10224 SmallVector<Expr *, 8> Vars; 10225 DSAStackTy::OperatorOffsetTy OpsOffs; 10226 llvm::APSInt DepCounter(/*BitWidth=*/32); 10227 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 10228 if (DepKind == OMPC_DEPEND_sink) { 10229 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 10230 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 10231 TotalDepCount.setIsUnsigned(/*Val=*/true); 10232 } 10233 } 10234 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || 10235 DSAStack->getParentOrderedRegionParam()) { 10236 for (auto &RefExpr : VarList) { 10237 assert(RefExpr && "NULL expr in OpenMP shared clause."); 10238 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 10239 // It will be analyzed later. 10240 Vars.push_back(RefExpr); 10241 continue; 10242 } 10243 10244 SourceLocation ELoc = RefExpr->getExprLoc(); 10245 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 10246 if (DepKind == OMPC_DEPEND_sink) { 10247 if (DepCounter >= TotalDepCount) { 10248 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 10249 continue; 10250 } 10251 ++DepCounter; 10252 // OpenMP [2.13.9, Summary] 10253 // depend(dependence-type : vec), where dependence-type is: 10254 // 'sink' and where vec is the iteration vector, which has the form: 10255 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 10256 // where n is the value specified by the ordered clause in the loop 10257 // directive, xi denotes the loop iteration variable of the i-th nested 10258 // loop associated with the loop directive, and di is a constant 10259 // non-negative integer. 10260 if (CurContext->isDependentContext()) { 10261 // It will be analyzed later. 10262 Vars.push_back(RefExpr); 10263 continue; 10264 } 10265 SimpleExpr = SimpleExpr->IgnoreImplicit(); 10266 OverloadedOperatorKind OOK = OO_None; 10267 SourceLocation OOLoc; 10268 Expr *LHS = SimpleExpr; 10269 Expr *RHS = nullptr; 10270 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 10271 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 10272 OOLoc = BO->getOperatorLoc(); 10273 LHS = BO->getLHS()->IgnoreParenImpCasts(); 10274 RHS = BO->getRHS()->IgnoreParenImpCasts(); 10275 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 10276 OOK = OCE->getOperator(); 10277 OOLoc = OCE->getOperatorLoc(); 10278 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10279 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 10280 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 10281 OOK = MCE->getMethodDecl() 10282 ->getNameInfo() 10283 .getName() 10284 .getCXXOverloadedOperator(); 10285 OOLoc = MCE->getCallee()->getExprLoc(); 10286 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 10287 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10288 } 10289 SourceLocation ELoc; 10290 SourceRange ERange; 10291 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 10292 /*AllowArraySection=*/false); 10293 if (Res.second) { 10294 // It will be analyzed later. 10295 Vars.push_back(RefExpr); 10296 } 10297 ValueDecl *D = Res.first; 10298 if (!D) 10299 continue; 10300 10301 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 10302 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 10303 continue; 10304 } 10305 if (RHS) { 10306 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 10307 RHS, OMPC_depend, /*StrictlyPositive=*/false); 10308 if (RHSRes.isInvalid()) 10309 continue; 10310 } 10311 if (!CurContext->isDependentContext() && 10312 DSAStack->getParentOrderedRegionParam() && 10313 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 10314 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 10315 << DSAStack->getParentLoopControlVariable( 10316 DepCounter.getZExtValue()); 10317 continue; 10318 } 10319 OpsOffs.push_back({RHS, OOK}); 10320 } else { 10321 // OpenMP [2.11.1.1, Restrictions, p.3] 10322 // A variable that is part of another variable (such as a field of a 10323 // structure) but is not an array element or an array section cannot 10324 // appear in a depend clause. 10325 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr); 10326 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 10327 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 10328 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 10329 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) || 10330 (ASE && 10331 !ASE->getBase() 10332 ->getType() 10333 .getNonReferenceType() 10334 ->isPointerType() && 10335 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 10336 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item) 10337 << 0 << RefExpr->getSourceRange(); 10338 continue; 10339 } 10340 } 10341 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 10342 } 10343 10344 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 10345 TotalDepCount > VarList.size() && 10346 DSAStack->getParentOrderedRegionParam()) { 10347 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 10348 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 10349 } 10350 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 10351 Vars.empty()) 10352 return nullptr; 10353 } 10354 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10355 DepKind, DepLoc, ColonLoc, Vars); 10356 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) 10357 DSAStack->addDoacrossDependClause(C, OpsOffs); 10358 return C; 10359 } 10360 10361 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 10362 SourceLocation LParenLoc, 10363 SourceLocation EndLoc) { 10364 Expr *ValExpr = Device; 10365 10366 // OpenMP [2.9.1, Restrictions] 10367 // The device expression must evaluate to a non-negative integer value. 10368 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 10369 /*StrictlyPositive=*/false)) 10370 return nullptr; 10371 10372 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10373 } 10374 10375 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc, 10376 DSAStackTy *Stack, CXXRecordDecl *RD) { 10377 if (!RD || RD->isInvalidDecl()) 10378 return true; 10379 10380 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 10381 if (auto *CTD = CTSD->getSpecializedTemplate()) 10382 RD = CTD->getTemplatedDecl(); 10383 auto QTy = SemaRef.Context.getRecordType(RD); 10384 if (RD->isDynamicClass()) { 10385 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10386 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target); 10387 return false; 10388 } 10389 auto *DC = RD; 10390 bool IsCorrect = true; 10391 for (auto *I : DC->decls()) { 10392 if (I) { 10393 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) { 10394 if (MD->isStatic()) { 10395 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10396 SemaRef.Diag(MD->getLocation(), 10397 diag::note_omp_static_member_in_target); 10398 IsCorrect = false; 10399 } 10400 } else if (auto *VD = dyn_cast<VarDecl>(I)) { 10401 if (VD->isStaticDataMember()) { 10402 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10403 SemaRef.Diag(VD->getLocation(), 10404 diag::note_omp_static_member_in_target); 10405 IsCorrect = false; 10406 } 10407 } 10408 } 10409 } 10410 10411 for (auto &I : RD->bases()) { 10412 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack, 10413 I.getType()->getAsCXXRecordDecl())) 10414 IsCorrect = false; 10415 } 10416 return IsCorrect; 10417 } 10418 10419 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 10420 DSAStackTy *Stack, QualType QTy) { 10421 NamedDecl *ND; 10422 if (QTy->isIncompleteType(&ND)) { 10423 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 10424 return false; 10425 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) { 10426 if (!RD->isInvalidDecl() && 10427 !IsCXXRecordForMappable(SemaRef, SL, Stack, RD)) 10428 return false; 10429 } 10430 return true; 10431 } 10432 10433 /// \brief Return true if it can be proven that the provided array expression 10434 /// (array section or array subscript) does NOT specify the whole size of the 10435 /// array whose base type is \a BaseQTy. 10436 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 10437 const Expr *E, 10438 QualType BaseQTy) { 10439 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10440 10441 // If this is an array subscript, it refers to the whole size if the size of 10442 // the dimension is constant and equals 1. Also, an array section assumes the 10443 // format of an array subscript if no colon is used. 10444 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 10445 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10446 return ATy->getSize().getSExtValue() != 1; 10447 // Size can't be evaluated statically. 10448 return false; 10449 } 10450 10451 assert(OASE && "Expecting array section if not an array subscript."); 10452 auto *LowerBound = OASE->getLowerBound(); 10453 auto *Length = OASE->getLength(); 10454 10455 // If there is a lower bound that does not evaluates to zero, we are not 10456 // convering the whole dimension. 10457 if (LowerBound) { 10458 llvm::APSInt ConstLowerBound; 10459 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 10460 return false; // Can't get the integer value as a constant. 10461 if (ConstLowerBound.getSExtValue()) 10462 return true; 10463 } 10464 10465 // If we don't have a length we covering the whole dimension. 10466 if (!Length) 10467 return false; 10468 10469 // If the base is a pointer, we don't have a way to get the size of the 10470 // pointee. 10471 if (BaseQTy->isPointerType()) 10472 return false; 10473 10474 // We can only check if the length is the same as the size of the dimension 10475 // if we have a constant array. 10476 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 10477 if (!CATy) 10478 return false; 10479 10480 llvm::APSInt ConstLength; 10481 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10482 return false; // Can't get the integer value as a constant. 10483 10484 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 10485 } 10486 10487 // Return true if it can be proven that the provided array expression (array 10488 // section or array subscript) does NOT specify a single element of the array 10489 // whose base type is \a BaseQTy. 10490 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 10491 const Expr *E, 10492 QualType BaseQTy) { 10493 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10494 10495 // An array subscript always refer to a single element. Also, an array section 10496 // assumes the format of an array subscript if no colon is used. 10497 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 10498 return false; 10499 10500 assert(OASE && "Expecting array section if not an array subscript."); 10501 auto *Length = OASE->getLength(); 10502 10503 // If we don't have a length we have to check if the array has unitary size 10504 // for this dimension. Also, we should always expect a length if the base type 10505 // is pointer. 10506 if (!Length) { 10507 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10508 return ATy->getSize().getSExtValue() != 1; 10509 // We cannot assume anything. 10510 return false; 10511 } 10512 10513 // Check if the length evaluates to 1. 10514 llvm::APSInt ConstLength; 10515 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10516 return false; // Can't get the integer value as a constant. 10517 10518 return ConstLength.getSExtValue() != 1; 10519 } 10520 10521 // Return the expression of the base of the mappable expression or null if it 10522 // cannot be determined and do all the necessary checks to see if the expression 10523 // is valid as a standalone mappable expression. In the process, record all the 10524 // components of the expression. 10525 static Expr *CheckMapClauseExpressionBase( 10526 Sema &SemaRef, Expr *E, 10527 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 10528 OpenMPClauseKind CKind) { 10529 SourceLocation ELoc = E->getExprLoc(); 10530 SourceRange ERange = E->getSourceRange(); 10531 10532 // The base of elements of list in a map clause have to be either: 10533 // - a reference to variable or field. 10534 // - a member expression. 10535 // - an array expression. 10536 // 10537 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 10538 // reference to 'r'. 10539 // 10540 // If we have: 10541 // 10542 // struct SS { 10543 // Bla S; 10544 // foo() { 10545 // #pragma omp target map (S.Arr[:12]); 10546 // } 10547 // } 10548 // 10549 // We want to retrieve the member expression 'this->S'; 10550 10551 Expr *RelevantExpr = nullptr; 10552 10553 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 10554 // If a list item is an array section, it must specify contiguous storage. 10555 // 10556 // For this restriction it is sufficient that we make sure only references 10557 // to variables or fields and array expressions, and that no array sections 10558 // exist except in the rightmost expression (unless they cover the whole 10559 // dimension of the array). E.g. these would be invalid: 10560 // 10561 // r.ArrS[3:5].Arr[6:7] 10562 // 10563 // r.ArrS[3:5].x 10564 // 10565 // but these would be valid: 10566 // r.ArrS[3].Arr[6:7] 10567 // 10568 // r.ArrS[3].x 10569 10570 bool AllowUnitySizeArraySection = true; 10571 bool AllowWholeSizeArraySection = true; 10572 10573 while (!RelevantExpr) { 10574 E = E->IgnoreParenImpCasts(); 10575 10576 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 10577 if (!isa<VarDecl>(CurE->getDecl())) 10578 break; 10579 10580 RelevantExpr = CurE; 10581 10582 // If we got a reference to a declaration, we should not expect any array 10583 // section before that. 10584 AllowUnitySizeArraySection = false; 10585 AllowWholeSizeArraySection = false; 10586 10587 // Record the component. 10588 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent( 10589 CurE, CurE->getDecl())); 10590 continue; 10591 } 10592 10593 if (auto *CurE = dyn_cast<MemberExpr>(E)) { 10594 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 10595 10596 if (isa<CXXThisExpr>(BaseE)) 10597 // We found a base expression: this->Val. 10598 RelevantExpr = CurE; 10599 else 10600 E = BaseE; 10601 10602 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 10603 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 10604 << CurE->getSourceRange(); 10605 break; 10606 } 10607 10608 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 10609 10610 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 10611 // A bit-field cannot appear in a map clause. 10612 // 10613 if (FD->isBitField()) { 10614 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 10615 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 10616 break; 10617 } 10618 10619 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10620 // If the type of a list item is a reference to a type T then the type 10621 // will be considered to be T for all purposes of this clause. 10622 QualType CurType = BaseE->getType().getNonReferenceType(); 10623 10624 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 10625 // A list item cannot be a variable that is a member of a structure with 10626 // a union type. 10627 // 10628 if (auto *RT = CurType->getAs<RecordType>()) 10629 if (RT->isUnionType()) { 10630 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 10631 << CurE->getSourceRange(); 10632 break; 10633 } 10634 10635 // If we got a member expression, we should not expect any array section 10636 // before that: 10637 // 10638 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 10639 // If a list item is an element of a structure, only the rightmost symbol 10640 // of the variable reference can be an array section. 10641 // 10642 AllowUnitySizeArraySection = false; 10643 AllowWholeSizeArraySection = false; 10644 10645 // Record the component. 10646 CurComponents.push_back( 10647 OMPClauseMappableExprCommon::MappableComponent(CurE, FD)); 10648 continue; 10649 } 10650 10651 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 10652 E = CurE->getBase()->IgnoreParenImpCasts(); 10653 10654 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 10655 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10656 << 0 << CurE->getSourceRange(); 10657 break; 10658 } 10659 10660 // If we got an array subscript that express the whole dimension we 10661 // can have any array expressions before. If it only expressing part of 10662 // the dimension, we can only have unitary-size array expressions. 10663 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 10664 E->getType())) 10665 AllowWholeSizeArraySection = false; 10666 10667 // Record the component - we don't have any declaration associated. 10668 CurComponents.push_back( 10669 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10670 continue; 10671 } 10672 10673 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 10674 E = CurE->getBase()->IgnoreParenImpCasts(); 10675 10676 auto CurType = 10677 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10678 10679 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10680 // If the type of a list item is a reference to a type T then the type 10681 // will be considered to be T for all purposes of this clause. 10682 if (CurType->isReferenceType()) 10683 CurType = CurType->getPointeeType(); 10684 10685 bool IsPointer = CurType->isAnyPointerType(); 10686 10687 if (!IsPointer && !CurType->isArrayType()) { 10688 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10689 << 0 << CurE->getSourceRange(); 10690 break; 10691 } 10692 10693 bool NotWhole = 10694 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 10695 bool NotUnity = 10696 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 10697 10698 if (AllowWholeSizeArraySection) { 10699 // Any array section is currently allowed. Allowing a whole size array 10700 // section implies allowing a unity array section as well. 10701 // 10702 // If this array section refers to the whole dimension we can still 10703 // accept other array sections before this one, except if the base is a 10704 // pointer. Otherwise, only unitary sections are accepted. 10705 if (NotWhole || IsPointer) 10706 AllowWholeSizeArraySection = false; 10707 } else if (AllowUnitySizeArraySection && NotUnity) { 10708 // A unity or whole array section is not allowed and that is not 10709 // compatible with the properties of the current array section. 10710 SemaRef.Diag( 10711 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 10712 << CurE->getSourceRange(); 10713 break; 10714 } 10715 10716 // Record the component - we don't have any declaration associated. 10717 CurComponents.push_back( 10718 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10719 continue; 10720 } 10721 10722 // If nothing else worked, this is not a valid map clause expression. 10723 SemaRef.Diag(ELoc, 10724 diag::err_omp_expected_named_var_member_or_array_expression) 10725 << ERange; 10726 break; 10727 } 10728 10729 return RelevantExpr; 10730 } 10731 10732 // Return true if expression E associated with value VD has conflicts with other 10733 // map information. 10734 static bool CheckMapConflicts( 10735 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 10736 bool CurrentRegionOnly, 10737 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 10738 OpenMPClauseKind CKind) { 10739 assert(VD && E); 10740 SourceLocation ELoc = E->getExprLoc(); 10741 SourceRange ERange = E->getSourceRange(); 10742 10743 // In order to easily check the conflicts we need to match each component of 10744 // the expression under test with the components of the expressions that are 10745 // already in the stack. 10746 10747 assert(!CurComponents.empty() && "Map clause expression with no components!"); 10748 assert(CurComponents.back().getAssociatedDeclaration() == VD && 10749 "Map clause expression with unexpected base!"); 10750 10751 // Variables to help detecting enclosing problems in data environment nests. 10752 bool IsEnclosedByDataEnvironmentExpr = false; 10753 const Expr *EnclosingExpr = nullptr; 10754 10755 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 10756 VD, CurrentRegionOnly, 10757 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 10758 StackComponents) -> bool { 10759 10760 assert(!StackComponents.empty() && 10761 "Map clause expression with no components!"); 10762 assert(StackComponents.back().getAssociatedDeclaration() == VD && 10763 "Map clause expression with unexpected base!"); 10764 10765 // The whole expression in the stack. 10766 auto *RE = StackComponents.front().getAssociatedExpression(); 10767 10768 // Expressions must start from the same base. Here we detect at which 10769 // point both expressions diverge from each other and see if we can 10770 // detect if the memory referred to both expressions is contiguous and 10771 // do not overlap. 10772 auto CI = CurComponents.rbegin(); 10773 auto CE = CurComponents.rend(); 10774 auto SI = StackComponents.rbegin(); 10775 auto SE = StackComponents.rend(); 10776 for (; CI != CE && SI != SE; ++CI, ++SI) { 10777 10778 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 10779 // At most one list item can be an array item derived from a given 10780 // variable in map clauses of the same construct. 10781 if (CurrentRegionOnly && 10782 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 10783 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 10784 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 10785 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 10786 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 10787 diag::err_omp_multiple_array_items_in_map_clause) 10788 << CI->getAssociatedExpression()->getSourceRange(); 10789 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 10790 diag::note_used_here) 10791 << SI->getAssociatedExpression()->getSourceRange(); 10792 return true; 10793 } 10794 10795 // Do both expressions have the same kind? 10796 if (CI->getAssociatedExpression()->getStmtClass() != 10797 SI->getAssociatedExpression()->getStmtClass()) 10798 break; 10799 10800 // Are we dealing with different variables/fields? 10801 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 10802 break; 10803 } 10804 // Check if the extra components of the expressions in the enclosing 10805 // data environment are redundant for the current base declaration. 10806 // If they are, the maps completely overlap, which is legal. 10807 for (; SI != SE; ++SI) { 10808 QualType Type; 10809 if (auto *ASE = 10810 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 10811 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 10812 } else if (auto *OASE = 10813 dyn_cast<OMPArraySectionExpr>(SI->getAssociatedExpression())) { 10814 auto *E = OASE->getBase()->IgnoreParenImpCasts(); 10815 Type = 10816 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10817 } 10818 if (Type.isNull() || Type->isAnyPointerType() || 10819 CheckArrayExpressionDoesNotReferToWholeSize( 10820 SemaRef, SI->getAssociatedExpression(), Type)) 10821 break; 10822 } 10823 10824 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10825 // List items of map clauses in the same construct must not share 10826 // original storage. 10827 // 10828 // If the expressions are exactly the same or one is a subset of the 10829 // other, it means they are sharing storage. 10830 if (CI == CE && SI == SE) { 10831 if (CurrentRegionOnly) { 10832 if (CKind == OMPC_map) 10833 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10834 else { 10835 assert(CKind == OMPC_to || CKind == OMPC_from); 10836 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10837 << ERange; 10838 } 10839 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10840 << RE->getSourceRange(); 10841 return true; 10842 } else { 10843 // If we find the same expression in the enclosing data environment, 10844 // that is legal. 10845 IsEnclosedByDataEnvironmentExpr = true; 10846 return false; 10847 } 10848 } 10849 10850 QualType DerivedType = 10851 std::prev(CI)->getAssociatedDeclaration()->getType(); 10852 SourceLocation DerivedLoc = 10853 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 10854 10855 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10856 // If the type of a list item is a reference to a type T then the type 10857 // will be considered to be T for all purposes of this clause. 10858 DerivedType = DerivedType.getNonReferenceType(); 10859 10860 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 10861 // A variable for which the type is pointer and an array section 10862 // derived from that variable must not appear as list items of map 10863 // clauses of the same construct. 10864 // 10865 // Also, cover one of the cases in: 10866 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10867 // If any part of the original storage of a list item has corresponding 10868 // storage in the device data environment, all of the original storage 10869 // must have corresponding storage in the device data environment. 10870 // 10871 if (DerivedType->isAnyPointerType()) { 10872 if (CI == CE || SI == SE) { 10873 SemaRef.Diag( 10874 DerivedLoc, 10875 diag::err_omp_pointer_mapped_along_with_derived_section) 10876 << DerivedLoc; 10877 } else { 10878 assert(CI != CE && SI != SE); 10879 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) 10880 << DerivedLoc; 10881 } 10882 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10883 << RE->getSourceRange(); 10884 return true; 10885 } 10886 10887 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10888 // List items of map clauses in the same construct must not share 10889 // original storage. 10890 // 10891 // An expression is a subset of the other. 10892 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 10893 if (CKind == OMPC_map) 10894 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10895 else { 10896 assert(CKind == OMPC_to || CKind == OMPC_from); 10897 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10898 << ERange; 10899 } 10900 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10901 << RE->getSourceRange(); 10902 return true; 10903 } 10904 10905 // The current expression uses the same base as other expression in the 10906 // data environment but does not contain it completely. 10907 if (!CurrentRegionOnly && SI != SE) 10908 EnclosingExpr = RE; 10909 10910 // The current expression is a subset of the expression in the data 10911 // environment. 10912 IsEnclosedByDataEnvironmentExpr |= 10913 (!CurrentRegionOnly && CI != CE && SI == SE); 10914 10915 return false; 10916 }); 10917 10918 if (CurrentRegionOnly) 10919 return FoundError; 10920 10921 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10922 // If any part of the original storage of a list item has corresponding 10923 // storage in the device data environment, all of the original storage must 10924 // have corresponding storage in the device data environment. 10925 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 10926 // If a list item is an element of a structure, and a different element of 10927 // the structure has a corresponding list item in the device data environment 10928 // prior to a task encountering the construct associated with the map clause, 10929 // then the list item must also have a corresponding list item in the device 10930 // data environment prior to the task encountering the construct. 10931 // 10932 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 10933 SemaRef.Diag(ELoc, 10934 diag::err_omp_original_storage_is_shared_and_does_not_contain) 10935 << ERange; 10936 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 10937 << EnclosingExpr->getSourceRange(); 10938 return true; 10939 } 10940 10941 return FoundError; 10942 } 10943 10944 namespace { 10945 // Utility struct that gathers all the related lists associated with a mappable 10946 // expression. 10947 struct MappableVarListInfo final { 10948 // The list of expressions. 10949 ArrayRef<Expr *> VarList; 10950 // The list of processed expressions. 10951 SmallVector<Expr *, 16> ProcessedVarList; 10952 // The mappble components for each expression. 10953 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 10954 // The base declaration of the variable. 10955 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 10956 10957 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 10958 // We have a list of components and base declarations for each entry in the 10959 // variable list. 10960 VarComponents.reserve(VarList.size()); 10961 VarBaseDeclarations.reserve(VarList.size()); 10962 } 10963 }; 10964 } 10965 10966 // Check the validity of the provided variable list for the provided clause kind 10967 // \a CKind. In the check process the valid expressions, and mappable expression 10968 // components and variables are extracted and used to fill \a Vars, 10969 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 10970 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 10971 static void 10972 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 10973 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 10974 SourceLocation StartLoc, 10975 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 10976 bool IsMapTypeImplicit = false) { 10977 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 10978 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 10979 "Unexpected clause kind with mappable expressions!"); 10980 10981 // Keep track of the mappable components and base declarations in this clause. 10982 // Each entry in the list is going to have a list of components associated. We 10983 // record each set of the components so that we can build the clause later on. 10984 // In the end we should have the same amount of declarations and component 10985 // lists. 10986 10987 for (auto &RE : MVLI.VarList) { 10988 assert(RE && "Null expr in omp to/from/map clause"); 10989 SourceLocation ELoc = RE->getExprLoc(); 10990 10991 auto *VE = RE->IgnoreParenLValueCasts(); 10992 10993 if (VE->isValueDependent() || VE->isTypeDependent() || 10994 VE->isInstantiationDependent() || 10995 VE->containsUnexpandedParameterPack()) { 10996 // We can only analyze this information once the missing information is 10997 // resolved. 10998 MVLI.ProcessedVarList.push_back(RE); 10999 continue; 11000 } 11001 11002 auto *SimpleExpr = RE->IgnoreParenCasts(); 11003 11004 if (!RE->IgnoreParenImpCasts()->isLValue()) { 11005 SemaRef.Diag(ELoc, 11006 diag::err_omp_expected_named_var_member_or_array_expression) 11007 << RE->getSourceRange(); 11008 continue; 11009 } 11010 11011 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 11012 ValueDecl *CurDeclaration = nullptr; 11013 11014 // Obtain the array or member expression bases if required. Also, fill the 11015 // components array with all the components identified in the process. 11016 auto *BE = 11017 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind); 11018 if (!BE) 11019 continue; 11020 11021 assert(!CurComponents.empty() && 11022 "Invalid mappable expression information."); 11023 11024 // For the following checks, we rely on the base declaration which is 11025 // expected to be associated with the last component. The declaration is 11026 // expected to be a variable or a field (if 'this' is being mapped). 11027 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 11028 assert(CurDeclaration && "Null decl on map clause."); 11029 assert( 11030 CurDeclaration->isCanonicalDecl() && 11031 "Expecting components to have associated only canonical declarations."); 11032 11033 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 11034 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 11035 11036 assert((VD || FD) && "Only variables or fields are expected here!"); 11037 (void)FD; 11038 11039 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 11040 // threadprivate variables cannot appear in a map clause. 11041 // OpenMP 4.5 [2.10.5, target update Construct] 11042 // threadprivate variables cannot appear in a from clause. 11043 if (VD && DSAS->isThreadPrivate(VD)) { 11044 auto DVar = DSAS->getTopDSA(VD, false); 11045 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 11046 << getOpenMPClauseName(CKind); 11047 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 11048 continue; 11049 } 11050 11051 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 11052 // A list item cannot appear in both a map clause and a data-sharing 11053 // attribute clause on the same construct. 11054 11055 // Check conflicts with other map clause expressions. We check the conflicts 11056 // with the current construct separately from the enclosing data 11057 // environment, because the restrictions are different. We only have to 11058 // check conflicts across regions for the map clauses. 11059 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 11060 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 11061 break; 11062 if (CKind == OMPC_map && 11063 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 11064 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 11065 break; 11066 11067 // OpenMP 4.5 [2.10.5, target update Construct] 11068 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11069 // If the type of a list item is a reference to a type T then the type will 11070 // be considered to be T for all purposes of this clause. 11071 QualType Type = CurDeclaration->getType().getNonReferenceType(); 11072 11073 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 11074 // A list item in a to or from clause must have a mappable type. 11075 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 11076 // A list item must have a mappable type. 11077 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 11078 DSAS, Type)) 11079 continue; 11080 11081 if (CKind == OMPC_map) { 11082 // target enter data 11083 // OpenMP [2.10.2, Restrictions, p. 99] 11084 // A map-type must be specified in all map clauses and must be either 11085 // to or alloc. 11086 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 11087 if (DKind == OMPD_target_enter_data && 11088 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 11089 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 11090 << (IsMapTypeImplicit ? 1 : 0) 11091 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 11092 << getOpenMPDirectiveName(DKind); 11093 continue; 11094 } 11095 11096 // target exit_data 11097 // OpenMP [2.10.3, Restrictions, p. 102] 11098 // A map-type must be specified in all map clauses and must be either 11099 // from, release, or delete. 11100 if (DKind == OMPD_target_exit_data && 11101 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 11102 MapType == OMPC_MAP_delete)) { 11103 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 11104 << (IsMapTypeImplicit ? 1 : 0) 11105 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 11106 << getOpenMPDirectiveName(DKind); 11107 continue; 11108 } 11109 11110 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 11111 // A list item cannot appear in both a map clause and a data-sharing 11112 // attribute clause on the same construct 11113 if (DKind == OMPD_target && VD) { 11114 auto DVar = DSAS->getTopDSA(VD, false); 11115 if (isOpenMPPrivate(DVar.CKind)) { 11116 SemaRef.Diag(ELoc, diag::err_omp_variable_in_map_and_dsa) 11117 << getOpenMPClauseName(DVar.CKind) 11118 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 11119 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 11120 continue; 11121 } 11122 } 11123 } 11124 11125 // Save the current expression. 11126 MVLI.ProcessedVarList.push_back(RE); 11127 11128 // Store the components in the stack so that they can be used to check 11129 // against other clauses later on. 11130 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents); 11131 11132 // Save the components and declaration to create the clause. For purposes of 11133 // the clause creation, any component list that has has base 'this' uses 11134 // null as base declaration. 11135 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11136 MVLI.VarComponents.back().append(CurComponents.begin(), 11137 CurComponents.end()); 11138 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 11139 : CurDeclaration); 11140 } 11141 } 11142 11143 OMPClause * 11144 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 11145 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 11146 SourceLocation MapLoc, SourceLocation ColonLoc, 11147 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 11148 SourceLocation LParenLoc, SourceLocation EndLoc) { 11149 MappableVarListInfo MVLI(VarList); 11150 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 11151 MapType, IsMapTypeImplicit); 11152 11153 // We need to produce a map clause even if we don't have variables so that 11154 // other diagnostics related with non-existing map clauses are accurate. 11155 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11156 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11157 MVLI.VarComponents, MapTypeModifier, MapType, 11158 IsMapTypeImplicit, MapLoc); 11159 } 11160 11161 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 11162 TypeResult ParsedType) { 11163 assert(ParsedType.isUsable()); 11164 11165 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 11166 if (ReductionType.isNull()) 11167 return QualType(); 11168 11169 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 11170 // A type name in a declare reduction directive cannot be a function type, an 11171 // array type, a reference type, or a type qualified with const, volatile or 11172 // restrict. 11173 if (ReductionType.hasQualifiers()) { 11174 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 11175 return QualType(); 11176 } 11177 11178 if (ReductionType->isFunctionType()) { 11179 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 11180 return QualType(); 11181 } 11182 if (ReductionType->isReferenceType()) { 11183 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 11184 return QualType(); 11185 } 11186 if (ReductionType->isArrayType()) { 11187 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 11188 return QualType(); 11189 } 11190 return ReductionType; 11191 } 11192 11193 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 11194 Scope *S, DeclContext *DC, DeclarationName Name, 11195 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 11196 AccessSpecifier AS, Decl *PrevDeclInScope) { 11197 SmallVector<Decl *, 8> Decls; 11198 Decls.reserve(ReductionTypes.size()); 11199 11200 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 11201 ForRedeclaration); 11202 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 11203 // A reduction-identifier may not be re-declared in the current scope for the 11204 // same type or for a type that is compatible according to the base language 11205 // rules. 11206 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 11207 OMPDeclareReductionDecl *PrevDRD = nullptr; 11208 bool InCompoundScope = true; 11209 if (S != nullptr) { 11210 // Find previous declaration with the same name not referenced in other 11211 // declarations. 11212 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 11213 InCompoundScope = 11214 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 11215 LookupName(Lookup, S); 11216 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 11217 /*AllowInlineNamespace=*/false); 11218 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 11219 auto Filter = Lookup.makeFilter(); 11220 while (Filter.hasNext()) { 11221 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 11222 if (InCompoundScope) { 11223 auto I = UsedAsPrevious.find(PrevDecl); 11224 if (I == UsedAsPrevious.end()) 11225 UsedAsPrevious[PrevDecl] = false; 11226 if (auto *D = PrevDecl->getPrevDeclInScope()) 11227 UsedAsPrevious[D] = true; 11228 } 11229 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 11230 PrevDecl->getLocation(); 11231 } 11232 Filter.done(); 11233 if (InCompoundScope) { 11234 for (auto &PrevData : UsedAsPrevious) { 11235 if (!PrevData.second) { 11236 PrevDRD = PrevData.first; 11237 break; 11238 } 11239 } 11240 } 11241 } else if (PrevDeclInScope != nullptr) { 11242 auto *PrevDRDInScope = PrevDRD = 11243 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 11244 do { 11245 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 11246 PrevDRDInScope->getLocation(); 11247 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 11248 } while (PrevDRDInScope != nullptr); 11249 } 11250 for (auto &TyData : ReductionTypes) { 11251 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 11252 bool Invalid = false; 11253 if (I != PreviousRedeclTypes.end()) { 11254 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 11255 << TyData.first; 11256 Diag(I->second, diag::note_previous_definition); 11257 Invalid = true; 11258 } 11259 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 11260 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 11261 Name, TyData.first, PrevDRD); 11262 DC->addDecl(DRD); 11263 DRD->setAccess(AS); 11264 Decls.push_back(DRD); 11265 if (Invalid) 11266 DRD->setInvalidDecl(); 11267 else 11268 PrevDRD = DRD; 11269 } 11270 11271 return DeclGroupPtrTy::make( 11272 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 11273 } 11274 11275 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 11276 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11277 11278 // Enter new function scope. 11279 PushFunctionScope(); 11280 getCurFunction()->setHasBranchProtectedScope(); 11281 getCurFunction()->setHasOMPDeclareReductionCombiner(); 11282 11283 if (S != nullptr) 11284 PushDeclContext(S, DRD); 11285 else 11286 CurContext = DRD; 11287 11288 PushExpressionEvaluationContext(PotentiallyEvaluated); 11289 11290 QualType ReductionType = DRD->getType(); 11291 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 11292 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 11293 // uses semantics of argument handles by value, but it should be passed by 11294 // reference. C lang does not support references, so pass all parameters as 11295 // pointers. 11296 // Create 'T omp_in;' variable. 11297 auto *OmpInParm = 11298 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 11299 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 11300 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 11301 // uses semantics of argument handles by value, but it should be passed by 11302 // reference. C lang does not support references, so pass all parameters as 11303 // pointers. 11304 // Create 'T omp_out;' variable. 11305 auto *OmpOutParm = 11306 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 11307 if (S != nullptr) { 11308 PushOnScopeChains(OmpInParm, S); 11309 PushOnScopeChains(OmpOutParm, S); 11310 } else { 11311 DRD->addDecl(OmpInParm); 11312 DRD->addDecl(OmpOutParm); 11313 } 11314 } 11315 11316 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 11317 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11318 DiscardCleanupsInEvaluationContext(); 11319 PopExpressionEvaluationContext(); 11320 11321 PopDeclContext(); 11322 PopFunctionScopeInfo(); 11323 11324 if (Combiner != nullptr) 11325 DRD->setCombiner(Combiner); 11326 else 11327 DRD->setInvalidDecl(); 11328 } 11329 11330 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 11331 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11332 11333 // Enter new function scope. 11334 PushFunctionScope(); 11335 getCurFunction()->setHasBranchProtectedScope(); 11336 11337 if (S != nullptr) 11338 PushDeclContext(S, DRD); 11339 else 11340 CurContext = DRD; 11341 11342 PushExpressionEvaluationContext(PotentiallyEvaluated); 11343 11344 QualType ReductionType = DRD->getType(); 11345 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 11346 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 11347 // uses semantics of argument handles by value, but it should be passed by 11348 // reference. C lang does not support references, so pass all parameters as 11349 // pointers. 11350 // Create 'T omp_priv;' variable. 11351 auto *OmpPrivParm = 11352 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 11353 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 11354 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 11355 // uses semantics of argument handles by value, but it should be passed by 11356 // reference. C lang does not support references, so pass all parameters as 11357 // pointers. 11358 // Create 'T omp_orig;' variable. 11359 auto *OmpOrigParm = 11360 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 11361 if (S != nullptr) { 11362 PushOnScopeChains(OmpPrivParm, S); 11363 PushOnScopeChains(OmpOrigParm, S); 11364 } else { 11365 DRD->addDecl(OmpPrivParm); 11366 DRD->addDecl(OmpOrigParm); 11367 } 11368 } 11369 11370 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, 11371 Expr *Initializer) { 11372 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11373 DiscardCleanupsInEvaluationContext(); 11374 PopExpressionEvaluationContext(); 11375 11376 PopDeclContext(); 11377 PopFunctionScopeInfo(); 11378 11379 if (Initializer != nullptr) 11380 DRD->setInitializer(Initializer); 11381 else 11382 DRD->setInvalidDecl(); 11383 } 11384 11385 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 11386 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 11387 for (auto *D : DeclReductions.get()) { 11388 if (IsValid) { 11389 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11390 if (S != nullptr) 11391 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 11392 } else 11393 D->setInvalidDecl(); 11394 } 11395 return DeclReductions; 11396 } 11397 11398 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 11399 SourceLocation StartLoc, 11400 SourceLocation LParenLoc, 11401 SourceLocation EndLoc) { 11402 Expr *ValExpr = NumTeams; 11403 11404 // OpenMP [teams Constrcut, Restrictions] 11405 // The num_teams expression must evaluate to a positive integer value. 11406 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 11407 /*StrictlyPositive=*/true)) 11408 return nullptr; 11409 11410 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11411 } 11412 11413 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 11414 SourceLocation StartLoc, 11415 SourceLocation LParenLoc, 11416 SourceLocation EndLoc) { 11417 Expr *ValExpr = ThreadLimit; 11418 11419 // OpenMP [teams Constrcut, Restrictions] 11420 // The thread_limit expression must evaluate to a positive integer value. 11421 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 11422 /*StrictlyPositive=*/true)) 11423 return nullptr; 11424 11425 return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, 11426 EndLoc); 11427 } 11428 11429 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 11430 SourceLocation StartLoc, 11431 SourceLocation LParenLoc, 11432 SourceLocation EndLoc) { 11433 Expr *ValExpr = Priority; 11434 11435 // OpenMP [2.9.1, task Constrcut] 11436 // The priority-value is a non-negative numerical scalar expression. 11437 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 11438 /*StrictlyPositive=*/false)) 11439 return nullptr; 11440 11441 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11442 } 11443 11444 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 11445 SourceLocation StartLoc, 11446 SourceLocation LParenLoc, 11447 SourceLocation EndLoc) { 11448 Expr *ValExpr = Grainsize; 11449 11450 // OpenMP [2.9.2, taskloop Constrcut] 11451 // The parameter of the grainsize clause must be a positive integer 11452 // expression. 11453 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 11454 /*StrictlyPositive=*/true)) 11455 return nullptr; 11456 11457 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11458 } 11459 11460 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 11461 SourceLocation StartLoc, 11462 SourceLocation LParenLoc, 11463 SourceLocation EndLoc) { 11464 Expr *ValExpr = NumTasks; 11465 11466 // OpenMP [2.9.2, taskloop Constrcut] 11467 // The parameter of the num_tasks clause must be a positive integer 11468 // expression. 11469 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 11470 /*StrictlyPositive=*/true)) 11471 return nullptr; 11472 11473 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11474 } 11475 11476 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 11477 SourceLocation LParenLoc, 11478 SourceLocation EndLoc) { 11479 // OpenMP [2.13.2, critical construct, Description] 11480 // ... where hint-expression is an integer constant expression that evaluates 11481 // to a valid lock hint. 11482 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 11483 if (HintExpr.isInvalid()) 11484 return nullptr; 11485 return new (Context) 11486 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 11487 } 11488 11489 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 11490 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 11491 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 11492 SourceLocation EndLoc) { 11493 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 11494 std::string Values; 11495 Values += "'"; 11496 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 11497 Values += "'"; 11498 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 11499 << Values << getOpenMPClauseName(OMPC_dist_schedule); 11500 return nullptr; 11501 } 11502 Expr *ValExpr = ChunkSize; 11503 Stmt *HelperValStmt = nullptr; 11504 if (ChunkSize) { 11505 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 11506 !ChunkSize->isInstantiationDependent() && 11507 !ChunkSize->containsUnexpandedParameterPack()) { 11508 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 11509 ExprResult Val = 11510 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 11511 if (Val.isInvalid()) 11512 return nullptr; 11513 11514 ValExpr = Val.get(); 11515 11516 // OpenMP [2.7.1, Restrictions] 11517 // chunk_size must be a loop invariant integer expression with a positive 11518 // value. 11519 llvm::APSInt Result; 11520 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 11521 if (Result.isSigned() && !Result.isStrictlyPositive()) { 11522 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 11523 << "dist_schedule" << ChunkSize->getSourceRange(); 11524 return nullptr; 11525 } 11526 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 11527 !CurContext->isDependentContext()) { 11528 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11529 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11530 HelperValStmt = buildPreInits(Context, Captures); 11531 } 11532 } 11533 } 11534 11535 return new (Context) 11536 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 11537 Kind, ValExpr, HelperValStmt); 11538 } 11539 11540 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 11541 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 11542 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 11543 SourceLocation KindLoc, SourceLocation EndLoc) { 11544 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 11545 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || 11546 Kind != OMPC_DEFAULTMAP_scalar) { 11547 std::string Value; 11548 SourceLocation Loc; 11549 Value += "'"; 11550 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 11551 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11552 OMPC_DEFAULTMAP_MODIFIER_tofrom); 11553 Loc = MLoc; 11554 } else { 11555 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11556 OMPC_DEFAULTMAP_scalar); 11557 Loc = KindLoc; 11558 } 11559 Value += "'"; 11560 Diag(Loc, diag::err_omp_unexpected_clause_value) 11561 << Value << getOpenMPClauseName(OMPC_defaultmap); 11562 return nullptr; 11563 } 11564 11565 return new (Context) 11566 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 11567 } 11568 11569 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 11570 DeclContext *CurLexicalContext = getCurLexicalContext(); 11571 if (!CurLexicalContext->isFileContext() && 11572 !CurLexicalContext->isExternCContext() && 11573 !CurLexicalContext->isExternCXXContext()) { 11574 Diag(Loc, diag::err_omp_region_not_file_context); 11575 return false; 11576 } 11577 if (IsInOpenMPDeclareTargetContext) { 11578 Diag(Loc, diag::err_omp_enclosed_declare_target); 11579 return false; 11580 } 11581 11582 IsInOpenMPDeclareTargetContext = true; 11583 return true; 11584 } 11585 11586 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 11587 assert(IsInOpenMPDeclareTargetContext && 11588 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 11589 11590 IsInOpenMPDeclareTargetContext = false; 11591 } 11592 11593 void 11594 Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, 11595 const DeclarationNameInfo &Id, 11596 OMPDeclareTargetDeclAttr::MapTypeTy MT, 11597 NamedDeclSetType &SameDirectiveDecls) { 11598 LookupResult Lookup(*this, Id, LookupOrdinaryName); 11599 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 11600 11601 if (Lookup.isAmbiguous()) 11602 return; 11603 Lookup.suppressDiagnostics(); 11604 11605 if (!Lookup.isSingleResult()) { 11606 if (TypoCorrection Corrected = 11607 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 11608 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 11609 CTK_ErrorRecovery)) { 11610 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 11611 << Id.getName()); 11612 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 11613 return; 11614 } 11615 11616 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 11617 return; 11618 } 11619 11620 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 11621 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 11622 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 11623 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 11624 11625 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 11626 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 11627 ND->addAttr(A); 11628 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11629 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 11630 checkDeclIsAllowedInOpenMPTarget(nullptr, ND); 11631 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 11632 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 11633 << Id.getName(); 11634 } 11635 } else 11636 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 11637 } 11638 11639 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 11640 Sema &SemaRef, Decl *D) { 11641 if (!D) 11642 return; 11643 Decl *LD = nullptr; 11644 if (isa<TagDecl>(D)) { 11645 LD = cast<TagDecl>(D)->getDefinition(); 11646 } else if (isa<VarDecl>(D)) { 11647 LD = cast<VarDecl>(D)->getDefinition(); 11648 11649 // If this is an implicit variable that is legal and we do not need to do 11650 // anything. 11651 if (cast<VarDecl>(D)->isImplicit()) { 11652 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11653 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11654 D->addAttr(A); 11655 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11656 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11657 return; 11658 } 11659 11660 } else if (isa<FunctionDecl>(D)) { 11661 const FunctionDecl *FD = nullptr; 11662 if (cast<FunctionDecl>(D)->hasBody(FD)) 11663 LD = const_cast<FunctionDecl *>(FD); 11664 11665 // If the definition is associated with the current declaration in the 11666 // target region (it can be e.g. a lambda) that is legal and we do not need 11667 // to do anything else. 11668 if (LD == D) { 11669 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11670 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11671 D->addAttr(A); 11672 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11673 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11674 return; 11675 } 11676 } 11677 if (!LD) 11678 LD = D; 11679 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 11680 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 11681 // Outlined declaration is not declared target. 11682 if (LD->isOutOfLine()) { 11683 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11684 SemaRef.Diag(SL, diag::note_used_here) << SR; 11685 } else { 11686 DeclContext *DC = LD->getDeclContext(); 11687 while (DC) { 11688 if (isa<FunctionDecl>(DC) && 11689 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 11690 break; 11691 DC = DC->getParent(); 11692 } 11693 if (DC) 11694 return; 11695 11696 // Is not declared in target context. 11697 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11698 SemaRef.Diag(SL, diag::note_used_here) << SR; 11699 } 11700 // Mark decl as declared target to prevent further diagnostic. 11701 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11702 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11703 D->addAttr(A); 11704 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11705 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11706 } 11707 } 11708 11709 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 11710 Sema &SemaRef, DSAStackTy *Stack, 11711 ValueDecl *VD) { 11712 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 11713 return true; 11714 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) 11715 return false; 11716 return true; 11717 } 11718 11719 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) { 11720 if (!D || D->isInvalidDecl()) 11721 return; 11722 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 11723 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 11724 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 11725 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11726 if (DSAStack->isThreadPrivate(VD)) { 11727 Diag(SL, diag::err_omp_threadprivate_in_target); 11728 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 11729 return; 11730 } 11731 } 11732 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 11733 // Problem if any with var declared with incomplete type will be reported 11734 // as normal, so no need to check it here. 11735 if ((E || !VD->getType()->isIncompleteType()) && 11736 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 11737 // Mark decl as declared target to prevent further diagnostic. 11738 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { 11739 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11740 Context, OMPDeclareTargetDeclAttr::MT_To); 11741 VD->addAttr(A); 11742 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11743 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 11744 } 11745 return; 11746 } 11747 } 11748 if (!E) { 11749 // Checking declaration inside declare target region. 11750 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 11751 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { 11752 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11753 Context, OMPDeclareTargetDeclAttr::MT_To); 11754 D->addAttr(A); 11755 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11756 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11757 } 11758 return; 11759 } 11760 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 11761 } 11762 11763 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 11764 SourceLocation StartLoc, 11765 SourceLocation LParenLoc, 11766 SourceLocation EndLoc) { 11767 MappableVarListInfo MVLI(VarList); 11768 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 11769 if (MVLI.ProcessedVarList.empty()) 11770 return nullptr; 11771 11772 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11773 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11774 MVLI.VarComponents); 11775 } 11776 11777 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 11778 SourceLocation StartLoc, 11779 SourceLocation LParenLoc, 11780 SourceLocation EndLoc) { 11781 MappableVarListInfo MVLI(VarList); 11782 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 11783 if (MVLI.ProcessedVarList.empty()) 11784 return nullptr; 11785 11786 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11787 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11788 MVLI.VarComponents); 11789 } 11790 11791 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 11792 SourceLocation StartLoc, 11793 SourceLocation LParenLoc, 11794 SourceLocation EndLoc) { 11795 SmallVector<Expr *, 8> Vars; 11796 for (auto &RefExpr : VarList) { 11797 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 11798 SourceLocation ELoc; 11799 SourceRange ERange; 11800 Expr *SimpleRefExpr = RefExpr; 11801 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11802 if (Res.second) { 11803 // It will be analyzed later. 11804 Vars.push_back(RefExpr); 11805 } 11806 ValueDecl *D = Res.first; 11807 if (!D) 11808 continue; 11809 11810 QualType Type = D->getType(); 11811 // item should be a pointer or reference to pointer 11812 if (!Type.getNonReferenceType()->isPointerType()) { 11813 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 11814 << 0 << RefExpr->getSourceRange(); 11815 continue; 11816 } 11817 Vars.push_back(RefExpr->IgnoreParens()); 11818 } 11819 11820 if (Vars.empty()) 11821 return nullptr; 11822 11823 return OMPUseDevicePtrClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11824 Vars); 11825 } 11826 11827 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 11828 SourceLocation StartLoc, 11829 SourceLocation LParenLoc, 11830 SourceLocation EndLoc) { 11831 SmallVector<Expr *, 8> Vars; 11832 for (auto &RefExpr : VarList) { 11833 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 11834 SourceLocation ELoc; 11835 SourceRange ERange; 11836 Expr *SimpleRefExpr = RefExpr; 11837 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11838 if (Res.second) { 11839 // It will be analyzed later. 11840 Vars.push_back(RefExpr); 11841 } 11842 ValueDecl *D = Res.first; 11843 if (!D) 11844 continue; 11845 11846 QualType Type = D->getType(); 11847 // item should be a pointer or array or reference to pointer or array 11848 if (!Type.getNonReferenceType()->isPointerType() && 11849 !Type.getNonReferenceType()->isArrayType()) { 11850 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 11851 << 0 << RefExpr->getSourceRange(); 11852 continue; 11853 } 11854 Vars.push_back(RefExpr->IgnoreParens()); 11855 } 11856 11857 if (Vars.empty()) 11858 return nullptr; 11859 11860 return OMPIsDevicePtrClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11861 Vars); 11862 } 11863