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, /*TypeMayContainAuto=*/false); 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 case OMPD_target_teams: { 1599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1600 QualType KmpInt32PtrTy = 1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1602 Sema::CapturedParamNameType Params[] = { 1603 std::make_pair(".global_tid.", KmpInt32PtrTy), 1604 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1605 std::make_pair(StringRef(), QualType()) // __context with shared vars 1606 }; 1607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1608 Params); 1609 break; 1610 } 1611 case OMPD_simd: 1612 case OMPD_for: 1613 case OMPD_for_simd: 1614 case OMPD_sections: 1615 case OMPD_section: 1616 case OMPD_single: 1617 case OMPD_master: 1618 case OMPD_critical: 1619 case OMPD_taskgroup: 1620 case OMPD_distribute: 1621 case OMPD_ordered: 1622 case OMPD_atomic: 1623 case OMPD_target_data: 1624 case OMPD_target: 1625 case OMPD_target_parallel: 1626 case OMPD_target_parallel_for: 1627 case OMPD_target_parallel_for_simd: 1628 case OMPD_target_simd: { 1629 Sema::CapturedParamNameType Params[] = { 1630 std::make_pair(StringRef(), QualType()) // __context with shared vars 1631 }; 1632 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1633 Params); 1634 break; 1635 } 1636 case OMPD_task: { 1637 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1638 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1639 FunctionProtoType::ExtProtoInfo EPI; 1640 EPI.Variadic = true; 1641 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1642 Sema::CapturedParamNameType Params[] = { 1643 std::make_pair(".global_tid.", KmpInt32Ty), 1644 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1645 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 1646 std::make_pair(".copy_fn.", 1647 Context.getPointerType(CopyFnType).withConst()), 1648 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1649 std::make_pair(StringRef(), QualType()) // __context with shared vars 1650 }; 1651 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1652 Params); 1653 // Mark this captured region as inlined, because we don't use outlined 1654 // function directly. 1655 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1656 AlwaysInlineAttr::CreateImplicit( 1657 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1658 break; 1659 } 1660 case OMPD_taskloop: 1661 case OMPD_taskloop_simd: { 1662 QualType KmpInt32Ty = 1663 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1664 QualType KmpUInt64Ty = 1665 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 1666 QualType KmpInt64Ty = 1667 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 1668 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1669 FunctionProtoType::ExtProtoInfo EPI; 1670 EPI.Variadic = true; 1671 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1672 Sema::CapturedParamNameType Params[] = { 1673 std::make_pair(".global_tid.", KmpInt32Ty), 1674 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1675 std::make_pair(".privates.", 1676 Context.VoidPtrTy.withConst().withRestrict()), 1677 std::make_pair( 1678 ".copy_fn.", 1679 Context.getPointerType(CopyFnType).withConst().withRestrict()), 1680 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1681 std::make_pair(".lb.", KmpUInt64Ty), 1682 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 1683 std::make_pair(".liter.", KmpInt32Ty), 1684 std::make_pair(StringRef(), QualType()) // __context with shared vars 1685 }; 1686 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1687 Params); 1688 // Mark this captured region as inlined, because we don't use outlined 1689 // function directly. 1690 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1691 AlwaysInlineAttr::CreateImplicit( 1692 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1693 break; 1694 } 1695 case OMPD_distribute_parallel_for_simd: 1696 case OMPD_distribute_simd: 1697 case OMPD_distribute_parallel_for: 1698 case OMPD_teams_distribute: 1699 case OMPD_teams_distribute_simd: 1700 case OMPD_teams_distribute_parallel_for_simd: 1701 case OMPD_teams_distribute_parallel_for: { 1702 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1703 QualType KmpInt32PtrTy = 1704 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1705 Sema::CapturedParamNameType Params[] = { 1706 std::make_pair(".global_tid.", KmpInt32PtrTy), 1707 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1708 std::make_pair(".previous.lb.", Context.getSizeType()), 1709 std::make_pair(".previous.ub.", Context.getSizeType()), 1710 std::make_pair(StringRef(), QualType()) // __context with shared vars 1711 }; 1712 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1713 Params); 1714 break; 1715 } 1716 case OMPD_threadprivate: 1717 case OMPD_taskyield: 1718 case OMPD_barrier: 1719 case OMPD_taskwait: 1720 case OMPD_cancellation_point: 1721 case OMPD_cancel: 1722 case OMPD_flush: 1723 case OMPD_target_enter_data: 1724 case OMPD_target_exit_data: 1725 case OMPD_declare_reduction: 1726 case OMPD_declare_simd: 1727 case OMPD_declare_target: 1728 case OMPD_end_declare_target: 1729 case OMPD_target_update: 1730 llvm_unreachable("OpenMP Directive is not allowed"); 1731 case OMPD_unknown: 1732 llvm_unreachable("Unknown OpenMP directive"); 1733 } 1734 } 1735 1736 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 1737 Expr *CaptureExpr, bool WithInit, 1738 bool AsExpression) { 1739 assert(CaptureExpr); 1740 ASTContext &C = S.getASTContext(); 1741 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 1742 QualType Ty = Init->getType(); 1743 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 1744 if (S.getLangOpts().CPlusPlus) 1745 Ty = C.getLValueReferenceType(Ty); 1746 else { 1747 Ty = C.getPointerType(Ty); 1748 ExprResult Res = 1749 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 1750 if (!Res.isUsable()) 1751 return nullptr; 1752 Init = Res.get(); 1753 } 1754 WithInit = true; 1755 } 1756 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 1757 CaptureExpr->getLocStart()); 1758 if (!WithInit) 1759 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 1760 S.CurContext->addHiddenDecl(CED); 1761 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false, 1762 /*TypeMayContainAuto=*/true); 1763 return CED; 1764 } 1765 1766 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 1767 bool WithInit) { 1768 OMPCapturedExprDecl *CD; 1769 if (auto *VD = S.IsOpenMPCapturedDecl(D)) 1770 CD = cast<OMPCapturedExprDecl>(VD); 1771 else 1772 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 1773 /*AsExpression=*/false); 1774 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1775 CaptureExpr->getExprLoc()); 1776 } 1777 1778 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 1779 if (!Ref) { 1780 auto *CD = 1781 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), 1782 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); 1783 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1784 CaptureExpr->getExprLoc()); 1785 } 1786 ExprResult Res = Ref; 1787 if (!S.getLangOpts().CPlusPlus && 1788 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 1789 Ref->getType()->isPointerType()) 1790 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 1791 if (!Res.isUsable()) 1792 return ExprError(); 1793 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); 1794 } 1795 1796 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 1797 ArrayRef<OMPClause *> Clauses) { 1798 if (!S.isUsable()) { 1799 ActOnCapturedRegionError(); 1800 return StmtError(); 1801 } 1802 1803 OMPOrderedClause *OC = nullptr; 1804 OMPScheduleClause *SC = nullptr; 1805 SmallVector<OMPLinearClause *, 4> LCs; 1806 // This is required for proper codegen. 1807 for (auto *Clause : Clauses) { 1808 if (isOpenMPPrivate(Clause->getClauseKind()) || 1809 Clause->getClauseKind() == OMPC_copyprivate || 1810 (getLangOpts().OpenMPUseTLS && 1811 getASTContext().getTargetInfo().isTLSSupported() && 1812 Clause->getClauseKind() == OMPC_copyin)) { 1813 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 1814 // Mark all variables in private list clauses as used in inner region. 1815 for (auto *VarRef : Clause->children()) { 1816 if (auto *E = cast_or_null<Expr>(VarRef)) { 1817 MarkDeclarationsReferencedInExpr(E); 1818 } 1819 } 1820 DSAStack->setForceVarCapturing(/*V=*/false); 1821 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 1822 // Mark all variables in private list clauses as used in inner region. 1823 // Required for proper codegen of combined directives. 1824 // TODO: add processing for other clauses. 1825 if (auto *C = OMPClauseWithPreInit::get(Clause)) { 1826 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 1827 for (auto *D : DS->decls()) 1828 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 1829 } 1830 } 1831 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 1832 if (auto *E = C->getPostUpdateExpr()) 1833 MarkDeclarationsReferencedInExpr(E); 1834 } 1835 } 1836 if (Clause->getClauseKind() == OMPC_schedule) 1837 SC = cast<OMPScheduleClause>(Clause); 1838 else if (Clause->getClauseKind() == OMPC_ordered) 1839 OC = cast<OMPOrderedClause>(Clause); 1840 else if (Clause->getClauseKind() == OMPC_linear) 1841 LCs.push_back(cast<OMPLinearClause>(Clause)); 1842 } 1843 bool ErrorFound = false; 1844 // OpenMP, 2.7.1 Loop Construct, Restrictions 1845 // The nonmonotonic modifier cannot be specified if an ordered clause is 1846 // specified. 1847 if (SC && 1848 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 1849 SC->getSecondScheduleModifier() == 1850 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 1851 OC) { 1852 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 1853 ? SC->getFirstScheduleModifierLoc() 1854 : SC->getSecondScheduleModifierLoc(), 1855 diag::err_omp_schedule_nonmonotonic_ordered) 1856 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1857 ErrorFound = true; 1858 } 1859 if (!LCs.empty() && OC && OC->getNumForLoops()) { 1860 for (auto *C : LCs) { 1861 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 1862 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1863 } 1864 ErrorFound = true; 1865 } 1866 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 1867 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 1868 OC->getNumForLoops()) { 1869 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 1870 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 1871 ErrorFound = true; 1872 } 1873 if (ErrorFound) { 1874 ActOnCapturedRegionError(); 1875 return StmtError(); 1876 } 1877 return ActOnCapturedRegionEnd(S.get()); 1878 } 1879 1880 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 1881 OpenMPDirectiveKind CurrentRegion, 1882 const DeclarationNameInfo &CurrentName, 1883 OpenMPDirectiveKind CancelRegion, 1884 SourceLocation StartLoc) { 1885 if (Stack->getCurScope()) { 1886 auto ParentRegion = Stack->getParentDirective(); 1887 auto OffendingRegion = ParentRegion; 1888 bool NestingProhibited = false; 1889 bool CloseNesting = true; 1890 bool OrphanSeen = false; 1891 enum { 1892 NoRecommend, 1893 ShouldBeInParallelRegion, 1894 ShouldBeInOrderedRegion, 1895 ShouldBeInTargetRegion, 1896 ShouldBeInTeamsRegion 1897 } Recommend = NoRecommend; 1898 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 1899 // OpenMP [2.16, Nesting of Regions] 1900 // OpenMP constructs may not be nested inside a simd region. 1901 // OpenMP [2.8.1,simd Construct, Restrictions] 1902 // An ordered construct with the simd clause is the only OpenMP 1903 // construct that can appear in the simd region. 1904 // Allowing a SIMD construct nested in another SIMD construct is an 1905 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 1906 // message. 1907 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 1908 ? diag::err_omp_prohibited_region_simd 1909 : diag::warn_omp_nesting_simd); 1910 return CurrentRegion != OMPD_simd; 1911 } 1912 if (ParentRegion == OMPD_atomic) { 1913 // OpenMP [2.16, Nesting of Regions] 1914 // OpenMP constructs may not be nested inside an atomic region. 1915 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 1916 return true; 1917 } 1918 if (CurrentRegion == OMPD_section) { 1919 // OpenMP [2.7.2, sections Construct, Restrictions] 1920 // Orphaned section directives are prohibited. That is, the section 1921 // directives must appear within the sections construct and must not be 1922 // encountered elsewhere in the sections region. 1923 if (ParentRegion != OMPD_sections && 1924 ParentRegion != OMPD_parallel_sections) { 1925 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 1926 << (ParentRegion != OMPD_unknown) 1927 << getOpenMPDirectiveName(ParentRegion); 1928 return true; 1929 } 1930 return false; 1931 } 1932 // Allow some constructs (except teams) to be orphaned (they could be 1933 // used in functions, called from OpenMP regions with the required 1934 // preconditions). 1935 if (ParentRegion == OMPD_unknown && 1936 !isOpenMPNestingTeamsDirective(CurrentRegion)) 1937 return false; 1938 if (CurrentRegion == OMPD_cancellation_point || 1939 CurrentRegion == OMPD_cancel) { 1940 // OpenMP [2.16, Nesting of Regions] 1941 // A cancellation point construct for which construct-type-clause is 1942 // taskgroup must be nested inside a task construct. A cancellation 1943 // point construct for which construct-type-clause is not taskgroup must 1944 // be closely nested inside an OpenMP construct that matches the type 1945 // specified in construct-type-clause. 1946 // A cancel construct for which construct-type-clause is taskgroup must be 1947 // nested inside a task construct. A cancel construct for which 1948 // construct-type-clause is not taskgroup must be closely nested inside an 1949 // OpenMP construct that matches the type specified in 1950 // construct-type-clause. 1951 NestingProhibited = 1952 !((CancelRegion == OMPD_parallel && 1953 (ParentRegion == OMPD_parallel || 1954 ParentRegion == OMPD_target_parallel)) || 1955 (CancelRegion == OMPD_for && 1956 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 1957 ParentRegion == OMPD_target_parallel_for)) || 1958 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 1959 (CancelRegion == OMPD_sections && 1960 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 1961 ParentRegion == OMPD_parallel_sections))); 1962 } else if (CurrentRegion == OMPD_master) { 1963 // OpenMP [2.16, Nesting of Regions] 1964 // A master region may not be closely nested inside a worksharing, 1965 // atomic, or explicit task region. 1966 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 1967 isOpenMPTaskingDirective(ParentRegion); 1968 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 1969 // OpenMP [2.16, Nesting of Regions] 1970 // A critical region may not be nested (closely or otherwise) inside a 1971 // critical region with the same name. Note that this restriction is not 1972 // sufficient to prevent deadlock. 1973 SourceLocation PreviousCriticalLoc; 1974 bool DeadLock = Stack->hasDirective( 1975 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 1976 const DeclarationNameInfo &DNI, 1977 SourceLocation Loc) -> bool { 1978 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 1979 PreviousCriticalLoc = Loc; 1980 return true; 1981 } else 1982 return false; 1983 }, 1984 false /* skip top directive */); 1985 if (DeadLock) { 1986 SemaRef.Diag(StartLoc, 1987 diag::err_omp_prohibited_region_critical_same_name) 1988 << CurrentName.getName(); 1989 if (PreviousCriticalLoc.isValid()) 1990 SemaRef.Diag(PreviousCriticalLoc, 1991 diag::note_omp_previous_critical_region); 1992 return true; 1993 } 1994 } else if (CurrentRegion == OMPD_barrier) { 1995 // OpenMP [2.16, Nesting of Regions] 1996 // A barrier region may not be closely nested inside a worksharing, 1997 // explicit task, critical, ordered, atomic, or master region. 1998 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 1999 isOpenMPTaskingDirective(ParentRegion) || 2000 ParentRegion == OMPD_master || 2001 ParentRegion == OMPD_critical || 2002 ParentRegion == OMPD_ordered; 2003 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2004 !isOpenMPParallelDirective(CurrentRegion) && 2005 !isOpenMPTeamsDirective(CurrentRegion)) { 2006 // OpenMP [2.16, Nesting of Regions] 2007 // A worksharing region may not be closely nested inside a worksharing, 2008 // explicit task, critical, ordered, atomic, or master region. 2009 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2010 isOpenMPTaskingDirective(ParentRegion) || 2011 ParentRegion == OMPD_master || 2012 ParentRegion == OMPD_critical || 2013 ParentRegion == OMPD_ordered; 2014 Recommend = ShouldBeInParallelRegion; 2015 } else if (CurrentRegion == OMPD_ordered) { 2016 // OpenMP [2.16, Nesting of Regions] 2017 // An ordered region may not be closely nested inside a critical, 2018 // atomic, or explicit task region. 2019 // An ordered region must be closely nested inside a loop region (or 2020 // parallel loop region) with an ordered clause. 2021 // OpenMP [2.8.1,simd Construct, Restrictions] 2022 // An ordered construct with the simd clause is the only OpenMP construct 2023 // that can appear in the simd region. 2024 NestingProhibited = ParentRegion == OMPD_critical || 2025 isOpenMPTaskingDirective(ParentRegion) || 2026 !(isOpenMPSimdDirective(ParentRegion) || 2027 Stack->isParentOrderedRegion()); 2028 Recommend = ShouldBeInOrderedRegion; 2029 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 2030 // OpenMP [2.16, Nesting of Regions] 2031 // If specified, a teams construct must be contained within a target 2032 // construct. 2033 NestingProhibited = ParentRegion != OMPD_target; 2034 OrphanSeen = ParentRegion == OMPD_unknown; 2035 Recommend = ShouldBeInTargetRegion; 2036 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 2037 } 2038 if (!NestingProhibited && 2039 !isOpenMPTargetExecutionDirective(CurrentRegion) && 2040 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 2041 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 2042 // OpenMP [2.16, Nesting of Regions] 2043 // distribute, parallel, parallel sections, parallel workshare, and the 2044 // parallel loop and parallel loop SIMD constructs are the only OpenMP 2045 // constructs that can be closely nested in the teams region. 2046 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 2047 !isOpenMPDistributeDirective(CurrentRegion); 2048 Recommend = ShouldBeInParallelRegion; 2049 } 2050 if (!NestingProhibited && 2051 isOpenMPNestingDistributeDirective(CurrentRegion)) { 2052 // OpenMP 4.5 [2.17 Nesting of Regions] 2053 // The region associated with the distribute construct must be strictly 2054 // nested inside a teams region 2055 NestingProhibited = 2056 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 2057 Recommend = ShouldBeInTeamsRegion; 2058 } 2059 if (!NestingProhibited && 2060 (isOpenMPTargetExecutionDirective(CurrentRegion) || 2061 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 2062 // OpenMP 4.5 [2.17 Nesting of Regions] 2063 // If a target, target update, target data, target enter data, or 2064 // target exit data construct is encountered during execution of a 2065 // target region, the behavior is unspecified. 2066 NestingProhibited = Stack->hasDirective( 2067 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2068 SourceLocation) -> bool { 2069 if (isOpenMPTargetExecutionDirective(K)) { 2070 OffendingRegion = K; 2071 return true; 2072 } else 2073 return false; 2074 }, 2075 false /* don't skip top directive */); 2076 CloseNesting = false; 2077 } 2078 if (NestingProhibited) { 2079 if (OrphanSeen) { 2080 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 2081 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 2082 } else { 2083 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 2084 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 2085 << Recommend << getOpenMPDirectiveName(CurrentRegion); 2086 } 2087 return true; 2088 } 2089 } 2090 return false; 2091 } 2092 2093 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 2094 ArrayRef<OMPClause *> Clauses, 2095 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 2096 bool ErrorFound = false; 2097 unsigned NamedModifiersNumber = 0; 2098 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 2099 OMPD_unknown + 1); 2100 SmallVector<SourceLocation, 4> NameModifierLoc; 2101 for (const auto *C : Clauses) { 2102 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 2103 // At most one if clause without a directive-name-modifier can appear on 2104 // the directive. 2105 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 2106 if (FoundNameModifiers[CurNM]) { 2107 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 2108 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 2109 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 2110 ErrorFound = true; 2111 } else if (CurNM != OMPD_unknown) { 2112 NameModifierLoc.push_back(IC->getNameModifierLoc()); 2113 ++NamedModifiersNumber; 2114 } 2115 FoundNameModifiers[CurNM] = IC; 2116 if (CurNM == OMPD_unknown) 2117 continue; 2118 // Check if the specified name modifier is allowed for the current 2119 // directive. 2120 // At most one if clause with the particular directive-name-modifier can 2121 // appear on the directive. 2122 bool MatchFound = false; 2123 for (auto NM : AllowedNameModifiers) { 2124 if (CurNM == NM) { 2125 MatchFound = true; 2126 break; 2127 } 2128 } 2129 if (!MatchFound) { 2130 S.Diag(IC->getNameModifierLoc(), 2131 diag::err_omp_wrong_if_directive_name_modifier) 2132 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 2133 ErrorFound = true; 2134 } 2135 } 2136 } 2137 // If any if clause on the directive includes a directive-name-modifier then 2138 // all if clauses on the directive must include a directive-name-modifier. 2139 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 2140 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 2141 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 2142 diag::err_omp_no_more_if_clause); 2143 } else { 2144 std::string Values; 2145 std::string Sep(", "); 2146 unsigned AllowedCnt = 0; 2147 unsigned TotalAllowedNum = 2148 AllowedNameModifiers.size() - NamedModifiersNumber; 2149 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 2150 ++Cnt) { 2151 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 2152 if (!FoundNameModifiers[NM]) { 2153 Values += "'"; 2154 Values += getOpenMPDirectiveName(NM); 2155 Values += "'"; 2156 if (AllowedCnt + 2 == TotalAllowedNum) 2157 Values += " or "; 2158 else if (AllowedCnt + 1 != TotalAllowedNum) 2159 Values += Sep; 2160 ++AllowedCnt; 2161 } 2162 } 2163 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 2164 diag::err_omp_unnamed_if_clause) 2165 << (TotalAllowedNum > 1) << Values; 2166 } 2167 for (auto Loc : NameModifierLoc) { 2168 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 2169 } 2170 ErrorFound = true; 2171 } 2172 return ErrorFound; 2173 } 2174 2175 StmtResult Sema::ActOnOpenMPExecutableDirective( 2176 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 2177 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 2178 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 2179 StmtResult Res = StmtError(); 2180 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 2181 StartLoc)) 2182 return StmtError(); 2183 2184 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 2185 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 2186 bool ErrorFound = false; 2187 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 2188 if (AStmt) { 2189 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2190 2191 // Check default data sharing attributes for referenced variables. 2192 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 2193 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt()); 2194 if (DSAChecker.isErrorFound()) 2195 return StmtError(); 2196 // Generate list of implicitly defined firstprivate variables. 2197 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 2198 2199 if (!DSAChecker.getImplicitFirstprivate().empty()) { 2200 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 2201 DSAChecker.getImplicitFirstprivate(), SourceLocation(), 2202 SourceLocation(), SourceLocation())) { 2203 ClausesWithImplicit.push_back(Implicit); 2204 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 2205 DSAChecker.getImplicitFirstprivate().size(); 2206 } else 2207 ErrorFound = true; 2208 } 2209 } 2210 2211 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 2212 switch (Kind) { 2213 case OMPD_parallel: 2214 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 2215 EndLoc); 2216 AllowedNameModifiers.push_back(OMPD_parallel); 2217 break; 2218 case OMPD_simd: 2219 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2220 VarsWithInheritedDSA); 2221 break; 2222 case OMPD_for: 2223 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2224 VarsWithInheritedDSA); 2225 break; 2226 case OMPD_for_simd: 2227 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2228 EndLoc, VarsWithInheritedDSA); 2229 break; 2230 case OMPD_sections: 2231 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 2232 EndLoc); 2233 break; 2234 case OMPD_section: 2235 assert(ClausesWithImplicit.empty() && 2236 "No clauses are allowed for 'omp section' directive"); 2237 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 2238 break; 2239 case OMPD_single: 2240 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 2241 EndLoc); 2242 break; 2243 case OMPD_master: 2244 assert(ClausesWithImplicit.empty() && 2245 "No clauses are allowed for 'omp master' directive"); 2246 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 2247 break; 2248 case OMPD_critical: 2249 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 2250 StartLoc, EndLoc); 2251 break; 2252 case OMPD_parallel_for: 2253 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 2254 EndLoc, VarsWithInheritedDSA); 2255 AllowedNameModifiers.push_back(OMPD_parallel); 2256 break; 2257 case OMPD_parallel_for_simd: 2258 Res = ActOnOpenMPParallelForSimdDirective( 2259 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2260 AllowedNameModifiers.push_back(OMPD_parallel); 2261 break; 2262 case OMPD_parallel_sections: 2263 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 2264 StartLoc, EndLoc); 2265 AllowedNameModifiers.push_back(OMPD_parallel); 2266 break; 2267 case OMPD_task: 2268 Res = 2269 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2270 AllowedNameModifiers.push_back(OMPD_task); 2271 break; 2272 case OMPD_taskyield: 2273 assert(ClausesWithImplicit.empty() && 2274 "No clauses are allowed for 'omp taskyield' directive"); 2275 assert(AStmt == nullptr && 2276 "No associated statement allowed for 'omp taskyield' directive"); 2277 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 2278 break; 2279 case OMPD_barrier: 2280 assert(ClausesWithImplicit.empty() && 2281 "No clauses are allowed for 'omp barrier' directive"); 2282 assert(AStmt == nullptr && 2283 "No associated statement allowed for 'omp barrier' directive"); 2284 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 2285 break; 2286 case OMPD_taskwait: 2287 assert(ClausesWithImplicit.empty() && 2288 "No clauses are allowed for 'omp taskwait' directive"); 2289 assert(AStmt == nullptr && 2290 "No associated statement allowed for 'omp taskwait' directive"); 2291 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 2292 break; 2293 case OMPD_taskgroup: 2294 assert(ClausesWithImplicit.empty() && 2295 "No clauses are allowed for 'omp taskgroup' directive"); 2296 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc); 2297 break; 2298 case OMPD_flush: 2299 assert(AStmt == nullptr && 2300 "No associated statement allowed for 'omp flush' directive"); 2301 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 2302 break; 2303 case OMPD_ordered: 2304 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 2305 EndLoc); 2306 break; 2307 case OMPD_atomic: 2308 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 2309 EndLoc); 2310 break; 2311 case OMPD_teams: 2312 Res = 2313 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2314 break; 2315 case OMPD_target: 2316 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 2317 EndLoc); 2318 AllowedNameModifiers.push_back(OMPD_target); 2319 break; 2320 case OMPD_target_parallel: 2321 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 2322 StartLoc, EndLoc); 2323 AllowedNameModifiers.push_back(OMPD_target); 2324 AllowedNameModifiers.push_back(OMPD_parallel); 2325 break; 2326 case OMPD_target_parallel_for: 2327 Res = ActOnOpenMPTargetParallelForDirective( 2328 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2329 AllowedNameModifiers.push_back(OMPD_target); 2330 AllowedNameModifiers.push_back(OMPD_parallel); 2331 break; 2332 case OMPD_cancellation_point: 2333 assert(ClausesWithImplicit.empty() && 2334 "No clauses are allowed for 'omp cancellation point' directive"); 2335 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 2336 "cancellation point' directive"); 2337 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 2338 break; 2339 case OMPD_cancel: 2340 assert(AStmt == nullptr && 2341 "No associated statement allowed for 'omp cancel' directive"); 2342 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 2343 CancelRegion); 2344 AllowedNameModifiers.push_back(OMPD_cancel); 2345 break; 2346 case OMPD_target_data: 2347 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 2348 EndLoc); 2349 AllowedNameModifiers.push_back(OMPD_target_data); 2350 break; 2351 case OMPD_target_enter_data: 2352 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 2353 EndLoc); 2354 AllowedNameModifiers.push_back(OMPD_target_enter_data); 2355 break; 2356 case OMPD_target_exit_data: 2357 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 2358 EndLoc); 2359 AllowedNameModifiers.push_back(OMPD_target_exit_data); 2360 break; 2361 case OMPD_taskloop: 2362 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 2363 EndLoc, VarsWithInheritedDSA); 2364 AllowedNameModifiers.push_back(OMPD_taskloop); 2365 break; 2366 case OMPD_taskloop_simd: 2367 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2368 EndLoc, VarsWithInheritedDSA); 2369 AllowedNameModifiers.push_back(OMPD_taskloop); 2370 break; 2371 case OMPD_distribute: 2372 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 2373 EndLoc, VarsWithInheritedDSA); 2374 break; 2375 case OMPD_target_update: 2376 assert(!AStmt && "Statement is not allowed for target update"); 2377 Res = 2378 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); 2379 AllowedNameModifiers.push_back(OMPD_target_update); 2380 break; 2381 case OMPD_distribute_parallel_for: 2382 Res = ActOnOpenMPDistributeParallelForDirective( 2383 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2384 AllowedNameModifiers.push_back(OMPD_parallel); 2385 break; 2386 case OMPD_distribute_parallel_for_simd: 2387 Res = ActOnOpenMPDistributeParallelForSimdDirective( 2388 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2389 AllowedNameModifiers.push_back(OMPD_parallel); 2390 break; 2391 case OMPD_distribute_simd: 2392 Res = ActOnOpenMPDistributeSimdDirective( 2393 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2394 break; 2395 case OMPD_target_parallel_for_simd: 2396 Res = ActOnOpenMPTargetParallelForSimdDirective( 2397 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2398 AllowedNameModifiers.push_back(OMPD_target); 2399 AllowedNameModifiers.push_back(OMPD_parallel); 2400 break; 2401 case OMPD_target_simd: 2402 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2403 EndLoc, VarsWithInheritedDSA); 2404 AllowedNameModifiers.push_back(OMPD_target); 2405 break; 2406 case OMPD_teams_distribute: 2407 Res = ActOnOpenMPTeamsDistributeDirective( 2408 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2409 break; 2410 case OMPD_teams_distribute_simd: 2411 Res = ActOnOpenMPTeamsDistributeSimdDirective( 2412 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2413 break; 2414 case OMPD_teams_distribute_parallel_for_simd: 2415 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 2416 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2417 AllowedNameModifiers.push_back(OMPD_parallel); 2418 break; 2419 case OMPD_teams_distribute_parallel_for: 2420 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 2421 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2422 AllowedNameModifiers.push_back(OMPD_parallel); 2423 break; 2424 case OMPD_target_teams: 2425 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 2426 EndLoc); 2427 AllowedNameModifiers.push_back(OMPD_target); 2428 break; 2429 case OMPD_declare_target: 2430 case OMPD_end_declare_target: 2431 case OMPD_threadprivate: 2432 case OMPD_declare_reduction: 2433 case OMPD_declare_simd: 2434 llvm_unreachable("OpenMP Directive is not allowed"); 2435 case OMPD_unknown: 2436 llvm_unreachable("Unknown OpenMP directive"); 2437 } 2438 2439 for (auto P : VarsWithInheritedDSA) { 2440 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 2441 << P.first << P.second->getSourceRange(); 2442 } 2443 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 2444 2445 if (!AllowedNameModifiers.empty()) 2446 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 2447 ErrorFound; 2448 2449 if (ErrorFound) 2450 return StmtError(); 2451 return Res; 2452 } 2453 2454 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 2455 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 2456 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 2457 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 2458 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 2459 assert(Aligneds.size() == Alignments.size()); 2460 assert(Linears.size() == LinModifiers.size()); 2461 assert(Linears.size() == Steps.size()); 2462 if (!DG || DG.get().isNull()) 2463 return DeclGroupPtrTy(); 2464 2465 if (!DG.get().isSingleDecl()) { 2466 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 2467 return DG; 2468 } 2469 auto *ADecl = DG.get().getSingleDecl(); 2470 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 2471 ADecl = FTD->getTemplatedDecl(); 2472 2473 auto *FD = dyn_cast<FunctionDecl>(ADecl); 2474 if (!FD) { 2475 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 2476 return DeclGroupPtrTy(); 2477 } 2478 2479 // OpenMP [2.8.2, declare simd construct, Description] 2480 // The parameter of the simdlen clause must be a constant positive integer 2481 // expression. 2482 ExprResult SL; 2483 if (Simdlen) 2484 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 2485 // OpenMP [2.8.2, declare simd construct, Description] 2486 // The special this pointer can be used as if was one of the arguments to the 2487 // function in any of the linear, aligned, or uniform clauses. 2488 // The uniform clause declares one or more arguments to have an invariant 2489 // value for all concurrent invocations of the function in the execution of a 2490 // single SIMD loop. 2491 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 2492 Expr *UniformedLinearThis = nullptr; 2493 for (auto *E : Uniforms) { 2494 E = E->IgnoreParenImpCasts(); 2495 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2496 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 2497 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2498 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2499 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 2500 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 2501 continue; 2502 } 2503 if (isa<CXXThisExpr>(E)) { 2504 UniformedLinearThis = E; 2505 continue; 2506 } 2507 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2508 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2509 } 2510 // OpenMP [2.8.2, declare simd construct, Description] 2511 // The aligned clause declares that the object to which each list item points 2512 // is aligned to the number of bytes expressed in the optional parameter of 2513 // the aligned clause. 2514 // The special this pointer can be used as if was one of the arguments to the 2515 // function in any of the linear, aligned, or uniform clauses. 2516 // The type of list items appearing in the aligned clause must be array, 2517 // pointer, reference to array, or reference to pointer. 2518 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 2519 Expr *AlignedThis = nullptr; 2520 for (auto *E : Aligneds) { 2521 E = E->IgnoreParenImpCasts(); 2522 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2523 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2524 auto *CanonPVD = PVD->getCanonicalDecl(); 2525 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2526 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2527 ->getCanonicalDecl() == CanonPVD) { 2528 // OpenMP [2.8.1, simd construct, Restrictions] 2529 // A list-item cannot appear in more than one aligned clause. 2530 if (AlignedArgs.count(CanonPVD) > 0) { 2531 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 2532 << 1 << E->getSourceRange(); 2533 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 2534 diag::note_omp_explicit_dsa) 2535 << getOpenMPClauseName(OMPC_aligned); 2536 continue; 2537 } 2538 AlignedArgs[CanonPVD] = E; 2539 QualType QTy = PVD->getType() 2540 .getNonReferenceType() 2541 .getUnqualifiedType() 2542 .getCanonicalType(); 2543 const Type *Ty = QTy.getTypePtrOrNull(); 2544 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 2545 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 2546 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 2547 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 2548 } 2549 continue; 2550 } 2551 } 2552 if (isa<CXXThisExpr>(E)) { 2553 if (AlignedThis) { 2554 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 2555 << 2 << E->getSourceRange(); 2556 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 2557 << getOpenMPClauseName(OMPC_aligned); 2558 } 2559 AlignedThis = E; 2560 continue; 2561 } 2562 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2563 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2564 } 2565 // The optional parameter of the aligned clause, alignment, must be a constant 2566 // positive integer expression. If no optional parameter is specified, 2567 // implementation-defined default alignments for SIMD instructions on the 2568 // target platforms are assumed. 2569 SmallVector<Expr *, 4> NewAligns; 2570 for (auto *E : Alignments) { 2571 ExprResult Align; 2572 if (E) 2573 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 2574 NewAligns.push_back(Align.get()); 2575 } 2576 // OpenMP [2.8.2, declare simd construct, Description] 2577 // The linear clause declares one or more list items to be private to a SIMD 2578 // lane and to have a linear relationship with respect to the iteration space 2579 // of a loop. 2580 // The special this pointer can be used as if was one of the arguments to the 2581 // function in any of the linear, aligned, or uniform clauses. 2582 // When a linear-step expression is specified in a linear clause it must be 2583 // either a constant integer expression or an integer-typed parameter that is 2584 // specified in a uniform clause on the directive. 2585 llvm::DenseMap<Decl *, Expr *> LinearArgs; 2586 const bool IsUniformedThis = UniformedLinearThis != nullptr; 2587 auto MI = LinModifiers.begin(); 2588 for (auto *E : Linears) { 2589 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 2590 ++MI; 2591 E = E->IgnoreParenImpCasts(); 2592 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2593 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2594 auto *CanonPVD = PVD->getCanonicalDecl(); 2595 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2596 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2597 ->getCanonicalDecl() == CanonPVD) { 2598 // OpenMP [2.15.3.7, linear Clause, Restrictions] 2599 // A list-item cannot appear in more than one linear clause. 2600 if (LinearArgs.count(CanonPVD) > 0) { 2601 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2602 << getOpenMPClauseName(OMPC_linear) 2603 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 2604 Diag(LinearArgs[CanonPVD]->getExprLoc(), 2605 diag::note_omp_explicit_dsa) 2606 << getOpenMPClauseName(OMPC_linear); 2607 continue; 2608 } 2609 // Each argument can appear in at most one uniform or linear clause. 2610 if (UniformedArgs.count(CanonPVD) > 0) { 2611 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2612 << getOpenMPClauseName(OMPC_linear) 2613 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 2614 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 2615 diag::note_omp_explicit_dsa) 2616 << getOpenMPClauseName(OMPC_uniform); 2617 continue; 2618 } 2619 LinearArgs[CanonPVD] = E; 2620 if (E->isValueDependent() || E->isTypeDependent() || 2621 E->isInstantiationDependent() || 2622 E->containsUnexpandedParameterPack()) 2623 continue; 2624 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 2625 PVD->getOriginalType()); 2626 continue; 2627 } 2628 } 2629 if (isa<CXXThisExpr>(E)) { 2630 if (UniformedLinearThis) { 2631 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2632 << getOpenMPClauseName(OMPC_linear) 2633 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 2634 << E->getSourceRange(); 2635 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 2636 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 2637 : OMPC_linear); 2638 continue; 2639 } 2640 UniformedLinearThis = E; 2641 if (E->isValueDependent() || E->isTypeDependent() || 2642 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 2643 continue; 2644 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 2645 E->getType()); 2646 continue; 2647 } 2648 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2649 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2650 } 2651 Expr *Step = nullptr; 2652 Expr *NewStep = nullptr; 2653 SmallVector<Expr *, 4> NewSteps; 2654 for (auto *E : Steps) { 2655 // Skip the same step expression, it was checked already. 2656 if (Step == E || !E) { 2657 NewSteps.push_back(E ? NewStep : nullptr); 2658 continue; 2659 } 2660 Step = E; 2661 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 2662 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2663 auto *CanonPVD = PVD->getCanonicalDecl(); 2664 if (UniformedArgs.count(CanonPVD) == 0) { 2665 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 2666 << Step->getSourceRange(); 2667 } else if (E->isValueDependent() || E->isTypeDependent() || 2668 E->isInstantiationDependent() || 2669 E->containsUnexpandedParameterPack() || 2670 CanonPVD->getType()->hasIntegerRepresentation()) 2671 NewSteps.push_back(Step); 2672 else { 2673 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 2674 << Step->getSourceRange(); 2675 } 2676 continue; 2677 } 2678 NewStep = Step; 2679 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 2680 !Step->isInstantiationDependent() && 2681 !Step->containsUnexpandedParameterPack()) { 2682 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 2683 .get(); 2684 if (NewStep) 2685 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 2686 } 2687 NewSteps.push_back(NewStep); 2688 } 2689 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 2690 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 2691 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 2692 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 2693 const_cast<Expr **>(Linears.data()), Linears.size(), 2694 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 2695 NewSteps.data(), NewSteps.size(), SR); 2696 ADecl->addAttr(NewAttr); 2697 return ConvertDeclToDeclGroup(ADecl); 2698 } 2699 2700 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 2701 Stmt *AStmt, 2702 SourceLocation StartLoc, 2703 SourceLocation EndLoc) { 2704 if (!AStmt) 2705 return StmtError(); 2706 2707 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 2708 // 1.2.2 OpenMP Language Terminology 2709 // Structured block - An executable statement with a single entry at the 2710 // top and a single exit at the bottom. 2711 // The point of exit cannot be a branch out of the structured block. 2712 // longjmp() and throw() must not violate the entry/exit criteria. 2713 CS->getCapturedDecl()->setNothrow(); 2714 2715 getCurFunction()->setHasBranchProtectedScope(); 2716 2717 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 2718 DSAStack->isCancelRegion()); 2719 } 2720 2721 namespace { 2722 /// \brief Helper class for checking canonical form of the OpenMP loops and 2723 /// extracting iteration space of each loop in the loop nest, that will be used 2724 /// for IR generation. 2725 class OpenMPIterationSpaceChecker { 2726 /// \brief Reference to Sema. 2727 Sema &SemaRef; 2728 /// \brief A location for diagnostics (when there is no some better location). 2729 SourceLocation DefaultLoc; 2730 /// \brief A location for diagnostics (when increment is not compatible). 2731 SourceLocation ConditionLoc; 2732 /// \brief A source location for referring to loop init later. 2733 SourceRange InitSrcRange; 2734 /// \brief A source location for referring to condition later. 2735 SourceRange ConditionSrcRange; 2736 /// \brief A source location for referring to increment later. 2737 SourceRange IncrementSrcRange; 2738 /// \brief Loop variable. 2739 ValueDecl *LCDecl = nullptr; 2740 /// \brief Reference to loop variable. 2741 Expr *LCRef = nullptr; 2742 /// \brief Lower bound (initializer for the var). 2743 Expr *LB = nullptr; 2744 /// \brief Upper bound. 2745 Expr *UB = nullptr; 2746 /// \brief Loop step (increment). 2747 Expr *Step = nullptr; 2748 /// \brief This flag is true when condition is one of: 2749 /// Var < UB 2750 /// Var <= UB 2751 /// UB > Var 2752 /// UB >= Var 2753 bool TestIsLessOp = false; 2754 /// \brief This flag is true when condition is strict ( < or > ). 2755 bool TestIsStrictOp = false; 2756 /// \brief This flag is true when step is subtracted on each iteration. 2757 bool SubtractStep = false; 2758 2759 public: 2760 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 2761 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 2762 /// \brief Check init-expr for canonical loop form and save loop counter 2763 /// variable - #Var and its initialization value - #LB. 2764 bool CheckInit(Stmt *S, bool EmitDiags = true); 2765 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 2766 /// for less/greater and for strict/non-strict comparison. 2767 bool CheckCond(Expr *S); 2768 /// \brief Check incr-expr for canonical loop form and return true if it 2769 /// does not conform, otherwise save loop step (#Step). 2770 bool CheckInc(Expr *S); 2771 /// \brief Return the loop counter variable. 2772 ValueDecl *GetLoopDecl() const { return LCDecl; } 2773 /// \brief Return the reference expression to loop counter variable. 2774 Expr *GetLoopDeclRefExpr() const { return LCRef; } 2775 /// \brief Source range of the loop init. 2776 SourceRange GetInitSrcRange() const { return InitSrcRange; } 2777 /// \brief Source range of the loop condition. 2778 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 2779 /// \brief Source range of the loop increment. 2780 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 2781 /// \brief True if the step should be subtracted. 2782 bool ShouldSubtractStep() const { return SubtractStep; } 2783 /// \brief Build the expression to calculate the number of iterations. 2784 Expr * 2785 BuildNumIterations(Scope *S, const bool LimitedType, 2786 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 2787 /// \brief Build the precondition expression for the loops. 2788 Expr *BuildPreCond(Scope *S, Expr *Cond, 2789 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 2790 /// \brief Build reference expression to the counter be used for codegen. 2791 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 2792 DSAStackTy &DSA) const; 2793 /// \brief Build reference expression to the private counter be used for 2794 /// codegen. 2795 Expr *BuildPrivateCounterVar() const; 2796 /// \brief Build initialization of the counter be used for codegen. 2797 Expr *BuildCounterInit() const; 2798 /// \brief Build step of the counter be used for codegen. 2799 Expr *BuildCounterStep() const; 2800 /// \brief Return true if any expression is dependent. 2801 bool Dependent() const; 2802 2803 private: 2804 /// \brief Check the right-hand side of an assignment in the increment 2805 /// expression. 2806 bool CheckIncRHS(Expr *RHS); 2807 /// \brief Helper to set loop counter variable and its initializer. 2808 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 2809 /// \brief Helper to set upper bound. 2810 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 2811 SourceLocation SL); 2812 /// \brief Helper to set loop increment. 2813 bool SetStep(Expr *NewStep, bool Subtract); 2814 }; 2815 2816 bool OpenMPIterationSpaceChecker::Dependent() const { 2817 if (!LCDecl) { 2818 assert(!LB && !UB && !Step); 2819 return false; 2820 } 2821 return LCDecl->getType()->isDependentType() || 2822 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 2823 (Step && Step->isValueDependent()); 2824 } 2825 2826 static Expr *getExprAsWritten(Expr *E) { 2827 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 2828 E = ExprTemp->getSubExpr(); 2829 2830 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 2831 E = MTE->GetTemporaryExpr(); 2832 2833 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 2834 E = Binder->getSubExpr(); 2835 2836 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 2837 E = ICE->getSubExprAsWritten(); 2838 return E->IgnoreParens(); 2839 } 2840 2841 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 2842 Expr *NewLCRefExpr, 2843 Expr *NewLB) { 2844 // State consistency checking to ensure correct usage. 2845 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 2846 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 2847 if (!NewLCDecl || !NewLB) 2848 return true; 2849 LCDecl = getCanonicalDecl(NewLCDecl); 2850 LCRef = NewLCRefExpr; 2851 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 2852 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 2853 if ((Ctor->isCopyOrMoveConstructor() || 2854 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 2855 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 2856 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 2857 LB = NewLB; 2858 return false; 2859 } 2860 2861 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 2862 SourceRange SR, SourceLocation SL) { 2863 // State consistency checking to ensure correct usage. 2864 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 2865 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 2866 if (!NewUB) 2867 return true; 2868 UB = NewUB; 2869 TestIsLessOp = LessOp; 2870 TestIsStrictOp = StrictOp; 2871 ConditionSrcRange = SR; 2872 ConditionLoc = SL; 2873 return false; 2874 } 2875 2876 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 2877 // State consistency checking to ensure correct usage. 2878 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 2879 if (!NewStep) 2880 return true; 2881 if (!NewStep->isValueDependent()) { 2882 // Check that the step is integer expression. 2883 SourceLocation StepLoc = NewStep->getLocStart(); 2884 ExprResult Val = 2885 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep); 2886 if (Val.isInvalid()) 2887 return true; 2888 NewStep = Val.get(); 2889 2890 // OpenMP [2.6, Canonical Loop Form, Restrictions] 2891 // If test-expr is of form var relational-op b and relational-op is < or 2892 // <= then incr-expr must cause var to increase on each iteration of the 2893 // loop. If test-expr is of form var relational-op b and relational-op is 2894 // > or >= then incr-expr must cause var to decrease on each iteration of 2895 // the loop. 2896 // If test-expr is of form b relational-op var and relational-op is < or 2897 // <= then incr-expr must cause var to decrease on each iteration of the 2898 // loop. If test-expr is of form b relational-op var and relational-op is 2899 // > or >= then incr-expr must cause var to increase on each iteration of 2900 // the loop. 2901 llvm::APSInt Result; 2902 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 2903 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 2904 bool IsConstNeg = 2905 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 2906 bool IsConstPos = 2907 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 2908 bool IsConstZero = IsConstant && !Result.getBoolValue(); 2909 if (UB && (IsConstZero || 2910 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 2911 : (IsConstPos || (IsUnsigned && !Subtract))))) { 2912 SemaRef.Diag(NewStep->getExprLoc(), 2913 diag::err_omp_loop_incr_not_compatible) 2914 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 2915 SemaRef.Diag(ConditionLoc, 2916 diag::note_omp_loop_cond_requres_compatible_incr) 2917 << TestIsLessOp << ConditionSrcRange; 2918 return true; 2919 } 2920 if (TestIsLessOp == Subtract) { 2921 NewStep = 2922 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 2923 .get(); 2924 Subtract = !Subtract; 2925 } 2926 } 2927 2928 Step = NewStep; 2929 SubtractStep = Subtract; 2930 return false; 2931 } 2932 2933 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 2934 // Check init-expr for canonical loop form and save loop counter 2935 // variable - #Var and its initialization value - #LB. 2936 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 2937 // var = lb 2938 // integer-type var = lb 2939 // random-access-iterator-type var = lb 2940 // pointer-type var = lb 2941 // 2942 if (!S) { 2943 if (EmitDiags) { 2944 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 2945 } 2946 return true; 2947 } 2948 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 2949 if (!ExprTemp->cleanupsHaveSideEffects()) 2950 S = ExprTemp->getSubExpr(); 2951 2952 InitSrcRange = S->getSourceRange(); 2953 if (Expr *E = dyn_cast<Expr>(S)) 2954 S = E->IgnoreParens(); 2955 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 2956 if (BO->getOpcode() == BO_Assign) { 2957 auto *LHS = BO->getLHS()->IgnoreParens(); 2958 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 2959 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 2960 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 2961 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 2962 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 2963 } 2964 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 2965 if (ME->isArrow() && 2966 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 2967 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 2968 } 2969 } 2970 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 2971 if (DS->isSingleDecl()) { 2972 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 2973 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 2974 // Accept non-canonical init form here but emit ext. warning. 2975 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 2976 SemaRef.Diag(S->getLocStart(), 2977 diag::ext_omp_loop_not_canonical_init) 2978 << S->getSourceRange(); 2979 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 2980 } 2981 } 2982 } 2983 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 2984 if (CE->getOperator() == OO_Equal) { 2985 auto *LHS = CE->getArg(0); 2986 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 2987 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 2988 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 2989 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 2990 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 2991 } 2992 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 2993 if (ME->isArrow() && 2994 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 2995 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 2996 } 2997 } 2998 } 2999 3000 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3001 return false; 3002 if (EmitDiags) { 3003 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 3004 << S->getSourceRange(); 3005 } 3006 return true; 3007 } 3008 3009 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 3010 /// variable (which may be the loop variable) if possible. 3011 static const ValueDecl *GetInitLCDecl(Expr *E) { 3012 if (!E) 3013 return nullptr; 3014 E = getExprAsWritten(E); 3015 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 3016 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3017 if ((Ctor->isCopyOrMoveConstructor() || 3018 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3019 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3020 E = CE->getArg(0)->IgnoreParenImpCasts(); 3021 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 3022 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 3023 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3024 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3025 return getCanonicalDecl(ME->getMemberDecl()); 3026 return getCanonicalDecl(VD); 3027 } 3028 } 3029 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 3030 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3031 return getCanonicalDecl(ME->getMemberDecl()); 3032 return nullptr; 3033 } 3034 3035 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 3036 // Check test-expr for canonical form, save upper-bound UB, flags for 3037 // less/greater and for strict/non-strict comparison. 3038 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3039 // var relational-op b 3040 // b relational-op var 3041 // 3042 if (!S) { 3043 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 3044 return true; 3045 } 3046 S = getExprAsWritten(S); 3047 SourceLocation CondLoc = S->getLocStart(); 3048 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3049 if (BO->isRelationalOp()) { 3050 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3051 return SetUB(BO->getRHS(), 3052 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 3053 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3054 BO->getSourceRange(), BO->getOperatorLoc()); 3055 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 3056 return SetUB(BO->getLHS(), 3057 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 3058 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3059 BO->getSourceRange(), BO->getOperatorLoc()); 3060 } 3061 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3062 if (CE->getNumArgs() == 2) { 3063 auto Op = CE->getOperator(); 3064 switch (Op) { 3065 case OO_Greater: 3066 case OO_GreaterEqual: 3067 case OO_Less: 3068 case OO_LessEqual: 3069 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3070 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 3071 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3072 CE->getOperatorLoc()); 3073 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 3074 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 3075 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3076 CE->getOperatorLoc()); 3077 break; 3078 default: 3079 break; 3080 } 3081 } 3082 } 3083 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3084 return false; 3085 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 3086 << S->getSourceRange() << LCDecl; 3087 return true; 3088 } 3089 3090 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 3091 // RHS of canonical loop form increment can be: 3092 // var + incr 3093 // incr + var 3094 // var - incr 3095 // 3096 RHS = RHS->IgnoreParenImpCasts(); 3097 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 3098 if (BO->isAdditiveOp()) { 3099 bool IsAdd = BO->getOpcode() == BO_Add; 3100 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3101 return SetStep(BO->getRHS(), !IsAdd); 3102 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 3103 return SetStep(BO->getLHS(), false); 3104 } 3105 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 3106 bool IsAdd = CE->getOperator() == OO_Plus; 3107 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 3108 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3109 return SetStep(CE->getArg(1), !IsAdd); 3110 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 3111 return SetStep(CE->getArg(0), false); 3112 } 3113 } 3114 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3115 return false; 3116 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3117 << RHS->getSourceRange() << LCDecl; 3118 return true; 3119 } 3120 3121 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 3122 // Check incr-expr for canonical loop form and return true if it 3123 // does not conform. 3124 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3125 // ++var 3126 // var++ 3127 // --var 3128 // var-- 3129 // var += incr 3130 // var -= incr 3131 // var = var + incr 3132 // var = incr + var 3133 // var = var - incr 3134 // 3135 if (!S) { 3136 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 3137 return true; 3138 } 3139 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3140 if (!ExprTemp->cleanupsHaveSideEffects()) 3141 S = ExprTemp->getSubExpr(); 3142 3143 IncrementSrcRange = S->getSourceRange(); 3144 S = S->IgnoreParens(); 3145 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 3146 if (UO->isIncrementDecrementOp() && 3147 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 3148 return SetStep(SemaRef 3149 .ActOnIntegerConstant(UO->getLocStart(), 3150 (UO->isDecrementOp() ? -1 : 1)) 3151 .get(), 3152 false); 3153 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3154 switch (BO->getOpcode()) { 3155 case BO_AddAssign: 3156 case BO_SubAssign: 3157 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3158 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 3159 break; 3160 case BO_Assign: 3161 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3162 return CheckIncRHS(BO->getRHS()); 3163 break; 3164 default: 3165 break; 3166 } 3167 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3168 switch (CE->getOperator()) { 3169 case OO_PlusPlus: 3170 case OO_MinusMinus: 3171 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3172 return SetStep(SemaRef 3173 .ActOnIntegerConstant( 3174 CE->getLocStart(), 3175 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 3176 .get(), 3177 false); 3178 break; 3179 case OO_PlusEqual: 3180 case OO_MinusEqual: 3181 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3182 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 3183 break; 3184 case OO_Equal: 3185 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3186 return CheckIncRHS(CE->getArg(1)); 3187 break; 3188 default: 3189 break; 3190 } 3191 } 3192 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3193 return false; 3194 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3195 << S->getSourceRange() << LCDecl; 3196 return true; 3197 } 3198 3199 static ExprResult 3200 tryBuildCapture(Sema &SemaRef, Expr *Capture, 3201 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3202 if (SemaRef.CurContext->isDependentContext()) 3203 return ExprResult(Capture); 3204 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 3205 return SemaRef.PerformImplicitConversion( 3206 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 3207 /*AllowExplicit=*/true); 3208 auto I = Captures.find(Capture); 3209 if (I != Captures.end()) 3210 return buildCapture(SemaRef, Capture, I->second); 3211 DeclRefExpr *Ref = nullptr; 3212 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 3213 Captures[Capture] = Ref; 3214 return Res; 3215 } 3216 3217 /// \brief Build the expression to calculate the number of iterations. 3218 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 3219 Scope *S, const bool LimitedType, 3220 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3221 ExprResult Diff; 3222 auto VarType = LCDecl->getType().getNonReferenceType(); 3223 if (VarType->isIntegerType() || VarType->isPointerType() || 3224 SemaRef.getLangOpts().CPlusPlus) { 3225 // Upper - Lower 3226 auto *UBExpr = TestIsLessOp ? UB : LB; 3227 auto *LBExpr = TestIsLessOp ? LB : UB; 3228 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 3229 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 3230 if (!Upper || !Lower) 3231 return nullptr; 3232 3233 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 3234 3235 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 3236 // BuildBinOp already emitted error, this one is to point user to upper 3237 // and lower bound, and to tell what is passed to 'operator-'. 3238 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 3239 << Upper->getSourceRange() << Lower->getSourceRange(); 3240 return nullptr; 3241 } 3242 } 3243 3244 if (!Diff.isUsable()) 3245 return nullptr; 3246 3247 // Upper - Lower [- 1] 3248 if (TestIsStrictOp) 3249 Diff = SemaRef.BuildBinOp( 3250 S, DefaultLoc, BO_Sub, Diff.get(), 3251 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3252 if (!Diff.isUsable()) 3253 return nullptr; 3254 3255 // Upper - Lower [- 1] + Step 3256 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 3257 if (!NewStep.isUsable()) 3258 return nullptr; 3259 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 3260 if (!Diff.isUsable()) 3261 return nullptr; 3262 3263 // Parentheses (for dumping/debugging purposes only). 3264 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 3265 if (!Diff.isUsable()) 3266 return nullptr; 3267 3268 // (Upper - Lower [- 1] + Step) / Step 3269 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 3270 if (!Diff.isUsable()) 3271 return nullptr; 3272 3273 // OpenMP runtime requires 32-bit or 64-bit loop variables. 3274 QualType Type = Diff.get()->getType(); 3275 auto &C = SemaRef.Context; 3276 bool UseVarType = VarType->hasIntegerRepresentation() && 3277 C.getTypeSize(Type) > C.getTypeSize(VarType); 3278 if (!Type->isIntegerType() || UseVarType) { 3279 unsigned NewSize = 3280 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 3281 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 3282 : Type->hasSignedIntegerRepresentation(); 3283 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 3284 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 3285 Diff = SemaRef.PerformImplicitConversion( 3286 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 3287 if (!Diff.isUsable()) 3288 return nullptr; 3289 } 3290 } 3291 if (LimitedType) { 3292 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 3293 if (NewSize != C.getTypeSize(Type)) { 3294 if (NewSize < C.getTypeSize(Type)) { 3295 assert(NewSize == 64 && "incorrect loop var size"); 3296 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 3297 << InitSrcRange << ConditionSrcRange; 3298 } 3299 QualType NewType = C.getIntTypeForBitwidth( 3300 NewSize, Type->hasSignedIntegerRepresentation() || 3301 C.getTypeSize(Type) < NewSize); 3302 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 3303 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 3304 Sema::AA_Converting, true); 3305 if (!Diff.isUsable()) 3306 return nullptr; 3307 } 3308 } 3309 } 3310 3311 return Diff.get(); 3312 } 3313 3314 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 3315 Scope *S, Expr *Cond, 3316 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3317 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 3318 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3319 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3320 3321 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 3322 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 3323 if (!NewLB.isUsable() || !NewUB.isUsable()) 3324 return nullptr; 3325 3326 auto CondExpr = SemaRef.BuildBinOp( 3327 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 3328 : (TestIsStrictOp ? BO_GT : BO_GE), 3329 NewLB.get(), NewUB.get()); 3330 if (CondExpr.isUsable()) { 3331 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 3332 SemaRef.Context.BoolTy)) 3333 CondExpr = SemaRef.PerformImplicitConversion( 3334 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 3335 /*AllowExplicit=*/true); 3336 } 3337 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3338 // Otherwise use original loop conditon and evaluate it in runtime. 3339 return CondExpr.isUsable() ? CondExpr.get() : Cond; 3340 } 3341 3342 /// \brief Build reference expression to the counter be used for codegen. 3343 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 3344 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 3345 auto *VD = dyn_cast<VarDecl>(LCDecl); 3346 if (!VD) { 3347 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 3348 auto *Ref = buildDeclRefExpr( 3349 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 3350 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 3351 // If the loop control decl is explicitly marked as private, do not mark it 3352 // as captured again. 3353 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 3354 Captures.insert(std::make_pair(LCRef, Ref)); 3355 return Ref; 3356 } 3357 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 3358 DefaultLoc); 3359 } 3360 3361 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 3362 if (LCDecl && !LCDecl->isInvalidDecl()) { 3363 auto Type = LCDecl->getType().getNonReferenceType(); 3364 auto *PrivateVar = 3365 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 3366 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 3367 if (PrivateVar->isInvalidDecl()) 3368 return nullptr; 3369 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 3370 } 3371 return nullptr; 3372 } 3373 3374 /// \brief Build initialization of the counter to be used for codegen. 3375 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 3376 3377 /// \brief Build step of the counter be used for codegen. 3378 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 3379 3380 /// \brief Iteration space of a single for loop. 3381 struct LoopIterationSpace final { 3382 /// \brief Condition of the loop. 3383 Expr *PreCond = nullptr; 3384 /// \brief This expression calculates the number of iterations in the loop. 3385 /// It is always possible to calculate it before starting the loop. 3386 Expr *NumIterations = nullptr; 3387 /// \brief The loop counter variable. 3388 Expr *CounterVar = nullptr; 3389 /// \brief Private loop counter variable. 3390 Expr *PrivateCounterVar = nullptr; 3391 /// \brief This is initializer for the initial value of #CounterVar. 3392 Expr *CounterInit = nullptr; 3393 /// \brief This is step for the #CounterVar used to generate its update: 3394 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 3395 Expr *CounterStep = nullptr; 3396 /// \brief Should step be subtracted? 3397 bool Subtract = false; 3398 /// \brief Source range of the loop init. 3399 SourceRange InitSrcRange; 3400 /// \brief Source range of the loop condition. 3401 SourceRange CondSrcRange; 3402 /// \brief Source range of the loop increment. 3403 SourceRange IncSrcRange; 3404 }; 3405 3406 } // namespace 3407 3408 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 3409 assert(getLangOpts().OpenMP && "OpenMP is not active."); 3410 assert(Init && "Expected loop in canonical form."); 3411 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 3412 if (AssociatedLoops > 0 && 3413 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 3414 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 3415 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 3416 if (auto *D = ISC.GetLoopDecl()) { 3417 auto *VD = dyn_cast<VarDecl>(D); 3418 if (!VD) { 3419 if (auto *Private = IsOpenMPCapturedDecl(D)) 3420 VD = Private; 3421 else { 3422 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 3423 /*WithInit=*/false); 3424 VD = cast<VarDecl>(Ref->getDecl()); 3425 } 3426 } 3427 DSAStack->addLoopControlVariable(D, VD); 3428 } 3429 } 3430 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 3431 } 3432 } 3433 3434 /// \brief Called on a for stmt to check and extract its iteration space 3435 /// for further processing (such as collapsing). 3436 static bool CheckOpenMPIterationSpace( 3437 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 3438 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 3439 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 3440 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3441 LoopIterationSpace &ResultIterSpace, 3442 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3443 // OpenMP [2.6, Canonical Loop Form] 3444 // for (init-expr; test-expr; incr-expr) structured-block 3445 auto *For = dyn_cast_or_null<ForStmt>(S); 3446 if (!For) { 3447 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 3448 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 3449 << getOpenMPDirectiveName(DKind) << NestedLoopCount 3450 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 3451 if (NestedLoopCount > 1) { 3452 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 3453 SemaRef.Diag(DSA.getConstructLoc(), 3454 diag::note_omp_collapse_ordered_expr) 3455 << 2 << CollapseLoopCountExpr->getSourceRange() 3456 << OrderedLoopCountExpr->getSourceRange(); 3457 else if (CollapseLoopCountExpr) 3458 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3459 diag::note_omp_collapse_ordered_expr) 3460 << 0 << CollapseLoopCountExpr->getSourceRange(); 3461 else 3462 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3463 diag::note_omp_collapse_ordered_expr) 3464 << 1 << OrderedLoopCountExpr->getSourceRange(); 3465 } 3466 return true; 3467 } 3468 assert(For->getBody()); 3469 3470 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 3471 3472 // Check init. 3473 auto Init = For->getInit(); 3474 if (ISC.CheckInit(Init)) 3475 return true; 3476 3477 bool HasErrors = false; 3478 3479 // Check loop variable's type. 3480 if (auto *LCDecl = ISC.GetLoopDecl()) { 3481 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 3482 3483 // OpenMP [2.6, Canonical Loop Form] 3484 // Var is one of the following: 3485 // A variable of signed or unsigned integer type. 3486 // For C++, a variable of a random access iterator type. 3487 // For C, a variable of a pointer type. 3488 auto VarType = LCDecl->getType().getNonReferenceType(); 3489 if (!VarType->isDependentType() && !VarType->isIntegerType() && 3490 !VarType->isPointerType() && 3491 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 3492 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 3493 << SemaRef.getLangOpts().CPlusPlus; 3494 HasErrors = true; 3495 } 3496 3497 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 3498 // a Construct 3499 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3500 // parallel for construct is (are) private. 3501 // The loop iteration variable in the associated for-loop of a simd 3502 // construct with just one associated for-loop is linear with a 3503 // constant-linear-step that is the increment of the associated for-loop. 3504 // Exclude loop var from the list of variables with implicitly defined data 3505 // sharing attributes. 3506 VarsWithImplicitDSA.erase(LCDecl); 3507 3508 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 3509 // in a Construct, C/C++]. 3510 // The loop iteration variable in the associated for-loop of a simd 3511 // construct with just one associated for-loop may be listed in a linear 3512 // clause with a constant-linear-step that is the increment of the 3513 // associated for-loop. 3514 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3515 // parallel for construct may be listed in a private or lastprivate clause. 3516 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 3517 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 3518 // declared in the loop and it is predetermined as a private. 3519 auto PredeterminedCKind = 3520 isOpenMPSimdDirective(DKind) 3521 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 3522 : OMPC_private; 3523 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3524 DVar.CKind != PredeterminedCKind) || 3525 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 3526 isOpenMPDistributeDirective(DKind)) && 3527 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3528 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 3529 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 3530 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 3531 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 3532 << getOpenMPClauseName(PredeterminedCKind); 3533 if (DVar.RefExpr == nullptr) 3534 DVar.CKind = PredeterminedCKind; 3535 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 3536 HasErrors = true; 3537 } else if (LoopDeclRefExpr != nullptr) { 3538 // Make the loop iteration variable private (for worksharing constructs), 3539 // linear (for simd directives with the only one associated loop) or 3540 // lastprivate (for simd directives with several collapsed or ordered 3541 // loops). 3542 if (DVar.CKind == OMPC_unknown) 3543 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 3544 [](OpenMPDirectiveKind) -> bool { return true; }, 3545 /*FromParent=*/false); 3546 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 3547 } 3548 3549 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 3550 3551 // Check test-expr. 3552 HasErrors |= ISC.CheckCond(For->getCond()); 3553 3554 // Check incr-expr. 3555 HasErrors |= ISC.CheckInc(For->getInc()); 3556 } 3557 3558 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 3559 return HasErrors; 3560 3561 // Build the loop's iteration space representation. 3562 ResultIterSpace.PreCond = 3563 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 3564 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 3565 DSA.getCurScope(), 3566 (isOpenMPWorksharingDirective(DKind) || 3567 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 3568 Captures); 3569 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 3570 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 3571 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 3572 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 3573 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 3574 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 3575 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 3576 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 3577 3578 HasErrors |= (ResultIterSpace.PreCond == nullptr || 3579 ResultIterSpace.NumIterations == nullptr || 3580 ResultIterSpace.CounterVar == nullptr || 3581 ResultIterSpace.PrivateCounterVar == nullptr || 3582 ResultIterSpace.CounterInit == nullptr || 3583 ResultIterSpace.CounterStep == nullptr); 3584 3585 return HasErrors; 3586 } 3587 3588 /// \brief Build 'VarRef = Start. 3589 static ExprResult 3590 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 3591 ExprResult Start, 3592 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3593 // Build 'VarRef = Start. 3594 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 3595 if (!NewStart.isUsable()) 3596 return ExprError(); 3597 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 3598 VarRef.get()->getType())) { 3599 NewStart = SemaRef.PerformImplicitConversion( 3600 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 3601 /*AllowExplicit=*/true); 3602 if (!NewStart.isUsable()) 3603 return ExprError(); 3604 } 3605 3606 auto Init = 3607 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3608 return Init; 3609 } 3610 3611 /// \brief Build 'VarRef = Start + Iter * Step'. 3612 static ExprResult 3613 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 3614 ExprResult VarRef, ExprResult Start, ExprResult Iter, 3615 ExprResult Step, bool Subtract, 3616 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 3617 // Add parentheses (for debugging purposes only). 3618 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 3619 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 3620 !Step.isUsable()) 3621 return ExprError(); 3622 3623 ExprResult NewStep = Step; 3624 if (Captures) 3625 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 3626 if (NewStep.isInvalid()) 3627 return ExprError(); 3628 ExprResult Update = 3629 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 3630 if (!Update.isUsable()) 3631 return ExprError(); 3632 3633 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 3634 // 'VarRef = Start (+|-) Iter * Step'. 3635 ExprResult NewStart = Start; 3636 if (Captures) 3637 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 3638 if (NewStart.isInvalid()) 3639 return ExprError(); 3640 3641 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 3642 ExprResult SavedUpdate = Update; 3643 ExprResult UpdateVal; 3644 if (VarRef.get()->getType()->isOverloadableType() || 3645 NewStart.get()->getType()->isOverloadableType() || 3646 Update.get()->getType()->isOverloadableType()) { 3647 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3648 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3649 Update = 3650 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3651 if (Update.isUsable()) { 3652 UpdateVal = 3653 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 3654 VarRef.get(), SavedUpdate.get()); 3655 if (UpdateVal.isUsable()) { 3656 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 3657 UpdateVal.get()); 3658 } 3659 } 3660 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3661 } 3662 3663 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 3664 if (!Update.isUsable() || !UpdateVal.isUsable()) { 3665 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 3666 NewStart.get(), SavedUpdate.get()); 3667 if (!Update.isUsable()) 3668 return ExprError(); 3669 3670 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 3671 VarRef.get()->getType())) { 3672 Update = SemaRef.PerformImplicitConversion( 3673 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 3674 if (!Update.isUsable()) 3675 return ExprError(); 3676 } 3677 3678 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 3679 } 3680 return Update; 3681 } 3682 3683 /// \brief Convert integer expression \a E to make it have at least \a Bits 3684 /// bits. 3685 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 3686 if (E == nullptr) 3687 return ExprError(); 3688 auto &C = SemaRef.Context; 3689 QualType OldType = E->getType(); 3690 unsigned HasBits = C.getTypeSize(OldType); 3691 if (HasBits >= Bits) 3692 return ExprResult(E); 3693 // OK to convert to signed, because new type has more bits than old. 3694 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 3695 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 3696 true); 3697 } 3698 3699 /// \brief Check if the given expression \a E is a constant integer that fits 3700 /// into \a Bits bits. 3701 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 3702 if (E == nullptr) 3703 return false; 3704 llvm::APSInt Result; 3705 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 3706 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 3707 return false; 3708 } 3709 3710 /// Build preinits statement for the given declarations. 3711 static Stmt *buildPreInits(ASTContext &Context, 3712 SmallVectorImpl<Decl *> &PreInits) { 3713 if (!PreInits.empty()) { 3714 return new (Context) DeclStmt( 3715 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 3716 SourceLocation(), SourceLocation()); 3717 } 3718 return nullptr; 3719 } 3720 3721 /// Build preinits statement for the given declarations. 3722 static Stmt *buildPreInits(ASTContext &Context, 3723 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3724 if (!Captures.empty()) { 3725 SmallVector<Decl *, 16> PreInits; 3726 for (auto &Pair : Captures) 3727 PreInits.push_back(Pair.second->getDecl()); 3728 return buildPreInits(Context, PreInits); 3729 } 3730 return nullptr; 3731 } 3732 3733 /// Build postupdate expression for the given list of postupdates expressions. 3734 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 3735 Expr *PostUpdate = nullptr; 3736 if (!PostUpdates.empty()) { 3737 for (auto *E : PostUpdates) { 3738 Expr *ConvE = S.BuildCStyleCastExpr( 3739 E->getExprLoc(), 3740 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 3741 E->getExprLoc(), E) 3742 .get(); 3743 PostUpdate = PostUpdate 3744 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 3745 PostUpdate, ConvE) 3746 .get() 3747 : ConvE; 3748 } 3749 } 3750 return PostUpdate; 3751 } 3752 3753 /// \brief Called on a for stmt to check itself and nested loops (if any). 3754 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 3755 /// number of collapsed loops otherwise. 3756 static unsigned 3757 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 3758 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 3759 DSAStackTy &DSA, 3760 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3761 OMPLoopDirective::HelperExprs &Built) { 3762 unsigned NestedLoopCount = 1; 3763 if (CollapseLoopCountExpr) { 3764 // Found 'collapse' clause - calculate collapse number. 3765 llvm::APSInt Result; 3766 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 3767 NestedLoopCount = Result.getLimitedValue(); 3768 } 3769 if (OrderedLoopCountExpr) { 3770 // Found 'ordered' clause - calculate collapse number. 3771 llvm::APSInt Result; 3772 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 3773 if (Result.getLimitedValue() < NestedLoopCount) { 3774 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3775 diag::err_omp_wrong_ordered_loop_count) 3776 << OrderedLoopCountExpr->getSourceRange(); 3777 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3778 diag::note_collapse_loop_count) 3779 << CollapseLoopCountExpr->getSourceRange(); 3780 } 3781 NestedLoopCount = Result.getLimitedValue(); 3782 } 3783 } 3784 // This is helper routine for loop directives (e.g., 'for', 'simd', 3785 // 'for simd', etc.). 3786 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 3787 SmallVector<LoopIterationSpace, 4> IterSpaces; 3788 IterSpaces.resize(NestedLoopCount); 3789 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 3790 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 3791 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 3792 NestedLoopCount, CollapseLoopCountExpr, 3793 OrderedLoopCountExpr, VarsWithImplicitDSA, 3794 IterSpaces[Cnt], Captures)) 3795 return 0; 3796 // Move on to the next nested for loop, or to the loop body. 3797 // OpenMP [2.8.1, simd construct, Restrictions] 3798 // All loops associated with the construct must be perfectly nested; that 3799 // is, there must be no intervening code nor any OpenMP directive between 3800 // any two loops. 3801 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 3802 } 3803 3804 Built.clear(/* size */ NestedLoopCount); 3805 3806 if (SemaRef.CurContext->isDependentContext()) 3807 return NestedLoopCount; 3808 3809 // An example of what is generated for the following code: 3810 // 3811 // #pragma omp simd collapse(2) ordered(2) 3812 // for (i = 0; i < NI; ++i) 3813 // for (k = 0; k < NK; ++k) 3814 // for (j = J0; j < NJ; j+=2) { 3815 // <loop body> 3816 // } 3817 // 3818 // We generate the code below. 3819 // Note: the loop body may be outlined in CodeGen. 3820 // Note: some counters may be C++ classes, operator- is used to find number of 3821 // iterations and operator+= to calculate counter value. 3822 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 3823 // or i64 is currently supported). 3824 // 3825 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 3826 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 3827 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 3828 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 3829 // // similar updates for vars in clauses (e.g. 'linear') 3830 // <loop body (using local i and j)> 3831 // } 3832 // i = NI; // assign final values of counters 3833 // j = NJ; 3834 // 3835 3836 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 3837 // the iteration counts of the collapsed for loops. 3838 // Precondition tests if there is at least one iteration (all conditions are 3839 // true). 3840 auto PreCond = ExprResult(IterSpaces[0].PreCond); 3841 auto N0 = IterSpaces[0].NumIterations; 3842 ExprResult LastIteration32 = WidenIterationCount( 3843 32 /* Bits */, SemaRef 3844 .PerformImplicitConversion( 3845 N0->IgnoreImpCasts(), N0->getType(), 3846 Sema::AA_Converting, /*AllowExplicit=*/true) 3847 .get(), 3848 SemaRef); 3849 ExprResult LastIteration64 = WidenIterationCount( 3850 64 /* Bits */, SemaRef 3851 .PerformImplicitConversion( 3852 N0->IgnoreImpCasts(), N0->getType(), 3853 Sema::AA_Converting, /*AllowExplicit=*/true) 3854 .get(), 3855 SemaRef); 3856 3857 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 3858 return NestedLoopCount; 3859 3860 auto &C = SemaRef.Context; 3861 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 3862 3863 Scope *CurScope = DSA.getCurScope(); 3864 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 3865 if (PreCond.isUsable()) { 3866 PreCond = 3867 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 3868 PreCond.get(), IterSpaces[Cnt].PreCond); 3869 } 3870 auto N = IterSpaces[Cnt].NumIterations; 3871 SourceLocation Loc = N->getExprLoc(); 3872 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 3873 if (LastIteration32.isUsable()) 3874 LastIteration32 = SemaRef.BuildBinOp( 3875 CurScope, Loc, BO_Mul, LastIteration32.get(), 3876 SemaRef 3877 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 3878 Sema::AA_Converting, 3879 /*AllowExplicit=*/true) 3880 .get()); 3881 if (LastIteration64.isUsable()) 3882 LastIteration64 = SemaRef.BuildBinOp( 3883 CurScope, Loc, BO_Mul, LastIteration64.get(), 3884 SemaRef 3885 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 3886 Sema::AA_Converting, 3887 /*AllowExplicit=*/true) 3888 .get()); 3889 } 3890 3891 // Choose either the 32-bit or 64-bit version. 3892 ExprResult LastIteration = LastIteration64; 3893 if (LastIteration32.isUsable() && 3894 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 3895 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 3896 FitsInto( 3897 32 /* Bits */, 3898 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 3899 LastIteration64.get(), SemaRef))) 3900 LastIteration = LastIteration32; 3901 QualType VType = LastIteration.get()->getType(); 3902 QualType RealVType = VType; 3903 QualType StrideVType = VType; 3904 if (isOpenMPTaskLoopDirective(DKind)) { 3905 VType = 3906 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 3907 StrideVType = 3908 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 3909 } 3910 3911 if (!LastIteration.isUsable()) 3912 return 0; 3913 3914 // Save the number of iterations. 3915 ExprResult NumIterations = LastIteration; 3916 { 3917 LastIteration = SemaRef.BuildBinOp( 3918 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 3919 LastIteration.get(), 3920 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3921 if (!LastIteration.isUsable()) 3922 return 0; 3923 } 3924 3925 // Calculate the last iteration number beforehand instead of doing this on 3926 // each iteration. Do not do this if the number of iterations may be kfold-ed. 3927 llvm::APSInt Result; 3928 bool IsConstant = 3929 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 3930 ExprResult CalcLastIteration; 3931 if (!IsConstant) { 3932 ExprResult SaveRef = 3933 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 3934 LastIteration = SaveRef; 3935 3936 // Prepare SaveRef + 1. 3937 NumIterations = SemaRef.BuildBinOp( 3938 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 3939 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3940 if (!NumIterations.isUsable()) 3941 return 0; 3942 } 3943 3944 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 3945 3946 // Build variables passed into runtime, necessary for worksharing directives. 3947 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB; 3948 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 3949 isOpenMPDistributeDirective(DKind)) { 3950 // Lower bound variable, initialized with zero. 3951 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 3952 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 3953 SemaRef.AddInitializerToDecl( 3954 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 3955 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 3956 3957 // Upper bound variable, initialized with last iteration number. 3958 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 3959 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 3960 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 3961 /*DirectInit*/ false, 3962 /*TypeMayContainAuto*/ false); 3963 3964 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 3965 // This will be used to implement clause 'lastprivate'. 3966 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 3967 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 3968 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 3969 SemaRef.AddInitializerToDecl( 3970 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 3971 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 3972 3973 // Stride variable returned by runtime (we initialize it to 1 by default). 3974 VarDecl *STDecl = 3975 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 3976 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 3977 SemaRef.AddInitializerToDecl( 3978 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 3979 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 3980 3981 // Build expression: UB = min(UB, LastIteration) 3982 // It is necessary for CodeGen of directives with static scheduling. 3983 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 3984 UB.get(), LastIteration.get()); 3985 ExprResult CondOp = SemaRef.ActOnConditionalOp( 3986 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 3987 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 3988 CondOp.get()); 3989 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 3990 3991 // If we have a combined directive that combines 'distribute', 'for' or 3992 // 'simd' we need to be able to access the bounds of the schedule of the 3993 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 3994 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 3995 if (isOpenMPLoopBoundSharingDirective(DKind)) { 3996 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 3997 3998 // We expect to have at least 2 more parameters than the 'parallel' 3999 // directive does - the lower and upper bounds of the previous schedule. 4000 assert(CD->getNumParams() >= 4 && 4001 "Unexpected number of parameters in loop combined directive"); 4002 4003 // Set the proper type for the bounds given what we learned from the 4004 // enclosed loops. 4005 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 4006 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 4007 4008 // Previous lower and upper bounds are obtained from the region 4009 // parameters. 4010 PrevLB = 4011 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 4012 PrevUB = 4013 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 4014 } 4015 } 4016 4017 // Build the iteration variable and its initialization before loop. 4018 ExprResult IV; 4019 ExprResult Init; 4020 { 4021 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 4022 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 4023 Expr *RHS = 4024 (isOpenMPWorksharingDirective(DKind) || 4025 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4026 ? LB.get() 4027 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4028 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 4029 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 4030 } 4031 4032 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 4033 SourceLocation CondLoc; 4034 ExprResult Cond = 4035 (isOpenMPWorksharingDirective(DKind) || 4036 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4037 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 4038 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 4039 NumIterations.get()); 4040 4041 // Loop increment (IV = IV + 1) 4042 SourceLocation IncLoc; 4043 ExprResult Inc = 4044 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 4045 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 4046 if (!Inc.isUsable()) 4047 return 0; 4048 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 4049 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 4050 if (!Inc.isUsable()) 4051 return 0; 4052 4053 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 4054 // Used for directives with static scheduling. 4055 ExprResult NextLB, NextUB; 4056 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4057 isOpenMPDistributeDirective(DKind)) { 4058 // LB + ST 4059 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 4060 if (!NextLB.isUsable()) 4061 return 0; 4062 // LB = LB + ST 4063 NextLB = 4064 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 4065 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 4066 if (!NextLB.isUsable()) 4067 return 0; 4068 // UB + ST 4069 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 4070 if (!NextUB.isUsable()) 4071 return 0; 4072 // UB = UB + ST 4073 NextUB = 4074 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 4075 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 4076 if (!NextUB.isUsable()) 4077 return 0; 4078 } 4079 4080 // Build updates and final values of the loop counters. 4081 bool HasErrors = false; 4082 Built.Counters.resize(NestedLoopCount); 4083 Built.Inits.resize(NestedLoopCount); 4084 Built.Updates.resize(NestedLoopCount); 4085 Built.Finals.resize(NestedLoopCount); 4086 SmallVector<Expr *, 4> LoopMultipliers; 4087 { 4088 ExprResult Div; 4089 // Go from inner nested loop to outer. 4090 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4091 LoopIterationSpace &IS = IterSpaces[Cnt]; 4092 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 4093 // Build: Iter = (IV / Div) % IS.NumIters 4094 // where Div is product of previous iterations' IS.NumIters. 4095 ExprResult Iter; 4096 if (Div.isUsable()) { 4097 Iter = 4098 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 4099 } else { 4100 Iter = IV; 4101 assert((Cnt == (int)NestedLoopCount - 1) && 4102 "unusable div expected on first iteration only"); 4103 } 4104 4105 if (Cnt != 0 && Iter.isUsable()) 4106 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 4107 IS.NumIterations); 4108 if (!Iter.isUsable()) { 4109 HasErrors = true; 4110 break; 4111 } 4112 4113 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 4114 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 4115 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 4116 IS.CounterVar->getExprLoc(), 4117 /*RefersToCapture=*/true); 4118 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 4119 IS.CounterInit, Captures); 4120 if (!Init.isUsable()) { 4121 HasErrors = true; 4122 break; 4123 } 4124 ExprResult Update = BuildCounterUpdate( 4125 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 4126 IS.CounterStep, IS.Subtract, &Captures); 4127 if (!Update.isUsable()) { 4128 HasErrors = true; 4129 break; 4130 } 4131 4132 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 4133 ExprResult Final = BuildCounterUpdate( 4134 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 4135 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 4136 if (!Final.isUsable()) { 4137 HasErrors = true; 4138 break; 4139 } 4140 4141 // Build Div for the next iteration: Div <- Div * IS.NumIters 4142 if (Cnt != 0) { 4143 if (Div.isUnset()) 4144 Div = IS.NumIterations; 4145 else 4146 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 4147 IS.NumIterations); 4148 4149 // Add parentheses (for debugging purposes only). 4150 if (Div.isUsable()) 4151 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 4152 if (!Div.isUsable()) { 4153 HasErrors = true; 4154 break; 4155 } 4156 LoopMultipliers.push_back(Div.get()); 4157 } 4158 if (!Update.isUsable() || !Final.isUsable()) { 4159 HasErrors = true; 4160 break; 4161 } 4162 // Save results 4163 Built.Counters[Cnt] = IS.CounterVar; 4164 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 4165 Built.Inits[Cnt] = Init.get(); 4166 Built.Updates[Cnt] = Update.get(); 4167 Built.Finals[Cnt] = Final.get(); 4168 } 4169 } 4170 4171 if (HasErrors) 4172 return 0; 4173 4174 // Save results 4175 Built.IterationVarRef = IV.get(); 4176 Built.LastIteration = LastIteration.get(); 4177 Built.NumIterations = NumIterations.get(); 4178 Built.CalcLastIteration = 4179 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 4180 Built.PreCond = PreCond.get(); 4181 Built.PreInits = buildPreInits(C, Captures); 4182 Built.Cond = Cond.get(); 4183 Built.Init = Init.get(); 4184 Built.Inc = Inc.get(); 4185 Built.LB = LB.get(); 4186 Built.UB = UB.get(); 4187 Built.IL = IL.get(); 4188 Built.ST = ST.get(); 4189 Built.EUB = EUB.get(); 4190 Built.NLB = NextLB.get(); 4191 Built.NUB = NextUB.get(); 4192 Built.PrevLB = PrevLB.get(); 4193 Built.PrevUB = PrevUB.get(); 4194 4195 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 4196 // Fill data for doacross depend clauses. 4197 for (auto Pair : DSA.getDoacrossDependClauses()) { 4198 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 4199 Pair.first->setCounterValue(CounterVal); 4200 else { 4201 if (NestedLoopCount != Pair.second.size() || 4202 NestedLoopCount != LoopMultipliers.size() + 1) { 4203 // Erroneous case - clause has some problems. 4204 Pair.first->setCounterValue(CounterVal); 4205 continue; 4206 } 4207 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 4208 auto I = Pair.second.rbegin(); 4209 auto IS = IterSpaces.rbegin(); 4210 auto ILM = LoopMultipliers.rbegin(); 4211 Expr *UpCounterVal = CounterVal; 4212 Expr *Multiplier = nullptr; 4213 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4214 if (I->first) { 4215 assert(IS->CounterStep); 4216 Expr *NormalizedOffset = 4217 SemaRef 4218 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 4219 I->first, IS->CounterStep) 4220 .get(); 4221 if (Multiplier) { 4222 NormalizedOffset = 4223 SemaRef 4224 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 4225 NormalizedOffset, Multiplier) 4226 .get(); 4227 } 4228 assert(I->second == OO_Plus || I->second == OO_Minus); 4229 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 4230 UpCounterVal = SemaRef 4231 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 4232 UpCounterVal, NormalizedOffset) 4233 .get(); 4234 } 4235 Multiplier = *ILM; 4236 ++I; 4237 ++IS; 4238 ++ILM; 4239 } 4240 Pair.first->setCounterValue(UpCounterVal); 4241 } 4242 } 4243 4244 return NestedLoopCount; 4245 } 4246 4247 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 4248 auto CollapseClauses = 4249 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 4250 if (CollapseClauses.begin() != CollapseClauses.end()) 4251 return (*CollapseClauses.begin())->getNumForLoops(); 4252 return nullptr; 4253 } 4254 4255 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 4256 auto OrderedClauses = 4257 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 4258 if (OrderedClauses.begin() != OrderedClauses.end()) 4259 return (*OrderedClauses.begin())->getNumForLoops(); 4260 return nullptr; 4261 } 4262 4263 static bool checkSimdlenSafelenSpecified(Sema &S, 4264 const ArrayRef<OMPClause *> Clauses) { 4265 OMPSafelenClause *Safelen = nullptr; 4266 OMPSimdlenClause *Simdlen = nullptr; 4267 4268 for (auto *Clause : Clauses) { 4269 if (Clause->getClauseKind() == OMPC_safelen) 4270 Safelen = cast<OMPSafelenClause>(Clause); 4271 else if (Clause->getClauseKind() == OMPC_simdlen) 4272 Simdlen = cast<OMPSimdlenClause>(Clause); 4273 if (Safelen && Simdlen) 4274 break; 4275 } 4276 4277 if (Simdlen && Safelen) { 4278 llvm::APSInt SimdlenRes, SafelenRes; 4279 auto SimdlenLength = Simdlen->getSimdlen(); 4280 auto SafelenLength = Safelen->getSafelen(); 4281 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 4282 SimdlenLength->isInstantiationDependent() || 4283 SimdlenLength->containsUnexpandedParameterPack()) 4284 return false; 4285 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 4286 SafelenLength->isInstantiationDependent() || 4287 SafelenLength->containsUnexpandedParameterPack()) 4288 return false; 4289 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 4290 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 4291 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 4292 // If both simdlen and safelen clauses are specified, the value of the 4293 // simdlen parameter must be less than or equal to the value of the safelen 4294 // parameter. 4295 if (SimdlenRes > SafelenRes) { 4296 S.Diag(SimdlenLength->getExprLoc(), 4297 diag::err_omp_wrong_simdlen_safelen_values) 4298 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 4299 return true; 4300 } 4301 } 4302 return false; 4303 } 4304 4305 StmtResult Sema::ActOnOpenMPSimdDirective( 4306 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4307 SourceLocation EndLoc, 4308 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4309 if (!AStmt) 4310 return StmtError(); 4311 4312 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4313 OMPLoopDirective::HelperExprs B; 4314 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4315 // define the nested loops number. 4316 unsigned NestedLoopCount = CheckOpenMPLoop( 4317 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4318 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4319 if (NestedLoopCount == 0) 4320 return StmtError(); 4321 4322 assert((CurContext->isDependentContext() || B.builtAll()) && 4323 "omp simd loop exprs were not built"); 4324 4325 if (!CurContext->isDependentContext()) { 4326 // Finalize the clauses that need pre-built expressions for CodeGen. 4327 for (auto C : Clauses) { 4328 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4329 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4330 B.NumIterations, *this, CurScope, 4331 DSAStack)) 4332 return StmtError(); 4333 } 4334 } 4335 4336 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4337 return StmtError(); 4338 4339 getCurFunction()->setHasBranchProtectedScope(); 4340 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4341 Clauses, AStmt, B); 4342 } 4343 4344 StmtResult Sema::ActOnOpenMPForDirective( 4345 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4346 SourceLocation EndLoc, 4347 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4348 if (!AStmt) 4349 return StmtError(); 4350 4351 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4352 OMPLoopDirective::HelperExprs B; 4353 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4354 // define the nested loops number. 4355 unsigned NestedLoopCount = CheckOpenMPLoop( 4356 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4357 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4358 if (NestedLoopCount == 0) 4359 return StmtError(); 4360 4361 assert((CurContext->isDependentContext() || B.builtAll()) && 4362 "omp for loop exprs were not built"); 4363 4364 if (!CurContext->isDependentContext()) { 4365 // Finalize the clauses that need pre-built expressions for CodeGen. 4366 for (auto C : Clauses) { 4367 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4368 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4369 B.NumIterations, *this, CurScope, 4370 DSAStack)) 4371 return StmtError(); 4372 } 4373 } 4374 4375 getCurFunction()->setHasBranchProtectedScope(); 4376 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4377 Clauses, AStmt, B, DSAStack->isCancelRegion()); 4378 } 4379 4380 StmtResult Sema::ActOnOpenMPForSimdDirective( 4381 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4382 SourceLocation EndLoc, 4383 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4384 if (!AStmt) 4385 return StmtError(); 4386 4387 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4388 OMPLoopDirective::HelperExprs B; 4389 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4390 // define the nested loops number. 4391 unsigned NestedLoopCount = 4392 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 4393 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4394 VarsWithImplicitDSA, B); 4395 if (NestedLoopCount == 0) 4396 return StmtError(); 4397 4398 assert((CurContext->isDependentContext() || B.builtAll()) && 4399 "omp for simd loop exprs were not built"); 4400 4401 if (!CurContext->isDependentContext()) { 4402 // Finalize the clauses that need pre-built expressions for CodeGen. 4403 for (auto C : Clauses) { 4404 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4405 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4406 B.NumIterations, *this, CurScope, 4407 DSAStack)) 4408 return StmtError(); 4409 } 4410 } 4411 4412 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4413 return StmtError(); 4414 4415 getCurFunction()->setHasBranchProtectedScope(); 4416 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4417 Clauses, AStmt, B); 4418 } 4419 4420 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 4421 Stmt *AStmt, 4422 SourceLocation StartLoc, 4423 SourceLocation EndLoc) { 4424 if (!AStmt) 4425 return StmtError(); 4426 4427 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4428 auto BaseStmt = AStmt; 4429 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4430 BaseStmt = CS->getCapturedStmt(); 4431 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4432 auto S = C->children(); 4433 if (S.begin() == S.end()) 4434 return StmtError(); 4435 // All associated statements must be '#pragma omp section' except for 4436 // the first one. 4437 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4438 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4439 if (SectionStmt) 4440 Diag(SectionStmt->getLocStart(), 4441 diag::err_omp_sections_substmt_not_section); 4442 return StmtError(); 4443 } 4444 cast<OMPSectionDirective>(SectionStmt) 4445 ->setHasCancel(DSAStack->isCancelRegion()); 4446 } 4447 } else { 4448 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 4449 return StmtError(); 4450 } 4451 4452 getCurFunction()->setHasBranchProtectedScope(); 4453 4454 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4455 DSAStack->isCancelRegion()); 4456 } 4457 4458 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 4459 SourceLocation StartLoc, 4460 SourceLocation EndLoc) { 4461 if (!AStmt) 4462 return StmtError(); 4463 4464 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4465 4466 getCurFunction()->setHasBranchProtectedScope(); 4467 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 4468 4469 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 4470 DSAStack->isCancelRegion()); 4471 } 4472 4473 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 4474 Stmt *AStmt, 4475 SourceLocation StartLoc, 4476 SourceLocation EndLoc) { 4477 if (!AStmt) 4478 return StmtError(); 4479 4480 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4481 4482 getCurFunction()->setHasBranchProtectedScope(); 4483 4484 // OpenMP [2.7.3, single Construct, Restrictions] 4485 // The copyprivate clause must not be used with the nowait clause. 4486 OMPClause *Nowait = nullptr; 4487 OMPClause *Copyprivate = nullptr; 4488 for (auto *Clause : Clauses) { 4489 if (Clause->getClauseKind() == OMPC_nowait) 4490 Nowait = Clause; 4491 else if (Clause->getClauseKind() == OMPC_copyprivate) 4492 Copyprivate = Clause; 4493 if (Copyprivate && Nowait) { 4494 Diag(Copyprivate->getLocStart(), 4495 diag::err_omp_single_copyprivate_with_nowait); 4496 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 4497 return StmtError(); 4498 } 4499 } 4500 4501 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 4502 } 4503 4504 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 4505 SourceLocation StartLoc, 4506 SourceLocation EndLoc) { 4507 if (!AStmt) 4508 return StmtError(); 4509 4510 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4511 4512 getCurFunction()->setHasBranchProtectedScope(); 4513 4514 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 4515 } 4516 4517 StmtResult Sema::ActOnOpenMPCriticalDirective( 4518 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 4519 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 4520 if (!AStmt) 4521 return StmtError(); 4522 4523 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4524 4525 bool ErrorFound = false; 4526 llvm::APSInt Hint; 4527 SourceLocation HintLoc; 4528 bool DependentHint = false; 4529 for (auto *C : Clauses) { 4530 if (C->getClauseKind() == OMPC_hint) { 4531 if (!DirName.getName()) { 4532 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 4533 ErrorFound = true; 4534 } 4535 Expr *E = cast<OMPHintClause>(C)->getHint(); 4536 if (E->isTypeDependent() || E->isValueDependent() || 4537 E->isInstantiationDependent()) 4538 DependentHint = true; 4539 else { 4540 Hint = E->EvaluateKnownConstInt(Context); 4541 HintLoc = C->getLocStart(); 4542 } 4543 } 4544 } 4545 if (ErrorFound) 4546 return StmtError(); 4547 auto Pair = DSAStack->getCriticalWithHint(DirName); 4548 if (Pair.first && DirName.getName() && !DependentHint) { 4549 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 4550 Diag(StartLoc, diag::err_omp_critical_with_hint); 4551 if (HintLoc.isValid()) { 4552 Diag(HintLoc, diag::note_omp_critical_hint_here) 4553 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 4554 } else 4555 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 4556 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 4557 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 4558 << 1 4559 << C->getHint()->EvaluateKnownConstInt(Context).toString( 4560 /*Radix=*/10, /*Signed=*/false); 4561 } else 4562 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 4563 } 4564 } 4565 4566 getCurFunction()->setHasBranchProtectedScope(); 4567 4568 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 4569 Clauses, AStmt); 4570 if (!Pair.first && DirName.getName() && !DependentHint) 4571 DSAStack->addCriticalWithHint(Dir, Hint); 4572 return Dir; 4573 } 4574 4575 StmtResult Sema::ActOnOpenMPParallelForDirective( 4576 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4577 SourceLocation EndLoc, 4578 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4579 if (!AStmt) 4580 return StmtError(); 4581 4582 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4583 // 1.2.2 OpenMP Language Terminology 4584 // Structured block - An executable statement with a single entry at the 4585 // top and a single exit at the bottom. 4586 // The point of exit cannot be a branch out of the structured block. 4587 // longjmp() and throw() must not violate the entry/exit criteria. 4588 CS->getCapturedDecl()->setNothrow(); 4589 4590 OMPLoopDirective::HelperExprs B; 4591 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4592 // define the nested loops number. 4593 unsigned NestedLoopCount = 4594 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 4595 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4596 VarsWithImplicitDSA, B); 4597 if (NestedLoopCount == 0) 4598 return StmtError(); 4599 4600 assert((CurContext->isDependentContext() || B.builtAll()) && 4601 "omp parallel for loop exprs were not built"); 4602 4603 if (!CurContext->isDependentContext()) { 4604 // Finalize the clauses that need pre-built expressions for CodeGen. 4605 for (auto C : Clauses) { 4606 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4607 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4608 B.NumIterations, *this, CurScope, 4609 DSAStack)) 4610 return StmtError(); 4611 } 4612 } 4613 4614 getCurFunction()->setHasBranchProtectedScope(); 4615 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 4616 NestedLoopCount, Clauses, AStmt, B, 4617 DSAStack->isCancelRegion()); 4618 } 4619 4620 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 4621 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4622 SourceLocation EndLoc, 4623 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4624 if (!AStmt) 4625 return StmtError(); 4626 4627 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4628 // 1.2.2 OpenMP Language Terminology 4629 // Structured block - An executable statement with a single entry at the 4630 // top and a single exit at the bottom. 4631 // The point of exit cannot be a branch out of the structured block. 4632 // longjmp() and throw() must not violate the entry/exit criteria. 4633 CS->getCapturedDecl()->setNothrow(); 4634 4635 OMPLoopDirective::HelperExprs B; 4636 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4637 // define the nested loops number. 4638 unsigned NestedLoopCount = 4639 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 4640 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4641 VarsWithImplicitDSA, B); 4642 if (NestedLoopCount == 0) 4643 return StmtError(); 4644 4645 if (!CurContext->isDependentContext()) { 4646 // Finalize the clauses that need pre-built expressions for CodeGen. 4647 for (auto C : Clauses) { 4648 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4649 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4650 B.NumIterations, *this, CurScope, 4651 DSAStack)) 4652 return StmtError(); 4653 } 4654 } 4655 4656 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4657 return StmtError(); 4658 4659 getCurFunction()->setHasBranchProtectedScope(); 4660 return OMPParallelForSimdDirective::Create( 4661 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 4662 } 4663 4664 StmtResult 4665 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 4666 Stmt *AStmt, SourceLocation StartLoc, 4667 SourceLocation EndLoc) { 4668 if (!AStmt) 4669 return StmtError(); 4670 4671 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4672 auto BaseStmt = AStmt; 4673 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4674 BaseStmt = CS->getCapturedStmt(); 4675 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4676 auto S = C->children(); 4677 if (S.begin() == S.end()) 4678 return StmtError(); 4679 // All associated statements must be '#pragma omp section' except for 4680 // the first one. 4681 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4682 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4683 if (SectionStmt) 4684 Diag(SectionStmt->getLocStart(), 4685 diag::err_omp_parallel_sections_substmt_not_section); 4686 return StmtError(); 4687 } 4688 cast<OMPSectionDirective>(SectionStmt) 4689 ->setHasCancel(DSAStack->isCancelRegion()); 4690 } 4691 } else { 4692 Diag(AStmt->getLocStart(), 4693 diag::err_omp_parallel_sections_not_compound_stmt); 4694 return StmtError(); 4695 } 4696 4697 getCurFunction()->setHasBranchProtectedScope(); 4698 4699 return OMPParallelSectionsDirective::Create( 4700 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 4701 } 4702 4703 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 4704 Stmt *AStmt, SourceLocation StartLoc, 4705 SourceLocation EndLoc) { 4706 if (!AStmt) 4707 return StmtError(); 4708 4709 auto *CS = cast<CapturedStmt>(AStmt); 4710 // 1.2.2 OpenMP Language Terminology 4711 // Structured block - An executable statement with a single entry at the 4712 // top and a single exit at the bottom. 4713 // The point of exit cannot be a branch out of the structured block. 4714 // longjmp() and throw() must not violate the entry/exit criteria. 4715 CS->getCapturedDecl()->setNothrow(); 4716 4717 getCurFunction()->setHasBranchProtectedScope(); 4718 4719 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4720 DSAStack->isCancelRegion()); 4721 } 4722 4723 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 4724 SourceLocation EndLoc) { 4725 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 4726 } 4727 4728 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 4729 SourceLocation EndLoc) { 4730 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 4731 } 4732 4733 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 4734 SourceLocation EndLoc) { 4735 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 4736 } 4737 4738 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt, 4739 SourceLocation StartLoc, 4740 SourceLocation EndLoc) { 4741 if (!AStmt) 4742 return StmtError(); 4743 4744 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4745 4746 getCurFunction()->setHasBranchProtectedScope(); 4747 4748 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt); 4749 } 4750 4751 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 4752 SourceLocation StartLoc, 4753 SourceLocation EndLoc) { 4754 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 4755 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 4756 } 4757 4758 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 4759 Stmt *AStmt, 4760 SourceLocation StartLoc, 4761 SourceLocation EndLoc) { 4762 OMPClause *DependFound = nullptr; 4763 OMPClause *DependSourceClause = nullptr; 4764 OMPClause *DependSinkClause = nullptr; 4765 bool ErrorFound = false; 4766 OMPThreadsClause *TC = nullptr; 4767 OMPSIMDClause *SC = nullptr; 4768 for (auto *C : Clauses) { 4769 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 4770 DependFound = C; 4771 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 4772 if (DependSourceClause) { 4773 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 4774 << getOpenMPDirectiveName(OMPD_ordered) 4775 << getOpenMPClauseName(OMPC_depend) << 2; 4776 ErrorFound = true; 4777 } else 4778 DependSourceClause = C; 4779 if (DependSinkClause) { 4780 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 4781 << 0; 4782 ErrorFound = true; 4783 } 4784 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 4785 if (DependSourceClause) { 4786 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 4787 << 1; 4788 ErrorFound = true; 4789 } 4790 DependSinkClause = C; 4791 } 4792 } else if (C->getClauseKind() == OMPC_threads) 4793 TC = cast<OMPThreadsClause>(C); 4794 else if (C->getClauseKind() == OMPC_simd) 4795 SC = cast<OMPSIMDClause>(C); 4796 } 4797 if (!ErrorFound && !SC && 4798 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 4799 // OpenMP [2.8.1,simd Construct, Restrictions] 4800 // An ordered construct with the simd clause is the only OpenMP construct 4801 // that can appear in the simd region. 4802 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 4803 ErrorFound = true; 4804 } else if (DependFound && (TC || SC)) { 4805 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 4806 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 4807 ErrorFound = true; 4808 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 4809 Diag(DependFound->getLocStart(), 4810 diag::err_omp_ordered_directive_without_param); 4811 ErrorFound = true; 4812 } else if (TC || Clauses.empty()) { 4813 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 4814 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 4815 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 4816 << (TC != nullptr); 4817 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 4818 ErrorFound = true; 4819 } 4820 } 4821 if ((!AStmt && !DependFound) || ErrorFound) 4822 return StmtError(); 4823 4824 if (AStmt) { 4825 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4826 4827 getCurFunction()->setHasBranchProtectedScope(); 4828 } 4829 4830 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 4831 } 4832 4833 namespace { 4834 /// \brief Helper class for checking expression in 'omp atomic [update]' 4835 /// construct. 4836 class OpenMPAtomicUpdateChecker { 4837 /// \brief Error results for atomic update expressions. 4838 enum ExprAnalysisErrorCode { 4839 /// \brief A statement is not an expression statement. 4840 NotAnExpression, 4841 /// \brief Expression is not builtin binary or unary operation. 4842 NotABinaryOrUnaryExpression, 4843 /// \brief Unary operation is not post-/pre- increment/decrement operation. 4844 NotAnUnaryIncDecExpression, 4845 /// \brief An expression is not of scalar type. 4846 NotAScalarType, 4847 /// \brief A binary operation is not an assignment operation. 4848 NotAnAssignmentOp, 4849 /// \brief RHS part of the binary operation is not a binary expression. 4850 NotABinaryExpression, 4851 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 4852 /// expression. 4853 NotABinaryOperator, 4854 /// \brief RHS binary operation does not have reference to the updated LHS 4855 /// part. 4856 NotAnUpdateExpression, 4857 /// \brief No errors is found. 4858 NoError 4859 }; 4860 /// \brief Reference to Sema. 4861 Sema &SemaRef; 4862 /// \brief A location for note diagnostics (when error is found). 4863 SourceLocation NoteLoc; 4864 /// \brief 'x' lvalue part of the source atomic expression. 4865 Expr *X; 4866 /// \brief 'expr' rvalue part of the source atomic expression. 4867 Expr *E; 4868 /// \brief Helper expression of the form 4869 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 4870 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 4871 Expr *UpdateExpr; 4872 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 4873 /// important for non-associative operations. 4874 bool IsXLHSInRHSPart; 4875 BinaryOperatorKind Op; 4876 SourceLocation OpLoc; 4877 /// \brief true if the source expression is a postfix unary operation, false 4878 /// if it is a prefix unary operation. 4879 bool IsPostfixUpdate; 4880 4881 public: 4882 OpenMPAtomicUpdateChecker(Sema &SemaRef) 4883 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 4884 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 4885 /// \brief Check specified statement that it is suitable for 'atomic update' 4886 /// constructs and extract 'x', 'expr' and Operation from the original 4887 /// expression. If DiagId and NoteId == 0, then only check is performed 4888 /// without error notification. 4889 /// \param DiagId Diagnostic which should be emitted if error is found. 4890 /// \param NoteId Diagnostic note for the main error message. 4891 /// \return true if statement is not an update expression, false otherwise. 4892 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 4893 /// \brief Return the 'x' lvalue part of the source atomic expression. 4894 Expr *getX() const { return X; } 4895 /// \brief Return the 'expr' rvalue part of the source atomic expression. 4896 Expr *getExpr() const { return E; } 4897 /// \brief Return the update expression used in calculation of the updated 4898 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 4899 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 4900 Expr *getUpdateExpr() const { return UpdateExpr; } 4901 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 4902 /// false otherwise. 4903 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 4904 4905 /// \brief true if the source expression is a postfix unary operation, false 4906 /// if it is a prefix unary operation. 4907 bool isPostfixUpdate() const { return IsPostfixUpdate; } 4908 4909 private: 4910 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 4911 unsigned NoteId = 0); 4912 }; 4913 } // namespace 4914 4915 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 4916 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 4917 ExprAnalysisErrorCode ErrorFound = NoError; 4918 SourceLocation ErrorLoc, NoteLoc; 4919 SourceRange ErrorRange, NoteRange; 4920 // Allowed constructs are: 4921 // x = x binop expr; 4922 // x = expr binop x; 4923 if (AtomicBinOp->getOpcode() == BO_Assign) { 4924 X = AtomicBinOp->getLHS(); 4925 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 4926 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 4927 if (AtomicInnerBinOp->isMultiplicativeOp() || 4928 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 4929 AtomicInnerBinOp->isBitwiseOp()) { 4930 Op = AtomicInnerBinOp->getOpcode(); 4931 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 4932 auto *LHS = AtomicInnerBinOp->getLHS(); 4933 auto *RHS = AtomicInnerBinOp->getRHS(); 4934 llvm::FoldingSetNodeID XId, LHSId, RHSId; 4935 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 4936 /*Canonical=*/true); 4937 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 4938 /*Canonical=*/true); 4939 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 4940 /*Canonical=*/true); 4941 if (XId == LHSId) { 4942 E = RHS; 4943 IsXLHSInRHSPart = true; 4944 } else if (XId == RHSId) { 4945 E = LHS; 4946 IsXLHSInRHSPart = false; 4947 } else { 4948 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 4949 ErrorRange = AtomicInnerBinOp->getSourceRange(); 4950 NoteLoc = X->getExprLoc(); 4951 NoteRange = X->getSourceRange(); 4952 ErrorFound = NotAnUpdateExpression; 4953 } 4954 } else { 4955 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 4956 ErrorRange = AtomicInnerBinOp->getSourceRange(); 4957 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 4958 NoteRange = SourceRange(NoteLoc, NoteLoc); 4959 ErrorFound = NotABinaryOperator; 4960 } 4961 } else { 4962 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 4963 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 4964 ErrorFound = NotABinaryExpression; 4965 } 4966 } else { 4967 ErrorLoc = AtomicBinOp->getExprLoc(); 4968 ErrorRange = AtomicBinOp->getSourceRange(); 4969 NoteLoc = AtomicBinOp->getOperatorLoc(); 4970 NoteRange = SourceRange(NoteLoc, NoteLoc); 4971 ErrorFound = NotAnAssignmentOp; 4972 } 4973 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 4974 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 4975 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 4976 return true; 4977 } else if (SemaRef.CurContext->isDependentContext()) 4978 E = X = UpdateExpr = nullptr; 4979 return ErrorFound != NoError; 4980 } 4981 4982 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 4983 unsigned NoteId) { 4984 ExprAnalysisErrorCode ErrorFound = NoError; 4985 SourceLocation ErrorLoc, NoteLoc; 4986 SourceRange ErrorRange, NoteRange; 4987 // Allowed constructs are: 4988 // x++; 4989 // x--; 4990 // ++x; 4991 // --x; 4992 // x binop= expr; 4993 // x = x binop expr; 4994 // x = expr binop x; 4995 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 4996 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 4997 if (AtomicBody->getType()->isScalarType() || 4998 AtomicBody->isInstantiationDependent()) { 4999 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 5000 AtomicBody->IgnoreParenImpCasts())) { 5001 // Check for Compound Assignment Operation 5002 Op = BinaryOperator::getOpForCompoundAssignment( 5003 AtomicCompAssignOp->getOpcode()); 5004 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 5005 E = AtomicCompAssignOp->getRHS(); 5006 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 5007 IsXLHSInRHSPart = true; 5008 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 5009 AtomicBody->IgnoreParenImpCasts())) { 5010 // Check for Binary Operation 5011 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 5012 return true; 5013 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 5014 AtomicBody->IgnoreParenImpCasts())) { 5015 // Check for Unary Operation 5016 if (AtomicUnaryOp->isIncrementDecrementOp()) { 5017 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 5018 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 5019 OpLoc = AtomicUnaryOp->getOperatorLoc(); 5020 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 5021 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 5022 IsXLHSInRHSPart = true; 5023 } else { 5024 ErrorFound = NotAnUnaryIncDecExpression; 5025 ErrorLoc = AtomicUnaryOp->getExprLoc(); 5026 ErrorRange = AtomicUnaryOp->getSourceRange(); 5027 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 5028 NoteRange = SourceRange(NoteLoc, NoteLoc); 5029 } 5030 } else if (!AtomicBody->isInstantiationDependent()) { 5031 ErrorFound = NotABinaryOrUnaryExpression; 5032 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 5033 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 5034 } 5035 } else { 5036 ErrorFound = NotAScalarType; 5037 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 5038 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5039 } 5040 } else { 5041 ErrorFound = NotAnExpression; 5042 NoteLoc = ErrorLoc = S->getLocStart(); 5043 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5044 } 5045 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5046 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5047 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5048 return true; 5049 } else if (SemaRef.CurContext->isDependentContext()) 5050 E = X = UpdateExpr = nullptr; 5051 if (ErrorFound == NoError && E && X) { 5052 // Build an update expression of form 'OpaqueValueExpr(x) binop 5053 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 5054 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 5055 auto *OVEX = new (SemaRef.getASTContext()) 5056 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 5057 auto *OVEExpr = new (SemaRef.getASTContext()) 5058 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 5059 auto Update = 5060 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 5061 IsXLHSInRHSPart ? OVEExpr : OVEX); 5062 if (Update.isInvalid()) 5063 return true; 5064 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 5065 Sema::AA_Casting); 5066 if (Update.isInvalid()) 5067 return true; 5068 UpdateExpr = Update.get(); 5069 } 5070 return ErrorFound != NoError; 5071 } 5072 5073 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 5074 Stmt *AStmt, 5075 SourceLocation StartLoc, 5076 SourceLocation EndLoc) { 5077 if (!AStmt) 5078 return StmtError(); 5079 5080 auto *CS = cast<CapturedStmt>(AStmt); 5081 // 1.2.2 OpenMP Language Terminology 5082 // Structured block - An executable statement with a single entry at the 5083 // top and a single exit at the bottom. 5084 // The point of exit cannot be a branch out of the structured block. 5085 // longjmp() and throw() must not violate the entry/exit criteria. 5086 OpenMPClauseKind AtomicKind = OMPC_unknown; 5087 SourceLocation AtomicKindLoc; 5088 for (auto *C : Clauses) { 5089 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 5090 C->getClauseKind() == OMPC_update || 5091 C->getClauseKind() == OMPC_capture) { 5092 if (AtomicKind != OMPC_unknown) { 5093 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 5094 << SourceRange(C->getLocStart(), C->getLocEnd()); 5095 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 5096 << getOpenMPClauseName(AtomicKind); 5097 } else { 5098 AtomicKind = C->getClauseKind(); 5099 AtomicKindLoc = C->getLocStart(); 5100 } 5101 } 5102 } 5103 5104 auto Body = CS->getCapturedStmt(); 5105 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 5106 Body = EWC->getSubExpr(); 5107 5108 Expr *X = nullptr; 5109 Expr *V = nullptr; 5110 Expr *E = nullptr; 5111 Expr *UE = nullptr; 5112 bool IsXLHSInRHSPart = false; 5113 bool IsPostfixUpdate = false; 5114 // OpenMP [2.12.6, atomic Construct] 5115 // In the next expressions: 5116 // * x and v (as applicable) are both l-value expressions with scalar type. 5117 // * During the execution of an atomic region, multiple syntactic 5118 // occurrences of x must designate the same storage location. 5119 // * Neither of v and expr (as applicable) may access the storage location 5120 // designated by x. 5121 // * Neither of x and expr (as applicable) may access the storage location 5122 // designated by v. 5123 // * expr is an expression with scalar type. 5124 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 5125 // * binop, binop=, ++, and -- are not overloaded operators. 5126 // * The expression x binop expr must be numerically equivalent to x binop 5127 // (expr). This requirement is satisfied if the operators in expr have 5128 // precedence greater than binop, or by using parentheses around expr or 5129 // subexpressions of expr. 5130 // * The expression expr binop x must be numerically equivalent to (expr) 5131 // binop x. This requirement is satisfied if the operators in expr have 5132 // precedence equal to or greater than binop, or by using parentheses around 5133 // expr or subexpressions of expr. 5134 // * For forms that allow multiple occurrences of x, the number of times 5135 // that x is evaluated is unspecified. 5136 if (AtomicKind == OMPC_read) { 5137 enum { 5138 NotAnExpression, 5139 NotAnAssignmentOp, 5140 NotAScalarType, 5141 NotAnLValue, 5142 NoError 5143 } ErrorFound = NoError; 5144 SourceLocation ErrorLoc, NoteLoc; 5145 SourceRange ErrorRange, NoteRange; 5146 // If clause is read: 5147 // v = x; 5148 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5149 auto *AtomicBinOp = 5150 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5151 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5152 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5153 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 5154 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5155 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 5156 if (!X->isLValue() || !V->isLValue()) { 5157 auto NotLValueExpr = X->isLValue() ? V : X; 5158 ErrorFound = NotAnLValue; 5159 ErrorLoc = AtomicBinOp->getExprLoc(); 5160 ErrorRange = AtomicBinOp->getSourceRange(); 5161 NoteLoc = NotLValueExpr->getExprLoc(); 5162 NoteRange = NotLValueExpr->getSourceRange(); 5163 } 5164 } else if (!X->isInstantiationDependent() || 5165 !V->isInstantiationDependent()) { 5166 auto NotScalarExpr = 5167 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5168 ? V 5169 : X; 5170 ErrorFound = NotAScalarType; 5171 ErrorLoc = AtomicBinOp->getExprLoc(); 5172 ErrorRange = AtomicBinOp->getSourceRange(); 5173 NoteLoc = NotScalarExpr->getExprLoc(); 5174 NoteRange = NotScalarExpr->getSourceRange(); 5175 } 5176 } else if (!AtomicBody->isInstantiationDependent()) { 5177 ErrorFound = NotAnAssignmentOp; 5178 ErrorLoc = AtomicBody->getExprLoc(); 5179 ErrorRange = AtomicBody->getSourceRange(); 5180 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5181 : AtomicBody->getExprLoc(); 5182 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5183 : AtomicBody->getSourceRange(); 5184 } 5185 } else { 5186 ErrorFound = NotAnExpression; 5187 NoteLoc = ErrorLoc = Body->getLocStart(); 5188 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5189 } 5190 if (ErrorFound != NoError) { 5191 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 5192 << ErrorRange; 5193 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5194 << NoteRange; 5195 return StmtError(); 5196 } else if (CurContext->isDependentContext()) 5197 V = X = nullptr; 5198 } else if (AtomicKind == OMPC_write) { 5199 enum { 5200 NotAnExpression, 5201 NotAnAssignmentOp, 5202 NotAScalarType, 5203 NotAnLValue, 5204 NoError 5205 } ErrorFound = NoError; 5206 SourceLocation ErrorLoc, NoteLoc; 5207 SourceRange ErrorRange, NoteRange; 5208 // If clause is write: 5209 // x = expr; 5210 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5211 auto *AtomicBinOp = 5212 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5213 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5214 X = AtomicBinOp->getLHS(); 5215 E = AtomicBinOp->getRHS(); 5216 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5217 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 5218 if (!X->isLValue()) { 5219 ErrorFound = NotAnLValue; 5220 ErrorLoc = AtomicBinOp->getExprLoc(); 5221 ErrorRange = AtomicBinOp->getSourceRange(); 5222 NoteLoc = X->getExprLoc(); 5223 NoteRange = X->getSourceRange(); 5224 } 5225 } else if (!X->isInstantiationDependent() || 5226 !E->isInstantiationDependent()) { 5227 auto NotScalarExpr = 5228 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5229 ? E 5230 : X; 5231 ErrorFound = NotAScalarType; 5232 ErrorLoc = AtomicBinOp->getExprLoc(); 5233 ErrorRange = AtomicBinOp->getSourceRange(); 5234 NoteLoc = NotScalarExpr->getExprLoc(); 5235 NoteRange = NotScalarExpr->getSourceRange(); 5236 } 5237 } else if (!AtomicBody->isInstantiationDependent()) { 5238 ErrorFound = NotAnAssignmentOp; 5239 ErrorLoc = AtomicBody->getExprLoc(); 5240 ErrorRange = AtomicBody->getSourceRange(); 5241 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5242 : AtomicBody->getExprLoc(); 5243 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5244 : AtomicBody->getSourceRange(); 5245 } 5246 } else { 5247 ErrorFound = NotAnExpression; 5248 NoteLoc = ErrorLoc = Body->getLocStart(); 5249 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5250 } 5251 if (ErrorFound != NoError) { 5252 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 5253 << ErrorRange; 5254 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5255 << NoteRange; 5256 return StmtError(); 5257 } else if (CurContext->isDependentContext()) 5258 E = X = nullptr; 5259 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 5260 // If clause is update: 5261 // x++; 5262 // x--; 5263 // ++x; 5264 // --x; 5265 // x binop= expr; 5266 // x = x binop expr; 5267 // x = expr binop x; 5268 OpenMPAtomicUpdateChecker Checker(*this); 5269 if (Checker.checkStatement( 5270 Body, (AtomicKind == OMPC_update) 5271 ? diag::err_omp_atomic_update_not_expression_statement 5272 : diag::err_omp_atomic_not_expression_statement, 5273 diag::note_omp_atomic_update)) 5274 return StmtError(); 5275 if (!CurContext->isDependentContext()) { 5276 E = Checker.getExpr(); 5277 X = Checker.getX(); 5278 UE = Checker.getUpdateExpr(); 5279 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5280 } 5281 } else if (AtomicKind == OMPC_capture) { 5282 enum { 5283 NotAnAssignmentOp, 5284 NotACompoundStatement, 5285 NotTwoSubstatements, 5286 NotASpecificExpression, 5287 NoError 5288 } ErrorFound = NoError; 5289 SourceLocation ErrorLoc, NoteLoc; 5290 SourceRange ErrorRange, NoteRange; 5291 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5292 // If clause is a capture: 5293 // v = x++; 5294 // v = x--; 5295 // v = ++x; 5296 // v = --x; 5297 // v = x binop= expr; 5298 // v = x = x binop expr; 5299 // v = x = expr binop x; 5300 auto *AtomicBinOp = 5301 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5302 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5303 V = AtomicBinOp->getLHS(); 5304 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5305 OpenMPAtomicUpdateChecker Checker(*this); 5306 if (Checker.checkStatement( 5307 Body, diag::err_omp_atomic_capture_not_expression_statement, 5308 diag::note_omp_atomic_update)) 5309 return StmtError(); 5310 E = Checker.getExpr(); 5311 X = Checker.getX(); 5312 UE = Checker.getUpdateExpr(); 5313 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5314 IsPostfixUpdate = Checker.isPostfixUpdate(); 5315 } else if (!AtomicBody->isInstantiationDependent()) { 5316 ErrorLoc = AtomicBody->getExprLoc(); 5317 ErrorRange = AtomicBody->getSourceRange(); 5318 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5319 : AtomicBody->getExprLoc(); 5320 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5321 : AtomicBody->getSourceRange(); 5322 ErrorFound = NotAnAssignmentOp; 5323 } 5324 if (ErrorFound != NoError) { 5325 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 5326 << ErrorRange; 5327 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5328 return StmtError(); 5329 } else if (CurContext->isDependentContext()) { 5330 UE = V = E = X = nullptr; 5331 } 5332 } else { 5333 // If clause is a capture: 5334 // { v = x; x = expr; } 5335 // { v = x; x++; } 5336 // { v = x; x--; } 5337 // { v = x; ++x; } 5338 // { v = x; --x; } 5339 // { v = x; x binop= expr; } 5340 // { v = x; x = x binop expr; } 5341 // { v = x; x = expr binop x; } 5342 // { x++; v = x; } 5343 // { x--; v = x; } 5344 // { ++x; v = x; } 5345 // { --x; v = x; } 5346 // { x binop= expr; v = x; } 5347 // { x = x binop expr; v = x; } 5348 // { x = expr binop x; v = x; } 5349 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 5350 // Check that this is { expr1; expr2; } 5351 if (CS->size() == 2) { 5352 auto *First = CS->body_front(); 5353 auto *Second = CS->body_back(); 5354 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 5355 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 5356 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 5357 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 5358 // Need to find what subexpression is 'v' and what is 'x'. 5359 OpenMPAtomicUpdateChecker Checker(*this); 5360 bool IsUpdateExprFound = !Checker.checkStatement(Second); 5361 BinaryOperator *BinOp = nullptr; 5362 if (IsUpdateExprFound) { 5363 BinOp = dyn_cast<BinaryOperator>(First); 5364 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5365 } 5366 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5367 // { v = x; x++; } 5368 // { v = x; x--; } 5369 // { v = x; ++x; } 5370 // { v = x; --x; } 5371 // { v = x; x binop= expr; } 5372 // { v = x; x = x binop expr; } 5373 // { v = x; x = expr binop x; } 5374 // Check that the first expression has form v = x. 5375 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5376 llvm::FoldingSetNodeID XId, PossibleXId; 5377 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5378 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5379 IsUpdateExprFound = XId == PossibleXId; 5380 if (IsUpdateExprFound) { 5381 V = BinOp->getLHS(); 5382 X = Checker.getX(); 5383 E = Checker.getExpr(); 5384 UE = Checker.getUpdateExpr(); 5385 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5386 IsPostfixUpdate = true; 5387 } 5388 } 5389 if (!IsUpdateExprFound) { 5390 IsUpdateExprFound = !Checker.checkStatement(First); 5391 BinOp = nullptr; 5392 if (IsUpdateExprFound) { 5393 BinOp = dyn_cast<BinaryOperator>(Second); 5394 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5395 } 5396 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5397 // { x++; v = x; } 5398 // { x--; v = x; } 5399 // { ++x; v = x; } 5400 // { --x; v = x; } 5401 // { x binop= expr; v = x; } 5402 // { x = x binop expr; v = x; } 5403 // { x = expr binop x; v = x; } 5404 // Check that the second expression has form v = x. 5405 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5406 llvm::FoldingSetNodeID XId, PossibleXId; 5407 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5408 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5409 IsUpdateExprFound = XId == PossibleXId; 5410 if (IsUpdateExprFound) { 5411 V = BinOp->getLHS(); 5412 X = Checker.getX(); 5413 E = Checker.getExpr(); 5414 UE = Checker.getUpdateExpr(); 5415 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5416 IsPostfixUpdate = false; 5417 } 5418 } 5419 } 5420 if (!IsUpdateExprFound) { 5421 // { v = x; x = expr; } 5422 auto *FirstExpr = dyn_cast<Expr>(First); 5423 auto *SecondExpr = dyn_cast<Expr>(Second); 5424 if (!FirstExpr || !SecondExpr || 5425 !(FirstExpr->isInstantiationDependent() || 5426 SecondExpr->isInstantiationDependent())) { 5427 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 5428 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 5429 ErrorFound = NotAnAssignmentOp; 5430 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 5431 : First->getLocStart(); 5432 NoteRange = ErrorRange = FirstBinOp 5433 ? FirstBinOp->getSourceRange() 5434 : SourceRange(ErrorLoc, ErrorLoc); 5435 } else { 5436 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 5437 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 5438 ErrorFound = NotAnAssignmentOp; 5439 NoteLoc = ErrorLoc = SecondBinOp 5440 ? SecondBinOp->getOperatorLoc() 5441 : Second->getLocStart(); 5442 NoteRange = ErrorRange = 5443 SecondBinOp ? SecondBinOp->getSourceRange() 5444 : SourceRange(ErrorLoc, ErrorLoc); 5445 } else { 5446 auto *PossibleXRHSInFirst = 5447 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 5448 auto *PossibleXLHSInSecond = 5449 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 5450 llvm::FoldingSetNodeID X1Id, X2Id; 5451 PossibleXRHSInFirst->Profile(X1Id, Context, 5452 /*Canonical=*/true); 5453 PossibleXLHSInSecond->Profile(X2Id, Context, 5454 /*Canonical=*/true); 5455 IsUpdateExprFound = X1Id == X2Id; 5456 if (IsUpdateExprFound) { 5457 V = FirstBinOp->getLHS(); 5458 X = SecondBinOp->getLHS(); 5459 E = SecondBinOp->getRHS(); 5460 UE = nullptr; 5461 IsXLHSInRHSPart = false; 5462 IsPostfixUpdate = true; 5463 } else { 5464 ErrorFound = NotASpecificExpression; 5465 ErrorLoc = FirstBinOp->getExprLoc(); 5466 ErrorRange = FirstBinOp->getSourceRange(); 5467 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 5468 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 5469 } 5470 } 5471 } 5472 } 5473 } 5474 } else { 5475 NoteLoc = ErrorLoc = Body->getLocStart(); 5476 NoteRange = ErrorRange = 5477 SourceRange(Body->getLocStart(), Body->getLocStart()); 5478 ErrorFound = NotTwoSubstatements; 5479 } 5480 } else { 5481 NoteLoc = ErrorLoc = Body->getLocStart(); 5482 NoteRange = ErrorRange = 5483 SourceRange(Body->getLocStart(), Body->getLocStart()); 5484 ErrorFound = NotACompoundStatement; 5485 } 5486 if (ErrorFound != NoError) { 5487 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 5488 << ErrorRange; 5489 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5490 return StmtError(); 5491 } else if (CurContext->isDependentContext()) { 5492 UE = V = E = X = nullptr; 5493 } 5494 } 5495 } 5496 5497 getCurFunction()->setHasBranchProtectedScope(); 5498 5499 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5500 X, V, E, UE, IsXLHSInRHSPart, 5501 IsPostfixUpdate); 5502 } 5503 5504 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 5505 Stmt *AStmt, 5506 SourceLocation StartLoc, 5507 SourceLocation EndLoc) { 5508 if (!AStmt) 5509 return StmtError(); 5510 5511 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5512 // 1.2.2 OpenMP Language Terminology 5513 // Structured block - An executable statement with a single entry at the 5514 // top and a single exit at the bottom. 5515 // The point of exit cannot be a branch out of the structured block. 5516 // longjmp() and throw() must not violate the entry/exit criteria. 5517 CS->getCapturedDecl()->setNothrow(); 5518 5519 // OpenMP [2.16, Nesting of Regions] 5520 // If specified, a teams construct must be contained within a target 5521 // construct. That target construct must contain no statements or directives 5522 // outside of the teams construct. 5523 if (DSAStack->hasInnerTeamsRegion()) { 5524 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 5525 bool OMPTeamsFound = true; 5526 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 5527 auto I = CS->body_begin(); 5528 while (I != CS->body_end()) { 5529 auto *OED = dyn_cast<OMPExecutableDirective>(*I); 5530 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 5531 OMPTeamsFound = false; 5532 break; 5533 } 5534 ++I; 5535 } 5536 assert(I != CS->body_end() && "Not found statement"); 5537 S = *I; 5538 } else { 5539 auto *OED = dyn_cast<OMPExecutableDirective>(S); 5540 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 5541 } 5542 if (!OMPTeamsFound) { 5543 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 5544 Diag(DSAStack->getInnerTeamsRegionLoc(), 5545 diag::note_omp_nested_teams_construct_here); 5546 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 5547 << isa<OMPExecutableDirective>(S); 5548 return StmtError(); 5549 } 5550 } 5551 5552 getCurFunction()->setHasBranchProtectedScope(); 5553 5554 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5555 } 5556 5557 StmtResult 5558 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 5559 Stmt *AStmt, SourceLocation StartLoc, 5560 SourceLocation EndLoc) { 5561 if (!AStmt) 5562 return StmtError(); 5563 5564 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5565 // 1.2.2 OpenMP Language Terminology 5566 // Structured block - An executable statement with a single entry at the 5567 // top and a single exit at the bottom. 5568 // The point of exit cannot be a branch out of the structured block. 5569 // longjmp() and throw() must not violate the entry/exit criteria. 5570 CS->getCapturedDecl()->setNothrow(); 5571 5572 getCurFunction()->setHasBranchProtectedScope(); 5573 5574 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 5575 AStmt); 5576 } 5577 5578 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 5579 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5580 SourceLocation EndLoc, 5581 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5582 if (!AStmt) 5583 return StmtError(); 5584 5585 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5586 // 1.2.2 OpenMP Language Terminology 5587 // Structured block - An executable statement with a single entry at the 5588 // top and a single exit at the bottom. 5589 // The point of exit cannot be a branch out of the structured block. 5590 // longjmp() and throw() must not violate the entry/exit criteria. 5591 CS->getCapturedDecl()->setNothrow(); 5592 5593 OMPLoopDirective::HelperExprs B; 5594 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5595 // define the nested loops number. 5596 unsigned NestedLoopCount = 5597 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 5598 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5599 VarsWithImplicitDSA, B); 5600 if (NestedLoopCount == 0) 5601 return StmtError(); 5602 5603 assert((CurContext->isDependentContext() || B.builtAll()) && 5604 "omp target parallel for loop exprs were not built"); 5605 5606 if (!CurContext->isDependentContext()) { 5607 // Finalize the clauses that need pre-built expressions for CodeGen. 5608 for (auto C : Clauses) { 5609 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5610 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5611 B.NumIterations, *this, CurScope, 5612 DSAStack)) 5613 return StmtError(); 5614 } 5615 } 5616 5617 getCurFunction()->setHasBranchProtectedScope(); 5618 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 5619 NestedLoopCount, Clauses, AStmt, 5620 B, DSAStack->isCancelRegion()); 5621 } 5622 5623 /// \brief Check for existence of a map clause in the list of clauses. 5624 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) { 5625 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end(); 5626 I != E; ++I) { 5627 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) { 5628 return true; 5629 } 5630 } 5631 5632 return false; 5633 } 5634 5635 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 5636 Stmt *AStmt, 5637 SourceLocation StartLoc, 5638 SourceLocation EndLoc) { 5639 if (!AStmt) 5640 return StmtError(); 5641 5642 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5643 5644 // OpenMP [2.10.1, Restrictions, p. 97] 5645 // At least one map clause must appear on the directive. 5646 if (!HasMapClause(Clauses)) { 5647 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5648 << getOpenMPDirectiveName(OMPD_target_data); 5649 return StmtError(); 5650 } 5651 5652 getCurFunction()->setHasBranchProtectedScope(); 5653 5654 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 5655 AStmt); 5656 } 5657 5658 StmtResult 5659 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 5660 SourceLocation StartLoc, 5661 SourceLocation EndLoc) { 5662 // OpenMP [2.10.2, Restrictions, p. 99] 5663 // At least one map clause must appear on the directive. 5664 if (!HasMapClause(Clauses)) { 5665 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5666 << getOpenMPDirectiveName(OMPD_target_enter_data); 5667 return StmtError(); 5668 } 5669 5670 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, 5671 Clauses); 5672 } 5673 5674 StmtResult 5675 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 5676 SourceLocation StartLoc, 5677 SourceLocation EndLoc) { 5678 // OpenMP [2.10.3, Restrictions, p. 102] 5679 // At least one map clause must appear on the directive. 5680 if (!HasMapClause(Clauses)) { 5681 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5682 << getOpenMPDirectiveName(OMPD_target_exit_data); 5683 return StmtError(); 5684 } 5685 5686 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses); 5687 } 5688 5689 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 5690 SourceLocation StartLoc, 5691 SourceLocation EndLoc) { 5692 bool seenMotionClause = false; 5693 for (auto *C : Clauses) { 5694 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from) 5695 seenMotionClause = true; 5696 } 5697 if (!seenMotionClause) { 5698 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 5699 return StmtError(); 5700 } 5701 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses); 5702 } 5703 5704 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 5705 Stmt *AStmt, SourceLocation StartLoc, 5706 SourceLocation EndLoc) { 5707 if (!AStmt) 5708 return StmtError(); 5709 5710 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5711 // 1.2.2 OpenMP Language Terminology 5712 // Structured block - An executable statement with a single entry at the 5713 // top and a single exit at the bottom. 5714 // The point of exit cannot be a branch out of the structured block. 5715 // longjmp() and throw() must not violate the entry/exit criteria. 5716 CS->getCapturedDecl()->setNothrow(); 5717 5718 getCurFunction()->setHasBranchProtectedScope(); 5719 5720 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5721 } 5722 5723 StmtResult 5724 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 5725 SourceLocation EndLoc, 5726 OpenMPDirectiveKind CancelRegion) { 5727 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for && 5728 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) { 5729 Diag(StartLoc, diag::err_omp_wrong_cancel_region) 5730 << getOpenMPDirectiveName(CancelRegion); 5731 return StmtError(); 5732 } 5733 if (DSAStack->isParentNowaitRegion()) { 5734 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 5735 return StmtError(); 5736 } 5737 if (DSAStack->isParentOrderedRegion()) { 5738 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 5739 return StmtError(); 5740 } 5741 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 5742 CancelRegion); 5743 } 5744 5745 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 5746 SourceLocation StartLoc, 5747 SourceLocation EndLoc, 5748 OpenMPDirectiveKind CancelRegion) { 5749 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for && 5750 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) { 5751 Diag(StartLoc, diag::err_omp_wrong_cancel_region) 5752 << getOpenMPDirectiveName(CancelRegion); 5753 return StmtError(); 5754 } 5755 if (DSAStack->isParentNowaitRegion()) { 5756 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 5757 return StmtError(); 5758 } 5759 if (DSAStack->isParentOrderedRegion()) { 5760 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 5761 return StmtError(); 5762 } 5763 DSAStack->setParentCancelRegion(/*Cancel=*/true); 5764 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 5765 CancelRegion); 5766 } 5767 5768 static bool checkGrainsizeNumTasksClauses(Sema &S, 5769 ArrayRef<OMPClause *> Clauses) { 5770 OMPClause *PrevClause = nullptr; 5771 bool ErrorFound = false; 5772 for (auto *C : Clauses) { 5773 if (C->getClauseKind() == OMPC_grainsize || 5774 C->getClauseKind() == OMPC_num_tasks) { 5775 if (!PrevClause) 5776 PrevClause = C; 5777 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 5778 S.Diag(C->getLocStart(), 5779 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 5780 << getOpenMPClauseName(C->getClauseKind()) 5781 << getOpenMPClauseName(PrevClause->getClauseKind()); 5782 S.Diag(PrevClause->getLocStart(), 5783 diag::note_omp_previous_grainsize_num_tasks) 5784 << getOpenMPClauseName(PrevClause->getClauseKind()); 5785 ErrorFound = true; 5786 } 5787 } 5788 } 5789 return ErrorFound; 5790 } 5791 5792 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 5793 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5794 SourceLocation EndLoc, 5795 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5796 if (!AStmt) 5797 return StmtError(); 5798 5799 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5800 OMPLoopDirective::HelperExprs B; 5801 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5802 // define the nested loops number. 5803 unsigned NestedLoopCount = 5804 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 5805 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 5806 VarsWithImplicitDSA, B); 5807 if (NestedLoopCount == 0) 5808 return StmtError(); 5809 5810 assert((CurContext->isDependentContext() || B.builtAll()) && 5811 "omp for loop exprs were not built"); 5812 5813 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 5814 // The grainsize clause and num_tasks clause are mutually exclusive and may 5815 // not appear on the same taskloop directive. 5816 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 5817 return StmtError(); 5818 5819 getCurFunction()->setHasBranchProtectedScope(); 5820 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 5821 NestedLoopCount, Clauses, AStmt, B); 5822 } 5823 5824 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 5825 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5826 SourceLocation EndLoc, 5827 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5828 if (!AStmt) 5829 return StmtError(); 5830 5831 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5832 OMPLoopDirective::HelperExprs B; 5833 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5834 // define the nested loops number. 5835 unsigned NestedLoopCount = 5836 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 5837 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 5838 VarsWithImplicitDSA, B); 5839 if (NestedLoopCount == 0) 5840 return StmtError(); 5841 5842 assert((CurContext->isDependentContext() || B.builtAll()) && 5843 "omp for loop exprs were not built"); 5844 5845 if (!CurContext->isDependentContext()) { 5846 // Finalize the clauses that need pre-built expressions for CodeGen. 5847 for (auto C : Clauses) { 5848 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5849 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5850 B.NumIterations, *this, CurScope, 5851 DSAStack)) 5852 return StmtError(); 5853 } 5854 } 5855 5856 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 5857 // The grainsize clause and num_tasks clause are mutually exclusive and may 5858 // not appear on the same taskloop directive. 5859 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 5860 return StmtError(); 5861 5862 getCurFunction()->setHasBranchProtectedScope(); 5863 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 5864 NestedLoopCount, Clauses, AStmt, B); 5865 } 5866 5867 StmtResult Sema::ActOnOpenMPDistributeDirective( 5868 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5869 SourceLocation EndLoc, 5870 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5871 if (!AStmt) 5872 return StmtError(); 5873 5874 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5875 OMPLoopDirective::HelperExprs B; 5876 // In presence of clause 'collapse' with number of loops, it will 5877 // define the nested loops number. 5878 unsigned NestedLoopCount = 5879 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 5880 nullptr /*ordered not a clause on distribute*/, AStmt, 5881 *this, *DSAStack, VarsWithImplicitDSA, B); 5882 if (NestedLoopCount == 0) 5883 return StmtError(); 5884 5885 assert((CurContext->isDependentContext() || B.builtAll()) && 5886 "omp for loop exprs were not built"); 5887 5888 getCurFunction()->setHasBranchProtectedScope(); 5889 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 5890 NestedLoopCount, Clauses, AStmt, B); 5891 } 5892 5893 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 5894 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5895 SourceLocation EndLoc, 5896 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5897 if (!AStmt) 5898 return StmtError(); 5899 5900 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5901 // 1.2.2 OpenMP Language Terminology 5902 // Structured block - An executable statement with a single entry at the 5903 // top and a single exit at the bottom. 5904 // The point of exit cannot be a branch out of the structured block. 5905 // longjmp() and throw() must not violate the entry/exit criteria. 5906 CS->getCapturedDecl()->setNothrow(); 5907 5908 OMPLoopDirective::HelperExprs B; 5909 // In presence of clause 'collapse' with number of loops, it will 5910 // define the nested loops number. 5911 unsigned NestedLoopCount = CheckOpenMPLoop( 5912 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 5913 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 5914 VarsWithImplicitDSA, B); 5915 if (NestedLoopCount == 0) 5916 return StmtError(); 5917 5918 assert((CurContext->isDependentContext() || B.builtAll()) && 5919 "omp for loop exprs were not built"); 5920 5921 getCurFunction()->setHasBranchProtectedScope(); 5922 return OMPDistributeParallelForDirective::Create( 5923 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 5924 } 5925 5926 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 5927 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5928 SourceLocation EndLoc, 5929 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5930 if (!AStmt) 5931 return StmtError(); 5932 5933 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5934 // 1.2.2 OpenMP Language Terminology 5935 // Structured block - An executable statement with a single entry at the 5936 // top and a single exit at the bottom. 5937 // The point of exit cannot be a branch out of the structured block. 5938 // longjmp() and throw() must not violate the entry/exit criteria. 5939 CS->getCapturedDecl()->setNothrow(); 5940 5941 OMPLoopDirective::HelperExprs B; 5942 // In presence of clause 'collapse' with number of loops, it will 5943 // define the nested loops number. 5944 unsigned NestedLoopCount = CheckOpenMPLoop( 5945 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 5946 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 5947 VarsWithImplicitDSA, B); 5948 if (NestedLoopCount == 0) 5949 return StmtError(); 5950 5951 assert((CurContext->isDependentContext() || B.builtAll()) && 5952 "omp for loop exprs were not built"); 5953 5954 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5955 return StmtError(); 5956 5957 getCurFunction()->setHasBranchProtectedScope(); 5958 return OMPDistributeParallelForSimdDirective::Create( 5959 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 5960 } 5961 5962 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 5963 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5964 SourceLocation EndLoc, 5965 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5966 if (!AStmt) 5967 return StmtError(); 5968 5969 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5970 // 1.2.2 OpenMP Language Terminology 5971 // Structured block - An executable statement with a single entry at the 5972 // top and a single exit at the bottom. 5973 // The point of exit cannot be a branch out of the structured block. 5974 // longjmp() and throw() must not violate the entry/exit criteria. 5975 CS->getCapturedDecl()->setNothrow(); 5976 5977 OMPLoopDirective::HelperExprs B; 5978 // In presence of clause 'collapse' with number of loops, it will 5979 // define the nested loops number. 5980 unsigned NestedLoopCount = 5981 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 5982 nullptr /*ordered not a clause on distribute*/, AStmt, 5983 *this, *DSAStack, VarsWithImplicitDSA, B); 5984 if (NestedLoopCount == 0) 5985 return StmtError(); 5986 5987 assert((CurContext->isDependentContext() || B.builtAll()) && 5988 "omp for loop exprs were not built"); 5989 5990 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5991 return StmtError(); 5992 5993 getCurFunction()->setHasBranchProtectedScope(); 5994 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 5995 NestedLoopCount, Clauses, AStmt, B); 5996 } 5997 5998 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 5999 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6000 SourceLocation EndLoc, 6001 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6002 if (!AStmt) 6003 return StmtError(); 6004 6005 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6006 // 1.2.2 OpenMP Language Terminology 6007 // Structured block - An executable statement with a single entry at the 6008 // top and a single exit at the bottom. 6009 // The point of exit cannot be a branch out of the structured block. 6010 // longjmp() and throw() must not violate the entry/exit criteria. 6011 CS->getCapturedDecl()->setNothrow(); 6012 6013 OMPLoopDirective::HelperExprs B; 6014 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6015 // define the nested loops number. 6016 unsigned NestedLoopCount = CheckOpenMPLoop( 6017 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 6018 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6019 VarsWithImplicitDSA, B); 6020 if (NestedLoopCount == 0) 6021 return StmtError(); 6022 6023 assert((CurContext->isDependentContext() || B.builtAll()) && 6024 "omp target parallel for simd loop exprs were not built"); 6025 6026 if (!CurContext->isDependentContext()) { 6027 // Finalize the clauses that need pre-built expressions for CodeGen. 6028 for (auto C : Clauses) { 6029 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6030 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6031 B.NumIterations, *this, CurScope, 6032 DSAStack)) 6033 return StmtError(); 6034 } 6035 } 6036 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6037 return StmtError(); 6038 6039 getCurFunction()->setHasBranchProtectedScope(); 6040 return OMPTargetParallelForSimdDirective::Create( 6041 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6042 } 6043 6044 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 6045 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6046 SourceLocation EndLoc, 6047 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6048 if (!AStmt) 6049 return StmtError(); 6050 6051 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6052 // 1.2.2 OpenMP Language Terminology 6053 // Structured block - An executable statement with a single entry at the 6054 // top and a single exit at the bottom. 6055 // The point of exit cannot be a branch out of the structured block. 6056 // longjmp() and throw() must not violate the entry/exit criteria. 6057 CS->getCapturedDecl()->setNothrow(); 6058 6059 OMPLoopDirective::HelperExprs B; 6060 // In presence of clause 'collapse' with number of loops, it will define the 6061 // nested loops number. 6062 unsigned NestedLoopCount = 6063 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 6064 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6065 VarsWithImplicitDSA, B); 6066 if (NestedLoopCount == 0) 6067 return StmtError(); 6068 6069 assert((CurContext->isDependentContext() || B.builtAll()) && 6070 "omp target simd loop exprs were not built"); 6071 6072 if (!CurContext->isDependentContext()) { 6073 // Finalize the clauses that need pre-built expressions for CodeGen. 6074 for (auto C : Clauses) { 6075 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6076 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6077 B.NumIterations, *this, CurScope, 6078 DSAStack)) 6079 return StmtError(); 6080 } 6081 } 6082 6083 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6084 return StmtError(); 6085 6086 getCurFunction()->setHasBranchProtectedScope(); 6087 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 6088 NestedLoopCount, Clauses, AStmt, B); 6089 } 6090 6091 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 6092 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6093 SourceLocation EndLoc, 6094 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6095 if (!AStmt) 6096 return StmtError(); 6097 6098 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6099 // 1.2.2 OpenMP Language Terminology 6100 // Structured block - An executable statement with a single entry at the 6101 // top and a single exit at the bottom. 6102 // The point of exit cannot be a branch out of the structured block. 6103 // longjmp() and throw() must not violate the entry/exit criteria. 6104 CS->getCapturedDecl()->setNothrow(); 6105 6106 OMPLoopDirective::HelperExprs B; 6107 // In presence of clause 'collapse' with number of loops, it will 6108 // define the nested loops number. 6109 unsigned NestedLoopCount = 6110 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 6111 nullptr /*ordered not a clause on distribute*/, AStmt, 6112 *this, *DSAStack, VarsWithImplicitDSA, B); 6113 if (NestedLoopCount == 0) 6114 return StmtError(); 6115 6116 assert((CurContext->isDependentContext() || B.builtAll()) && 6117 "omp teams distribute loop exprs were not built"); 6118 6119 getCurFunction()->setHasBranchProtectedScope(); 6120 return OMPTeamsDistributeDirective::Create( 6121 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6122 } 6123 6124 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 6125 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6126 SourceLocation EndLoc, 6127 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6128 if (!AStmt) 6129 return StmtError(); 6130 6131 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6132 // 1.2.2 OpenMP Language Terminology 6133 // Structured block - An executable statement with a single entry at the 6134 // top and a single exit at the bottom. 6135 // The point of exit cannot be a branch out of the structured block. 6136 // longjmp() and throw() must not violate the entry/exit criteria. 6137 CS->getCapturedDecl()->setNothrow(); 6138 6139 OMPLoopDirective::HelperExprs B; 6140 // In presence of clause 'collapse' with number of loops, it will 6141 // define the nested loops number. 6142 unsigned NestedLoopCount = CheckOpenMPLoop( 6143 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6144 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6145 VarsWithImplicitDSA, B); 6146 6147 if (NestedLoopCount == 0) 6148 return StmtError(); 6149 6150 assert((CurContext->isDependentContext() || B.builtAll()) && 6151 "omp teams distribute simd loop exprs were not built"); 6152 6153 if (!CurContext->isDependentContext()) { 6154 // Finalize the clauses that need pre-built expressions for CodeGen. 6155 for (auto C : Clauses) { 6156 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6157 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6158 B.NumIterations, *this, CurScope, 6159 DSAStack)) 6160 return StmtError(); 6161 } 6162 } 6163 6164 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6165 return StmtError(); 6166 6167 getCurFunction()->setHasBranchProtectedScope(); 6168 return OMPTeamsDistributeSimdDirective::Create( 6169 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6170 } 6171 6172 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6173 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6174 SourceLocation EndLoc, 6175 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6176 if (!AStmt) 6177 return StmtError(); 6178 6179 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6180 // 1.2.2 OpenMP Language Terminology 6181 // Structured block - An executable statement with a single entry at the 6182 // top and a single exit at the bottom. 6183 // The point of exit cannot be a branch out of the structured block. 6184 // longjmp() and throw() must not violate the entry/exit criteria. 6185 CS->getCapturedDecl()->setNothrow(); 6186 6187 OMPLoopDirective::HelperExprs B; 6188 // In presence of clause 'collapse' with number of loops, it will 6189 // define the nested loops number. 6190 auto NestedLoopCount = CheckOpenMPLoop( 6191 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6192 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6193 VarsWithImplicitDSA, B); 6194 6195 if (NestedLoopCount == 0) 6196 return StmtError(); 6197 6198 assert((CurContext->isDependentContext() || B.builtAll()) && 6199 "omp for loop exprs were not built"); 6200 6201 if (!CurContext->isDependentContext()) { 6202 // Finalize the clauses that need pre-built expressions for CodeGen. 6203 for (auto C : Clauses) { 6204 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6205 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6206 B.NumIterations, *this, CurScope, 6207 DSAStack)) 6208 return StmtError(); 6209 } 6210 } 6211 6212 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6213 return StmtError(); 6214 6215 getCurFunction()->setHasBranchProtectedScope(); 6216 return OMPTeamsDistributeParallelForSimdDirective::Create( 6217 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6218 } 6219 6220 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 6221 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6222 SourceLocation EndLoc, 6223 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6224 if (!AStmt) 6225 return StmtError(); 6226 6227 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6228 // 1.2.2 OpenMP Language Terminology 6229 // Structured block - An executable statement with a single entry at the 6230 // top and a single exit at the bottom. 6231 // The point of exit cannot be a branch out of the structured block. 6232 // longjmp() and throw() must not violate the entry/exit criteria. 6233 CS->getCapturedDecl()->setNothrow(); 6234 6235 OMPLoopDirective::HelperExprs B; 6236 // In presence of clause 'collapse' with number of loops, it will 6237 // define the nested loops number. 6238 unsigned NestedLoopCount = CheckOpenMPLoop( 6239 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6240 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6241 VarsWithImplicitDSA, B); 6242 6243 if (NestedLoopCount == 0) 6244 return StmtError(); 6245 6246 assert((CurContext->isDependentContext() || B.builtAll()) && 6247 "omp for loop exprs were not built"); 6248 6249 if (!CurContext->isDependentContext()) { 6250 // Finalize the clauses that need pre-built expressions for CodeGen. 6251 for (auto C : Clauses) { 6252 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6253 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6254 B.NumIterations, *this, CurScope, 6255 DSAStack)) 6256 return StmtError(); 6257 } 6258 } 6259 6260 getCurFunction()->setHasBranchProtectedScope(); 6261 return OMPTeamsDistributeParallelForDirective::Create( 6262 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6263 } 6264 6265 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 6266 Stmt *AStmt, 6267 SourceLocation StartLoc, 6268 SourceLocation EndLoc) { 6269 if (!AStmt) 6270 return StmtError(); 6271 6272 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6273 // 1.2.2 OpenMP Language Terminology 6274 // Structured block - An executable statement with a single entry at the 6275 // top and a single exit at the bottom. 6276 // The point of exit cannot be a branch out of the structured block. 6277 // longjmp() and throw() must not violate the entry/exit criteria. 6278 CS->getCapturedDecl()->setNothrow(); 6279 6280 getCurFunction()->setHasBranchProtectedScope(); 6281 6282 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 6283 AStmt); 6284 } 6285 6286 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 6287 SourceLocation StartLoc, 6288 SourceLocation LParenLoc, 6289 SourceLocation EndLoc) { 6290 OMPClause *Res = nullptr; 6291 switch (Kind) { 6292 case OMPC_final: 6293 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 6294 break; 6295 case OMPC_num_threads: 6296 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 6297 break; 6298 case OMPC_safelen: 6299 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 6300 break; 6301 case OMPC_simdlen: 6302 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 6303 break; 6304 case OMPC_collapse: 6305 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 6306 break; 6307 case OMPC_ordered: 6308 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 6309 break; 6310 case OMPC_device: 6311 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 6312 break; 6313 case OMPC_num_teams: 6314 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 6315 break; 6316 case OMPC_thread_limit: 6317 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 6318 break; 6319 case OMPC_priority: 6320 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 6321 break; 6322 case OMPC_grainsize: 6323 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 6324 break; 6325 case OMPC_num_tasks: 6326 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 6327 break; 6328 case OMPC_hint: 6329 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 6330 break; 6331 case OMPC_if: 6332 case OMPC_default: 6333 case OMPC_proc_bind: 6334 case OMPC_schedule: 6335 case OMPC_private: 6336 case OMPC_firstprivate: 6337 case OMPC_lastprivate: 6338 case OMPC_shared: 6339 case OMPC_reduction: 6340 case OMPC_linear: 6341 case OMPC_aligned: 6342 case OMPC_copyin: 6343 case OMPC_copyprivate: 6344 case OMPC_nowait: 6345 case OMPC_untied: 6346 case OMPC_mergeable: 6347 case OMPC_threadprivate: 6348 case OMPC_flush: 6349 case OMPC_read: 6350 case OMPC_write: 6351 case OMPC_update: 6352 case OMPC_capture: 6353 case OMPC_seq_cst: 6354 case OMPC_depend: 6355 case OMPC_threads: 6356 case OMPC_simd: 6357 case OMPC_map: 6358 case OMPC_nogroup: 6359 case OMPC_dist_schedule: 6360 case OMPC_defaultmap: 6361 case OMPC_unknown: 6362 case OMPC_uniform: 6363 case OMPC_to: 6364 case OMPC_from: 6365 case OMPC_use_device_ptr: 6366 case OMPC_is_device_ptr: 6367 llvm_unreachable("Clause is not allowed."); 6368 } 6369 return Res; 6370 } 6371 6372 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 6373 Expr *Condition, SourceLocation StartLoc, 6374 SourceLocation LParenLoc, 6375 SourceLocation NameModifierLoc, 6376 SourceLocation ColonLoc, 6377 SourceLocation EndLoc) { 6378 Expr *ValExpr = Condition; 6379 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 6380 !Condition->isInstantiationDependent() && 6381 !Condition->containsUnexpandedParameterPack()) { 6382 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 6383 if (Val.isInvalid()) 6384 return nullptr; 6385 6386 ValExpr = MakeFullExpr(Val.get()).get(); 6387 } 6388 6389 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc, 6390 NameModifierLoc, ColonLoc, EndLoc); 6391 } 6392 6393 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 6394 SourceLocation StartLoc, 6395 SourceLocation LParenLoc, 6396 SourceLocation EndLoc) { 6397 Expr *ValExpr = Condition; 6398 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 6399 !Condition->isInstantiationDependent() && 6400 !Condition->containsUnexpandedParameterPack()) { 6401 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 6402 if (Val.isInvalid()) 6403 return nullptr; 6404 6405 ValExpr = MakeFullExpr(Val.get()).get(); 6406 } 6407 6408 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 6409 } 6410 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 6411 Expr *Op) { 6412 if (!Op) 6413 return ExprError(); 6414 6415 class IntConvertDiagnoser : public ICEConvertDiagnoser { 6416 public: 6417 IntConvertDiagnoser() 6418 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 6419 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 6420 QualType T) override { 6421 return S.Diag(Loc, diag::err_omp_not_integral) << T; 6422 } 6423 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 6424 QualType T) override { 6425 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 6426 } 6427 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 6428 QualType T, 6429 QualType ConvTy) override { 6430 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 6431 } 6432 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 6433 QualType ConvTy) override { 6434 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 6435 << ConvTy->isEnumeralType() << ConvTy; 6436 } 6437 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 6438 QualType T) override { 6439 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 6440 } 6441 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 6442 QualType ConvTy) override { 6443 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 6444 << ConvTy->isEnumeralType() << ConvTy; 6445 } 6446 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 6447 QualType) override { 6448 llvm_unreachable("conversion functions are permitted"); 6449 } 6450 } ConvertDiagnoser; 6451 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 6452 } 6453 6454 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 6455 OpenMPClauseKind CKind, 6456 bool StrictlyPositive) { 6457 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 6458 !ValExpr->isInstantiationDependent()) { 6459 SourceLocation Loc = ValExpr->getExprLoc(); 6460 ExprResult Value = 6461 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 6462 if (Value.isInvalid()) 6463 return false; 6464 6465 ValExpr = Value.get(); 6466 // The expression must evaluate to a non-negative integer value. 6467 llvm::APSInt Result; 6468 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 6469 Result.isSigned() && 6470 !((!StrictlyPositive && Result.isNonNegative()) || 6471 (StrictlyPositive && Result.isStrictlyPositive()))) { 6472 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 6473 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 6474 << ValExpr->getSourceRange(); 6475 return false; 6476 } 6477 } 6478 return true; 6479 } 6480 6481 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 6482 SourceLocation StartLoc, 6483 SourceLocation LParenLoc, 6484 SourceLocation EndLoc) { 6485 Expr *ValExpr = NumThreads; 6486 6487 // OpenMP [2.5, Restrictions] 6488 // The num_threads expression must evaluate to a positive integer value. 6489 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 6490 /*StrictlyPositive=*/true)) 6491 return nullptr; 6492 6493 return new (Context) 6494 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc); 6495 } 6496 6497 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 6498 OpenMPClauseKind CKind, 6499 bool StrictlyPositive) { 6500 if (!E) 6501 return ExprError(); 6502 if (E->isValueDependent() || E->isTypeDependent() || 6503 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 6504 return E; 6505 llvm::APSInt Result; 6506 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 6507 if (ICE.isInvalid()) 6508 return ExprError(); 6509 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 6510 (!StrictlyPositive && !Result.isNonNegative())) { 6511 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 6512 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 6513 << E->getSourceRange(); 6514 return ExprError(); 6515 } 6516 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 6517 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 6518 << E->getSourceRange(); 6519 return ExprError(); 6520 } 6521 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 6522 DSAStack->setAssociatedLoops(Result.getExtValue()); 6523 else if (CKind == OMPC_ordered) 6524 DSAStack->setAssociatedLoops(Result.getExtValue()); 6525 return ICE; 6526 } 6527 6528 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 6529 SourceLocation LParenLoc, 6530 SourceLocation EndLoc) { 6531 // OpenMP [2.8.1, simd construct, Description] 6532 // The parameter of the safelen clause must be a constant 6533 // positive integer expression. 6534 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 6535 if (Safelen.isInvalid()) 6536 return nullptr; 6537 return new (Context) 6538 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 6539 } 6540 6541 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 6542 SourceLocation LParenLoc, 6543 SourceLocation EndLoc) { 6544 // OpenMP [2.8.1, simd construct, Description] 6545 // The parameter of the simdlen clause must be a constant 6546 // positive integer expression. 6547 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 6548 if (Simdlen.isInvalid()) 6549 return nullptr; 6550 return new (Context) 6551 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 6552 } 6553 6554 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 6555 SourceLocation StartLoc, 6556 SourceLocation LParenLoc, 6557 SourceLocation EndLoc) { 6558 // OpenMP [2.7.1, loop construct, Description] 6559 // OpenMP [2.8.1, simd construct, Description] 6560 // OpenMP [2.9.6, distribute construct, Description] 6561 // The parameter of the collapse clause must be a constant 6562 // positive integer expression. 6563 ExprResult NumForLoopsResult = 6564 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 6565 if (NumForLoopsResult.isInvalid()) 6566 return nullptr; 6567 return new (Context) 6568 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 6569 } 6570 6571 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 6572 SourceLocation EndLoc, 6573 SourceLocation LParenLoc, 6574 Expr *NumForLoops) { 6575 // OpenMP [2.7.1, loop construct, Description] 6576 // OpenMP [2.8.1, simd construct, Description] 6577 // OpenMP [2.9.6, distribute construct, Description] 6578 // The parameter of the ordered clause must be a constant 6579 // positive integer expression if any. 6580 if (NumForLoops && LParenLoc.isValid()) { 6581 ExprResult NumForLoopsResult = 6582 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 6583 if (NumForLoopsResult.isInvalid()) 6584 return nullptr; 6585 NumForLoops = NumForLoopsResult.get(); 6586 } else 6587 NumForLoops = nullptr; 6588 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 6589 return new (Context) 6590 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 6591 } 6592 6593 OMPClause *Sema::ActOnOpenMPSimpleClause( 6594 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 6595 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 6596 OMPClause *Res = nullptr; 6597 switch (Kind) { 6598 case OMPC_default: 6599 Res = 6600 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 6601 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 6602 break; 6603 case OMPC_proc_bind: 6604 Res = ActOnOpenMPProcBindClause( 6605 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 6606 LParenLoc, EndLoc); 6607 break; 6608 case OMPC_if: 6609 case OMPC_final: 6610 case OMPC_num_threads: 6611 case OMPC_safelen: 6612 case OMPC_simdlen: 6613 case OMPC_collapse: 6614 case OMPC_schedule: 6615 case OMPC_private: 6616 case OMPC_firstprivate: 6617 case OMPC_lastprivate: 6618 case OMPC_shared: 6619 case OMPC_reduction: 6620 case OMPC_linear: 6621 case OMPC_aligned: 6622 case OMPC_copyin: 6623 case OMPC_copyprivate: 6624 case OMPC_ordered: 6625 case OMPC_nowait: 6626 case OMPC_untied: 6627 case OMPC_mergeable: 6628 case OMPC_threadprivate: 6629 case OMPC_flush: 6630 case OMPC_read: 6631 case OMPC_write: 6632 case OMPC_update: 6633 case OMPC_capture: 6634 case OMPC_seq_cst: 6635 case OMPC_depend: 6636 case OMPC_device: 6637 case OMPC_threads: 6638 case OMPC_simd: 6639 case OMPC_map: 6640 case OMPC_num_teams: 6641 case OMPC_thread_limit: 6642 case OMPC_priority: 6643 case OMPC_grainsize: 6644 case OMPC_nogroup: 6645 case OMPC_num_tasks: 6646 case OMPC_hint: 6647 case OMPC_dist_schedule: 6648 case OMPC_defaultmap: 6649 case OMPC_unknown: 6650 case OMPC_uniform: 6651 case OMPC_to: 6652 case OMPC_from: 6653 case OMPC_use_device_ptr: 6654 case OMPC_is_device_ptr: 6655 llvm_unreachable("Clause is not allowed."); 6656 } 6657 return Res; 6658 } 6659 6660 static std::string 6661 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 6662 ArrayRef<unsigned> Exclude = llvm::None) { 6663 std::string Values; 6664 unsigned Bound = Last >= 2 ? Last - 2 : 0; 6665 unsigned Skipped = Exclude.size(); 6666 auto S = Exclude.begin(), E = Exclude.end(); 6667 for (unsigned i = First; i < Last; ++i) { 6668 if (std::find(S, E, i) != E) { 6669 --Skipped; 6670 continue; 6671 } 6672 Values += "'"; 6673 Values += getOpenMPSimpleClauseTypeName(K, i); 6674 Values += "'"; 6675 if (i == Bound - Skipped) 6676 Values += " or "; 6677 else if (i != Bound + 1 - Skipped) 6678 Values += ", "; 6679 } 6680 return Values; 6681 } 6682 6683 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 6684 SourceLocation KindKwLoc, 6685 SourceLocation StartLoc, 6686 SourceLocation LParenLoc, 6687 SourceLocation EndLoc) { 6688 if (Kind == OMPC_DEFAULT_unknown) { 6689 static_assert(OMPC_DEFAULT_unknown > 0, 6690 "OMPC_DEFAULT_unknown not greater than 0"); 6691 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 6692 << getListOfPossibleValues(OMPC_default, /*First=*/0, 6693 /*Last=*/OMPC_DEFAULT_unknown) 6694 << getOpenMPClauseName(OMPC_default); 6695 return nullptr; 6696 } 6697 switch (Kind) { 6698 case OMPC_DEFAULT_none: 6699 DSAStack->setDefaultDSANone(KindKwLoc); 6700 break; 6701 case OMPC_DEFAULT_shared: 6702 DSAStack->setDefaultDSAShared(KindKwLoc); 6703 break; 6704 case OMPC_DEFAULT_unknown: 6705 llvm_unreachable("Clause kind is not allowed."); 6706 break; 6707 } 6708 return new (Context) 6709 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 6710 } 6711 6712 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 6713 SourceLocation KindKwLoc, 6714 SourceLocation StartLoc, 6715 SourceLocation LParenLoc, 6716 SourceLocation EndLoc) { 6717 if (Kind == OMPC_PROC_BIND_unknown) { 6718 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 6719 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 6720 /*Last=*/OMPC_PROC_BIND_unknown) 6721 << getOpenMPClauseName(OMPC_proc_bind); 6722 return nullptr; 6723 } 6724 return new (Context) 6725 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 6726 } 6727 6728 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 6729 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 6730 SourceLocation StartLoc, SourceLocation LParenLoc, 6731 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 6732 SourceLocation EndLoc) { 6733 OMPClause *Res = nullptr; 6734 switch (Kind) { 6735 case OMPC_schedule: 6736 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 6737 assert(Argument.size() == NumberOfElements && 6738 ArgumentLoc.size() == NumberOfElements); 6739 Res = ActOnOpenMPScheduleClause( 6740 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 6741 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 6742 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 6743 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 6744 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 6745 break; 6746 case OMPC_if: 6747 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 6748 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 6749 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 6750 DelimLoc, EndLoc); 6751 break; 6752 case OMPC_dist_schedule: 6753 Res = ActOnOpenMPDistScheduleClause( 6754 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 6755 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 6756 break; 6757 case OMPC_defaultmap: 6758 enum { Modifier, DefaultmapKind }; 6759 Res = ActOnOpenMPDefaultmapClause( 6760 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 6761 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 6762 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 6763 EndLoc); 6764 break; 6765 case OMPC_final: 6766 case OMPC_num_threads: 6767 case OMPC_safelen: 6768 case OMPC_simdlen: 6769 case OMPC_collapse: 6770 case OMPC_default: 6771 case OMPC_proc_bind: 6772 case OMPC_private: 6773 case OMPC_firstprivate: 6774 case OMPC_lastprivate: 6775 case OMPC_shared: 6776 case OMPC_reduction: 6777 case OMPC_linear: 6778 case OMPC_aligned: 6779 case OMPC_copyin: 6780 case OMPC_copyprivate: 6781 case OMPC_ordered: 6782 case OMPC_nowait: 6783 case OMPC_untied: 6784 case OMPC_mergeable: 6785 case OMPC_threadprivate: 6786 case OMPC_flush: 6787 case OMPC_read: 6788 case OMPC_write: 6789 case OMPC_update: 6790 case OMPC_capture: 6791 case OMPC_seq_cst: 6792 case OMPC_depend: 6793 case OMPC_device: 6794 case OMPC_threads: 6795 case OMPC_simd: 6796 case OMPC_map: 6797 case OMPC_num_teams: 6798 case OMPC_thread_limit: 6799 case OMPC_priority: 6800 case OMPC_grainsize: 6801 case OMPC_nogroup: 6802 case OMPC_num_tasks: 6803 case OMPC_hint: 6804 case OMPC_unknown: 6805 case OMPC_uniform: 6806 case OMPC_to: 6807 case OMPC_from: 6808 case OMPC_use_device_ptr: 6809 case OMPC_is_device_ptr: 6810 llvm_unreachable("Clause is not allowed."); 6811 } 6812 return Res; 6813 } 6814 6815 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 6816 OpenMPScheduleClauseModifier M2, 6817 SourceLocation M1Loc, SourceLocation M2Loc) { 6818 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 6819 SmallVector<unsigned, 2> Excluded; 6820 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 6821 Excluded.push_back(M2); 6822 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 6823 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 6824 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 6825 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 6826 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 6827 << getListOfPossibleValues(OMPC_schedule, 6828 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 6829 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 6830 Excluded) 6831 << getOpenMPClauseName(OMPC_schedule); 6832 return true; 6833 } 6834 return false; 6835 } 6836 6837 OMPClause *Sema::ActOnOpenMPScheduleClause( 6838 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 6839 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 6840 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 6841 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 6842 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 6843 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 6844 return nullptr; 6845 // OpenMP, 2.7.1, Loop Construct, Restrictions 6846 // Either the monotonic modifier or the nonmonotonic modifier can be specified 6847 // but not both. 6848 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 6849 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 6850 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 6851 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 6852 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 6853 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 6854 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 6855 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 6856 return nullptr; 6857 } 6858 if (Kind == OMPC_SCHEDULE_unknown) { 6859 std::string Values; 6860 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 6861 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 6862 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 6863 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 6864 Exclude); 6865 } else { 6866 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 6867 /*Last=*/OMPC_SCHEDULE_unknown); 6868 } 6869 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 6870 << Values << getOpenMPClauseName(OMPC_schedule); 6871 return nullptr; 6872 } 6873 // OpenMP, 2.7.1, Loop Construct, Restrictions 6874 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 6875 // schedule(guided). 6876 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 6877 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 6878 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 6879 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 6880 diag::err_omp_schedule_nonmonotonic_static); 6881 return nullptr; 6882 } 6883 Expr *ValExpr = ChunkSize; 6884 Stmt *HelperValStmt = nullptr; 6885 if (ChunkSize) { 6886 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 6887 !ChunkSize->isInstantiationDependent() && 6888 !ChunkSize->containsUnexpandedParameterPack()) { 6889 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 6890 ExprResult Val = 6891 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 6892 if (Val.isInvalid()) 6893 return nullptr; 6894 6895 ValExpr = Val.get(); 6896 6897 // OpenMP [2.7.1, Restrictions] 6898 // chunk_size must be a loop invariant integer expression with a positive 6899 // value. 6900 llvm::APSInt Result; 6901 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 6902 if (Result.isSigned() && !Result.isStrictlyPositive()) { 6903 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 6904 << "schedule" << 1 << ChunkSize->getSourceRange(); 6905 return nullptr; 6906 } 6907 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 6908 !CurContext->isDependentContext()) { 6909 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 6910 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 6911 HelperValStmt = buildPreInits(Context, Captures); 6912 } 6913 } 6914 } 6915 6916 return new (Context) 6917 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 6918 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 6919 } 6920 6921 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 6922 SourceLocation StartLoc, 6923 SourceLocation EndLoc) { 6924 OMPClause *Res = nullptr; 6925 switch (Kind) { 6926 case OMPC_ordered: 6927 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 6928 break; 6929 case OMPC_nowait: 6930 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 6931 break; 6932 case OMPC_untied: 6933 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 6934 break; 6935 case OMPC_mergeable: 6936 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 6937 break; 6938 case OMPC_read: 6939 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 6940 break; 6941 case OMPC_write: 6942 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 6943 break; 6944 case OMPC_update: 6945 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 6946 break; 6947 case OMPC_capture: 6948 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 6949 break; 6950 case OMPC_seq_cst: 6951 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 6952 break; 6953 case OMPC_threads: 6954 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 6955 break; 6956 case OMPC_simd: 6957 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 6958 break; 6959 case OMPC_nogroup: 6960 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 6961 break; 6962 case OMPC_if: 6963 case OMPC_final: 6964 case OMPC_num_threads: 6965 case OMPC_safelen: 6966 case OMPC_simdlen: 6967 case OMPC_collapse: 6968 case OMPC_schedule: 6969 case OMPC_private: 6970 case OMPC_firstprivate: 6971 case OMPC_lastprivate: 6972 case OMPC_shared: 6973 case OMPC_reduction: 6974 case OMPC_linear: 6975 case OMPC_aligned: 6976 case OMPC_copyin: 6977 case OMPC_copyprivate: 6978 case OMPC_default: 6979 case OMPC_proc_bind: 6980 case OMPC_threadprivate: 6981 case OMPC_flush: 6982 case OMPC_depend: 6983 case OMPC_device: 6984 case OMPC_map: 6985 case OMPC_num_teams: 6986 case OMPC_thread_limit: 6987 case OMPC_priority: 6988 case OMPC_grainsize: 6989 case OMPC_num_tasks: 6990 case OMPC_hint: 6991 case OMPC_dist_schedule: 6992 case OMPC_defaultmap: 6993 case OMPC_unknown: 6994 case OMPC_uniform: 6995 case OMPC_to: 6996 case OMPC_from: 6997 case OMPC_use_device_ptr: 6998 case OMPC_is_device_ptr: 6999 llvm_unreachable("Clause is not allowed."); 7000 } 7001 return Res; 7002 } 7003 7004 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 7005 SourceLocation EndLoc) { 7006 DSAStack->setNowaitRegion(); 7007 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 7008 } 7009 7010 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 7011 SourceLocation EndLoc) { 7012 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 7013 } 7014 7015 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 7016 SourceLocation EndLoc) { 7017 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 7018 } 7019 7020 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 7021 SourceLocation EndLoc) { 7022 return new (Context) OMPReadClause(StartLoc, EndLoc); 7023 } 7024 7025 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 7026 SourceLocation EndLoc) { 7027 return new (Context) OMPWriteClause(StartLoc, EndLoc); 7028 } 7029 7030 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 7031 SourceLocation EndLoc) { 7032 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 7033 } 7034 7035 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 7036 SourceLocation EndLoc) { 7037 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 7038 } 7039 7040 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 7041 SourceLocation EndLoc) { 7042 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 7043 } 7044 7045 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 7046 SourceLocation EndLoc) { 7047 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 7048 } 7049 7050 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 7051 SourceLocation EndLoc) { 7052 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 7053 } 7054 7055 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 7056 SourceLocation EndLoc) { 7057 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 7058 } 7059 7060 OMPClause *Sema::ActOnOpenMPVarListClause( 7061 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 7062 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 7063 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 7064 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 7065 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 7066 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 7067 SourceLocation DepLinMapLoc) { 7068 OMPClause *Res = nullptr; 7069 switch (Kind) { 7070 case OMPC_private: 7071 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7072 break; 7073 case OMPC_firstprivate: 7074 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7075 break; 7076 case OMPC_lastprivate: 7077 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7078 break; 7079 case OMPC_shared: 7080 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 7081 break; 7082 case OMPC_reduction: 7083 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 7084 EndLoc, ReductionIdScopeSpec, ReductionId); 7085 break; 7086 case OMPC_linear: 7087 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 7088 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 7089 break; 7090 case OMPC_aligned: 7091 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 7092 ColonLoc, EndLoc); 7093 break; 7094 case OMPC_copyin: 7095 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 7096 break; 7097 case OMPC_copyprivate: 7098 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7099 break; 7100 case OMPC_flush: 7101 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 7102 break; 7103 case OMPC_depend: 7104 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 7105 StartLoc, LParenLoc, EndLoc); 7106 break; 7107 case OMPC_map: 7108 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 7109 DepLinMapLoc, ColonLoc, VarList, StartLoc, 7110 LParenLoc, EndLoc); 7111 break; 7112 case OMPC_to: 7113 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 7114 break; 7115 case OMPC_from: 7116 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 7117 break; 7118 case OMPC_use_device_ptr: 7119 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 7120 break; 7121 case OMPC_is_device_ptr: 7122 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 7123 break; 7124 case OMPC_if: 7125 case OMPC_final: 7126 case OMPC_num_threads: 7127 case OMPC_safelen: 7128 case OMPC_simdlen: 7129 case OMPC_collapse: 7130 case OMPC_default: 7131 case OMPC_proc_bind: 7132 case OMPC_schedule: 7133 case OMPC_ordered: 7134 case OMPC_nowait: 7135 case OMPC_untied: 7136 case OMPC_mergeable: 7137 case OMPC_threadprivate: 7138 case OMPC_read: 7139 case OMPC_write: 7140 case OMPC_update: 7141 case OMPC_capture: 7142 case OMPC_seq_cst: 7143 case OMPC_device: 7144 case OMPC_threads: 7145 case OMPC_simd: 7146 case OMPC_num_teams: 7147 case OMPC_thread_limit: 7148 case OMPC_priority: 7149 case OMPC_grainsize: 7150 case OMPC_nogroup: 7151 case OMPC_num_tasks: 7152 case OMPC_hint: 7153 case OMPC_dist_schedule: 7154 case OMPC_defaultmap: 7155 case OMPC_unknown: 7156 case OMPC_uniform: 7157 llvm_unreachable("Clause is not allowed."); 7158 } 7159 return Res; 7160 } 7161 7162 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 7163 ExprObjectKind OK, SourceLocation Loc) { 7164 ExprResult Res = BuildDeclRefExpr( 7165 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 7166 if (!Res.isUsable()) 7167 return ExprError(); 7168 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 7169 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 7170 if (!Res.isUsable()) 7171 return ExprError(); 7172 } 7173 if (VK != VK_LValue && Res.get()->isGLValue()) { 7174 Res = DefaultLvalueConversion(Res.get()); 7175 if (!Res.isUsable()) 7176 return ExprError(); 7177 } 7178 return Res; 7179 } 7180 7181 static std::pair<ValueDecl *, bool> 7182 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 7183 SourceRange &ERange, bool AllowArraySection = false) { 7184 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 7185 RefExpr->containsUnexpandedParameterPack()) 7186 return std::make_pair(nullptr, true); 7187 7188 // OpenMP [3.1, C/C++] 7189 // A list item is a variable name. 7190 // OpenMP [2.9.3.3, Restrictions, p.1] 7191 // A variable that is part of another variable (as an array or 7192 // structure element) cannot appear in a private clause. 7193 RefExpr = RefExpr->IgnoreParens(); 7194 enum { 7195 NoArrayExpr = -1, 7196 ArraySubscript = 0, 7197 OMPArraySection = 1 7198 } IsArrayExpr = NoArrayExpr; 7199 if (AllowArraySection) { 7200 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 7201 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 7202 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 7203 Base = TempASE->getBase()->IgnoreParenImpCasts(); 7204 RefExpr = Base; 7205 IsArrayExpr = ArraySubscript; 7206 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 7207 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 7208 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 7209 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 7210 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 7211 Base = TempASE->getBase()->IgnoreParenImpCasts(); 7212 RefExpr = Base; 7213 IsArrayExpr = OMPArraySection; 7214 } 7215 } 7216 ELoc = RefExpr->getExprLoc(); 7217 ERange = RefExpr->getSourceRange(); 7218 RefExpr = RefExpr->IgnoreParenImpCasts(); 7219 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 7220 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 7221 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 7222 (S.getCurrentThisType().isNull() || !ME || 7223 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 7224 !isa<FieldDecl>(ME->getMemberDecl()))) { 7225 if (IsArrayExpr != NoArrayExpr) 7226 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 7227 << ERange; 7228 else { 7229 S.Diag(ELoc, 7230 AllowArraySection 7231 ? diag::err_omp_expected_var_name_member_expr_or_array_item 7232 : diag::err_omp_expected_var_name_member_expr) 7233 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 7234 } 7235 return std::make_pair(nullptr, false); 7236 } 7237 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false); 7238 } 7239 7240 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 7241 SourceLocation StartLoc, 7242 SourceLocation LParenLoc, 7243 SourceLocation EndLoc) { 7244 SmallVector<Expr *, 8> Vars; 7245 SmallVector<Expr *, 8> PrivateCopies; 7246 for (auto &RefExpr : VarList) { 7247 assert(RefExpr && "NULL expr in OpenMP private clause."); 7248 SourceLocation ELoc; 7249 SourceRange ERange; 7250 Expr *SimpleRefExpr = RefExpr; 7251 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 7252 if (Res.second) { 7253 // It will be analyzed later. 7254 Vars.push_back(RefExpr); 7255 PrivateCopies.push_back(nullptr); 7256 } 7257 ValueDecl *D = Res.first; 7258 if (!D) 7259 continue; 7260 7261 QualType Type = D->getType(); 7262 auto *VD = dyn_cast<VarDecl>(D); 7263 7264 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 7265 // A variable that appears in a private clause must not have an incomplete 7266 // type or a reference type. 7267 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 7268 continue; 7269 Type = Type.getNonReferenceType(); 7270 7271 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 7272 // in a Construct] 7273 // Variables with the predetermined data-sharing attributes may not be 7274 // listed in data-sharing attributes clauses, except for the cases 7275 // listed below. For these exceptions only, listing a predetermined 7276 // variable in a data-sharing attribute clause is allowed and overrides 7277 // the variable's predetermined data-sharing attributes. 7278 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 7279 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 7280 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 7281 << getOpenMPClauseName(OMPC_private); 7282 ReportOriginalDSA(*this, DSAStack, D, DVar); 7283 continue; 7284 } 7285 7286 auto CurrDir = DSAStack->getCurrentDirective(); 7287 // Variably modified types are not supported for tasks. 7288 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 7289 isOpenMPTaskingDirective(CurrDir)) { 7290 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 7291 << getOpenMPClauseName(OMPC_private) << Type 7292 << getOpenMPDirectiveName(CurrDir); 7293 bool IsDecl = 7294 !VD || 7295 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 7296 Diag(D->getLocation(), 7297 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 7298 << D; 7299 continue; 7300 } 7301 7302 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 7303 // A list item cannot appear in both a map clause and a data-sharing 7304 // attribute clause on the same construct 7305 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 7306 CurrDir == OMPD_target_teams) { 7307 OpenMPClauseKind ConflictKind; 7308 if (DSAStack->checkMappableExprComponentListsForDecl( 7309 VD, /*CurrentRegionOnly=*/true, 7310 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 7311 OpenMPClauseKind WhereFoundClauseKind) -> bool { 7312 ConflictKind = WhereFoundClauseKind; 7313 return true; 7314 })) { 7315 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 7316 << getOpenMPClauseName(OMPC_private) 7317 << getOpenMPClauseName(ConflictKind) 7318 << getOpenMPDirectiveName(CurrDir); 7319 ReportOriginalDSA(*this, DSAStack, D, DVar); 7320 continue; 7321 } 7322 } 7323 7324 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 7325 // A variable of class type (or array thereof) that appears in a private 7326 // clause requires an accessible, unambiguous default constructor for the 7327 // class type. 7328 // Generate helper private variable and initialize it with the default 7329 // value. The address of the original variable is replaced by the address of 7330 // the new private variable in CodeGen. This new variable is not added to 7331 // IdResolver, so the code in the OpenMP region uses original variable for 7332 // proper diagnostics. 7333 Type = Type.getUnqualifiedType(); 7334 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 7335 D->hasAttrs() ? &D->getAttrs() : nullptr); 7336 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false); 7337 if (VDPrivate->isInvalidDecl()) 7338 continue; 7339 auto VDPrivateRefExpr = buildDeclRefExpr( 7340 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 7341 7342 DeclRefExpr *Ref = nullptr; 7343 if (!VD && !CurContext->isDependentContext()) 7344 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 7345 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 7346 Vars.push_back((VD || CurContext->isDependentContext()) 7347 ? RefExpr->IgnoreParens() 7348 : Ref); 7349 PrivateCopies.push_back(VDPrivateRefExpr); 7350 } 7351 7352 if (Vars.empty()) 7353 return nullptr; 7354 7355 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 7356 PrivateCopies); 7357 } 7358 7359 namespace { 7360 class DiagsUninitializedSeveretyRAII { 7361 private: 7362 DiagnosticsEngine &Diags; 7363 SourceLocation SavedLoc; 7364 bool IsIgnored; 7365 7366 public: 7367 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 7368 bool IsIgnored) 7369 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 7370 if (!IsIgnored) { 7371 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 7372 /*Map*/ diag::Severity::Ignored, Loc); 7373 } 7374 } 7375 ~DiagsUninitializedSeveretyRAII() { 7376 if (!IsIgnored) 7377 Diags.popMappings(SavedLoc); 7378 } 7379 }; 7380 } 7381 7382 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 7383 SourceLocation StartLoc, 7384 SourceLocation LParenLoc, 7385 SourceLocation EndLoc) { 7386 SmallVector<Expr *, 8> Vars; 7387 SmallVector<Expr *, 8> PrivateCopies; 7388 SmallVector<Expr *, 8> Inits; 7389 SmallVector<Decl *, 4> ExprCaptures; 7390 bool IsImplicitClause = 7391 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 7392 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 7393 7394 for (auto &RefExpr : VarList) { 7395 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 7396 SourceLocation ELoc; 7397 SourceRange ERange; 7398 Expr *SimpleRefExpr = RefExpr; 7399 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 7400 if (Res.second) { 7401 // It will be analyzed later. 7402 Vars.push_back(RefExpr); 7403 PrivateCopies.push_back(nullptr); 7404 Inits.push_back(nullptr); 7405 } 7406 ValueDecl *D = Res.first; 7407 if (!D) 7408 continue; 7409 7410 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 7411 QualType Type = D->getType(); 7412 auto *VD = dyn_cast<VarDecl>(D); 7413 7414 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 7415 // A variable that appears in a private clause must not have an incomplete 7416 // type or a reference type. 7417 if (RequireCompleteType(ELoc, Type, 7418 diag::err_omp_firstprivate_incomplete_type)) 7419 continue; 7420 Type = Type.getNonReferenceType(); 7421 7422 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 7423 // A variable of class type (or array thereof) that appears in a private 7424 // clause requires an accessible, unambiguous copy constructor for the 7425 // class type. 7426 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 7427 7428 // If an implicit firstprivate variable found it was checked already. 7429 DSAStackTy::DSAVarData TopDVar; 7430 if (!IsImplicitClause) { 7431 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 7432 TopDVar = DVar; 7433 bool IsConstant = ElemType.isConstant(Context); 7434 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 7435 // A list item that specifies a given variable may not appear in more 7436 // than one clause on the same directive, except that a variable may be 7437 // specified in both firstprivate and lastprivate clauses. 7438 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 7439 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) { 7440 Diag(ELoc, diag::err_omp_wrong_dsa) 7441 << getOpenMPClauseName(DVar.CKind) 7442 << getOpenMPClauseName(OMPC_firstprivate); 7443 ReportOriginalDSA(*this, DSAStack, D, DVar); 7444 continue; 7445 } 7446 7447 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 7448 // in a Construct] 7449 // Variables with the predetermined data-sharing attributes may not be 7450 // listed in data-sharing attributes clauses, except for the cases 7451 // listed below. For these exceptions only, listing a predetermined 7452 // variable in a data-sharing attribute clause is allowed and overrides 7453 // the variable's predetermined data-sharing attributes. 7454 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 7455 // in a Construct, C/C++, p.2] 7456 // Variables with const-qualified type having no mutable member may be 7457 // listed in a firstprivate clause, even if they are static data members. 7458 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 7459 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 7460 Diag(ELoc, diag::err_omp_wrong_dsa) 7461 << getOpenMPClauseName(DVar.CKind) 7462 << getOpenMPClauseName(OMPC_firstprivate); 7463 ReportOriginalDSA(*this, DSAStack, D, DVar); 7464 continue; 7465 } 7466 7467 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 7468 // OpenMP [2.9.3.4, Restrictions, p.2] 7469 // A list item that is private within a parallel region must not appear 7470 // in a firstprivate clause on a worksharing construct if any of the 7471 // worksharing regions arising from the worksharing construct ever bind 7472 // to any of the parallel regions arising from the parallel construct. 7473 if (isOpenMPWorksharingDirective(CurrDir) && 7474 !isOpenMPParallelDirective(CurrDir) && 7475 !isOpenMPTeamsDirective(CurrDir)) { 7476 DVar = DSAStack->getImplicitDSA(D, true); 7477 if (DVar.CKind != OMPC_shared && 7478 (isOpenMPParallelDirective(DVar.DKind) || 7479 DVar.DKind == OMPD_unknown)) { 7480 Diag(ELoc, diag::err_omp_required_access) 7481 << getOpenMPClauseName(OMPC_firstprivate) 7482 << getOpenMPClauseName(OMPC_shared); 7483 ReportOriginalDSA(*this, DSAStack, D, DVar); 7484 continue; 7485 } 7486 } 7487 // OpenMP [2.9.3.4, Restrictions, p.3] 7488 // A list item that appears in a reduction clause of a parallel construct 7489 // must not appear in a firstprivate clause on a worksharing or task 7490 // construct if any of the worksharing or task regions arising from the 7491 // worksharing or task construct ever bind to any of the parallel regions 7492 // arising from the parallel construct. 7493 // OpenMP [2.9.3.4, Restrictions, p.4] 7494 // A list item that appears in a reduction clause in worksharing 7495 // construct must not appear in a firstprivate clause in a task construct 7496 // encountered during execution of any of the worksharing regions arising 7497 // from the worksharing construct. 7498 if (isOpenMPTaskingDirective(CurrDir)) { 7499 DVar = DSAStack->hasInnermostDSA( 7500 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 7501 [](OpenMPDirectiveKind K) -> bool { 7502 return isOpenMPParallelDirective(K) || 7503 isOpenMPWorksharingDirective(K); 7504 }, 7505 false); 7506 if (DVar.CKind == OMPC_reduction && 7507 (isOpenMPParallelDirective(DVar.DKind) || 7508 isOpenMPWorksharingDirective(DVar.DKind))) { 7509 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 7510 << getOpenMPDirectiveName(DVar.DKind); 7511 ReportOriginalDSA(*this, DSAStack, D, DVar); 7512 continue; 7513 } 7514 } 7515 7516 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 7517 // A list item that is private within a teams region must not appear in a 7518 // firstprivate clause on a distribute construct if any of the distribute 7519 // regions arising from the distribute construct ever bind to any of the 7520 // teams regions arising from the teams construct. 7521 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 7522 // A list item that appears in a reduction clause of a teams construct 7523 // must not appear in a firstprivate clause on a distribute construct if 7524 // any of the distribute regions arising from the distribute construct 7525 // ever bind to any of the teams regions arising from the teams construct. 7526 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 7527 // A list item may appear in a firstprivate or lastprivate clause but not 7528 // both. 7529 if (CurrDir == OMPD_distribute) { 7530 DVar = DSAStack->hasInnermostDSA( 7531 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; }, 7532 [](OpenMPDirectiveKind K) -> bool { 7533 return isOpenMPTeamsDirective(K); 7534 }, 7535 false); 7536 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) { 7537 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams); 7538 ReportOriginalDSA(*this, DSAStack, D, DVar); 7539 continue; 7540 } 7541 DVar = DSAStack->hasInnermostDSA( 7542 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 7543 [](OpenMPDirectiveKind K) -> bool { 7544 return isOpenMPTeamsDirective(K); 7545 }, 7546 false); 7547 if (DVar.CKind == OMPC_reduction && 7548 isOpenMPTeamsDirective(DVar.DKind)) { 7549 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction); 7550 ReportOriginalDSA(*this, DSAStack, D, DVar); 7551 continue; 7552 } 7553 DVar = DSAStack->getTopDSA(D, false); 7554 if (DVar.CKind == OMPC_lastprivate) { 7555 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 7556 ReportOriginalDSA(*this, DSAStack, D, DVar); 7557 continue; 7558 } 7559 } 7560 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 7561 // A list item cannot appear in both a map clause and a data-sharing 7562 // attribute clause on the same construct 7563 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 7564 CurrDir == OMPD_target_teams) { 7565 OpenMPClauseKind ConflictKind; 7566 if (DSAStack->checkMappableExprComponentListsForDecl( 7567 VD, /*CurrentRegionOnly=*/true, 7568 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 7569 OpenMPClauseKind WhereFoundClauseKind) -> bool { 7570 ConflictKind = WhereFoundClauseKind; 7571 return true; 7572 })) { 7573 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 7574 << getOpenMPClauseName(OMPC_firstprivate) 7575 << getOpenMPClauseName(ConflictKind) 7576 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 7577 ReportOriginalDSA(*this, DSAStack, D, DVar); 7578 continue; 7579 } 7580 } 7581 } 7582 7583 // Variably modified types are not supported for tasks. 7584 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 7585 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 7586 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 7587 << getOpenMPClauseName(OMPC_firstprivate) << Type 7588 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 7589 bool IsDecl = 7590 !VD || 7591 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 7592 Diag(D->getLocation(), 7593 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 7594 << D; 7595 continue; 7596 } 7597 7598 Type = Type.getUnqualifiedType(); 7599 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 7600 D->hasAttrs() ? &D->getAttrs() : nullptr); 7601 // Generate helper private variable and initialize it with the value of the 7602 // original variable. The address of the original variable is replaced by 7603 // the address of the new private variable in the CodeGen. This new variable 7604 // is not added to IdResolver, so the code in the OpenMP region uses 7605 // original variable for proper diagnostics and variable capturing. 7606 Expr *VDInitRefExpr = nullptr; 7607 // For arrays generate initializer for single element and replace it by the 7608 // original array element in CodeGen. 7609 if (Type->isArrayType()) { 7610 auto VDInit = 7611 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 7612 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 7613 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 7614 ElemType = ElemType.getUnqualifiedType(); 7615 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 7616 ".firstprivate.temp"); 7617 InitializedEntity Entity = 7618 InitializedEntity::InitializeVariable(VDInitTemp); 7619 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 7620 7621 InitializationSequence InitSeq(*this, Entity, Kind, Init); 7622 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 7623 if (Result.isInvalid()) 7624 VDPrivate->setInvalidDecl(); 7625 else 7626 VDPrivate->setInit(Result.getAs<Expr>()); 7627 // Remove temp variable declaration. 7628 Context.Deallocate(VDInitTemp); 7629 } else { 7630 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 7631 ".firstprivate.temp"); 7632 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 7633 RefExpr->getExprLoc()); 7634 AddInitializerToDecl(VDPrivate, 7635 DefaultLvalueConversion(VDInitRefExpr).get(), 7636 /*DirectInit=*/false, /*TypeMayContainAuto=*/false); 7637 } 7638 if (VDPrivate->isInvalidDecl()) { 7639 if (IsImplicitClause) { 7640 Diag(RefExpr->getExprLoc(), 7641 diag::note_omp_task_predetermined_firstprivate_here); 7642 } 7643 continue; 7644 } 7645 CurContext->addDecl(VDPrivate); 7646 auto VDPrivateRefExpr = buildDeclRefExpr( 7647 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 7648 RefExpr->getExprLoc()); 7649 DeclRefExpr *Ref = nullptr; 7650 if (!VD && !CurContext->isDependentContext()) { 7651 if (TopDVar.CKind == OMPC_lastprivate) 7652 Ref = TopDVar.PrivateCopy; 7653 else { 7654 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 7655 if (!IsOpenMPCapturedDecl(D)) 7656 ExprCaptures.push_back(Ref->getDecl()); 7657 } 7658 } 7659 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 7660 Vars.push_back((VD || CurContext->isDependentContext()) 7661 ? RefExpr->IgnoreParens() 7662 : Ref); 7663 PrivateCopies.push_back(VDPrivateRefExpr); 7664 Inits.push_back(VDInitRefExpr); 7665 } 7666 7667 if (Vars.empty()) 7668 return nullptr; 7669 7670 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 7671 Vars, PrivateCopies, Inits, 7672 buildPreInits(Context, ExprCaptures)); 7673 } 7674 7675 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 7676 SourceLocation StartLoc, 7677 SourceLocation LParenLoc, 7678 SourceLocation EndLoc) { 7679 SmallVector<Expr *, 8> Vars; 7680 SmallVector<Expr *, 8> SrcExprs; 7681 SmallVector<Expr *, 8> DstExprs; 7682 SmallVector<Expr *, 8> AssignmentOps; 7683 SmallVector<Decl *, 4> ExprCaptures; 7684 SmallVector<Expr *, 4> ExprPostUpdates; 7685 for (auto &RefExpr : VarList) { 7686 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 7687 SourceLocation ELoc; 7688 SourceRange ERange; 7689 Expr *SimpleRefExpr = RefExpr; 7690 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 7691 if (Res.second) { 7692 // It will be analyzed later. 7693 Vars.push_back(RefExpr); 7694 SrcExprs.push_back(nullptr); 7695 DstExprs.push_back(nullptr); 7696 AssignmentOps.push_back(nullptr); 7697 } 7698 ValueDecl *D = Res.first; 7699 if (!D) 7700 continue; 7701 7702 QualType Type = D->getType(); 7703 auto *VD = dyn_cast<VarDecl>(D); 7704 7705 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 7706 // A variable that appears in a lastprivate clause must not have an 7707 // incomplete type or a reference type. 7708 if (RequireCompleteType(ELoc, Type, 7709 diag::err_omp_lastprivate_incomplete_type)) 7710 continue; 7711 Type = Type.getNonReferenceType(); 7712 7713 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 7714 // in a Construct] 7715 // Variables with the predetermined data-sharing attributes may not be 7716 // listed in data-sharing attributes clauses, except for the cases 7717 // listed below. 7718 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 7719 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 7720 DVar.CKind != OMPC_firstprivate && 7721 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 7722 Diag(ELoc, diag::err_omp_wrong_dsa) 7723 << getOpenMPClauseName(DVar.CKind) 7724 << getOpenMPClauseName(OMPC_lastprivate); 7725 ReportOriginalDSA(*this, DSAStack, D, DVar); 7726 continue; 7727 } 7728 7729 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 7730 // OpenMP [2.14.3.5, Restrictions, p.2] 7731 // A list item that is private within a parallel region, or that appears in 7732 // the reduction clause of a parallel construct, must not appear in a 7733 // lastprivate clause on a worksharing construct if any of the corresponding 7734 // worksharing regions ever binds to any of the corresponding parallel 7735 // regions. 7736 DSAStackTy::DSAVarData TopDVar = DVar; 7737 if (isOpenMPWorksharingDirective(CurrDir) && 7738 !isOpenMPParallelDirective(CurrDir) && 7739 !isOpenMPTeamsDirective(CurrDir)) { 7740 DVar = DSAStack->getImplicitDSA(D, true); 7741 if (DVar.CKind != OMPC_shared) { 7742 Diag(ELoc, diag::err_omp_required_access) 7743 << getOpenMPClauseName(OMPC_lastprivate) 7744 << getOpenMPClauseName(OMPC_shared); 7745 ReportOriginalDSA(*this, DSAStack, D, DVar); 7746 continue; 7747 } 7748 } 7749 7750 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 7751 // A list item may appear in a firstprivate or lastprivate clause but not 7752 // both. 7753 if (CurrDir == OMPD_distribute) { 7754 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 7755 if (DVar.CKind == OMPC_firstprivate) { 7756 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 7757 ReportOriginalDSA(*this, DSAStack, D, DVar); 7758 continue; 7759 } 7760 } 7761 7762 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 7763 // A variable of class type (or array thereof) that appears in a 7764 // lastprivate clause requires an accessible, unambiguous default 7765 // constructor for the class type, unless the list item is also specified 7766 // in a firstprivate clause. 7767 // A variable of class type (or array thereof) that appears in a 7768 // lastprivate clause requires an accessible, unambiguous copy assignment 7769 // operator for the class type. 7770 Type = Context.getBaseElementType(Type).getNonReferenceType(); 7771 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 7772 Type.getUnqualifiedType(), ".lastprivate.src", 7773 D->hasAttrs() ? &D->getAttrs() : nullptr); 7774 auto *PseudoSrcExpr = 7775 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 7776 auto *DstVD = 7777 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 7778 D->hasAttrs() ? &D->getAttrs() : nullptr); 7779 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 7780 // For arrays generate assignment operation for single element and replace 7781 // it by the original array element in CodeGen. 7782 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 7783 PseudoDstExpr, PseudoSrcExpr); 7784 if (AssignmentOp.isInvalid()) 7785 continue; 7786 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 7787 /*DiscardedValue=*/true); 7788 if (AssignmentOp.isInvalid()) 7789 continue; 7790 7791 DeclRefExpr *Ref = nullptr; 7792 if (!VD && !CurContext->isDependentContext()) { 7793 if (TopDVar.CKind == OMPC_firstprivate) 7794 Ref = TopDVar.PrivateCopy; 7795 else { 7796 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 7797 if (!IsOpenMPCapturedDecl(D)) 7798 ExprCaptures.push_back(Ref->getDecl()); 7799 } 7800 if (TopDVar.CKind == OMPC_firstprivate || 7801 (!IsOpenMPCapturedDecl(D) && 7802 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 7803 ExprResult RefRes = DefaultLvalueConversion(Ref); 7804 if (!RefRes.isUsable()) 7805 continue; 7806 ExprResult PostUpdateRes = 7807 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 7808 RefRes.get()); 7809 if (!PostUpdateRes.isUsable()) 7810 continue; 7811 ExprPostUpdates.push_back( 7812 IgnoredValueConversions(PostUpdateRes.get()).get()); 7813 } 7814 } 7815 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 7816 Vars.push_back((VD || CurContext->isDependentContext()) 7817 ? RefExpr->IgnoreParens() 7818 : Ref); 7819 SrcExprs.push_back(PseudoSrcExpr); 7820 DstExprs.push_back(PseudoDstExpr); 7821 AssignmentOps.push_back(AssignmentOp.get()); 7822 } 7823 7824 if (Vars.empty()) 7825 return nullptr; 7826 7827 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 7828 Vars, SrcExprs, DstExprs, AssignmentOps, 7829 buildPreInits(Context, ExprCaptures), 7830 buildPostUpdate(*this, ExprPostUpdates)); 7831 } 7832 7833 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 7834 SourceLocation StartLoc, 7835 SourceLocation LParenLoc, 7836 SourceLocation EndLoc) { 7837 SmallVector<Expr *, 8> Vars; 7838 for (auto &RefExpr : VarList) { 7839 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 7840 SourceLocation ELoc; 7841 SourceRange ERange; 7842 Expr *SimpleRefExpr = RefExpr; 7843 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 7844 if (Res.second) { 7845 // It will be analyzed later. 7846 Vars.push_back(RefExpr); 7847 } 7848 ValueDecl *D = Res.first; 7849 if (!D) 7850 continue; 7851 7852 auto *VD = dyn_cast<VarDecl>(D); 7853 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 7854 // in a Construct] 7855 // Variables with the predetermined data-sharing attributes may not be 7856 // listed in data-sharing attributes clauses, except for the cases 7857 // listed below. For these exceptions only, listing a predetermined 7858 // variable in a data-sharing attribute clause is allowed and overrides 7859 // the variable's predetermined data-sharing attributes. 7860 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 7861 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 7862 DVar.RefExpr) { 7863 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 7864 << getOpenMPClauseName(OMPC_shared); 7865 ReportOriginalDSA(*this, DSAStack, D, DVar); 7866 continue; 7867 } 7868 7869 DeclRefExpr *Ref = nullptr; 7870 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 7871 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 7872 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 7873 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 7874 ? RefExpr->IgnoreParens() 7875 : Ref); 7876 } 7877 7878 if (Vars.empty()) 7879 return nullptr; 7880 7881 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 7882 } 7883 7884 namespace { 7885 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 7886 DSAStackTy *Stack; 7887 7888 public: 7889 bool VisitDeclRefExpr(DeclRefExpr *E) { 7890 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 7891 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 7892 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 7893 return false; 7894 if (DVar.CKind != OMPC_unknown) 7895 return true; 7896 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 7897 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 7898 false); 7899 if (DVarPrivate.CKind != OMPC_unknown) 7900 return true; 7901 return false; 7902 } 7903 return false; 7904 } 7905 bool VisitStmt(Stmt *S) { 7906 for (auto Child : S->children()) { 7907 if (Child && Visit(Child)) 7908 return true; 7909 } 7910 return false; 7911 } 7912 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 7913 }; 7914 } // namespace 7915 7916 namespace { 7917 // Transform MemberExpression for specified FieldDecl of current class to 7918 // DeclRefExpr to specified OMPCapturedExprDecl. 7919 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 7920 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 7921 ValueDecl *Field; 7922 DeclRefExpr *CapturedExpr; 7923 7924 public: 7925 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 7926 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 7927 7928 ExprResult TransformMemberExpr(MemberExpr *E) { 7929 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 7930 E->getMemberDecl() == Field) { 7931 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 7932 return CapturedExpr; 7933 } 7934 return BaseTransform::TransformMemberExpr(E); 7935 } 7936 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 7937 }; 7938 } // namespace 7939 7940 template <typename T> 7941 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 7942 const llvm::function_ref<T(ValueDecl *)> &Gen) { 7943 for (auto &Set : Lookups) { 7944 for (auto *D : Set) { 7945 if (auto Res = Gen(cast<ValueDecl>(D))) 7946 return Res; 7947 } 7948 } 7949 return T(); 7950 } 7951 7952 static ExprResult 7953 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 7954 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 7955 const DeclarationNameInfo &ReductionId, QualType Ty, 7956 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 7957 if (ReductionIdScopeSpec.isInvalid()) 7958 return ExprError(); 7959 SmallVector<UnresolvedSet<8>, 4> Lookups; 7960 if (S) { 7961 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 7962 Lookup.suppressDiagnostics(); 7963 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 7964 auto *D = Lookup.getRepresentativeDecl(); 7965 do { 7966 S = S->getParent(); 7967 } while (S && !S->isDeclScope(D)); 7968 if (S) 7969 S = S->getParent(); 7970 Lookups.push_back(UnresolvedSet<8>()); 7971 Lookups.back().append(Lookup.begin(), Lookup.end()); 7972 Lookup.clear(); 7973 } 7974 } else if (auto *ULE = 7975 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 7976 Lookups.push_back(UnresolvedSet<8>()); 7977 Decl *PrevD = nullptr; 7978 for (auto *D : ULE->decls()) { 7979 if (D == PrevD) 7980 Lookups.push_back(UnresolvedSet<8>()); 7981 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 7982 Lookups.back().addDecl(DRD); 7983 PrevD = D; 7984 } 7985 } 7986 if (Ty->isDependentType() || Ty->isInstantiationDependentType() || 7987 Ty->containsUnexpandedParameterPack() || 7988 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 7989 return !D->isInvalidDecl() && 7990 (D->getType()->isDependentType() || 7991 D->getType()->isInstantiationDependentType() || 7992 D->getType()->containsUnexpandedParameterPack()); 7993 })) { 7994 UnresolvedSet<8> ResSet; 7995 for (auto &Set : Lookups) { 7996 ResSet.append(Set.begin(), Set.end()); 7997 // The last item marks the end of all declarations at the specified scope. 7998 ResSet.addDecl(Set[Set.size() - 1]); 7999 } 8000 return UnresolvedLookupExpr::Create( 8001 SemaRef.Context, /*NamingClass=*/nullptr, 8002 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 8003 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 8004 } 8005 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8006 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 8007 if (!D->isInvalidDecl() && 8008 SemaRef.Context.hasSameType(D->getType(), Ty)) 8009 return D; 8010 return nullptr; 8011 })) 8012 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8013 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8014 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 8015 if (!D->isInvalidDecl() && 8016 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 8017 !Ty.isMoreQualifiedThan(D->getType())) 8018 return D; 8019 return nullptr; 8020 })) { 8021 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 8022 /*DetectVirtual=*/false); 8023 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 8024 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 8025 VD->getType().getUnqualifiedType()))) { 8026 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 8027 /*DiagID=*/0) != 8028 Sema::AR_inaccessible) { 8029 SemaRef.BuildBasePathArray(Paths, BasePath); 8030 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8031 } 8032 } 8033 } 8034 } 8035 if (ReductionIdScopeSpec.isSet()) { 8036 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 8037 return ExprError(); 8038 } 8039 return ExprEmpty(); 8040 } 8041 8042 OMPClause *Sema::ActOnOpenMPReductionClause( 8043 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 8044 SourceLocation ColonLoc, SourceLocation EndLoc, 8045 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 8046 ArrayRef<Expr *> UnresolvedReductions) { 8047 auto DN = ReductionId.getName(); 8048 auto OOK = DN.getCXXOverloadedOperator(); 8049 BinaryOperatorKind BOK = BO_Comma; 8050 8051 // OpenMP [2.14.3.6, reduction clause] 8052 // C 8053 // reduction-identifier is either an identifier or one of the following 8054 // operators: +, -, *, &, |, ^, && and || 8055 // C++ 8056 // reduction-identifier is either an id-expression or one of the following 8057 // operators: +, -, *, &, |, ^, && and || 8058 // FIXME: Only 'min' and 'max' identifiers are supported for now. 8059 switch (OOK) { 8060 case OO_Plus: 8061 case OO_Minus: 8062 BOK = BO_Add; 8063 break; 8064 case OO_Star: 8065 BOK = BO_Mul; 8066 break; 8067 case OO_Amp: 8068 BOK = BO_And; 8069 break; 8070 case OO_Pipe: 8071 BOK = BO_Or; 8072 break; 8073 case OO_Caret: 8074 BOK = BO_Xor; 8075 break; 8076 case OO_AmpAmp: 8077 BOK = BO_LAnd; 8078 break; 8079 case OO_PipePipe: 8080 BOK = BO_LOr; 8081 break; 8082 case OO_New: 8083 case OO_Delete: 8084 case OO_Array_New: 8085 case OO_Array_Delete: 8086 case OO_Slash: 8087 case OO_Percent: 8088 case OO_Tilde: 8089 case OO_Exclaim: 8090 case OO_Equal: 8091 case OO_Less: 8092 case OO_Greater: 8093 case OO_LessEqual: 8094 case OO_GreaterEqual: 8095 case OO_PlusEqual: 8096 case OO_MinusEqual: 8097 case OO_StarEqual: 8098 case OO_SlashEqual: 8099 case OO_PercentEqual: 8100 case OO_CaretEqual: 8101 case OO_AmpEqual: 8102 case OO_PipeEqual: 8103 case OO_LessLess: 8104 case OO_GreaterGreater: 8105 case OO_LessLessEqual: 8106 case OO_GreaterGreaterEqual: 8107 case OO_EqualEqual: 8108 case OO_ExclaimEqual: 8109 case OO_PlusPlus: 8110 case OO_MinusMinus: 8111 case OO_Comma: 8112 case OO_ArrowStar: 8113 case OO_Arrow: 8114 case OO_Call: 8115 case OO_Subscript: 8116 case OO_Conditional: 8117 case OO_Coawait: 8118 case NUM_OVERLOADED_OPERATORS: 8119 llvm_unreachable("Unexpected reduction identifier"); 8120 case OO_None: 8121 if (auto II = DN.getAsIdentifierInfo()) { 8122 if (II->isStr("max")) 8123 BOK = BO_GT; 8124 else if (II->isStr("min")) 8125 BOK = BO_LT; 8126 } 8127 break; 8128 } 8129 SourceRange ReductionIdRange; 8130 if (ReductionIdScopeSpec.isValid()) 8131 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 8132 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 8133 8134 SmallVector<Expr *, 8> Vars; 8135 SmallVector<Expr *, 8> Privates; 8136 SmallVector<Expr *, 8> LHSs; 8137 SmallVector<Expr *, 8> RHSs; 8138 SmallVector<Expr *, 8> ReductionOps; 8139 SmallVector<Decl *, 4> ExprCaptures; 8140 SmallVector<Expr *, 4> ExprPostUpdates; 8141 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 8142 bool FirstIter = true; 8143 for (auto RefExpr : VarList) { 8144 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 8145 // OpenMP [2.1, C/C++] 8146 // A list item is a variable or array section, subject to the restrictions 8147 // specified in Section 2.4 on page 42 and in each of the sections 8148 // describing clauses and directives for which a list appears. 8149 // OpenMP [2.14.3.3, Restrictions, p.1] 8150 // A variable that is part of another variable (as an array or 8151 // structure element) cannot appear in a private clause. 8152 if (!FirstIter && IR != ER) 8153 ++IR; 8154 FirstIter = false; 8155 SourceLocation ELoc; 8156 SourceRange ERange; 8157 Expr *SimpleRefExpr = RefExpr; 8158 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 8159 /*AllowArraySection=*/true); 8160 if (Res.second) { 8161 // It will be analyzed later. 8162 Vars.push_back(RefExpr); 8163 Privates.push_back(nullptr); 8164 LHSs.push_back(nullptr); 8165 RHSs.push_back(nullptr); 8166 // Try to find 'declare reduction' corresponding construct before using 8167 // builtin/overloaded operators. 8168 QualType Type = Context.DependentTy; 8169 CXXCastPath BasePath; 8170 ExprResult DeclareReductionRef = buildDeclareReductionRef( 8171 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 8172 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 8173 if (CurContext->isDependentContext() && 8174 (DeclareReductionRef.isUnset() || 8175 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 8176 ReductionOps.push_back(DeclareReductionRef.get()); 8177 else 8178 ReductionOps.push_back(nullptr); 8179 } 8180 ValueDecl *D = Res.first; 8181 if (!D) 8182 continue; 8183 8184 QualType Type; 8185 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 8186 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 8187 if (ASE) 8188 Type = ASE->getType().getNonReferenceType(); 8189 else if (OASE) { 8190 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 8191 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 8192 Type = ATy->getElementType(); 8193 else 8194 Type = BaseType->getPointeeType(); 8195 Type = Type.getNonReferenceType(); 8196 } else 8197 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 8198 auto *VD = dyn_cast<VarDecl>(D); 8199 8200 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8201 // A variable that appears in a private clause must not have an incomplete 8202 // type or a reference type. 8203 if (RequireCompleteType(ELoc, Type, 8204 diag::err_omp_reduction_incomplete_type)) 8205 continue; 8206 // OpenMP [2.14.3.6, reduction clause, Restrictions] 8207 // A list item that appears in a reduction clause must not be 8208 // const-qualified. 8209 if (Type.getNonReferenceType().isConstant(Context)) { 8210 Diag(ELoc, diag::err_omp_const_reduction_list_item) 8211 << getOpenMPClauseName(OMPC_reduction) << Type << ERange; 8212 if (!ASE && !OASE) { 8213 bool IsDecl = !VD || 8214 VD->isThisDeclarationADefinition(Context) == 8215 VarDecl::DeclarationOnly; 8216 Diag(D->getLocation(), 8217 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8218 << D; 8219 } 8220 continue; 8221 } 8222 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 8223 // If a list-item is a reference type then it must bind to the same object 8224 // for all threads of the team. 8225 if (!ASE && !OASE && VD) { 8226 VarDecl *VDDef = VD->getDefinition(); 8227 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 8228 DSARefChecker Check(DSAStack); 8229 if (Check.Visit(VDDef->getInit())) { 8230 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange; 8231 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 8232 continue; 8233 } 8234 } 8235 } 8236 8237 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8238 // in a Construct] 8239 // Variables with the predetermined data-sharing attributes may not be 8240 // listed in data-sharing attributes clauses, except for the cases 8241 // listed below. For these exceptions only, listing a predetermined 8242 // variable in a data-sharing attribute clause is allowed and overrides 8243 // the variable's predetermined data-sharing attributes. 8244 // OpenMP [2.14.3.6, Restrictions, p.3] 8245 // Any number of reduction clauses can be specified on the directive, 8246 // but a list item can appear only once in the reduction clauses for that 8247 // directive. 8248 DSAStackTy::DSAVarData DVar; 8249 DVar = DSAStack->getTopDSA(D, false); 8250 if (DVar.CKind == OMPC_reduction) { 8251 Diag(ELoc, diag::err_omp_once_referenced) 8252 << getOpenMPClauseName(OMPC_reduction); 8253 if (DVar.RefExpr) 8254 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 8255 } else if (DVar.CKind != OMPC_unknown) { 8256 Diag(ELoc, diag::err_omp_wrong_dsa) 8257 << getOpenMPClauseName(DVar.CKind) 8258 << getOpenMPClauseName(OMPC_reduction); 8259 ReportOriginalDSA(*this, DSAStack, D, DVar); 8260 continue; 8261 } 8262 8263 // OpenMP [2.14.3.6, Restrictions, p.1] 8264 // A list item that appears in a reduction clause of a worksharing 8265 // construct must be shared in the parallel regions to which any of the 8266 // worksharing regions arising from the worksharing construct bind. 8267 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8268 if (isOpenMPWorksharingDirective(CurrDir) && 8269 !isOpenMPParallelDirective(CurrDir) && 8270 !isOpenMPTeamsDirective(CurrDir)) { 8271 DVar = DSAStack->getImplicitDSA(D, true); 8272 if (DVar.CKind != OMPC_shared) { 8273 Diag(ELoc, diag::err_omp_required_access) 8274 << getOpenMPClauseName(OMPC_reduction) 8275 << getOpenMPClauseName(OMPC_shared); 8276 ReportOriginalDSA(*this, DSAStack, D, DVar); 8277 continue; 8278 } 8279 } 8280 8281 // Try to find 'declare reduction' corresponding construct before using 8282 // builtin/overloaded operators. 8283 CXXCastPath BasePath; 8284 ExprResult DeclareReductionRef = buildDeclareReductionRef( 8285 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 8286 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 8287 if (DeclareReductionRef.isInvalid()) 8288 continue; 8289 if (CurContext->isDependentContext() && 8290 (DeclareReductionRef.isUnset() || 8291 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 8292 Vars.push_back(RefExpr); 8293 Privates.push_back(nullptr); 8294 LHSs.push_back(nullptr); 8295 RHSs.push_back(nullptr); 8296 ReductionOps.push_back(DeclareReductionRef.get()); 8297 continue; 8298 } 8299 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 8300 // Not allowed reduction identifier is found. 8301 Diag(ReductionId.getLocStart(), 8302 diag::err_omp_unknown_reduction_identifier) 8303 << Type << ReductionIdRange; 8304 continue; 8305 } 8306 8307 // OpenMP [2.14.3.6, reduction clause, Restrictions] 8308 // The type of a list item that appears in a reduction clause must be valid 8309 // for the reduction-identifier. For a max or min reduction in C, the type 8310 // of the list item must be an allowed arithmetic data type: char, int, 8311 // float, double, or _Bool, possibly modified with long, short, signed, or 8312 // unsigned. For a max or min reduction in C++, the type of the list item 8313 // must be an allowed arithmetic data type: char, wchar_t, int, float, 8314 // double, or bool, possibly modified with long, short, signed, or unsigned. 8315 if (DeclareReductionRef.isUnset()) { 8316 if ((BOK == BO_GT || BOK == BO_LT) && 8317 !(Type->isScalarType() || 8318 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 8319 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 8320 << getLangOpts().CPlusPlus; 8321 if (!ASE && !OASE) { 8322 bool IsDecl = !VD || 8323 VD->isThisDeclarationADefinition(Context) == 8324 VarDecl::DeclarationOnly; 8325 Diag(D->getLocation(), 8326 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8327 << D; 8328 } 8329 continue; 8330 } 8331 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 8332 !getLangOpts().CPlusPlus && Type->isFloatingType()) { 8333 Diag(ELoc, diag::err_omp_clause_floating_type_arg); 8334 if (!ASE && !OASE) { 8335 bool IsDecl = !VD || 8336 VD->isThisDeclarationADefinition(Context) == 8337 VarDecl::DeclarationOnly; 8338 Diag(D->getLocation(), 8339 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8340 << D; 8341 } 8342 continue; 8343 } 8344 } 8345 8346 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 8347 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs", 8348 D->hasAttrs() ? &D->getAttrs() : nullptr); 8349 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(), 8350 D->hasAttrs() ? &D->getAttrs() : nullptr); 8351 auto PrivateTy = Type; 8352 if (OASE || 8353 (!ASE && 8354 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 8355 // For arrays/array sections only: 8356 // Create pseudo array type for private copy. The size for this array will 8357 // be generated during codegen. 8358 // For array subscripts or single variables Private Ty is the same as Type 8359 // (type of the variable or single array element). 8360 PrivateTy = Context.getVariableArrayType( 8361 Type, new (Context) OpaqueValueExpr(SourceLocation(), 8362 Context.getSizeType(), VK_RValue), 8363 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 8364 } else if (!ASE && !OASE && 8365 Context.getAsArrayType(D->getType().getNonReferenceType())) 8366 PrivateTy = D->getType().getNonReferenceType(); 8367 // Private copy. 8368 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(), 8369 D->hasAttrs() ? &D->getAttrs() : nullptr); 8370 // Add initializer for private variable. 8371 Expr *Init = nullptr; 8372 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc); 8373 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc); 8374 if (DeclareReductionRef.isUsable()) { 8375 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 8376 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 8377 if (DRD->getInitializer()) { 8378 Init = DRDRef; 8379 RHSVD->setInit(DRDRef); 8380 RHSVD->setInitStyle(VarDecl::CallInit); 8381 } 8382 } else { 8383 switch (BOK) { 8384 case BO_Add: 8385 case BO_Xor: 8386 case BO_Or: 8387 case BO_LOr: 8388 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 8389 if (Type->isScalarType() || Type->isAnyComplexType()) 8390 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 8391 break; 8392 case BO_Mul: 8393 case BO_LAnd: 8394 if (Type->isScalarType() || Type->isAnyComplexType()) { 8395 // '*' and '&&' reduction ops - initializer is '1'. 8396 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 8397 } 8398 break; 8399 case BO_And: { 8400 // '&' reduction op - initializer is '~0'. 8401 QualType OrigType = Type; 8402 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 8403 Type = ComplexTy->getElementType(); 8404 if (Type->isRealFloatingType()) { 8405 llvm::APFloat InitValue = 8406 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 8407 /*isIEEE=*/true); 8408 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 8409 Type, ELoc); 8410 } else if (Type->isScalarType()) { 8411 auto Size = Context.getTypeSize(Type); 8412 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 8413 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 8414 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 8415 } 8416 if (Init && OrigType->isAnyComplexType()) { 8417 // Init = 0xFFFF + 0xFFFFi; 8418 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 8419 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 8420 } 8421 Type = OrigType; 8422 break; 8423 } 8424 case BO_LT: 8425 case BO_GT: { 8426 // 'min' reduction op - initializer is 'Largest representable number in 8427 // the reduction list item type'. 8428 // 'max' reduction op - initializer is 'Least representable number in 8429 // the reduction list item type'. 8430 if (Type->isIntegerType() || Type->isPointerType()) { 8431 bool IsSigned = Type->hasSignedIntegerRepresentation(); 8432 auto Size = Context.getTypeSize(Type); 8433 QualType IntTy = 8434 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 8435 llvm::APInt InitValue = 8436 (BOK != BO_LT) 8437 ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 8438 : llvm::APInt::getMinValue(Size) 8439 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 8440 : llvm::APInt::getMaxValue(Size); 8441 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 8442 if (Type->isPointerType()) { 8443 // Cast to pointer type. 8444 auto CastExpr = BuildCStyleCastExpr( 8445 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc), 8446 SourceLocation(), Init); 8447 if (CastExpr.isInvalid()) 8448 continue; 8449 Init = CastExpr.get(); 8450 } 8451 } else if (Type->isRealFloatingType()) { 8452 llvm::APFloat InitValue = llvm::APFloat::getLargest( 8453 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 8454 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 8455 Type, ELoc); 8456 } 8457 break; 8458 } 8459 case BO_PtrMemD: 8460 case BO_PtrMemI: 8461 case BO_MulAssign: 8462 case BO_Div: 8463 case BO_Rem: 8464 case BO_Sub: 8465 case BO_Shl: 8466 case BO_Shr: 8467 case BO_LE: 8468 case BO_GE: 8469 case BO_EQ: 8470 case BO_NE: 8471 case BO_AndAssign: 8472 case BO_XorAssign: 8473 case BO_OrAssign: 8474 case BO_Assign: 8475 case BO_AddAssign: 8476 case BO_SubAssign: 8477 case BO_DivAssign: 8478 case BO_RemAssign: 8479 case BO_ShlAssign: 8480 case BO_ShrAssign: 8481 case BO_Comma: 8482 llvm_unreachable("Unexpected reduction operation"); 8483 } 8484 } 8485 if (Init && DeclareReductionRef.isUnset()) { 8486 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false, 8487 /*TypeMayContainAuto=*/false); 8488 } else if (!Init) 8489 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false); 8490 if (RHSVD->isInvalidDecl()) 8491 continue; 8492 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 8493 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type 8494 << ReductionIdRange; 8495 bool IsDecl = 8496 !VD || 8497 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8498 Diag(D->getLocation(), 8499 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8500 << D; 8501 continue; 8502 } 8503 // Store initializer for single element in private copy. Will be used during 8504 // codegen. 8505 PrivateVD->setInit(RHSVD->getInit()); 8506 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 8507 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc); 8508 ExprResult ReductionOp; 8509 if (DeclareReductionRef.isUsable()) { 8510 QualType RedTy = DeclareReductionRef.get()->getType(); 8511 QualType PtrRedTy = Context.getPointerType(RedTy); 8512 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 8513 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 8514 if (!BasePath.empty()) { 8515 LHS = DefaultLvalueConversion(LHS.get()); 8516 RHS = DefaultLvalueConversion(RHS.get()); 8517 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 8518 CK_UncheckedDerivedToBase, LHS.get(), 8519 &BasePath, LHS.get()->getValueKind()); 8520 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 8521 CK_UncheckedDerivedToBase, RHS.get(), 8522 &BasePath, RHS.get()->getValueKind()); 8523 } 8524 FunctionProtoType::ExtProtoInfo EPI; 8525 QualType Params[] = {PtrRedTy, PtrRedTy}; 8526 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 8527 auto *OVE = new (Context) OpaqueValueExpr( 8528 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 8529 DefaultLvalueConversion(DeclareReductionRef.get()).get()); 8530 Expr *Args[] = {LHS.get(), RHS.get()}; 8531 ReductionOp = new (Context) 8532 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 8533 } else { 8534 ReductionOp = BuildBinOp(DSAStack->getCurScope(), 8535 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 8536 if (ReductionOp.isUsable()) { 8537 if (BOK != BO_LT && BOK != BO_GT) { 8538 ReductionOp = 8539 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 8540 BO_Assign, LHSDRE, ReductionOp.get()); 8541 } else { 8542 auto *ConditionalOp = new (Context) ConditionalOperator( 8543 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(), 8544 RHSDRE, Type, VK_LValue, OK_Ordinary); 8545 ReductionOp = 8546 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 8547 BO_Assign, LHSDRE, ConditionalOp); 8548 } 8549 ReductionOp = ActOnFinishFullExpr(ReductionOp.get()); 8550 } 8551 if (ReductionOp.isInvalid()) 8552 continue; 8553 } 8554 8555 DeclRefExpr *Ref = nullptr; 8556 Expr *VarsExpr = RefExpr->IgnoreParens(); 8557 if (!VD && !CurContext->isDependentContext()) { 8558 if (ASE || OASE) { 8559 TransformExprToCaptures RebuildToCapture(*this, D); 8560 VarsExpr = 8561 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 8562 Ref = RebuildToCapture.getCapturedExpr(); 8563 } else { 8564 VarsExpr = Ref = 8565 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8566 } 8567 if (!IsOpenMPCapturedDecl(D)) { 8568 ExprCaptures.push_back(Ref->getDecl()); 8569 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 8570 ExprResult RefRes = DefaultLvalueConversion(Ref); 8571 if (!RefRes.isUsable()) 8572 continue; 8573 ExprResult PostUpdateRes = 8574 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 8575 SimpleRefExpr, RefRes.get()); 8576 if (!PostUpdateRes.isUsable()) 8577 continue; 8578 ExprPostUpdates.push_back( 8579 IgnoredValueConversions(PostUpdateRes.get()).get()); 8580 } 8581 } 8582 } 8583 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 8584 Vars.push_back(VarsExpr); 8585 Privates.push_back(PrivateDRE); 8586 LHSs.push_back(LHSDRE); 8587 RHSs.push_back(RHSDRE); 8588 ReductionOps.push_back(ReductionOp.get()); 8589 } 8590 8591 if (Vars.empty()) 8592 return nullptr; 8593 8594 return OMPReductionClause::Create( 8595 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars, 8596 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates, 8597 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures), 8598 buildPostUpdate(*this, ExprPostUpdates)); 8599 } 8600 8601 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 8602 SourceLocation LinLoc) { 8603 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 8604 LinKind == OMPC_LINEAR_unknown) { 8605 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 8606 return true; 8607 } 8608 return false; 8609 } 8610 8611 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 8612 OpenMPLinearClauseKind LinKind, 8613 QualType Type) { 8614 auto *VD = dyn_cast_or_null<VarDecl>(D); 8615 // A variable must not have an incomplete type or a reference type. 8616 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 8617 return true; 8618 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 8619 !Type->isReferenceType()) { 8620 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 8621 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 8622 return true; 8623 } 8624 Type = Type.getNonReferenceType(); 8625 8626 // A list item must not be const-qualified. 8627 if (Type.isConstant(Context)) { 8628 Diag(ELoc, diag::err_omp_const_variable) 8629 << getOpenMPClauseName(OMPC_linear); 8630 if (D) { 8631 bool IsDecl = 8632 !VD || 8633 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8634 Diag(D->getLocation(), 8635 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8636 << D; 8637 } 8638 return true; 8639 } 8640 8641 // A list item must be of integral or pointer type. 8642 Type = Type.getUnqualifiedType().getCanonicalType(); 8643 const auto *Ty = Type.getTypePtrOrNull(); 8644 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 8645 !Ty->isPointerType())) { 8646 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 8647 if (D) { 8648 bool IsDecl = 8649 !VD || 8650 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8651 Diag(D->getLocation(), 8652 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8653 << D; 8654 } 8655 return true; 8656 } 8657 return false; 8658 } 8659 8660 OMPClause *Sema::ActOnOpenMPLinearClause( 8661 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 8662 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 8663 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 8664 SmallVector<Expr *, 8> Vars; 8665 SmallVector<Expr *, 8> Privates; 8666 SmallVector<Expr *, 8> Inits; 8667 SmallVector<Decl *, 4> ExprCaptures; 8668 SmallVector<Expr *, 4> ExprPostUpdates; 8669 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 8670 LinKind = OMPC_LINEAR_val; 8671 for (auto &RefExpr : VarList) { 8672 assert(RefExpr && "NULL expr in OpenMP linear clause."); 8673 SourceLocation ELoc; 8674 SourceRange ERange; 8675 Expr *SimpleRefExpr = RefExpr; 8676 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 8677 /*AllowArraySection=*/false); 8678 if (Res.second) { 8679 // It will be analyzed later. 8680 Vars.push_back(RefExpr); 8681 Privates.push_back(nullptr); 8682 Inits.push_back(nullptr); 8683 } 8684 ValueDecl *D = Res.first; 8685 if (!D) 8686 continue; 8687 8688 QualType Type = D->getType(); 8689 auto *VD = dyn_cast<VarDecl>(D); 8690 8691 // OpenMP [2.14.3.7, linear clause] 8692 // A list-item cannot appear in more than one linear clause. 8693 // A list-item that appears in a linear clause cannot appear in any 8694 // other data-sharing attribute clause. 8695 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8696 if (DVar.RefExpr) { 8697 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8698 << getOpenMPClauseName(OMPC_linear); 8699 ReportOriginalDSA(*this, DSAStack, D, DVar); 8700 continue; 8701 } 8702 8703 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 8704 continue; 8705 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 8706 8707 // Build private copy of original var. 8708 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 8709 D->hasAttrs() ? &D->getAttrs() : nullptr); 8710 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 8711 // Build var to save initial value. 8712 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 8713 Expr *InitExpr; 8714 DeclRefExpr *Ref = nullptr; 8715 if (!VD && !CurContext->isDependentContext()) { 8716 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8717 if (!IsOpenMPCapturedDecl(D)) { 8718 ExprCaptures.push_back(Ref->getDecl()); 8719 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 8720 ExprResult RefRes = DefaultLvalueConversion(Ref); 8721 if (!RefRes.isUsable()) 8722 continue; 8723 ExprResult PostUpdateRes = 8724 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 8725 SimpleRefExpr, RefRes.get()); 8726 if (!PostUpdateRes.isUsable()) 8727 continue; 8728 ExprPostUpdates.push_back( 8729 IgnoredValueConversions(PostUpdateRes.get()).get()); 8730 } 8731 } 8732 } 8733 if (LinKind == OMPC_LINEAR_uval) 8734 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 8735 else 8736 InitExpr = VD ? SimpleRefExpr : Ref; 8737 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 8738 /*DirectInit=*/false, /*TypeMayContainAuto=*/false); 8739 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 8740 8741 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 8742 Vars.push_back((VD || CurContext->isDependentContext()) 8743 ? RefExpr->IgnoreParens() 8744 : Ref); 8745 Privates.push_back(PrivateRef); 8746 Inits.push_back(InitRef); 8747 } 8748 8749 if (Vars.empty()) 8750 return nullptr; 8751 8752 Expr *StepExpr = Step; 8753 Expr *CalcStepExpr = nullptr; 8754 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 8755 !Step->isInstantiationDependent() && 8756 !Step->containsUnexpandedParameterPack()) { 8757 SourceLocation StepLoc = Step->getLocStart(); 8758 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 8759 if (Val.isInvalid()) 8760 return nullptr; 8761 StepExpr = Val.get(); 8762 8763 // Build var to save the step value. 8764 VarDecl *SaveVar = 8765 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 8766 ExprResult SaveRef = 8767 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 8768 ExprResult CalcStep = 8769 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 8770 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 8771 8772 // Warn about zero linear step (it would be probably better specified as 8773 // making corresponding variables 'const'). 8774 llvm::APSInt Result; 8775 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 8776 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 8777 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 8778 << (Vars.size() > 1); 8779 if (!IsConstant && CalcStep.isUsable()) { 8780 // Calculate the step beforehand instead of doing this on each iteration. 8781 // (This is not used if the number of iterations may be kfold-ed). 8782 CalcStepExpr = CalcStep.get(); 8783 } 8784 } 8785 8786 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 8787 ColonLoc, EndLoc, Vars, Privates, Inits, 8788 StepExpr, CalcStepExpr, 8789 buildPreInits(Context, ExprCaptures), 8790 buildPostUpdate(*this, ExprPostUpdates)); 8791 } 8792 8793 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 8794 Expr *NumIterations, Sema &SemaRef, 8795 Scope *S, DSAStackTy *Stack) { 8796 // Walk the vars and build update/final expressions for the CodeGen. 8797 SmallVector<Expr *, 8> Updates; 8798 SmallVector<Expr *, 8> Finals; 8799 Expr *Step = Clause.getStep(); 8800 Expr *CalcStep = Clause.getCalcStep(); 8801 // OpenMP [2.14.3.7, linear clause] 8802 // If linear-step is not specified it is assumed to be 1. 8803 if (Step == nullptr) 8804 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 8805 else if (CalcStep) { 8806 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 8807 } 8808 bool HasErrors = false; 8809 auto CurInit = Clause.inits().begin(); 8810 auto CurPrivate = Clause.privates().begin(); 8811 auto LinKind = Clause.getModifier(); 8812 for (auto &RefExpr : Clause.varlists()) { 8813 SourceLocation ELoc; 8814 SourceRange ERange; 8815 Expr *SimpleRefExpr = RefExpr; 8816 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 8817 /*AllowArraySection=*/false); 8818 ValueDecl *D = Res.first; 8819 if (Res.second || !D) { 8820 Updates.push_back(nullptr); 8821 Finals.push_back(nullptr); 8822 HasErrors = true; 8823 continue; 8824 } 8825 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) { 8826 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts()) 8827 ->getMemberDecl(); 8828 } 8829 auto &&Info = Stack->isLoopControlVariable(D); 8830 Expr *InitExpr = *CurInit; 8831 8832 // Build privatized reference to the current linear var. 8833 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 8834 Expr *CapturedRef; 8835 if (LinKind == OMPC_LINEAR_uval) 8836 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 8837 else 8838 CapturedRef = 8839 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 8840 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 8841 /*RefersToCapture=*/true); 8842 8843 // Build update: Var = InitExpr + IV * Step 8844 ExprResult Update; 8845 if (!Info.first) { 8846 Update = 8847 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 8848 InitExpr, IV, Step, /* Subtract */ false); 8849 } else 8850 Update = *CurPrivate; 8851 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 8852 /*DiscardedValue=*/true); 8853 8854 // Build final: Var = InitExpr + NumIterations * Step 8855 ExprResult Final; 8856 if (!Info.first) { 8857 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 8858 InitExpr, NumIterations, Step, 8859 /* Subtract */ false); 8860 } else 8861 Final = *CurPrivate; 8862 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 8863 /*DiscardedValue=*/true); 8864 8865 if (!Update.isUsable() || !Final.isUsable()) { 8866 Updates.push_back(nullptr); 8867 Finals.push_back(nullptr); 8868 HasErrors = true; 8869 } else { 8870 Updates.push_back(Update.get()); 8871 Finals.push_back(Final.get()); 8872 } 8873 ++CurInit; 8874 ++CurPrivate; 8875 } 8876 Clause.setUpdates(Updates); 8877 Clause.setFinals(Finals); 8878 return HasErrors; 8879 } 8880 8881 OMPClause *Sema::ActOnOpenMPAlignedClause( 8882 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 8883 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 8884 8885 SmallVector<Expr *, 8> Vars; 8886 for (auto &RefExpr : VarList) { 8887 assert(RefExpr && "NULL expr in OpenMP linear clause."); 8888 SourceLocation ELoc; 8889 SourceRange ERange; 8890 Expr *SimpleRefExpr = RefExpr; 8891 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 8892 /*AllowArraySection=*/false); 8893 if (Res.second) { 8894 // It will be analyzed later. 8895 Vars.push_back(RefExpr); 8896 } 8897 ValueDecl *D = Res.first; 8898 if (!D) 8899 continue; 8900 8901 QualType QType = D->getType(); 8902 auto *VD = dyn_cast<VarDecl>(D); 8903 8904 // OpenMP [2.8.1, simd construct, Restrictions] 8905 // The type of list items appearing in the aligned clause must be 8906 // array, pointer, reference to array, or reference to pointer. 8907 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 8908 const Type *Ty = QType.getTypePtrOrNull(); 8909 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 8910 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 8911 << QType << getLangOpts().CPlusPlus << ERange; 8912 bool IsDecl = 8913 !VD || 8914 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8915 Diag(D->getLocation(), 8916 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8917 << D; 8918 continue; 8919 } 8920 8921 // OpenMP [2.8.1, simd construct, Restrictions] 8922 // A list-item cannot appear in more than one aligned clause. 8923 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 8924 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 8925 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 8926 << getOpenMPClauseName(OMPC_aligned); 8927 continue; 8928 } 8929 8930 DeclRefExpr *Ref = nullptr; 8931 if (!VD && IsOpenMPCapturedDecl(D)) 8932 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8933 Vars.push_back(DefaultFunctionArrayConversion( 8934 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 8935 .get()); 8936 } 8937 8938 // OpenMP [2.8.1, simd construct, Description] 8939 // The parameter of the aligned clause, alignment, must be a constant 8940 // positive integer expression. 8941 // If no optional parameter is specified, implementation-defined default 8942 // alignments for SIMD instructions on the target platforms are assumed. 8943 if (Alignment != nullptr) { 8944 ExprResult AlignResult = 8945 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 8946 if (AlignResult.isInvalid()) 8947 return nullptr; 8948 Alignment = AlignResult.get(); 8949 } 8950 if (Vars.empty()) 8951 return nullptr; 8952 8953 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 8954 EndLoc, Vars, Alignment); 8955 } 8956 8957 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 8958 SourceLocation StartLoc, 8959 SourceLocation LParenLoc, 8960 SourceLocation EndLoc) { 8961 SmallVector<Expr *, 8> Vars; 8962 SmallVector<Expr *, 8> SrcExprs; 8963 SmallVector<Expr *, 8> DstExprs; 8964 SmallVector<Expr *, 8> AssignmentOps; 8965 for (auto &RefExpr : VarList) { 8966 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 8967 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 8968 // It will be analyzed later. 8969 Vars.push_back(RefExpr); 8970 SrcExprs.push_back(nullptr); 8971 DstExprs.push_back(nullptr); 8972 AssignmentOps.push_back(nullptr); 8973 continue; 8974 } 8975 8976 SourceLocation ELoc = RefExpr->getExprLoc(); 8977 // OpenMP [2.1, C/C++] 8978 // A list item is a variable name. 8979 // OpenMP [2.14.4.1, Restrictions, p.1] 8980 // A list item that appears in a copyin clause must be threadprivate. 8981 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 8982 if (!DE || !isa<VarDecl>(DE->getDecl())) { 8983 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 8984 << 0 << RefExpr->getSourceRange(); 8985 continue; 8986 } 8987 8988 Decl *D = DE->getDecl(); 8989 VarDecl *VD = cast<VarDecl>(D); 8990 8991 QualType Type = VD->getType(); 8992 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 8993 // It will be analyzed later. 8994 Vars.push_back(DE); 8995 SrcExprs.push_back(nullptr); 8996 DstExprs.push_back(nullptr); 8997 AssignmentOps.push_back(nullptr); 8998 continue; 8999 } 9000 9001 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 9002 // A list item that appears in a copyin clause must be threadprivate. 9003 if (!DSAStack->isThreadPrivate(VD)) { 9004 Diag(ELoc, diag::err_omp_required_access) 9005 << getOpenMPClauseName(OMPC_copyin) 9006 << getOpenMPDirectiveName(OMPD_threadprivate); 9007 continue; 9008 } 9009 9010 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9011 // A variable of class type (or array thereof) that appears in a 9012 // copyin clause requires an accessible, unambiguous copy assignment 9013 // operator for the class type. 9014 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 9015 auto *SrcVD = 9016 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 9017 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9018 auto *PseudoSrcExpr = buildDeclRefExpr( 9019 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 9020 auto *DstVD = 9021 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 9022 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9023 auto *PseudoDstExpr = 9024 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 9025 // For arrays generate assignment operation for single element and replace 9026 // it by the original array element in CodeGen. 9027 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 9028 PseudoDstExpr, PseudoSrcExpr); 9029 if (AssignmentOp.isInvalid()) 9030 continue; 9031 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 9032 /*DiscardedValue=*/true); 9033 if (AssignmentOp.isInvalid()) 9034 continue; 9035 9036 DSAStack->addDSA(VD, DE, OMPC_copyin); 9037 Vars.push_back(DE); 9038 SrcExprs.push_back(PseudoSrcExpr); 9039 DstExprs.push_back(PseudoDstExpr); 9040 AssignmentOps.push_back(AssignmentOp.get()); 9041 } 9042 9043 if (Vars.empty()) 9044 return nullptr; 9045 9046 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 9047 SrcExprs, DstExprs, AssignmentOps); 9048 } 9049 9050 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 9051 SourceLocation StartLoc, 9052 SourceLocation LParenLoc, 9053 SourceLocation EndLoc) { 9054 SmallVector<Expr *, 8> Vars; 9055 SmallVector<Expr *, 8> SrcExprs; 9056 SmallVector<Expr *, 8> DstExprs; 9057 SmallVector<Expr *, 8> AssignmentOps; 9058 for (auto &RefExpr : VarList) { 9059 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9060 SourceLocation ELoc; 9061 SourceRange ERange; 9062 Expr *SimpleRefExpr = RefExpr; 9063 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9064 /*AllowArraySection=*/false); 9065 if (Res.second) { 9066 // It will be analyzed later. 9067 Vars.push_back(RefExpr); 9068 SrcExprs.push_back(nullptr); 9069 DstExprs.push_back(nullptr); 9070 AssignmentOps.push_back(nullptr); 9071 } 9072 ValueDecl *D = Res.first; 9073 if (!D) 9074 continue; 9075 9076 QualType Type = D->getType(); 9077 auto *VD = dyn_cast<VarDecl>(D); 9078 9079 // OpenMP [2.14.4.2, Restrictions, p.2] 9080 // A list item that appears in a copyprivate clause may not appear in a 9081 // private or firstprivate clause on the single construct. 9082 if (!VD || !DSAStack->isThreadPrivate(VD)) { 9083 auto DVar = DSAStack->getTopDSA(D, false); 9084 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 9085 DVar.RefExpr) { 9086 Diag(ELoc, diag::err_omp_wrong_dsa) 9087 << getOpenMPClauseName(DVar.CKind) 9088 << getOpenMPClauseName(OMPC_copyprivate); 9089 ReportOriginalDSA(*this, DSAStack, D, DVar); 9090 continue; 9091 } 9092 9093 // OpenMP [2.11.4.2, Restrictions, p.1] 9094 // All list items that appear in a copyprivate clause must be either 9095 // threadprivate or private in the enclosing context. 9096 if (DVar.CKind == OMPC_unknown) { 9097 DVar = DSAStack->getImplicitDSA(D, false); 9098 if (DVar.CKind == OMPC_shared) { 9099 Diag(ELoc, diag::err_omp_required_access) 9100 << getOpenMPClauseName(OMPC_copyprivate) 9101 << "threadprivate or private in the enclosing context"; 9102 ReportOriginalDSA(*this, DSAStack, D, DVar); 9103 continue; 9104 } 9105 } 9106 } 9107 9108 // Variably modified types are not supported. 9109 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 9110 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9111 << getOpenMPClauseName(OMPC_copyprivate) << Type 9112 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 9113 bool IsDecl = 9114 !VD || 9115 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9116 Diag(D->getLocation(), 9117 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9118 << D; 9119 continue; 9120 } 9121 9122 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9123 // A variable of class type (or array thereof) that appears in a 9124 // copyin clause requires an accessible, unambiguous copy assignment 9125 // operator for the class type. 9126 Type = Context.getBaseElementType(Type.getNonReferenceType()) 9127 .getUnqualifiedType(); 9128 auto *SrcVD = 9129 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 9130 D->hasAttrs() ? &D->getAttrs() : nullptr); 9131 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 9132 auto *DstVD = 9133 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 9134 D->hasAttrs() ? &D->getAttrs() : nullptr); 9135 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 9136 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9137 PseudoDstExpr, PseudoSrcExpr); 9138 if (AssignmentOp.isInvalid()) 9139 continue; 9140 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 9141 /*DiscardedValue=*/true); 9142 if (AssignmentOp.isInvalid()) 9143 continue; 9144 9145 // No need to mark vars as copyprivate, they are already threadprivate or 9146 // implicitly private. 9147 assert(VD || IsOpenMPCapturedDecl(D)); 9148 Vars.push_back( 9149 VD ? RefExpr->IgnoreParens() 9150 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 9151 SrcExprs.push_back(PseudoSrcExpr); 9152 DstExprs.push_back(PseudoDstExpr); 9153 AssignmentOps.push_back(AssignmentOp.get()); 9154 } 9155 9156 if (Vars.empty()) 9157 return nullptr; 9158 9159 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9160 Vars, SrcExprs, DstExprs, AssignmentOps); 9161 } 9162 9163 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 9164 SourceLocation StartLoc, 9165 SourceLocation LParenLoc, 9166 SourceLocation EndLoc) { 9167 if (VarList.empty()) 9168 return nullptr; 9169 9170 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 9171 } 9172 9173 OMPClause * 9174 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 9175 SourceLocation DepLoc, SourceLocation ColonLoc, 9176 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 9177 SourceLocation LParenLoc, SourceLocation EndLoc) { 9178 if (DSAStack->getCurrentDirective() == OMPD_ordered && 9179 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 9180 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 9181 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 9182 return nullptr; 9183 } 9184 if (DSAStack->getCurrentDirective() != OMPD_ordered && 9185 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 9186 DepKind == OMPC_DEPEND_sink)) { 9187 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 9188 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 9189 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 9190 /*Last=*/OMPC_DEPEND_unknown, Except) 9191 << getOpenMPClauseName(OMPC_depend); 9192 return nullptr; 9193 } 9194 SmallVector<Expr *, 8> Vars; 9195 DSAStackTy::OperatorOffsetTy OpsOffs; 9196 llvm::APSInt DepCounter(/*BitWidth=*/32); 9197 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 9198 if (DepKind == OMPC_DEPEND_sink) { 9199 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 9200 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 9201 TotalDepCount.setIsUnsigned(/*Val=*/true); 9202 } 9203 } 9204 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || 9205 DSAStack->getParentOrderedRegionParam()) { 9206 for (auto &RefExpr : VarList) { 9207 assert(RefExpr && "NULL expr in OpenMP shared clause."); 9208 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 9209 // It will be analyzed later. 9210 Vars.push_back(RefExpr); 9211 continue; 9212 } 9213 9214 SourceLocation ELoc = RefExpr->getExprLoc(); 9215 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 9216 if (DepKind == OMPC_DEPEND_sink) { 9217 if (DepCounter >= TotalDepCount) { 9218 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 9219 continue; 9220 } 9221 ++DepCounter; 9222 // OpenMP [2.13.9, Summary] 9223 // depend(dependence-type : vec), where dependence-type is: 9224 // 'sink' and where vec is the iteration vector, which has the form: 9225 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 9226 // where n is the value specified by the ordered clause in the loop 9227 // directive, xi denotes the loop iteration variable of the i-th nested 9228 // loop associated with the loop directive, and di is a constant 9229 // non-negative integer. 9230 if (CurContext->isDependentContext()) { 9231 // It will be analyzed later. 9232 Vars.push_back(RefExpr); 9233 continue; 9234 } 9235 SimpleExpr = SimpleExpr->IgnoreImplicit(); 9236 OverloadedOperatorKind OOK = OO_None; 9237 SourceLocation OOLoc; 9238 Expr *LHS = SimpleExpr; 9239 Expr *RHS = nullptr; 9240 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 9241 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 9242 OOLoc = BO->getOperatorLoc(); 9243 LHS = BO->getLHS()->IgnoreParenImpCasts(); 9244 RHS = BO->getRHS()->IgnoreParenImpCasts(); 9245 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 9246 OOK = OCE->getOperator(); 9247 OOLoc = OCE->getOperatorLoc(); 9248 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 9249 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 9250 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 9251 OOK = MCE->getMethodDecl() 9252 ->getNameInfo() 9253 .getName() 9254 .getCXXOverloadedOperator(); 9255 OOLoc = MCE->getCallee()->getExprLoc(); 9256 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 9257 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 9258 } 9259 SourceLocation ELoc; 9260 SourceRange ERange; 9261 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 9262 /*AllowArraySection=*/false); 9263 if (Res.second) { 9264 // It will be analyzed later. 9265 Vars.push_back(RefExpr); 9266 } 9267 ValueDecl *D = Res.first; 9268 if (!D) 9269 continue; 9270 9271 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 9272 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 9273 continue; 9274 } 9275 if (RHS) { 9276 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 9277 RHS, OMPC_depend, /*StrictlyPositive=*/false); 9278 if (RHSRes.isInvalid()) 9279 continue; 9280 } 9281 if (!CurContext->isDependentContext() && 9282 DSAStack->getParentOrderedRegionParam() && 9283 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 9284 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 9285 << DSAStack->getParentLoopControlVariable( 9286 DepCounter.getZExtValue()); 9287 continue; 9288 } 9289 OpsOffs.push_back({RHS, OOK}); 9290 } else { 9291 // OpenMP [2.11.1.1, Restrictions, p.3] 9292 // A variable that is part of another variable (such as a field of a 9293 // structure) but is not an array element or an array section cannot 9294 // appear in a depend clause. 9295 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr); 9296 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 9297 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 9298 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 9299 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) || 9300 (ASE && 9301 !ASE->getBase() 9302 ->getType() 9303 .getNonReferenceType() 9304 ->isPointerType() && 9305 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 9306 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item) 9307 << 0 << RefExpr->getSourceRange(); 9308 continue; 9309 } 9310 } 9311 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 9312 } 9313 9314 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 9315 TotalDepCount > VarList.size() && 9316 DSAStack->getParentOrderedRegionParam()) { 9317 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 9318 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 9319 } 9320 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 9321 Vars.empty()) 9322 return nullptr; 9323 } 9324 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9325 DepKind, DepLoc, ColonLoc, Vars); 9326 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) 9327 DSAStack->addDoacrossDependClause(C, OpsOffs); 9328 return C; 9329 } 9330 9331 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 9332 SourceLocation LParenLoc, 9333 SourceLocation EndLoc) { 9334 Expr *ValExpr = Device; 9335 9336 // OpenMP [2.9.1, Restrictions] 9337 // The device expression must evaluate to a non-negative integer value. 9338 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 9339 /*StrictlyPositive=*/false)) 9340 return nullptr; 9341 9342 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc); 9343 } 9344 9345 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc, 9346 DSAStackTy *Stack, CXXRecordDecl *RD) { 9347 if (!RD || RD->isInvalidDecl()) 9348 return true; 9349 9350 auto QTy = SemaRef.Context.getRecordType(RD); 9351 if (RD->isDynamicClass()) { 9352 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 9353 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target); 9354 return false; 9355 } 9356 auto *DC = RD; 9357 bool IsCorrect = true; 9358 for (auto *I : DC->decls()) { 9359 if (I) { 9360 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) { 9361 if (MD->isStatic()) { 9362 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 9363 SemaRef.Diag(MD->getLocation(), 9364 diag::note_omp_static_member_in_target); 9365 IsCorrect = false; 9366 } 9367 } else if (auto *VD = dyn_cast<VarDecl>(I)) { 9368 if (VD->isStaticDataMember()) { 9369 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 9370 SemaRef.Diag(VD->getLocation(), 9371 diag::note_omp_static_member_in_target); 9372 IsCorrect = false; 9373 } 9374 } 9375 } 9376 } 9377 9378 for (auto &I : RD->bases()) { 9379 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack, 9380 I.getType()->getAsCXXRecordDecl())) 9381 IsCorrect = false; 9382 } 9383 return IsCorrect; 9384 } 9385 9386 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 9387 DSAStackTy *Stack, QualType QTy) { 9388 NamedDecl *ND; 9389 if (QTy->isIncompleteType(&ND)) { 9390 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 9391 return false; 9392 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) { 9393 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD)) 9394 return false; 9395 } 9396 return true; 9397 } 9398 9399 /// \brief Return true if it can be proven that the provided array expression 9400 /// (array section or array subscript) does NOT specify the whole size of the 9401 /// array whose base type is \a BaseQTy. 9402 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 9403 const Expr *E, 9404 QualType BaseQTy) { 9405 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 9406 9407 // If this is an array subscript, it refers to the whole size if the size of 9408 // the dimension is constant and equals 1. Also, an array section assumes the 9409 // format of an array subscript if no colon is used. 9410 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 9411 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 9412 return ATy->getSize().getSExtValue() != 1; 9413 // Size can't be evaluated statically. 9414 return false; 9415 } 9416 9417 assert(OASE && "Expecting array section if not an array subscript."); 9418 auto *LowerBound = OASE->getLowerBound(); 9419 auto *Length = OASE->getLength(); 9420 9421 // If there is a lower bound that does not evaluates to zero, we are not 9422 // covering the whole dimension. 9423 if (LowerBound) { 9424 llvm::APSInt ConstLowerBound; 9425 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 9426 return false; // Can't get the integer value as a constant. 9427 if (ConstLowerBound.getSExtValue()) 9428 return true; 9429 } 9430 9431 // If we don't have a length we covering the whole dimension. 9432 if (!Length) 9433 return false; 9434 9435 // If the base is a pointer, we don't have a way to get the size of the 9436 // pointee. 9437 if (BaseQTy->isPointerType()) 9438 return false; 9439 9440 // We can only check if the length is the same as the size of the dimension 9441 // if we have a constant array. 9442 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 9443 if (!CATy) 9444 return false; 9445 9446 llvm::APSInt ConstLength; 9447 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 9448 return false; // Can't get the integer value as a constant. 9449 9450 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 9451 } 9452 9453 // Return true if it can be proven that the provided array expression (array 9454 // section or array subscript) does NOT specify a single element of the array 9455 // whose base type is \a BaseQTy. 9456 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 9457 const Expr *E, 9458 QualType BaseQTy) { 9459 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 9460 9461 // An array subscript always refer to a single element. Also, an array section 9462 // assumes the format of an array subscript if no colon is used. 9463 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 9464 return false; 9465 9466 assert(OASE && "Expecting array section if not an array subscript."); 9467 auto *Length = OASE->getLength(); 9468 9469 // If we don't have a length we have to check if the array has unitary size 9470 // for this dimension. Also, we should always expect a length if the base type 9471 // is pointer. 9472 if (!Length) { 9473 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 9474 return ATy->getSize().getSExtValue() != 1; 9475 // We cannot assume anything. 9476 return false; 9477 } 9478 9479 // Check if the length evaluates to 1. 9480 llvm::APSInt ConstLength; 9481 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 9482 return false; // Can't get the integer value as a constant. 9483 9484 return ConstLength.getSExtValue() != 1; 9485 } 9486 9487 // Return the expression of the base of the mappable expression or null if it 9488 // cannot be determined and do all the necessary checks to see if the expression 9489 // is valid as a standalone mappable expression. In the process, record all the 9490 // components of the expression. 9491 static Expr *CheckMapClauseExpressionBase( 9492 Sema &SemaRef, Expr *E, 9493 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 9494 OpenMPClauseKind CKind) { 9495 SourceLocation ELoc = E->getExprLoc(); 9496 SourceRange ERange = E->getSourceRange(); 9497 9498 // The base of elements of list in a map clause have to be either: 9499 // - a reference to variable or field. 9500 // - a member expression. 9501 // - an array expression. 9502 // 9503 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 9504 // reference to 'r'. 9505 // 9506 // If we have: 9507 // 9508 // struct SS { 9509 // Bla S; 9510 // foo() { 9511 // #pragma omp target map (S.Arr[:12]); 9512 // } 9513 // } 9514 // 9515 // We want to retrieve the member expression 'this->S'; 9516 9517 Expr *RelevantExpr = nullptr; 9518 9519 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 9520 // If a list item is an array section, it must specify contiguous storage. 9521 // 9522 // For this restriction it is sufficient that we make sure only references 9523 // to variables or fields and array expressions, and that no array sections 9524 // exist except in the rightmost expression (unless they cover the whole 9525 // dimension of the array). E.g. these would be invalid: 9526 // 9527 // r.ArrS[3:5].Arr[6:7] 9528 // 9529 // r.ArrS[3:5].x 9530 // 9531 // but these would be valid: 9532 // r.ArrS[3].Arr[6:7] 9533 // 9534 // r.ArrS[3].x 9535 9536 bool AllowUnitySizeArraySection = true; 9537 bool AllowWholeSizeArraySection = true; 9538 9539 while (!RelevantExpr) { 9540 E = E->IgnoreParenImpCasts(); 9541 9542 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 9543 if (!isa<VarDecl>(CurE->getDecl())) 9544 break; 9545 9546 RelevantExpr = CurE; 9547 9548 // If we got a reference to a declaration, we should not expect any array 9549 // section before that. 9550 AllowUnitySizeArraySection = false; 9551 AllowWholeSizeArraySection = false; 9552 9553 // Record the component. 9554 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent( 9555 CurE, CurE->getDecl())); 9556 continue; 9557 } 9558 9559 if (auto *CurE = dyn_cast<MemberExpr>(E)) { 9560 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 9561 9562 if (isa<CXXThisExpr>(BaseE)) 9563 // We found a base expression: this->Val. 9564 RelevantExpr = CurE; 9565 else 9566 E = BaseE; 9567 9568 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 9569 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 9570 << CurE->getSourceRange(); 9571 break; 9572 } 9573 9574 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 9575 9576 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 9577 // A bit-field cannot appear in a map clause. 9578 // 9579 if (FD->isBitField()) { 9580 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 9581 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 9582 break; 9583 } 9584 9585 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 9586 // If the type of a list item is a reference to a type T then the type 9587 // will be considered to be T for all purposes of this clause. 9588 QualType CurType = BaseE->getType().getNonReferenceType(); 9589 9590 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 9591 // A list item cannot be a variable that is a member of a structure with 9592 // a union type. 9593 // 9594 if (auto *RT = CurType->getAs<RecordType>()) 9595 if (RT->isUnionType()) { 9596 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 9597 << CurE->getSourceRange(); 9598 break; 9599 } 9600 9601 // If we got a member expression, we should not expect any array section 9602 // before that: 9603 // 9604 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 9605 // If a list item is an element of a structure, only the rightmost symbol 9606 // of the variable reference can be an array section. 9607 // 9608 AllowUnitySizeArraySection = false; 9609 AllowWholeSizeArraySection = false; 9610 9611 // Record the component. 9612 CurComponents.push_back( 9613 OMPClauseMappableExprCommon::MappableComponent(CurE, FD)); 9614 continue; 9615 } 9616 9617 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 9618 E = CurE->getBase()->IgnoreParenImpCasts(); 9619 9620 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 9621 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 9622 << 0 << CurE->getSourceRange(); 9623 break; 9624 } 9625 9626 // If we got an array subscript that express the whole dimension we 9627 // can have any array expressions before. If it only expressing part of 9628 // the dimension, we can only have unitary-size array expressions. 9629 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 9630 E->getType())) 9631 AllowWholeSizeArraySection = false; 9632 9633 // Record the component - we don't have any declaration associated. 9634 CurComponents.push_back( 9635 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 9636 continue; 9637 } 9638 9639 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 9640 E = CurE->getBase()->IgnoreParenImpCasts(); 9641 9642 auto CurType = 9643 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 9644 9645 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 9646 // If the type of a list item is a reference to a type T then the type 9647 // will be considered to be T for all purposes of this clause. 9648 if (CurType->isReferenceType()) 9649 CurType = CurType->getPointeeType(); 9650 9651 bool IsPointer = CurType->isAnyPointerType(); 9652 9653 if (!IsPointer && !CurType->isArrayType()) { 9654 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 9655 << 0 << CurE->getSourceRange(); 9656 break; 9657 } 9658 9659 bool NotWhole = 9660 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 9661 bool NotUnity = 9662 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 9663 9664 if (AllowWholeSizeArraySection) { 9665 // Any array section is currently allowed. Allowing a whole size array 9666 // section implies allowing a unity array section as well. 9667 // 9668 // If this array section refers to the whole dimension we can still 9669 // accept other array sections before this one, except if the base is a 9670 // pointer. Otherwise, only unitary sections are accepted. 9671 if (NotWhole || IsPointer) 9672 AllowWholeSizeArraySection = false; 9673 } else if (AllowUnitySizeArraySection && NotUnity) { 9674 // A unity or whole array section is not allowed and that is not 9675 // compatible with the properties of the current array section. 9676 SemaRef.Diag( 9677 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 9678 << CurE->getSourceRange(); 9679 break; 9680 } 9681 9682 // Record the component - we don't have any declaration associated. 9683 CurComponents.push_back( 9684 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 9685 continue; 9686 } 9687 9688 // If nothing else worked, this is not a valid map clause expression. 9689 SemaRef.Diag(ELoc, 9690 diag::err_omp_expected_named_var_member_or_array_expression) 9691 << ERange; 9692 break; 9693 } 9694 9695 return RelevantExpr; 9696 } 9697 9698 // Return true if expression E associated with value VD has conflicts with other 9699 // map information. 9700 static bool CheckMapConflicts( 9701 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 9702 bool CurrentRegionOnly, 9703 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 9704 OpenMPClauseKind CKind) { 9705 assert(VD && E); 9706 SourceLocation ELoc = E->getExprLoc(); 9707 SourceRange ERange = E->getSourceRange(); 9708 9709 // In order to easily check the conflicts we need to match each component of 9710 // the expression under test with the components of the expressions that are 9711 // already in the stack. 9712 9713 assert(!CurComponents.empty() && "Map clause expression with no components!"); 9714 assert(CurComponents.back().getAssociatedDeclaration() == VD && 9715 "Map clause expression with unexpected base!"); 9716 9717 // Variables to help detecting enclosing problems in data environment nests. 9718 bool IsEnclosedByDataEnvironmentExpr = false; 9719 const Expr *EnclosingExpr = nullptr; 9720 9721 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 9722 VD, CurrentRegionOnly, 9723 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 9724 StackComponents, 9725 OpenMPClauseKind) -> bool { 9726 9727 assert(!StackComponents.empty() && 9728 "Map clause expression with no components!"); 9729 assert(StackComponents.back().getAssociatedDeclaration() == VD && 9730 "Map clause expression with unexpected base!"); 9731 9732 // The whole expression in the stack. 9733 auto *RE = StackComponents.front().getAssociatedExpression(); 9734 9735 // Expressions must start from the same base. Here we detect at which 9736 // point both expressions diverge from each other and see if we can 9737 // detect if the memory referred to both expressions is contiguous and 9738 // do not overlap. 9739 auto CI = CurComponents.rbegin(); 9740 auto CE = CurComponents.rend(); 9741 auto SI = StackComponents.rbegin(); 9742 auto SE = StackComponents.rend(); 9743 for (; CI != CE && SI != SE; ++CI, ++SI) { 9744 9745 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 9746 // At most one list item can be an array item derived from a given 9747 // variable in map clauses of the same construct. 9748 if (CurrentRegionOnly && 9749 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 9750 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 9751 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 9752 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 9753 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 9754 diag::err_omp_multiple_array_items_in_map_clause) 9755 << CI->getAssociatedExpression()->getSourceRange(); 9756 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 9757 diag::note_used_here) 9758 << SI->getAssociatedExpression()->getSourceRange(); 9759 return true; 9760 } 9761 9762 // Do both expressions have the same kind? 9763 if (CI->getAssociatedExpression()->getStmtClass() != 9764 SI->getAssociatedExpression()->getStmtClass()) 9765 break; 9766 9767 // Are we dealing with different variables/fields? 9768 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 9769 break; 9770 } 9771 // Check if the extra components of the expressions in the enclosing 9772 // data environment are redundant for the current base declaration. 9773 // If they are, the maps completely overlap, which is legal. 9774 for (; SI != SE; ++SI) { 9775 QualType Type; 9776 if (auto *ASE = 9777 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 9778 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 9779 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>( 9780 SI->getAssociatedExpression())) { 9781 auto *E = OASE->getBase()->IgnoreParenImpCasts(); 9782 Type = 9783 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 9784 } 9785 if (Type.isNull() || Type->isAnyPointerType() || 9786 CheckArrayExpressionDoesNotReferToWholeSize( 9787 SemaRef, SI->getAssociatedExpression(), Type)) 9788 break; 9789 } 9790 9791 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 9792 // List items of map clauses in the same construct must not share 9793 // original storage. 9794 // 9795 // If the expressions are exactly the same or one is a subset of the 9796 // other, it means they are sharing storage. 9797 if (CI == CE && SI == SE) { 9798 if (CurrentRegionOnly) { 9799 if (CKind == OMPC_map) 9800 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 9801 else { 9802 assert(CKind == OMPC_to || CKind == OMPC_from); 9803 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 9804 << ERange; 9805 } 9806 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 9807 << RE->getSourceRange(); 9808 return true; 9809 } else { 9810 // If we find the same expression in the enclosing data environment, 9811 // that is legal. 9812 IsEnclosedByDataEnvironmentExpr = true; 9813 return false; 9814 } 9815 } 9816 9817 QualType DerivedType = 9818 std::prev(CI)->getAssociatedDeclaration()->getType(); 9819 SourceLocation DerivedLoc = 9820 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 9821 9822 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 9823 // If the type of a list item is a reference to a type T then the type 9824 // will be considered to be T for all purposes of this clause. 9825 DerivedType = DerivedType.getNonReferenceType(); 9826 9827 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 9828 // A variable for which the type is pointer and an array section 9829 // derived from that variable must not appear as list items of map 9830 // clauses of the same construct. 9831 // 9832 // Also, cover one of the cases in: 9833 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 9834 // If any part of the original storage of a list item has corresponding 9835 // storage in the device data environment, all of the original storage 9836 // must have corresponding storage in the device data environment. 9837 // 9838 if (DerivedType->isAnyPointerType()) { 9839 if (CI == CE || SI == SE) { 9840 SemaRef.Diag( 9841 DerivedLoc, 9842 diag::err_omp_pointer_mapped_along_with_derived_section) 9843 << DerivedLoc; 9844 } else { 9845 assert(CI != CE && SI != SE); 9846 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) 9847 << DerivedLoc; 9848 } 9849 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 9850 << RE->getSourceRange(); 9851 return true; 9852 } 9853 9854 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 9855 // List items of map clauses in the same construct must not share 9856 // original storage. 9857 // 9858 // An expression is a subset of the other. 9859 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 9860 if (CKind == OMPC_map) 9861 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 9862 else { 9863 assert(CKind == OMPC_to || CKind == OMPC_from); 9864 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 9865 << ERange; 9866 } 9867 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 9868 << RE->getSourceRange(); 9869 return true; 9870 } 9871 9872 // The current expression uses the same base as other expression in the 9873 // data environment but does not contain it completely. 9874 if (!CurrentRegionOnly && SI != SE) 9875 EnclosingExpr = RE; 9876 9877 // The current expression is a subset of the expression in the data 9878 // environment. 9879 IsEnclosedByDataEnvironmentExpr |= 9880 (!CurrentRegionOnly && CI != CE && SI == SE); 9881 9882 return false; 9883 }); 9884 9885 if (CurrentRegionOnly) 9886 return FoundError; 9887 9888 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 9889 // If any part of the original storage of a list item has corresponding 9890 // storage in the device data environment, all of the original storage must 9891 // have corresponding storage in the device data environment. 9892 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 9893 // If a list item is an element of a structure, and a different element of 9894 // the structure has a corresponding list item in the device data environment 9895 // prior to a task encountering the construct associated with the map clause, 9896 // then the list item must also have a corresponding list item in the device 9897 // data environment prior to the task encountering the construct. 9898 // 9899 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 9900 SemaRef.Diag(ELoc, 9901 diag::err_omp_original_storage_is_shared_and_does_not_contain) 9902 << ERange; 9903 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 9904 << EnclosingExpr->getSourceRange(); 9905 return true; 9906 } 9907 9908 return FoundError; 9909 } 9910 9911 namespace { 9912 // Utility struct that gathers all the related lists associated with a mappable 9913 // expression. 9914 struct MappableVarListInfo final { 9915 // The list of expressions. 9916 ArrayRef<Expr *> VarList; 9917 // The list of processed expressions. 9918 SmallVector<Expr *, 16> ProcessedVarList; 9919 // The mappble components for each expression. 9920 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 9921 // The base declaration of the variable. 9922 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 9923 9924 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 9925 // We have a list of components and base declarations for each entry in the 9926 // variable list. 9927 VarComponents.reserve(VarList.size()); 9928 VarBaseDeclarations.reserve(VarList.size()); 9929 } 9930 }; 9931 } 9932 9933 // Check the validity of the provided variable list for the provided clause kind 9934 // \a CKind. In the check process the valid expressions, and mappable expression 9935 // components and variables are extracted and used to fill \a Vars, 9936 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 9937 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 9938 static void 9939 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 9940 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 9941 SourceLocation StartLoc, 9942 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 9943 bool IsMapTypeImplicit = false) { 9944 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 9945 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 9946 "Unexpected clause kind with mappable expressions!"); 9947 9948 // Keep track of the mappable components and base declarations in this clause. 9949 // Each entry in the list is going to have a list of components associated. We 9950 // record each set of the components so that we can build the clause later on. 9951 // In the end we should have the same amount of declarations and component 9952 // lists. 9953 9954 for (auto &RE : MVLI.VarList) { 9955 assert(RE && "Null expr in omp to/from/map clause"); 9956 SourceLocation ELoc = RE->getExprLoc(); 9957 9958 auto *VE = RE->IgnoreParenLValueCasts(); 9959 9960 if (VE->isValueDependent() || VE->isTypeDependent() || 9961 VE->isInstantiationDependent() || 9962 VE->containsUnexpandedParameterPack()) { 9963 // We can only analyze this information once the missing information is 9964 // resolved. 9965 MVLI.ProcessedVarList.push_back(RE); 9966 continue; 9967 } 9968 9969 auto *SimpleExpr = RE->IgnoreParenCasts(); 9970 9971 if (!RE->IgnoreParenImpCasts()->isLValue()) { 9972 SemaRef.Diag(ELoc, 9973 diag::err_omp_expected_named_var_member_or_array_expression) 9974 << RE->getSourceRange(); 9975 continue; 9976 } 9977 9978 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 9979 ValueDecl *CurDeclaration = nullptr; 9980 9981 // Obtain the array or member expression bases if required. Also, fill the 9982 // components array with all the components identified in the process. 9983 auto *BE = 9984 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind); 9985 if (!BE) 9986 continue; 9987 9988 assert(!CurComponents.empty() && 9989 "Invalid mappable expression information."); 9990 9991 // For the following checks, we rely on the base declaration which is 9992 // expected to be associated with the last component. The declaration is 9993 // expected to be a variable or a field (if 'this' is being mapped). 9994 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 9995 assert(CurDeclaration && "Null decl on map clause."); 9996 assert( 9997 CurDeclaration->isCanonicalDecl() && 9998 "Expecting components to have associated only canonical declarations."); 9999 10000 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 10001 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 10002 10003 assert((VD || FD) && "Only variables or fields are expected here!"); 10004 (void)FD; 10005 10006 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 10007 // threadprivate variables cannot appear in a map clause. 10008 // OpenMP 4.5 [2.10.5, target update Construct] 10009 // threadprivate variables cannot appear in a from clause. 10010 if (VD && DSAS->isThreadPrivate(VD)) { 10011 auto DVar = DSAS->getTopDSA(VD, false); 10012 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 10013 << getOpenMPClauseName(CKind); 10014 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 10015 continue; 10016 } 10017 10018 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10019 // A list item cannot appear in both a map clause and a data-sharing 10020 // attribute clause on the same construct. 10021 10022 // Check conflicts with other map clause expressions. We check the conflicts 10023 // with the current construct separately from the enclosing data 10024 // environment, because the restrictions are different. We only have to 10025 // check conflicts across regions for the map clauses. 10026 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10027 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 10028 break; 10029 if (CKind == OMPC_map && 10030 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10031 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 10032 break; 10033 10034 // OpenMP 4.5 [2.10.5, target update Construct] 10035 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10036 // If the type of a list item is a reference to a type T then the type will 10037 // be considered to be T for all purposes of this clause. 10038 QualType Type = CurDeclaration->getType().getNonReferenceType(); 10039 10040 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 10041 // A list item in a to or from clause must have a mappable type. 10042 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10043 // A list item must have a mappable type. 10044 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 10045 DSAS, Type)) 10046 continue; 10047 10048 if (CKind == OMPC_map) { 10049 // target enter data 10050 // OpenMP [2.10.2, Restrictions, p. 99] 10051 // A map-type must be specified in all map clauses and must be either 10052 // to or alloc. 10053 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 10054 if (DKind == OMPD_target_enter_data && 10055 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 10056 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 10057 << (IsMapTypeImplicit ? 1 : 0) 10058 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 10059 << getOpenMPDirectiveName(DKind); 10060 continue; 10061 } 10062 10063 // target exit_data 10064 // OpenMP [2.10.3, Restrictions, p. 102] 10065 // A map-type must be specified in all map clauses and must be either 10066 // from, release, or delete. 10067 if (DKind == OMPD_target_exit_data && 10068 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 10069 MapType == OMPC_MAP_delete)) { 10070 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 10071 << (IsMapTypeImplicit ? 1 : 0) 10072 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 10073 << getOpenMPDirectiveName(DKind); 10074 continue; 10075 } 10076 10077 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10078 // A list item cannot appear in both a map clause and a data-sharing 10079 // attribute clause on the same construct 10080 if ((DKind == OMPD_target || DKind == OMPD_target_teams) && VD) { 10081 auto DVar = DSAS->getTopDSA(VD, false); 10082 if (isOpenMPPrivate(DVar.CKind)) { 10083 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10084 << getOpenMPClauseName(DVar.CKind) 10085 << getOpenMPClauseName(OMPC_map) 10086 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 10087 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 10088 continue; 10089 } 10090 } 10091 } 10092 10093 // Save the current expression. 10094 MVLI.ProcessedVarList.push_back(RE); 10095 10096 // Store the components in the stack so that they can be used to check 10097 // against other clauses later on. 10098 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 10099 /*WhereFoundClauseKind=*/OMPC_map); 10100 10101 // Save the components and declaration to create the clause. For purposes of 10102 // the clause creation, any component list that has has base 'this' uses 10103 // null as base declaration. 10104 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 10105 MVLI.VarComponents.back().append(CurComponents.begin(), 10106 CurComponents.end()); 10107 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 10108 : CurDeclaration); 10109 } 10110 } 10111 10112 OMPClause * 10113 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 10114 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 10115 SourceLocation MapLoc, SourceLocation ColonLoc, 10116 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10117 SourceLocation LParenLoc, SourceLocation EndLoc) { 10118 MappableVarListInfo MVLI(VarList); 10119 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 10120 MapType, IsMapTypeImplicit); 10121 10122 // We need to produce a map clause even if we don't have variables so that 10123 // other diagnostics related with non-existing map clauses are accurate. 10124 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10125 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 10126 MVLI.VarComponents, MapTypeModifier, MapType, 10127 IsMapTypeImplicit, MapLoc); 10128 } 10129 10130 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 10131 TypeResult ParsedType) { 10132 assert(ParsedType.isUsable()); 10133 10134 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 10135 if (ReductionType.isNull()) 10136 return QualType(); 10137 10138 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 10139 // A type name in a declare reduction directive cannot be a function type, an 10140 // array type, a reference type, or a type qualified with const, volatile or 10141 // restrict. 10142 if (ReductionType.hasQualifiers()) { 10143 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 10144 return QualType(); 10145 } 10146 10147 if (ReductionType->isFunctionType()) { 10148 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 10149 return QualType(); 10150 } 10151 if (ReductionType->isReferenceType()) { 10152 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 10153 return QualType(); 10154 } 10155 if (ReductionType->isArrayType()) { 10156 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 10157 return QualType(); 10158 } 10159 return ReductionType; 10160 } 10161 10162 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 10163 Scope *S, DeclContext *DC, DeclarationName Name, 10164 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 10165 AccessSpecifier AS, Decl *PrevDeclInScope) { 10166 SmallVector<Decl *, 8> Decls; 10167 Decls.reserve(ReductionTypes.size()); 10168 10169 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 10170 ForRedeclaration); 10171 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 10172 // A reduction-identifier may not be re-declared in the current scope for the 10173 // same type or for a type that is compatible according to the base language 10174 // rules. 10175 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 10176 OMPDeclareReductionDecl *PrevDRD = nullptr; 10177 bool InCompoundScope = true; 10178 if (S != nullptr) { 10179 // Find previous declaration with the same name not referenced in other 10180 // declarations. 10181 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 10182 InCompoundScope = 10183 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 10184 LookupName(Lookup, S); 10185 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 10186 /*AllowInlineNamespace=*/false); 10187 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 10188 auto Filter = Lookup.makeFilter(); 10189 while (Filter.hasNext()) { 10190 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 10191 if (InCompoundScope) { 10192 auto I = UsedAsPrevious.find(PrevDecl); 10193 if (I == UsedAsPrevious.end()) 10194 UsedAsPrevious[PrevDecl] = false; 10195 if (auto *D = PrevDecl->getPrevDeclInScope()) 10196 UsedAsPrevious[D] = true; 10197 } 10198 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 10199 PrevDecl->getLocation(); 10200 } 10201 Filter.done(); 10202 if (InCompoundScope) { 10203 for (auto &PrevData : UsedAsPrevious) { 10204 if (!PrevData.second) { 10205 PrevDRD = PrevData.first; 10206 break; 10207 } 10208 } 10209 } 10210 } else if (PrevDeclInScope != nullptr) { 10211 auto *PrevDRDInScope = PrevDRD = 10212 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 10213 do { 10214 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 10215 PrevDRDInScope->getLocation(); 10216 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 10217 } while (PrevDRDInScope != nullptr); 10218 } 10219 for (auto &TyData : ReductionTypes) { 10220 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 10221 bool Invalid = false; 10222 if (I != PreviousRedeclTypes.end()) { 10223 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 10224 << TyData.first; 10225 Diag(I->second, diag::note_previous_definition); 10226 Invalid = true; 10227 } 10228 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 10229 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 10230 Name, TyData.first, PrevDRD); 10231 DC->addDecl(DRD); 10232 DRD->setAccess(AS); 10233 Decls.push_back(DRD); 10234 if (Invalid) 10235 DRD->setInvalidDecl(); 10236 else 10237 PrevDRD = DRD; 10238 } 10239 10240 return DeclGroupPtrTy::make( 10241 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 10242 } 10243 10244 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 10245 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10246 10247 // Enter new function scope. 10248 PushFunctionScope(); 10249 getCurFunction()->setHasBranchProtectedScope(); 10250 getCurFunction()->setHasOMPDeclareReductionCombiner(); 10251 10252 if (S != nullptr) 10253 PushDeclContext(S, DRD); 10254 else 10255 CurContext = DRD; 10256 10257 PushExpressionEvaluationContext(PotentiallyEvaluated); 10258 10259 QualType ReductionType = DRD->getType(); 10260 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 10261 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 10262 // uses semantics of argument handles by value, but it should be passed by 10263 // reference. C lang does not support references, so pass all parameters as 10264 // pointers. 10265 // Create 'T omp_in;' variable. 10266 auto *OmpInParm = 10267 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 10268 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 10269 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 10270 // uses semantics of argument handles by value, but it should be passed by 10271 // reference. C lang does not support references, so pass all parameters as 10272 // pointers. 10273 // Create 'T omp_out;' variable. 10274 auto *OmpOutParm = 10275 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 10276 if (S != nullptr) { 10277 PushOnScopeChains(OmpInParm, S); 10278 PushOnScopeChains(OmpOutParm, S); 10279 } else { 10280 DRD->addDecl(OmpInParm); 10281 DRD->addDecl(OmpOutParm); 10282 } 10283 } 10284 10285 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 10286 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10287 DiscardCleanupsInEvaluationContext(); 10288 PopExpressionEvaluationContext(); 10289 10290 PopDeclContext(); 10291 PopFunctionScopeInfo(); 10292 10293 if (Combiner != nullptr) 10294 DRD->setCombiner(Combiner); 10295 else 10296 DRD->setInvalidDecl(); 10297 } 10298 10299 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 10300 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10301 10302 // Enter new function scope. 10303 PushFunctionScope(); 10304 getCurFunction()->setHasBranchProtectedScope(); 10305 10306 if (S != nullptr) 10307 PushDeclContext(S, DRD); 10308 else 10309 CurContext = DRD; 10310 10311 PushExpressionEvaluationContext(PotentiallyEvaluated); 10312 10313 QualType ReductionType = DRD->getType(); 10314 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 10315 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 10316 // uses semantics of argument handles by value, but it should be passed by 10317 // reference. C lang does not support references, so pass all parameters as 10318 // pointers. 10319 // Create 'T omp_priv;' variable. 10320 auto *OmpPrivParm = 10321 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 10322 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 10323 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 10324 // uses semantics of argument handles by value, but it should be passed by 10325 // reference. C lang does not support references, so pass all parameters as 10326 // pointers. 10327 // Create 'T omp_orig;' variable. 10328 auto *OmpOrigParm = 10329 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 10330 if (S != nullptr) { 10331 PushOnScopeChains(OmpPrivParm, S); 10332 PushOnScopeChains(OmpOrigParm, S); 10333 } else { 10334 DRD->addDecl(OmpPrivParm); 10335 DRD->addDecl(OmpOrigParm); 10336 } 10337 } 10338 10339 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, 10340 Expr *Initializer) { 10341 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10342 DiscardCleanupsInEvaluationContext(); 10343 PopExpressionEvaluationContext(); 10344 10345 PopDeclContext(); 10346 PopFunctionScopeInfo(); 10347 10348 if (Initializer != nullptr) 10349 DRD->setInitializer(Initializer); 10350 else 10351 DRD->setInvalidDecl(); 10352 } 10353 10354 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 10355 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 10356 for (auto *D : DeclReductions.get()) { 10357 if (IsValid) { 10358 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10359 if (S != nullptr) 10360 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 10361 } else 10362 D->setInvalidDecl(); 10363 } 10364 return DeclReductions; 10365 } 10366 10367 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 10368 SourceLocation StartLoc, 10369 SourceLocation LParenLoc, 10370 SourceLocation EndLoc) { 10371 Expr *ValExpr = NumTeams; 10372 10373 // OpenMP [teams Constrcut, Restrictions] 10374 // The num_teams expression must evaluate to a positive integer value. 10375 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 10376 /*StrictlyPositive=*/true)) 10377 return nullptr; 10378 10379 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10380 } 10381 10382 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 10383 SourceLocation StartLoc, 10384 SourceLocation LParenLoc, 10385 SourceLocation EndLoc) { 10386 Expr *ValExpr = ThreadLimit; 10387 10388 // OpenMP [teams Constrcut, Restrictions] 10389 // The thread_limit expression must evaluate to a positive integer value. 10390 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 10391 /*StrictlyPositive=*/true)) 10392 return nullptr; 10393 10394 return new (Context) 10395 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10396 } 10397 10398 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 10399 SourceLocation StartLoc, 10400 SourceLocation LParenLoc, 10401 SourceLocation EndLoc) { 10402 Expr *ValExpr = Priority; 10403 10404 // OpenMP [2.9.1, task Constrcut] 10405 // The priority-value is a non-negative numerical scalar expression. 10406 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 10407 /*StrictlyPositive=*/false)) 10408 return nullptr; 10409 10410 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10411 } 10412 10413 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 10414 SourceLocation StartLoc, 10415 SourceLocation LParenLoc, 10416 SourceLocation EndLoc) { 10417 Expr *ValExpr = Grainsize; 10418 10419 // OpenMP [2.9.2, taskloop Constrcut] 10420 // The parameter of the grainsize clause must be a positive integer 10421 // expression. 10422 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 10423 /*StrictlyPositive=*/true)) 10424 return nullptr; 10425 10426 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10427 } 10428 10429 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 10430 SourceLocation StartLoc, 10431 SourceLocation LParenLoc, 10432 SourceLocation EndLoc) { 10433 Expr *ValExpr = NumTasks; 10434 10435 // OpenMP [2.9.2, taskloop Constrcut] 10436 // The parameter of the num_tasks clause must be a positive integer 10437 // expression. 10438 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 10439 /*StrictlyPositive=*/true)) 10440 return nullptr; 10441 10442 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10443 } 10444 10445 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 10446 SourceLocation LParenLoc, 10447 SourceLocation EndLoc) { 10448 // OpenMP [2.13.2, critical construct, Description] 10449 // ... where hint-expression is an integer constant expression that evaluates 10450 // to a valid lock hint. 10451 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 10452 if (HintExpr.isInvalid()) 10453 return nullptr; 10454 return new (Context) 10455 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 10456 } 10457 10458 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 10459 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 10460 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 10461 SourceLocation EndLoc) { 10462 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 10463 std::string Values; 10464 Values += "'"; 10465 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 10466 Values += "'"; 10467 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 10468 << Values << getOpenMPClauseName(OMPC_dist_schedule); 10469 return nullptr; 10470 } 10471 Expr *ValExpr = ChunkSize; 10472 Stmt *HelperValStmt = nullptr; 10473 if (ChunkSize) { 10474 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 10475 !ChunkSize->isInstantiationDependent() && 10476 !ChunkSize->containsUnexpandedParameterPack()) { 10477 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 10478 ExprResult Val = 10479 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 10480 if (Val.isInvalid()) 10481 return nullptr; 10482 10483 ValExpr = Val.get(); 10484 10485 // OpenMP [2.7.1, Restrictions] 10486 // chunk_size must be a loop invariant integer expression with a positive 10487 // value. 10488 llvm::APSInt Result; 10489 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 10490 if (Result.isSigned() && !Result.isStrictlyPositive()) { 10491 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 10492 << "dist_schedule" << ChunkSize->getSourceRange(); 10493 return nullptr; 10494 } 10495 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 10496 !CurContext->isDependentContext()) { 10497 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 10498 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 10499 HelperValStmt = buildPreInits(Context, Captures); 10500 } 10501 } 10502 } 10503 10504 return new (Context) 10505 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 10506 Kind, ValExpr, HelperValStmt); 10507 } 10508 10509 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 10510 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 10511 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 10512 SourceLocation KindLoc, SourceLocation EndLoc) { 10513 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 10514 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 10515 std::string Value; 10516 SourceLocation Loc; 10517 Value += "'"; 10518 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 10519 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 10520 OMPC_DEFAULTMAP_MODIFIER_tofrom); 10521 Loc = MLoc; 10522 } else { 10523 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 10524 OMPC_DEFAULTMAP_scalar); 10525 Loc = KindLoc; 10526 } 10527 Value += "'"; 10528 Diag(Loc, diag::err_omp_unexpected_clause_value) 10529 << Value << getOpenMPClauseName(OMPC_defaultmap); 10530 return nullptr; 10531 } 10532 10533 return new (Context) 10534 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 10535 } 10536 10537 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 10538 DeclContext *CurLexicalContext = getCurLexicalContext(); 10539 if (!CurLexicalContext->isFileContext() && 10540 !CurLexicalContext->isExternCContext() && 10541 !CurLexicalContext->isExternCXXContext()) { 10542 Diag(Loc, diag::err_omp_region_not_file_context); 10543 return false; 10544 } 10545 if (IsInOpenMPDeclareTargetContext) { 10546 Diag(Loc, diag::err_omp_enclosed_declare_target); 10547 return false; 10548 } 10549 10550 IsInOpenMPDeclareTargetContext = true; 10551 return true; 10552 } 10553 10554 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 10555 assert(IsInOpenMPDeclareTargetContext && 10556 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 10557 10558 IsInOpenMPDeclareTargetContext = false; 10559 } 10560 10561 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 10562 CXXScopeSpec &ScopeSpec, 10563 const DeclarationNameInfo &Id, 10564 OMPDeclareTargetDeclAttr::MapTypeTy MT, 10565 NamedDeclSetType &SameDirectiveDecls) { 10566 LookupResult Lookup(*this, Id, LookupOrdinaryName); 10567 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 10568 10569 if (Lookup.isAmbiguous()) 10570 return; 10571 Lookup.suppressDiagnostics(); 10572 10573 if (!Lookup.isSingleResult()) { 10574 if (TypoCorrection Corrected = 10575 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 10576 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 10577 CTK_ErrorRecovery)) { 10578 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 10579 << Id.getName()); 10580 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 10581 return; 10582 } 10583 10584 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 10585 return; 10586 } 10587 10588 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 10589 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 10590 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 10591 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 10592 10593 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 10594 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 10595 ND->addAttr(A); 10596 if (ASTMutationListener *ML = Context.getASTMutationListener()) 10597 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 10598 checkDeclIsAllowedInOpenMPTarget(nullptr, ND); 10599 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 10600 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 10601 << Id.getName(); 10602 } 10603 } else 10604 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 10605 } 10606 10607 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 10608 Sema &SemaRef, Decl *D) { 10609 if (!D) 10610 return; 10611 Decl *LD = nullptr; 10612 if (isa<TagDecl>(D)) { 10613 LD = cast<TagDecl>(D)->getDefinition(); 10614 } else if (isa<VarDecl>(D)) { 10615 LD = cast<VarDecl>(D)->getDefinition(); 10616 10617 // If this is an implicit variable that is legal and we do not need to do 10618 // anything. 10619 if (cast<VarDecl>(D)->isImplicit()) { 10620 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 10621 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 10622 D->addAttr(A); 10623 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 10624 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 10625 return; 10626 } 10627 10628 } else if (isa<FunctionDecl>(D)) { 10629 const FunctionDecl *FD = nullptr; 10630 if (cast<FunctionDecl>(D)->hasBody(FD)) 10631 LD = const_cast<FunctionDecl *>(FD); 10632 10633 // If the definition is associated with the current declaration in the 10634 // target region (it can be e.g. a lambda) that is legal and we do not need 10635 // to do anything else. 10636 if (LD == D) { 10637 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 10638 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 10639 D->addAttr(A); 10640 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 10641 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 10642 return; 10643 } 10644 } 10645 if (!LD) 10646 LD = D; 10647 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 10648 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 10649 // Outlined declaration is not declared target. 10650 if (LD->isOutOfLine()) { 10651 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 10652 SemaRef.Diag(SL, diag::note_used_here) << SR; 10653 } else { 10654 DeclContext *DC = LD->getDeclContext(); 10655 while (DC) { 10656 if (isa<FunctionDecl>(DC) && 10657 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 10658 break; 10659 DC = DC->getParent(); 10660 } 10661 if (DC) 10662 return; 10663 10664 // Is not declared in target context. 10665 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 10666 SemaRef.Diag(SL, diag::note_used_here) << SR; 10667 } 10668 // Mark decl as declared target to prevent further diagnostic. 10669 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 10670 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 10671 D->addAttr(A); 10672 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 10673 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 10674 } 10675 } 10676 10677 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 10678 Sema &SemaRef, DSAStackTy *Stack, 10679 ValueDecl *VD) { 10680 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 10681 return true; 10682 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) 10683 return false; 10684 return true; 10685 } 10686 10687 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) { 10688 if (!D || D->isInvalidDecl()) 10689 return; 10690 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 10691 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 10692 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 10693 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10694 if (DSAStack->isThreadPrivate(VD)) { 10695 Diag(SL, diag::err_omp_threadprivate_in_target); 10696 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 10697 return; 10698 } 10699 } 10700 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 10701 // Problem if any with var declared with incomplete type will be reported 10702 // as normal, so no need to check it here. 10703 if ((E || !VD->getType()->isIncompleteType()) && 10704 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 10705 // Mark decl as declared target to prevent further diagnostic. 10706 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { 10707 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 10708 Context, OMPDeclareTargetDeclAttr::MT_To); 10709 VD->addAttr(A); 10710 if (ASTMutationListener *ML = Context.getASTMutationListener()) 10711 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 10712 } 10713 return; 10714 } 10715 } 10716 if (!E) { 10717 // Checking declaration inside declare target region. 10718 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 10719 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { 10720 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 10721 Context, OMPDeclareTargetDeclAttr::MT_To); 10722 D->addAttr(A); 10723 if (ASTMutationListener *ML = Context.getASTMutationListener()) 10724 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 10725 } 10726 return; 10727 } 10728 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 10729 } 10730 10731 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 10732 SourceLocation StartLoc, 10733 SourceLocation LParenLoc, 10734 SourceLocation EndLoc) { 10735 MappableVarListInfo MVLI(VarList); 10736 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 10737 if (MVLI.ProcessedVarList.empty()) 10738 return nullptr; 10739 10740 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10741 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 10742 MVLI.VarComponents); 10743 } 10744 10745 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 10746 SourceLocation StartLoc, 10747 SourceLocation LParenLoc, 10748 SourceLocation EndLoc) { 10749 MappableVarListInfo MVLI(VarList); 10750 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 10751 if (MVLI.ProcessedVarList.empty()) 10752 return nullptr; 10753 10754 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10755 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 10756 MVLI.VarComponents); 10757 } 10758 10759 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 10760 SourceLocation StartLoc, 10761 SourceLocation LParenLoc, 10762 SourceLocation EndLoc) { 10763 MappableVarListInfo MVLI(VarList); 10764 SmallVector<Expr *, 8> PrivateCopies; 10765 SmallVector<Expr *, 8> Inits; 10766 10767 for (auto &RefExpr : VarList) { 10768 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 10769 SourceLocation ELoc; 10770 SourceRange ERange; 10771 Expr *SimpleRefExpr = RefExpr; 10772 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10773 if (Res.second) { 10774 // It will be analyzed later. 10775 MVLI.ProcessedVarList.push_back(RefExpr); 10776 PrivateCopies.push_back(nullptr); 10777 Inits.push_back(nullptr); 10778 } 10779 ValueDecl *D = Res.first; 10780 if (!D) 10781 continue; 10782 10783 QualType Type = D->getType(); 10784 Type = Type.getNonReferenceType().getUnqualifiedType(); 10785 10786 auto *VD = dyn_cast<VarDecl>(D); 10787 10788 // Item should be a pointer or reference to pointer. 10789 if (!Type->isPointerType()) { 10790 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 10791 << 0 << RefExpr->getSourceRange(); 10792 continue; 10793 } 10794 10795 // Build the private variable and the expression that refers to it. 10796 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 10797 D->hasAttrs() ? &D->getAttrs() : nullptr); 10798 if (VDPrivate->isInvalidDecl()) 10799 continue; 10800 10801 CurContext->addDecl(VDPrivate); 10802 auto VDPrivateRefExpr = buildDeclRefExpr( 10803 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 10804 10805 // Add temporary variable to initialize the private copy of the pointer. 10806 auto *VDInit = 10807 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 10808 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 10809 RefExpr->getExprLoc()); 10810 AddInitializerToDecl(VDPrivate, 10811 DefaultLvalueConversion(VDInitRefExpr).get(), 10812 /*DirectInit=*/false, /*TypeMayContainAuto=*/false); 10813 10814 // If required, build a capture to implement the privatization initialized 10815 // with the current list item value. 10816 DeclRefExpr *Ref = nullptr; 10817 if (!VD) 10818 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 10819 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 10820 PrivateCopies.push_back(VDPrivateRefExpr); 10821 Inits.push_back(VDInitRefExpr); 10822 10823 // We need to add a data sharing attribute for this variable to make sure it 10824 // is correctly captured. A variable that shows up in a use_device_ptr has 10825 // similar properties of a first private variable. 10826 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 10827 10828 // Create a mappable component for the list item. List items in this clause 10829 // only need a component. 10830 MVLI.VarBaseDeclarations.push_back(D); 10831 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 10832 MVLI.VarComponents.back().push_back( 10833 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 10834 } 10835 10836 if (MVLI.ProcessedVarList.empty()) 10837 return nullptr; 10838 10839 return OMPUseDevicePtrClause::Create( 10840 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 10841 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 10842 } 10843 10844 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 10845 SourceLocation StartLoc, 10846 SourceLocation LParenLoc, 10847 SourceLocation EndLoc) { 10848 MappableVarListInfo MVLI(VarList); 10849 for (auto &RefExpr : VarList) { 10850 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 10851 SourceLocation ELoc; 10852 SourceRange ERange; 10853 Expr *SimpleRefExpr = RefExpr; 10854 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10855 if (Res.second) { 10856 // It will be analyzed later. 10857 MVLI.ProcessedVarList.push_back(RefExpr); 10858 } 10859 ValueDecl *D = Res.first; 10860 if (!D) 10861 continue; 10862 10863 QualType Type = D->getType(); 10864 // item should be a pointer or array or reference to pointer or array 10865 if (!Type.getNonReferenceType()->isPointerType() && 10866 !Type.getNonReferenceType()->isArrayType()) { 10867 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 10868 << 0 << RefExpr->getSourceRange(); 10869 continue; 10870 } 10871 10872 // Check if the declaration in the clause does not show up in any data 10873 // sharing attribute. 10874 auto DVar = DSAStack->getTopDSA(D, false); 10875 if (isOpenMPPrivate(DVar.CKind)) { 10876 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10877 << getOpenMPClauseName(DVar.CKind) 10878 << getOpenMPClauseName(OMPC_is_device_ptr) 10879 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 10880 ReportOriginalDSA(*this, DSAStack, D, DVar); 10881 continue; 10882 } 10883 10884 Expr *ConflictExpr; 10885 if (DSAStack->checkMappableExprComponentListsForDecl( 10886 D, /*CurrentRegionOnly=*/true, 10887 [&ConflictExpr]( 10888 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 10889 OpenMPClauseKind) -> bool { 10890 ConflictExpr = R.front().getAssociatedExpression(); 10891 return true; 10892 })) { 10893 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 10894 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 10895 << ConflictExpr->getSourceRange(); 10896 continue; 10897 } 10898 10899 // Store the components in the stack so that they can be used to check 10900 // against other clauses later on. 10901 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 10902 DSAStack->addMappableExpressionComponents( 10903 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 10904 10905 // Record the expression we've just processed. 10906 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 10907 10908 // Create a mappable component for the list item. List items in this clause 10909 // only need a component. We use a null declaration to signal fields in 10910 // 'this'. 10911 assert((isa<DeclRefExpr>(SimpleRefExpr) || 10912 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 10913 "Unexpected device pointer expression!"); 10914 MVLI.VarBaseDeclarations.push_back( 10915 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 10916 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 10917 MVLI.VarComponents.back().push_back(MC); 10918 } 10919 10920 if (MVLI.ProcessedVarList.empty()) 10921 return nullptr; 10922 10923 return OMPIsDevicePtrClause::Create( 10924 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 10925 MVLI.VarBaseDeclarations, MVLI.VarComponents); 10926 } 10927