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