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