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 /// Struct that associates a component with the clause kind where they are 76 /// found. 77 struct MappedExprComponentTy { 78 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 79 OpenMPClauseKind Kind = OMPC_unknown; 80 }; 81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy> 82 MappedExprComponentsTy; 83 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>> 84 CriticalsWithHintsTy; 85 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy> 86 DoacrossDependMapTy; 87 88 struct SharingMapTy final { 89 DeclSAMapTy SharingMap; 90 AlignedMapTy AlignedMap; 91 MappedExprComponentsTy MappedExprComponents; 92 LoopControlVariablesMapTy LCVMap; 93 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 94 SourceLocation DefaultAttrLoc; 95 OpenMPDirectiveKind Directive = OMPD_unknown; 96 DeclarationNameInfo DirectiveName; 97 Scope *CurScope = nullptr; 98 SourceLocation ConstructLoc; 99 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 100 /// get the data (loop counters etc.) about enclosing loop-based construct. 101 /// This data is required during codegen. 102 DoacrossDependMapTy DoacrossDepends; 103 /// \brief first argument (Expr *) contains optional argument of the 104 /// 'ordered' clause, the second one is true if the regions has 'ordered' 105 /// clause, false otherwise. 106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion; 107 bool NowaitRegion = false; 108 bool CancelRegion = false; 109 unsigned AssociatedLoops = 1; 110 SourceLocation InnerTeamsRegionLoc; 111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 112 Scope *CurScope, SourceLocation Loc) 113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 114 ConstructLoc(Loc) {} 115 SharingMapTy() {} 116 }; 117 118 typedef SmallVector<SharingMapTy, 4> StackTy; 119 120 /// \brief Stack of used declaration and their data-sharing attributes. 121 StackTy Stack; 122 /// \brief true, if check for DSA must be from parent directive, false, if 123 /// from current directive. 124 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 125 Sema &SemaRef; 126 bool ForceCapturing = false; 127 CriticalsWithHintsTy Criticals; 128 129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; 130 131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D); 132 133 /// \brief Checks if the variable is a local for OpenMP region. 134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); 135 136 public: 137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {} 138 139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 141 142 bool isForceVarCapturing() const { return ForceCapturing; } 143 void setForceVarCapturing(bool V) { ForceCapturing = V; } 144 145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 146 Scope *CurScope, SourceLocation Loc) { 147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc)); 148 Stack.back().DefaultAttrLoc = Loc; 149 } 150 151 void pop() { 152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!"); 153 Stack.pop_back(); 154 } 155 156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) { 157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint); 158 } 159 const std::pair<OMPCriticalDirective *, llvm::APSInt> 160 getCriticalWithHint(const DeclarationNameInfo &Name) const { 161 auto I = Criticals.find(Name.getAsString()); 162 if (I != Criticals.end()) 163 return I->second; 164 return std::make_pair(nullptr, llvm::APSInt()); 165 } 166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet, 167 /// add it and return NULL; otherwise return previous occurrence's expression 168 /// for diagnostics. 169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE); 170 171 /// \brief Register specified variable as loop control variable. 172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture); 173 /// \brief Check if the specified variable is a loop control variable for 174 /// current region. 175 /// \return The index of the loop control variable in the list of associated 176 /// for-loops (from outer to inner). 177 LCDeclInfo isLoopControlVariable(ValueDecl *D); 178 /// \brief Check if the specified variable is a loop control variable for 179 /// parent region. 180 /// \return The index of the loop control variable in the list of associated 181 /// for-loops (from outer to inner). 182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D); 183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in 184 /// parent directive. 185 ValueDecl *getParentLoopControlVariable(unsigned I); 186 187 /// \brief Adds explicit data sharing attribute to the specified declaration. 188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 189 DeclRefExpr *PrivateCopy = nullptr); 190 191 /// \brief Returns data sharing attributes from top of the stack for the 192 /// specified declaration. 193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 194 /// \brief Returns data-sharing attributes for the specified declaration. 195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent); 196 /// \brief Checks if the specified variables has data-sharing attributes which 197 /// match specified \a CPred predicate in any directive which matches \a DPred 198 /// predicate. 199 DSAVarData hasDSA(ValueDecl *D, 200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 202 bool FromParent); 203 /// \brief Checks if the specified variables has data-sharing attributes which 204 /// match specified \a CPred predicate in any innermost directive which 205 /// matches \a DPred predicate. 206 DSAVarData 207 hasInnermostDSA(ValueDecl *D, 208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 210 bool FromParent); 211 /// \brief Checks if the specified variables has explicit data-sharing 212 /// attributes which match specified \a CPred predicate at the specified 213 /// OpenMP region. 214 bool hasExplicitDSA(ValueDecl *D, 215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 216 unsigned Level, bool NotLastprivate = false); 217 218 /// \brief Returns true if the directive at level \Level matches in the 219 /// specified \a DPred predicate. 220 bool hasExplicitDirective( 221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 222 unsigned Level); 223 224 /// \brief Finds a directive which matches specified \a DPred predicate. 225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind, 226 const DeclarationNameInfo &, 227 SourceLocation)> &DPred, 228 bool FromParent); 229 230 /// \brief Returns currently analyzed directive. 231 OpenMPDirectiveKind getCurrentDirective() const { 232 return Stack.back().Directive; 233 } 234 /// \brief Returns parent directive. 235 OpenMPDirectiveKind getParentDirective() const { 236 if (Stack.size() > 2) 237 return Stack[Stack.size() - 2].Directive; 238 return OMPD_unknown; 239 } 240 241 /// \brief Set default data sharing attribute to none. 242 void setDefaultDSANone(SourceLocation Loc) { 243 Stack.back().DefaultAttr = DSA_none; 244 Stack.back().DefaultAttrLoc = Loc; 245 } 246 /// \brief Set default data sharing attribute to shared. 247 void setDefaultDSAShared(SourceLocation Loc) { 248 Stack.back().DefaultAttr = DSA_shared; 249 Stack.back().DefaultAttrLoc = Loc; 250 } 251 252 DefaultDataSharingAttributes getDefaultDSA() const { 253 return Stack.back().DefaultAttr; 254 } 255 SourceLocation getDefaultDSALocation() const { 256 return Stack.back().DefaultAttrLoc; 257 } 258 259 /// \brief Checks if the specified variable is a threadprivate. 260 bool isThreadPrivate(VarDecl *D) { 261 DSAVarData DVar = getTopDSA(D, false); 262 return isOpenMPThreadPrivate(DVar.CKind); 263 } 264 265 /// \brief Marks current region as ordered (it has an 'ordered' clause). 266 void setOrderedRegion(bool IsOrdered, Expr *Param) { 267 Stack.back().OrderedRegion.setInt(IsOrdered); 268 Stack.back().OrderedRegion.setPointer(Param); 269 } 270 /// \brief Returns true, if parent region is ordered (has associated 271 /// 'ordered' clause), false - otherwise. 272 bool isParentOrderedRegion() const { 273 if (Stack.size() > 2) 274 return Stack[Stack.size() - 2].OrderedRegion.getInt(); 275 return false; 276 } 277 /// \brief Returns optional parameter for the ordered region. 278 Expr *getParentOrderedRegionParam() const { 279 if (Stack.size() > 2) 280 return Stack[Stack.size() - 2].OrderedRegion.getPointer(); 281 return nullptr; 282 } 283 /// \brief Marks current region as nowait (it has a 'nowait' clause). 284 void setNowaitRegion(bool IsNowait = true) { 285 Stack.back().NowaitRegion = IsNowait; 286 } 287 /// \brief Returns true, if parent region is nowait (has associated 288 /// 'nowait' clause), false - otherwise. 289 bool isParentNowaitRegion() const { 290 if (Stack.size() > 2) 291 return Stack[Stack.size() - 2].NowaitRegion; 292 return false; 293 } 294 /// \brief Marks parent region as cancel region. 295 void setParentCancelRegion(bool Cancel = true) { 296 if (Stack.size() > 2) 297 Stack[Stack.size() - 2].CancelRegion = 298 Stack[Stack.size() - 2].CancelRegion || Cancel; 299 } 300 /// \brief Return true if current region has inner cancel construct. 301 bool isCancelRegion() const { return Stack.back().CancelRegion; } 302 303 /// \brief Set collapse value for the region. 304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; } 305 /// \brief Return collapse value for region. 306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; } 307 308 /// \brief Marks current target region as one with closely nested teams 309 /// region. 310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 311 if (Stack.size() > 2) 312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc; 313 } 314 /// \brief Returns true, if current region has closely nested teams region. 315 bool hasInnerTeamsRegion() const { 316 return getInnerTeamsRegionLoc().isValid(); 317 } 318 /// \brief Returns location of the nested teams region (if any). 319 SourceLocation getInnerTeamsRegionLoc() const { 320 if (Stack.size() > 1) 321 return Stack.back().InnerTeamsRegionLoc; 322 return SourceLocation(); 323 } 324 325 Scope *getCurScope() const { return Stack.back().CurScope; } 326 Scope *getCurScope() { return Stack.back().CurScope; } 327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; } 328 329 /// Do the check specified in \a Check to all component lists and return true 330 /// if any issue is found. 331 bool checkMappableExprComponentListsForDecl( 332 ValueDecl *VD, bool CurrentRegionOnly, 333 const llvm::function_ref< 334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 335 OpenMPClauseKind)> &Check) { 336 auto SI = Stack.rbegin(); 337 auto SE = Stack.rend(); 338 339 if (SI == SE) 340 return false; 341 342 if (CurrentRegionOnly) { 343 SE = std::next(SI); 344 } else { 345 ++SI; 346 } 347 348 for (; SI != SE; ++SI) { 349 auto MI = SI->MappedExprComponents.find(VD); 350 if (MI != SI->MappedExprComponents.end()) 351 for (auto &L : MI->second.Components) 352 if (Check(L, MI->second.Kind)) 353 return true; 354 } 355 return false; 356 } 357 358 /// Create a new mappable expression component list associated with a given 359 /// declaration and initialize it with the provided list of components. 360 void addMappableExpressionComponents( 361 ValueDecl *VD, 362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 363 OpenMPClauseKind WhereFoundClauseKind) { 364 assert(Stack.size() > 1 && 365 "Not expecting to retrieve components from a empty stack!"); 366 auto &MEC = Stack.back().MappedExprComponents[VD]; 367 // Create new entry and append the new components there. 368 MEC.Components.resize(MEC.Components.size() + 1); 369 MEC.Components.back().append(Components.begin(), Components.end()); 370 MEC.Kind = WhereFoundClauseKind; 371 } 372 373 unsigned getNestingLevel() const { 374 assert(Stack.size() > 1); 375 return Stack.size() - 2; 376 } 377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) { 378 assert(Stack.size() > 2); 379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive)); 380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs}); 381 } 382 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 383 getDoacrossDependClauses() const { 384 assert(Stack.size() > 1); 385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) { 386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends; 387 return llvm::make_range(Ref.begin(), Ref.end()); 388 } 389 return llvm::make_range(Stack[0].DoacrossDepends.end(), 390 Stack[0].DoacrossDepends.end()); 391 } 392 }; 393 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || 395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 396 } 397 } // namespace 398 399 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 400 auto *VD = dyn_cast<VarDecl>(D); 401 auto *FD = dyn_cast<FieldDecl>(D); 402 if (VD != nullptr) { 403 VD = VD->getCanonicalDecl(); 404 D = VD; 405 } else { 406 assert(FD); 407 FD = FD->getCanonicalDecl(); 408 D = FD; 409 } 410 return D; 411 } 412 413 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter, 414 ValueDecl *D) { 415 D = getCanonicalDecl(D); 416 auto *VD = dyn_cast<VarDecl>(D); 417 auto *FD = dyn_cast<FieldDecl>(D); 418 DSAVarData DVar; 419 if (Iter == std::prev(Stack.rend())) { 420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 421 // in a region but not in construct] 422 // File-scope or namespace-scope variables referenced in called routines 423 // in the region are shared unless they appear in a threadprivate 424 // directive. 425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 426 DVar.CKind = OMPC_shared; 427 428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 429 // in a region but not in construct] 430 // Variables with static storage duration that are declared in called 431 // routines in the region are shared. 432 if (VD && VD->hasGlobalStorage()) 433 DVar.CKind = OMPC_shared; 434 435 // Non-static data members are shared by default. 436 if (FD) 437 DVar.CKind = OMPC_shared; 438 439 return DVar; 440 } 441 442 DVar.DKind = Iter->Directive; 443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 444 // in a Construct, C/C++, predetermined, p.1] 445 // Variables with automatic storage duration that are declared in a scope 446 // inside the construct are private. 447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 449 DVar.CKind = OMPC_private; 450 return DVar; 451 } 452 453 // Explicitly specified attributes and local variables with predetermined 454 // attributes. 455 if (Iter->SharingMap.count(D)) { 456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer(); 457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy; 458 DVar.CKind = Iter->SharingMap[D].Attributes; 459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 460 return DVar; 461 } 462 463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 464 // in a Construct, C/C++, implicitly determined, p.1] 465 // In a parallel or task construct, the data-sharing attributes of these 466 // variables are determined by the default clause, if present. 467 switch (Iter->DefaultAttr) { 468 case DSA_shared: 469 DVar.CKind = OMPC_shared; 470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 471 return DVar; 472 case DSA_none: 473 return DVar; 474 case DSA_unspecified: 475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 476 // in a Construct, implicitly determined, p.2] 477 // In a parallel construct, if no default clause is present, these 478 // variables are shared. 479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 480 if (isOpenMPParallelDirective(DVar.DKind) || 481 isOpenMPTeamsDirective(DVar.DKind)) { 482 DVar.CKind = OMPC_shared; 483 return DVar; 484 } 485 486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 487 // in a Construct, implicitly determined, p.4] 488 // In a task construct, if no default clause is present, a variable that in 489 // the enclosing context is determined to be shared by all implicit tasks 490 // bound to the current team is shared. 491 if (isOpenMPTaskingDirective(DVar.DKind)) { 492 DSAVarData DVarTemp; 493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend(); 494 I != EE; ++I) { 495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 496 // Referenced in a Construct, implicitly determined, p.6] 497 // In a task construct, if no default clause is present, a variable 498 // whose data-sharing attribute is not determined by the rules above is 499 // firstprivate. 500 DVarTemp = getDSA(I, D); 501 if (DVarTemp.CKind != OMPC_shared) { 502 DVar.RefExpr = nullptr; 503 DVar.CKind = OMPC_firstprivate; 504 return DVar; 505 } 506 if (isParallelOrTaskRegion(I->Directive)) 507 break; 508 } 509 DVar.CKind = 510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 511 return DVar; 512 } 513 } 514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 515 // in a Construct, implicitly determined, p.3] 516 // For constructs other than task, if no default clause is present, these 517 // variables inherit their data-sharing attributes from the enclosing 518 // context. 519 return getDSA(++Iter, D); 520 } 521 522 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) { 523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty"); 524 D = getCanonicalDecl(D); 525 auto It = Stack.back().AlignedMap.find(D); 526 if (It == Stack.back().AlignedMap.end()) { 527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 528 Stack.back().AlignedMap[D] = NewDE; 529 return nullptr; 530 } else { 531 assert(It->second && "Unexpected nullptr expr in the aligned map"); 532 return It->second; 533 } 534 return nullptr; 535 } 536 537 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) { 538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 539 D = getCanonicalDecl(D); 540 Stack.back().LCVMap.insert( 541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture))); 542 } 543 544 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) { 545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 546 D = getCanonicalDecl(D); 547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D] 548 : LCDeclInfo(0, nullptr); 549 } 550 551 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) { 552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty"); 553 D = getCanonicalDecl(D); 554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0 555 ? Stack[Stack.size() - 2].LCVMap[D] 556 : LCDeclInfo(0, nullptr); 557 } 558 559 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) { 560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty"); 561 if (Stack[Stack.size() - 2].LCVMap.size() < I) 562 return nullptr; 563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) { 564 if (Pair.second.first == I) 565 return Pair.first; 566 } 567 return nullptr; 568 } 569 570 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 571 DeclRefExpr *PrivateCopy) { 572 D = getCanonicalDecl(D); 573 if (A == OMPC_threadprivate) { 574 auto &Data = Stack[0].SharingMap[D]; 575 Data.Attributes = A; 576 Data.RefExpr.setPointer(E); 577 Data.PrivateCopy = nullptr; 578 } else { 579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 580 auto &Data = Stack.back().SharingMap[D]; 581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 584 (isLoopControlVariable(D).first && A == OMPC_private)); 585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 586 Data.RefExpr.setInt(/*IntVal=*/true); 587 return; 588 } 589 const bool IsLastprivate = 590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 591 Data.Attributes = A; 592 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 593 Data.PrivateCopy = PrivateCopy; 594 if (PrivateCopy) { 595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()]; 596 Data.Attributes = A; 597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 598 Data.PrivateCopy = nullptr; 599 } 600 } 601 } 602 603 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 604 D = D->getCanonicalDecl(); 605 if (Stack.size() > 2) { 606 reverse_iterator I = Iter, E = std::prev(Stack.rend()); 607 Scope *TopScope = nullptr; 608 while (I != E && !isParallelOrTaskRegion(I->Directive)) { 609 ++I; 610 } 611 if (I == E) 612 return false; 613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 614 Scope *CurScope = getCurScope(); 615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) { 616 CurScope = CurScope->getParent(); 617 } 618 return CurScope != TopScope; 619 } 620 return false; 621 } 622 623 /// \brief Build a variable declaration for OpenMP loop iteration variable. 624 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 625 StringRef Name, const AttrVec *Attrs = nullptr) { 626 DeclContext *DC = SemaRef.CurContext; 627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 629 VarDecl *Decl = 630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 631 if (Attrs) { 632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 633 I != E; ++I) 634 Decl->addAttr(*I); 635 } 636 Decl->setImplicit(); 637 return Decl; 638 } 639 640 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 641 SourceLocation Loc, 642 bool RefersToCapture = false) { 643 D->setReferenced(); 644 D->markUsed(S.Context); 645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 646 SourceLocation(), D, RefersToCapture, Loc, Ty, 647 VK_LValue); 648 } 649 650 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) { 651 D = getCanonicalDecl(D); 652 DSAVarData DVar; 653 654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 655 // in a Construct, C/C++, predetermined, p.1] 656 // Variables appearing in threadprivate directives are threadprivate. 657 auto *VD = dyn_cast<VarDecl>(D); 658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 660 SemaRef.getLangOpts().OpenMPUseTLS && 661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 662 (VD && VD->getStorageClass() == SC_Register && 663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 665 D->getLocation()), 666 OMPC_threadprivate); 667 } 668 if (Stack[0].SharingMap.count(D)) { 669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer(); 670 DVar.CKind = OMPC_threadprivate; 671 return DVar; 672 } 673 674 if (Stack.size() == 1) { 675 // Not in OpenMP execution region and top scope was already checked. 676 return DVar; 677 } 678 679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 680 // in a Construct, C/C++, predetermined, p.4] 681 // Static data members are shared. 682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 683 // in a Construct, C/C++, predetermined, p.7] 684 // Variables with static storage duration that are declared in a scope 685 // inside the construct are shared. 686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; 687 if (VD && VD->isStaticDataMember()) { 688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 690 return DVar; 691 692 DVar.CKind = OMPC_shared; 693 return DVar; 694 } 695 696 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 697 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 698 Type = SemaRef.getASTContext().getBaseElementType(Type); 699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 700 // in a Construct, C/C++, predetermined, p.6] 701 // Variables with const qualified type having no mutable member are 702 // shared. 703 CXXRecordDecl *RD = 704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 706 if (auto *CTD = CTSD->getSpecializedTemplate()) 707 RD = CTD->getTemplatedDecl(); 708 if (IsConstant && 709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && 710 RD->hasMutableFields())) { 711 // Variables with const-qualified type having no mutable member may be 712 // listed in a firstprivate clause, even if they are static data members. 713 DSAVarData DVarTemp = hasDSA( 714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, 715 MatchesAlways, FromParent); 716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 717 return DVar; 718 719 DVar.CKind = OMPC_shared; 720 return DVar; 721 } 722 723 // Explicitly specified attributes and local variables with predetermined 724 // attributes. 725 auto StartI = std::next(Stack.rbegin()); 726 auto EndI = std::prev(Stack.rend()); 727 if (FromParent && StartI != EndI) { 728 StartI = std::next(StartI); 729 } 730 auto I = std::prev(StartI); 731 if (I->SharingMap.count(D)) { 732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); 733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; 734 DVar.CKind = I->SharingMap[D].Attributes; 735 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 736 } 737 738 return DVar; 739 } 740 741 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 742 bool FromParent) { 743 D = getCanonicalDecl(D); 744 auto StartI = Stack.rbegin(); 745 auto EndI = std::prev(Stack.rend()); 746 if (FromParent && StartI != EndI) { 747 StartI = std::next(StartI); 748 } 749 return getDSA(StartI, D); 750 } 751 752 DSAStackTy::DSAVarData 753 DSAStackTy::hasDSA(ValueDecl *D, 754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 756 bool FromParent) { 757 D = getCanonicalDecl(D); 758 auto StartI = std::next(Stack.rbegin()); 759 auto EndI = Stack.rend(); 760 if (FromParent && StartI != EndI) { 761 StartI = std::next(StartI); 762 } 763 for (auto I = StartI, EE = EndI; I != EE; ++I) { 764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 765 continue; 766 DSAVarData DVar = getDSA(I, D); 767 if (CPred(DVar.CKind)) 768 return DVar; 769 } 770 return DSAVarData(); 771 } 772 773 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 776 bool FromParent) { 777 D = getCanonicalDecl(D); 778 auto StartI = std::next(Stack.rbegin()); 779 auto EndI = Stack.rend(); 780 if (FromParent && StartI != EndI) 781 StartI = std::next(StartI); 782 if (StartI == EndI || !DPred(StartI->Directive)) 783 return DSAVarData(); 784 DSAVarData DVar = getDSA(StartI, D); 785 return CPred(DVar.CKind) ? DVar : DSAVarData(); 786 } 787 788 bool DSAStackTy::hasExplicitDSA( 789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 790 unsigned Level, bool NotLastprivate) { 791 if (CPred(ClauseKindMode)) 792 return true; 793 D = getCanonicalDecl(D); 794 auto StartI = std::next(Stack.begin()); 795 auto EndI = Stack.end(); 796 if (std::distance(StartI, EndI) <= (int)Level) 797 return false; 798 std::advance(StartI, Level); 799 return (StartI->SharingMap.count(D) > 0) && 800 StartI->SharingMap[D].RefExpr.getPointer() && 801 CPred(StartI->SharingMap[D].Attributes) && 802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt()); 803 } 804 805 bool DSAStackTy::hasExplicitDirective( 806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 807 unsigned Level) { 808 auto StartI = std::next(Stack.begin()); 809 auto EndI = Stack.end(); 810 if (std::distance(StartI, EndI) <= (int)Level) 811 return false; 812 std::advance(StartI, Level); 813 return DPred(StartI->Directive); 814 } 815 816 bool DSAStackTy::hasDirective( 817 const llvm::function_ref<bool(OpenMPDirectiveKind, 818 const DeclarationNameInfo &, SourceLocation)> 819 &DPred, 820 bool FromParent) { 821 // We look only in the enclosing region. 822 if (Stack.size() < 2) 823 return false; 824 auto StartI = std::next(Stack.rbegin()); 825 auto EndI = std::prev(Stack.rend()); 826 if (FromParent && StartI != EndI) { 827 StartI = std::next(StartI); 828 } 829 for (auto I = StartI, EE = EndI; I != EE; ++I) { 830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 831 return true; 832 } 833 return false; 834 } 835 836 void Sema::InitDataSharingAttributesStack() { 837 VarDataSharingAttributesStack = new DSAStackTy(*this); 838 } 839 840 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 841 842 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { 843 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 844 845 auto &Ctx = getASTContext(); 846 bool IsByRef = true; 847 848 // Find the directive that is associated with the provided scope. 849 auto Ty = D->getType(); 850 851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 852 // This table summarizes how a given variable should be passed to the device 853 // given its type and the clauses where it appears. This table is based on 854 // the description in OpenMP 4.5 [2.10.4, target Construct] and 855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 856 // 857 // ========================================================================= 858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 859 // | |(tofrom:scalar)| | pvt | | | | 860 // ========================================================================= 861 // | scl | | | | - | | bycopy| 862 // | scl | | - | x | - | - | bycopy| 863 // | scl | | x | - | - | - | null | 864 // | scl | x | | | - | | byref | 865 // | scl | x | - | x | - | - | bycopy| 866 // | scl | x | x | - | - | - | null | 867 // | scl | | - | - | - | x | byref | 868 // | scl | x | - | - | - | x | byref | 869 // 870 // | agg | n.a. | | | - | | byref | 871 // | agg | n.a. | - | x | - | - | byref | 872 // | agg | n.a. | x | - | - | - | null | 873 // | agg | n.a. | - | - | - | x | byref | 874 // | agg | n.a. | - | - | - | x[] | byref | 875 // 876 // | ptr | n.a. | | | - | | bycopy| 877 // | ptr | n.a. | - | x | - | - | bycopy| 878 // | ptr | n.a. | x | - | - | - | null | 879 // | ptr | n.a. | - | - | - | x | byref | 880 // | ptr | n.a. | - | - | - | x[] | bycopy| 881 // | ptr | n.a. | - | - | x | | bycopy| 882 // | ptr | n.a. | - | - | x | x | bycopy| 883 // | ptr | n.a. | - | - | x | x[] | bycopy| 884 // ========================================================================= 885 // Legend: 886 // scl - scalar 887 // ptr - pointer 888 // agg - aggregate 889 // x - applies 890 // - - invalid in this combination 891 // [] - mapped with an array section 892 // byref - should be mapped by reference 893 // byval - should be mapped by value 894 // null - initialize a local variable to null on the device 895 // 896 // Observations: 897 // - All scalar declarations that show up in a map clause have to be passed 898 // by reference, because they may have been mapped in the enclosing data 899 // environment. 900 // - If the scalar value does not fit the size of uintptr, it has to be 901 // passed by reference, regardless the result in the table above. 902 // - For pointers mapped by value that have either an implicit map or an 903 // array section, the runtime library may pass the NULL value to the 904 // device instead of the value passed to it by the compiler. 905 906 if (Ty->isReferenceType()) 907 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 908 909 // Locate map clauses and see if the variable being captured is referred to 910 // in any of those clauses. Here we only care about variables, not fields, 911 // because fields are part of aggregates. 912 bool IsVariableUsedInMapClause = false; 913 bool IsVariableAssociatedWithSection = false; 914 915 DSAStack->checkMappableExprComponentListsForDecl( 916 D, /*CurrentRegionOnly=*/true, 917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 918 MapExprComponents, 919 OpenMPClauseKind WhereFoundClauseKind) { 920 // Only the map clause information influences how a variable is 921 // captured. E.g. is_device_ptr does not require changing the default 922 // behavior. 923 if (WhereFoundClauseKind != OMPC_map) 924 return false; 925 926 auto EI = MapExprComponents.rbegin(); 927 auto EE = MapExprComponents.rend(); 928 929 assert(EI != EE && "Invalid map expression!"); 930 931 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 933 934 ++EI; 935 if (EI == EE) 936 return false; 937 938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 940 isa<MemberExpr>(EI->getAssociatedExpression())) { 941 IsVariableAssociatedWithSection = true; 942 // There is nothing more we need to know about this variable. 943 return true; 944 } 945 946 // Keep looking for more map info. 947 return false; 948 }); 949 950 if (IsVariableUsedInMapClause) { 951 // If variable is identified in a map clause it is always captured by 952 // reference except if it is a pointer that is dereferenced somehow. 953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 954 } else { 955 // By default, all the data that has a scalar type is mapped by copy. 956 IsByRef = !Ty->isScalarType(); 957 } 958 } 959 960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 961 IsByRef = !DSAStack->hasExplicitDSA( 962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 963 Level, /*NotLastprivate=*/true); 964 } 965 966 // When passing data by copy, we need to make sure it fits the uintptr size 967 // and alignment, because the runtime library only deals with uintptr types. 968 // If it does not fit the uintptr size, we need to pass the data by reference 969 // instead. 970 if (!IsByRef && 971 (Ctx.getTypeSizeInChars(Ty) > 972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 974 IsByRef = true; 975 } 976 977 return IsByRef; 978 } 979 980 unsigned Sema::getOpenMPNestingLevel() const { 981 assert(getLangOpts().OpenMP); 982 return DSAStack->getNestingLevel(); 983 } 984 985 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { 986 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 987 D = getCanonicalDecl(D); 988 989 // If we are attempting to capture a global variable in a directive with 990 // 'target' we return true so that this global is also mapped to the device. 991 // 992 // FIXME: If the declaration is enclosed in a 'declare target' directive, 993 // then it should not be captured. Therefore, an extra check has to be 994 // inserted here once support for 'declare target' is added. 995 // 996 auto *VD = dyn_cast<VarDecl>(D); 997 if (VD && !VD->hasLocalStorage()) { 998 if (DSAStack->getCurrentDirective() == OMPD_target && 999 !DSAStack->isClauseParsingMode()) 1000 return VD; 1001 if (DSAStack->hasDirective( 1002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1003 SourceLocation) -> bool { 1004 return isOpenMPTargetExecutionDirective(K); 1005 }, 1006 false)) 1007 return VD; 1008 } 1009 1010 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1011 (!DSAStack->isClauseParsingMode() || 1012 DSAStack->getParentDirective() != OMPD_unknown)) { 1013 auto &&Info = DSAStack->isLoopControlVariable(D); 1014 if (Info.first || 1015 (VD && VD->hasLocalStorage() && 1016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 1017 (VD && DSAStack->isForceVarCapturing())) 1018 return VD ? VD : Info.second; 1019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1022 DVarPrivate = DSAStack->hasDSA( 1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 1024 DSAStack->isClauseParsingMode()); 1025 if (DVarPrivate.CKind != OMPC_unknown) 1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1027 } 1028 return nullptr; 1029 } 1030 1031 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { 1032 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1033 return DSAStack->hasExplicitDSA( 1034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level); 1035 } 1036 1037 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { 1038 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1039 // Return true if the current level is no longer enclosed in a target region. 1040 1041 auto *VD = dyn_cast<VarDecl>(D); 1042 return VD && !VD->hasLocalStorage() && 1043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1044 Level); 1045 } 1046 1047 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1048 1049 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1050 const DeclarationNameInfo &DirName, 1051 Scope *CurScope, SourceLocation Loc) { 1052 DSAStack->push(DKind, DirName, CurScope, Loc); 1053 PushExpressionEvaluationContext(PotentiallyEvaluated); 1054 } 1055 1056 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1057 DSAStack->setClauseParsingMode(K); 1058 } 1059 1060 void Sema::EndOpenMPClause() { 1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1062 } 1063 1064 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1066 // A variable of class type (or array thereof) that appears in a lastprivate 1067 // clause requires an accessible, unambiguous default constructor for the 1068 // class type, unless the list item is also specified in a firstprivate 1069 // clause. 1070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1071 for (auto *C : D->clauses()) { 1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1073 SmallVector<Expr *, 8> PrivateCopies; 1074 for (auto *DE : Clause->varlists()) { 1075 if (DE->isValueDependent() || DE->isTypeDependent()) { 1076 PrivateCopies.push_back(nullptr); 1077 continue; 1078 } 1079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1080 VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1081 QualType Type = VD->getType().getNonReferenceType(); 1082 auto DVar = DSAStack->getTopDSA(VD, false); 1083 if (DVar.CKind == OMPC_lastprivate) { 1084 // Generate helper private variable and initialize it with the 1085 // default value. The address of the original variable is replaced 1086 // by the address of the new private variable in CodeGen. This new 1087 // variable is not added to IdResolver, so the code in the OpenMP 1088 // region uses original variable for proper diagnostics. 1089 auto *VDPrivate = buildVarDecl( 1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); 1092 ActOnUninitializedDecl(VDPrivate); 1093 if (VDPrivate->isInvalidDecl()) 1094 continue; 1095 PrivateCopies.push_back(buildDeclRefExpr( 1096 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1097 } else { 1098 // The variable is also a firstprivate, so initialization sequence 1099 // for private copy is generated already. 1100 PrivateCopies.push_back(nullptr); 1101 } 1102 } 1103 // Set initializers to private copies if no errors were found. 1104 if (PrivateCopies.size() == Clause->varlist_size()) 1105 Clause->setPrivateCopies(PrivateCopies); 1106 } 1107 } 1108 } 1109 1110 DSAStack->pop(); 1111 DiscardCleanupsInEvaluationContext(); 1112 PopExpressionEvaluationContext(); 1113 } 1114 1115 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1116 Expr *NumIterations, Sema &SemaRef, 1117 Scope *S, DSAStackTy *Stack); 1118 1119 namespace { 1120 1121 class VarDeclFilterCCC : public CorrectionCandidateCallback { 1122 private: 1123 Sema &SemaRef; 1124 1125 public: 1126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1127 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1128 NamedDecl *ND = Candidate.getCorrectionDecl(); 1129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1130 return VD->hasGlobalStorage() && 1131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1132 SemaRef.getCurScope()); 1133 } 1134 return false; 1135 } 1136 }; 1137 1138 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { 1139 private: 1140 Sema &SemaRef; 1141 1142 public: 1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1144 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1145 NamedDecl *ND = Candidate.getCorrectionDecl(); 1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1148 SemaRef.getCurScope()); 1149 } 1150 return false; 1151 } 1152 }; 1153 1154 } // namespace 1155 1156 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1157 CXXScopeSpec &ScopeSpec, 1158 const DeclarationNameInfo &Id) { 1159 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1161 1162 if (Lookup.isAmbiguous()) 1163 return ExprError(); 1164 1165 VarDecl *VD; 1166 if (!Lookup.isSingleResult()) { 1167 if (TypoCorrection Corrected = CorrectTypo( 1168 Id, LookupOrdinaryName, CurScope, nullptr, 1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1170 diagnoseTypo(Corrected, 1171 PDiag(Lookup.empty() 1172 ? diag::err_undeclared_var_use_suggest 1173 : diag::err_omp_expected_var_arg_suggest) 1174 << Id.getName()); 1175 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1176 } else { 1177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1178 : diag::err_omp_expected_var_arg) 1179 << Id.getName(); 1180 return ExprError(); 1181 } 1182 } else { 1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1186 return ExprError(); 1187 } 1188 } 1189 Lookup.suppressDiagnostics(); 1190 1191 // OpenMP [2.9.2, Syntax, C/C++] 1192 // Variables must be file-scope, namespace-scope, or static block-scope. 1193 if (!VD->hasGlobalStorage()) { 1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1196 bool IsDecl = 1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1198 Diag(VD->getLocation(), 1199 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1200 << VD; 1201 return ExprError(); 1202 } 1203 1204 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 1206 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1207 // A threadprivate directive for file-scope variables must appear outside 1208 // any definition or declaration. 1209 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1210 !getCurLexicalContext()->isTranslationUnit()) { 1211 Diag(Id.getLoc(), diag::err_omp_var_scope) 1212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1213 bool IsDecl = 1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1215 Diag(VD->getLocation(), 1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1217 << VD; 1218 return ExprError(); 1219 } 1220 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1221 // A threadprivate directive for static class member variables must appear 1222 // in the class definition, in the same scope in which the member 1223 // variables are declared. 1224 if (CanonicalVD->isStaticDataMember() && 1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1226 Diag(Id.getLoc(), diag::err_omp_var_scope) 1227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1228 bool IsDecl = 1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1230 Diag(VD->getLocation(), 1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1232 << VD; 1233 return ExprError(); 1234 } 1235 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1236 // A threadprivate directive for namespace-scope variables must appear 1237 // outside any definition or declaration other than the namespace 1238 // definition itself. 1239 if (CanonicalVD->getDeclContext()->isNamespace() && 1240 (!getCurLexicalContext()->isFileContext() || 1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1242 Diag(Id.getLoc(), diag::err_omp_var_scope) 1243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1244 bool IsDecl = 1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1246 Diag(VD->getLocation(), 1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1248 << VD; 1249 return ExprError(); 1250 } 1251 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1252 // A threadprivate directive for static block-scope variables must appear 1253 // in the scope of the variable and not in a nested scope. 1254 if (CanonicalVD->isStaticLocal() && CurScope && 1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1256 Diag(Id.getLoc(), diag::err_omp_var_scope) 1257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1258 bool IsDecl = 1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1260 Diag(VD->getLocation(), 1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1262 << VD; 1263 return ExprError(); 1264 } 1265 1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1267 // A threadprivate directive must lexically precede all references to any 1268 // of the variables in its list. 1269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1270 Diag(Id.getLoc(), diag::err_omp_var_used) 1271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1272 return ExprError(); 1273 } 1274 1275 QualType ExprType = VD->getType().getNonReferenceType(); 1276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1277 SourceLocation(), VD, 1278 /*RefersToEnclosingVariableOrCapture=*/false, 1279 Id.getLoc(), ExprType, VK_LValue); 1280 } 1281 1282 Sema::DeclGroupPtrTy 1283 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1284 ArrayRef<Expr *> VarList) { 1285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1286 CurContext->addDecl(D); 1287 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1288 } 1289 return nullptr; 1290 } 1291 1292 namespace { 1293 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1294 Sema &SemaRef; 1295 1296 public: 1297 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1299 if (VD->hasLocalStorage()) { 1300 SemaRef.Diag(E->getLocStart(), 1301 diag::err_omp_local_var_in_threadprivate_init) 1302 << E->getSourceRange(); 1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1304 << VD << VD->getSourceRange(); 1305 return true; 1306 } 1307 } 1308 return false; 1309 } 1310 bool VisitStmt(const Stmt *S) { 1311 for (auto Child : S->children()) { 1312 if (Child && Visit(Child)) 1313 return true; 1314 } 1315 return false; 1316 } 1317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1318 }; 1319 } // namespace 1320 1321 OMPThreadPrivateDecl * 1322 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1323 SmallVector<Expr *, 8> Vars; 1324 for (auto &RefExpr : VarList) { 1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 1326 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 1327 SourceLocation ILoc = DE->getExprLoc(); 1328 1329 // Mark variable as used. 1330 VD->setReferenced(); 1331 VD->markUsed(Context); 1332 1333 QualType QType = VD->getType(); 1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1335 // It will be analyzed later. 1336 Vars.push_back(DE); 1337 continue; 1338 } 1339 1340 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1341 // A threadprivate variable must not have an incomplete type. 1342 if (RequireCompleteType(ILoc, VD->getType(), 1343 diag::err_omp_threadprivate_incomplete_type)) { 1344 continue; 1345 } 1346 1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1348 // A threadprivate variable must not have a reference type. 1349 if (VD->getType()->isReferenceType()) { 1350 Diag(ILoc, diag::err_omp_ref_type_arg) 1351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1352 bool IsDecl = 1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1354 Diag(VD->getLocation(), 1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1356 << VD; 1357 continue; 1358 } 1359 1360 // Check if this is a TLS variable. If TLS is not being supported, produce 1361 // the corresponding diagnostic. 1362 if ((VD->getTLSKind() != VarDecl::TLS_None && 1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1364 getLangOpts().OpenMPUseTLS && 1365 getASTContext().getTargetInfo().isTLSSupported())) || 1366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1367 !VD->isLocalVarDecl())) { 1368 Diag(ILoc, diag::err_omp_var_thread_local) 1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1370 bool IsDecl = 1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1372 Diag(VD->getLocation(), 1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1374 << VD; 1375 continue; 1376 } 1377 1378 // Check if initial value of threadprivate variable reference variable with 1379 // local storage (it is not supported by runtime). 1380 if (auto Init = VD->getAnyInitializer()) { 1381 LocalVarRefChecker Checker(*this); 1382 if (Checker.Visit(Init)) 1383 continue; 1384 } 1385 1386 Vars.push_back(RefExpr); 1387 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1389 Context, SourceRange(Loc, Loc))); 1390 if (auto *ML = Context.getASTMutationListener()) 1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1392 } 1393 OMPThreadPrivateDecl *D = nullptr; 1394 if (!Vars.empty()) { 1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1396 Vars); 1397 D->setAccess(AS_public); 1398 } 1399 return D; 1400 } 1401 1402 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 1403 const ValueDecl *D, DSAStackTy::DSAVarData DVar, 1404 bool IsLoopIterVar = false) { 1405 if (DVar.RefExpr) { 1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1407 << getOpenMPClauseName(DVar.CKind); 1408 return; 1409 } 1410 enum { 1411 PDSA_StaticMemberShared, 1412 PDSA_StaticLocalVarShared, 1413 PDSA_LoopIterVarPrivate, 1414 PDSA_LoopIterVarLinear, 1415 PDSA_LoopIterVarLastprivate, 1416 PDSA_ConstVarShared, 1417 PDSA_GlobalVarShared, 1418 PDSA_TaskVarFirstprivate, 1419 PDSA_LocalVarPrivate, 1420 PDSA_Implicit 1421 } Reason = PDSA_Implicit; 1422 bool ReportHint = false; 1423 auto ReportLoc = D->getLocation(); 1424 auto *VD = dyn_cast<VarDecl>(D); 1425 if (IsLoopIterVar) { 1426 if (DVar.CKind == OMPC_private) 1427 Reason = PDSA_LoopIterVarPrivate; 1428 else if (DVar.CKind == OMPC_lastprivate) 1429 Reason = PDSA_LoopIterVarLastprivate; 1430 else 1431 Reason = PDSA_LoopIterVarLinear; 1432 } else if (isOpenMPTaskingDirective(DVar.DKind) && 1433 DVar.CKind == OMPC_firstprivate) { 1434 Reason = PDSA_TaskVarFirstprivate; 1435 ReportLoc = DVar.ImplicitDSALoc; 1436 } else if (VD && VD->isStaticLocal()) 1437 Reason = PDSA_StaticLocalVarShared; 1438 else if (VD && VD->isStaticDataMember()) 1439 Reason = PDSA_StaticMemberShared; 1440 else if (VD && VD->isFileVarDecl()) 1441 Reason = PDSA_GlobalVarShared; 1442 else if (D->getType().isConstant(SemaRef.getASTContext())) 1443 Reason = PDSA_ConstVarShared; 1444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 1445 ReportHint = true; 1446 Reason = PDSA_LocalVarPrivate; 1447 } 1448 if (Reason != PDSA_Implicit) { 1449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 1450 << Reason << ReportHint 1451 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 1452 } else if (DVar.ImplicitDSALoc.isValid()) { 1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 1454 << getOpenMPClauseName(DVar.CKind); 1455 } 1456 } 1457 1458 namespace { 1459 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 1460 DSAStackTy *Stack; 1461 Sema &SemaRef; 1462 bool ErrorFound; 1463 CapturedStmt *CS; 1464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 1465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 1466 1467 public: 1468 void VisitDeclRefExpr(DeclRefExpr *E) { 1469 if (E->isTypeDependent() || E->isValueDependent() || 1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1471 return; 1472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1473 // Skip internally declared variables. 1474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) 1475 return; 1476 1477 auto DVar = Stack->getTopDSA(VD, false); 1478 // Check if the variable has explicit DSA set and stop analysis if it so. 1479 if (DVar.RefExpr) 1480 return; 1481 1482 auto ELoc = E->getExprLoc(); 1483 auto DKind = Stack->getCurrentDirective(); 1484 // The default(none) clause requires that each variable that is referenced 1485 // in the construct, and does not have a predetermined data-sharing 1486 // attribute, must have its data-sharing attribute explicitly determined 1487 // by being listed in a data-sharing attribute clause. 1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 1489 isParallelOrTaskRegion(DKind) && 1490 VarsWithInheritedDSA.count(VD) == 0) { 1491 VarsWithInheritedDSA[VD] = E; 1492 return; 1493 } 1494 1495 // OpenMP [2.9.3.6, Restrictions, p.2] 1496 // A list item that appears in a reduction clause of the innermost 1497 // enclosing worksharing or parallel construct may not be accessed in an 1498 // explicit task. 1499 DVar = Stack->hasInnermostDSA( 1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1501 [](OpenMPDirectiveKind K) -> bool { 1502 return isOpenMPParallelDirective(K) || 1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1504 }, 1505 false); 1506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1507 ErrorFound = true; 1508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 1510 return; 1511 } 1512 1513 // Define implicit data-sharing attributes for task. 1514 DVar = Stack->getImplicitDSA(VD, false); 1515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1516 !Stack->isLoopControlVariable(VD).first) 1517 ImplicitFirstprivate.push_back(E); 1518 } 1519 } 1520 void VisitMemberExpr(MemberExpr *E) { 1521 if (E->isTypeDependent() || E->isValueDependent() || 1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1523 return; 1524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 1526 auto DVar = Stack->getTopDSA(FD, false); 1527 // Check if the variable has explicit DSA set and stop analysis if it 1528 // so. 1529 if (DVar.RefExpr) 1530 return; 1531 1532 auto ELoc = E->getExprLoc(); 1533 auto DKind = Stack->getCurrentDirective(); 1534 // OpenMP [2.9.3.6, Restrictions, p.2] 1535 // A list item that appears in a reduction clause of the innermost 1536 // enclosing worksharing or parallel construct may not be accessed in 1537 // an explicit task. 1538 DVar = Stack->hasInnermostDSA( 1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1540 [](OpenMPDirectiveKind K) -> bool { 1541 return isOpenMPParallelDirective(K) || 1542 isOpenMPWorksharingDirective(K) || 1543 isOpenMPTeamsDirective(K); 1544 }, 1545 false); 1546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1547 ErrorFound = true; 1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar); 1550 return; 1551 } 1552 1553 // Define implicit data-sharing attributes for task. 1554 DVar = Stack->getImplicitDSA(FD, false); 1555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1556 !Stack->isLoopControlVariable(FD).first) 1557 ImplicitFirstprivate.push_back(E); 1558 } 1559 } else 1560 Visit(E->getBase()); 1561 } 1562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 1563 for (auto *C : S->clauses()) { 1564 // Skip analysis of arguments of implicitly defined firstprivate clause 1565 // for task directives. 1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid())) 1567 for (auto *CC : C->children()) { 1568 if (CC) 1569 Visit(CC); 1570 } 1571 } 1572 } 1573 void VisitStmt(Stmt *S) { 1574 for (auto *C : S->children()) { 1575 if (C && !isa<OMPExecutableDirective>(C)) 1576 Visit(C); 1577 } 1578 } 1579 1580 bool isErrorFound() { return ErrorFound; } 1581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; } 1582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() { 1583 return VarsWithInheritedDSA; 1584 } 1585 1586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 1588 }; 1589 } // namespace 1590 1591 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 1592 switch (DKind) { 1593 case OMPD_parallel: 1594 case OMPD_parallel_for: 1595 case OMPD_parallel_for_simd: 1596 case OMPD_parallel_sections: 1597 case OMPD_teams: { 1598 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1599 QualType KmpInt32PtrTy = 1600 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1601 Sema::CapturedParamNameType Params[] = { 1602 std::make_pair(".global_tid.", KmpInt32PtrTy), 1603 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1604 std::make_pair(StringRef(), QualType()) // __context with shared vars 1605 }; 1606 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1607 Params); 1608 break; 1609 } 1610 case OMPD_target_teams: 1611 case OMPD_target_parallel: { 1612 Sema::CapturedParamNameType ParamsTarget[] = { 1613 std::make_pair(StringRef(), QualType()) // __context with shared vars 1614 }; 1615 // Start a captured region for 'target' with no implicit parameters. 1616 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1617 ParamsTarget); 1618 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1619 QualType KmpInt32PtrTy = 1620 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1621 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 1622 std::make_pair(".global_tid.", KmpInt32PtrTy), 1623 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1624 std::make_pair(StringRef(), QualType()) // __context with shared vars 1625 }; 1626 // Start a captured region for 'teams' or 'parallel'. Both regions have 1627 // the same implicit parameters. 1628 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1629 ParamsTeamsOrParallel); 1630 break; 1631 } 1632 case OMPD_simd: 1633 case OMPD_for: 1634 case OMPD_for_simd: 1635 case OMPD_sections: 1636 case OMPD_section: 1637 case OMPD_single: 1638 case OMPD_master: 1639 case OMPD_critical: 1640 case OMPD_taskgroup: 1641 case OMPD_distribute: 1642 case OMPD_ordered: 1643 case OMPD_atomic: 1644 case OMPD_target_data: 1645 case OMPD_target: 1646 case OMPD_target_parallel_for: 1647 case OMPD_target_parallel_for_simd: 1648 case OMPD_target_simd: { 1649 Sema::CapturedParamNameType Params[] = { 1650 std::make_pair(StringRef(), QualType()) // __context with shared vars 1651 }; 1652 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1653 Params); 1654 break; 1655 } 1656 case OMPD_task: { 1657 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1658 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1659 FunctionProtoType::ExtProtoInfo EPI; 1660 EPI.Variadic = true; 1661 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1662 Sema::CapturedParamNameType Params[] = { 1663 std::make_pair(".global_tid.", KmpInt32Ty), 1664 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1665 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 1666 std::make_pair(".copy_fn.", 1667 Context.getPointerType(CopyFnType).withConst()), 1668 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1669 std::make_pair(StringRef(), QualType()) // __context with shared vars 1670 }; 1671 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1672 Params); 1673 // Mark this captured region as inlined, because we don't use outlined 1674 // function directly. 1675 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1676 AlwaysInlineAttr::CreateImplicit( 1677 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1678 break; 1679 } 1680 case OMPD_taskloop: 1681 case OMPD_taskloop_simd: { 1682 QualType KmpInt32Ty = 1683 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1684 QualType KmpUInt64Ty = 1685 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 1686 QualType KmpInt64Ty = 1687 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 1688 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1689 FunctionProtoType::ExtProtoInfo EPI; 1690 EPI.Variadic = true; 1691 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1692 Sema::CapturedParamNameType Params[] = { 1693 std::make_pair(".global_tid.", KmpInt32Ty), 1694 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1695 std::make_pair(".privates.", 1696 Context.VoidPtrTy.withConst().withRestrict()), 1697 std::make_pair( 1698 ".copy_fn.", 1699 Context.getPointerType(CopyFnType).withConst().withRestrict()), 1700 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1701 std::make_pair(".lb.", KmpUInt64Ty), 1702 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 1703 std::make_pair(".liter.", KmpInt32Ty), 1704 std::make_pair(StringRef(), QualType()) // __context with shared vars 1705 }; 1706 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1707 Params); 1708 // Mark this captured region as inlined, because we don't use outlined 1709 // function directly. 1710 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1711 AlwaysInlineAttr::CreateImplicit( 1712 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1713 break; 1714 } 1715 case OMPD_distribute_parallel_for_simd: 1716 case OMPD_distribute_simd: 1717 case OMPD_distribute_parallel_for: 1718 case OMPD_teams_distribute: 1719 case OMPD_teams_distribute_simd: 1720 case OMPD_teams_distribute_parallel_for_simd: 1721 case OMPD_teams_distribute_parallel_for: 1722 case OMPD_target_teams_distribute: 1723 case OMPD_target_teams_distribute_parallel_for: 1724 case OMPD_target_teams_distribute_parallel_for_simd: 1725 case OMPD_target_teams_distribute_simd: { 1726 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1727 QualType KmpInt32PtrTy = 1728 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1729 Sema::CapturedParamNameType Params[] = { 1730 std::make_pair(".global_tid.", KmpInt32PtrTy), 1731 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1732 std::make_pair(".previous.lb.", Context.getSizeType()), 1733 std::make_pair(".previous.ub.", Context.getSizeType()), 1734 std::make_pair(StringRef(), QualType()) // __context with shared vars 1735 }; 1736 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1737 Params); 1738 break; 1739 } 1740 case OMPD_threadprivate: 1741 case OMPD_taskyield: 1742 case OMPD_barrier: 1743 case OMPD_taskwait: 1744 case OMPD_cancellation_point: 1745 case OMPD_cancel: 1746 case OMPD_flush: 1747 case OMPD_target_enter_data: 1748 case OMPD_target_exit_data: 1749 case OMPD_declare_reduction: 1750 case OMPD_declare_simd: 1751 case OMPD_declare_target: 1752 case OMPD_end_declare_target: 1753 case OMPD_target_update: 1754 llvm_unreachable("OpenMP Directive is not allowed"); 1755 case OMPD_unknown: 1756 llvm_unreachable("Unknown OpenMP directive"); 1757 } 1758 } 1759 1760 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 1761 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 1762 getOpenMPCaptureRegions(CaptureRegions, DKind); 1763 return CaptureRegions.size(); 1764 } 1765 1766 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 1767 Expr *CaptureExpr, bool WithInit, 1768 bool AsExpression) { 1769 assert(CaptureExpr); 1770 ASTContext &C = S.getASTContext(); 1771 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 1772 QualType Ty = Init->getType(); 1773 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 1774 if (S.getLangOpts().CPlusPlus) 1775 Ty = C.getLValueReferenceType(Ty); 1776 else { 1777 Ty = C.getPointerType(Ty); 1778 ExprResult Res = 1779 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 1780 if (!Res.isUsable()) 1781 return nullptr; 1782 Init = Res.get(); 1783 } 1784 WithInit = true; 1785 } 1786 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 1787 CaptureExpr->getLocStart()); 1788 if (!WithInit) 1789 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 1790 S.CurContext->addHiddenDecl(CED); 1791 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 1792 return CED; 1793 } 1794 1795 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 1796 bool WithInit) { 1797 OMPCapturedExprDecl *CD; 1798 if (auto *VD = S.IsOpenMPCapturedDecl(D)) 1799 CD = cast<OMPCapturedExprDecl>(VD); 1800 else 1801 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 1802 /*AsExpression=*/false); 1803 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1804 CaptureExpr->getExprLoc()); 1805 } 1806 1807 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 1808 if (!Ref) { 1809 auto *CD = 1810 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), 1811 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); 1812 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1813 CaptureExpr->getExprLoc()); 1814 } 1815 ExprResult Res = Ref; 1816 if (!S.getLangOpts().CPlusPlus && 1817 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 1818 Ref->getType()->isPointerType()) 1819 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 1820 if (!Res.isUsable()) 1821 return ExprError(); 1822 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); 1823 } 1824 1825 namespace { 1826 // OpenMP directives parsed in this section are represented as a 1827 // CapturedStatement with an associated statement. If a syntax error 1828 // is detected during the parsing of the associated statement, the 1829 // compiler must abort processing and close the CapturedStatement. 1830 // 1831 // Combined directives such as 'target parallel' have more than one 1832 // nested CapturedStatements. This RAII ensures that we unwind out 1833 // of all the nested CapturedStatements when an error is found. 1834 class CaptureRegionUnwinderRAII { 1835 private: 1836 Sema &S; 1837 bool &ErrorFound; 1838 OpenMPDirectiveKind DKind; 1839 1840 public: 1841 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 1842 OpenMPDirectiveKind DKind) 1843 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 1844 ~CaptureRegionUnwinderRAII() { 1845 if (ErrorFound) { 1846 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 1847 while (--ThisCaptureLevel >= 0) 1848 S.ActOnCapturedRegionError(); 1849 } 1850 } 1851 }; 1852 } // namespace 1853 1854 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 1855 ArrayRef<OMPClause *> Clauses) { 1856 bool ErrorFound = false; 1857 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 1858 *this, ErrorFound, DSAStack->getCurrentDirective()); 1859 if (!S.isUsable()) { 1860 ErrorFound = true; 1861 return StmtError(); 1862 } 1863 1864 OMPOrderedClause *OC = nullptr; 1865 OMPScheduleClause *SC = nullptr; 1866 SmallVector<OMPLinearClause *, 4> LCs; 1867 SmallVector<OMPClauseWithPreInit *, 8> PICs; 1868 // This is required for proper codegen. 1869 for (auto *Clause : Clauses) { 1870 if (isOpenMPPrivate(Clause->getClauseKind()) || 1871 Clause->getClauseKind() == OMPC_copyprivate || 1872 (getLangOpts().OpenMPUseTLS && 1873 getASTContext().getTargetInfo().isTLSSupported() && 1874 Clause->getClauseKind() == OMPC_copyin)) { 1875 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 1876 // Mark all variables in private list clauses as used in inner region. 1877 for (auto *VarRef : Clause->children()) { 1878 if (auto *E = cast_or_null<Expr>(VarRef)) { 1879 MarkDeclarationsReferencedInExpr(E); 1880 } 1881 } 1882 DSAStack->setForceVarCapturing(/*V=*/false); 1883 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 1884 if (auto *C = OMPClauseWithPreInit::get(Clause)) 1885 PICs.push_back(C); 1886 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 1887 if (auto *E = C->getPostUpdateExpr()) 1888 MarkDeclarationsReferencedInExpr(E); 1889 } 1890 } 1891 if (Clause->getClauseKind() == OMPC_schedule) 1892 SC = cast<OMPScheduleClause>(Clause); 1893 else if (Clause->getClauseKind() == OMPC_ordered) 1894 OC = cast<OMPOrderedClause>(Clause); 1895 else if (Clause->getClauseKind() == OMPC_linear) 1896 LCs.push_back(cast<OMPLinearClause>(Clause)); 1897 } 1898 // OpenMP, 2.7.1 Loop Construct, Restrictions 1899 // The nonmonotonic modifier cannot be specified if an ordered clause is 1900 // specified. 1901 if (SC && 1902 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 1903 SC->getSecondScheduleModifier() == 1904 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 1905 OC) { 1906 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 1907 ? SC->getFirstScheduleModifierLoc() 1908 : SC->getSecondScheduleModifierLoc(), 1909 diag::err_omp_schedule_nonmonotonic_ordered) 1910 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1911 ErrorFound = true; 1912 } 1913 if (!LCs.empty() && OC && OC->getNumForLoops()) { 1914 for (auto *C : LCs) { 1915 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 1916 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1917 } 1918 ErrorFound = true; 1919 } 1920 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 1921 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 1922 OC->getNumForLoops()) { 1923 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 1924 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 1925 ErrorFound = true; 1926 } 1927 if (ErrorFound) { 1928 return StmtError(); 1929 } 1930 StmtResult SR = S; 1931 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 1932 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 1933 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 1934 // Mark all variables in private list clauses as used in inner region. 1935 // Required for proper codegen of combined directives. 1936 // TODO: add processing for other clauses. 1937 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 1938 for (auto *C : PICs) { 1939 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 1940 // Find the particular capture region for the clause if the 1941 // directive is a combined one with multiple capture regions. 1942 // If the directive is not a combined one, the capture region 1943 // associated with the clause is OMPD_unknown and is generated 1944 // only once. 1945 if (CaptureRegion == ThisCaptureRegion || 1946 CaptureRegion == OMPD_unknown) { 1947 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 1948 for (auto *D : DS->decls()) 1949 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 1950 } 1951 } 1952 } 1953 } 1954 SR = ActOnCapturedRegionEnd(SR.get()); 1955 } 1956 return SR; 1957 } 1958 1959 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 1960 OpenMPDirectiveKind CurrentRegion, 1961 const DeclarationNameInfo &CurrentName, 1962 OpenMPDirectiveKind CancelRegion, 1963 SourceLocation StartLoc) { 1964 if (Stack->getCurScope()) { 1965 auto ParentRegion = Stack->getParentDirective(); 1966 auto OffendingRegion = ParentRegion; 1967 bool NestingProhibited = false; 1968 bool CloseNesting = true; 1969 bool OrphanSeen = false; 1970 enum { 1971 NoRecommend, 1972 ShouldBeInParallelRegion, 1973 ShouldBeInOrderedRegion, 1974 ShouldBeInTargetRegion, 1975 ShouldBeInTeamsRegion 1976 } Recommend = NoRecommend; 1977 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 1978 // OpenMP [2.16, Nesting of Regions] 1979 // OpenMP constructs may not be nested inside a simd region. 1980 // OpenMP [2.8.1,simd Construct, Restrictions] 1981 // An ordered construct with the simd clause is the only OpenMP 1982 // construct that can appear in the simd region. 1983 // Allowing a SIMD construct nested in another SIMD construct is an 1984 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 1985 // message. 1986 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 1987 ? diag::err_omp_prohibited_region_simd 1988 : diag::warn_omp_nesting_simd); 1989 return CurrentRegion != OMPD_simd; 1990 } 1991 if (ParentRegion == OMPD_atomic) { 1992 // OpenMP [2.16, Nesting of Regions] 1993 // OpenMP constructs may not be nested inside an atomic region. 1994 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 1995 return true; 1996 } 1997 if (CurrentRegion == OMPD_section) { 1998 // OpenMP [2.7.2, sections Construct, Restrictions] 1999 // Orphaned section directives are prohibited. That is, the section 2000 // directives must appear within the sections construct and must not be 2001 // encountered elsewhere in the sections region. 2002 if (ParentRegion != OMPD_sections && 2003 ParentRegion != OMPD_parallel_sections) { 2004 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 2005 << (ParentRegion != OMPD_unknown) 2006 << getOpenMPDirectiveName(ParentRegion); 2007 return true; 2008 } 2009 return false; 2010 } 2011 // Allow some constructs (except teams) to be orphaned (they could be 2012 // used in functions, called from OpenMP regions with the required 2013 // preconditions). 2014 if (ParentRegion == OMPD_unknown && 2015 !isOpenMPNestingTeamsDirective(CurrentRegion)) 2016 return false; 2017 if (CurrentRegion == OMPD_cancellation_point || 2018 CurrentRegion == OMPD_cancel) { 2019 // OpenMP [2.16, Nesting of Regions] 2020 // A cancellation point construct for which construct-type-clause is 2021 // taskgroup must be nested inside a task construct. A cancellation 2022 // point construct for which construct-type-clause is not taskgroup must 2023 // be closely nested inside an OpenMP construct that matches the type 2024 // specified in construct-type-clause. 2025 // A cancel construct for which construct-type-clause is taskgroup must be 2026 // nested inside a task construct. A cancel construct for which 2027 // construct-type-clause is not taskgroup must be closely nested inside an 2028 // OpenMP construct that matches the type specified in 2029 // construct-type-clause. 2030 NestingProhibited = 2031 !((CancelRegion == OMPD_parallel && 2032 (ParentRegion == OMPD_parallel || 2033 ParentRegion == OMPD_target_parallel)) || 2034 (CancelRegion == OMPD_for && 2035 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 2036 ParentRegion == OMPD_target_parallel_for)) || 2037 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 2038 (CancelRegion == OMPD_sections && 2039 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 2040 ParentRegion == OMPD_parallel_sections))); 2041 } else if (CurrentRegion == OMPD_master) { 2042 // OpenMP [2.16, Nesting of Regions] 2043 // A master region may not be closely nested inside a worksharing, 2044 // atomic, or explicit task region. 2045 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2046 isOpenMPTaskingDirective(ParentRegion); 2047 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 2048 // OpenMP [2.16, Nesting of Regions] 2049 // A critical region may not be nested (closely or otherwise) inside a 2050 // critical region with the same name. Note that this restriction is not 2051 // sufficient to prevent deadlock. 2052 SourceLocation PreviousCriticalLoc; 2053 bool DeadLock = Stack->hasDirective( 2054 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 2055 const DeclarationNameInfo &DNI, 2056 SourceLocation Loc) -> bool { 2057 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 2058 PreviousCriticalLoc = Loc; 2059 return true; 2060 } else 2061 return false; 2062 }, 2063 false /* skip top directive */); 2064 if (DeadLock) { 2065 SemaRef.Diag(StartLoc, 2066 diag::err_omp_prohibited_region_critical_same_name) 2067 << CurrentName.getName(); 2068 if (PreviousCriticalLoc.isValid()) 2069 SemaRef.Diag(PreviousCriticalLoc, 2070 diag::note_omp_previous_critical_region); 2071 return true; 2072 } 2073 } else if (CurrentRegion == OMPD_barrier) { 2074 // OpenMP [2.16, Nesting of Regions] 2075 // A barrier region may not be closely nested inside a worksharing, 2076 // explicit task, critical, ordered, atomic, or master region. 2077 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2078 isOpenMPTaskingDirective(ParentRegion) || 2079 ParentRegion == OMPD_master || 2080 ParentRegion == OMPD_critical || 2081 ParentRegion == OMPD_ordered; 2082 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2083 !isOpenMPParallelDirective(CurrentRegion) && 2084 !isOpenMPTeamsDirective(CurrentRegion)) { 2085 // OpenMP [2.16, Nesting of Regions] 2086 // A worksharing region may not be closely nested inside a worksharing, 2087 // explicit task, critical, ordered, atomic, or master region. 2088 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2089 isOpenMPTaskingDirective(ParentRegion) || 2090 ParentRegion == OMPD_master || 2091 ParentRegion == OMPD_critical || 2092 ParentRegion == OMPD_ordered; 2093 Recommend = ShouldBeInParallelRegion; 2094 } else if (CurrentRegion == OMPD_ordered) { 2095 // OpenMP [2.16, Nesting of Regions] 2096 // An ordered region may not be closely nested inside a critical, 2097 // atomic, or explicit task region. 2098 // An ordered region must be closely nested inside a loop region (or 2099 // parallel loop region) with an ordered clause. 2100 // OpenMP [2.8.1,simd Construct, Restrictions] 2101 // An ordered construct with the simd clause is the only OpenMP construct 2102 // that can appear in the simd region. 2103 NestingProhibited = ParentRegion == OMPD_critical || 2104 isOpenMPTaskingDirective(ParentRegion) || 2105 !(isOpenMPSimdDirective(ParentRegion) || 2106 Stack->isParentOrderedRegion()); 2107 Recommend = ShouldBeInOrderedRegion; 2108 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 2109 // OpenMP [2.16, Nesting of Regions] 2110 // If specified, a teams construct must be contained within a target 2111 // construct. 2112 NestingProhibited = ParentRegion != OMPD_target; 2113 OrphanSeen = ParentRegion == OMPD_unknown; 2114 Recommend = ShouldBeInTargetRegion; 2115 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 2116 } 2117 if (!NestingProhibited && 2118 !isOpenMPTargetExecutionDirective(CurrentRegion) && 2119 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 2120 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 2121 // OpenMP [2.16, Nesting of Regions] 2122 // distribute, parallel, parallel sections, parallel workshare, and the 2123 // parallel loop and parallel loop SIMD constructs are the only OpenMP 2124 // constructs that can be closely nested in the teams region. 2125 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 2126 !isOpenMPDistributeDirective(CurrentRegion); 2127 Recommend = ShouldBeInParallelRegion; 2128 } 2129 if (!NestingProhibited && 2130 isOpenMPNestingDistributeDirective(CurrentRegion)) { 2131 // OpenMP 4.5 [2.17 Nesting of Regions] 2132 // The region associated with the distribute construct must be strictly 2133 // nested inside a teams region 2134 NestingProhibited = 2135 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 2136 Recommend = ShouldBeInTeamsRegion; 2137 } 2138 if (!NestingProhibited && 2139 (isOpenMPTargetExecutionDirective(CurrentRegion) || 2140 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 2141 // OpenMP 4.5 [2.17 Nesting of Regions] 2142 // If a target, target update, target data, target enter data, or 2143 // target exit data construct is encountered during execution of a 2144 // target region, the behavior is unspecified. 2145 NestingProhibited = Stack->hasDirective( 2146 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2147 SourceLocation) -> bool { 2148 if (isOpenMPTargetExecutionDirective(K)) { 2149 OffendingRegion = K; 2150 return true; 2151 } else 2152 return false; 2153 }, 2154 false /* don't skip top directive */); 2155 CloseNesting = false; 2156 } 2157 if (NestingProhibited) { 2158 if (OrphanSeen) { 2159 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 2160 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 2161 } else { 2162 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 2163 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 2164 << Recommend << getOpenMPDirectiveName(CurrentRegion); 2165 } 2166 return true; 2167 } 2168 } 2169 return false; 2170 } 2171 2172 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 2173 ArrayRef<OMPClause *> Clauses, 2174 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 2175 bool ErrorFound = false; 2176 unsigned NamedModifiersNumber = 0; 2177 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 2178 OMPD_unknown + 1); 2179 SmallVector<SourceLocation, 4> NameModifierLoc; 2180 for (const auto *C : Clauses) { 2181 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 2182 // At most one if clause without a directive-name-modifier can appear on 2183 // the directive. 2184 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 2185 if (FoundNameModifiers[CurNM]) { 2186 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 2187 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 2188 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 2189 ErrorFound = true; 2190 } else if (CurNM != OMPD_unknown) { 2191 NameModifierLoc.push_back(IC->getNameModifierLoc()); 2192 ++NamedModifiersNumber; 2193 } 2194 FoundNameModifiers[CurNM] = IC; 2195 if (CurNM == OMPD_unknown) 2196 continue; 2197 // Check if the specified name modifier is allowed for the current 2198 // directive. 2199 // At most one if clause with the particular directive-name-modifier can 2200 // appear on the directive. 2201 bool MatchFound = false; 2202 for (auto NM : AllowedNameModifiers) { 2203 if (CurNM == NM) { 2204 MatchFound = true; 2205 break; 2206 } 2207 } 2208 if (!MatchFound) { 2209 S.Diag(IC->getNameModifierLoc(), 2210 diag::err_omp_wrong_if_directive_name_modifier) 2211 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 2212 ErrorFound = true; 2213 } 2214 } 2215 } 2216 // If any if clause on the directive includes a directive-name-modifier then 2217 // all if clauses on the directive must include a directive-name-modifier. 2218 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 2219 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 2220 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 2221 diag::err_omp_no_more_if_clause); 2222 } else { 2223 std::string Values; 2224 std::string Sep(", "); 2225 unsigned AllowedCnt = 0; 2226 unsigned TotalAllowedNum = 2227 AllowedNameModifiers.size() - NamedModifiersNumber; 2228 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 2229 ++Cnt) { 2230 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 2231 if (!FoundNameModifiers[NM]) { 2232 Values += "'"; 2233 Values += getOpenMPDirectiveName(NM); 2234 Values += "'"; 2235 if (AllowedCnt + 2 == TotalAllowedNum) 2236 Values += " or "; 2237 else if (AllowedCnt + 1 != TotalAllowedNum) 2238 Values += Sep; 2239 ++AllowedCnt; 2240 } 2241 } 2242 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 2243 diag::err_omp_unnamed_if_clause) 2244 << (TotalAllowedNum > 1) << Values; 2245 } 2246 for (auto Loc : NameModifierLoc) { 2247 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 2248 } 2249 ErrorFound = true; 2250 } 2251 return ErrorFound; 2252 } 2253 2254 StmtResult Sema::ActOnOpenMPExecutableDirective( 2255 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 2256 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 2257 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 2258 StmtResult Res = StmtError(); 2259 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 2260 StartLoc)) 2261 return StmtError(); 2262 2263 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 2264 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 2265 bool ErrorFound = false; 2266 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 2267 if (AStmt) { 2268 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2269 2270 // Check default data sharing attributes for referenced variables. 2271 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 2272 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 2273 Stmt *S = AStmt; 2274 while (--ThisCaptureLevel >= 0) 2275 S = cast<CapturedStmt>(S)->getCapturedStmt(); 2276 DSAChecker.Visit(S); 2277 if (DSAChecker.isErrorFound()) 2278 return StmtError(); 2279 // Generate list of implicitly defined firstprivate variables. 2280 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 2281 2282 if (!DSAChecker.getImplicitFirstprivate().empty()) { 2283 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 2284 DSAChecker.getImplicitFirstprivate(), SourceLocation(), 2285 SourceLocation(), SourceLocation())) { 2286 ClausesWithImplicit.push_back(Implicit); 2287 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 2288 DSAChecker.getImplicitFirstprivate().size(); 2289 } else 2290 ErrorFound = true; 2291 } 2292 } 2293 2294 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 2295 switch (Kind) { 2296 case OMPD_parallel: 2297 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 2298 EndLoc); 2299 AllowedNameModifiers.push_back(OMPD_parallel); 2300 break; 2301 case OMPD_simd: 2302 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2303 VarsWithInheritedDSA); 2304 break; 2305 case OMPD_for: 2306 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2307 VarsWithInheritedDSA); 2308 break; 2309 case OMPD_for_simd: 2310 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2311 EndLoc, VarsWithInheritedDSA); 2312 break; 2313 case OMPD_sections: 2314 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 2315 EndLoc); 2316 break; 2317 case OMPD_section: 2318 assert(ClausesWithImplicit.empty() && 2319 "No clauses are allowed for 'omp section' directive"); 2320 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 2321 break; 2322 case OMPD_single: 2323 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 2324 EndLoc); 2325 break; 2326 case OMPD_master: 2327 assert(ClausesWithImplicit.empty() && 2328 "No clauses are allowed for 'omp master' directive"); 2329 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 2330 break; 2331 case OMPD_critical: 2332 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 2333 StartLoc, EndLoc); 2334 break; 2335 case OMPD_parallel_for: 2336 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 2337 EndLoc, VarsWithInheritedDSA); 2338 AllowedNameModifiers.push_back(OMPD_parallel); 2339 break; 2340 case OMPD_parallel_for_simd: 2341 Res = ActOnOpenMPParallelForSimdDirective( 2342 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2343 AllowedNameModifiers.push_back(OMPD_parallel); 2344 break; 2345 case OMPD_parallel_sections: 2346 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 2347 StartLoc, EndLoc); 2348 AllowedNameModifiers.push_back(OMPD_parallel); 2349 break; 2350 case OMPD_task: 2351 Res = 2352 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2353 AllowedNameModifiers.push_back(OMPD_task); 2354 break; 2355 case OMPD_taskyield: 2356 assert(ClausesWithImplicit.empty() && 2357 "No clauses are allowed for 'omp taskyield' directive"); 2358 assert(AStmt == nullptr && 2359 "No associated statement allowed for 'omp taskyield' directive"); 2360 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 2361 break; 2362 case OMPD_barrier: 2363 assert(ClausesWithImplicit.empty() && 2364 "No clauses are allowed for 'omp barrier' directive"); 2365 assert(AStmt == nullptr && 2366 "No associated statement allowed for 'omp barrier' directive"); 2367 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 2368 break; 2369 case OMPD_taskwait: 2370 assert(ClausesWithImplicit.empty() && 2371 "No clauses are allowed for 'omp taskwait' directive"); 2372 assert(AStmt == nullptr && 2373 "No associated statement allowed for 'omp taskwait' directive"); 2374 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 2375 break; 2376 case OMPD_taskgroup: 2377 assert(ClausesWithImplicit.empty() && 2378 "No clauses are allowed for 'omp taskgroup' directive"); 2379 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc); 2380 break; 2381 case OMPD_flush: 2382 assert(AStmt == nullptr && 2383 "No associated statement allowed for 'omp flush' directive"); 2384 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 2385 break; 2386 case OMPD_ordered: 2387 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 2388 EndLoc); 2389 break; 2390 case OMPD_atomic: 2391 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 2392 EndLoc); 2393 break; 2394 case OMPD_teams: 2395 Res = 2396 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2397 break; 2398 case OMPD_target: 2399 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 2400 EndLoc); 2401 AllowedNameModifiers.push_back(OMPD_target); 2402 break; 2403 case OMPD_target_parallel: 2404 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 2405 StartLoc, EndLoc); 2406 AllowedNameModifiers.push_back(OMPD_target); 2407 AllowedNameModifiers.push_back(OMPD_parallel); 2408 break; 2409 case OMPD_target_parallel_for: 2410 Res = ActOnOpenMPTargetParallelForDirective( 2411 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2412 AllowedNameModifiers.push_back(OMPD_target); 2413 AllowedNameModifiers.push_back(OMPD_parallel); 2414 break; 2415 case OMPD_cancellation_point: 2416 assert(ClausesWithImplicit.empty() && 2417 "No clauses are allowed for 'omp cancellation point' directive"); 2418 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 2419 "cancellation point' directive"); 2420 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 2421 break; 2422 case OMPD_cancel: 2423 assert(AStmt == nullptr && 2424 "No associated statement allowed for 'omp cancel' directive"); 2425 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 2426 CancelRegion); 2427 AllowedNameModifiers.push_back(OMPD_cancel); 2428 break; 2429 case OMPD_target_data: 2430 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 2431 EndLoc); 2432 AllowedNameModifiers.push_back(OMPD_target_data); 2433 break; 2434 case OMPD_target_enter_data: 2435 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 2436 EndLoc); 2437 AllowedNameModifiers.push_back(OMPD_target_enter_data); 2438 break; 2439 case OMPD_target_exit_data: 2440 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 2441 EndLoc); 2442 AllowedNameModifiers.push_back(OMPD_target_exit_data); 2443 break; 2444 case OMPD_taskloop: 2445 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 2446 EndLoc, VarsWithInheritedDSA); 2447 AllowedNameModifiers.push_back(OMPD_taskloop); 2448 break; 2449 case OMPD_taskloop_simd: 2450 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2451 EndLoc, VarsWithInheritedDSA); 2452 AllowedNameModifiers.push_back(OMPD_taskloop); 2453 break; 2454 case OMPD_distribute: 2455 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 2456 EndLoc, VarsWithInheritedDSA); 2457 break; 2458 case OMPD_target_update: 2459 assert(!AStmt && "Statement is not allowed for target update"); 2460 Res = 2461 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); 2462 AllowedNameModifiers.push_back(OMPD_target_update); 2463 break; 2464 case OMPD_distribute_parallel_for: 2465 Res = ActOnOpenMPDistributeParallelForDirective( 2466 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2467 AllowedNameModifiers.push_back(OMPD_parallel); 2468 break; 2469 case OMPD_distribute_parallel_for_simd: 2470 Res = ActOnOpenMPDistributeParallelForSimdDirective( 2471 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2472 AllowedNameModifiers.push_back(OMPD_parallel); 2473 break; 2474 case OMPD_distribute_simd: 2475 Res = ActOnOpenMPDistributeSimdDirective( 2476 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2477 break; 2478 case OMPD_target_parallel_for_simd: 2479 Res = ActOnOpenMPTargetParallelForSimdDirective( 2480 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2481 AllowedNameModifiers.push_back(OMPD_target); 2482 AllowedNameModifiers.push_back(OMPD_parallel); 2483 break; 2484 case OMPD_target_simd: 2485 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2486 EndLoc, VarsWithInheritedDSA); 2487 AllowedNameModifiers.push_back(OMPD_target); 2488 break; 2489 case OMPD_teams_distribute: 2490 Res = ActOnOpenMPTeamsDistributeDirective( 2491 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2492 break; 2493 case OMPD_teams_distribute_simd: 2494 Res = ActOnOpenMPTeamsDistributeSimdDirective( 2495 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2496 break; 2497 case OMPD_teams_distribute_parallel_for_simd: 2498 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 2499 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2500 AllowedNameModifiers.push_back(OMPD_parallel); 2501 break; 2502 case OMPD_teams_distribute_parallel_for: 2503 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 2504 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2505 AllowedNameModifiers.push_back(OMPD_parallel); 2506 break; 2507 case OMPD_target_teams: 2508 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 2509 EndLoc); 2510 AllowedNameModifiers.push_back(OMPD_target); 2511 break; 2512 case OMPD_target_teams_distribute: 2513 Res = ActOnOpenMPTargetTeamsDistributeDirective( 2514 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2515 AllowedNameModifiers.push_back(OMPD_target); 2516 break; 2517 case OMPD_target_teams_distribute_parallel_for: 2518 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 2519 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2520 AllowedNameModifiers.push_back(OMPD_target); 2521 AllowedNameModifiers.push_back(OMPD_parallel); 2522 break; 2523 case OMPD_target_teams_distribute_parallel_for_simd: 2524 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 2525 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2526 AllowedNameModifiers.push_back(OMPD_target); 2527 AllowedNameModifiers.push_back(OMPD_parallel); 2528 break; 2529 case OMPD_target_teams_distribute_simd: 2530 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 2531 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2532 AllowedNameModifiers.push_back(OMPD_target); 2533 break; 2534 case OMPD_declare_target: 2535 case OMPD_end_declare_target: 2536 case OMPD_threadprivate: 2537 case OMPD_declare_reduction: 2538 case OMPD_declare_simd: 2539 llvm_unreachable("OpenMP Directive is not allowed"); 2540 case OMPD_unknown: 2541 llvm_unreachable("Unknown OpenMP directive"); 2542 } 2543 2544 for (auto P : VarsWithInheritedDSA) { 2545 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 2546 << P.first << P.second->getSourceRange(); 2547 } 2548 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 2549 2550 if (!AllowedNameModifiers.empty()) 2551 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 2552 ErrorFound; 2553 2554 if (ErrorFound) 2555 return StmtError(); 2556 return Res; 2557 } 2558 2559 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 2560 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 2561 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 2562 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 2563 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 2564 assert(Aligneds.size() == Alignments.size()); 2565 assert(Linears.size() == LinModifiers.size()); 2566 assert(Linears.size() == Steps.size()); 2567 if (!DG || DG.get().isNull()) 2568 return DeclGroupPtrTy(); 2569 2570 if (!DG.get().isSingleDecl()) { 2571 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 2572 return DG; 2573 } 2574 auto *ADecl = DG.get().getSingleDecl(); 2575 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 2576 ADecl = FTD->getTemplatedDecl(); 2577 2578 auto *FD = dyn_cast<FunctionDecl>(ADecl); 2579 if (!FD) { 2580 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 2581 return DeclGroupPtrTy(); 2582 } 2583 2584 // OpenMP [2.8.2, declare simd construct, Description] 2585 // The parameter of the simdlen clause must be a constant positive integer 2586 // expression. 2587 ExprResult SL; 2588 if (Simdlen) 2589 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 2590 // OpenMP [2.8.2, declare simd construct, Description] 2591 // The special this pointer can be used as if was one of the arguments to the 2592 // function in any of the linear, aligned, or uniform clauses. 2593 // The uniform clause declares one or more arguments to have an invariant 2594 // value for all concurrent invocations of the function in the execution of a 2595 // single SIMD loop. 2596 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 2597 Expr *UniformedLinearThis = nullptr; 2598 for (auto *E : Uniforms) { 2599 E = E->IgnoreParenImpCasts(); 2600 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2601 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 2602 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2603 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2604 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 2605 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 2606 continue; 2607 } 2608 if (isa<CXXThisExpr>(E)) { 2609 UniformedLinearThis = E; 2610 continue; 2611 } 2612 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2613 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2614 } 2615 // OpenMP [2.8.2, declare simd construct, Description] 2616 // The aligned clause declares that the object to which each list item points 2617 // is aligned to the number of bytes expressed in the optional parameter of 2618 // the aligned clause. 2619 // The special this pointer can be used as if was one of the arguments to the 2620 // function in any of the linear, aligned, or uniform clauses. 2621 // The type of list items appearing in the aligned clause must be array, 2622 // pointer, reference to array, or reference to pointer. 2623 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 2624 Expr *AlignedThis = nullptr; 2625 for (auto *E : Aligneds) { 2626 E = E->IgnoreParenImpCasts(); 2627 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2628 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2629 auto *CanonPVD = PVD->getCanonicalDecl(); 2630 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2631 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2632 ->getCanonicalDecl() == CanonPVD) { 2633 // OpenMP [2.8.1, simd construct, Restrictions] 2634 // A list-item cannot appear in more than one aligned clause. 2635 if (AlignedArgs.count(CanonPVD) > 0) { 2636 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 2637 << 1 << E->getSourceRange(); 2638 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 2639 diag::note_omp_explicit_dsa) 2640 << getOpenMPClauseName(OMPC_aligned); 2641 continue; 2642 } 2643 AlignedArgs[CanonPVD] = E; 2644 QualType QTy = PVD->getType() 2645 .getNonReferenceType() 2646 .getUnqualifiedType() 2647 .getCanonicalType(); 2648 const Type *Ty = QTy.getTypePtrOrNull(); 2649 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 2650 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 2651 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 2652 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 2653 } 2654 continue; 2655 } 2656 } 2657 if (isa<CXXThisExpr>(E)) { 2658 if (AlignedThis) { 2659 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 2660 << 2 << E->getSourceRange(); 2661 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 2662 << getOpenMPClauseName(OMPC_aligned); 2663 } 2664 AlignedThis = E; 2665 continue; 2666 } 2667 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2668 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2669 } 2670 // The optional parameter of the aligned clause, alignment, must be a constant 2671 // positive integer expression. If no optional parameter is specified, 2672 // implementation-defined default alignments for SIMD instructions on the 2673 // target platforms are assumed. 2674 SmallVector<Expr *, 4> NewAligns; 2675 for (auto *E : Alignments) { 2676 ExprResult Align; 2677 if (E) 2678 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 2679 NewAligns.push_back(Align.get()); 2680 } 2681 // OpenMP [2.8.2, declare simd construct, Description] 2682 // The linear clause declares one or more list items to be private to a SIMD 2683 // lane and to have a linear relationship with respect to the iteration space 2684 // of a loop. 2685 // The special this pointer can be used as if was one of the arguments to the 2686 // function in any of the linear, aligned, or uniform clauses. 2687 // When a linear-step expression is specified in a linear clause it must be 2688 // either a constant integer expression or an integer-typed parameter that is 2689 // specified in a uniform clause on the directive. 2690 llvm::DenseMap<Decl *, Expr *> LinearArgs; 2691 const bool IsUniformedThis = UniformedLinearThis != nullptr; 2692 auto MI = LinModifiers.begin(); 2693 for (auto *E : Linears) { 2694 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 2695 ++MI; 2696 E = E->IgnoreParenImpCasts(); 2697 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2698 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2699 auto *CanonPVD = PVD->getCanonicalDecl(); 2700 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2701 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2702 ->getCanonicalDecl() == CanonPVD) { 2703 // OpenMP [2.15.3.7, linear Clause, Restrictions] 2704 // A list-item cannot appear in more than one linear clause. 2705 if (LinearArgs.count(CanonPVD) > 0) { 2706 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2707 << getOpenMPClauseName(OMPC_linear) 2708 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 2709 Diag(LinearArgs[CanonPVD]->getExprLoc(), 2710 diag::note_omp_explicit_dsa) 2711 << getOpenMPClauseName(OMPC_linear); 2712 continue; 2713 } 2714 // Each argument can appear in at most one uniform or linear clause. 2715 if (UniformedArgs.count(CanonPVD) > 0) { 2716 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2717 << getOpenMPClauseName(OMPC_linear) 2718 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 2719 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 2720 diag::note_omp_explicit_dsa) 2721 << getOpenMPClauseName(OMPC_uniform); 2722 continue; 2723 } 2724 LinearArgs[CanonPVD] = E; 2725 if (E->isValueDependent() || E->isTypeDependent() || 2726 E->isInstantiationDependent() || 2727 E->containsUnexpandedParameterPack()) 2728 continue; 2729 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 2730 PVD->getOriginalType()); 2731 continue; 2732 } 2733 } 2734 if (isa<CXXThisExpr>(E)) { 2735 if (UniformedLinearThis) { 2736 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2737 << getOpenMPClauseName(OMPC_linear) 2738 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 2739 << E->getSourceRange(); 2740 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 2741 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 2742 : OMPC_linear); 2743 continue; 2744 } 2745 UniformedLinearThis = E; 2746 if (E->isValueDependent() || E->isTypeDependent() || 2747 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 2748 continue; 2749 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 2750 E->getType()); 2751 continue; 2752 } 2753 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2754 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2755 } 2756 Expr *Step = nullptr; 2757 Expr *NewStep = nullptr; 2758 SmallVector<Expr *, 4> NewSteps; 2759 for (auto *E : Steps) { 2760 // Skip the same step expression, it was checked already. 2761 if (Step == E || !E) { 2762 NewSteps.push_back(E ? NewStep : nullptr); 2763 continue; 2764 } 2765 Step = E; 2766 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 2767 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2768 auto *CanonPVD = PVD->getCanonicalDecl(); 2769 if (UniformedArgs.count(CanonPVD) == 0) { 2770 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 2771 << Step->getSourceRange(); 2772 } else if (E->isValueDependent() || E->isTypeDependent() || 2773 E->isInstantiationDependent() || 2774 E->containsUnexpandedParameterPack() || 2775 CanonPVD->getType()->hasIntegerRepresentation()) 2776 NewSteps.push_back(Step); 2777 else { 2778 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 2779 << Step->getSourceRange(); 2780 } 2781 continue; 2782 } 2783 NewStep = Step; 2784 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 2785 !Step->isInstantiationDependent() && 2786 !Step->containsUnexpandedParameterPack()) { 2787 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 2788 .get(); 2789 if (NewStep) 2790 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 2791 } 2792 NewSteps.push_back(NewStep); 2793 } 2794 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 2795 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 2796 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 2797 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 2798 const_cast<Expr **>(Linears.data()), Linears.size(), 2799 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 2800 NewSteps.data(), NewSteps.size(), SR); 2801 ADecl->addAttr(NewAttr); 2802 return ConvertDeclToDeclGroup(ADecl); 2803 } 2804 2805 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 2806 Stmt *AStmt, 2807 SourceLocation StartLoc, 2808 SourceLocation EndLoc) { 2809 if (!AStmt) 2810 return StmtError(); 2811 2812 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 2813 // 1.2.2 OpenMP Language Terminology 2814 // Structured block - An executable statement with a single entry at the 2815 // top and a single exit at the bottom. 2816 // The point of exit cannot be a branch out of the structured block. 2817 // longjmp() and throw() must not violate the entry/exit criteria. 2818 CS->getCapturedDecl()->setNothrow(); 2819 2820 getCurFunction()->setHasBranchProtectedScope(); 2821 2822 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 2823 DSAStack->isCancelRegion()); 2824 } 2825 2826 namespace { 2827 /// \brief Helper class for checking canonical form of the OpenMP loops and 2828 /// extracting iteration space of each loop in the loop nest, that will be used 2829 /// for IR generation. 2830 class OpenMPIterationSpaceChecker { 2831 /// \brief Reference to Sema. 2832 Sema &SemaRef; 2833 /// \brief A location for diagnostics (when there is no some better location). 2834 SourceLocation DefaultLoc; 2835 /// \brief A location for diagnostics (when increment is not compatible). 2836 SourceLocation ConditionLoc; 2837 /// \brief A source location for referring to loop init later. 2838 SourceRange InitSrcRange; 2839 /// \brief A source location for referring to condition later. 2840 SourceRange ConditionSrcRange; 2841 /// \brief A source location for referring to increment later. 2842 SourceRange IncrementSrcRange; 2843 /// \brief Loop variable. 2844 ValueDecl *LCDecl = nullptr; 2845 /// \brief Reference to loop variable. 2846 Expr *LCRef = nullptr; 2847 /// \brief Lower bound (initializer for the var). 2848 Expr *LB = nullptr; 2849 /// \brief Upper bound. 2850 Expr *UB = nullptr; 2851 /// \brief Loop step (increment). 2852 Expr *Step = nullptr; 2853 /// \brief This flag is true when condition is one of: 2854 /// Var < UB 2855 /// Var <= UB 2856 /// UB > Var 2857 /// UB >= Var 2858 bool TestIsLessOp = false; 2859 /// \brief This flag is true when condition is strict ( < or > ). 2860 bool TestIsStrictOp = false; 2861 /// \brief This flag is true when step is subtracted on each iteration. 2862 bool SubtractStep = false; 2863 2864 public: 2865 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 2866 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 2867 /// \brief Check init-expr for canonical loop form and save loop counter 2868 /// variable - #Var and its initialization value - #LB. 2869 bool CheckInit(Stmt *S, bool EmitDiags = true); 2870 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 2871 /// for less/greater and for strict/non-strict comparison. 2872 bool CheckCond(Expr *S); 2873 /// \brief Check incr-expr for canonical loop form and return true if it 2874 /// does not conform, otherwise save loop step (#Step). 2875 bool CheckInc(Expr *S); 2876 /// \brief Return the loop counter variable. 2877 ValueDecl *GetLoopDecl() const { return LCDecl; } 2878 /// \brief Return the reference expression to loop counter variable. 2879 Expr *GetLoopDeclRefExpr() const { return LCRef; } 2880 /// \brief Source range of the loop init. 2881 SourceRange GetInitSrcRange() const { return InitSrcRange; } 2882 /// \brief Source range of the loop condition. 2883 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 2884 /// \brief Source range of the loop increment. 2885 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 2886 /// \brief True if the step should be subtracted. 2887 bool ShouldSubtractStep() const { return SubtractStep; } 2888 /// \brief Build the expression to calculate the number of iterations. 2889 Expr * 2890 BuildNumIterations(Scope *S, const bool LimitedType, 2891 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 2892 /// \brief Build the precondition expression for the loops. 2893 Expr *BuildPreCond(Scope *S, Expr *Cond, 2894 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 2895 /// \brief Build reference expression to the counter be used for codegen. 2896 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 2897 DSAStackTy &DSA) const; 2898 /// \brief Build reference expression to the private counter be used for 2899 /// codegen. 2900 Expr *BuildPrivateCounterVar() const; 2901 /// \brief Build initialization of the counter be used for codegen. 2902 Expr *BuildCounterInit() const; 2903 /// \brief Build step of the counter be used for codegen. 2904 Expr *BuildCounterStep() const; 2905 /// \brief Return true if any expression is dependent. 2906 bool Dependent() const; 2907 2908 private: 2909 /// \brief Check the right-hand side of an assignment in the increment 2910 /// expression. 2911 bool CheckIncRHS(Expr *RHS); 2912 /// \brief Helper to set loop counter variable and its initializer. 2913 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 2914 /// \brief Helper to set upper bound. 2915 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 2916 SourceLocation SL); 2917 /// \brief Helper to set loop increment. 2918 bool SetStep(Expr *NewStep, bool Subtract); 2919 }; 2920 2921 bool OpenMPIterationSpaceChecker::Dependent() const { 2922 if (!LCDecl) { 2923 assert(!LB && !UB && !Step); 2924 return false; 2925 } 2926 return LCDecl->getType()->isDependentType() || 2927 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 2928 (Step && Step->isValueDependent()); 2929 } 2930 2931 static Expr *getExprAsWritten(Expr *E) { 2932 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 2933 E = ExprTemp->getSubExpr(); 2934 2935 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 2936 E = MTE->GetTemporaryExpr(); 2937 2938 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 2939 E = Binder->getSubExpr(); 2940 2941 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 2942 E = ICE->getSubExprAsWritten(); 2943 return E->IgnoreParens(); 2944 } 2945 2946 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 2947 Expr *NewLCRefExpr, 2948 Expr *NewLB) { 2949 // State consistency checking to ensure correct usage. 2950 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 2951 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 2952 if (!NewLCDecl || !NewLB) 2953 return true; 2954 LCDecl = getCanonicalDecl(NewLCDecl); 2955 LCRef = NewLCRefExpr; 2956 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 2957 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 2958 if ((Ctor->isCopyOrMoveConstructor() || 2959 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 2960 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 2961 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 2962 LB = NewLB; 2963 return false; 2964 } 2965 2966 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 2967 SourceRange SR, SourceLocation SL) { 2968 // State consistency checking to ensure correct usage. 2969 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 2970 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 2971 if (!NewUB) 2972 return true; 2973 UB = NewUB; 2974 TestIsLessOp = LessOp; 2975 TestIsStrictOp = StrictOp; 2976 ConditionSrcRange = SR; 2977 ConditionLoc = SL; 2978 return false; 2979 } 2980 2981 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 2982 // State consistency checking to ensure correct usage. 2983 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 2984 if (!NewStep) 2985 return true; 2986 if (!NewStep->isValueDependent()) { 2987 // Check that the step is integer expression. 2988 SourceLocation StepLoc = NewStep->getLocStart(); 2989 ExprResult Val = 2990 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep); 2991 if (Val.isInvalid()) 2992 return true; 2993 NewStep = Val.get(); 2994 2995 // OpenMP [2.6, Canonical Loop Form, Restrictions] 2996 // If test-expr is of form var relational-op b and relational-op is < or 2997 // <= then incr-expr must cause var to increase on each iteration of the 2998 // loop. If test-expr is of form var relational-op b and relational-op is 2999 // > or >= then incr-expr must cause var to decrease on each iteration of 3000 // the loop. 3001 // If test-expr is of form b relational-op var and relational-op is < or 3002 // <= then incr-expr must cause var to decrease on each iteration of the 3003 // loop. If test-expr is of form b relational-op var and relational-op is 3004 // > or >= then incr-expr must cause var to increase on each iteration of 3005 // the loop. 3006 llvm::APSInt Result; 3007 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 3008 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 3009 bool IsConstNeg = 3010 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 3011 bool IsConstPos = 3012 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 3013 bool IsConstZero = IsConstant && !Result.getBoolValue(); 3014 if (UB && (IsConstZero || 3015 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 3016 : (IsConstPos || (IsUnsigned && !Subtract))))) { 3017 SemaRef.Diag(NewStep->getExprLoc(), 3018 diag::err_omp_loop_incr_not_compatible) 3019 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 3020 SemaRef.Diag(ConditionLoc, 3021 diag::note_omp_loop_cond_requres_compatible_incr) 3022 << TestIsLessOp << ConditionSrcRange; 3023 return true; 3024 } 3025 if (TestIsLessOp == Subtract) { 3026 NewStep = 3027 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 3028 .get(); 3029 Subtract = !Subtract; 3030 } 3031 } 3032 3033 Step = NewStep; 3034 SubtractStep = Subtract; 3035 return false; 3036 } 3037 3038 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 3039 // Check init-expr for canonical loop form and save loop counter 3040 // variable - #Var and its initialization value - #LB. 3041 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 3042 // var = lb 3043 // integer-type var = lb 3044 // random-access-iterator-type var = lb 3045 // pointer-type var = lb 3046 // 3047 if (!S) { 3048 if (EmitDiags) { 3049 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 3050 } 3051 return true; 3052 } 3053 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3054 if (!ExprTemp->cleanupsHaveSideEffects()) 3055 S = ExprTemp->getSubExpr(); 3056 3057 InitSrcRange = S->getSourceRange(); 3058 if (Expr *E = dyn_cast<Expr>(S)) 3059 S = E->IgnoreParens(); 3060 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3061 if (BO->getOpcode() == BO_Assign) { 3062 auto *LHS = BO->getLHS()->IgnoreParens(); 3063 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3064 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3065 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3066 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3067 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 3068 } 3069 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3070 if (ME->isArrow() && 3071 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3072 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3073 } 3074 } 3075 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 3076 if (DS->isSingleDecl()) { 3077 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 3078 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 3079 // Accept non-canonical init form here but emit ext. warning. 3080 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 3081 SemaRef.Diag(S->getLocStart(), 3082 diag::ext_omp_loop_not_canonical_init) 3083 << S->getSourceRange(); 3084 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 3085 } 3086 } 3087 } 3088 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3089 if (CE->getOperator() == OO_Equal) { 3090 auto *LHS = CE->getArg(0); 3091 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3092 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3093 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3094 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3095 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 3096 } 3097 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3098 if (ME->isArrow() && 3099 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3100 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3101 } 3102 } 3103 } 3104 3105 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3106 return false; 3107 if (EmitDiags) { 3108 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 3109 << S->getSourceRange(); 3110 } 3111 return true; 3112 } 3113 3114 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 3115 /// variable (which may be the loop variable) if possible. 3116 static const ValueDecl *GetInitLCDecl(Expr *E) { 3117 if (!E) 3118 return nullptr; 3119 E = getExprAsWritten(E); 3120 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 3121 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3122 if ((Ctor->isCopyOrMoveConstructor() || 3123 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3124 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3125 E = CE->getArg(0)->IgnoreParenImpCasts(); 3126 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 3127 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 3128 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3129 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3130 return getCanonicalDecl(ME->getMemberDecl()); 3131 return getCanonicalDecl(VD); 3132 } 3133 } 3134 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 3135 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3136 return getCanonicalDecl(ME->getMemberDecl()); 3137 return nullptr; 3138 } 3139 3140 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 3141 // Check test-expr for canonical form, save upper-bound UB, flags for 3142 // less/greater and for strict/non-strict comparison. 3143 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3144 // var relational-op b 3145 // b relational-op var 3146 // 3147 if (!S) { 3148 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 3149 return true; 3150 } 3151 S = getExprAsWritten(S); 3152 SourceLocation CondLoc = S->getLocStart(); 3153 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3154 if (BO->isRelationalOp()) { 3155 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3156 return SetUB(BO->getRHS(), 3157 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 3158 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3159 BO->getSourceRange(), BO->getOperatorLoc()); 3160 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 3161 return SetUB(BO->getLHS(), 3162 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 3163 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3164 BO->getSourceRange(), BO->getOperatorLoc()); 3165 } 3166 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3167 if (CE->getNumArgs() == 2) { 3168 auto Op = CE->getOperator(); 3169 switch (Op) { 3170 case OO_Greater: 3171 case OO_GreaterEqual: 3172 case OO_Less: 3173 case OO_LessEqual: 3174 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3175 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 3176 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3177 CE->getOperatorLoc()); 3178 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 3179 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 3180 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3181 CE->getOperatorLoc()); 3182 break; 3183 default: 3184 break; 3185 } 3186 } 3187 } 3188 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3189 return false; 3190 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 3191 << S->getSourceRange() << LCDecl; 3192 return true; 3193 } 3194 3195 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 3196 // RHS of canonical loop form increment can be: 3197 // var + incr 3198 // incr + var 3199 // var - incr 3200 // 3201 RHS = RHS->IgnoreParenImpCasts(); 3202 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 3203 if (BO->isAdditiveOp()) { 3204 bool IsAdd = BO->getOpcode() == BO_Add; 3205 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3206 return SetStep(BO->getRHS(), !IsAdd); 3207 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 3208 return SetStep(BO->getLHS(), false); 3209 } 3210 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 3211 bool IsAdd = CE->getOperator() == OO_Plus; 3212 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 3213 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3214 return SetStep(CE->getArg(1), !IsAdd); 3215 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 3216 return SetStep(CE->getArg(0), false); 3217 } 3218 } 3219 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3220 return false; 3221 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3222 << RHS->getSourceRange() << LCDecl; 3223 return true; 3224 } 3225 3226 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 3227 // Check incr-expr for canonical loop form and return true if it 3228 // does not conform. 3229 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3230 // ++var 3231 // var++ 3232 // --var 3233 // var-- 3234 // var += incr 3235 // var -= incr 3236 // var = var + incr 3237 // var = incr + var 3238 // var = var - incr 3239 // 3240 if (!S) { 3241 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 3242 return true; 3243 } 3244 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3245 if (!ExprTemp->cleanupsHaveSideEffects()) 3246 S = ExprTemp->getSubExpr(); 3247 3248 IncrementSrcRange = S->getSourceRange(); 3249 S = S->IgnoreParens(); 3250 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 3251 if (UO->isIncrementDecrementOp() && 3252 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 3253 return SetStep(SemaRef 3254 .ActOnIntegerConstant(UO->getLocStart(), 3255 (UO->isDecrementOp() ? -1 : 1)) 3256 .get(), 3257 false); 3258 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3259 switch (BO->getOpcode()) { 3260 case BO_AddAssign: 3261 case BO_SubAssign: 3262 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3263 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 3264 break; 3265 case BO_Assign: 3266 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3267 return CheckIncRHS(BO->getRHS()); 3268 break; 3269 default: 3270 break; 3271 } 3272 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3273 switch (CE->getOperator()) { 3274 case OO_PlusPlus: 3275 case OO_MinusMinus: 3276 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3277 return SetStep(SemaRef 3278 .ActOnIntegerConstant( 3279 CE->getLocStart(), 3280 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 3281 .get(), 3282 false); 3283 break; 3284 case OO_PlusEqual: 3285 case OO_MinusEqual: 3286 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3287 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 3288 break; 3289 case OO_Equal: 3290 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3291 return CheckIncRHS(CE->getArg(1)); 3292 break; 3293 default: 3294 break; 3295 } 3296 } 3297 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3298 return false; 3299 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3300 << S->getSourceRange() << LCDecl; 3301 return true; 3302 } 3303 3304 static ExprResult 3305 tryBuildCapture(Sema &SemaRef, Expr *Capture, 3306 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3307 if (SemaRef.CurContext->isDependentContext()) 3308 return ExprResult(Capture); 3309 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 3310 return SemaRef.PerformImplicitConversion( 3311 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 3312 /*AllowExplicit=*/true); 3313 auto I = Captures.find(Capture); 3314 if (I != Captures.end()) 3315 return buildCapture(SemaRef, Capture, I->second); 3316 DeclRefExpr *Ref = nullptr; 3317 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 3318 Captures[Capture] = Ref; 3319 return Res; 3320 } 3321 3322 /// \brief Build the expression to calculate the number of iterations. 3323 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 3324 Scope *S, const bool LimitedType, 3325 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3326 ExprResult Diff; 3327 auto VarType = LCDecl->getType().getNonReferenceType(); 3328 if (VarType->isIntegerType() || VarType->isPointerType() || 3329 SemaRef.getLangOpts().CPlusPlus) { 3330 // Upper - Lower 3331 auto *UBExpr = TestIsLessOp ? UB : LB; 3332 auto *LBExpr = TestIsLessOp ? LB : UB; 3333 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 3334 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 3335 if (!Upper || !Lower) 3336 return nullptr; 3337 3338 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 3339 3340 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 3341 // BuildBinOp already emitted error, this one is to point user to upper 3342 // and lower bound, and to tell what is passed to 'operator-'. 3343 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 3344 << Upper->getSourceRange() << Lower->getSourceRange(); 3345 return nullptr; 3346 } 3347 } 3348 3349 if (!Diff.isUsable()) 3350 return nullptr; 3351 3352 // Upper - Lower [- 1] 3353 if (TestIsStrictOp) 3354 Diff = SemaRef.BuildBinOp( 3355 S, DefaultLoc, BO_Sub, Diff.get(), 3356 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3357 if (!Diff.isUsable()) 3358 return nullptr; 3359 3360 // Upper - Lower [- 1] + Step 3361 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 3362 if (!NewStep.isUsable()) 3363 return nullptr; 3364 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 3365 if (!Diff.isUsable()) 3366 return nullptr; 3367 3368 // Parentheses (for dumping/debugging purposes only). 3369 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 3370 if (!Diff.isUsable()) 3371 return nullptr; 3372 3373 // (Upper - Lower [- 1] + Step) / Step 3374 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 3375 if (!Diff.isUsable()) 3376 return nullptr; 3377 3378 // OpenMP runtime requires 32-bit or 64-bit loop variables. 3379 QualType Type = Diff.get()->getType(); 3380 auto &C = SemaRef.Context; 3381 bool UseVarType = VarType->hasIntegerRepresentation() && 3382 C.getTypeSize(Type) > C.getTypeSize(VarType); 3383 if (!Type->isIntegerType() || UseVarType) { 3384 unsigned NewSize = 3385 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 3386 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 3387 : Type->hasSignedIntegerRepresentation(); 3388 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 3389 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 3390 Diff = SemaRef.PerformImplicitConversion( 3391 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 3392 if (!Diff.isUsable()) 3393 return nullptr; 3394 } 3395 } 3396 if (LimitedType) { 3397 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 3398 if (NewSize != C.getTypeSize(Type)) { 3399 if (NewSize < C.getTypeSize(Type)) { 3400 assert(NewSize == 64 && "incorrect loop var size"); 3401 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 3402 << InitSrcRange << ConditionSrcRange; 3403 } 3404 QualType NewType = C.getIntTypeForBitwidth( 3405 NewSize, Type->hasSignedIntegerRepresentation() || 3406 C.getTypeSize(Type) < NewSize); 3407 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 3408 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 3409 Sema::AA_Converting, true); 3410 if (!Diff.isUsable()) 3411 return nullptr; 3412 } 3413 } 3414 } 3415 3416 return Diff.get(); 3417 } 3418 3419 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 3420 Scope *S, Expr *Cond, 3421 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3422 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 3423 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3424 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3425 3426 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 3427 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 3428 if (!NewLB.isUsable() || !NewUB.isUsable()) 3429 return nullptr; 3430 3431 auto CondExpr = SemaRef.BuildBinOp( 3432 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 3433 : (TestIsStrictOp ? BO_GT : BO_GE), 3434 NewLB.get(), NewUB.get()); 3435 if (CondExpr.isUsable()) { 3436 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 3437 SemaRef.Context.BoolTy)) 3438 CondExpr = SemaRef.PerformImplicitConversion( 3439 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 3440 /*AllowExplicit=*/true); 3441 } 3442 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3443 // Otherwise use original loop conditon and evaluate it in runtime. 3444 return CondExpr.isUsable() ? CondExpr.get() : Cond; 3445 } 3446 3447 /// \brief Build reference expression to the counter be used for codegen. 3448 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 3449 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 3450 auto *VD = dyn_cast<VarDecl>(LCDecl); 3451 if (!VD) { 3452 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 3453 auto *Ref = buildDeclRefExpr( 3454 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 3455 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 3456 // If the loop control decl is explicitly marked as private, do not mark it 3457 // as captured again. 3458 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 3459 Captures.insert(std::make_pair(LCRef, Ref)); 3460 return Ref; 3461 } 3462 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 3463 DefaultLoc); 3464 } 3465 3466 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 3467 if (LCDecl && !LCDecl->isInvalidDecl()) { 3468 auto Type = LCDecl->getType().getNonReferenceType(); 3469 auto *PrivateVar = 3470 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 3471 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 3472 if (PrivateVar->isInvalidDecl()) 3473 return nullptr; 3474 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 3475 } 3476 return nullptr; 3477 } 3478 3479 /// \brief Build initialization of the counter to be used for codegen. 3480 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 3481 3482 /// \brief Build step of the counter be used for codegen. 3483 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 3484 3485 /// \brief Iteration space of a single for loop. 3486 struct LoopIterationSpace final { 3487 /// \brief Condition of the loop. 3488 Expr *PreCond = nullptr; 3489 /// \brief This expression calculates the number of iterations in the loop. 3490 /// It is always possible to calculate it before starting the loop. 3491 Expr *NumIterations = nullptr; 3492 /// \brief The loop counter variable. 3493 Expr *CounterVar = nullptr; 3494 /// \brief Private loop counter variable. 3495 Expr *PrivateCounterVar = nullptr; 3496 /// \brief This is initializer for the initial value of #CounterVar. 3497 Expr *CounterInit = nullptr; 3498 /// \brief This is step for the #CounterVar used to generate its update: 3499 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 3500 Expr *CounterStep = nullptr; 3501 /// \brief Should step be subtracted? 3502 bool Subtract = false; 3503 /// \brief Source range of the loop init. 3504 SourceRange InitSrcRange; 3505 /// \brief Source range of the loop condition. 3506 SourceRange CondSrcRange; 3507 /// \brief Source range of the loop increment. 3508 SourceRange IncSrcRange; 3509 }; 3510 3511 } // namespace 3512 3513 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 3514 assert(getLangOpts().OpenMP && "OpenMP is not active."); 3515 assert(Init && "Expected loop in canonical form."); 3516 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 3517 if (AssociatedLoops > 0 && 3518 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 3519 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 3520 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 3521 if (auto *D = ISC.GetLoopDecl()) { 3522 auto *VD = dyn_cast<VarDecl>(D); 3523 if (!VD) { 3524 if (auto *Private = IsOpenMPCapturedDecl(D)) 3525 VD = Private; 3526 else { 3527 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 3528 /*WithInit=*/false); 3529 VD = cast<VarDecl>(Ref->getDecl()); 3530 } 3531 } 3532 DSAStack->addLoopControlVariable(D, VD); 3533 } 3534 } 3535 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 3536 } 3537 } 3538 3539 /// \brief Called on a for stmt to check and extract its iteration space 3540 /// for further processing (such as collapsing). 3541 static bool CheckOpenMPIterationSpace( 3542 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 3543 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 3544 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 3545 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3546 LoopIterationSpace &ResultIterSpace, 3547 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3548 // OpenMP [2.6, Canonical Loop Form] 3549 // for (init-expr; test-expr; incr-expr) structured-block 3550 auto *For = dyn_cast_or_null<ForStmt>(S); 3551 if (!For) { 3552 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 3553 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 3554 << getOpenMPDirectiveName(DKind) << NestedLoopCount 3555 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 3556 if (NestedLoopCount > 1) { 3557 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 3558 SemaRef.Diag(DSA.getConstructLoc(), 3559 diag::note_omp_collapse_ordered_expr) 3560 << 2 << CollapseLoopCountExpr->getSourceRange() 3561 << OrderedLoopCountExpr->getSourceRange(); 3562 else if (CollapseLoopCountExpr) 3563 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3564 diag::note_omp_collapse_ordered_expr) 3565 << 0 << CollapseLoopCountExpr->getSourceRange(); 3566 else 3567 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3568 diag::note_omp_collapse_ordered_expr) 3569 << 1 << OrderedLoopCountExpr->getSourceRange(); 3570 } 3571 return true; 3572 } 3573 assert(For->getBody()); 3574 3575 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 3576 3577 // Check init. 3578 auto Init = For->getInit(); 3579 if (ISC.CheckInit(Init)) 3580 return true; 3581 3582 bool HasErrors = false; 3583 3584 // Check loop variable's type. 3585 if (auto *LCDecl = ISC.GetLoopDecl()) { 3586 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 3587 3588 // OpenMP [2.6, Canonical Loop Form] 3589 // Var is one of the following: 3590 // A variable of signed or unsigned integer type. 3591 // For C++, a variable of a random access iterator type. 3592 // For C, a variable of a pointer type. 3593 auto VarType = LCDecl->getType().getNonReferenceType(); 3594 if (!VarType->isDependentType() && !VarType->isIntegerType() && 3595 !VarType->isPointerType() && 3596 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 3597 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 3598 << SemaRef.getLangOpts().CPlusPlus; 3599 HasErrors = true; 3600 } 3601 3602 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 3603 // a Construct 3604 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3605 // parallel for construct is (are) private. 3606 // The loop iteration variable in the associated for-loop of a simd 3607 // construct with just one associated for-loop is linear with a 3608 // constant-linear-step that is the increment of the associated for-loop. 3609 // Exclude loop var from the list of variables with implicitly defined data 3610 // sharing attributes. 3611 VarsWithImplicitDSA.erase(LCDecl); 3612 3613 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 3614 // in a Construct, C/C++]. 3615 // The loop iteration variable in the associated for-loop of a simd 3616 // construct with just one associated for-loop may be listed in a linear 3617 // clause with a constant-linear-step that is the increment of the 3618 // associated for-loop. 3619 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3620 // parallel for construct may be listed in a private or lastprivate clause. 3621 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 3622 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 3623 // declared in the loop and it is predetermined as a private. 3624 auto PredeterminedCKind = 3625 isOpenMPSimdDirective(DKind) 3626 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 3627 : OMPC_private; 3628 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3629 DVar.CKind != PredeterminedCKind) || 3630 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 3631 isOpenMPDistributeDirective(DKind)) && 3632 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3633 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 3634 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 3635 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 3636 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 3637 << getOpenMPClauseName(PredeterminedCKind); 3638 if (DVar.RefExpr == nullptr) 3639 DVar.CKind = PredeterminedCKind; 3640 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 3641 HasErrors = true; 3642 } else if (LoopDeclRefExpr != nullptr) { 3643 // Make the loop iteration variable private (for worksharing constructs), 3644 // linear (for simd directives with the only one associated loop) or 3645 // lastprivate (for simd directives with several collapsed or ordered 3646 // loops). 3647 if (DVar.CKind == OMPC_unknown) 3648 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 3649 [](OpenMPDirectiveKind) -> bool { return true; }, 3650 /*FromParent=*/false); 3651 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 3652 } 3653 3654 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 3655 3656 // Check test-expr. 3657 HasErrors |= ISC.CheckCond(For->getCond()); 3658 3659 // Check incr-expr. 3660 HasErrors |= ISC.CheckInc(For->getInc()); 3661 } 3662 3663 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 3664 return HasErrors; 3665 3666 // Build the loop's iteration space representation. 3667 ResultIterSpace.PreCond = 3668 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 3669 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 3670 DSA.getCurScope(), 3671 (isOpenMPWorksharingDirective(DKind) || 3672 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 3673 Captures); 3674 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 3675 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 3676 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 3677 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 3678 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 3679 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 3680 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 3681 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 3682 3683 HasErrors |= (ResultIterSpace.PreCond == nullptr || 3684 ResultIterSpace.NumIterations == nullptr || 3685 ResultIterSpace.CounterVar == nullptr || 3686 ResultIterSpace.PrivateCounterVar == nullptr || 3687 ResultIterSpace.CounterInit == nullptr || 3688 ResultIterSpace.CounterStep == nullptr); 3689 3690 return HasErrors; 3691 } 3692 3693 /// \brief Build 'VarRef = Start. 3694 static ExprResult 3695 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 3696 ExprResult Start, 3697 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3698 // Build 'VarRef = Start. 3699 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 3700 if (!NewStart.isUsable()) 3701 return ExprError(); 3702 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 3703 VarRef.get()->getType())) { 3704 NewStart = SemaRef.PerformImplicitConversion( 3705 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 3706 /*AllowExplicit=*/true); 3707 if (!NewStart.isUsable()) 3708 return ExprError(); 3709 } 3710 3711 auto Init = 3712 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3713 return Init; 3714 } 3715 3716 /// \brief Build 'VarRef = Start + Iter * Step'. 3717 static ExprResult 3718 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 3719 ExprResult VarRef, ExprResult Start, ExprResult Iter, 3720 ExprResult Step, bool Subtract, 3721 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 3722 // Add parentheses (for debugging purposes only). 3723 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 3724 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 3725 !Step.isUsable()) 3726 return ExprError(); 3727 3728 ExprResult NewStep = Step; 3729 if (Captures) 3730 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 3731 if (NewStep.isInvalid()) 3732 return ExprError(); 3733 ExprResult Update = 3734 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 3735 if (!Update.isUsable()) 3736 return ExprError(); 3737 3738 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 3739 // 'VarRef = Start (+|-) Iter * Step'. 3740 ExprResult NewStart = Start; 3741 if (Captures) 3742 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 3743 if (NewStart.isInvalid()) 3744 return ExprError(); 3745 3746 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 3747 ExprResult SavedUpdate = Update; 3748 ExprResult UpdateVal; 3749 if (VarRef.get()->getType()->isOverloadableType() || 3750 NewStart.get()->getType()->isOverloadableType() || 3751 Update.get()->getType()->isOverloadableType()) { 3752 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3753 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3754 Update = 3755 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3756 if (Update.isUsable()) { 3757 UpdateVal = 3758 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 3759 VarRef.get(), SavedUpdate.get()); 3760 if (UpdateVal.isUsable()) { 3761 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 3762 UpdateVal.get()); 3763 } 3764 } 3765 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3766 } 3767 3768 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 3769 if (!Update.isUsable() || !UpdateVal.isUsable()) { 3770 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 3771 NewStart.get(), SavedUpdate.get()); 3772 if (!Update.isUsable()) 3773 return ExprError(); 3774 3775 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 3776 VarRef.get()->getType())) { 3777 Update = SemaRef.PerformImplicitConversion( 3778 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 3779 if (!Update.isUsable()) 3780 return ExprError(); 3781 } 3782 3783 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 3784 } 3785 return Update; 3786 } 3787 3788 /// \brief Convert integer expression \a E to make it have at least \a Bits 3789 /// bits. 3790 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 3791 if (E == nullptr) 3792 return ExprError(); 3793 auto &C = SemaRef.Context; 3794 QualType OldType = E->getType(); 3795 unsigned HasBits = C.getTypeSize(OldType); 3796 if (HasBits >= Bits) 3797 return ExprResult(E); 3798 // OK to convert to signed, because new type has more bits than old. 3799 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 3800 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 3801 true); 3802 } 3803 3804 /// \brief Check if the given expression \a E is a constant integer that fits 3805 /// into \a Bits bits. 3806 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 3807 if (E == nullptr) 3808 return false; 3809 llvm::APSInt Result; 3810 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 3811 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 3812 return false; 3813 } 3814 3815 /// Build preinits statement for the given declarations. 3816 static Stmt *buildPreInits(ASTContext &Context, 3817 SmallVectorImpl<Decl *> &PreInits) { 3818 if (!PreInits.empty()) { 3819 return new (Context) DeclStmt( 3820 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 3821 SourceLocation(), SourceLocation()); 3822 } 3823 return nullptr; 3824 } 3825 3826 /// Build preinits statement for the given declarations. 3827 static Stmt *buildPreInits(ASTContext &Context, 3828 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3829 if (!Captures.empty()) { 3830 SmallVector<Decl *, 16> PreInits; 3831 for (auto &Pair : Captures) 3832 PreInits.push_back(Pair.second->getDecl()); 3833 return buildPreInits(Context, PreInits); 3834 } 3835 return nullptr; 3836 } 3837 3838 /// Build postupdate expression for the given list of postupdates expressions. 3839 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 3840 Expr *PostUpdate = nullptr; 3841 if (!PostUpdates.empty()) { 3842 for (auto *E : PostUpdates) { 3843 Expr *ConvE = S.BuildCStyleCastExpr( 3844 E->getExprLoc(), 3845 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 3846 E->getExprLoc(), E) 3847 .get(); 3848 PostUpdate = PostUpdate 3849 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 3850 PostUpdate, ConvE) 3851 .get() 3852 : ConvE; 3853 } 3854 } 3855 return PostUpdate; 3856 } 3857 3858 /// \brief Called on a for stmt to check itself and nested loops (if any). 3859 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 3860 /// number of collapsed loops otherwise. 3861 static unsigned 3862 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 3863 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 3864 DSAStackTy &DSA, 3865 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3866 OMPLoopDirective::HelperExprs &Built) { 3867 unsigned NestedLoopCount = 1; 3868 if (CollapseLoopCountExpr) { 3869 // Found 'collapse' clause - calculate collapse number. 3870 llvm::APSInt Result; 3871 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 3872 NestedLoopCount = Result.getLimitedValue(); 3873 } 3874 if (OrderedLoopCountExpr) { 3875 // Found 'ordered' clause - calculate collapse number. 3876 llvm::APSInt Result; 3877 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 3878 if (Result.getLimitedValue() < NestedLoopCount) { 3879 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3880 diag::err_omp_wrong_ordered_loop_count) 3881 << OrderedLoopCountExpr->getSourceRange(); 3882 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3883 diag::note_collapse_loop_count) 3884 << CollapseLoopCountExpr->getSourceRange(); 3885 } 3886 NestedLoopCount = Result.getLimitedValue(); 3887 } 3888 } 3889 // This is helper routine for loop directives (e.g., 'for', 'simd', 3890 // 'for simd', etc.). 3891 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 3892 SmallVector<LoopIterationSpace, 4> IterSpaces; 3893 IterSpaces.resize(NestedLoopCount); 3894 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 3895 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 3896 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 3897 NestedLoopCount, CollapseLoopCountExpr, 3898 OrderedLoopCountExpr, VarsWithImplicitDSA, 3899 IterSpaces[Cnt], Captures)) 3900 return 0; 3901 // Move on to the next nested for loop, or to the loop body. 3902 // OpenMP [2.8.1, simd construct, Restrictions] 3903 // All loops associated with the construct must be perfectly nested; that 3904 // is, there must be no intervening code nor any OpenMP directive between 3905 // any two loops. 3906 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 3907 } 3908 3909 Built.clear(/* size */ NestedLoopCount); 3910 3911 if (SemaRef.CurContext->isDependentContext()) 3912 return NestedLoopCount; 3913 3914 // An example of what is generated for the following code: 3915 // 3916 // #pragma omp simd collapse(2) ordered(2) 3917 // for (i = 0; i < NI; ++i) 3918 // for (k = 0; k < NK; ++k) 3919 // for (j = J0; j < NJ; j+=2) { 3920 // <loop body> 3921 // } 3922 // 3923 // We generate the code below. 3924 // Note: the loop body may be outlined in CodeGen. 3925 // Note: some counters may be C++ classes, operator- is used to find number of 3926 // iterations and operator+= to calculate counter value. 3927 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 3928 // or i64 is currently supported). 3929 // 3930 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 3931 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 3932 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 3933 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 3934 // // similar updates for vars in clauses (e.g. 'linear') 3935 // <loop body (using local i and j)> 3936 // } 3937 // i = NI; // assign final values of counters 3938 // j = NJ; 3939 // 3940 3941 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 3942 // the iteration counts of the collapsed for loops. 3943 // Precondition tests if there is at least one iteration (all conditions are 3944 // true). 3945 auto PreCond = ExprResult(IterSpaces[0].PreCond); 3946 auto N0 = IterSpaces[0].NumIterations; 3947 ExprResult LastIteration32 = WidenIterationCount( 3948 32 /* Bits */, SemaRef 3949 .PerformImplicitConversion( 3950 N0->IgnoreImpCasts(), N0->getType(), 3951 Sema::AA_Converting, /*AllowExplicit=*/true) 3952 .get(), 3953 SemaRef); 3954 ExprResult LastIteration64 = WidenIterationCount( 3955 64 /* Bits */, SemaRef 3956 .PerformImplicitConversion( 3957 N0->IgnoreImpCasts(), N0->getType(), 3958 Sema::AA_Converting, /*AllowExplicit=*/true) 3959 .get(), 3960 SemaRef); 3961 3962 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 3963 return NestedLoopCount; 3964 3965 auto &C = SemaRef.Context; 3966 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 3967 3968 Scope *CurScope = DSA.getCurScope(); 3969 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 3970 if (PreCond.isUsable()) { 3971 PreCond = 3972 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 3973 PreCond.get(), IterSpaces[Cnt].PreCond); 3974 } 3975 auto N = IterSpaces[Cnt].NumIterations; 3976 SourceLocation Loc = N->getExprLoc(); 3977 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 3978 if (LastIteration32.isUsable()) 3979 LastIteration32 = SemaRef.BuildBinOp( 3980 CurScope, Loc, BO_Mul, LastIteration32.get(), 3981 SemaRef 3982 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 3983 Sema::AA_Converting, 3984 /*AllowExplicit=*/true) 3985 .get()); 3986 if (LastIteration64.isUsable()) 3987 LastIteration64 = SemaRef.BuildBinOp( 3988 CurScope, Loc, BO_Mul, LastIteration64.get(), 3989 SemaRef 3990 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 3991 Sema::AA_Converting, 3992 /*AllowExplicit=*/true) 3993 .get()); 3994 } 3995 3996 // Choose either the 32-bit or 64-bit version. 3997 ExprResult LastIteration = LastIteration64; 3998 if (LastIteration32.isUsable() && 3999 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 4000 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 4001 FitsInto( 4002 32 /* Bits */, 4003 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 4004 LastIteration64.get(), SemaRef))) 4005 LastIteration = LastIteration32; 4006 QualType VType = LastIteration.get()->getType(); 4007 QualType RealVType = VType; 4008 QualType StrideVType = VType; 4009 if (isOpenMPTaskLoopDirective(DKind)) { 4010 VType = 4011 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 4012 StrideVType = 4013 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 4014 } 4015 4016 if (!LastIteration.isUsable()) 4017 return 0; 4018 4019 // Save the number of iterations. 4020 ExprResult NumIterations = LastIteration; 4021 { 4022 LastIteration = SemaRef.BuildBinOp( 4023 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 4024 LastIteration.get(), 4025 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4026 if (!LastIteration.isUsable()) 4027 return 0; 4028 } 4029 4030 // Calculate the last iteration number beforehand instead of doing this on 4031 // each iteration. Do not do this if the number of iterations may be kfold-ed. 4032 llvm::APSInt Result; 4033 bool IsConstant = 4034 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 4035 ExprResult CalcLastIteration; 4036 if (!IsConstant) { 4037 ExprResult SaveRef = 4038 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 4039 LastIteration = SaveRef; 4040 4041 // Prepare SaveRef + 1. 4042 NumIterations = SemaRef.BuildBinOp( 4043 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 4044 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4045 if (!NumIterations.isUsable()) 4046 return 0; 4047 } 4048 4049 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 4050 4051 // Build variables passed into runtime, necessary for worksharing directives. 4052 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB; 4053 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4054 isOpenMPDistributeDirective(DKind)) { 4055 // Lower bound variable, initialized with zero. 4056 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 4057 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 4058 SemaRef.AddInitializerToDecl(LBDecl, 4059 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4060 /*DirectInit*/ false); 4061 4062 // Upper bound variable, initialized with last iteration number. 4063 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 4064 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 4065 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 4066 /*DirectInit*/ false); 4067 4068 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 4069 // This will be used to implement clause 'lastprivate'. 4070 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 4071 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 4072 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 4073 SemaRef.AddInitializerToDecl(ILDecl, 4074 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4075 /*DirectInit*/ false); 4076 4077 // Stride variable returned by runtime (we initialize it to 1 by default). 4078 VarDecl *STDecl = 4079 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 4080 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 4081 SemaRef.AddInitializerToDecl(STDecl, 4082 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 4083 /*DirectInit*/ false); 4084 4085 // Build expression: UB = min(UB, LastIteration) 4086 // It is necessary for CodeGen of directives with static scheduling. 4087 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 4088 UB.get(), LastIteration.get()); 4089 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4090 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 4091 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 4092 CondOp.get()); 4093 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 4094 4095 // If we have a combined directive that combines 'distribute', 'for' or 4096 // 'simd' we need to be able to access the bounds of the schedule of the 4097 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 4098 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 4099 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4100 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 4101 4102 // We expect to have at least 2 more parameters than the 'parallel' 4103 // directive does - the lower and upper bounds of the previous schedule. 4104 assert(CD->getNumParams() >= 4 && 4105 "Unexpected number of parameters in loop combined directive"); 4106 4107 // Set the proper type for the bounds given what we learned from the 4108 // enclosed loops. 4109 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 4110 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 4111 4112 // Previous lower and upper bounds are obtained from the region 4113 // parameters. 4114 PrevLB = 4115 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 4116 PrevUB = 4117 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 4118 } 4119 } 4120 4121 // Build the iteration variable and its initialization before loop. 4122 ExprResult IV; 4123 ExprResult Init; 4124 { 4125 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 4126 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 4127 Expr *RHS = 4128 (isOpenMPWorksharingDirective(DKind) || 4129 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4130 ? LB.get() 4131 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4132 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 4133 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 4134 } 4135 4136 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 4137 SourceLocation CondLoc; 4138 ExprResult Cond = 4139 (isOpenMPWorksharingDirective(DKind) || 4140 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4141 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 4142 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 4143 NumIterations.get()); 4144 4145 // Loop increment (IV = IV + 1) 4146 SourceLocation IncLoc; 4147 ExprResult Inc = 4148 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 4149 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 4150 if (!Inc.isUsable()) 4151 return 0; 4152 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 4153 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 4154 if (!Inc.isUsable()) 4155 return 0; 4156 4157 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 4158 // Used for directives with static scheduling. 4159 ExprResult NextLB, NextUB; 4160 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4161 isOpenMPDistributeDirective(DKind)) { 4162 // LB + ST 4163 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 4164 if (!NextLB.isUsable()) 4165 return 0; 4166 // LB = LB + ST 4167 NextLB = 4168 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 4169 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 4170 if (!NextLB.isUsable()) 4171 return 0; 4172 // UB + ST 4173 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 4174 if (!NextUB.isUsable()) 4175 return 0; 4176 // UB = UB + ST 4177 NextUB = 4178 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 4179 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 4180 if (!NextUB.isUsable()) 4181 return 0; 4182 } 4183 4184 // Build updates and final values of the loop counters. 4185 bool HasErrors = false; 4186 Built.Counters.resize(NestedLoopCount); 4187 Built.Inits.resize(NestedLoopCount); 4188 Built.Updates.resize(NestedLoopCount); 4189 Built.Finals.resize(NestedLoopCount); 4190 SmallVector<Expr *, 4> LoopMultipliers; 4191 { 4192 ExprResult Div; 4193 // Go from inner nested loop to outer. 4194 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4195 LoopIterationSpace &IS = IterSpaces[Cnt]; 4196 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 4197 // Build: Iter = (IV / Div) % IS.NumIters 4198 // where Div is product of previous iterations' IS.NumIters. 4199 ExprResult Iter; 4200 if (Div.isUsable()) { 4201 Iter = 4202 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 4203 } else { 4204 Iter = IV; 4205 assert((Cnt == (int)NestedLoopCount - 1) && 4206 "unusable div expected on first iteration only"); 4207 } 4208 4209 if (Cnt != 0 && Iter.isUsable()) 4210 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 4211 IS.NumIterations); 4212 if (!Iter.isUsable()) { 4213 HasErrors = true; 4214 break; 4215 } 4216 4217 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 4218 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 4219 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 4220 IS.CounterVar->getExprLoc(), 4221 /*RefersToCapture=*/true); 4222 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 4223 IS.CounterInit, Captures); 4224 if (!Init.isUsable()) { 4225 HasErrors = true; 4226 break; 4227 } 4228 ExprResult Update = BuildCounterUpdate( 4229 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 4230 IS.CounterStep, IS.Subtract, &Captures); 4231 if (!Update.isUsable()) { 4232 HasErrors = true; 4233 break; 4234 } 4235 4236 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 4237 ExprResult Final = BuildCounterUpdate( 4238 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 4239 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 4240 if (!Final.isUsable()) { 4241 HasErrors = true; 4242 break; 4243 } 4244 4245 // Build Div for the next iteration: Div <- Div * IS.NumIters 4246 if (Cnt != 0) { 4247 if (Div.isUnset()) 4248 Div = IS.NumIterations; 4249 else 4250 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 4251 IS.NumIterations); 4252 4253 // Add parentheses (for debugging purposes only). 4254 if (Div.isUsable()) 4255 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 4256 if (!Div.isUsable()) { 4257 HasErrors = true; 4258 break; 4259 } 4260 LoopMultipliers.push_back(Div.get()); 4261 } 4262 if (!Update.isUsable() || !Final.isUsable()) { 4263 HasErrors = true; 4264 break; 4265 } 4266 // Save results 4267 Built.Counters[Cnt] = IS.CounterVar; 4268 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 4269 Built.Inits[Cnt] = Init.get(); 4270 Built.Updates[Cnt] = Update.get(); 4271 Built.Finals[Cnt] = Final.get(); 4272 } 4273 } 4274 4275 if (HasErrors) 4276 return 0; 4277 4278 // Save results 4279 Built.IterationVarRef = IV.get(); 4280 Built.LastIteration = LastIteration.get(); 4281 Built.NumIterations = NumIterations.get(); 4282 Built.CalcLastIteration = 4283 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 4284 Built.PreCond = PreCond.get(); 4285 Built.PreInits = buildPreInits(C, Captures); 4286 Built.Cond = Cond.get(); 4287 Built.Init = Init.get(); 4288 Built.Inc = Inc.get(); 4289 Built.LB = LB.get(); 4290 Built.UB = UB.get(); 4291 Built.IL = IL.get(); 4292 Built.ST = ST.get(); 4293 Built.EUB = EUB.get(); 4294 Built.NLB = NextLB.get(); 4295 Built.NUB = NextUB.get(); 4296 Built.PrevLB = PrevLB.get(); 4297 Built.PrevUB = PrevUB.get(); 4298 4299 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 4300 // Fill data for doacross depend clauses. 4301 for (auto Pair : DSA.getDoacrossDependClauses()) { 4302 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 4303 Pair.first->setCounterValue(CounterVal); 4304 else { 4305 if (NestedLoopCount != Pair.second.size() || 4306 NestedLoopCount != LoopMultipliers.size() + 1) { 4307 // Erroneous case - clause has some problems. 4308 Pair.first->setCounterValue(CounterVal); 4309 continue; 4310 } 4311 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 4312 auto I = Pair.second.rbegin(); 4313 auto IS = IterSpaces.rbegin(); 4314 auto ILM = LoopMultipliers.rbegin(); 4315 Expr *UpCounterVal = CounterVal; 4316 Expr *Multiplier = nullptr; 4317 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4318 if (I->first) { 4319 assert(IS->CounterStep); 4320 Expr *NormalizedOffset = 4321 SemaRef 4322 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 4323 I->first, IS->CounterStep) 4324 .get(); 4325 if (Multiplier) { 4326 NormalizedOffset = 4327 SemaRef 4328 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 4329 NormalizedOffset, Multiplier) 4330 .get(); 4331 } 4332 assert(I->second == OO_Plus || I->second == OO_Minus); 4333 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 4334 UpCounterVal = SemaRef 4335 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 4336 UpCounterVal, NormalizedOffset) 4337 .get(); 4338 } 4339 Multiplier = *ILM; 4340 ++I; 4341 ++IS; 4342 ++ILM; 4343 } 4344 Pair.first->setCounterValue(UpCounterVal); 4345 } 4346 } 4347 4348 return NestedLoopCount; 4349 } 4350 4351 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 4352 auto CollapseClauses = 4353 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 4354 if (CollapseClauses.begin() != CollapseClauses.end()) 4355 return (*CollapseClauses.begin())->getNumForLoops(); 4356 return nullptr; 4357 } 4358 4359 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 4360 auto OrderedClauses = 4361 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 4362 if (OrderedClauses.begin() != OrderedClauses.end()) 4363 return (*OrderedClauses.begin())->getNumForLoops(); 4364 return nullptr; 4365 } 4366 4367 static bool checkSimdlenSafelenSpecified(Sema &S, 4368 const ArrayRef<OMPClause *> Clauses) { 4369 OMPSafelenClause *Safelen = nullptr; 4370 OMPSimdlenClause *Simdlen = nullptr; 4371 4372 for (auto *Clause : Clauses) { 4373 if (Clause->getClauseKind() == OMPC_safelen) 4374 Safelen = cast<OMPSafelenClause>(Clause); 4375 else if (Clause->getClauseKind() == OMPC_simdlen) 4376 Simdlen = cast<OMPSimdlenClause>(Clause); 4377 if (Safelen && Simdlen) 4378 break; 4379 } 4380 4381 if (Simdlen && Safelen) { 4382 llvm::APSInt SimdlenRes, SafelenRes; 4383 auto SimdlenLength = Simdlen->getSimdlen(); 4384 auto SafelenLength = Safelen->getSafelen(); 4385 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 4386 SimdlenLength->isInstantiationDependent() || 4387 SimdlenLength->containsUnexpandedParameterPack()) 4388 return false; 4389 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 4390 SafelenLength->isInstantiationDependent() || 4391 SafelenLength->containsUnexpandedParameterPack()) 4392 return false; 4393 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 4394 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 4395 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 4396 // If both simdlen and safelen clauses are specified, the value of the 4397 // simdlen parameter must be less than or equal to the value of the safelen 4398 // parameter. 4399 if (SimdlenRes > SafelenRes) { 4400 S.Diag(SimdlenLength->getExprLoc(), 4401 diag::err_omp_wrong_simdlen_safelen_values) 4402 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 4403 return true; 4404 } 4405 } 4406 return false; 4407 } 4408 4409 StmtResult Sema::ActOnOpenMPSimdDirective( 4410 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4411 SourceLocation EndLoc, 4412 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4413 if (!AStmt) 4414 return StmtError(); 4415 4416 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4417 OMPLoopDirective::HelperExprs B; 4418 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4419 // define the nested loops number. 4420 unsigned NestedLoopCount = CheckOpenMPLoop( 4421 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4422 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4423 if (NestedLoopCount == 0) 4424 return StmtError(); 4425 4426 assert((CurContext->isDependentContext() || B.builtAll()) && 4427 "omp simd loop exprs were not built"); 4428 4429 if (!CurContext->isDependentContext()) { 4430 // Finalize the clauses that need pre-built expressions for CodeGen. 4431 for (auto C : Clauses) { 4432 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4433 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4434 B.NumIterations, *this, CurScope, 4435 DSAStack)) 4436 return StmtError(); 4437 } 4438 } 4439 4440 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4441 return StmtError(); 4442 4443 getCurFunction()->setHasBranchProtectedScope(); 4444 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4445 Clauses, AStmt, B); 4446 } 4447 4448 StmtResult Sema::ActOnOpenMPForDirective( 4449 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4450 SourceLocation EndLoc, 4451 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4452 if (!AStmt) 4453 return StmtError(); 4454 4455 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4456 OMPLoopDirective::HelperExprs B; 4457 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4458 // define the nested loops number. 4459 unsigned NestedLoopCount = CheckOpenMPLoop( 4460 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4461 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4462 if (NestedLoopCount == 0) 4463 return StmtError(); 4464 4465 assert((CurContext->isDependentContext() || B.builtAll()) && 4466 "omp for loop exprs were not built"); 4467 4468 if (!CurContext->isDependentContext()) { 4469 // Finalize the clauses that need pre-built expressions for CodeGen. 4470 for (auto C : Clauses) { 4471 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4472 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4473 B.NumIterations, *this, CurScope, 4474 DSAStack)) 4475 return StmtError(); 4476 } 4477 } 4478 4479 getCurFunction()->setHasBranchProtectedScope(); 4480 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4481 Clauses, AStmt, B, DSAStack->isCancelRegion()); 4482 } 4483 4484 StmtResult Sema::ActOnOpenMPForSimdDirective( 4485 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4486 SourceLocation EndLoc, 4487 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4488 if (!AStmt) 4489 return StmtError(); 4490 4491 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4492 OMPLoopDirective::HelperExprs B; 4493 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4494 // define the nested loops number. 4495 unsigned NestedLoopCount = 4496 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 4497 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4498 VarsWithImplicitDSA, B); 4499 if (NestedLoopCount == 0) 4500 return StmtError(); 4501 4502 assert((CurContext->isDependentContext() || B.builtAll()) && 4503 "omp for simd loop exprs were not built"); 4504 4505 if (!CurContext->isDependentContext()) { 4506 // Finalize the clauses that need pre-built expressions for CodeGen. 4507 for (auto C : Clauses) { 4508 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4509 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4510 B.NumIterations, *this, CurScope, 4511 DSAStack)) 4512 return StmtError(); 4513 } 4514 } 4515 4516 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4517 return StmtError(); 4518 4519 getCurFunction()->setHasBranchProtectedScope(); 4520 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4521 Clauses, AStmt, B); 4522 } 4523 4524 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 4525 Stmt *AStmt, 4526 SourceLocation StartLoc, 4527 SourceLocation EndLoc) { 4528 if (!AStmt) 4529 return StmtError(); 4530 4531 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4532 auto BaseStmt = AStmt; 4533 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4534 BaseStmt = CS->getCapturedStmt(); 4535 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4536 auto S = C->children(); 4537 if (S.begin() == S.end()) 4538 return StmtError(); 4539 // All associated statements must be '#pragma omp section' except for 4540 // the first one. 4541 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4542 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4543 if (SectionStmt) 4544 Diag(SectionStmt->getLocStart(), 4545 diag::err_omp_sections_substmt_not_section); 4546 return StmtError(); 4547 } 4548 cast<OMPSectionDirective>(SectionStmt) 4549 ->setHasCancel(DSAStack->isCancelRegion()); 4550 } 4551 } else { 4552 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 4553 return StmtError(); 4554 } 4555 4556 getCurFunction()->setHasBranchProtectedScope(); 4557 4558 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4559 DSAStack->isCancelRegion()); 4560 } 4561 4562 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 4563 SourceLocation StartLoc, 4564 SourceLocation EndLoc) { 4565 if (!AStmt) 4566 return StmtError(); 4567 4568 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4569 4570 getCurFunction()->setHasBranchProtectedScope(); 4571 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 4572 4573 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 4574 DSAStack->isCancelRegion()); 4575 } 4576 4577 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 4578 Stmt *AStmt, 4579 SourceLocation StartLoc, 4580 SourceLocation EndLoc) { 4581 if (!AStmt) 4582 return StmtError(); 4583 4584 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4585 4586 getCurFunction()->setHasBranchProtectedScope(); 4587 4588 // OpenMP [2.7.3, single Construct, Restrictions] 4589 // The copyprivate clause must not be used with the nowait clause. 4590 OMPClause *Nowait = nullptr; 4591 OMPClause *Copyprivate = nullptr; 4592 for (auto *Clause : Clauses) { 4593 if (Clause->getClauseKind() == OMPC_nowait) 4594 Nowait = Clause; 4595 else if (Clause->getClauseKind() == OMPC_copyprivate) 4596 Copyprivate = Clause; 4597 if (Copyprivate && Nowait) { 4598 Diag(Copyprivate->getLocStart(), 4599 diag::err_omp_single_copyprivate_with_nowait); 4600 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 4601 return StmtError(); 4602 } 4603 } 4604 4605 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 4606 } 4607 4608 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 4609 SourceLocation StartLoc, 4610 SourceLocation EndLoc) { 4611 if (!AStmt) 4612 return StmtError(); 4613 4614 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4615 4616 getCurFunction()->setHasBranchProtectedScope(); 4617 4618 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 4619 } 4620 4621 StmtResult Sema::ActOnOpenMPCriticalDirective( 4622 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 4623 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 4624 if (!AStmt) 4625 return StmtError(); 4626 4627 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4628 4629 bool ErrorFound = false; 4630 llvm::APSInt Hint; 4631 SourceLocation HintLoc; 4632 bool DependentHint = false; 4633 for (auto *C : Clauses) { 4634 if (C->getClauseKind() == OMPC_hint) { 4635 if (!DirName.getName()) { 4636 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 4637 ErrorFound = true; 4638 } 4639 Expr *E = cast<OMPHintClause>(C)->getHint(); 4640 if (E->isTypeDependent() || E->isValueDependent() || 4641 E->isInstantiationDependent()) 4642 DependentHint = true; 4643 else { 4644 Hint = E->EvaluateKnownConstInt(Context); 4645 HintLoc = C->getLocStart(); 4646 } 4647 } 4648 } 4649 if (ErrorFound) 4650 return StmtError(); 4651 auto Pair = DSAStack->getCriticalWithHint(DirName); 4652 if (Pair.first && DirName.getName() && !DependentHint) { 4653 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 4654 Diag(StartLoc, diag::err_omp_critical_with_hint); 4655 if (HintLoc.isValid()) { 4656 Diag(HintLoc, diag::note_omp_critical_hint_here) 4657 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 4658 } else 4659 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 4660 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 4661 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 4662 << 1 4663 << C->getHint()->EvaluateKnownConstInt(Context).toString( 4664 /*Radix=*/10, /*Signed=*/false); 4665 } else 4666 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 4667 } 4668 } 4669 4670 getCurFunction()->setHasBranchProtectedScope(); 4671 4672 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 4673 Clauses, AStmt); 4674 if (!Pair.first && DirName.getName() && !DependentHint) 4675 DSAStack->addCriticalWithHint(Dir, Hint); 4676 return Dir; 4677 } 4678 4679 StmtResult Sema::ActOnOpenMPParallelForDirective( 4680 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4681 SourceLocation EndLoc, 4682 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4683 if (!AStmt) 4684 return StmtError(); 4685 4686 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4687 // 1.2.2 OpenMP Language Terminology 4688 // Structured block - An executable statement with a single entry at the 4689 // top and a single exit at the bottom. 4690 // The point of exit cannot be a branch out of the structured block. 4691 // longjmp() and throw() must not violate the entry/exit criteria. 4692 CS->getCapturedDecl()->setNothrow(); 4693 4694 OMPLoopDirective::HelperExprs B; 4695 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4696 // define the nested loops number. 4697 unsigned NestedLoopCount = 4698 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 4699 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4700 VarsWithImplicitDSA, B); 4701 if (NestedLoopCount == 0) 4702 return StmtError(); 4703 4704 assert((CurContext->isDependentContext() || B.builtAll()) && 4705 "omp parallel for loop exprs were not built"); 4706 4707 if (!CurContext->isDependentContext()) { 4708 // Finalize the clauses that need pre-built expressions for CodeGen. 4709 for (auto C : Clauses) { 4710 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4711 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4712 B.NumIterations, *this, CurScope, 4713 DSAStack)) 4714 return StmtError(); 4715 } 4716 } 4717 4718 getCurFunction()->setHasBranchProtectedScope(); 4719 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 4720 NestedLoopCount, Clauses, AStmt, B, 4721 DSAStack->isCancelRegion()); 4722 } 4723 4724 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 4725 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4726 SourceLocation EndLoc, 4727 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4728 if (!AStmt) 4729 return StmtError(); 4730 4731 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4732 // 1.2.2 OpenMP Language Terminology 4733 // Structured block - An executable statement with a single entry at the 4734 // top and a single exit at the bottom. 4735 // The point of exit cannot be a branch out of the structured block. 4736 // longjmp() and throw() must not violate the entry/exit criteria. 4737 CS->getCapturedDecl()->setNothrow(); 4738 4739 OMPLoopDirective::HelperExprs B; 4740 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4741 // define the nested loops number. 4742 unsigned NestedLoopCount = 4743 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 4744 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4745 VarsWithImplicitDSA, B); 4746 if (NestedLoopCount == 0) 4747 return StmtError(); 4748 4749 if (!CurContext->isDependentContext()) { 4750 // Finalize the clauses that need pre-built expressions for CodeGen. 4751 for (auto C : Clauses) { 4752 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4753 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4754 B.NumIterations, *this, CurScope, 4755 DSAStack)) 4756 return StmtError(); 4757 } 4758 } 4759 4760 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4761 return StmtError(); 4762 4763 getCurFunction()->setHasBranchProtectedScope(); 4764 return OMPParallelForSimdDirective::Create( 4765 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 4766 } 4767 4768 StmtResult 4769 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 4770 Stmt *AStmt, SourceLocation StartLoc, 4771 SourceLocation EndLoc) { 4772 if (!AStmt) 4773 return StmtError(); 4774 4775 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4776 auto BaseStmt = AStmt; 4777 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4778 BaseStmt = CS->getCapturedStmt(); 4779 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4780 auto S = C->children(); 4781 if (S.begin() == S.end()) 4782 return StmtError(); 4783 // All associated statements must be '#pragma omp section' except for 4784 // the first one. 4785 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4786 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4787 if (SectionStmt) 4788 Diag(SectionStmt->getLocStart(), 4789 diag::err_omp_parallel_sections_substmt_not_section); 4790 return StmtError(); 4791 } 4792 cast<OMPSectionDirective>(SectionStmt) 4793 ->setHasCancel(DSAStack->isCancelRegion()); 4794 } 4795 } else { 4796 Diag(AStmt->getLocStart(), 4797 diag::err_omp_parallel_sections_not_compound_stmt); 4798 return StmtError(); 4799 } 4800 4801 getCurFunction()->setHasBranchProtectedScope(); 4802 4803 return OMPParallelSectionsDirective::Create( 4804 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 4805 } 4806 4807 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 4808 Stmt *AStmt, SourceLocation StartLoc, 4809 SourceLocation EndLoc) { 4810 if (!AStmt) 4811 return StmtError(); 4812 4813 auto *CS = cast<CapturedStmt>(AStmt); 4814 // 1.2.2 OpenMP Language Terminology 4815 // Structured block - An executable statement with a single entry at the 4816 // top and a single exit at the bottom. 4817 // The point of exit cannot be a branch out of the structured block. 4818 // longjmp() and throw() must not violate the entry/exit criteria. 4819 CS->getCapturedDecl()->setNothrow(); 4820 4821 getCurFunction()->setHasBranchProtectedScope(); 4822 4823 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4824 DSAStack->isCancelRegion()); 4825 } 4826 4827 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 4828 SourceLocation EndLoc) { 4829 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 4830 } 4831 4832 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 4833 SourceLocation EndLoc) { 4834 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 4835 } 4836 4837 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 4838 SourceLocation EndLoc) { 4839 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 4840 } 4841 4842 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt, 4843 SourceLocation StartLoc, 4844 SourceLocation EndLoc) { 4845 if (!AStmt) 4846 return StmtError(); 4847 4848 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4849 4850 getCurFunction()->setHasBranchProtectedScope(); 4851 4852 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt); 4853 } 4854 4855 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 4856 SourceLocation StartLoc, 4857 SourceLocation EndLoc) { 4858 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 4859 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 4860 } 4861 4862 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 4863 Stmt *AStmt, 4864 SourceLocation StartLoc, 4865 SourceLocation EndLoc) { 4866 OMPClause *DependFound = nullptr; 4867 OMPClause *DependSourceClause = nullptr; 4868 OMPClause *DependSinkClause = nullptr; 4869 bool ErrorFound = false; 4870 OMPThreadsClause *TC = nullptr; 4871 OMPSIMDClause *SC = nullptr; 4872 for (auto *C : Clauses) { 4873 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 4874 DependFound = C; 4875 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 4876 if (DependSourceClause) { 4877 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 4878 << getOpenMPDirectiveName(OMPD_ordered) 4879 << getOpenMPClauseName(OMPC_depend) << 2; 4880 ErrorFound = true; 4881 } else 4882 DependSourceClause = C; 4883 if (DependSinkClause) { 4884 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 4885 << 0; 4886 ErrorFound = true; 4887 } 4888 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 4889 if (DependSourceClause) { 4890 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 4891 << 1; 4892 ErrorFound = true; 4893 } 4894 DependSinkClause = C; 4895 } 4896 } else if (C->getClauseKind() == OMPC_threads) 4897 TC = cast<OMPThreadsClause>(C); 4898 else if (C->getClauseKind() == OMPC_simd) 4899 SC = cast<OMPSIMDClause>(C); 4900 } 4901 if (!ErrorFound && !SC && 4902 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 4903 // OpenMP [2.8.1,simd Construct, Restrictions] 4904 // An ordered construct with the simd clause is the only OpenMP construct 4905 // that can appear in the simd region. 4906 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 4907 ErrorFound = true; 4908 } else if (DependFound && (TC || SC)) { 4909 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 4910 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 4911 ErrorFound = true; 4912 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 4913 Diag(DependFound->getLocStart(), 4914 diag::err_omp_ordered_directive_without_param); 4915 ErrorFound = true; 4916 } else if (TC || Clauses.empty()) { 4917 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 4918 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 4919 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 4920 << (TC != nullptr); 4921 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 4922 ErrorFound = true; 4923 } 4924 } 4925 if ((!AStmt && !DependFound) || ErrorFound) 4926 return StmtError(); 4927 4928 if (AStmt) { 4929 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4930 4931 getCurFunction()->setHasBranchProtectedScope(); 4932 } 4933 4934 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 4935 } 4936 4937 namespace { 4938 /// \brief Helper class for checking expression in 'omp atomic [update]' 4939 /// construct. 4940 class OpenMPAtomicUpdateChecker { 4941 /// \brief Error results for atomic update expressions. 4942 enum ExprAnalysisErrorCode { 4943 /// \brief A statement is not an expression statement. 4944 NotAnExpression, 4945 /// \brief Expression is not builtin binary or unary operation. 4946 NotABinaryOrUnaryExpression, 4947 /// \brief Unary operation is not post-/pre- increment/decrement operation. 4948 NotAnUnaryIncDecExpression, 4949 /// \brief An expression is not of scalar type. 4950 NotAScalarType, 4951 /// \brief A binary operation is not an assignment operation. 4952 NotAnAssignmentOp, 4953 /// \brief RHS part of the binary operation is not a binary expression. 4954 NotABinaryExpression, 4955 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 4956 /// expression. 4957 NotABinaryOperator, 4958 /// \brief RHS binary operation does not have reference to the updated LHS 4959 /// part. 4960 NotAnUpdateExpression, 4961 /// \brief No errors is found. 4962 NoError 4963 }; 4964 /// \brief Reference to Sema. 4965 Sema &SemaRef; 4966 /// \brief A location for note diagnostics (when error is found). 4967 SourceLocation NoteLoc; 4968 /// \brief 'x' lvalue part of the source atomic expression. 4969 Expr *X; 4970 /// \brief 'expr' rvalue part of the source atomic expression. 4971 Expr *E; 4972 /// \brief Helper expression of the form 4973 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 4974 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 4975 Expr *UpdateExpr; 4976 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 4977 /// important for non-associative operations. 4978 bool IsXLHSInRHSPart; 4979 BinaryOperatorKind Op; 4980 SourceLocation OpLoc; 4981 /// \brief true if the source expression is a postfix unary operation, false 4982 /// if it is a prefix unary operation. 4983 bool IsPostfixUpdate; 4984 4985 public: 4986 OpenMPAtomicUpdateChecker(Sema &SemaRef) 4987 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 4988 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 4989 /// \brief Check specified statement that it is suitable for 'atomic update' 4990 /// constructs and extract 'x', 'expr' and Operation from the original 4991 /// expression. If DiagId and NoteId == 0, then only check is performed 4992 /// without error notification. 4993 /// \param DiagId Diagnostic which should be emitted if error is found. 4994 /// \param NoteId Diagnostic note for the main error message. 4995 /// \return true if statement is not an update expression, false otherwise. 4996 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 4997 /// \brief Return the 'x' lvalue part of the source atomic expression. 4998 Expr *getX() const { return X; } 4999 /// \brief Return the 'expr' rvalue part of the source atomic expression. 5000 Expr *getExpr() const { return E; } 5001 /// \brief Return the update expression used in calculation of the updated 5002 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5003 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5004 Expr *getUpdateExpr() const { return UpdateExpr; } 5005 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 5006 /// false otherwise. 5007 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 5008 5009 /// \brief true if the source expression is a postfix unary operation, false 5010 /// if it is a prefix unary operation. 5011 bool isPostfixUpdate() const { return IsPostfixUpdate; } 5012 5013 private: 5014 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 5015 unsigned NoteId = 0); 5016 }; 5017 } // namespace 5018 5019 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 5020 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 5021 ExprAnalysisErrorCode ErrorFound = NoError; 5022 SourceLocation ErrorLoc, NoteLoc; 5023 SourceRange ErrorRange, NoteRange; 5024 // Allowed constructs are: 5025 // x = x binop expr; 5026 // x = expr binop x; 5027 if (AtomicBinOp->getOpcode() == BO_Assign) { 5028 X = AtomicBinOp->getLHS(); 5029 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 5030 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 5031 if (AtomicInnerBinOp->isMultiplicativeOp() || 5032 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 5033 AtomicInnerBinOp->isBitwiseOp()) { 5034 Op = AtomicInnerBinOp->getOpcode(); 5035 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 5036 auto *LHS = AtomicInnerBinOp->getLHS(); 5037 auto *RHS = AtomicInnerBinOp->getRHS(); 5038 llvm::FoldingSetNodeID XId, LHSId, RHSId; 5039 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 5040 /*Canonical=*/true); 5041 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 5042 /*Canonical=*/true); 5043 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 5044 /*Canonical=*/true); 5045 if (XId == LHSId) { 5046 E = RHS; 5047 IsXLHSInRHSPart = true; 5048 } else if (XId == RHSId) { 5049 E = LHS; 5050 IsXLHSInRHSPart = false; 5051 } else { 5052 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5053 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5054 NoteLoc = X->getExprLoc(); 5055 NoteRange = X->getSourceRange(); 5056 ErrorFound = NotAnUpdateExpression; 5057 } 5058 } else { 5059 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5060 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5061 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 5062 NoteRange = SourceRange(NoteLoc, NoteLoc); 5063 ErrorFound = NotABinaryOperator; 5064 } 5065 } else { 5066 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 5067 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 5068 ErrorFound = NotABinaryExpression; 5069 } 5070 } else { 5071 ErrorLoc = AtomicBinOp->getExprLoc(); 5072 ErrorRange = AtomicBinOp->getSourceRange(); 5073 NoteLoc = AtomicBinOp->getOperatorLoc(); 5074 NoteRange = SourceRange(NoteLoc, NoteLoc); 5075 ErrorFound = NotAnAssignmentOp; 5076 } 5077 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5078 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5079 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5080 return true; 5081 } else if (SemaRef.CurContext->isDependentContext()) 5082 E = X = UpdateExpr = nullptr; 5083 return ErrorFound != NoError; 5084 } 5085 5086 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 5087 unsigned NoteId) { 5088 ExprAnalysisErrorCode ErrorFound = NoError; 5089 SourceLocation ErrorLoc, NoteLoc; 5090 SourceRange ErrorRange, NoteRange; 5091 // Allowed constructs are: 5092 // x++; 5093 // x--; 5094 // ++x; 5095 // --x; 5096 // x binop= expr; 5097 // x = x binop expr; 5098 // x = expr binop x; 5099 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 5100 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 5101 if (AtomicBody->getType()->isScalarType() || 5102 AtomicBody->isInstantiationDependent()) { 5103 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 5104 AtomicBody->IgnoreParenImpCasts())) { 5105 // Check for Compound Assignment Operation 5106 Op = BinaryOperator::getOpForCompoundAssignment( 5107 AtomicCompAssignOp->getOpcode()); 5108 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 5109 E = AtomicCompAssignOp->getRHS(); 5110 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 5111 IsXLHSInRHSPart = true; 5112 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 5113 AtomicBody->IgnoreParenImpCasts())) { 5114 // Check for Binary Operation 5115 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 5116 return true; 5117 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 5118 AtomicBody->IgnoreParenImpCasts())) { 5119 // Check for Unary Operation 5120 if (AtomicUnaryOp->isIncrementDecrementOp()) { 5121 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 5122 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 5123 OpLoc = AtomicUnaryOp->getOperatorLoc(); 5124 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 5125 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 5126 IsXLHSInRHSPart = true; 5127 } else { 5128 ErrorFound = NotAnUnaryIncDecExpression; 5129 ErrorLoc = AtomicUnaryOp->getExprLoc(); 5130 ErrorRange = AtomicUnaryOp->getSourceRange(); 5131 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 5132 NoteRange = SourceRange(NoteLoc, NoteLoc); 5133 } 5134 } else if (!AtomicBody->isInstantiationDependent()) { 5135 ErrorFound = NotABinaryOrUnaryExpression; 5136 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 5137 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 5138 } 5139 } else { 5140 ErrorFound = NotAScalarType; 5141 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 5142 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5143 } 5144 } else { 5145 ErrorFound = NotAnExpression; 5146 NoteLoc = ErrorLoc = S->getLocStart(); 5147 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5148 } 5149 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5150 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5151 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5152 return true; 5153 } else if (SemaRef.CurContext->isDependentContext()) 5154 E = X = UpdateExpr = nullptr; 5155 if (ErrorFound == NoError && E && X) { 5156 // Build an update expression of form 'OpaqueValueExpr(x) binop 5157 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 5158 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 5159 auto *OVEX = new (SemaRef.getASTContext()) 5160 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 5161 auto *OVEExpr = new (SemaRef.getASTContext()) 5162 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 5163 auto Update = 5164 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 5165 IsXLHSInRHSPart ? OVEExpr : OVEX); 5166 if (Update.isInvalid()) 5167 return true; 5168 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 5169 Sema::AA_Casting); 5170 if (Update.isInvalid()) 5171 return true; 5172 UpdateExpr = Update.get(); 5173 } 5174 return ErrorFound != NoError; 5175 } 5176 5177 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 5178 Stmt *AStmt, 5179 SourceLocation StartLoc, 5180 SourceLocation EndLoc) { 5181 if (!AStmt) 5182 return StmtError(); 5183 5184 auto *CS = cast<CapturedStmt>(AStmt); 5185 // 1.2.2 OpenMP Language Terminology 5186 // Structured block - An executable statement with a single entry at the 5187 // top and a single exit at the bottom. 5188 // The point of exit cannot be a branch out of the structured block. 5189 // longjmp() and throw() must not violate the entry/exit criteria. 5190 OpenMPClauseKind AtomicKind = OMPC_unknown; 5191 SourceLocation AtomicKindLoc; 5192 for (auto *C : Clauses) { 5193 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 5194 C->getClauseKind() == OMPC_update || 5195 C->getClauseKind() == OMPC_capture) { 5196 if (AtomicKind != OMPC_unknown) { 5197 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 5198 << SourceRange(C->getLocStart(), C->getLocEnd()); 5199 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 5200 << getOpenMPClauseName(AtomicKind); 5201 } else { 5202 AtomicKind = C->getClauseKind(); 5203 AtomicKindLoc = C->getLocStart(); 5204 } 5205 } 5206 } 5207 5208 auto Body = CS->getCapturedStmt(); 5209 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 5210 Body = EWC->getSubExpr(); 5211 5212 Expr *X = nullptr; 5213 Expr *V = nullptr; 5214 Expr *E = nullptr; 5215 Expr *UE = nullptr; 5216 bool IsXLHSInRHSPart = false; 5217 bool IsPostfixUpdate = false; 5218 // OpenMP [2.12.6, atomic Construct] 5219 // In the next expressions: 5220 // * x and v (as applicable) are both l-value expressions with scalar type. 5221 // * During the execution of an atomic region, multiple syntactic 5222 // occurrences of x must designate the same storage location. 5223 // * Neither of v and expr (as applicable) may access the storage location 5224 // designated by x. 5225 // * Neither of x and expr (as applicable) may access the storage location 5226 // designated by v. 5227 // * expr is an expression with scalar type. 5228 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 5229 // * binop, binop=, ++, and -- are not overloaded operators. 5230 // * The expression x binop expr must be numerically equivalent to x binop 5231 // (expr). This requirement is satisfied if the operators in expr have 5232 // precedence greater than binop, or by using parentheses around expr or 5233 // subexpressions of expr. 5234 // * The expression expr binop x must be numerically equivalent to (expr) 5235 // binop x. This requirement is satisfied if the operators in expr have 5236 // precedence equal to or greater than binop, or by using parentheses around 5237 // expr or subexpressions of expr. 5238 // * For forms that allow multiple occurrences of x, the number of times 5239 // that x is evaluated is unspecified. 5240 if (AtomicKind == OMPC_read) { 5241 enum { 5242 NotAnExpression, 5243 NotAnAssignmentOp, 5244 NotAScalarType, 5245 NotAnLValue, 5246 NoError 5247 } ErrorFound = NoError; 5248 SourceLocation ErrorLoc, NoteLoc; 5249 SourceRange ErrorRange, NoteRange; 5250 // If clause is read: 5251 // v = x; 5252 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5253 auto *AtomicBinOp = 5254 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5255 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5256 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5257 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 5258 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5259 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 5260 if (!X->isLValue() || !V->isLValue()) { 5261 auto NotLValueExpr = X->isLValue() ? V : X; 5262 ErrorFound = NotAnLValue; 5263 ErrorLoc = AtomicBinOp->getExprLoc(); 5264 ErrorRange = AtomicBinOp->getSourceRange(); 5265 NoteLoc = NotLValueExpr->getExprLoc(); 5266 NoteRange = NotLValueExpr->getSourceRange(); 5267 } 5268 } else if (!X->isInstantiationDependent() || 5269 !V->isInstantiationDependent()) { 5270 auto NotScalarExpr = 5271 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5272 ? V 5273 : X; 5274 ErrorFound = NotAScalarType; 5275 ErrorLoc = AtomicBinOp->getExprLoc(); 5276 ErrorRange = AtomicBinOp->getSourceRange(); 5277 NoteLoc = NotScalarExpr->getExprLoc(); 5278 NoteRange = NotScalarExpr->getSourceRange(); 5279 } 5280 } else if (!AtomicBody->isInstantiationDependent()) { 5281 ErrorFound = NotAnAssignmentOp; 5282 ErrorLoc = AtomicBody->getExprLoc(); 5283 ErrorRange = AtomicBody->getSourceRange(); 5284 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5285 : AtomicBody->getExprLoc(); 5286 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5287 : AtomicBody->getSourceRange(); 5288 } 5289 } else { 5290 ErrorFound = NotAnExpression; 5291 NoteLoc = ErrorLoc = Body->getLocStart(); 5292 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5293 } 5294 if (ErrorFound != NoError) { 5295 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 5296 << ErrorRange; 5297 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5298 << NoteRange; 5299 return StmtError(); 5300 } else if (CurContext->isDependentContext()) 5301 V = X = nullptr; 5302 } else if (AtomicKind == OMPC_write) { 5303 enum { 5304 NotAnExpression, 5305 NotAnAssignmentOp, 5306 NotAScalarType, 5307 NotAnLValue, 5308 NoError 5309 } ErrorFound = NoError; 5310 SourceLocation ErrorLoc, NoteLoc; 5311 SourceRange ErrorRange, NoteRange; 5312 // If clause is write: 5313 // x = expr; 5314 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5315 auto *AtomicBinOp = 5316 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5317 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5318 X = AtomicBinOp->getLHS(); 5319 E = AtomicBinOp->getRHS(); 5320 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5321 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 5322 if (!X->isLValue()) { 5323 ErrorFound = NotAnLValue; 5324 ErrorLoc = AtomicBinOp->getExprLoc(); 5325 ErrorRange = AtomicBinOp->getSourceRange(); 5326 NoteLoc = X->getExprLoc(); 5327 NoteRange = X->getSourceRange(); 5328 } 5329 } else if (!X->isInstantiationDependent() || 5330 !E->isInstantiationDependent()) { 5331 auto NotScalarExpr = 5332 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5333 ? E 5334 : X; 5335 ErrorFound = NotAScalarType; 5336 ErrorLoc = AtomicBinOp->getExprLoc(); 5337 ErrorRange = AtomicBinOp->getSourceRange(); 5338 NoteLoc = NotScalarExpr->getExprLoc(); 5339 NoteRange = NotScalarExpr->getSourceRange(); 5340 } 5341 } else if (!AtomicBody->isInstantiationDependent()) { 5342 ErrorFound = NotAnAssignmentOp; 5343 ErrorLoc = AtomicBody->getExprLoc(); 5344 ErrorRange = AtomicBody->getSourceRange(); 5345 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5346 : AtomicBody->getExprLoc(); 5347 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5348 : AtomicBody->getSourceRange(); 5349 } 5350 } else { 5351 ErrorFound = NotAnExpression; 5352 NoteLoc = ErrorLoc = Body->getLocStart(); 5353 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5354 } 5355 if (ErrorFound != NoError) { 5356 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 5357 << ErrorRange; 5358 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5359 << NoteRange; 5360 return StmtError(); 5361 } else if (CurContext->isDependentContext()) 5362 E = X = nullptr; 5363 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 5364 // If clause is update: 5365 // x++; 5366 // x--; 5367 // ++x; 5368 // --x; 5369 // x binop= expr; 5370 // x = x binop expr; 5371 // x = expr binop x; 5372 OpenMPAtomicUpdateChecker Checker(*this); 5373 if (Checker.checkStatement( 5374 Body, (AtomicKind == OMPC_update) 5375 ? diag::err_omp_atomic_update_not_expression_statement 5376 : diag::err_omp_atomic_not_expression_statement, 5377 diag::note_omp_atomic_update)) 5378 return StmtError(); 5379 if (!CurContext->isDependentContext()) { 5380 E = Checker.getExpr(); 5381 X = Checker.getX(); 5382 UE = Checker.getUpdateExpr(); 5383 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5384 } 5385 } else if (AtomicKind == OMPC_capture) { 5386 enum { 5387 NotAnAssignmentOp, 5388 NotACompoundStatement, 5389 NotTwoSubstatements, 5390 NotASpecificExpression, 5391 NoError 5392 } ErrorFound = NoError; 5393 SourceLocation ErrorLoc, NoteLoc; 5394 SourceRange ErrorRange, NoteRange; 5395 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5396 // If clause is a capture: 5397 // v = x++; 5398 // v = x--; 5399 // v = ++x; 5400 // v = --x; 5401 // v = x binop= expr; 5402 // v = x = x binop expr; 5403 // v = x = expr binop x; 5404 auto *AtomicBinOp = 5405 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5406 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5407 V = AtomicBinOp->getLHS(); 5408 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5409 OpenMPAtomicUpdateChecker Checker(*this); 5410 if (Checker.checkStatement( 5411 Body, diag::err_omp_atomic_capture_not_expression_statement, 5412 diag::note_omp_atomic_update)) 5413 return StmtError(); 5414 E = Checker.getExpr(); 5415 X = Checker.getX(); 5416 UE = Checker.getUpdateExpr(); 5417 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5418 IsPostfixUpdate = Checker.isPostfixUpdate(); 5419 } else if (!AtomicBody->isInstantiationDependent()) { 5420 ErrorLoc = AtomicBody->getExprLoc(); 5421 ErrorRange = AtomicBody->getSourceRange(); 5422 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5423 : AtomicBody->getExprLoc(); 5424 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5425 : AtomicBody->getSourceRange(); 5426 ErrorFound = NotAnAssignmentOp; 5427 } 5428 if (ErrorFound != NoError) { 5429 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 5430 << ErrorRange; 5431 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5432 return StmtError(); 5433 } else if (CurContext->isDependentContext()) { 5434 UE = V = E = X = nullptr; 5435 } 5436 } else { 5437 // If clause is a capture: 5438 // { v = x; x = expr; } 5439 // { v = x; x++; } 5440 // { v = x; x--; } 5441 // { v = x; ++x; } 5442 // { v = x; --x; } 5443 // { v = x; x binop= expr; } 5444 // { v = x; x = x binop expr; } 5445 // { v = x; x = expr binop x; } 5446 // { x++; v = x; } 5447 // { x--; v = x; } 5448 // { ++x; v = x; } 5449 // { --x; v = x; } 5450 // { x binop= expr; v = x; } 5451 // { x = x binop expr; v = x; } 5452 // { x = expr binop x; v = x; } 5453 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 5454 // Check that this is { expr1; expr2; } 5455 if (CS->size() == 2) { 5456 auto *First = CS->body_front(); 5457 auto *Second = CS->body_back(); 5458 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 5459 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 5460 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 5461 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 5462 // Need to find what subexpression is 'v' and what is 'x'. 5463 OpenMPAtomicUpdateChecker Checker(*this); 5464 bool IsUpdateExprFound = !Checker.checkStatement(Second); 5465 BinaryOperator *BinOp = nullptr; 5466 if (IsUpdateExprFound) { 5467 BinOp = dyn_cast<BinaryOperator>(First); 5468 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5469 } 5470 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5471 // { v = x; x++; } 5472 // { v = x; x--; } 5473 // { v = x; ++x; } 5474 // { v = x; --x; } 5475 // { v = x; x binop= expr; } 5476 // { v = x; x = x binop expr; } 5477 // { v = x; x = expr binop x; } 5478 // Check that the first expression has form v = x. 5479 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5480 llvm::FoldingSetNodeID XId, PossibleXId; 5481 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5482 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5483 IsUpdateExprFound = XId == PossibleXId; 5484 if (IsUpdateExprFound) { 5485 V = BinOp->getLHS(); 5486 X = Checker.getX(); 5487 E = Checker.getExpr(); 5488 UE = Checker.getUpdateExpr(); 5489 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5490 IsPostfixUpdate = true; 5491 } 5492 } 5493 if (!IsUpdateExprFound) { 5494 IsUpdateExprFound = !Checker.checkStatement(First); 5495 BinOp = nullptr; 5496 if (IsUpdateExprFound) { 5497 BinOp = dyn_cast<BinaryOperator>(Second); 5498 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5499 } 5500 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5501 // { x++; v = x; } 5502 // { x--; v = x; } 5503 // { ++x; v = x; } 5504 // { --x; v = x; } 5505 // { x binop= expr; v = x; } 5506 // { x = x binop expr; v = x; } 5507 // { x = expr binop x; v = x; } 5508 // Check that the second expression has form v = x. 5509 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5510 llvm::FoldingSetNodeID XId, PossibleXId; 5511 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5512 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5513 IsUpdateExprFound = XId == PossibleXId; 5514 if (IsUpdateExprFound) { 5515 V = BinOp->getLHS(); 5516 X = Checker.getX(); 5517 E = Checker.getExpr(); 5518 UE = Checker.getUpdateExpr(); 5519 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5520 IsPostfixUpdate = false; 5521 } 5522 } 5523 } 5524 if (!IsUpdateExprFound) { 5525 // { v = x; x = expr; } 5526 auto *FirstExpr = dyn_cast<Expr>(First); 5527 auto *SecondExpr = dyn_cast<Expr>(Second); 5528 if (!FirstExpr || !SecondExpr || 5529 !(FirstExpr->isInstantiationDependent() || 5530 SecondExpr->isInstantiationDependent())) { 5531 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 5532 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 5533 ErrorFound = NotAnAssignmentOp; 5534 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 5535 : First->getLocStart(); 5536 NoteRange = ErrorRange = FirstBinOp 5537 ? FirstBinOp->getSourceRange() 5538 : SourceRange(ErrorLoc, ErrorLoc); 5539 } else { 5540 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 5541 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 5542 ErrorFound = NotAnAssignmentOp; 5543 NoteLoc = ErrorLoc = SecondBinOp 5544 ? SecondBinOp->getOperatorLoc() 5545 : Second->getLocStart(); 5546 NoteRange = ErrorRange = 5547 SecondBinOp ? SecondBinOp->getSourceRange() 5548 : SourceRange(ErrorLoc, ErrorLoc); 5549 } else { 5550 auto *PossibleXRHSInFirst = 5551 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 5552 auto *PossibleXLHSInSecond = 5553 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 5554 llvm::FoldingSetNodeID X1Id, X2Id; 5555 PossibleXRHSInFirst->Profile(X1Id, Context, 5556 /*Canonical=*/true); 5557 PossibleXLHSInSecond->Profile(X2Id, Context, 5558 /*Canonical=*/true); 5559 IsUpdateExprFound = X1Id == X2Id; 5560 if (IsUpdateExprFound) { 5561 V = FirstBinOp->getLHS(); 5562 X = SecondBinOp->getLHS(); 5563 E = SecondBinOp->getRHS(); 5564 UE = nullptr; 5565 IsXLHSInRHSPart = false; 5566 IsPostfixUpdate = true; 5567 } else { 5568 ErrorFound = NotASpecificExpression; 5569 ErrorLoc = FirstBinOp->getExprLoc(); 5570 ErrorRange = FirstBinOp->getSourceRange(); 5571 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 5572 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 5573 } 5574 } 5575 } 5576 } 5577 } 5578 } else { 5579 NoteLoc = ErrorLoc = Body->getLocStart(); 5580 NoteRange = ErrorRange = 5581 SourceRange(Body->getLocStart(), Body->getLocStart()); 5582 ErrorFound = NotTwoSubstatements; 5583 } 5584 } else { 5585 NoteLoc = ErrorLoc = Body->getLocStart(); 5586 NoteRange = ErrorRange = 5587 SourceRange(Body->getLocStart(), Body->getLocStart()); 5588 ErrorFound = NotACompoundStatement; 5589 } 5590 if (ErrorFound != NoError) { 5591 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 5592 << ErrorRange; 5593 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5594 return StmtError(); 5595 } else if (CurContext->isDependentContext()) { 5596 UE = V = E = X = nullptr; 5597 } 5598 } 5599 } 5600 5601 getCurFunction()->setHasBranchProtectedScope(); 5602 5603 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5604 X, V, E, UE, IsXLHSInRHSPart, 5605 IsPostfixUpdate); 5606 } 5607 5608 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 5609 Stmt *AStmt, 5610 SourceLocation StartLoc, 5611 SourceLocation EndLoc) { 5612 if (!AStmt) 5613 return StmtError(); 5614 5615 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5616 // 1.2.2 OpenMP Language Terminology 5617 // Structured block - An executable statement with a single entry at the 5618 // top and a single exit at the bottom. 5619 // The point of exit cannot be a branch out of the structured block. 5620 // longjmp() and throw() must not violate the entry/exit criteria. 5621 CS->getCapturedDecl()->setNothrow(); 5622 5623 // OpenMP [2.16, Nesting of Regions] 5624 // If specified, a teams construct must be contained within a target 5625 // construct. That target construct must contain no statements or directives 5626 // outside of the teams construct. 5627 if (DSAStack->hasInnerTeamsRegion()) { 5628 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 5629 bool OMPTeamsFound = true; 5630 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 5631 auto I = CS->body_begin(); 5632 while (I != CS->body_end()) { 5633 auto *OED = dyn_cast<OMPExecutableDirective>(*I); 5634 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 5635 OMPTeamsFound = false; 5636 break; 5637 } 5638 ++I; 5639 } 5640 assert(I != CS->body_end() && "Not found statement"); 5641 S = *I; 5642 } else { 5643 auto *OED = dyn_cast<OMPExecutableDirective>(S); 5644 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 5645 } 5646 if (!OMPTeamsFound) { 5647 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 5648 Diag(DSAStack->getInnerTeamsRegionLoc(), 5649 diag::note_omp_nested_teams_construct_here); 5650 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 5651 << isa<OMPExecutableDirective>(S); 5652 return StmtError(); 5653 } 5654 } 5655 5656 getCurFunction()->setHasBranchProtectedScope(); 5657 5658 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5659 } 5660 5661 StmtResult 5662 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 5663 Stmt *AStmt, SourceLocation StartLoc, 5664 SourceLocation EndLoc) { 5665 if (!AStmt) 5666 return StmtError(); 5667 5668 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5669 // 1.2.2 OpenMP Language Terminology 5670 // Structured block - An executable statement with a single entry at the 5671 // top and a single exit at the bottom. 5672 // The point of exit cannot be a branch out of the structured block. 5673 // longjmp() and throw() must not violate the entry/exit criteria. 5674 CS->getCapturedDecl()->setNothrow(); 5675 5676 getCurFunction()->setHasBranchProtectedScope(); 5677 5678 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 5679 AStmt); 5680 } 5681 5682 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 5683 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5684 SourceLocation EndLoc, 5685 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5686 if (!AStmt) 5687 return StmtError(); 5688 5689 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5690 // 1.2.2 OpenMP Language Terminology 5691 // Structured block - An executable statement with a single entry at the 5692 // top and a single exit at the bottom. 5693 // The point of exit cannot be a branch out of the structured block. 5694 // longjmp() and throw() must not violate the entry/exit criteria. 5695 CS->getCapturedDecl()->setNothrow(); 5696 5697 OMPLoopDirective::HelperExprs B; 5698 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5699 // define the nested loops number. 5700 unsigned NestedLoopCount = 5701 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 5702 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5703 VarsWithImplicitDSA, B); 5704 if (NestedLoopCount == 0) 5705 return StmtError(); 5706 5707 assert((CurContext->isDependentContext() || B.builtAll()) && 5708 "omp target parallel for loop exprs were not built"); 5709 5710 if (!CurContext->isDependentContext()) { 5711 // Finalize the clauses that need pre-built expressions for CodeGen. 5712 for (auto C : Clauses) { 5713 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5714 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5715 B.NumIterations, *this, CurScope, 5716 DSAStack)) 5717 return StmtError(); 5718 } 5719 } 5720 5721 getCurFunction()->setHasBranchProtectedScope(); 5722 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 5723 NestedLoopCount, Clauses, AStmt, 5724 B, DSAStack->isCancelRegion()); 5725 } 5726 5727 /// \brief Check for existence of a map clause in the list of clauses. 5728 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) { 5729 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end(); 5730 I != E; ++I) { 5731 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) { 5732 return true; 5733 } 5734 } 5735 5736 return false; 5737 } 5738 5739 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 5740 Stmt *AStmt, 5741 SourceLocation StartLoc, 5742 SourceLocation EndLoc) { 5743 if (!AStmt) 5744 return StmtError(); 5745 5746 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5747 5748 // OpenMP [2.10.1, Restrictions, p. 97] 5749 // At least one map clause must appear on the directive. 5750 if (!HasMapClause(Clauses)) { 5751 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5752 << getOpenMPDirectiveName(OMPD_target_data); 5753 return StmtError(); 5754 } 5755 5756 getCurFunction()->setHasBranchProtectedScope(); 5757 5758 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 5759 AStmt); 5760 } 5761 5762 StmtResult 5763 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 5764 SourceLocation StartLoc, 5765 SourceLocation EndLoc) { 5766 // OpenMP [2.10.2, Restrictions, p. 99] 5767 // At least one map clause must appear on the directive. 5768 if (!HasMapClause(Clauses)) { 5769 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5770 << getOpenMPDirectiveName(OMPD_target_enter_data); 5771 return StmtError(); 5772 } 5773 5774 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, 5775 Clauses); 5776 } 5777 5778 StmtResult 5779 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 5780 SourceLocation StartLoc, 5781 SourceLocation EndLoc) { 5782 // OpenMP [2.10.3, Restrictions, p. 102] 5783 // At least one map clause must appear on the directive. 5784 if (!HasMapClause(Clauses)) { 5785 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5786 << getOpenMPDirectiveName(OMPD_target_exit_data); 5787 return StmtError(); 5788 } 5789 5790 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses); 5791 } 5792 5793 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 5794 SourceLocation StartLoc, 5795 SourceLocation EndLoc) { 5796 bool seenMotionClause = false; 5797 for (auto *C : Clauses) { 5798 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from) 5799 seenMotionClause = true; 5800 } 5801 if (!seenMotionClause) { 5802 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 5803 return StmtError(); 5804 } 5805 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses); 5806 } 5807 5808 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 5809 Stmt *AStmt, SourceLocation StartLoc, 5810 SourceLocation EndLoc) { 5811 if (!AStmt) 5812 return StmtError(); 5813 5814 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5815 // 1.2.2 OpenMP Language Terminology 5816 // Structured block - An executable statement with a single entry at the 5817 // top and a single exit at the bottom. 5818 // The point of exit cannot be a branch out of the structured block. 5819 // longjmp() and throw() must not violate the entry/exit criteria. 5820 CS->getCapturedDecl()->setNothrow(); 5821 5822 getCurFunction()->setHasBranchProtectedScope(); 5823 5824 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5825 } 5826 5827 StmtResult 5828 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 5829 SourceLocation EndLoc, 5830 OpenMPDirectiveKind CancelRegion) { 5831 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for && 5832 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) { 5833 Diag(StartLoc, diag::err_omp_wrong_cancel_region) 5834 << getOpenMPDirectiveName(CancelRegion); 5835 return StmtError(); 5836 } 5837 if (DSAStack->isParentNowaitRegion()) { 5838 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 5839 return StmtError(); 5840 } 5841 if (DSAStack->isParentOrderedRegion()) { 5842 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 5843 return StmtError(); 5844 } 5845 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 5846 CancelRegion); 5847 } 5848 5849 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 5850 SourceLocation StartLoc, 5851 SourceLocation EndLoc, 5852 OpenMPDirectiveKind CancelRegion) { 5853 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for && 5854 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) { 5855 Diag(StartLoc, diag::err_omp_wrong_cancel_region) 5856 << getOpenMPDirectiveName(CancelRegion); 5857 return StmtError(); 5858 } 5859 if (DSAStack->isParentNowaitRegion()) { 5860 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 5861 return StmtError(); 5862 } 5863 if (DSAStack->isParentOrderedRegion()) { 5864 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 5865 return StmtError(); 5866 } 5867 DSAStack->setParentCancelRegion(/*Cancel=*/true); 5868 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 5869 CancelRegion); 5870 } 5871 5872 static bool checkGrainsizeNumTasksClauses(Sema &S, 5873 ArrayRef<OMPClause *> Clauses) { 5874 OMPClause *PrevClause = nullptr; 5875 bool ErrorFound = false; 5876 for (auto *C : Clauses) { 5877 if (C->getClauseKind() == OMPC_grainsize || 5878 C->getClauseKind() == OMPC_num_tasks) { 5879 if (!PrevClause) 5880 PrevClause = C; 5881 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 5882 S.Diag(C->getLocStart(), 5883 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 5884 << getOpenMPClauseName(C->getClauseKind()) 5885 << getOpenMPClauseName(PrevClause->getClauseKind()); 5886 S.Diag(PrevClause->getLocStart(), 5887 diag::note_omp_previous_grainsize_num_tasks) 5888 << getOpenMPClauseName(PrevClause->getClauseKind()); 5889 ErrorFound = true; 5890 } 5891 } 5892 } 5893 return ErrorFound; 5894 } 5895 5896 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 5897 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5898 SourceLocation EndLoc, 5899 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5900 if (!AStmt) 5901 return StmtError(); 5902 5903 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5904 OMPLoopDirective::HelperExprs B; 5905 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5906 // define the nested loops number. 5907 unsigned NestedLoopCount = 5908 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 5909 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 5910 VarsWithImplicitDSA, B); 5911 if (NestedLoopCount == 0) 5912 return StmtError(); 5913 5914 assert((CurContext->isDependentContext() || B.builtAll()) && 5915 "omp for loop exprs were not built"); 5916 5917 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 5918 // The grainsize clause and num_tasks clause are mutually exclusive and may 5919 // not appear on the same taskloop directive. 5920 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 5921 return StmtError(); 5922 5923 getCurFunction()->setHasBranchProtectedScope(); 5924 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 5925 NestedLoopCount, Clauses, AStmt, B); 5926 } 5927 5928 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 5929 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5930 SourceLocation EndLoc, 5931 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5932 if (!AStmt) 5933 return StmtError(); 5934 5935 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5936 OMPLoopDirective::HelperExprs B; 5937 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5938 // define the nested loops number. 5939 unsigned NestedLoopCount = 5940 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 5941 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 5942 VarsWithImplicitDSA, B); 5943 if (NestedLoopCount == 0) 5944 return StmtError(); 5945 5946 assert((CurContext->isDependentContext() || B.builtAll()) && 5947 "omp for loop exprs were not built"); 5948 5949 if (!CurContext->isDependentContext()) { 5950 // Finalize the clauses that need pre-built expressions for CodeGen. 5951 for (auto C : Clauses) { 5952 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5953 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5954 B.NumIterations, *this, CurScope, 5955 DSAStack)) 5956 return StmtError(); 5957 } 5958 } 5959 5960 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 5961 // The grainsize clause and num_tasks clause are mutually exclusive and may 5962 // not appear on the same taskloop directive. 5963 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 5964 return StmtError(); 5965 5966 getCurFunction()->setHasBranchProtectedScope(); 5967 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 5968 NestedLoopCount, Clauses, AStmt, B); 5969 } 5970 5971 StmtResult Sema::ActOnOpenMPDistributeDirective( 5972 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5973 SourceLocation EndLoc, 5974 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5975 if (!AStmt) 5976 return StmtError(); 5977 5978 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5979 OMPLoopDirective::HelperExprs B; 5980 // In presence of clause 'collapse' with number of loops, it will 5981 // define the nested loops number. 5982 unsigned NestedLoopCount = 5983 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 5984 nullptr /*ordered not a clause on distribute*/, AStmt, 5985 *this, *DSAStack, VarsWithImplicitDSA, B); 5986 if (NestedLoopCount == 0) 5987 return StmtError(); 5988 5989 assert((CurContext->isDependentContext() || B.builtAll()) && 5990 "omp for loop exprs were not built"); 5991 5992 getCurFunction()->setHasBranchProtectedScope(); 5993 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 5994 NestedLoopCount, Clauses, AStmt, B); 5995 } 5996 5997 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 5998 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5999 SourceLocation EndLoc, 6000 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6001 if (!AStmt) 6002 return StmtError(); 6003 6004 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6005 // 1.2.2 OpenMP Language Terminology 6006 // Structured block - An executable statement with a single entry at the 6007 // top and a single exit at the bottom. 6008 // The point of exit cannot be a branch out of the structured block. 6009 // longjmp() and throw() must not violate the entry/exit criteria. 6010 CS->getCapturedDecl()->setNothrow(); 6011 6012 OMPLoopDirective::HelperExprs B; 6013 // In presence of clause 'collapse' with number of loops, it will 6014 // define the nested loops number. 6015 unsigned NestedLoopCount = CheckOpenMPLoop( 6016 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6017 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6018 VarsWithImplicitDSA, B); 6019 if (NestedLoopCount == 0) 6020 return StmtError(); 6021 6022 assert((CurContext->isDependentContext() || B.builtAll()) && 6023 "omp for loop exprs were not built"); 6024 6025 getCurFunction()->setHasBranchProtectedScope(); 6026 return OMPDistributeParallelForDirective::Create( 6027 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6028 } 6029 6030 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 6031 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6032 SourceLocation EndLoc, 6033 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6034 if (!AStmt) 6035 return StmtError(); 6036 6037 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6038 // 1.2.2 OpenMP Language Terminology 6039 // Structured block - An executable statement with a single entry at the 6040 // top and a single exit at the bottom. 6041 // The point of exit cannot be a branch out of the structured block. 6042 // longjmp() and throw() must not violate the entry/exit criteria. 6043 CS->getCapturedDecl()->setNothrow(); 6044 6045 OMPLoopDirective::HelperExprs B; 6046 // In presence of clause 'collapse' with number of loops, it will 6047 // define the nested loops number. 6048 unsigned NestedLoopCount = CheckOpenMPLoop( 6049 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6050 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6051 VarsWithImplicitDSA, B); 6052 if (NestedLoopCount == 0) 6053 return StmtError(); 6054 6055 assert((CurContext->isDependentContext() || B.builtAll()) && 6056 "omp for loop exprs were not built"); 6057 6058 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6059 return StmtError(); 6060 6061 getCurFunction()->setHasBranchProtectedScope(); 6062 return OMPDistributeParallelForSimdDirective::Create( 6063 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6064 } 6065 6066 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 6067 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6068 SourceLocation EndLoc, 6069 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6070 if (!AStmt) 6071 return StmtError(); 6072 6073 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6074 // 1.2.2 OpenMP Language Terminology 6075 // Structured block - An executable statement with a single entry at the 6076 // top and a single exit at the bottom. 6077 // The point of exit cannot be a branch out of the structured block. 6078 // longjmp() and throw() must not violate the entry/exit criteria. 6079 CS->getCapturedDecl()->setNothrow(); 6080 6081 OMPLoopDirective::HelperExprs B; 6082 // In presence of clause 'collapse' with number of loops, it will 6083 // define the nested loops number. 6084 unsigned NestedLoopCount = 6085 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 6086 nullptr /*ordered not a clause on distribute*/, AStmt, 6087 *this, *DSAStack, VarsWithImplicitDSA, B); 6088 if (NestedLoopCount == 0) 6089 return StmtError(); 6090 6091 assert((CurContext->isDependentContext() || B.builtAll()) && 6092 "omp for loop exprs were not built"); 6093 6094 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6095 return StmtError(); 6096 6097 getCurFunction()->setHasBranchProtectedScope(); 6098 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 6099 NestedLoopCount, Clauses, AStmt, B); 6100 } 6101 6102 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 6103 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6104 SourceLocation EndLoc, 6105 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6106 if (!AStmt) 6107 return StmtError(); 6108 6109 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6110 // 1.2.2 OpenMP Language Terminology 6111 // Structured block - An executable statement with a single entry at the 6112 // top and a single exit at the bottom. 6113 // The point of exit cannot be a branch out of the structured block. 6114 // longjmp() and throw() must not violate the entry/exit criteria. 6115 CS->getCapturedDecl()->setNothrow(); 6116 6117 OMPLoopDirective::HelperExprs B; 6118 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6119 // define the nested loops number. 6120 unsigned NestedLoopCount = CheckOpenMPLoop( 6121 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 6122 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6123 VarsWithImplicitDSA, B); 6124 if (NestedLoopCount == 0) 6125 return StmtError(); 6126 6127 assert((CurContext->isDependentContext() || B.builtAll()) && 6128 "omp target parallel for simd loop exprs were not built"); 6129 6130 if (!CurContext->isDependentContext()) { 6131 // Finalize the clauses that need pre-built expressions for CodeGen. 6132 for (auto C : Clauses) { 6133 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6134 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6135 B.NumIterations, *this, CurScope, 6136 DSAStack)) 6137 return StmtError(); 6138 } 6139 } 6140 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6141 return StmtError(); 6142 6143 getCurFunction()->setHasBranchProtectedScope(); 6144 return OMPTargetParallelForSimdDirective::Create( 6145 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6146 } 6147 6148 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 6149 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6150 SourceLocation EndLoc, 6151 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6152 if (!AStmt) 6153 return StmtError(); 6154 6155 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6156 // 1.2.2 OpenMP Language Terminology 6157 // Structured block - An executable statement with a single entry at the 6158 // top and a single exit at the bottom. 6159 // The point of exit cannot be a branch out of the structured block. 6160 // longjmp() and throw() must not violate the entry/exit criteria. 6161 CS->getCapturedDecl()->setNothrow(); 6162 6163 OMPLoopDirective::HelperExprs B; 6164 // In presence of clause 'collapse' with number of loops, it will define the 6165 // nested loops number. 6166 unsigned NestedLoopCount = 6167 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 6168 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6169 VarsWithImplicitDSA, B); 6170 if (NestedLoopCount == 0) 6171 return StmtError(); 6172 6173 assert((CurContext->isDependentContext() || B.builtAll()) && 6174 "omp target simd loop exprs were not built"); 6175 6176 if (!CurContext->isDependentContext()) { 6177 // Finalize the clauses that need pre-built expressions for CodeGen. 6178 for (auto C : Clauses) { 6179 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6180 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6181 B.NumIterations, *this, CurScope, 6182 DSAStack)) 6183 return StmtError(); 6184 } 6185 } 6186 6187 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6188 return StmtError(); 6189 6190 getCurFunction()->setHasBranchProtectedScope(); 6191 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 6192 NestedLoopCount, Clauses, AStmt, B); 6193 } 6194 6195 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 6196 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6197 SourceLocation EndLoc, 6198 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6199 if (!AStmt) 6200 return StmtError(); 6201 6202 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6203 // 1.2.2 OpenMP Language Terminology 6204 // Structured block - An executable statement with a single entry at the 6205 // top and a single exit at the bottom. 6206 // The point of exit cannot be a branch out of the structured block. 6207 // longjmp() and throw() must not violate the entry/exit criteria. 6208 CS->getCapturedDecl()->setNothrow(); 6209 6210 OMPLoopDirective::HelperExprs B; 6211 // In presence of clause 'collapse' with number of loops, it will 6212 // define the nested loops number. 6213 unsigned NestedLoopCount = 6214 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 6215 nullptr /*ordered not a clause on distribute*/, AStmt, 6216 *this, *DSAStack, VarsWithImplicitDSA, B); 6217 if (NestedLoopCount == 0) 6218 return StmtError(); 6219 6220 assert((CurContext->isDependentContext() || B.builtAll()) && 6221 "omp teams distribute loop exprs were not built"); 6222 6223 getCurFunction()->setHasBranchProtectedScope(); 6224 return OMPTeamsDistributeDirective::Create( 6225 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6226 } 6227 6228 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 6229 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6230 SourceLocation EndLoc, 6231 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6232 if (!AStmt) 6233 return StmtError(); 6234 6235 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6236 // 1.2.2 OpenMP Language Terminology 6237 // Structured block - An executable statement with a single entry at the 6238 // top and a single exit at the bottom. 6239 // The point of exit cannot be a branch out of the structured block. 6240 // longjmp() and throw() must not violate the entry/exit criteria. 6241 CS->getCapturedDecl()->setNothrow(); 6242 6243 OMPLoopDirective::HelperExprs B; 6244 // In presence of clause 'collapse' with number of loops, it will 6245 // define the nested loops number. 6246 unsigned NestedLoopCount = CheckOpenMPLoop( 6247 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6248 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6249 VarsWithImplicitDSA, B); 6250 6251 if (NestedLoopCount == 0) 6252 return StmtError(); 6253 6254 assert((CurContext->isDependentContext() || B.builtAll()) && 6255 "omp teams distribute simd loop exprs were not built"); 6256 6257 if (!CurContext->isDependentContext()) { 6258 // Finalize the clauses that need pre-built expressions for CodeGen. 6259 for (auto C : Clauses) { 6260 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6261 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6262 B.NumIterations, *this, CurScope, 6263 DSAStack)) 6264 return StmtError(); 6265 } 6266 } 6267 6268 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6269 return StmtError(); 6270 6271 getCurFunction()->setHasBranchProtectedScope(); 6272 return OMPTeamsDistributeSimdDirective::Create( 6273 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6274 } 6275 6276 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6277 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6278 SourceLocation EndLoc, 6279 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6280 if (!AStmt) 6281 return StmtError(); 6282 6283 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6284 // 1.2.2 OpenMP Language Terminology 6285 // Structured block - An executable statement with a single entry at the 6286 // top and a single exit at the bottom. 6287 // The point of exit cannot be a branch out of the structured block. 6288 // longjmp() and throw() must not violate the entry/exit criteria. 6289 CS->getCapturedDecl()->setNothrow(); 6290 6291 OMPLoopDirective::HelperExprs B; 6292 // In presence of clause 'collapse' with number of loops, it will 6293 // define the nested loops number. 6294 auto NestedLoopCount = CheckOpenMPLoop( 6295 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6296 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6297 VarsWithImplicitDSA, B); 6298 6299 if (NestedLoopCount == 0) 6300 return StmtError(); 6301 6302 assert((CurContext->isDependentContext() || B.builtAll()) && 6303 "omp for loop exprs were not built"); 6304 6305 if (!CurContext->isDependentContext()) { 6306 // Finalize the clauses that need pre-built expressions for CodeGen. 6307 for (auto C : Clauses) { 6308 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6309 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6310 B.NumIterations, *this, CurScope, 6311 DSAStack)) 6312 return StmtError(); 6313 } 6314 } 6315 6316 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6317 return StmtError(); 6318 6319 getCurFunction()->setHasBranchProtectedScope(); 6320 return OMPTeamsDistributeParallelForSimdDirective::Create( 6321 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6322 } 6323 6324 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 6325 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6326 SourceLocation EndLoc, 6327 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6328 if (!AStmt) 6329 return StmtError(); 6330 6331 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6332 // 1.2.2 OpenMP Language Terminology 6333 // Structured block - An executable statement with a single entry at the 6334 // top and a single exit at the bottom. 6335 // The point of exit cannot be a branch out of the structured block. 6336 // longjmp() and throw() must not violate the entry/exit criteria. 6337 CS->getCapturedDecl()->setNothrow(); 6338 6339 OMPLoopDirective::HelperExprs B; 6340 // In presence of clause 'collapse' with number of loops, it will 6341 // define the nested loops number. 6342 unsigned NestedLoopCount = CheckOpenMPLoop( 6343 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6344 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6345 VarsWithImplicitDSA, B); 6346 6347 if (NestedLoopCount == 0) 6348 return StmtError(); 6349 6350 assert((CurContext->isDependentContext() || B.builtAll()) && 6351 "omp for loop exprs were not built"); 6352 6353 if (!CurContext->isDependentContext()) { 6354 // Finalize the clauses that need pre-built expressions for CodeGen. 6355 for (auto C : Clauses) { 6356 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6357 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6358 B.NumIterations, *this, CurScope, 6359 DSAStack)) 6360 return StmtError(); 6361 } 6362 } 6363 6364 getCurFunction()->setHasBranchProtectedScope(); 6365 return OMPTeamsDistributeParallelForDirective::Create( 6366 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6367 } 6368 6369 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 6370 Stmt *AStmt, 6371 SourceLocation StartLoc, 6372 SourceLocation EndLoc) { 6373 if (!AStmt) 6374 return StmtError(); 6375 6376 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6377 // 1.2.2 OpenMP Language Terminology 6378 // Structured block - An executable statement with a single entry at the 6379 // top and a single exit at the bottom. 6380 // The point of exit cannot be a branch out of the structured block. 6381 // longjmp() and throw() must not violate the entry/exit criteria. 6382 CS->getCapturedDecl()->setNothrow(); 6383 6384 getCurFunction()->setHasBranchProtectedScope(); 6385 6386 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 6387 AStmt); 6388 } 6389 6390 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 6391 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6392 SourceLocation EndLoc, 6393 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6394 if (!AStmt) 6395 return StmtError(); 6396 6397 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6398 // 1.2.2 OpenMP Language Terminology 6399 // Structured block - An executable statement with a single entry at the 6400 // top and a single exit at the bottom. 6401 // The point of exit cannot be a branch out of the structured block. 6402 // longjmp() and throw() must not violate the entry/exit criteria. 6403 CS->getCapturedDecl()->setNothrow(); 6404 6405 OMPLoopDirective::HelperExprs B; 6406 // In presence of clause 'collapse' with number of loops, it will 6407 // define the nested loops number. 6408 auto NestedLoopCount = CheckOpenMPLoop( 6409 OMPD_target_teams_distribute, 6410 getCollapseNumberExpr(Clauses), 6411 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6412 VarsWithImplicitDSA, B); 6413 if (NestedLoopCount == 0) 6414 return StmtError(); 6415 6416 assert((CurContext->isDependentContext() || B.builtAll()) && 6417 "omp target teams distribute loop exprs were not built"); 6418 6419 getCurFunction()->setHasBranchProtectedScope(); 6420 return OMPTargetTeamsDistributeDirective::Create( 6421 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6422 } 6423 6424 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 6425 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6426 SourceLocation EndLoc, 6427 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6428 if (!AStmt) 6429 return StmtError(); 6430 6431 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6432 // 1.2.2 OpenMP Language Terminology 6433 // Structured block - An executable statement with a single entry at the 6434 // top and a single exit at the bottom. 6435 // The point of exit cannot be a branch out of the structured block. 6436 // longjmp() and throw() must not violate the entry/exit criteria. 6437 CS->getCapturedDecl()->setNothrow(); 6438 6439 OMPLoopDirective::HelperExprs B; 6440 // In presence of clause 'collapse' with number of loops, it will 6441 // define the nested loops number. 6442 auto NestedLoopCount = CheckOpenMPLoop( 6443 OMPD_target_teams_distribute_parallel_for, 6444 getCollapseNumberExpr(Clauses), 6445 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6446 VarsWithImplicitDSA, B); 6447 if (NestedLoopCount == 0) 6448 return StmtError(); 6449 6450 assert((CurContext->isDependentContext() || B.builtAll()) && 6451 "omp target teams distribute parallel for loop exprs were not built"); 6452 6453 if (!CurContext->isDependentContext()) { 6454 // Finalize the clauses that need pre-built expressions for CodeGen. 6455 for (auto C : Clauses) { 6456 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6457 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6458 B.NumIterations, *this, CurScope, 6459 DSAStack)) 6460 return StmtError(); 6461 } 6462 } 6463 6464 getCurFunction()->setHasBranchProtectedScope(); 6465 return OMPTargetTeamsDistributeParallelForDirective::Create( 6466 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6467 } 6468 6469 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 6470 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6471 SourceLocation EndLoc, 6472 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6473 if (!AStmt) 6474 return StmtError(); 6475 6476 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6477 // 1.2.2 OpenMP Language Terminology 6478 // Structured block - An executable statement with a single entry at the 6479 // top and a single exit at the bottom. 6480 // The point of exit cannot be a branch out of the structured block. 6481 // longjmp() and throw() must not violate the entry/exit criteria. 6482 CS->getCapturedDecl()->setNothrow(); 6483 6484 OMPLoopDirective::HelperExprs B; 6485 // In presence of clause 'collapse' with number of loops, it will 6486 // define the nested loops number. 6487 auto NestedLoopCount = CheckOpenMPLoop( 6488 OMPD_target_teams_distribute_parallel_for_simd, 6489 getCollapseNumberExpr(Clauses), 6490 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6491 VarsWithImplicitDSA, B); 6492 if (NestedLoopCount == 0) 6493 return StmtError(); 6494 6495 assert((CurContext->isDependentContext() || B.builtAll()) && 6496 "omp target teams distribute parallel for simd loop exprs were not " 6497 "built"); 6498 6499 if (!CurContext->isDependentContext()) { 6500 // Finalize the clauses that need pre-built expressions for CodeGen. 6501 for (auto C : Clauses) { 6502 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6503 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6504 B.NumIterations, *this, CurScope, 6505 DSAStack)) 6506 return StmtError(); 6507 } 6508 } 6509 6510 getCurFunction()->setHasBranchProtectedScope(); 6511 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 6512 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6513 } 6514 6515 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 6516 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6517 SourceLocation EndLoc, 6518 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6519 if (!AStmt) 6520 return StmtError(); 6521 6522 auto *CS = cast<CapturedStmt>(AStmt); 6523 // 1.2.2 OpenMP Language Terminology 6524 // Structured block - An executable statement with a single entry at the 6525 // top and a single exit at the bottom. 6526 // The point of exit cannot be a branch out of the structured block. 6527 // longjmp() and throw() must not violate the entry/exit criteria. 6528 CS->getCapturedDecl()->setNothrow(); 6529 6530 OMPLoopDirective::HelperExprs B; 6531 // In presence of clause 'collapse' with number of loops, it will 6532 // define the nested loops number. 6533 auto NestedLoopCount = CheckOpenMPLoop( 6534 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6535 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6536 VarsWithImplicitDSA, B); 6537 if (NestedLoopCount == 0) 6538 return StmtError(); 6539 6540 assert((CurContext->isDependentContext() || B.builtAll()) && 6541 "omp target teams distribute simd loop exprs were not built"); 6542 6543 getCurFunction()->setHasBranchProtectedScope(); 6544 return OMPTargetTeamsDistributeSimdDirective::Create( 6545 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6546 } 6547 6548 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 6549 SourceLocation StartLoc, 6550 SourceLocation LParenLoc, 6551 SourceLocation EndLoc) { 6552 OMPClause *Res = nullptr; 6553 switch (Kind) { 6554 case OMPC_final: 6555 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 6556 break; 6557 case OMPC_num_threads: 6558 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 6559 break; 6560 case OMPC_safelen: 6561 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 6562 break; 6563 case OMPC_simdlen: 6564 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 6565 break; 6566 case OMPC_collapse: 6567 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 6568 break; 6569 case OMPC_ordered: 6570 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 6571 break; 6572 case OMPC_device: 6573 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 6574 break; 6575 case OMPC_num_teams: 6576 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 6577 break; 6578 case OMPC_thread_limit: 6579 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 6580 break; 6581 case OMPC_priority: 6582 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 6583 break; 6584 case OMPC_grainsize: 6585 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 6586 break; 6587 case OMPC_num_tasks: 6588 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 6589 break; 6590 case OMPC_hint: 6591 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 6592 break; 6593 case OMPC_if: 6594 case OMPC_default: 6595 case OMPC_proc_bind: 6596 case OMPC_schedule: 6597 case OMPC_private: 6598 case OMPC_firstprivate: 6599 case OMPC_lastprivate: 6600 case OMPC_shared: 6601 case OMPC_reduction: 6602 case OMPC_linear: 6603 case OMPC_aligned: 6604 case OMPC_copyin: 6605 case OMPC_copyprivate: 6606 case OMPC_nowait: 6607 case OMPC_untied: 6608 case OMPC_mergeable: 6609 case OMPC_threadprivate: 6610 case OMPC_flush: 6611 case OMPC_read: 6612 case OMPC_write: 6613 case OMPC_update: 6614 case OMPC_capture: 6615 case OMPC_seq_cst: 6616 case OMPC_depend: 6617 case OMPC_threads: 6618 case OMPC_simd: 6619 case OMPC_map: 6620 case OMPC_nogroup: 6621 case OMPC_dist_schedule: 6622 case OMPC_defaultmap: 6623 case OMPC_unknown: 6624 case OMPC_uniform: 6625 case OMPC_to: 6626 case OMPC_from: 6627 case OMPC_use_device_ptr: 6628 case OMPC_is_device_ptr: 6629 llvm_unreachable("Clause is not allowed."); 6630 } 6631 return Res; 6632 } 6633 6634 // An OpenMP directive such as 'target parallel' has two captured regions: 6635 // for the 'target' and 'parallel' respectively. This function returns 6636 // the region in which to capture expressions associated with a clause. 6637 // A return value of OMPD_unknown signifies that the expression should not 6638 // be captured. 6639 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 6640 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 6641 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 6642 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 6643 6644 switch (CKind) { 6645 case OMPC_if: 6646 switch (DKind) { 6647 case OMPD_target_parallel: 6648 // If this clause applies to the nested 'parallel' region, capture within 6649 // the 'target' region, otherwise do not capture. 6650 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 6651 CaptureRegion = OMPD_target; 6652 break; 6653 case OMPD_cancel: 6654 case OMPD_parallel: 6655 case OMPD_parallel_sections: 6656 case OMPD_parallel_for: 6657 case OMPD_parallel_for_simd: 6658 case OMPD_target: 6659 case OMPD_target_simd: 6660 case OMPD_target_parallel_for: 6661 case OMPD_target_parallel_for_simd: 6662 case OMPD_target_teams: 6663 case OMPD_target_teams_distribute: 6664 case OMPD_target_teams_distribute_simd: 6665 case OMPD_target_teams_distribute_parallel_for: 6666 case OMPD_target_teams_distribute_parallel_for_simd: 6667 case OMPD_teams_distribute_parallel_for: 6668 case OMPD_teams_distribute_parallel_for_simd: 6669 case OMPD_distribute_parallel_for: 6670 case OMPD_distribute_parallel_for_simd: 6671 case OMPD_task: 6672 case OMPD_taskloop: 6673 case OMPD_taskloop_simd: 6674 case OMPD_target_data: 6675 case OMPD_target_enter_data: 6676 case OMPD_target_exit_data: 6677 case OMPD_target_update: 6678 // Do not capture if-clause expressions. 6679 break; 6680 case OMPD_threadprivate: 6681 case OMPD_taskyield: 6682 case OMPD_barrier: 6683 case OMPD_taskwait: 6684 case OMPD_cancellation_point: 6685 case OMPD_flush: 6686 case OMPD_declare_reduction: 6687 case OMPD_declare_simd: 6688 case OMPD_declare_target: 6689 case OMPD_end_declare_target: 6690 case OMPD_teams: 6691 case OMPD_simd: 6692 case OMPD_for: 6693 case OMPD_for_simd: 6694 case OMPD_sections: 6695 case OMPD_section: 6696 case OMPD_single: 6697 case OMPD_master: 6698 case OMPD_critical: 6699 case OMPD_taskgroup: 6700 case OMPD_distribute: 6701 case OMPD_ordered: 6702 case OMPD_atomic: 6703 case OMPD_distribute_simd: 6704 case OMPD_teams_distribute: 6705 case OMPD_teams_distribute_simd: 6706 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 6707 case OMPD_unknown: 6708 llvm_unreachable("Unknown OpenMP directive"); 6709 } 6710 break; 6711 case OMPC_num_threads: 6712 switch (DKind) { 6713 case OMPD_target_parallel: 6714 CaptureRegion = OMPD_target; 6715 break; 6716 case OMPD_cancel: 6717 case OMPD_parallel: 6718 case OMPD_parallel_sections: 6719 case OMPD_parallel_for: 6720 case OMPD_parallel_for_simd: 6721 case OMPD_target: 6722 case OMPD_target_simd: 6723 case OMPD_target_parallel_for: 6724 case OMPD_target_parallel_for_simd: 6725 case OMPD_target_teams: 6726 case OMPD_target_teams_distribute: 6727 case OMPD_target_teams_distribute_simd: 6728 case OMPD_target_teams_distribute_parallel_for: 6729 case OMPD_target_teams_distribute_parallel_for_simd: 6730 case OMPD_teams_distribute_parallel_for: 6731 case OMPD_teams_distribute_parallel_for_simd: 6732 case OMPD_distribute_parallel_for: 6733 case OMPD_distribute_parallel_for_simd: 6734 case OMPD_task: 6735 case OMPD_taskloop: 6736 case OMPD_taskloop_simd: 6737 case OMPD_target_data: 6738 case OMPD_target_enter_data: 6739 case OMPD_target_exit_data: 6740 case OMPD_target_update: 6741 // Do not capture num_threads-clause expressions. 6742 break; 6743 case OMPD_threadprivate: 6744 case OMPD_taskyield: 6745 case OMPD_barrier: 6746 case OMPD_taskwait: 6747 case OMPD_cancellation_point: 6748 case OMPD_flush: 6749 case OMPD_declare_reduction: 6750 case OMPD_declare_simd: 6751 case OMPD_declare_target: 6752 case OMPD_end_declare_target: 6753 case OMPD_teams: 6754 case OMPD_simd: 6755 case OMPD_for: 6756 case OMPD_for_simd: 6757 case OMPD_sections: 6758 case OMPD_section: 6759 case OMPD_single: 6760 case OMPD_master: 6761 case OMPD_critical: 6762 case OMPD_taskgroup: 6763 case OMPD_distribute: 6764 case OMPD_ordered: 6765 case OMPD_atomic: 6766 case OMPD_distribute_simd: 6767 case OMPD_teams_distribute: 6768 case OMPD_teams_distribute_simd: 6769 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 6770 case OMPD_unknown: 6771 llvm_unreachable("Unknown OpenMP directive"); 6772 } 6773 break; 6774 case OMPC_num_teams: 6775 switch (DKind) { 6776 case OMPD_target_teams: 6777 CaptureRegion = OMPD_target; 6778 break; 6779 case OMPD_cancel: 6780 case OMPD_parallel: 6781 case OMPD_parallel_sections: 6782 case OMPD_parallel_for: 6783 case OMPD_parallel_for_simd: 6784 case OMPD_target: 6785 case OMPD_target_simd: 6786 case OMPD_target_parallel: 6787 case OMPD_target_parallel_for: 6788 case OMPD_target_parallel_for_simd: 6789 case OMPD_target_teams_distribute: 6790 case OMPD_target_teams_distribute_simd: 6791 case OMPD_target_teams_distribute_parallel_for: 6792 case OMPD_target_teams_distribute_parallel_for_simd: 6793 case OMPD_teams_distribute_parallel_for: 6794 case OMPD_teams_distribute_parallel_for_simd: 6795 case OMPD_distribute_parallel_for: 6796 case OMPD_distribute_parallel_for_simd: 6797 case OMPD_task: 6798 case OMPD_taskloop: 6799 case OMPD_taskloop_simd: 6800 case OMPD_target_data: 6801 case OMPD_target_enter_data: 6802 case OMPD_target_exit_data: 6803 case OMPD_target_update: 6804 case OMPD_teams: 6805 case OMPD_teams_distribute: 6806 case OMPD_teams_distribute_simd: 6807 // Do not capture num_teams-clause expressions. 6808 break; 6809 case OMPD_threadprivate: 6810 case OMPD_taskyield: 6811 case OMPD_barrier: 6812 case OMPD_taskwait: 6813 case OMPD_cancellation_point: 6814 case OMPD_flush: 6815 case OMPD_declare_reduction: 6816 case OMPD_declare_simd: 6817 case OMPD_declare_target: 6818 case OMPD_end_declare_target: 6819 case OMPD_simd: 6820 case OMPD_for: 6821 case OMPD_for_simd: 6822 case OMPD_sections: 6823 case OMPD_section: 6824 case OMPD_single: 6825 case OMPD_master: 6826 case OMPD_critical: 6827 case OMPD_taskgroup: 6828 case OMPD_distribute: 6829 case OMPD_ordered: 6830 case OMPD_atomic: 6831 case OMPD_distribute_simd: 6832 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 6833 case OMPD_unknown: 6834 llvm_unreachable("Unknown OpenMP directive"); 6835 } 6836 break; 6837 case OMPC_thread_limit: 6838 switch (DKind) { 6839 case OMPD_target_teams: 6840 CaptureRegion = OMPD_target; 6841 break; 6842 case OMPD_cancel: 6843 case OMPD_parallel: 6844 case OMPD_parallel_sections: 6845 case OMPD_parallel_for: 6846 case OMPD_parallel_for_simd: 6847 case OMPD_target: 6848 case OMPD_target_simd: 6849 case OMPD_target_parallel: 6850 case OMPD_target_parallel_for: 6851 case OMPD_target_parallel_for_simd: 6852 case OMPD_target_teams_distribute: 6853 case OMPD_target_teams_distribute_simd: 6854 case OMPD_target_teams_distribute_parallel_for: 6855 case OMPD_target_teams_distribute_parallel_for_simd: 6856 case OMPD_teams_distribute_parallel_for: 6857 case OMPD_teams_distribute_parallel_for_simd: 6858 case OMPD_distribute_parallel_for: 6859 case OMPD_distribute_parallel_for_simd: 6860 case OMPD_task: 6861 case OMPD_taskloop: 6862 case OMPD_taskloop_simd: 6863 case OMPD_target_data: 6864 case OMPD_target_enter_data: 6865 case OMPD_target_exit_data: 6866 case OMPD_target_update: 6867 case OMPD_teams: 6868 case OMPD_teams_distribute: 6869 case OMPD_teams_distribute_simd: 6870 // Do not capture thread_limit-clause expressions. 6871 break; 6872 case OMPD_threadprivate: 6873 case OMPD_taskyield: 6874 case OMPD_barrier: 6875 case OMPD_taskwait: 6876 case OMPD_cancellation_point: 6877 case OMPD_flush: 6878 case OMPD_declare_reduction: 6879 case OMPD_declare_simd: 6880 case OMPD_declare_target: 6881 case OMPD_end_declare_target: 6882 case OMPD_simd: 6883 case OMPD_for: 6884 case OMPD_for_simd: 6885 case OMPD_sections: 6886 case OMPD_section: 6887 case OMPD_single: 6888 case OMPD_master: 6889 case OMPD_critical: 6890 case OMPD_taskgroup: 6891 case OMPD_distribute: 6892 case OMPD_ordered: 6893 case OMPD_atomic: 6894 case OMPD_distribute_simd: 6895 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 6896 case OMPD_unknown: 6897 llvm_unreachable("Unknown OpenMP directive"); 6898 } 6899 break; 6900 case OMPC_schedule: 6901 case OMPC_dist_schedule: 6902 case OMPC_firstprivate: 6903 case OMPC_lastprivate: 6904 case OMPC_reduction: 6905 case OMPC_linear: 6906 case OMPC_default: 6907 case OMPC_proc_bind: 6908 case OMPC_final: 6909 case OMPC_safelen: 6910 case OMPC_simdlen: 6911 case OMPC_collapse: 6912 case OMPC_private: 6913 case OMPC_shared: 6914 case OMPC_aligned: 6915 case OMPC_copyin: 6916 case OMPC_copyprivate: 6917 case OMPC_ordered: 6918 case OMPC_nowait: 6919 case OMPC_untied: 6920 case OMPC_mergeable: 6921 case OMPC_threadprivate: 6922 case OMPC_flush: 6923 case OMPC_read: 6924 case OMPC_write: 6925 case OMPC_update: 6926 case OMPC_capture: 6927 case OMPC_seq_cst: 6928 case OMPC_depend: 6929 case OMPC_device: 6930 case OMPC_threads: 6931 case OMPC_simd: 6932 case OMPC_map: 6933 case OMPC_priority: 6934 case OMPC_grainsize: 6935 case OMPC_nogroup: 6936 case OMPC_num_tasks: 6937 case OMPC_hint: 6938 case OMPC_defaultmap: 6939 case OMPC_unknown: 6940 case OMPC_uniform: 6941 case OMPC_to: 6942 case OMPC_from: 6943 case OMPC_use_device_ptr: 6944 case OMPC_is_device_ptr: 6945 llvm_unreachable("Unexpected OpenMP clause."); 6946 } 6947 return CaptureRegion; 6948 } 6949 6950 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 6951 Expr *Condition, SourceLocation StartLoc, 6952 SourceLocation LParenLoc, 6953 SourceLocation NameModifierLoc, 6954 SourceLocation ColonLoc, 6955 SourceLocation EndLoc) { 6956 Expr *ValExpr = Condition; 6957 Stmt *HelperValStmt = nullptr; 6958 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 6959 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 6960 !Condition->isInstantiationDependent() && 6961 !Condition->containsUnexpandedParameterPack()) { 6962 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 6963 if (Val.isInvalid()) 6964 return nullptr; 6965 6966 ValExpr = MakeFullExpr(Val.get()).get(); 6967 6968 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 6969 CaptureRegion = 6970 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 6971 if (CaptureRegion != OMPD_unknown) { 6972 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 6973 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 6974 HelperValStmt = buildPreInits(Context, Captures); 6975 } 6976 } 6977 6978 return new (Context) 6979 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 6980 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 6981 } 6982 6983 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 6984 SourceLocation StartLoc, 6985 SourceLocation LParenLoc, 6986 SourceLocation EndLoc) { 6987 Expr *ValExpr = Condition; 6988 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 6989 !Condition->isInstantiationDependent() && 6990 !Condition->containsUnexpandedParameterPack()) { 6991 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 6992 if (Val.isInvalid()) 6993 return nullptr; 6994 6995 ValExpr = MakeFullExpr(Val.get()).get(); 6996 } 6997 6998 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 6999 } 7000 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 7001 Expr *Op) { 7002 if (!Op) 7003 return ExprError(); 7004 7005 class IntConvertDiagnoser : public ICEConvertDiagnoser { 7006 public: 7007 IntConvertDiagnoser() 7008 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 7009 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 7010 QualType T) override { 7011 return S.Diag(Loc, diag::err_omp_not_integral) << T; 7012 } 7013 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 7014 QualType T) override { 7015 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 7016 } 7017 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 7018 QualType T, 7019 QualType ConvTy) override { 7020 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 7021 } 7022 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 7023 QualType ConvTy) override { 7024 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7025 << ConvTy->isEnumeralType() << ConvTy; 7026 } 7027 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 7028 QualType T) override { 7029 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 7030 } 7031 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 7032 QualType ConvTy) override { 7033 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7034 << ConvTy->isEnumeralType() << ConvTy; 7035 } 7036 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 7037 QualType) override { 7038 llvm_unreachable("conversion functions are permitted"); 7039 } 7040 } ConvertDiagnoser; 7041 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 7042 } 7043 7044 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 7045 OpenMPClauseKind CKind, 7046 bool StrictlyPositive) { 7047 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 7048 !ValExpr->isInstantiationDependent()) { 7049 SourceLocation Loc = ValExpr->getExprLoc(); 7050 ExprResult Value = 7051 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 7052 if (Value.isInvalid()) 7053 return false; 7054 7055 ValExpr = Value.get(); 7056 // The expression must evaluate to a non-negative integer value. 7057 llvm::APSInt Result; 7058 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 7059 Result.isSigned() && 7060 !((!StrictlyPositive && Result.isNonNegative()) || 7061 (StrictlyPositive && Result.isStrictlyPositive()))) { 7062 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 7063 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7064 << ValExpr->getSourceRange(); 7065 return false; 7066 } 7067 } 7068 return true; 7069 } 7070 7071 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 7072 SourceLocation StartLoc, 7073 SourceLocation LParenLoc, 7074 SourceLocation EndLoc) { 7075 Expr *ValExpr = NumThreads; 7076 Stmt *HelperValStmt = nullptr; 7077 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7078 7079 // OpenMP [2.5, Restrictions] 7080 // The num_threads expression must evaluate to a positive integer value. 7081 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 7082 /*StrictlyPositive=*/true)) 7083 return nullptr; 7084 7085 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7086 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 7087 if (CaptureRegion != OMPD_unknown) { 7088 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7089 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7090 HelperValStmt = buildPreInits(Context, Captures); 7091 } 7092 7093 return new (Context) OMPNumThreadsClause( 7094 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 7095 } 7096 7097 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 7098 OpenMPClauseKind CKind, 7099 bool StrictlyPositive) { 7100 if (!E) 7101 return ExprError(); 7102 if (E->isValueDependent() || E->isTypeDependent() || 7103 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 7104 return E; 7105 llvm::APSInt Result; 7106 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 7107 if (ICE.isInvalid()) 7108 return ExprError(); 7109 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 7110 (!StrictlyPositive && !Result.isNonNegative())) { 7111 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 7112 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7113 << E->getSourceRange(); 7114 return ExprError(); 7115 } 7116 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 7117 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 7118 << E->getSourceRange(); 7119 return ExprError(); 7120 } 7121 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 7122 DSAStack->setAssociatedLoops(Result.getExtValue()); 7123 else if (CKind == OMPC_ordered) 7124 DSAStack->setAssociatedLoops(Result.getExtValue()); 7125 return ICE; 7126 } 7127 7128 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 7129 SourceLocation LParenLoc, 7130 SourceLocation EndLoc) { 7131 // OpenMP [2.8.1, simd construct, Description] 7132 // The parameter of the safelen clause must be a constant 7133 // positive integer expression. 7134 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 7135 if (Safelen.isInvalid()) 7136 return nullptr; 7137 return new (Context) 7138 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 7139 } 7140 7141 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 7142 SourceLocation LParenLoc, 7143 SourceLocation EndLoc) { 7144 // OpenMP [2.8.1, simd construct, Description] 7145 // The parameter of the simdlen clause must be a constant 7146 // positive integer expression. 7147 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 7148 if (Simdlen.isInvalid()) 7149 return nullptr; 7150 return new (Context) 7151 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 7152 } 7153 7154 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 7155 SourceLocation StartLoc, 7156 SourceLocation LParenLoc, 7157 SourceLocation EndLoc) { 7158 // OpenMP [2.7.1, loop construct, Description] 7159 // OpenMP [2.8.1, simd construct, Description] 7160 // OpenMP [2.9.6, distribute construct, Description] 7161 // The parameter of the collapse clause must be a constant 7162 // positive integer expression. 7163 ExprResult NumForLoopsResult = 7164 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 7165 if (NumForLoopsResult.isInvalid()) 7166 return nullptr; 7167 return new (Context) 7168 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 7169 } 7170 7171 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 7172 SourceLocation EndLoc, 7173 SourceLocation LParenLoc, 7174 Expr *NumForLoops) { 7175 // OpenMP [2.7.1, loop construct, Description] 7176 // OpenMP [2.8.1, simd construct, Description] 7177 // OpenMP [2.9.6, distribute construct, Description] 7178 // The parameter of the ordered clause must be a constant 7179 // positive integer expression if any. 7180 if (NumForLoops && LParenLoc.isValid()) { 7181 ExprResult NumForLoopsResult = 7182 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 7183 if (NumForLoopsResult.isInvalid()) 7184 return nullptr; 7185 NumForLoops = NumForLoopsResult.get(); 7186 } else 7187 NumForLoops = nullptr; 7188 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 7189 return new (Context) 7190 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 7191 } 7192 7193 OMPClause *Sema::ActOnOpenMPSimpleClause( 7194 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 7195 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 7196 OMPClause *Res = nullptr; 7197 switch (Kind) { 7198 case OMPC_default: 7199 Res = 7200 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 7201 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 7202 break; 7203 case OMPC_proc_bind: 7204 Res = ActOnOpenMPProcBindClause( 7205 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 7206 LParenLoc, EndLoc); 7207 break; 7208 case OMPC_if: 7209 case OMPC_final: 7210 case OMPC_num_threads: 7211 case OMPC_safelen: 7212 case OMPC_simdlen: 7213 case OMPC_collapse: 7214 case OMPC_schedule: 7215 case OMPC_private: 7216 case OMPC_firstprivate: 7217 case OMPC_lastprivate: 7218 case OMPC_shared: 7219 case OMPC_reduction: 7220 case OMPC_linear: 7221 case OMPC_aligned: 7222 case OMPC_copyin: 7223 case OMPC_copyprivate: 7224 case OMPC_ordered: 7225 case OMPC_nowait: 7226 case OMPC_untied: 7227 case OMPC_mergeable: 7228 case OMPC_threadprivate: 7229 case OMPC_flush: 7230 case OMPC_read: 7231 case OMPC_write: 7232 case OMPC_update: 7233 case OMPC_capture: 7234 case OMPC_seq_cst: 7235 case OMPC_depend: 7236 case OMPC_device: 7237 case OMPC_threads: 7238 case OMPC_simd: 7239 case OMPC_map: 7240 case OMPC_num_teams: 7241 case OMPC_thread_limit: 7242 case OMPC_priority: 7243 case OMPC_grainsize: 7244 case OMPC_nogroup: 7245 case OMPC_num_tasks: 7246 case OMPC_hint: 7247 case OMPC_dist_schedule: 7248 case OMPC_defaultmap: 7249 case OMPC_unknown: 7250 case OMPC_uniform: 7251 case OMPC_to: 7252 case OMPC_from: 7253 case OMPC_use_device_ptr: 7254 case OMPC_is_device_ptr: 7255 llvm_unreachable("Clause is not allowed."); 7256 } 7257 return Res; 7258 } 7259 7260 static std::string 7261 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 7262 ArrayRef<unsigned> Exclude = llvm::None) { 7263 std::string Values; 7264 unsigned Bound = Last >= 2 ? Last - 2 : 0; 7265 unsigned Skipped = Exclude.size(); 7266 auto S = Exclude.begin(), E = Exclude.end(); 7267 for (unsigned i = First; i < Last; ++i) { 7268 if (std::find(S, E, i) != E) { 7269 --Skipped; 7270 continue; 7271 } 7272 Values += "'"; 7273 Values += getOpenMPSimpleClauseTypeName(K, i); 7274 Values += "'"; 7275 if (i == Bound - Skipped) 7276 Values += " or "; 7277 else if (i != Bound + 1 - Skipped) 7278 Values += ", "; 7279 } 7280 return Values; 7281 } 7282 7283 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 7284 SourceLocation KindKwLoc, 7285 SourceLocation StartLoc, 7286 SourceLocation LParenLoc, 7287 SourceLocation EndLoc) { 7288 if (Kind == OMPC_DEFAULT_unknown) { 7289 static_assert(OMPC_DEFAULT_unknown > 0, 7290 "OMPC_DEFAULT_unknown not greater than 0"); 7291 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7292 << getListOfPossibleValues(OMPC_default, /*First=*/0, 7293 /*Last=*/OMPC_DEFAULT_unknown) 7294 << getOpenMPClauseName(OMPC_default); 7295 return nullptr; 7296 } 7297 switch (Kind) { 7298 case OMPC_DEFAULT_none: 7299 DSAStack->setDefaultDSANone(KindKwLoc); 7300 break; 7301 case OMPC_DEFAULT_shared: 7302 DSAStack->setDefaultDSAShared(KindKwLoc); 7303 break; 7304 case OMPC_DEFAULT_unknown: 7305 llvm_unreachable("Clause kind is not allowed."); 7306 break; 7307 } 7308 return new (Context) 7309 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7310 } 7311 7312 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 7313 SourceLocation KindKwLoc, 7314 SourceLocation StartLoc, 7315 SourceLocation LParenLoc, 7316 SourceLocation EndLoc) { 7317 if (Kind == OMPC_PROC_BIND_unknown) { 7318 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7319 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 7320 /*Last=*/OMPC_PROC_BIND_unknown) 7321 << getOpenMPClauseName(OMPC_proc_bind); 7322 return nullptr; 7323 } 7324 return new (Context) 7325 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7326 } 7327 7328 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 7329 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 7330 SourceLocation StartLoc, SourceLocation LParenLoc, 7331 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 7332 SourceLocation EndLoc) { 7333 OMPClause *Res = nullptr; 7334 switch (Kind) { 7335 case OMPC_schedule: 7336 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 7337 assert(Argument.size() == NumberOfElements && 7338 ArgumentLoc.size() == NumberOfElements); 7339 Res = ActOnOpenMPScheduleClause( 7340 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 7341 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 7342 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 7343 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 7344 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 7345 break; 7346 case OMPC_if: 7347 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 7348 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 7349 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 7350 DelimLoc, EndLoc); 7351 break; 7352 case OMPC_dist_schedule: 7353 Res = ActOnOpenMPDistScheduleClause( 7354 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 7355 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 7356 break; 7357 case OMPC_defaultmap: 7358 enum { Modifier, DefaultmapKind }; 7359 Res = ActOnOpenMPDefaultmapClause( 7360 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 7361 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 7362 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 7363 EndLoc); 7364 break; 7365 case OMPC_final: 7366 case OMPC_num_threads: 7367 case OMPC_safelen: 7368 case OMPC_simdlen: 7369 case OMPC_collapse: 7370 case OMPC_default: 7371 case OMPC_proc_bind: 7372 case OMPC_private: 7373 case OMPC_firstprivate: 7374 case OMPC_lastprivate: 7375 case OMPC_shared: 7376 case OMPC_reduction: 7377 case OMPC_linear: 7378 case OMPC_aligned: 7379 case OMPC_copyin: 7380 case OMPC_copyprivate: 7381 case OMPC_ordered: 7382 case OMPC_nowait: 7383 case OMPC_untied: 7384 case OMPC_mergeable: 7385 case OMPC_threadprivate: 7386 case OMPC_flush: 7387 case OMPC_read: 7388 case OMPC_write: 7389 case OMPC_update: 7390 case OMPC_capture: 7391 case OMPC_seq_cst: 7392 case OMPC_depend: 7393 case OMPC_device: 7394 case OMPC_threads: 7395 case OMPC_simd: 7396 case OMPC_map: 7397 case OMPC_num_teams: 7398 case OMPC_thread_limit: 7399 case OMPC_priority: 7400 case OMPC_grainsize: 7401 case OMPC_nogroup: 7402 case OMPC_num_tasks: 7403 case OMPC_hint: 7404 case OMPC_unknown: 7405 case OMPC_uniform: 7406 case OMPC_to: 7407 case OMPC_from: 7408 case OMPC_use_device_ptr: 7409 case OMPC_is_device_ptr: 7410 llvm_unreachable("Clause is not allowed."); 7411 } 7412 return Res; 7413 } 7414 7415 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 7416 OpenMPScheduleClauseModifier M2, 7417 SourceLocation M1Loc, SourceLocation M2Loc) { 7418 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 7419 SmallVector<unsigned, 2> Excluded; 7420 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 7421 Excluded.push_back(M2); 7422 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 7423 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 7424 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 7425 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 7426 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 7427 << getListOfPossibleValues(OMPC_schedule, 7428 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 7429 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7430 Excluded) 7431 << getOpenMPClauseName(OMPC_schedule); 7432 return true; 7433 } 7434 return false; 7435 } 7436 7437 OMPClause *Sema::ActOnOpenMPScheduleClause( 7438 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 7439 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 7440 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 7441 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 7442 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 7443 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 7444 return nullptr; 7445 // OpenMP, 2.7.1, Loop Construct, Restrictions 7446 // Either the monotonic modifier or the nonmonotonic modifier can be specified 7447 // but not both. 7448 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 7449 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 7450 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 7451 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 7452 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 7453 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 7454 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 7455 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 7456 return nullptr; 7457 } 7458 if (Kind == OMPC_SCHEDULE_unknown) { 7459 std::string Values; 7460 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 7461 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 7462 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7463 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7464 Exclude); 7465 } else { 7466 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7467 /*Last=*/OMPC_SCHEDULE_unknown); 7468 } 7469 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 7470 << Values << getOpenMPClauseName(OMPC_schedule); 7471 return nullptr; 7472 } 7473 // OpenMP, 2.7.1, Loop Construct, Restrictions 7474 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 7475 // schedule(guided). 7476 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 7477 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 7478 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 7479 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 7480 diag::err_omp_schedule_nonmonotonic_static); 7481 return nullptr; 7482 } 7483 Expr *ValExpr = ChunkSize; 7484 Stmt *HelperValStmt = nullptr; 7485 if (ChunkSize) { 7486 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 7487 !ChunkSize->isInstantiationDependent() && 7488 !ChunkSize->containsUnexpandedParameterPack()) { 7489 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 7490 ExprResult Val = 7491 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 7492 if (Val.isInvalid()) 7493 return nullptr; 7494 7495 ValExpr = Val.get(); 7496 7497 // OpenMP [2.7.1, Restrictions] 7498 // chunk_size must be a loop invariant integer expression with a positive 7499 // value. 7500 llvm::APSInt Result; 7501 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 7502 if (Result.isSigned() && !Result.isStrictlyPositive()) { 7503 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 7504 << "schedule" << 1 << ChunkSize->getSourceRange(); 7505 return nullptr; 7506 } 7507 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 7508 !CurContext->isDependentContext()) { 7509 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7510 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7511 HelperValStmt = buildPreInits(Context, Captures); 7512 } 7513 } 7514 } 7515 7516 return new (Context) 7517 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 7518 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 7519 } 7520 7521 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 7522 SourceLocation StartLoc, 7523 SourceLocation EndLoc) { 7524 OMPClause *Res = nullptr; 7525 switch (Kind) { 7526 case OMPC_ordered: 7527 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 7528 break; 7529 case OMPC_nowait: 7530 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 7531 break; 7532 case OMPC_untied: 7533 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 7534 break; 7535 case OMPC_mergeable: 7536 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 7537 break; 7538 case OMPC_read: 7539 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 7540 break; 7541 case OMPC_write: 7542 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 7543 break; 7544 case OMPC_update: 7545 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 7546 break; 7547 case OMPC_capture: 7548 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 7549 break; 7550 case OMPC_seq_cst: 7551 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 7552 break; 7553 case OMPC_threads: 7554 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 7555 break; 7556 case OMPC_simd: 7557 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 7558 break; 7559 case OMPC_nogroup: 7560 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 7561 break; 7562 case OMPC_if: 7563 case OMPC_final: 7564 case OMPC_num_threads: 7565 case OMPC_safelen: 7566 case OMPC_simdlen: 7567 case OMPC_collapse: 7568 case OMPC_schedule: 7569 case OMPC_private: 7570 case OMPC_firstprivate: 7571 case OMPC_lastprivate: 7572 case OMPC_shared: 7573 case OMPC_reduction: 7574 case OMPC_linear: 7575 case OMPC_aligned: 7576 case OMPC_copyin: 7577 case OMPC_copyprivate: 7578 case OMPC_default: 7579 case OMPC_proc_bind: 7580 case OMPC_threadprivate: 7581 case OMPC_flush: 7582 case OMPC_depend: 7583 case OMPC_device: 7584 case OMPC_map: 7585 case OMPC_num_teams: 7586 case OMPC_thread_limit: 7587 case OMPC_priority: 7588 case OMPC_grainsize: 7589 case OMPC_num_tasks: 7590 case OMPC_hint: 7591 case OMPC_dist_schedule: 7592 case OMPC_defaultmap: 7593 case OMPC_unknown: 7594 case OMPC_uniform: 7595 case OMPC_to: 7596 case OMPC_from: 7597 case OMPC_use_device_ptr: 7598 case OMPC_is_device_ptr: 7599 llvm_unreachable("Clause is not allowed."); 7600 } 7601 return Res; 7602 } 7603 7604 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 7605 SourceLocation EndLoc) { 7606 DSAStack->setNowaitRegion(); 7607 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 7608 } 7609 7610 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 7611 SourceLocation EndLoc) { 7612 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 7613 } 7614 7615 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 7616 SourceLocation EndLoc) { 7617 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 7618 } 7619 7620 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 7621 SourceLocation EndLoc) { 7622 return new (Context) OMPReadClause(StartLoc, EndLoc); 7623 } 7624 7625 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 7626 SourceLocation EndLoc) { 7627 return new (Context) OMPWriteClause(StartLoc, EndLoc); 7628 } 7629 7630 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 7631 SourceLocation EndLoc) { 7632 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 7633 } 7634 7635 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 7636 SourceLocation EndLoc) { 7637 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 7638 } 7639 7640 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 7641 SourceLocation EndLoc) { 7642 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 7643 } 7644 7645 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 7646 SourceLocation EndLoc) { 7647 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 7648 } 7649 7650 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 7651 SourceLocation EndLoc) { 7652 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 7653 } 7654 7655 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 7656 SourceLocation EndLoc) { 7657 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 7658 } 7659 7660 OMPClause *Sema::ActOnOpenMPVarListClause( 7661 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 7662 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 7663 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 7664 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 7665 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 7666 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 7667 SourceLocation DepLinMapLoc) { 7668 OMPClause *Res = nullptr; 7669 switch (Kind) { 7670 case OMPC_private: 7671 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7672 break; 7673 case OMPC_firstprivate: 7674 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7675 break; 7676 case OMPC_lastprivate: 7677 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7678 break; 7679 case OMPC_shared: 7680 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 7681 break; 7682 case OMPC_reduction: 7683 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 7684 EndLoc, ReductionIdScopeSpec, ReductionId); 7685 break; 7686 case OMPC_linear: 7687 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 7688 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 7689 break; 7690 case OMPC_aligned: 7691 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 7692 ColonLoc, EndLoc); 7693 break; 7694 case OMPC_copyin: 7695 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 7696 break; 7697 case OMPC_copyprivate: 7698 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7699 break; 7700 case OMPC_flush: 7701 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 7702 break; 7703 case OMPC_depend: 7704 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 7705 StartLoc, LParenLoc, EndLoc); 7706 break; 7707 case OMPC_map: 7708 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 7709 DepLinMapLoc, ColonLoc, VarList, StartLoc, 7710 LParenLoc, EndLoc); 7711 break; 7712 case OMPC_to: 7713 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 7714 break; 7715 case OMPC_from: 7716 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 7717 break; 7718 case OMPC_use_device_ptr: 7719 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 7720 break; 7721 case OMPC_is_device_ptr: 7722 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 7723 break; 7724 case OMPC_if: 7725 case OMPC_final: 7726 case OMPC_num_threads: 7727 case OMPC_safelen: 7728 case OMPC_simdlen: 7729 case OMPC_collapse: 7730 case OMPC_default: 7731 case OMPC_proc_bind: 7732 case OMPC_schedule: 7733 case OMPC_ordered: 7734 case OMPC_nowait: 7735 case OMPC_untied: 7736 case OMPC_mergeable: 7737 case OMPC_threadprivate: 7738 case OMPC_read: 7739 case OMPC_write: 7740 case OMPC_update: 7741 case OMPC_capture: 7742 case OMPC_seq_cst: 7743 case OMPC_device: 7744 case OMPC_threads: 7745 case OMPC_simd: 7746 case OMPC_num_teams: 7747 case OMPC_thread_limit: 7748 case OMPC_priority: 7749 case OMPC_grainsize: 7750 case OMPC_nogroup: 7751 case OMPC_num_tasks: 7752 case OMPC_hint: 7753 case OMPC_dist_schedule: 7754 case OMPC_defaultmap: 7755 case OMPC_unknown: 7756 case OMPC_uniform: 7757 llvm_unreachable("Clause is not allowed."); 7758 } 7759 return Res; 7760 } 7761 7762 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 7763 ExprObjectKind OK, SourceLocation Loc) { 7764 ExprResult Res = BuildDeclRefExpr( 7765 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 7766 if (!Res.isUsable()) 7767 return ExprError(); 7768 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 7769 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 7770 if (!Res.isUsable()) 7771 return ExprError(); 7772 } 7773 if (VK != VK_LValue && Res.get()->isGLValue()) { 7774 Res = DefaultLvalueConversion(Res.get()); 7775 if (!Res.isUsable()) 7776 return ExprError(); 7777 } 7778 return Res; 7779 } 7780 7781 static std::pair<ValueDecl *, bool> 7782 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 7783 SourceRange &ERange, bool AllowArraySection = false) { 7784 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 7785 RefExpr->containsUnexpandedParameterPack()) 7786 return std::make_pair(nullptr, true); 7787 7788 // OpenMP [3.1, C/C++] 7789 // A list item is a variable name. 7790 // OpenMP [2.9.3.3, Restrictions, p.1] 7791 // A variable that is part of another variable (as an array or 7792 // structure element) cannot appear in a private clause. 7793 RefExpr = RefExpr->IgnoreParens(); 7794 enum { 7795 NoArrayExpr = -1, 7796 ArraySubscript = 0, 7797 OMPArraySection = 1 7798 } IsArrayExpr = NoArrayExpr; 7799 if (AllowArraySection) { 7800 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 7801 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 7802 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 7803 Base = TempASE->getBase()->IgnoreParenImpCasts(); 7804 RefExpr = Base; 7805 IsArrayExpr = ArraySubscript; 7806 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 7807 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 7808 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 7809 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 7810 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 7811 Base = TempASE->getBase()->IgnoreParenImpCasts(); 7812 RefExpr = Base; 7813 IsArrayExpr = OMPArraySection; 7814 } 7815 } 7816 ELoc = RefExpr->getExprLoc(); 7817 ERange = RefExpr->getSourceRange(); 7818 RefExpr = RefExpr->IgnoreParenImpCasts(); 7819 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 7820 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 7821 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 7822 (S.getCurrentThisType().isNull() || !ME || 7823 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 7824 !isa<FieldDecl>(ME->getMemberDecl()))) { 7825 if (IsArrayExpr != NoArrayExpr) 7826 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 7827 << ERange; 7828 else { 7829 S.Diag(ELoc, 7830 AllowArraySection 7831 ? diag::err_omp_expected_var_name_member_expr_or_array_item 7832 : diag::err_omp_expected_var_name_member_expr) 7833 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 7834 } 7835 return std::make_pair(nullptr, false); 7836 } 7837 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false); 7838 } 7839 7840 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 7841 SourceLocation StartLoc, 7842 SourceLocation LParenLoc, 7843 SourceLocation EndLoc) { 7844 SmallVector<Expr *, 8> Vars; 7845 SmallVector<Expr *, 8> PrivateCopies; 7846 for (auto &RefExpr : VarList) { 7847 assert(RefExpr && "NULL expr in OpenMP private clause."); 7848 SourceLocation ELoc; 7849 SourceRange ERange; 7850 Expr *SimpleRefExpr = RefExpr; 7851 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 7852 if (Res.second) { 7853 // It will be analyzed later. 7854 Vars.push_back(RefExpr); 7855 PrivateCopies.push_back(nullptr); 7856 } 7857 ValueDecl *D = Res.first; 7858 if (!D) 7859 continue; 7860 7861 QualType Type = D->getType(); 7862 auto *VD = dyn_cast<VarDecl>(D); 7863 7864 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 7865 // A variable that appears in a private clause must not have an incomplete 7866 // type or a reference type. 7867 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 7868 continue; 7869 Type = Type.getNonReferenceType(); 7870 7871 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 7872 // in a Construct] 7873 // Variables with the predetermined data-sharing attributes may not be 7874 // listed in data-sharing attributes clauses, except for the cases 7875 // listed below. For these exceptions only, listing a predetermined 7876 // variable in a data-sharing attribute clause is allowed and overrides 7877 // the variable's predetermined data-sharing attributes. 7878 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 7879 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 7880 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 7881 << getOpenMPClauseName(OMPC_private); 7882 ReportOriginalDSA(*this, DSAStack, D, DVar); 7883 continue; 7884 } 7885 7886 auto CurrDir = DSAStack->getCurrentDirective(); 7887 // Variably modified types are not supported for tasks. 7888 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 7889 isOpenMPTaskingDirective(CurrDir)) { 7890 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 7891 << getOpenMPClauseName(OMPC_private) << Type 7892 << getOpenMPDirectiveName(CurrDir); 7893 bool IsDecl = 7894 !VD || 7895 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 7896 Diag(D->getLocation(), 7897 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 7898 << D; 7899 continue; 7900 } 7901 7902 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 7903 // A list item cannot appear in both a map clause and a data-sharing 7904 // attribute clause on the same construct 7905 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 7906 CurrDir == OMPD_target_teams || 7907 CurrDir == OMPD_target_teams_distribute || 7908 CurrDir == OMPD_target_teams_distribute_parallel_for || 7909 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 7910 CurrDir == OMPD_target_teams_distribute_simd || 7911 CurrDir == OMPD_target_parallel_for_simd || 7912 CurrDir == OMPD_target_parallel_for) { 7913 OpenMPClauseKind ConflictKind; 7914 if (DSAStack->checkMappableExprComponentListsForDecl( 7915 VD, /*CurrentRegionOnly=*/true, 7916 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 7917 OpenMPClauseKind WhereFoundClauseKind) -> bool { 7918 ConflictKind = WhereFoundClauseKind; 7919 return true; 7920 })) { 7921 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 7922 << getOpenMPClauseName(OMPC_private) 7923 << getOpenMPClauseName(ConflictKind) 7924 << getOpenMPDirectiveName(CurrDir); 7925 ReportOriginalDSA(*this, DSAStack, D, DVar); 7926 continue; 7927 } 7928 } 7929 7930 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 7931 // A variable of class type (or array thereof) that appears in a private 7932 // clause requires an accessible, unambiguous default constructor for the 7933 // class type. 7934 // Generate helper private variable and initialize it with the default 7935 // value. The address of the original variable is replaced by the address of 7936 // the new private variable in CodeGen. This new variable is not added to 7937 // IdResolver, so the code in the OpenMP region uses original variable for 7938 // proper diagnostics. 7939 Type = Type.getUnqualifiedType(); 7940 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 7941 D->hasAttrs() ? &D->getAttrs() : nullptr); 7942 ActOnUninitializedDecl(VDPrivate); 7943 if (VDPrivate->isInvalidDecl()) 7944 continue; 7945 auto VDPrivateRefExpr = buildDeclRefExpr( 7946 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 7947 7948 DeclRefExpr *Ref = nullptr; 7949 if (!VD && !CurContext->isDependentContext()) 7950 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 7951 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 7952 Vars.push_back((VD || CurContext->isDependentContext()) 7953 ? RefExpr->IgnoreParens() 7954 : Ref); 7955 PrivateCopies.push_back(VDPrivateRefExpr); 7956 } 7957 7958 if (Vars.empty()) 7959 return nullptr; 7960 7961 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 7962 PrivateCopies); 7963 } 7964 7965 namespace { 7966 class DiagsUninitializedSeveretyRAII { 7967 private: 7968 DiagnosticsEngine &Diags; 7969 SourceLocation SavedLoc; 7970 bool IsIgnored; 7971 7972 public: 7973 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 7974 bool IsIgnored) 7975 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 7976 if (!IsIgnored) { 7977 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 7978 /*Map*/ diag::Severity::Ignored, Loc); 7979 } 7980 } 7981 ~DiagsUninitializedSeveretyRAII() { 7982 if (!IsIgnored) 7983 Diags.popMappings(SavedLoc); 7984 } 7985 }; 7986 } 7987 7988 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 7989 SourceLocation StartLoc, 7990 SourceLocation LParenLoc, 7991 SourceLocation EndLoc) { 7992 SmallVector<Expr *, 8> Vars; 7993 SmallVector<Expr *, 8> PrivateCopies; 7994 SmallVector<Expr *, 8> Inits; 7995 SmallVector<Decl *, 4> ExprCaptures; 7996 bool IsImplicitClause = 7997 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 7998 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 7999 8000 for (auto &RefExpr : VarList) { 8001 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 8002 SourceLocation ELoc; 8003 SourceRange ERange; 8004 Expr *SimpleRefExpr = RefExpr; 8005 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8006 if (Res.second) { 8007 // It will be analyzed later. 8008 Vars.push_back(RefExpr); 8009 PrivateCopies.push_back(nullptr); 8010 Inits.push_back(nullptr); 8011 } 8012 ValueDecl *D = Res.first; 8013 if (!D) 8014 continue; 8015 8016 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 8017 QualType Type = D->getType(); 8018 auto *VD = dyn_cast<VarDecl>(D); 8019 8020 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8021 // A variable that appears in a private clause must not have an incomplete 8022 // type or a reference type. 8023 if (RequireCompleteType(ELoc, Type, 8024 diag::err_omp_firstprivate_incomplete_type)) 8025 continue; 8026 Type = Type.getNonReferenceType(); 8027 8028 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 8029 // A variable of class type (or array thereof) that appears in a private 8030 // clause requires an accessible, unambiguous copy constructor for the 8031 // class type. 8032 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 8033 8034 // If an implicit firstprivate variable found it was checked already. 8035 DSAStackTy::DSAVarData TopDVar; 8036 if (!IsImplicitClause) { 8037 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8038 TopDVar = DVar; 8039 bool IsConstant = ElemType.isConstant(Context); 8040 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 8041 // A list item that specifies a given variable may not appear in more 8042 // than one clause on the same directive, except that a variable may be 8043 // specified in both firstprivate and lastprivate clauses. 8044 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 8045 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) { 8046 Diag(ELoc, diag::err_omp_wrong_dsa) 8047 << getOpenMPClauseName(DVar.CKind) 8048 << getOpenMPClauseName(OMPC_firstprivate); 8049 ReportOriginalDSA(*this, DSAStack, D, DVar); 8050 continue; 8051 } 8052 8053 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8054 // in a Construct] 8055 // Variables with the predetermined data-sharing attributes may not be 8056 // listed in data-sharing attributes clauses, except for the cases 8057 // listed below. For these exceptions only, listing a predetermined 8058 // variable in a data-sharing attribute clause is allowed and overrides 8059 // the variable's predetermined data-sharing attributes. 8060 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8061 // in a Construct, C/C++, p.2] 8062 // Variables with const-qualified type having no mutable member may be 8063 // listed in a firstprivate clause, even if they are static data members. 8064 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 8065 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 8066 Diag(ELoc, diag::err_omp_wrong_dsa) 8067 << getOpenMPClauseName(DVar.CKind) 8068 << getOpenMPClauseName(OMPC_firstprivate); 8069 ReportOriginalDSA(*this, DSAStack, D, DVar); 8070 continue; 8071 } 8072 8073 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8074 // OpenMP [2.9.3.4, Restrictions, p.2] 8075 // A list item that is private within a parallel region must not appear 8076 // in a firstprivate clause on a worksharing construct if any of the 8077 // worksharing regions arising from the worksharing construct ever bind 8078 // to any of the parallel regions arising from the parallel construct. 8079 if (isOpenMPWorksharingDirective(CurrDir) && 8080 !isOpenMPParallelDirective(CurrDir) && 8081 !isOpenMPTeamsDirective(CurrDir)) { 8082 DVar = DSAStack->getImplicitDSA(D, true); 8083 if (DVar.CKind != OMPC_shared && 8084 (isOpenMPParallelDirective(DVar.DKind) || 8085 DVar.DKind == OMPD_unknown)) { 8086 Diag(ELoc, diag::err_omp_required_access) 8087 << getOpenMPClauseName(OMPC_firstprivate) 8088 << getOpenMPClauseName(OMPC_shared); 8089 ReportOriginalDSA(*this, DSAStack, D, DVar); 8090 continue; 8091 } 8092 } 8093 // OpenMP [2.9.3.4, Restrictions, p.3] 8094 // A list item that appears in a reduction clause of a parallel construct 8095 // must not appear in a firstprivate clause on a worksharing or task 8096 // construct if any of the worksharing or task regions arising from the 8097 // worksharing or task construct ever bind to any of the parallel regions 8098 // arising from the parallel construct. 8099 // OpenMP [2.9.3.4, Restrictions, p.4] 8100 // A list item that appears in a reduction clause in worksharing 8101 // construct must not appear in a firstprivate clause in a task construct 8102 // encountered during execution of any of the worksharing regions arising 8103 // from the worksharing construct. 8104 if (isOpenMPTaskingDirective(CurrDir)) { 8105 DVar = DSAStack->hasInnermostDSA( 8106 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8107 [](OpenMPDirectiveKind K) -> bool { 8108 return isOpenMPParallelDirective(K) || 8109 isOpenMPWorksharingDirective(K); 8110 }, 8111 false); 8112 if (DVar.CKind == OMPC_reduction && 8113 (isOpenMPParallelDirective(DVar.DKind) || 8114 isOpenMPWorksharingDirective(DVar.DKind))) { 8115 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 8116 << getOpenMPDirectiveName(DVar.DKind); 8117 ReportOriginalDSA(*this, DSAStack, D, DVar); 8118 continue; 8119 } 8120 } 8121 8122 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8123 // A list item that is private within a teams region must not appear in a 8124 // firstprivate clause on a distribute construct if any of the distribute 8125 // regions arising from the distribute construct ever bind to any of the 8126 // teams regions arising from the teams construct. 8127 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8128 // A list item that appears in a reduction clause of a teams construct 8129 // must not appear in a firstprivate clause on a distribute construct if 8130 // any of the distribute regions arising from the distribute construct 8131 // ever bind to any of the teams regions arising from the teams construct. 8132 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8133 // A list item may appear in a firstprivate or lastprivate clause but not 8134 // both. 8135 if (CurrDir == OMPD_distribute) { 8136 DVar = DSAStack->hasInnermostDSA( 8137 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; }, 8138 [](OpenMPDirectiveKind K) -> bool { 8139 return isOpenMPTeamsDirective(K); 8140 }, 8141 false); 8142 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) { 8143 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams); 8144 ReportOriginalDSA(*this, DSAStack, D, DVar); 8145 continue; 8146 } 8147 DVar = DSAStack->hasInnermostDSA( 8148 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8149 [](OpenMPDirectiveKind K) -> bool { 8150 return isOpenMPTeamsDirective(K); 8151 }, 8152 false); 8153 if (DVar.CKind == OMPC_reduction && 8154 isOpenMPTeamsDirective(DVar.DKind)) { 8155 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction); 8156 ReportOriginalDSA(*this, DSAStack, D, DVar); 8157 continue; 8158 } 8159 DVar = DSAStack->getTopDSA(D, false); 8160 if (DVar.CKind == OMPC_lastprivate) { 8161 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8162 ReportOriginalDSA(*this, DSAStack, D, DVar); 8163 continue; 8164 } 8165 } 8166 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8167 // A list item cannot appear in both a map clause and a data-sharing 8168 // attribute clause on the same construct 8169 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 8170 CurrDir == OMPD_target_teams || 8171 CurrDir == OMPD_target_teams_distribute || 8172 CurrDir == OMPD_target_teams_distribute_parallel_for || 8173 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 8174 CurrDir == OMPD_target_teams_distribute_simd || 8175 CurrDir == OMPD_target_parallel_for_simd || 8176 CurrDir == OMPD_target_parallel_for) { 8177 OpenMPClauseKind ConflictKind; 8178 if (DSAStack->checkMappableExprComponentListsForDecl( 8179 VD, /*CurrentRegionOnly=*/true, 8180 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 8181 OpenMPClauseKind WhereFoundClauseKind) -> bool { 8182 ConflictKind = WhereFoundClauseKind; 8183 return true; 8184 })) { 8185 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 8186 << getOpenMPClauseName(OMPC_firstprivate) 8187 << getOpenMPClauseName(ConflictKind) 8188 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8189 ReportOriginalDSA(*this, DSAStack, D, DVar); 8190 continue; 8191 } 8192 } 8193 } 8194 8195 // Variably modified types are not supported for tasks. 8196 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8197 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 8198 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8199 << getOpenMPClauseName(OMPC_firstprivate) << Type 8200 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8201 bool IsDecl = 8202 !VD || 8203 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8204 Diag(D->getLocation(), 8205 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8206 << D; 8207 continue; 8208 } 8209 8210 Type = Type.getUnqualifiedType(); 8211 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8212 D->hasAttrs() ? &D->getAttrs() : nullptr); 8213 // Generate helper private variable and initialize it with the value of the 8214 // original variable. The address of the original variable is replaced by 8215 // the address of the new private variable in the CodeGen. This new variable 8216 // is not added to IdResolver, so the code in the OpenMP region uses 8217 // original variable for proper diagnostics and variable capturing. 8218 Expr *VDInitRefExpr = nullptr; 8219 // For arrays generate initializer for single element and replace it by the 8220 // original array element in CodeGen. 8221 if (Type->isArrayType()) { 8222 auto VDInit = 8223 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 8224 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 8225 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 8226 ElemType = ElemType.getUnqualifiedType(); 8227 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 8228 ".firstprivate.temp"); 8229 InitializedEntity Entity = 8230 InitializedEntity::InitializeVariable(VDInitTemp); 8231 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 8232 8233 InitializationSequence InitSeq(*this, Entity, Kind, Init); 8234 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 8235 if (Result.isInvalid()) 8236 VDPrivate->setInvalidDecl(); 8237 else 8238 VDPrivate->setInit(Result.getAs<Expr>()); 8239 // Remove temp variable declaration. 8240 Context.Deallocate(VDInitTemp); 8241 } else { 8242 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 8243 ".firstprivate.temp"); 8244 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 8245 RefExpr->getExprLoc()); 8246 AddInitializerToDecl(VDPrivate, 8247 DefaultLvalueConversion(VDInitRefExpr).get(), 8248 /*DirectInit=*/false); 8249 } 8250 if (VDPrivate->isInvalidDecl()) { 8251 if (IsImplicitClause) { 8252 Diag(RefExpr->getExprLoc(), 8253 diag::note_omp_task_predetermined_firstprivate_here); 8254 } 8255 continue; 8256 } 8257 CurContext->addDecl(VDPrivate); 8258 auto VDPrivateRefExpr = buildDeclRefExpr( 8259 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 8260 RefExpr->getExprLoc()); 8261 DeclRefExpr *Ref = nullptr; 8262 if (!VD && !CurContext->isDependentContext()) { 8263 if (TopDVar.CKind == OMPC_lastprivate) 8264 Ref = TopDVar.PrivateCopy; 8265 else { 8266 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8267 if (!IsOpenMPCapturedDecl(D)) 8268 ExprCaptures.push_back(Ref->getDecl()); 8269 } 8270 } 8271 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 8272 Vars.push_back((VD || CurContext->isDependentContext()) 8273 ? RefExpr->IgnoreParens() 8274 : Ref); 8275 PrivateCopies.push_back(VDPrivateRefExpr); 8276 Inits.push_back(VDInitRefExpr); 8277 } 8278 8279 if (Vars.empty()) 8280 return nullptr; 8281 8282 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8283 Vars, PrivateCopies, Inits, 8284 buildPreInits(Context, ExprCaptures)); 8285 } 8286 8287 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 8288 SourceLocation StartLoc, 8289 SourceLocation LParenLoc, 8290 SourceLocation EndLoc) { 8291 SmallVector<Expr *, 8> Vars; 8292 SmallVector<Expr *, 8> SrcExprs; 8293 SmallVector<Expr *, 8> DstExprs; 8294 SmallVector<Expr *, 8> AssignmentOps; 8295 SmallVector<Decl *, 4> ExprCaptures; 8296 SmallVector<Expr *, 4> ExprPostUpdates; 8297 for (auto &RefExpr : VarList) { 8298 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8299 SourceLocation ELoc; 8300 SourceRange ERange; 8301 Expr *SimpleRefExpr = RefExpr; 8302 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8303 if (Res.second) { 8304 // It will be analyzed later. 8305 Vars.push_back(RefExpr); 8306 SrcExprs.push_back(nullptr); 8307 DstExprs.push_back(nullptr); 8308 AssignmentOps.push_back(nullptr); 8309 } 8310 ValueDecl *D = Res.first; 8311 if (!D) 8312 continue; 8313 8314 QualType Type = D->getType(); 8315 auto *VD = dyn_cast<VarDecl>(D); 8316 8317 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 8318 // A variable that appears in a lastprivate clause must not have an 8319 // incomplete type or a reference type. 8320 if (RequireCompleteType(ELoc, Type, 8321 diag::err_omp_lastprivate_incomplete_type)) 8322 continue; 8323 Type = Type.getNonReferenceType(); 8324 8325 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8326 // in a Construct] 8327 // Variables with the predetermined data-sharing attributes may not be 8328 // listed in data-sharing attributes clauses, except for the cases 8329 // listed below. 8330 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8331 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 8332 DVar.CKind != OMPC_firstprivate && 8333 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 8334 Diag(ELoc, diag::err_omp_wrong_dsa) 8335 << getOpenMPClauseName(DVar.CKind) 8336 << getOpenMPClauseName(OMPC_lastprivate); 8337 ReportOriginalDSA(*this, DSAStack, D, DVar); 8338 continue; 8339 } 8340 8341 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8342 // OpenMP [2.14.3.5, Restrictions, p.2] 8343 // A list item that is private within a parallel region, or that appears in 8344 // the reduction clause of a parallel construct, must not appear in a 8345 // lastprivate clause on a worksharing construct if any of the corresponding 8346 // worksharing regions ever binds to any of the corresponding parallel 8347 // regions. 8348 DSAStackTy::DSAVarData TopDVar = DVar; 8349 if (isOpenMPWorksharingDirective(CurrDir) && 8350 !isOpenMPParallelDirective(CurrDir) && 8351 !isOpenMPTeamsDirective(CurrDir)) { 8352 DVar = DSAStack->getImplicitDSA(D, true); 8353 if (DVar.CKind != OMPC_shared) { 8354 Diag(ELoc, diag::err_omp_required_access) 8355 << getOpenMPClauseName(OMPC_lastprivate) 8356 << getOpenMPClauseName(OMPC_shared); 8357 ReportOriginalDSA(*this, DSAStack, D, DVar); 8358 continue; 8359 } 8360 } 8361 8362 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8363 // A list item may appear in a firstprivate or lastprivate clause but not 8364 // both. 8365 if (CurrDir == OMPD_distribute) { 8366 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8367 if (DVar.CKind == OMPC_firstprivate) { 8368 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8369 ReportOriginalDSA(*this, DSAStack, D, DVar); 8370 continue; 8371 } 8372 } 8373 8374 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 8375 // A variable of class type (or array thereof) that appears in a 8376 // lastprivate clause requires an accessible, unambiguous default 8377 // constructor for the class type, unless the list item is also specified 8378 // in a firstprivate clause. 8379 // A variable of class type (or array thereof) that appears in a 8380 // lastprivate clause requires an accessible, unambiguous copy assignment 8381 // operator for the class type. 8382 Type = Context.getBaseElementType(Type).getNonReferenceType(); 8383 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 8384 Type.getUnqualifiedType(), ".lastprivate.src", 8385 D->hasAttrs() ? &D->getAttrs() : nullptr); 8386 auto *PseudoSrcExpr = 8387 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 8388 auto *DstVD = 8389 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 8390 D->hasAttrs() ? &D->getAttrs() : nullptr); 8391 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 8392 // For arrays generate assignment operation for single element and replace 8393 // it by the original array element in CodeGen. 8394 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 8395 PseudoDstExpr, PseudoSrcExpr); 8396 if (AssignmentOp.isInvalid()) 8397 continue; 8398 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 8399 /*DiscardedValue=*/true); 8400 if (AssignmentOp.isInvalid()) 8401 continue; 8402 8403 DeclRefExpr *Ref = nullptr; 8404 if (!VD && !CurContext->isDependentContext()) { 8405 if (TopDVar.CKind == OMPC_firstprivate) 8406 Ref = TopDVar.PrivateCopy; 8407 else { 8408 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8409 if (!IsOpenMPCapturedDecl(D)) 8410 ExprCaptures.push_back(Ref->getDecl()); 8411 } 8412 if (TopDVar.CKind == OMPC_firstprivate || 8413 (!IsOpenMPCapturedDecl(D) && 8414 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 8415 ExprResult RefRes = DefaultLvalueConversion(Ref); 8416 if (!RefRes.isUsable()) 8417 continue; 8418 ExprResult PostUpdateRes = 8419 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 8420 RefRes.get()); 8421 if (!PostUpdateRes.isUsable()) 8422 continue; 8423 ExprPostUpdates.push_back( 8424 IgnoredValueConversions(PostUpdateRes.get()).get()); 8425 } 8426 } 8427 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 8428 Vars.push_back((VD || CurContext->isDependentContext()) 8429 ? RefExpr->IgnoreParens() 8430 : Ref); 8431 SrcExprs.push_back(PseudoSrcExpr); 8432 DstExprs.push_back(PseudoDstExpr); 8433 AssignmentOps.push_back(AssignmentOp.get()); 8434 } 8435 8436 if (Vars.empty()) 8437 return nullptr; 8438 8439 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8440 Vars, SrcExprs, DstExprs, AssignmentOps, 8441 buildPreInits(Context, ExprCaptures), 8442 buildPostUpdate(*this, ExprPostUpdates)); 8443 } 8444 8445 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 8446 SourceLocation StartLoc, 8447 SourceLocation LParenLoc, 8448 SourceLocation EndLoc) { 8449 SmallVector<Expr *, 8> Vars; 8450 for (auto &RefExpr : VarList) { 8451 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8452 SourceLocation ELoc; 8453 SourceRange ERange; 8454 Expr *SimpleRefExpr = RefExpr; 8455 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8456 if (Res.second) { 8457 // It will be analyzed later. 8458 Vars.push_back(RefExpr); 8459 } 8460 ValueDecl *D = Res.first; 8461 if (!D) 8462 continue; 8463 8464 auto *VD = dyn_cast<VarDecl>(D); 8465 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8466 // in a Construct] 8467 // Variables with the predetermined data-sharing attributes may not be 8468 // listed in data-sharing attributes clauses, except for the cases 8469 // listed below. For these exceptions only, listing a predetermined 8470 // variable in a data-sharing attribute clause is allowed and overrides 8471 // the variable's predetermined data-sharing attributes. 8472 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8473 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 8474 DVar.RefExpr) { 8475 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8476 << getOpenMPClauseName(OMPC_shared); 8477 ReportOriginalDSA(*this, DSAStack, D, DVar); 8478 continue; 8479 } 8480 8481 DeclRefExpr *Ref = nullptr; 8482 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 8483 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8484 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 8485 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 8486 ? RefExpr->IgnoreParens() 8487 : Ref); 8488 } 8489 8490 if (Vars.empty()) 8491 return nullptr; 8492 8493 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 8494 } 8495 8496 namespace { 8497 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 8498 DSAStackTy *Stack; 8499 8500 public: 8501 bool VisitDeclRefExpr(DeclRefExpr *E) { 8502 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 8503 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 8504 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 8505 return false; 8506 if (DVar.CKind != OMPC_unknown) 8507 return true; 8508 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 8509 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 8510 false); 8511 if (DVarPrivate.CKind != OMPC_unknown) 8512 return true; 8513 return false; 8514 } 8515 return false; 8516 } 8517 bool VisitStmt(Stmt *S) { 8518 for (auto Child : S->children()) { 8519 if (Child && Visit(Child)) 8520 return true; 8521 } 8522 return false; 8523 } 8524 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 8525 }; 8526 } // namespace 8527 8528 namespace { 8529 // Transform MemberExpression for specified FieldDecl of current class to 8530 // DeclRefExpr to specified OMPCapturedExprDecl. 8531 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 8532 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 8533 ValueDecl *Field; 8534 DeclRefExpr *CapturedExpr; 8535 8536 public: 8537 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 8538 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 8539 8540 ExprResult TransformMemberExpr(MemberExpr *E) { 8541 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 8542 E->getMemberDecl() == Field) { 8543 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 8544 return CapturedExpr; 8545 } 8546 return BaseTransform::TransformMemberExpr(E); 8547 } 8548 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 8549 }; 8550 } // namespace 8551 8552 template <typename T> 8553 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 8554 const llvm::function_ref<T(ValueDecl *)> &Gen) { 8555 for (auto &Set : Lookups) { 8556 for (auto *D : Set) { 8557 if (auto Res = Gen(cast<ValueDecl>(D))) 8558 return Res; 8559 } 8560 } 8561 return T(); 8562 } 8563 8564 static ExprResult 8565 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 8566 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 8567 const DeclarationNameInfo &ReductionId, QualType Ty, 8568 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 8569 if (ReductionIdScopeSpec.isInvalid()) 8570 return ExprError(); 8571 SmallVector<UnresolvedSet<8>, 4> Lookups; 8572 if (S) { 8573 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 8574 Lookup.suppressDiagnostics(); 8575 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 8576 auto *D = Lookup.getRepresentativeDecl(); 8577 do { 8578 S = S->getParent(); 8579 } while (S && !S->isDeclScope(D)); 8580 if (S) 8581 S = S->getParent(); 8582 Lookups.push_back(UnresolvedSet<8>()); 8583 Lookups.back().append(Lookup.begin(), Lookup.end()); 8584 Lookup.clear(); 8585 } 8586 } else if (auto *ULE = 8587 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 8588 Lookups.push_back(UnresolvedSet<8>()); 8589 Decl *PrevD = nullptr; 8590 for (auto *D : ULE->decls()) { 8591 if (D == PrevD) 8592 Lookups.push_back(UnresolvedSet<8>()); 8593 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 8594 Lookups.back().addDecl(DRD); 8595 PrevD = D; 8596 } 8597 } 8598 if (Ty->isDependentType() || Ty->isInstantiationDependentType() || 8599 Ty->containsUnexpandedParameterPack() || 8600 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 8601 return !D->isInvalidDecl() && 8602 (D->getType()->isDependentType() || 8603 D->getType()->isInstantiationDependentType() || 8604 D->getType()->containsUnexpandedParameterPack()); 8605 })) { 8606 UnresolvedSet<8> ResSet; 8607 for (auto &Set : Lookups) { 8608 ResSet.append(Set.begin(), Set.end()); 8609 // The last item marks the end of all declarations at the specified scope. 8610 ResSet.addDecl(Set[Set.size() - 1]); 8611 } 8612 return UnresolvedLookupExpr::Create( 8613 SemaRef.Context, /*NamingClass=*/nullptr, 8614 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 8615 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 8616 } 8617 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8618 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 8619 if (!D->isInvalidDecl() && 8620 SemaRef.Context.hasSameType(D->getType(), Ty)) 8621 return D; 8622 return nullptr; 8623 })) 8624 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8625 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8626 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 8627 if (!D->isInvalidDecl() && 8628 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 8629 !Ty.isMoreQualifiedThan(D->getType())) 8630 return D; 8631 return nullptr; 8632 })) { 8633 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 8634 /*DetectVirtual=*/false); 8635 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 8636 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 8637 VD->getType().getUnqualifiedType()))) { 8638 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 8639 /*DiagID=*/0) != 8640 Sema::AR_inaccessible) { 8641 SemaRef.BuildBasePathArray(Paths, BasePath); 8642 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8643 } 8644 } 8645 } 8646 } 8647 if (ReductionIdScopeSpec.isSet()) { 8648 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 8649 return ExprError(); 8650 } 8651 return ExprEmpty(); 8652 } 8653 8654 OMPClause *Sema::ActOnOpenMPReductionClause( 8655 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 8656 SourceLocation ColonLoc, SourceLocation EndLoc, 8657 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 8658 ArrayRef<Expr *> UnresolvedReductions) { 8659 auto DN = ReductionId.getName(); 8660 auto OOK = DN.getCXXOverloadedOperator(); 8661 BinaryOperatorKind BOK = BO_Comma; 8662 8663 // OpenMP [2.14.3.6, reduction clause] 8664 // C 8665 // reduction-identifier is either an identifier or one of the following 8666 // operators: +, -, *, &, |, ^, && and || 8667 // C++ 8668 // reduction-identifier is either an id-expression or one of the following 8669 // operators: +, -, *, &, |, ^, && and || 8670 // FIXME: Only 'min' and 'max' identifiers are supported for now. 8671 switch (OOK) { 8672 case OO_Plus: 8673 case OO_Minus: 8674 BOK = BO_Add; 8675 break; 8676 case OO_Star: 8677 BOK = BO_Mul; 8678 break; 8679 case OO_Amp: 8680 BOK = BO_And; 8681 break; 8682 case OO_Pipe: 8683 BOK = BO_Or; 8684 break; 8685 case OO_Caret: 8686 BOK = BO_Xor; 8687 break; 8688 case OO_AmpAmp: 8689 BOK = BO_LAnd; 8690 break; 8691 case OO_PipePipe: 8692 BOK = BO_LOr; 8693 break; 8694 case OO_New: 8695 case OO_Delete: 8696 case OO_Array_New: 8697 case OO_Array_Delete: 8698 case OO_Slash: 8699 case OO_Percent: 8700 case OO_Tilde: 8701 case OO_Exclaim: 8702 case OO_Equal: 8703 case OO_Less: 8704 case OO_Greater: 8705 case OO_LessEqual: 8706 case OO_GreaterEqual: 8707 case OO_PlusEqual: 8708 case OO_MinusEqual: 8709 case OO_StarEqual: 8710 case OO_SlashEqual: 8711 case OO_PercentEqual: 8712 case OO_CaretEqual: 8713 case OO_AmpEqual: 8714 case OO_PipeEqual: 8715 case OO_LessLess: 8716 case OO_GreaterGreater: 8717 case OO_LessLessEqual: 8718 case OO_GreaterGreaterEqual: 8719 case OO_EqualEqual: 8720 case OO_ExclaimEqual: 8721 case OO_PlusPlus: 8722 case OO_MinusMinus: 8723 case OO_Comma: 8724 case OO_ArrowStar: 8725 case OO_Arrow: 8726 case OO_Call: 8727 case OO_Subscript: 8728 case OO_Conditional: 8729 case OO_Coawait: 8730 case NUM_OVERLOADED_OPERATORS: 8731 llvm_unreachable("Unexpected reduction identifier"); 8732 case OO_None: 8733 if (auto II = DN.getAsIdentifierInfo()) { 8734 if (II->isStr("max")) 8735 BOK = BO_GT; 8736 else if (II->isStr("min")) 8737 BOK = BO_LT; 8738 } 8739 break; 8740 } 8741 SourceRange ReductionIdRange; 8742 if (ReductionIdScopeSpec.isValid()) 8743 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 8744 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 8745 8746 SmallVector<Expr *, 8> Vars; 8747 SmallVector<Expr *, 8> Privates; 8748 SmallVector<Expr *, 8> LHSs; 8749 SmallVector<Expr *, 8> RHSs; 8750 SmallVector<Expr *, 8> ReductionOps; 8751 SmallVector<Decl *, 4> ExprCaptures; 8752 SmallVector<Expr *, 4> ExprPostUpdates; 8753 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 8754 bool FirstIter = true; 8755 for (auto RefExpr : VarList) { 8756 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 8757 // OpenMP [2.1, C/C++] 8758 // A list item is a variable or array section, subject to the restrictions 8759 // specified in Section 2.4 on page 42 and in each of the sections 8760 // describing clauses and directives for which a list appears. 8761 // OpenMP [2.14.3.3, Restrictions, p.1] 8762 // A variable that is part of another variable (as an array or 8763 // structure element) cannot appear in a private clause. 8764 if (!FirstIter && IR != ER) 8765 ++IR; 8766 FirstIter = false; 8767 SourceLocation ELoc; 8768 SourceRange ERange; 8769 Expr *SimpleRefExpr = RefExpr; 8770 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 8771 /*AllowArraySection=*/true); 8772 if (Res.second) { 8773 // It will be analyzed later. 8774 Vars.push_back(RefExpr); 8775 Privates.push_back(nullptr); 8776 LHSs.push_back(nullptr); 8777 RHSs.push_back(nullptr); 8778 // Try to find 'declare reduction' corresponding construct before using 8779 // builtin/overloaded operators. 8780 QualType Type = Context.DependentTy; 8781 CXXCastPath BasePath; 8782 ExprResult DeclareReductionRef = buildDeclareReductionRef( 8783 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 8784 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 8785 if (CurContext->isDependentContext() && 8786 (DeclareReductionRef.isUnset() || 8787 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 8788 ReductionOps.push_back(DeclareReductionRef.get()); 8789 else 8790 ReductionOps.push_back(nullptr); 8791 } 8792 ValueDecl *D = Res.first; 8793 if (!D) 8794 continue; 8795 8796 QualType Type; 8797 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 8798 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 8799 if (ASE) 8800 Type = ASE->getType().getNonReferenceType(); 8801 else if (OASE) { 8802 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 8803 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 8804 Type = ATy->getElementType(); 8805 else 8806 Type = BaseType->getPointeeType(); 8807 Type = Type.getNonReferenceType(); 8808 } else 8809 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 8810 auto *VD = dyn_cast<VarDecl>(D); 8811 8812 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8813 // A variable that appears in a private clause must not have an incomplete 8814 // type or a reference type. 8815 if (RequireCompleteType(ELoc, Type, 8816 diag::err_omp_reduction_incomplete_type)) 8817 continue; 8818 // OpenMP [2.14.3.6, reduction clause, Restrictions] 8819 // A list item that appears in a reduction clause must not be 8820 // const-qualified. 8821 if (Type.getNonReferenceType().isConstant(Context)) { 8822 Diag(ELoc, diag::err_omp_const_reduction_list_item) 8823 << getOpenMPClauseName(OMPC_reduction) << Type << ERange; 8824 if (!ASE && !OASE) { 8825 bool IsDecl = !VD || 8826 VD->isThisDeclarationADefinition(Context) == 8827 VarDecl::DeclarationOnly; 8828 Diag(D->getLocation(), 8829 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8830 << D; 8831 } 8832 continue; 8833 } 8834 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 8835 // If a list-item is a reference type then it must bind to the same object 8836 // for all threads of the team. 8837 if (!ASE && !OASE && VD) { 8838 VarDecl *VDDef = VD->getDefinition(); 8839 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 8840 DSARefChecker Check(DSAStack); 8841 if (Check.Visit(VDDef->getInit())) { 8842 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange; 8843 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 8844 continue; 8845 } 8846 } 8847 } 8848 8849 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8850 // in a Construct] 8851 // Variables with the predetermined data-sharing attributes may not be 8852 // listed in data-sharing attributes clauses, except for the cases 8853 // listed below. For these exceptions only, listing a predetermined 8854 // variable in a data-sharing attribute clause is allowed and overrides 8855 // the variable's predetermined data-sharing attributes. 8856 // OpenMP [2.14.3.6, Restrictions, p.3] 8857 // Any number of reduction clauses can be specified on the directive, 8858 // but a list item can appear only once in the reduction clauses for that 8859 // directive. 8860 DSAStackTy::DSAVarData DVar; 8861 DVar = DSAStack->getTopDSA(D, false); 8862 if (DVar.CKind == OMPC_reduction) { 8863 Diag(ELoc, diag::err_omp_once_referenced) 8864 << getOpenMPClauseName(OMPC_reduction); 8865 if (DVar.RefExpr) 8866 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 8867 } else if (DVar.CKind != OMPC_unknown) { 8868 Diag(ELoc, diag::err_omp_wrong_dsa) 8869 << getOpenMPClauseName(DVar.CKind) 8870 << getOpenMPClauseName(OMPC_reduction); 8871 ReportOriginalDSA(*this, DSAStack, D, DVar); 8872 continue; 8873 } 8874 8875 // OpenMP [2.14.3.6, Restrictions, p.1] 8876 // A list item that appears in a reduction clause of a worksharing 8877 // construct must be shared in the parallel regions to which any of the 8878 // worksharing regions arising from the worksharing construct bind. 8879 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8880 if (isOpenMPWorksharingDirective(CurrDir) && 8881 !isOpenMPParallelDirective(CurrDir) && 8882 !isOpenMPTeamsDirective(CurrDir)) { 8883 DVar = DSAStack->getImplicitDSA(D, true); 8884 if (DVar.CKind != OMPC_shared) { 8885 Diag(ELoc, diag::err_omp_required_access) 8886 << getOpenMPClauseName(OMPC_reduction) 8887 << getOpenMPClauseName(OMPC_shared); 8888 ReportOriginalDSA(*this, DSAStack, D, DVar); 8889 continue; 8890 } 8891 } 8892 8893 // Try to find 'declare reduction' corresponding construct before using 8894 // builtin/overloaded operators. 8895 CXXCastPath BasePath; 8896 ExprResult DeclareReductionRef = buildDeclareReductionRef( 8897 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 8898 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 8899 if (DeclareReductionRef.isInvalid()) 8900 continue; 8901 if (CurContext->isDependentContext() && 8902 (DeclareReductionRef.isUnset() || 8903 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 8904 Vars.push_back(RefExpr); 8905 Privates.push_back(nullptr); 8906 LHSs.push_back(nullptr); 8907 RHSs.push_back(nullptr); 8908 ReductionOps.push_back(DeclareReductionRef.get()); 8909 continue; 8910 } 8911 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 8912 // Not allowed reduction identifier is found. 8913 Diag(ReductionId.getLocStart(), 8914 diag::err_omp_unknown_reduction_identifier) 8915 << Type << ReductionIdRange; 8916 continue; 8917 } 8918 8919 // OpenMP [2.14.3.6, reduction clause, Restrictions] 8920 // The type of a list item that appears in a reduction clause must be valid 8921 // for the reduction-identifier. For a max or min reduction in C, the type 8922 // of the list item must be an allowed arithmetic data type: char, int, 8923 // float, double, or _Bool, possibly modified with long, short, signed, or 8924 // unsigned. For a max or min reduction in C++, the type of the list item 8925 // must be an allowed arithmetic data type: char, wchar_t, int, float, 8926 // double, or bool, possibly modified with long, short, signed, or unsigned. 8927 if (DeclareReductionRef.isUnset()) { 8928 if ((BOK == BO_GT || BOK == BO_LT) && 8929 !(Type->isScalarType() || 8930 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 8931 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 8932 << getLangOpts().CPlusPlus; 8933 if (!ASE && !OASE) { 8934 bool IsDecl = !VD || 8935 VD->isThisDeclarationADefinition(Context) == 8936 VarDecl::DeclarationOnly; 8937 Diag(D->getLocation(), 8938 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8939 << D; 8940 } 8941 continue; 8942 } 8943 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 8944 !getLangOpts().CPlusPlus && Type->isFloatingType()) { 8945 Diag(ELoc, diag::err_omp_clause_floating_type_arg); 8946 if (!ASE && !OASE) { 8947 bool IsDecl = !VD || 8948 VD->isThisDeclarationADefinition(Context) == 8949 VarDecl::DeclarationOnly; 8950 Diag(D->getLocation(), 8951 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8952 << D; 8953 } 8954 continue; 8955 } 8956 } 8957 8958 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 8959 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs", 8960 D->hasAttrs() ? &D->getAttrs() : nullptr); 8961 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(), 8962 D->hasAttrs() ? &D->getAttrs() : nullptr); 8963 auto PrivateTy = Type; 8964 if (OASE || 8965 (!ASE && 8966 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 8967 // For arrays/array sections only: 8968 // Create pseudo array type for private copy. The size for this array will 8969 // be generated during codegen. 8970 // For array subscripts or single variables Private Ty is the same as Type 8971 // (type of the variable or single array element). 8972 PrivateTy = Context.getVariableArrayType( 8973 Type, new (Context) OpaqueValueExpr(SourceLocation(), 8974 Context.getSizeType(), VK_RValue), 8975 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 8976 } else if (!ASE && !OASE && 8977 Context.getAsArrayType(D->getType().getNonReferenceType())) 8978 PrivateTy = D->getType().getNonReferenceType(); 8979 // Private copy. 8980 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(), 8981 D->hasAttrs() ? &D->getAttrs() : nullptr); 8982 // Add initializer for private variable. 8983 Expr *Init = nullptr; 8984 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc); 8985 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc); 8986 if (DeclareReductionRef.isUsable()) { 8987 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 8988 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 8989 if (DRD->getInitializer()) { 8990 Init = DRDRef; 8991 RHSVD->setInit(DRDRef); 8992 RHSVD->setInitStyle(VarDecl::CallInit); 8993 } 8994 } else { 8995 switch (BOK) { 8996 case BO_Add: 8997 case BO_Xor: 8998 case BO_Or: 8999 case BO_LOr: 9000 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 9001 if (Type->isScalarType() || Type->isAnyComplexType()) 9002 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 9003 break; 9004 case BO_Mul: 9005 case BO_LAnd: 9006 if (Type->isScalarType() || Type->isAnyComplexType()) { 9007 // '*' and '&&' reduction ops - initializer is '1'. 9008 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 9009 } 9010 break; 9011 case BO_And: { 9012 // '&' reduction op - initializer is '~0'. 9013 QualType OrigType = Type; 9014 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 9015 Type = ComplexTy->getElementType(); 9016 if (Type->isRealFloatingType()) { 9017 llvm::APFloat InitValue = 9018 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 9019 /*isIEEE=*/true); 9020 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9021 Type, ELoc); 9022 } else if (Type->isScalarType()) { 9023 auto Size = Context.getTypeSize(Type); 9024 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 9025 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 9026 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9027 } 9028 if (Init && OrigType->isAnyComplexType()) { 9029 // Init = 0xFFFF + 0xFFFFi; 9030 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 9031 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 9032 } 9033 Type = OrigType; 9034 break; 9035 } 9036 case BO_LT: 9037 case BO_GT: { 9038 // 'min' reduction op - initializer is 'Largest representable number in 9039 // the reduction list item type'. 9040 // 'max' reduction op - initializer is 'Least representable number in 9041 // the reduction list item type'. 9042 if (Type->isIntegerType() || Type->isPointerType()) { 9043 bool IsSigned = Type->hasSignedIntegerRepresentation(); 9044 auto Size = Context.getTypeSize(Type); 9045 QualType IntTy = 9046 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 9047 llvm::APInt InitValue = 9048 (BOK != BO_LT) 9049 ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 9050 : llvm::APInt::getMinValue(Size) 9051 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 9052 : llvm::APInt::getMaxValue(Size); 9053 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9054 if (Type->isPointerType()) { 9055 // Cast to pointer type. 9056 auto CastExpr = BuildCStyleCastExpr( 9057 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc), 9058 SourceLocation(), Init); 9059 if (CastExpr.isInvalid()) 9060 continue; 9061 Init = CastExpr.get(); 9062 } 9063 } else if (Type->isRealFloatingType()) { 9064 llvm::APFloat InitValue = llvm::APFloat::getLargest( 9065 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 9066 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9067 Type, ELoc); 9068 } 9069 break; 9070 } 9071 case BO_PtrMemD: 9072 case BO_PtrMemI: 9073 case BO_MulAssign: 9074 case BO_Div: 9075 case BO_Rem: 9076 case BO_Sub: 9077 case BO_Shl: 9078 case BO_Shr: 9079 case BO_LE: 9080 case BO_GE: 9081 case BO_EQ: 9082 case BO_NE: 9083 case BO_AndAssign: 9084 case BO_XorAssign: 9085 case BO_OrAssign: 9086 case BO_Assign: 9087 case BO_AddAssign: 9088 case BO_SubAssign: 9089 case BO_DivAssign: 9090 case BO_RemAssign: 9091 case BO_ShlAssign: 9092 case BO_ShrAssign: 9093 case BO_Comma: 9094 llvm_unreachable("Unexpected reduction operation"); 9095 } 9096 } 9097 if (Init && DeclareReductionRef.isUnset()) { 9098 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 9099 } else if (!Init) 9100 ActOnUninitializedDecl(RHSVD); 9101 if (RHSVD->isInvalidDecl()) 9102 continue; 9103 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 9104 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type 9105 << ReductionIdRange; 9106 bool IsDecl = 9107 !VD || 9108 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9109 Diag(D->getLocation(), 9110 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9111 << D; 9112 continue; 9113 } 9114 // Store initializer for single element in private copy. Will be used during 9115 // codegen. 9116 PrivateVD->setInit(RHSVD->getInit()); 9117 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 9118 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc); 9119 ExprResult ReductionOp; 9120 if (DeclareReductionRef.isUsable()) { 9121 QualType RedTy = DeclareReductionRef.get()->getType(); 9122 QualType PtrRedTy = Context.getPointerType(RedTy); 9123 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 9124 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 9125 if (!BasePath.empty()) { 9126 LHS = DefaultLvalueConversion(LHS.get()); 9127 RHS = DefaultLvalueConversion(RHS.get()); 9128 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9129 CK_UncheckedDerivedToBase, LHS.get(), 9130 &BasePath, LHS.get()->getValueKind()); 9131 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9132 CK_UncheckedDerivedToBase, RHS.get(), 9133 &BasePath, RHS.get()->getValueKind()); 9134 } 9135 FunctionProtoType::ExtProtoInfo EPI; 9136 QualType Params[] = {PtrRedTy, PtrRedTy}; 9137 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 9138 auto *OVE = new (Context) OpaqueValueExpr( 9139 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 9140 DefaultLvalueConversion(DeclareReductionRef.get()).get()); 9141 Expr *Args[] = {LHS.get(), RHS.get()}; 9142 ReductionOp = new (Context) 9143 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 9144 } else { 9145 ReductionOp = BuildBinOp(DSAStack->getCurScope(), 9146 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 9147 if (ReductionOp.isUsable()) { 9148 if (BOK != BO_LT && BOK != BO_GT) { 9149 ReductionOp = 9150 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 9151 BO_Assign, LHSDRE, ReductionOp.get()); 9152 } else { 9153 auto *ConditionalOp = new (Context) ConditionalOperator( 9154 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(), 9155 RHSDRE, Type, VK_LValue, OK_Ordinary); 9156 ReductionOp = 9157 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 9158 BO_Assign, LHSDRE, ConditionalOp); 9159 } 9160 ReductionOp = ActOnFinishFullExpr(ReductionOp.get()); 9161 } 9162 if (ReductionOp.isInvalid()) 9163 continue; 9164 } 9165 9166 DeclRefExpr *Ref = nullptr; 9167 Expr *VarsExpr = RefExpr->IgnoreParens(); 9168 if (!VD && !CurContext->isDependentContext()) { 9169 if (ASE || OASE) { 9170 TransformExprToCaptures RebuildToCapture(*this, D); 9171 VarsExpr = 9172 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 9173 Ref = RebuildToCapture.getCapturedExpr(); 9174 } else { 9175 VarsExpr = Ref = 9176 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9177 } 9178 if (!IsOpenMPCapturedDecl(D)) { 9179 ExprCaptures.push_back(Ref->getDecl()); 9180 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9181 ExprResult RefRes = DefaultLvalueConversion(Ref); 9182 if (!RefRes.isUsable()) 9183 continue; 9184 ExprResult PostUpdateRes = 9185 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9186 SimpleRefExpr, RefRes.get()); 9187 if (!PostUpdateRes.isUsable()) 9188 continue; 9189 ExprPostUpdates.push_back( 9190 IgnoredValueConversions(PostUpdateRes.get()).get()); 9191 } 9192 } 9193 } 9194 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 9195 Vars.push_back(VarsExpr); 9196 Privates.push_back(PrivateDRE); 9197 LHSs.push_back(LHSDRE); 9198 RHSs.push_back(RHSDRE); 9199 ReductionOps.push_back(ReductionOp.get()); 9200 } 9201 9202 if (Vars.empty()) 9203 return nullptr; 9204 9205 return OMPReductionClause::Create( 9206 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars, 9207 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates, 9208 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures), 9209 buildPostUpdate(*this, ExprPostUpdates)); 9210 } 9211 9212 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 9213 SourceLocation LinLoc) { 9214 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 9215 LinKind == OMPC_LINEAR_unknown) { 9216 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 9217 return true; 9218 } 9219 return false; 9220 } 9221 9222 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 9223 OpenMPLinearClauseKind LinKind, 9224 QualType Type) { 9225 auto *VD = dyn_cast_or_null<VarDecl>(D); 9226 // A variable must not have an incomplete type or a reference type. 9227 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 9228 return true; 9229 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 9230 !Type->isReferenceType()) { 9231 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 9232 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 9233 return true; 9234 } 9235 Type = Type.getNonReferenceType(); 9236 9237 // A list item must not be const-qualified. 9238 if (Type.isConstant(Context)) { 9239 Diag(ELoc, diag::err_omp_const_variable) 9240 << getOpenMPClauseName(OMPC_linear); 9241 if (D) { 9242 bool IsDecl = 9243 !VD || 9244 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9245 Diag(D->getLocation(), 9246 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9247 << D; 9248 } 9249 return true; 9250 } 9251 9252 // A list item must be of integral or pointer type. 9253 Type = Type.getUnqualifiedType().getCanonicalType(); 9254 const auto *Ty = Type.getTypePtrOrNull(); 9255 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 9256 !Ty->isPointerType())) { 9257 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 9258 if (D) { 9259 bool IsDecl = 9260 !VD || 9261 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9262 Diag(D->getLocation(), 9263 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9264 << D; 9265 } 9266 return true; 9267 } 9268 return false; 9269 } 9270 9271 OMPClause *Sema::ActOnOpenMPLinearClause( 9272 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 9273 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 9274 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9275 SmallVector<Expr *, 8> Vars; 9276 SmallVector<Expr *, 8> Privates; 9277 SmallVector<Expr *, 8> Inits; 9278 SmallVector<Decl *, 4> ExprCaptures; 9279 SmallVector<Expr *, 4> ExprPostUpdates; 9280 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 9281 LinKind = OMPC_LINEAR_val; 9282 for (auto &RefExpr : VarList) { 9283 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9284 SourceLocation ELoc; 9285 SourceRange ERange; 9286 Expr *SimpleRefExpr = RefExpr; 9287 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9288 /*AllowArraySection=*/false); 9289 if (Res.second) { 9290 // It will be analyzed later. 9291 Vars.push_back(RefExpr); 9292 Privates.push_back(nullptr); 9293 Inits.push_back(nullptr); 9294 } 9295 ValueDecl *D = Res.first; 9296 if (!D) 9297 continue; 9298 9299 QualType Type = D->getType(); 9300 auto *VD = dyn_cast<VarDecl>(D); 9301 9302 // OpenMP [2.14.3.7, linear clause] 9303 // A list-item cannot appear in more than one linear clause. 9304 // A list-item that appears in a linear clause cannot appear in any 9305 // other data-sharing attribute clause. 9306 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9307 if (DVar.RefExpr) { 9308 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9309 << getOpenMPClauseName(OMPC_linear); 9310 ReportOriginalDSA(*this, DSAStack, D, DVar); 9311 continue; 9312 } 9313 9314 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 9315 continue; 9316 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9317 9318 // Build private copy of original var. 9319 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 9320 D->hasAttrs() ? &D->getAttrs() : nullptr); 9321 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 9322 // Build var to save initial value. 9323 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 9324 Expr *InitExpr; 9325 DeclRefExpr *Ref = nullptr; 9326 if (!VD && !CurContext->isDependentContext()) { 9327 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9328 if (!IsOpenMPCapturedDecl(D)) { 9329 ExprCaptures.push_back(Ref->getDecl()); 9330 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9331 ExprResult RefRes = DefaultLvalueConversion(Ref); 9332 if (!RefRes.isUsable()) 9333 continue; 9334 ExprResult PostUpdateRes = 9335 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9336 SimpleRefExpr, RefRes.get()); 9337 if (!PostUpdateRes.isUsable()) 9338 continue; 9339 ExprPostUpdates.push_back( 9340 IgnoredValueConversions(PostUpdateRes.get()).get()); 9341 } 9342 } 9343 } 9344 if (LinKind == OMPC_LINEAR_uval) 9345 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 9346 else 9347 InitExpr = VD ? SimpleRefExpr : Ref; 9348 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 9349 /*DirectInit=*/false); 9350 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 9351 9352 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 9353 Vars.push_back((VD || CurContext->isDependentContext()) 9354 ? RefExpr->IgnoreParens() 9355 : Ref); 9356 Privates.push_back(PrivateRef); 9357 Inits.push_back(InitRef); 9358 } 9359 9360 if (Vars.empty()) 9361 return nullptr; 9362 9363 Expr *StepExpr = Step; 9364 Expr *CalcStepExpr = nullptr; 9365 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 9366 !Step->isInstantiationDependent() && 9367 !Step->containsUnexpandedParameterPack()) { 9368 SourceLocation StepLoc = Step->getLocStart(); 9369 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 9370 if (Val.isInvalid()) 9371 return nullptr; 9372 StepExpr = Val.get(); 9373 9374 // Build var to save the step value. 9375 VarDecl *SaveVar = 9376 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 9377 ExprResult SaveRef = 9378 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 9379 ExprResult CalcStep = 9380 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 9381 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 9382 9383 // Warn about zero linear step (it would be probably better specified as 9384 // making corresponding variables 'const'). 9385 llvm::APSInt Result; 9386 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 9387 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 9388 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 9389 << (Vars.size() > 1); 9390 if (!IsConstant && CalcStep.isUsable()) { 9391 // Calculate the step beforehand instead of doing this on each iteration. 9392 // (This is not used if the number of iterations may be kfold-ed). 9393 CalcStepExpr = CalcStep.get(); 9394 } 9395 } 9396 9397 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 9398 ColonLoc, EndLoc, Vars, Privates, Inits, 9399 StepExpr, CalcStepExpr, 9400 buildPreInits(Context, ExprCaptures), 9401 buildPostUpdate(*this, ExprPostUpdates)); 9402 } 9403 9404 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 9405 Expr *NumIterations, Sema &SemaRef, 9406 Scope *S, DSAStackTy *Stack) { 9407 // Walk the vars and build update/final expressions for the CodeGen. 9408 SmallVector<Expr *, 8> Updates; 9409 SmallVector<Expr *, 8> Finals; 9410 Expr *Step = Clause.getStep(); 9411 Expr *CalcStep = Clause.getCalcStep(); 9412 // OpenMP [2.14.3.7, linear clause] 9413 // If linear-step is not specified it is assumed to be 1. 9414 if (Step == nullptr) 9415 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9416 else if (CalcStep) { 9417 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 9418 } 9419 bool HasErrors = false; 9420 auto CurInit = Clause.inits().begin(); 9421 auto CurPrivate = Clause.privates().begin(); 9422 auto LinKind = Clause.getModifier(); 9423 for (auto &RefExpr : Clause.varlists()) { 9424 SourceLocation ELoc; 9425 SourceRange ERange; 9426 Expr *SimpleRefExpr = RefExpr; 9427 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 9428 /*AllowArraySection=*/false); 9429 ValueDecl *D = Res.first; 9430 if (Res.second || !D) { 9431 Updates.push_back(nullptr); 9432 Finals.push_back(nullptr); 9433 HasErrors = true; 9434 continue; 9435 } 9436 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) { 9437 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts()) 9438 ->getMemberDecl(); 9439 } 9440 auto &&Info = Stack->isLoopControlVariable(D); 9441 Expr *InitExpr = *CurInit; 9442 9443 // Build privatized reference to the current linear var. 9444 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 9445 Expr *CapturedRef; 9446 if (LinKind == OMPC_LINEAR_uval) 9447 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 9448 else 9449 CapturedRef = 9450 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 9451 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 9452 /*RefersToCapture=*/true); 9453 9454 // Build update: Var = InitExpr + IV * Step 9455 ExprResult Update; 9456 if (!Info.first) { 9457 Update = 9458 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 9459 InitExpr, IV, Step, /* Subtract */ false); 9460 } else 9461 Update = *CurPrivate; 9462 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 9463 /*DiscardedValue=*/true); 9464 9465 // Build final: Var = InitExpr + NumIterations * Step 9466 ExprResult Final; 9467 if (!Info.first) { 9468 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 9469 InitExpr, NumIterations, Step, 9470 /* Subtract */ false); 9471 } else 9472 Final = *CurPrivate; 9473 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 9474 /*DiscardedValue=*/true); 9475 9476 if (!Update.isUsable() || !Final.isUsable()) { 9477 Updates.push_back(nullptr); 9478 Finals.push_back(nullptr); 9479 HasErrors = true; 9480 } else { 9481 Updates.push_back(Update.get()); 9482 Finals.push_back(Final.get()); 9483 } 9484 ++CurInit; 9485 ++CurPrivate; 9486 } 9487 Clause.setUpdates(Updates); 9488 Clause.setFinals(Finals); 9489 return HasErrors; 9490 } 9491 9492 OMPClause *Sema::ActOnOpenMPAlignedClause( 9493 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 9494 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9495 9496 SmallVector<Expr *, 8> Vars; 9497 for (auto &RefExpr : VarList) { 9498 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9499 SourceLocation ELoc; 9500 SourceRange ERange; 9501 Expr *SimpleRefExpr = RefExpr; 9502 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9503 /*AllowArraySection=*/false); 9504 if (Res.second) { 9505 // It will be analyzed later. 9506 Vars.push_back(RefExpr); 9507 } 9508 ValueDecl *D = Res.first; 9509 if (!D) 9510 continue; 9511 9512 QualType QType = D->getType(); 9513 auto *VD = dyn_cast<VarDecl>(D); 9514 9515 // OpenMP [2.8.1, simd construct, Restrictions] 9516 // The type of list items appearing in the aligned clause must be 9517 // array, pointer, reference to array, or reference to pointer. 9518 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9519 const Type *Ty = QType.getTypePtrOrNull(); 9520 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 9521 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 9522 << QType << getLangOpts().CPlusPlus << ERange; 9523 bool IsDecl = 9524 !VD || 9525 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9526 Diag(D->getLocation(), 9527 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9528 << D; 9529 continue; 9530 } 9531 9532 // OpenMP [2.8.1, simd construct, Restrictions] 9533 // A list-item cannot appear in more than one aligned clause. 9534 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 9535 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 9536 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 9537 << getOpenMPClauseName(OMPC_aligned); 9538 continue; 9539 } 9540 9541 DeclRefExpr *Ref = nullptr; 9542 if (!VD && IsOpenMPCapturedDecl(D)) 9543 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9544 Vars.push_back(DefaultFunctionArrayConversion( 9545 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 9546 .get()); 9547 } 9548 9549 // OpenMP [2.8.1, simd construct, Description] 9550 // The parameter of the aligned clause, alignment, must be a constant 9551 // positive integer expression. 9552 // If no optional parameter is specified, implementation-defined default 9553 // alignments for SIMD instructions on the target platforms are assumed. 9554 if (Alignment != nullptr) { 9555 ExprResult AlignResult = 9556 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 9557 if (AlignResult.isInvalid()) 9558 return nullptr; 9559 Alignment = AlignResult.get(); 9560 } 9561 if (Vars.empty()) 9562 return nullptr; 9563 9564 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 9565 EndLoc, Vars, Alignment); 9566 } 9567 9568 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 9569 SourceLocation StartLoc, 9570 SourceLocation LParenLoc, 9571 SourceLocation EndLoc) { 9572 SmallVector<Expr *, 8> Vars; 9573 SmallVector<Expr *, 8> SrcExprs; 9574 SmallVector<Expr *, 8> DstExprs; 9575 SmallVector<Expr *, 8> AssignmentOps; 9576 for (auto &RefExpr : VarList) { 9577 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 9578 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 9579 // It will be analyzed later. 9580 Vars.push_back(RefExpr); 9581 SrcExprs.push_back(nullptr); 9582 DstExprs.push_back(nullptr); 9583 AssignmentOps.push_back(nullptr); 9584 continue; 9585 } 9586 9587 SourceLocation ELoc = RefExpr->getExprLoc(); 9588 // OpenMP [2.1, C/C++] 9589 // A list item is a variable name. 9590 // OpenMP [2.14.4.1, Restrictions, p.1] 9591 // A list item that appears in a copyin clause must be threadprivate. 9592 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 9593 if (!DE || !isa<VarDecl>(DE->getDecl())) { 9594 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 9595 << 0 << RefExpr->getSourceRange(); 9596 continue; 9597 } 9598 9599 Decl *D = DE->getDecl(); 9600 VarDecl *VD = cast<VarDecl>(D); 9601 9602 QualType Type = VD->getType(); 9603 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 9604 // It will be analyzed later. 9605 Vars.push_back(DE); 9606 SrcExprs.push_back(nullptr); 9607 DstExprs.push_back(nullptr); 9608 AssignmentOps.push_back(nullptr); 9609 continue; 9610 } 9611 9612 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 9613 // A list item that appears in a copyin clause must be threadprivate. 9614 if (!DSAStack->isThreadPrivate(VD)) { 9615 Diag(ELoc, diag::err_omp_required_access) 9616 << getOpenMPClauseName(OMPC_copyin) 9617 << getOpenMPDirectiveName(OMPD_threadprivate); 9618 continue; 9619 } 9620 9621 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9622 // A variable of class type (or array thereof) that appears in a 9623 // copyin clause requires an accessible, unambiguous copy assignment 9624 // operator for the class type. 9625 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 9626 auto *SrcVD = 9627 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 9628 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9629 auto *PseudoSrcExpr = buildDeclRefExpr( 9630 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 9631 auto *DstVD = 9632 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 9633 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9634 auto *PseudoDstExpr = 9635 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 9636 // For arrays generate assignment operation for single element and replace 9637 // it by the original array element in CodeGen. 9638 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 9639 PseudoDstExpr, PseudoSrcExpr); 9640 if (AssignmentOp.isInvalid()) 9641 continue; 9642 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 9643 /*DiscardedValue=*/true); 9644 if (AssignmentOp.isInvalid()) 9645 continue; 9646 9647 DSAStack->addDSA(VD, DE, OMPC_copyin); 9648 Vars.push_back(DE); 9649 SrcExprs.push_back(PseudoSrcExpr); 9650 DstExprs.push_back(PseudoDstExpr); 9651 AssignmentOps.push_back(AssignmentOp.get()); 9652 } 9653 9654 if (Vars.empty()) 9655 return nullptr; 9656 9657 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 9658 SrcExprs, DstExprs, AssignmentOps); 9659 } 9660 9661 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 9662 SourceLocation StartLoc, 9663 SourceLocation LParenLoc, 9664 SourceLocation EndLoc) { 9665 SmallVector<Expr *, 8> Vars; 9666 SmallVector<Expr *, 8> SrcExprs; 9667 SmallVector<Expr *, 8> DstExprs; 9668 SmallVector<Expr *, 8> AssignmentOps; 9669 for (auto &RefExpr : VarList) { 9670 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9671 SourceLocation ELoc; 9672 SourceRange ERange; 9673 Expr *SimpleRefExpr = RefExpr; 9674 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9675 /*AllowArraySection=*/false); 9676 if (Res.second) { 9677 // It will be analyzed later. 9678 Vars.push_back(RefExpr); 9679 SrcExprs.push_back(nullptr); 9680 DstExprs.push_back(nullptr); 9681 AssignmentOps.push_back(nullptr); 9682 } 9683 ValueDecl *D = Res.first; 9684 if (!D) 9685 continue; 9686 9687 QualType Type = D->getType(); 9688 auto *VD = dyn_cast<VarDecl>(D); 9689 9690 // OpenMP [2.14.4.2, Restrictions, p.2] 9691 // A list item that appears in a copyprivate clause may not appear in a 9692 // private or firstprivate clause on the single construct. 9693 if (!VD || !DSAStack->isThreadPrivate(VD)) { 9694 auto DVar = DSAStack->getTopDSA(D, false); 9695 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 9696 DVar.RefExpr) { 9697 Diag(ELoc, diag::err_omp_wrong_dsa) 9698 << getOpenMPClauseName(DVar.CKind) 9699 << getOpenMPClauseName(OMPC_copyprivate); 9700 ReportOriginalDSA(*this, DSAStack, D, DVar); 9701 continue; 9702 } 9703 9704 // OpenMP [2.11.4.2, Restrictions, p.1] 9705 // All list items that appear in a copyprivate clause must be either 9706 // threadprivate or private in the enclosing context. 9707 if (DVar.CKind == OMPC_unknown) { 9708 DVar = DSAStack->getImplicitDSA(D, false); 9709 if (DVar.CKind == OMPC_shared) { 9710 Diag(ELoc, diag::err_omp_required_access) 9711 << getOpenMPClauseName(OMPC_copyprivate) 9712 << "threadprivate or private in the enclosing context"; 9713 ReportOriginalDSA(*this, DSAStack, D, DVar); 9714 continue; 9715 } 9716 } 9717 } 9718 9719 // Variably modified types are not supported. 9720 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 9721 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9722 << getOpenMPClauseName(OMPC_copyprivate) << Type 9723 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 9724 bool IsDecl = 9725 !VD || 9726 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9727 Diag(D->getLocation(), 9728 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9729 << D; 9730 continue; 9731 } 9732 9733 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9734 // A variable of class type (or array thereof) that appears in a 9735 // copyin clause requires an accessible, unambiguous copy assignment 9736 // operator for the class type. 9737 Type = Context.getBaseElementType(Type.getNonReferenceType()) 9738 .getUnqualifiedType(); 9739 auto *SrcVD = 9740 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 9741 D->hasAttrs() ? &D->getAttrs() : nullptr); 9742 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 9743 auto *DstVD = 9744 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 9745 D->hasAttrs() ? &D->getAttrs() : nullptr); 9746 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 9747 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9748 PseudoDstExpr, PseudoSrcExpr); 9749 if (AssignmentOp.isInvalid()) 9750 continue; 9751 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 9752 /*DiscardedValue=*/true); 9753 if (AssignmentOp.isInvalid()) 9754 continue; 9755 9756 // No need to mark vars as copyprivate, they are already threadprivate or 9757 // implicitly private. 9758 assert(VD || IsOpenMPCapturedDecl(D)); 9759 Vars.push_back( 9760 VD ? RefExpr->IgnoreParens() 9761 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 9762 SrcExprs.push_back(PseudoSrcExpr); 9763 DstExprs.push_back(PseudoDstExpr); 9764 AssignmentOps.push_back(AssignmentOp.get()); 9765 } 9766 9767 if (Vars.empty()) 9768 return nullptr; 9769 9770 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9771 Vars, SrcExprs, DstExprs, AssignmentOps); 9772 } 9773 9774 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 9775 SourceLocation StartLoc, 9776 SourceLocation LParenLoc, 9777 SourceLocation EndLoc) { 9778 if (VarList.empty()) 9779 return nullptr; 9780 9781 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 9782 } 9783 9784 OMPClause * 9785 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 9786 SourceLocation DepLoc, SourceLocation ColonLoc, 9787 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 9788 SourceLocation LParenLoc, SourceLocation EndLoc) { 9789 if (DSAStack->getCurrentDirective() == OMPD_ordered && 9790 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 9791 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 9792 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 9793 return nullptr; 9794 } 9795 if (DSAStack->getCurrentDirective() != OMPD_ordered && 9796 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 9797 DepKind == OMPC_DEPEND_sink)) { 9798 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 9799 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 9800 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 9801 /*Last=*/OMPC_DEPEND_unknown, Except) 9802 << getOpenMPClauseName(OMPC_depend); 9803 return nullptr; 9804 } 9805 SmallVector<Expr *, 8> Vars; 9806 DSAStackTy::OperatorOffsetTy OpsOffs; 9807 llvm::APSInt DepCounter(/*BitWidth=*/32); 9808 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 9809 if (DepKind == OMPC_DEPEND_sink) { 9810 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 9811 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 9812 TotalDepCount.setIsUnsigned(/*Val=*/true); 9813 } 9814 } 9815 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || 9816 DSAStack->getParentOrderedRegionParam()) { 9817 for (auto &RefExpr : VarList) { 9818 assert(RefExpr && "NULL expr in OpenMP shared clause."); 9819 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 9820 // It will be analyzed later. 9821 Vars.push_back(RefExpr); 9822 continue; 9823 } 9824 9825 SourceLocation ELoc = RefExpr->getExprLoc(); 9826 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 9827 if (DepKind == OMPC_DEPEND_sink) { 9828 if (DepCounter >= TotalDepCount) { 9829 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 9830 continue; 9831 } 9832 ++DepCounter; 9833 // OpenMP [2.13.9, Summary] 9834 // depend(dependence-type : vec), where dependence-type is: 9835 // 'sink' and where vec is the iteration vector, which has the form: 9836 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 9837 // where n is the value specified by the ordered clause in the loop 9838 // directive, xi denotes the loop iteration variable of the i-th nested 9839 // loop associated with the loop directive, and di is a constant 9840 // non-negative integer. 9841 if (CurContext->isDependentContext()) { 9842 // It will be analyzed later. 9843 Vars.push_back(RefExpr); 9844 continue; 9845 } 9846 SimpleExpr = SimpleExpr->IgnoreImplicit(); 9847 OverloadedOperatorKind OOK = OO_None; 9848 SourceLocation OOLoc; 9849 Expr *LHS = SimpleExpr; 9850 Expr *RHS = nullptr; 9851 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 9852 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 9853 OOLoc = BO->getOperatorLoc(); 9854 LHS = BO->getLHS()->IgnoreParenImpCasts(); 9855 RHS = BO->getRHS()->IgnoreParenImpCasts(); 9856 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 9857 OOK = OCE->getOperator(); 9858 OOLoc = OCE->getOperatorLoc(); 9859 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 9860 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 9861 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 9862 OOK = MCE->getMethodDecl() 9863 ->getNameInfo() 9864 .getName() 9865 .getCXXOverloadedOperator(); 9866 OOLoc = MCE->getCallee()->getExprLoc(); 9867 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 9868 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 9869 } 9870 SourceLocation ELoc; 9871 SourceRange ERange; 9872 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 9873 /*AllowArraySection=*/false); 9874 if (Res.second) { 9875 // It will be analyzed later. 9876 Vars.push_back(RefExpr); 9877 } 9878 ValueDecl *D = Res.first; 9879 if (!D) 9880 continue; 9881 9882 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 9883 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 9884 continue; 9885 } 9886 if (RHS) { 9887 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 9888 RHS, OMPC_depend, /*StrictlyPositive=*/false); 9889 if (RHSRes.isInvalid()) 9890 continue; 9891 } 9892 if (!CurContext->isDependentContext() && 9893 DSAStack->getParentOrderedRegionParam() && 9894 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 9895 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 9896 << DSAStack->getParentLoopControlVariable( 9897 DepCounter.getZExtValue()); 9898 continue; 9899 } 9900 OpsOffs.push_back({RHS, OOK}); 9901 } else { 9902 // OpenMP [2.11.1.1, Restrictions, p.3] 9903 // A variable that is part of another variable (such as a field of a 9904 // structure) but is not an array element or an array section cannot 9905 // appear in a depend clause. 9906 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr); 9907 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 9908 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 9909 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 9910 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) || 9911 (ASE && 9912 !ASE->getBase() 9913 ->getType() 9914 .getNonReferenceType() 9915 ->isPointerType() && 9916 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 9917 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item) 9918 << 0 << RefExpr->getSourceRange(); 9919 continue; 9920 } 9921 } 9922 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 9923 } 9924 9925 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 9926 TotalDepCount > VarList.size() && 9927 DSAStack->getParentOrderedRegionParam()) { 9928 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 9929 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 9930 } 9931 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 9932 Vars.empty()) 9933 return nullptr; 9934 } 9935 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9936 DepKind, DepLoc, ColonLoc, Vars); 9937 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) 9938 DSAStack->addDoacrossDependClause(C, OpsOffs); 9939 return C; 9940 } 9941 9942 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 9943 SourceLocation LParenLoc, 9944 SourceLocation EndLoc) { 9945 Expr *ValExpr = Device; 9946 9947 // OpenMP [2.9.1, Restrictions] 9948 // The device expression must evaluate to a non-negative integer value. 9949 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 9950 /*StrictlyPositive=*/false)) 9951 return nullptr; 9952 9953 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc); 9954 } 9955 9956 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc, 9957 DSAStackTy *Stack, CXXRecordDecl *RD) { 9958 if (!RD || RD->isInvalidDecl()) 9959 return true; 9960 9961 auto QTy = SemaRef.Context.getRecordType(RD); 9962 if (RD->isDynamicClass()) { 9963 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 9964 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target); 9965 return false; 9966 } 9967 auto *DC = RD; 9968 bool IsCorrect = true; 9969 for (auto *I : DC->decls()) { 9970 if (I) { 9971 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) { 9972 if (MD->isStatic()) { 9973 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 9974 SemaRef.Diag(MD->getLocation(), 9975 diag::note_omp_static_member_in_target); 9976 IsCorrect = false; 9977 } 9978 } else if (auto *VD = dyn_cast<VarDecl>(I)) { 9979 if (VD->isStaticDataMember()) { 9980 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 9981 SemaRef.Diag(VD->getLocation(), 9982 diag::note_omp_static_member_in_target); 9983 IsCorrect = false; 9984 } 9985 } 9986 } 9987 } 9988 9989 for (auto &I : RD->bases()) { 9990 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack, 9991 I.getType()->getAsCXXRecordDecl())) 9992 IsCorrect = false; 9993 } 9994 return IsCorrect; 9995 } 9996 9997 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 9998 DSAStackTy *Stack, QualType QTy) { 9999 NamedDecl *ND; 10000 if (QTy->isIncompleteType(&ND)) { 10001 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 10002 return false; 10003 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) { 10004 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD)) 10005 return false; 10006 } 10007 return true; 10008 } 10009 10010 /// \brief Return true if it can be proven that the provided array expression 10011 /// (array section or array subscript) does NOT specify the whole size of the 10012 /// array whose base type is \a BaseQTy. 10013 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 10014 const Expr *E, 10015 QualType BaseQTy) { 10016 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10017 10018 // If this is an array subscript, it refers to the whole size if the size of 10019 // the dimension is constant and equals 1. Also, an array section assumes the 10020 // format of an array subscript if no colon is used. 10021 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 10022 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10023 return ATy->getSize().getSExtValue() != 1; 10024 // Size can't be evaluated statically. 10025 return false; 10026 } 10027 10028 assert(OASE && "Expecting array section if not an array subscript."); 10029 auto *LowerBound = OASE->getLowerBound(); 10030 auto *Length = OASE->getLength(); 10031 10032 // If there is a lower bound that does not evaluates to zero, we are not 10033 // covering the whole dimension. 10034 if (LowerBound) { 10035 llvm::APSInt ConstLowerBound; 10036 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 10037 return false; // Can't get the integer value as a constant. 10038 if (ConstLowerBound.getSExtValue()) 10039 return true; 10040 } 10041 10042 // If we don't have a length we covering the whole dimension. 10043 if (!Length) 10044 return false; 10045 10046 // If the base is a pointer, we don't have a way to get the size of the 10047 // pointee. 10048 if (BaseQTy->isPointerType()) 10049 return false; 10050 10051 // We can only check if the length is the same as the size of the dimension 10052 // if we have a constant array. 10053 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 10054 if (!CATy) 10055 return false; 10056 10057 llvm::APSInt ConstLength; 10058 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10059 return false; // Can't get the integer value as a constant. 10060 10061 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 10062 } 10063 10064 // Return true if it can be proven that the provided array expression (array 10065 // section or array subscript) does NOT specify a single element of the array 10066 // whose base type is \a BaseQTy. 10067 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 10068 const Expr *E, 10069 QualType BaseQTy) { 10070 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10071 10072 // An array subscript always refer to a single element. Also, an array section 10073 // assumes the format of an array subscript if no colon is used. 10074 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 10075 return false; 10076 10077 assert(OASE && "Expecting array section if not an array subscript."); 10078 auto *Length = OASE->getLength(); 10079 10080 // If we don't have a length we have to check if the array has unitary size 10081 // for this dimension. Also, we should always expect a length if the base type 10082 // is pointer. 10083 if (!Length) { 10084 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10085 return ATy->getSize().getSExtValue() != 1; 10086 // We cannot assume anything. 10087 return false; 10088 } 10089 10090 // Check if the length evaluates to 1. 10091 llvm::APSInt ConstLength; 10092 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10093 return false; // Can't get the integer value as a constant. 10094 10095 return ConstLength.getSExtValue() != 1; 10096 } 10097 10098 // Return the expression of the base of the mappable expression or null if it 10099 // cannot be determined and do all the necessary checks to see if the expression 10100 // is valid as a standalone mappable expression. In the process, record all the 10101 // components of the expression. 10102 static Expr *CheckMapClauseExpressionBase( 10103 Sema &SemaRef, Expr *E, 10104 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 10105 OpenMPClauseKind CKind) { 10106 SourceLocation ELoc = E->getExprLoc(); 10107 SourceRange ERange = E->getSourceRange(); 10108 10109 // The base of elements of list in a map clause have to be either: 10110 // - a reference to variable or field. 10111 // - a member expression. 10112 // - an array expression. 10113 // 10114 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 10115 // reference to 'r'. 10116 // 10117 // If we have: 10118 // 10119 // struct SS { 10120 // Bla S; 10121 // foo() { 10122 // #pragma omp target map (S.Arr[:12]); 10123 // } 10124 // } 10125 // 10126 // We want to retrieve the member expression 'this->S'; 10127 10128 Expr *RelevantExpr = nullptr; 10129 10130 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 10131 // If a list item is an array section, it must specify contiguous storage. 10132 // 10133 // For this restriction it is sufficient that we make sure only references 10134 // to variables or fields and array expressions, and that no array sections 10135 // exist except in the rightmost expression (unless they cover the whole 10136 // dimension of the array). E.g. these would be invalid: 10137 // 10138 // r.ArrS[3:5].Arr[6:7] 10139 // 10140 // r.ArrS[3:5].x 10141 // 10142 // but these would be valid: 10143 // r.ArrS[3].Arr[6:7] 10144 // 10145 // r.ArrS[3].x 10146 10147 bool AllowUnitySizeArraySection = true; 10148 bool AllowWholeSizeArraySection = true; 10149 10150 while (!RelevantExpr) { 10151 E = E->IgnoreParenImpCasts(); 10152 10153 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 10154 if (!isa<VarDecl>(CurE->getDecl())) 10155 break; 10156 10157 RelevantExpr = CurE; 10158 10159 // If we got a reference to a declaration, we should not expect any array 10160 // section before that. 10161 AllowUnitySizeArraySection = false; 10162 AllowWholeSizeArraySection = false; 10163 10164 // Record the component. 10165 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent( 10166 CurE, CurE->getDecl())); 10167 continue; 10168 } 10169 10170 if (auto *CurE = dyn_cast<MemberExpr>(E)) { 10171 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 10172 10173 if (isa<CXXThisExpr>(BaseE)) 10174 // We found a base expression: this->Val. 10175 RelevantExpr = CurE; 10176 else 10177 E = BaseE; 10178 10179 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 10180 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 10181 << CurE->getSourceRange(); 10182 break; 10183 } 10184 10185 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 10186 10187 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 10188 // A bit-field cannot appear in a map clause. 10189 // 10190 if (FD->isBitField()) { 10191 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 10192 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 10193 break; 10194 } 10195 10196 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10197 // If the type of a list item is a reference to a type T then the type 10198 // will be considered to be T for all purposes of this clause. 10199 QualType CurType = BaseE->getType().getNonReferenceType(); 10200 10201 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 10202 // A list item cannot be a variable that is a member of a structure with 10203 // a union type. 10204 // 10205 if (auto *RT = CurType->getAs<RecordType>()) 10206 if (RT->isUnionType()) { 10207 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 10208 << CurE->getSourceRange(); 10209 break; 10210 } 10211 10212 // If we got a member expression, we should not expect any array section 10213 // before that: 10214 // 10215 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 10216 // If a list item is an element of a structure, only the rightmost symbol 10217 // of the variable reference can be an array section. 10218 // 10219 AllowUnitySizeArraySection = false; 10220 AllowWholeSizeArraySection = false; 10221 10222 // Record the component. 10223 CurComponents.push_back( 10224 OMPClauseMappableExprCommon::MappableComponent(CurE, FD)); 10225 continue; 10226 } 10227 10228 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 10229 E = CurE->getBase()->IgnoreParenImpCasts(); 10230 10231 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 10232 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10233 << 0 << CurE->getSourceRange(); 10234 break; 10235 } 10236 10237 // If we got an array subscript that express the whole dimension we 10238 // can have any array expressions before. If it only expressing part of 10239 // the dimension, we can only have unitary-size array expressions. 10240 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 10241 E->getType())) 10242 AllowWholeSizeArraySection = false; 10243 10244 // Record the component - we don't have any declaration associated. 10245 CurComponents.push_back( 10246 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10247 continue; 10248 } 10249 10250 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 10251 E = CurE->getBase()->IgnoreParenImpCasts(); 10252 10253 auto CurType = 10254 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10255 10256 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10257 // If the type of a list item is a reference to a type T then the type 10258 // will be considered to be T for all purposes of this clause. 10259 if (CurType->isReferenceType()) 10260 CurType = CurType->getPointeeType(); 10261 10262 bool IsPointer = CurType->isAnyPointerType(); 10263 10264 if (!IsPointer && !CurType->isArrayType()) { 10265 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10266 << 0 << CurE->getSourceRange(); 10267 break; 10268 } 10269 10270 bool NotWhole = 10271 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 10272 bool NotUnity = 10273 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 10274 10275 if (AllowWholeSizeArraySection) { 10276 // Any array section is currently allowed. Allowing a whole size array 10277 // section implies allowing a unity array section as well. 10278 // 10279 // If this array section refers to the whole dimension we can still 10280 // accept other array sections before this one, except if the base is a 10281 // pointer. Otherwise, only unitary sections are accepted. 10282 if (NotWhole || IsPointer) 10283 AllowWholeSizeArraySection = false; 10284 } else if (AllowUnitySizeArraySection && NotUnity) { 10285 // A unity or whole array section is not allowed and that is not 10286 // compatible with the properties of the current array section. 10287 SemaRef.Diag( 10288 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 10289 << CurE->getSourceRange(); 10290 break; 10291 } 10292 10293 // Record the component - we don't have any declaration associated. 10294 CurComponents.push_back( 10295 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10296 continue; 10297 } 10298 10299 // If nothing else worked, this is not a valid map clause expression. 10300 SemaRef.Diag(ELoc, 10301 diag::err_omp_expected_named_var_member_or_array_expression) 10302 << ERange; 10303 break; 10304 } 10305 10306 return RelevantExpr; 10307 } 10308 10309 // Return true if expression E associated with value VD has conflicts with other 10310 // map information. 10311 static bool CheckMapConflicts( 10312 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 10313 bool CurrentRegionOnly, 10314 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 10315 OpenMPClauseKind CKind) { 10316 assert(VD && E); 10317 SourceLocation ELoc = E->getExprLoc(); 10318 SourceRange ERange = E->getSourceRange(); 10319 10320 // In order to easily check the conflicts we need to match each component of 10321 // the expression under test with the components of the expressions that are 10322 // already in the stack. 10323 10324 assert(!CurComponents.empty() && "Map clause expression with no components!"); 10325 assert(CurComponents.back().getAssociatedDeclaration() == VD && 10326 "Map clause expression with unexpected base!"); 10327 10328 // Variables to help detecting enclosing problems in data environment nests. 10329 bool IsEnclosedByDataEnvironmentExpr = false; 10330 const Expr *EnclosingExpr = nullptr; 10331 10332 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 10333 VD, CurrentRegionOnly, 10334 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 10335 StackComponents, 10336 OpenMPClauseKind) -> bool { 10337 10338 assert(!StackComponents.empty() && 10339 "Map clause expression with no components!"); 10340 assert(StackComponents.back().getAssociatedDeclaration() == VD && 10341 "Map clause expression with unexpected base!"); 10342 10343 // The whole expression in the stack. 10344 auto *RE = StackComponents.front().getAssociatedExpression(); 10345 10346 // Expressions must start from the same base. Here we detect at which 10347 // point both expressions diverge from each other and see if we can 10348 // detect if the memory referred to both expressions is contiguous and 10349 // do not overlap. 10350 auto CI = CurComponents.rbegin(); 10351 auto CE = CurComponents.rend(); 10352 auto SI = StackComponents.rbegin(); 10353 auto SE = StackComponents.rend(); 10354 for (; CI != CE && SI != SE; ++CI, ++SI) { 10355 10356 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 10357 // At most one list item can be an array item derived from a given 10358 // variable in map clauses of the same construct. 10359 if (CurrentRegionOnly && 10360 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 10361 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 10362 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 10363 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 10364 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 10365 diag::err_omp_multiple_array_items_in_map_clause) 10366 << CI->getAssociatedExpression()->getSourceRange(); 10367 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 10368 diag::note_used_here) 10369 << SI->getAssociatedExpression()->getSourceRange(); 10370 return true; 10371 } 10372 10373 // Do both expressions have the same kind? 10374 if (CI->getAssociatedExpression()->getStmtClass() != 10375 SI->getAssociatedExpression()->getStmtClass()) 10376 break; 10377 10378 // Are we dealing with different variables/fields? 10379 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 10380 break; 10381 } 10382 // Check if the extra components of the expressions in the enclosing 10383 // data environment are redundant for the current base declaration. 10384 // If they are, the maps completely overlap, which is legal. 10385 for (; SI != SE; ++SI) { 10386 QualType Type; 10387 if (auto *ASE = 10388 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 10389 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 10390 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>( 10391 SI->getAssociatedExpression())) { 10392 auto *E = OASE->getBase()->IgnoreParenImpCasts(); 10393 Type = 10394 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10395 } 10396 if (Type.isNull() || Type->isAnyPointerType() || 10397 CheckArrayExpressionDoesNotReferToWholeSize( 10398 SemaRef, SI->getAssociatedExpression(), Type)) 10399 break; 10400 } 10401 10402 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10403 // List items of map clauses in the same construct must not share 10404 // original storage. 10405 // 10406 // If the expressions are exactly the same or one is a subset of the 10407 // other, it means they are sharing storage. 10408 if (CI == CE && SI == SE) { 10409 if (CurrentRegionOnly) { 10410 if (CKind == OMPC_map) 10411 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10412 else { 10413 assert(CKind == OMPC_to || CKind == OMPC_from); 10414 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10415 << ERange; 10416 } 10417 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10418 << RE->getSourceRange(); 10419 return true; 10420 } else { 10421 // If we find the same expression in the enclosing data environment, 10422 // that is legal. 10423 IsEnclosedByDataEnvironmentExpr = true; 10424 return false; 10425 } 10426 } 10427 10428 QualType DerivedType = 10429 std::prev(CI)->getAssociatedDeclaration()->getType(); 10430 SourceLocation DerivedLoc = 10431 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 10432 10433 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10434 // If the type of a list item is a reference to a type T then the type 10435 // will be considered to be T for all purposes of this clause. 10436 DerivedType = DerivedType.getNonReferenceType(); 10437 10438 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 10439 // A variable for which the type is pointer and an array section 10440 // derived from that variable must not appear as list items of map 10441 // clauses of the same construct. 10442 // 10443 // Also, cover one of the cases in: 10444 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10445 // If any part of the original storage of a list item has corresponding 10446 // storage in the device data environment, all of the original storage 10447 // must have corresponding storage in the device data environment. 10448 // 10449 if (DerivedType->isAnyPointerType()) { 10450 if (CI == CE || SI == SE) { 10451 SemaRef.Diag( 10452 DerivedLoc, 10453 diag::err_omp_pointer_mapped_along_with_derived_section) 10454 << DerivedLoc; 10455 } else { 10456 assert(CI != CE && SI != SE); 10457 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) 10458 << DerivedLoc; 10459 } 10460 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10461 << RE->getSourceRange(); 10462 return true; 10463 } 10464 10465 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10466 // List items of map clauses in the same construct must not share 10467 // original storage. 10468 // 10469 // An expression is a subset of the other. 10470 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 10471 if (CKind == OMPC_map) 10472 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10473 else { 10474 assert(CKind == OMPC_to || CKind == OMPC_from); 10475 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10476 << ERange; 10477 } 10478 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10479 << RE->getSourceRange(); 10480 return true; 10481 } 10482 10483 // The current expression uses the same base as other expression in the 10484 // data environment but does not contain it completely. 10485 if (!CurrentRegionOnly && SI != SE) 10486 EnclosingExpr = RE; 10487 10488 // The current expression is a subset of the expression in the data 10489 // environment. 10490 IsEnclosedByDataEnvironmentExpr |= 10491 (!CurrentRegionOnly && CI != CE && SI == SE); 10492 10493 return false; 10494 }); 10495 10496 if (CurrentRegionOnly) 10497 return FoundError; 10498 10499 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10500 // If any part of the original storage of a list item has corresponding 10501 // storage in the device data environment, all of the original storage must 10502 // have corresponding storage in the device data environment. 10503 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 10504 // If a list item is an element of a structure, and a different element of 10505 // the structure has a corresponding list item in the device data environment 10506 // prior to a task encountering the construct associated with the map clause, 10507 // then the list item must also have a corresponding list item in the device 10508 // data environment prior to the task encountering the construct. 10509 // 10510 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 10511 SemaRef.Diag(ELoc, 10512 diag::err_omp_original_storage_is_shared_and_does_not_contain) 10513 << ERange; 10514 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 10515 << EnclosingExpr->getSourceRange(); 10516 return true; 10517 } 10518 10519 return FoundError; 10520 } 10521 10522 namespace { 10523 // Utility struct that gathers all the related lists associated with a mappable 10524 // expression. 10525 struct MappableVarListInfo final { 10526 // The list of expressions. 10527 ArrayRef<Expr *> VarList; 10528 // The list of processed expressions. 10529 SmallVector<Expr *, 16> ProcessedVarList; 10530 // The mappble components for each expression. 10531 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 10532 // The base declaration of the variable. 10533 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 10534 10535 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 10536 // We have a list of components and base declarations for each entry in the 10537 // variable list. 10538 VarComponents.reserve(VarList.size()); 10539 VarBaseDeclarations.reserve(VarList.size()); 10540 } 10541 }; 10542 } 10543 10544 // Check the validity of the provided variable list for the provided clause kind 10545 // \a CKind. In the check process the valid expressions, and mappable expression 10546 // components and variables are extracted and used to fill \a Vars, 10547 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 10548 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 10549 static void 10550 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 10551 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 10552 SourceLocation StartLoc, 10553 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 10554 bool IsMapTypeImplicit = false) { 10555 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 10556 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 10557 "Unexpected clause kind with mappable expressions!"); 10558 10559 // Keep track of the mappable components and base declarations in this clause. 10560 // Each entry in the list is going to have a list of components associated. We 10561 // record each set of the components so that we can build the clause later on. 10562 // In the end we should have the same amount of declarations and component 10563 // lists. 10564 10565 for (auto &RE : MVLI.VarList) { 10566 assert(RE && "Null expr in omp to/from/map clause"); 10567 SourceLocation ELoc = RE->getExprLoc(); 10568 10569 auto *VE = RE->IgnoreParenLValueCasts(); 10570 10571 if (VE->isValueDependent() || VE->isTypeDependent() || 10572 VE->isInstantiationDependent() || 10573 VE->containsUnexpandedParameterPack()) { 10574 // We can only analyze this information once the missing information is 10575 // resolved. 10576 MVLI.ProcessedVarList.push_back(RE); 10577 continue; 10578 } 10579 10580 auto *SimpleExpr = RE->IgnoreParenCasts(); 10581 10582 if (!RE->IgnoreParenImpCasts()->isLValue()) { 10583 SemaRef.Diag(ELoc, 10584 diag::err_omp_expected_named_var_member_or_array_expression) 10585 << RE->getSourceRange(); 10586 continue; 10587 } 10588 10589 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 10590 ValueDecl *CurDeclaration = nullptr; 10591 10592 // Obtain the array or member expression bases if required. Also, fill the 10593 // components array with all the components identified in the process. 10594 auto *BE = 10595 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind); 10596 if (!BE) 10597 continue; 10598 10599 assert(!CurComponents.empty() && 10600 "Invalid mappable expression information."); 10601 10602 // For the following checks, we rely on the base declaration which is 10603 // expected to be associated with the last component. The declaration is 10604 // expected to be a variable or a field (if 'this' is being mapped). 10605 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 10606 assert(CurDeclaration && "Null decl on map clause."); 10607 assert( 10608 CurDeclaration->isCanonicalDecl() && 10609 "Expecting components to have associated only canonical declarations."); 10610 10611 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 10612 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 10613 10614 assert((VD || FD) && "Only variables or fields are expected here!"); 10615 (void)FD; 10616 10617 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 10618 // threadprivate variables cannot appear in a map clause. 10619 // OpenMP 4.5 [2.10.5, target update Construct] 10620 // threadprivate variables cannot appear in a from clause. 10621 if (VD && DSAS->isThreadPrivate(VD)) { 10622 auto DVar = DSAS->getTopDSA(VD, false); 10623 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 10624 << getOpenMPClauseName(CKind); 10625 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 10626 continue; 10627 } 10628 10629 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10630 // A list item cannot appear in both a map clause and a data-sharing 10631 // attribute clause on the same construct. 10632 10633 // Check conflicts with other map clause expressions. We check the conflicts 10634 // with the current construct separately from the enclosing data 10635 // environment, because the restrictions are different. We only have to 10636 // check conflicts across regions for the map clauses. 10637 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10638 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 10639 break; 10640 if (CKind == OMPC_map && 10641 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10642 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 10643 break; 10644 10645 // OpenMP 4.5 [2.10.5, target update Construct] 10646 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10647 // If the type of a list item is a reference to a type T then the type will 10648 // be considered to be T for all purposes of this clause. 10649 QualType Type = CurDeclaration->getType().getNonReferenceType(); 10650 10651 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 10652 // A list item in a to or from clause must have a mappable type. 10653 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10654 // A list item must have a mappable type. 10655 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 10656 DSAS, Type)) 10657 continue; 10658 10659 if (CKind == OMPC_map) { 10660 // target enter data 10661 // OpenMP [2.10.2, Restrictions, p. 99] 10662 // A map-type must be specified in all map clauses and must be either 10663 // to or alloc. 10664 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 10665 if (DKind == OMPD_target_enter_data && 10666 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 10667 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 10668 << (IsMapTypeImplicit ? 1 : 0) 10669 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 10670 << getOpenMPDirectiveName(DKind); 10671 continue; 10672 } 10673 10674 // target exit_data 10675 // OpenMP [2.10.3, Restrictions, p. 102] 10676 // A map-type must be specified in all map clauses and must be either 10677 // from, release, or delete. 10678 if (DKind == OMPD_target_exit_data && 10679 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 10680 MapType == OMPC_MAP_delete)) { 10681 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 10682 << (IsMapTypeImplicit ? 1 : 0) 10683 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 10684 << getOpenMPDirectiveName(DKind); 10685 continue; 10686 } 10687 10688 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10689 // A list item cannot appear in both a map clause and a data-sharing 10690 // attribute clause on the same construct 10691 if ((DKind == OMPD_target || DKind == OMPD_target_teams || 10692 DKind == OMPD_target_teams_distribute || 10693 DKind == OMPD_target_teams_distribute_parallel_for || 10694 DKind == OMPD_target_teams_distribute_parallel_for_simd || 10695 DKind == OMPD_target_teams_distribute_simd) && VD) { 10696 auto DVar = DSAS->getTopDSA(VD, false); 10697 if (isOpenMPPrivate(DVar.CKind)) { 10698 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10699 << getOpenMPClauseName(DVar.CKind) 10700 << getOpenMPClauseName(OMPC_map) 10701 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 10702 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 10703 continue; 10704 } 10705 } 10706 } 10707 10708 // Save the current expression. 10709 MVLI.ProcessedVarList.push_back(RE); 10710 10711 // Store the components in the stack so that they can be used to check 10712 // against other clauses later on. 10713 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 10714 /*WhereFoundClauseKind=*/OMPC_map); 10715 10716 // Save the components and declaration to create the clause. For purposes of 10717 // the clause creation, any component list that has has base 'this' uses 10718 // null as base declaration. 10719 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 10720 MVLI.VarComponents.back().append(CurComponents.begin(), 10721 CurComponents.end()); 10722 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 10723 : CurDeclaration); 10724 } 10725 } 10726 10727 OMPClause * 10728 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 10729 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 10730 SourceLocation MapLoc, SourceLocation ColonLoc, 10731 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10732 SourceLocation LParenLoc, SourceLocation EndLoc) { 10733 MappableVarListInfo MVLI(VarList); 10734 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 10735 MapType, IsMapTypeImplicit); 10736 10737 // We need to produce a map clause even if we don't have variables so that 10738 // other diagnostics related with non-existing map clauses are accurate. 10739 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10740 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 10741 MVLI.VarComponents, MapTypeModifier, MapType, 10742 IsMapTypeImplicit, MapLoc); 10743 } 10744 10745 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 10746 TypeResult ParsedType) { 10747 assert(ParsedType.isUsable()); 10748 10749 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 10750 if (ReductionType.isNull()) 10751 return QualType(); 10752 10753 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 10754 // A type name in a declare reduction directive cannot be a function type, an 10755 // array type, a reference type, or a type qualified with const, volatile or 10756 // restrict. 10757 if (ReductionType.hasQualifiers()) { 10758 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 10759 return QualType(); 10760 } 10761 10762 if (ReductionType->isFunctionType()) { 10763 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 10764 return QualType(); 10765 } 10766 if (ReductionType->isReferenceType()) { 10767 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 10768 return QualType(); 10769 } 10770 if (ReductionType->isArrayType()) { 10771 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 10772 return QualType(); 10773 } 10774 return ReductionType; 10775 } 10776 10777 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 10778 Scope *S, DeclContext *DC, DeclarationName Name, 10779 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 10780 AccessSpecifier AS, Decl *PrevDeclInScope) { 10781 SmallVector<Decl *, 8> Decls; 10782 Decls.reserve(ReductionTypes.size()); 10783 10784 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 10785 ForRedeclaration); 10786 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 10787 // A reduction-identifier may not be re-declared in the current scope for the 10788 // same type or for a type that is compatible according to the base language 10789 // rules. 10790 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 10791 OMPDeclareReductionDecl *PrevDRD = nullptr; 10792 bool InCompoundScope = true; 10793 if (S != nullptr) { 10794 // Find previous declaration with the same name not referenced in other 10795 // declarations. 10796 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 10797 InCompoundScope = 10798 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 10799 LookupName(Lookup, S); 10800 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 10801 /*AllowInlineNamespace=*/false); 10802 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 10803 auto Filter = Lookup.makeFilter(); 10804 while (Filter.hasNext()) { 10805 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 10806 if (InCompoundScope) { 10807 auto I = UsedAsPrevious.find(PrevDecl); 10808 if (I == UsedAsPrevious.end()) 10809 UsedAsPrevious[PrevDecl] = false; 10810 if (auto *D = PrevDecl->getPrevDeclInScope()) 10811 UsedAsPrevious[D] = true; 10812 } 10813 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 10814 PrevDecl->getLocation(); 10815 } 10816 Filter.done(); 10817 if (InCompoundScope) { 10818 for (auto &PrevData : UsedAsPrevious) { 10819 if (!PrevData.second) { 10820 PrevDRD = PrevData.first; 10821 break; 10822 } 10823 } 10824 } 10825 } else if (PrevDeclInScope != nullptr) { 10826 auto *PrevDRDInScope = PrevDRD = 10827 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 10828 do { 10829 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 10830 PrevDRDInScope->getLocation(); 10831 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 10832 } while (PrevDRDInScope != nullptr); 10833 } 10834 for (auto &TyData : ReductionTypes) { 10835 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 10836 bool Invalid = false; 10837 if (I != PreviousRedeclTypes.end()) { 10838 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 10839 << TyData.first; 10840 Diag(I->second, diag::note_previous_definition); 10841 Invalid = true; 10842 } 10843 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 10844 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 10845 Name, TyData.first, PrevDRD); 10846 DC->addDecl(DRD); 10847 DRD->setAccess(AS); 10848 Decls.push_back(DRD); 10849 if (Invalid) 10850 DRD->setInvalidDecl(); 10851 else 10852 PrevDRD = DRD; 10853 } 10854 10855 return DeclGroupPtrTy::make( 10856 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 10857 } 10858 10859 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 10860 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10861 10862 // Enter new function scope. 10863 PushFunctionScope(); 10864 getCurFunction()->setHasBranchProtectedScope(); 10865 getCurFunction()->setHasOMPDeclareReductionCombiner(); 10866 10867 if (S != nullptr) 10868 PushDeclContext(S, DRD); 10869 else 10870 CurContext = DRD; 10871 10872 PushExpressionEvaluationContext(PotentiallyEvaluated); 10873 10874 QualType ReductionType = DRD->getType(); 10875 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 10876 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 10877 // uses semantics of argument handles by value, but it should be passed by 10878 // reference. C lang does not support references, so pass all parameters as 10879 // pointers. 10880 // Create 'T omp_in;' variable. 10881 auto *OmpInParm = 10882 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 10883 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 10884 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 10885 // uses semantics of argument handles by value, but it should be passed by 10886 // reference. C lang does not support references, so pass all parameters as 10887 // pointers. 10888 // Create 'T omp_out;' variable. 10889 auto *OmpOutParm = 10890 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 10891 if (S != nullptr) { 10892 PushOnScopeChains(OmpInParm, S); 10893 PushOnScopeChains(OmpOutParm, S); 10894 } else { 10895 DRD->addDecl(OmpInParm); 10896 DRD->addDecl(OmpOutParm); 10897 } 10898 } 10899 10900 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 10901 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10902 DiscardCleanupsInEvaluationContext(); 10903 PopExpressionEvaluationContext(); 10904 10905 PopDeclContext(); 10906 PopFunctionScopeInfo(); 10907 10908 if (Combiner != nullptr) 10909 DRD->setCombiner(Combiner); 10910 else 10911 DRD->setInvalidDecl(); 10912 } 10913 10914 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 10915 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10916 10917 // Enter new function scope. 10918 PushFunctionScope(); 10919 getCurFunction()->setHasBranchProtectedScope(); 10920 10921 if (S != nullptr) 10922 PushDeclContext(S, DRD); 10923 else 10924 CurContext = DRD; 10925 10926 PushExpressionEvaluationContext(PotentiallyEvaluated); 10927 10928 QualType ReductionType = DRD->getType(); 10929 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 10930 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 10931 // uses semantics of argument handles by value, but it should be passed by 10932 // reference. C lang does not support references, so pass all parameters as 10933 // pointers. 10934 // Create 'T omp_priv;' variable. 10935 auto *OmpPrivParm = 10936 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 10937 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 10938 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 10939 // uses semantics of argument handles by value, but it should be passed by 10940 // reference. C lang does not support references, so pass all parameters as 10941 // pointers. 10942 // Create 'T omp_orig;' variable. 10943 auto *OmpOrigParm = 10944 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 10945 if (S != nullptr) { 10946 PushOnScopeChains(OmpPrivParm, S); 10947 PushOnScopeChains(OmpOrigParm, S); 10948 } else { 10949 DRD->addDecl(OmpPrivParm); 10950 DRD->addDecl(OmpOrigParm); 10951 } 10952 } 10953 10954 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, 10955 Expr *Initializer) { 10956 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10957 DiscardCleanupsInEvaluationContext(); 10958 PopExpressionEvaluationContext(); 10959 10960 PopDeclContext(); 10961 PopFunctionScopeInfo(); 10962 10963 if (Initializer != nullptr) 10964 DRD->setInitializer(Initializer); 10965 else 10966 DRD->setInvalidDecl(); 10967 } 10968 10969 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 10970 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 10971 for (auto *D : DeclReductions.get()) { 10972 if (IsValid) { 10973 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10974 if (S != nullptr) 10975 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 10976 } else 10977 D->setInvalidDecl(); 10978 } 10979 return DeclReductions; 10980 } 10981 10982 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 10983 SourceLocation StartLoc, 10984 SourceLocation LParenLoc, 10985 SourceLocation EndLoc) { 10986 Expr *ValExpr = NumTeams; 10987 Stmt *HelperValStmt = nullptr; 10988 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 10989 10990 // OpenMP [teams Constrcut, Restrictions] 10991 // The num_teams expression must evaluate to a positive integer value. 10992 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 10993 /*StrictlyPositive=*/true)) 10994 return nullptr; 10995 10996 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 10997 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 10998 if (CaptureRegion != OMPD_unknown) { 10999 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11000 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11001 HelperValStmt = buildPreInits(Context, Captures); 11002 } 11003 11004 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 11005 StartLoc, LParenLoc, EndLoc); 11006 } 11007 11008 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 11009 SourceLocation StartLoc, 11010 SourceLocation LParenLoc, 11011 SourceLocation EndLoc) { 11012 Expr *ValExpr = ThreadLimit; 11013 Stmt *HelperValStmt = nullptr; 11014 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11015 11016 // OpenMP [teams Constrcut, Restrictions] 11017 // The thread_limit expression must evaluate to a positive integer value. 11018 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 11019 /*StrictlyPositive=*/true)) 11020 return nullptr; 11021 11022 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11023 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 11024 if (CaptureRegion != OMPD_unknown) { 11025 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11026 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11027 HelperValStmt = buildPreInits(Context, Captures); 11028 } 11029 11030 return new (Context) OMPThreadLimitClause( 11031 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 11032 } 11033 11034 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 11035 SourceLocation StartLoc, 11036 SourceLocation LParenLoc, 11037 SourceLocation EndLoc) { 11038 Expr *ValExpr = Priority; 11039 11040 // OpenMP [2.9.1, task Constrcut] 11041 // The priority-value is a non-negative numerical scalar expression. 11042 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 11043 /*StrictlyPositive=*/false)) 11044 return nullptr; 11045 11046 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11047 } 11048 11049 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 11050 SourceLocation StartLoc, 11051 SourceLocation LParenLoc, 11052 SourceLocation EndLoc) { 11053 Expr *ValExpr = Grainsize; 11054 11055 // OpenMP [2.9.2, taskloop Constrcut] 11056 // The parameter of the grainsize clause must be a positive integer 11057 // expression. 11058 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 11059 /*StrictlyPositive=*/true)) 11060 return nullptr; 11061 11062 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11063 } 11064 11065 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 11066 SourceLocation StartLoc, 11067 SourceLocation LParenLoc, 11068 SourceLocation EndLoc) { 11069 Expr *ValExpr = NumTasks; 11070 11071 // OpenMP [2.9.2, taskloop Constrcut] 11072 // The parameter of the num_tasks clause must be a positive integer 11073 // expression. 11074 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 11075 /*StrictlyPositive=*/true)) 11076 return nullptr; 11077 11078 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11079 } 11080 11081 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 11082 SourceLocation LParenLoc, 11083 SourceLocation EndLoc) { 11084 // OpenMP [2.13.2, critical construct, Description] 11085 // ... where hint-expression is an integer constant expression that evaluates 11086 // to a valid lock hint. 11087 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 11088 if (HintExpr.isInvalid()) 11089 return nullptr; 11090 return new (Context) 11091 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 11092 } 11093 11094 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 11095 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 11096 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 11097 SourceLocation EndLoc) { 11098 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 11099 std::string Values; 11100 Values += "'"; 11101 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 11102 Values += "'"; 11103 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 11104 << Values << getOpenMPClauseName(OMPC_dist_schedule); 11105 return nullptr; 11106 } 11107 Expr *ValExpr = ChunkSize; 11108 Stmt *HelperValStmt = nullptr; 11109 if (ChunkSize) { 11110 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 11111 !ChunkSize->isInstantiationDependent() && 11112 !ChunkSize->containsUnexpandedParameterPack()) { 11113 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 11114 ExprResult Val = 11115 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 11116 if (Val.isInvalid()) 11117 return nullptr; 11118 11119 ValExpr = Val.get(); 11120 11121 // OpenMP [2.7.1, Restrictions] 11122 // chunk_size must be a loop invariant integer expression with a positive 11123 // value. 11124 llvm::APSInt Result; 11125 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 11126 if (Result.isSigned() && !Result.isStrictlyPositive()) { 11127 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 11128 << "dist_schedule" << ChunkSize->getSourceRange(); 11129 return nullptr; 11130 } 11131 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 11132 !CurContext->isDependentContext()) { 11133 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11134 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11135 HelperValStmt = buildPreInits(Context, Captures); 11136 } 11137 } 11138 } 11139 11140 return new (Context) 11141 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 11142 Kind, ValExpr, HelperValStmt); 11143 } 11144 11145 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 11146 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 11147 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 11148 SourceLocation KindLoc, SourceLocation EndLoc) { 11149 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 11150 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 11151 std::string Value; 11152 SourceLocation Loc; 11153 Value += "'"; 11154 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 11155 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11156 OMPC_DEFAULTMAP_MODIFIER_tofrom); 11157 Loc = MLoc; 11158 } else { 11159 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11160 OMPC_DEFAULTMAP_scalar); 11161 Loc = KindLoc; 11162 } 11163 Value += "'"; 11164 Diag(Loc, diag::err_omp_unexpected_clause_value) 11165 << Value << getOpenMPClauseName(OMPC_defaultmap); 11166 return nullptr; 11167 } 11168 11169 return new (Context) 11170 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 11171 } 11172 11173 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 11174 DeclContext *CurLexicalContext = getCurLexicalContext(); 11175 if (!CurLexicalContext->isFileContext() && 11176 !CurLexicalContext->isExternCContext() && 11177 !CurLexicalContext->isExternCXXContext()) { 11178 Diag(Loc, diag::err_omp_region_not_file_context); 11179 return false; 11180 } 11181 if (IsInOpenMPDeclareTargetContext) { 11182 Diag(Loc, diag::err_omp_enclosed_declare_target); 11183 return false; 11184 } 11185 11186 IsInOpenMPDeclareTargetContext = true; 11187 return true; 11188 } 11189 11190 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 11191 assert(IsInOpenMPDeclareTargetContext && 11192 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 11193 11194 IsInOpenMPDeclareTargetContext = false; 11195 } 11196 11197 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 11198 CXXScopeSpec &ScopeSpec, 11199 const DeclarationNameInfo &Id, 11200 OMPDeclareTargetDeclAttr::MapTypeTy MT, 11201 NamedDeclSetType &SameDirectiveDecls) { 11202 LookupResult Lookup(*this, Id, LookupOrdinaryName); 11203 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 11204 11205 if (Lookup.isAmbiguous()) 11206 return; 11207 Lookup.suppressDiagnostics(); 11208 11209 if (!Lookup.isSingleResult()) { 11210 if (TypoCorrection Corrected = 11211 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 11212 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 11213 CTK_ErrorRecovery)) { 11214 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 11215 << Id.getName()); 11216 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 11217 return; 11218 } 11219 11220 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 11221 return; 11222 } 11223 11224 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 11225 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 11226 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 11227 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 11228 11229 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 11230 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 11231 ND->addAttr(A); 11232 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11233 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 11234 checkDeclIsAllowedInOpenMPTarget(nullptr, ND); 11235 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 11236 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 11237 << Id.getName(); 11238 } 11239 } else 11240 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 11241 } 11242 11243 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 11244 Sema &SemaRef, Decl *D) { 11245 if (!D) 11246 return; 11247 Decl *LD = nullptr; 11248 if (isa<TagDecl>(D)) { 11249 LD = cast<TagDecl>(D)->getDefinition(); 11250 } else if (isa<VarDecl>(D)) { 11251 LD = cast<VarDecl>(D)->getDefinition(); 11252 11253 // If this is an implicit variable that is legal and we do not need to do 11254 // anything. 11255 if (cast<VarDecl>(D)->isImplicit()) { 11256 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11257 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11258 D->addAttr(A); 11259 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11260 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11261 return; 11262 } 11263 11264 } else if (isa<FunctionDecl>(D)) { 11265 const FunctionDecl *FD = nullptr; 11266 if (cast<FunctionDecl>(D)->hasBody(FD)) 11267 LD = const_cast<FunctionDecl *>(FD); 11268 11269 // If the definition is associated with the current declaration in the 11270 // target region (it can be e.g. a lambda) that is legal and we do not need 11271 // to do anything else. 11272 if (LD == D) { 11273 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11274 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11275 D->addAttr(A); 11276 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11277 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11278 return; 11279 } 11280 } 11281 if (!LD) 11282 LD = D; 11283 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 11284 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 11285 // Outlined declaration is not declared target. 11286 if (LD->isOutOfLine()) { 11287 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11288 SemaRef.Diag(SL, diag::note_used_here) << SR; 11289 } else { 11290 DeclContext *DC = LD->getDeclContext(); 11291 while (DC) { 11292 if (isa<FunctionDecl>(DC) && 11293 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 11294 break; 11295 DC = DC->getParent(); 11296 } 11297 if (DC) 11298 return; 11299 11300 // Is not declared in target context. 11301 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11302 SemaRef.Diag(SL, diag::note_used_here) << SR; 11303 } 11304 // Mark decl as declared target to prevent further diagnostic. 11305 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11306 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11307 D->addAttr(A); 11308 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11309 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11310 } 11311 } 11312 11313 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 11314 Sema &SemaRef, DSAStackTy *Stack, 11315 ValueDecl *VD) { 11316 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 11317 return true; 11318 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) 11319 return false; 11320 return true; 11321 } 11322 11323 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) { 11324 if (!D || D->isInvalidDecl()) 11325 return; 11326 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 11327 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 11328 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 11329 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11330 if (DSAStack->isThreadPrivate(VD)) { 11331 Diag(SL, diag::err_omp_threadprivate_in_target); 11332 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 11333 return; 11334 } 11335 } 11336 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 11337 // Problem if any with var declared with incomplete type will be reported 11338 // as normal, so no need to check it here. 11339 if ((E || !VD->getType()->isIncompleteType()) && 11340 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 11341 // Mark decl as declared target to prevent further diagnostic. 11342 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { 11343 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11344 Context, OMPDeclareTargetDeclAttr::MT_To); 11345 VD->addAttr(A); 11346 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11347 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 11348 } 11349 return; 11350 } 11351 } 11352 if (!E) { 11353 // Checking declaration inside declare target region. 11354 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 11355 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { 11356 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11357 Context, OMPDeclareTargetDeclAttr::MT_To); 11358 D->addAttr(A); 11359 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11360 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11361 } 11362 return; 11363 } 11364 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 11365 } 11366 11367 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 11368 SourceLocation StartLoc, 11369 SourceLocation LParenLoc, 11370 SourceLocation EndLoc) { 11371 MappableVarListInfo MVLI(VarList); 11372 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 11373 if (MVLI.ProcessedVarList.empty()) 11374 return nullptr; 11375 11376 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11377 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11378 MVLI.VarComponents); 11379 } 11380 11381 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 11382 SourceLocation StartLoc, 11383 SourceLocation LParenLoc, 11384 SourceLocation EndLoc) { 11385 MappableVarListInfo MVLI(VarList); 11386 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 11387 if (MVLI.ProcessedVarList.empty()) 11388 return nullptr; 11389 11390 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11391 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11392 MVLI.VarComponents); 11393 } 11394 11395 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 11396 SourceLocation StartLoc, 11397 SourceLocation LParenLoc, 11398 SourceLocation EndLoc) { 11399 MappableVarListInfo MVLI(VarList); 11400 SmallVector<Expr *, 8> PrivateCopies; 11401 SmallVector<Expr *, 8> Inits; 11402 11403 for (auto &RefExpr : VarList) { 11404 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 11405 SourceLocation ELoc; 11406 SourceRange ERange; 11407 Expr *SimpleRefExpr = RefExpr; 11408 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11409 if (Res.second) { 11410 // It will be analyzed later. 11411 MVLI.ProcessedVarList.push_back(RefExpr); 11412 PrivateCopies.push_back(nullptr); 11413 Inits.push_back(nullptr); 11414 } 11415 ValueDecl *D = Res.first; 11416 if (!D) 11417 continue; 11418 11419 QualType Type = D->getType(); 11420 Type = Type.getNonReferenceType().getUnqualifiedType(); 11421 11422 auto *VD = dyn_cast<VarDecl>(D); 11423 11424 // Item should be a pointer or reference to pointer. 11425 if (!Type->isPointerType()) { 11426 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 11427 << 0 << RefExpr->getSourceRange(); 11428 continue; 11429 } 11430 11431 // Build the private variable and the expression that refers to it. 11432 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 11433 D->hasAttrs() ? &D->getAttrs() : nullptr); 11434 if (VDPrivate->isInvalidDecl()) 11435 continue; 11436 11437 CurContext->addDecl(VDPrivate); 11438 auto VDPrivateRefExpr = buildDeclRefExpr( 11439 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 11440 11441 // Add temporary variable to initialize the private copy of the pointer. 11442 auto *VDInit = 11443 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 11444 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 11445 RefExpr->getExprLoc()); 11446 AddInitializerToDecl(VDPrivate, 11447 DefaultLvalueConversion(VDInitRefExpr).get(), 11448 /*DirectInit=*/false); 11449 11450 // If required, build a capture to implement the privatization initialized 11451 // with the current list item value. 11452 DeclRefExpr *Ref = nullptr; 11453 if (!VD) 11454 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 11455 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 11456 PrivateCopies.push_back(VDPrivateRefExpr); 11457 Inits.push_back(VDInitRefExpr); 11458 11459 // We need to add a data sharing attribute for this variable to make sure it 11460 // is correctly captured. A variable that shows up in a use_device_ptr has 11461 // similar properties of a first private variable. 11462 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 11463 11464 // Create a mappable component for the list item. List items in this clause 11465 // only need a component. 11466 MVLI.VarBaseDeclarations.push_back(D); 11467 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11468 MVLI.VarComponents.back().push_back( 11469 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 11470 } 11471 11472 if (MVLI.ProcessedVarList.empty()) 11473 return nullptr; 11474 11475 return OMPUseDevicePtrClause::Create( 11476 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 11477 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 11478 } 11479 11480 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 11481 SourceLocation StartLoc, 11482 SourceLocation LParenLoc, 11483 SourceLocation EndLoc) { 11484 MappableVarListInfo MVLI(VarList); 11485 for (auto &RefExpr : VarList) { 11486 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 11487 SourceLocation ELoc; 11488 SourceRange ERange; 11489 Expr *SimpleRefExpr = RefExpr; 11490 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11491 if (Res.second) { 11492 // It will be analyzed later. 11493 MVLI.ProcessedVarList.push_back(RefExpr); 11494 } 11495 ValueDecl *D = Res.first; 11496 if (!D) 11497 continue; 11498 11499 QualType Type = D->getType(); 11500 // item should be a pointer or array or reference to pointer or array 11501 if (!Type.getNonReferenceType()->isPointerType() && 11502 !Type.getNonReferenceType()->isArrayType()) { 11503 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 11504 << 0 << RefExpr->getSourceRange(); 11505 continue; 11506 } 11507 11508 // Check if the declaration in the clause does not show up in any data 11509 // sharing attribute. 11510 auto DVar = DSAStack->getTopDSA(D, false); 11511 if (isOpenMPPrivate(DVar.CKind)) { 11512 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 11513 << getOpenMPClauseName(DVar.CKind) 11514 << getOpenMPClauseName(OMPC_is_device_ptr) 11515 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 11516 ReportOriginalDSA(*this, DSAStack, D, DVar); 11517 continue; 11518 } 11519 11520 Expr *ConflictExpr; 11521 if (DSAStack->checkMappableExprComponentListsForDecl( 11522 D, /*CurrentRegionOnly=*/true, 11523 [&ConflictExpr]( 11524 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 11525 OpenMPClauseKind) -> bool { 11526 ConflictExpr = R.front().getAssociatedExpression(); 11527 return true; 11528 })) { 11529 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 11530 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 11531 << ConflictExpr->getSourceRange(); 11532 continue; 11533 } 11534 11535 // Store the components in the stack so that they can be used to check 11536 // against other clauses later on. 11537 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 11538 DSAStack->addMappableExpressionComponents( 11539 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 11540 11541 // Record the expression we've just processed. 11542 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 11543 11544 // Create a mappable component for the list item. List items in this clause 11545 // only need a component. We use a null declaration to signal fields in 11546 // 'this'. 11547 assert((isa<DeclRefExpr>(SimpleRefExpr) || 11548 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 11549 "Unexpected device pointer expression!"); 11550 MVLI.VarBaseDeclarations.push_back( 11551 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 11552 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11553 MVLI.VarComponents.back().push_back(MC); 11554 } 11555 11556 if (MVLI.ProcessedVarList.empty()) 11557 return nullptr; 11558 11559 return OMPIsDevicePtrClause::Create( 11560 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 11561 MVLI.VarBaseDeclarations, MVLI.VarComponents); 11562 } 11563