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/Basic/OpenMPKinds.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Scope.h" 29 #include "clang/Sema/ScopeInfo.h" 30 #include "clang/Sema/SemaInternal.h" 31 #include "llvm/ADT/PointerEmbeddedInt.h" 32 using namespace clang; 33 34 //===----------------------------------------------------------------------===// 35 // Stack of data-sharing attributes for variables 36 //===----------------------------------------------------------------------===// 37 38 static Expr *CheckMapClauseExpressionBase( 39 Sema &SemaRef, Expr *E, 40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 41 OpenMPClauseKind CKind); 42 43 namespace { 44 /// \brief Default data sharing attributes, which can be applied to directive. 45 enum DefaultDataSharingAttributes { 46 DSA_unspecified = 0, /// \brief Data sharing attribute not specified. 47 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'. 48 DSA_shared = 1 << 1, /// \brief Default data sharing attribute 'shared'. 49 }; 50 51 /// Attributes of the defaultmap clause. 52 enum DefaultMapAttributes { 53 DMA_unspecified, /// Default mapping is not specified. 54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'. 55 }; 56 57 /// \brief Stack for tracking declarations used in OpenMP directives and 58 /// clauses and their data-sharing attributes. 59 class DSAStackTy final { 60 public: 61 struct DSAVarData final { 62 OpenMPDirectiveKind DKind = OMPD_unknown; 63 OpenMPClauseKind CKind = OMPC_unknown; 64 Expr *RefExpr = nullptr; 65 DeclRefExpr *PrivateCopy = nullptr; 66 SourceLocation ImplicitDSALoc; 67 DSAVarData() = default; 68 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr, 69 DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc) 70 : DKind(DKind), CKind(CKind), RefExpr(RefExpr), 71 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {} 72 }; 73 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4> 74 OperatorOffsetTy; 75 76 private: 77 struct DSAInfo final { 78 OpenMPClauseKind Attributes = OMPC_unknown; 79 /// Pointer to a reference expression and a flag which shows that the 80 /// variable is marked as lastprivate(true) or not (false). 81 llvm::PointerIntPair<Expr *, 1, bool> RefExpr; 82 DeclRefExpr *PrivateCopy = nullptr; 83 }; 84 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy; 85 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy; 86 typedef std::pair<unsigned, VarDecl *> LCDeclInfo; 87 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy; 88 /// Struct that associates a component with the clause kind where they are 89 /// found. 90 struct MappedExprComponentTy { 91 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 92 OpenMPClauseKind Kind = OMPC_unknown; 93 }; 94 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy> 95 MappedExprComponentsTy; 96 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>> 97 CriticalsWithHintsTy; 98 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy> 99 DoacrossDependMapTy; 100 struct ReductionData { 101 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType; 102 SourceRange ReductionRange; 103 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 104 ReductionData() = default; 105 void set(BinaryOperatorKind BO, SourceRange RR) { 106 ReductionRange = RR; 107 ReductionOp = BO; 108 } 109 void set(const Expr *RefExpr, SourceRange RR) { 110 ReductionRange = RR; 111 ReductionOp = RefExpr; 112 } 113 }; 114 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy; 115 116 struct SharingMapTy final { 117 DeclSAMapTy SharingMap; 118 DeclReductionMapTy ReductionMap; 119 AlignedMapTy AlignedMap; 120 MappedExprComponentsTy MappedExprComponents; 121 LoopControlVariablesMapTy LCVMap; 122 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 123 SourceLocation DefaultAttrLoc; 124 DefaultMapAttributes DefaultMapAttr = DMA_unspecified; 125 SourceLocation DefaultMapAttrLoc; 126 OpenMPDirectiveKind Directive = OMPD_unknown; 127 DeclarationNameInfo DirectiveName; 128 Scope *CurScope = nullptr; 129 SourceLocation ConstructLoc; 130 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 131 /// get the data (loop counters etc.) about enclosing loop-based construct. 132 /// This data is required during codegen. 133 DoacrossDependMapTy DoacrossDepends; 134 /// \brief first argument (Expr *) contains optional argument of the 135 /// 'ordered' clause, the second one is true if the regions has 'ordered' 136 /// clause, false otherwise. 137 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion; 138 bool NowaitRegion = false; 139 bool CancelRegion = false; 140 unsigned AssociatedLoops = 1; 141 SourceLocation InnerTeamsRegionLoc; 142 /// Reference to the taskgroup task_reduction reference expression. 143 Expr *TaskgroupReductionRef = nullptr; 144 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 145 Scope *CurScope, SourceLocation Loc) 146 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 147 ConstructLoc(Loc) {} 148 SharingMapTy() = default; 149 }; 150 151 typedef SmallVector<SharingMapTy, 4> StackTy; 152 153 /// \brief Stack of used declaration and their data-sharing attributes. 154 DeclSAMapTy Threadprivates; 155 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 156 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 157 /// \brief true, if check for DSA must be from parent directive, false, if 158 /// from current directive. 159 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 160 Sema &SemaRef; 161 bool ForceCapturing = false; 162 CriticalsWithHintsTy Criticals; 163 164 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; 165 166 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D); 167 168 /// \brief Checks if the variable is a local for OpenMP region. 169 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); 170 171 bool isStackEmpty() const { 172 return Stack.empty() || 173 Stack.back().second != CurrentNonCapturingFunctionScope || 174 Stack.back().first.empty(); 175 } 176 177 public: 178 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 179 180 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 181 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 182 183 bool isForceVarCapturing() const { return ForceCapturing; } 184 void setForceVarCapturing(bool V) { ForceCapturing = V; } 185 186 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 187 Scope *CurScope, SourceLocation Loc) { 188 if (Stack.empty() || 189 Stack.back().second != CurrentNonCapturingFunctionScope) 190 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 191 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 192 Stack.back().first.back().DefaultAttrLoc = Loc; 193 } 194 195 void pop() { 196 assert(!Stack.back().first.empty() && 197 "Data-sharing attributes stack is empty!"); 198 Stack.back().first.pop_back(); 199 } 200 201 /// Start new OpenMP region stack in new non-capturing function. 202 void pushFunction() { 203 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 204 assert(!isa<CapturingScopeInfo>(CurFnScope)); 205 CurrentNonCapturingFunctionScope = CurFnScope; 206 } 207 /// Pop region stack for non-capturing function. 208 void popFunction(const FunctionScopeInfo *OldFSI) { 209 if (!Stack.empty() && Stack.back().second == OldFSI) { 210 assert(Stack.back().first.empty()); 211 Stack.pop_back(); 212 } 213 CurrentNonCapturingFunctionScope = nullptr; 214 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 215 if (!isa<CapturingScopeInfo>(FSI)) { 216 CurrentNonCapturingFunctionScope = FSI; 217 break; 218 } 219 } 220 } 221 222 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) { 223 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint); 224 } 225 const std::pair<OMPCriticalDirective *, llvm::APSInt> 226 getCriticalWithHint(const DeclarationNameInfo &Name) const { 227 auto I = Criticals.find(Name.getAsString()); 228 if (I != Criticals.end()) 229 return I->second; 230 return std::make_pair(nullptr, llvm::APSInt()); 231 } 232 /// \brief If 'aligned' declaration for given variable \a D was not seen yet, 233 /// add it and return NULL; otherwise return previous occurrence's expression 234 /// for diagnostics. 235 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE); 236 237 /// \brief Register specified variable as loop control variable. 238 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture); 239 /// \brief Check if the specified variable is a loop control variable for 240 /// current region. 241 /// \return The index of the loop control variable in the list of associated 242 /// for-loops (from outer to inner). 243 LCDeclInfo isLoopControlVariable(ValueDecl *D); 244 /// \brief Check if the specified variable is a loop control variable for 245 /// parent region. 246 /// \return The index of the loop control variable in the list of associated 247 /// for-loops (from outer to inner). 248 LCDeclInfo isParentLoopControlVariable(ValueDecl *D); 249 /// \brief Get the loop control variable for the I-th loop (or nullptr) in 250 /// parent directive. 251 ValueDecl *getParentLoopControlVariable(unsigned I); 252 253 /// \brief Adds explicit data sharing attribute to the specified declaration. 254 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 255 DeclRefExpr *PrivateCopy = nullptr); 256 257 /// Adds additional information for the reduction items with the reduction id 258 /// represented as an operator. 259 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 260 BinaryOperatorKind BOK); 261 /// Adds additional information for the reduction items with the reduction id 262 /// represented as reduction identifier. 263 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 264 const Expr *ReductionRef); 265 /// Returns the location and reduction operation from the innermost parent 266 /// region for the given \p D. 267 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 268 BinaryOperatorKind &BOK, 269 Expr *&TaskgroupDescriptor); 270 /// Returns the location and reduction operation from the innermost parent 271 /// region for the given \p D. 272 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 273 const Expr *&ReductionRef, 274 Expr *&TaskgroupDescriptor); 275 /// Return reduction reference expression for the current taskgroup. 276 Expr *getTaskgroupReductionRef() const { 277 assert(Stack.back().first.back().Directive == OMPD_taskgroup && 278 "taskgroup reference expression requested for non taskgroup " 279 "directive."); 280 return Stack.back().first.back().TaskgroupReductionRef; 281 } 282 /// Checks if the given \p VD declaration is actually a taskgroup reduction 283 /// descriptor variable at the \p Level of OpenMP regions. 284 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const { 285 return Stack.back().first[Level].TaskgroupReductionRef && 286 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef) 287 ->getDecl() == VD; 288 } 289 290 /// \brief Returns data sharing attributes from top of the stack for the 291 /// specified declaration. 292 DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 293 /// \brief Returns data-sharing attributes for the specified declaration. 294 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent); 295 /// \brief Checks if the specified variables has data-sharing attributes which 296 /// match specified \a CPred predicate in any directive which matches \a DPred 297 /// predicate. 298 DSAVarData hasDSA(ValueDecl *D, 299 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 300 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 301 bool FromParent); 302 /// \brief Checks if the specified variables has data-sharing attributes which 303 /// match specified \a CPred predicate in any innermost directive which 304 /// matches \a DPred predicate. 305 DSAVarData 306 hasInnermostDSA(ValueDecl *D, 307 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 308 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 309 bool FromParent); 310 /// \brief Checks if the specified variables has explicit data-sharing 311 /// attributes which match specified \a CPred predicate at the specified 312 /// OpenMP region. 313 bool hasExplicitDSA(ValueDecl *D, 314 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 315 unsigned Level, bool NotLastprivate = false); 316 317 /// \brief Returns true if the directive at level \Level matches in the 318 /// specified \a DPred predicate. 319 bool hasExplicitDirective( 320 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 321 unsigned Level); 322 323 /// \brief Finds a directive which matches specified \a DPred predicate. 324 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind, 325 const DeclarationNameInfo &, 326 SourceLocation)> &DPred, 327 bool FromParent); 328 329 /// \brief Returns currently analyzed directive. 330 OpenMPDirectiveKind getCurrentDirective() const { 331 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive; 332 } 333 /// \brief Returns parent directive. 334 OpenMPDirectiveKind getParentDirective() const { 335 if (isStackEmpty() || Stack.back().first.size() == 1) 336 return OMPD_unknown; 337 return std::next(Stack.back().first.rbegin())->Directive; 338 } 339 340 /// \brief Set default data sharing attribute to none. 341 void setDefaultDSANone(SourceLocation Loc) { 342 assert(!isStackEmpty()); 343 Stack.back().first.back().DefaultAttr = DSA_none; 344 Stack.back().first.back().DefaultAttrLoc = Loc; 345 } 346 /// \brief Set default data sharing attribute to shared. 347 void setDefaultDSAShared(SourceLocation Loc) { 348 assert(!isStackEmpty()); 349 Stack.back().first.back().DefaultAttr = DSA_shared; 350 Stack.back().first.back().DefaultAttrLoc = Loc; 351 } 352 /// Set default data mapping attribute to 'tofrom:scalar'. 353 void setDefaultDMAToFromScalar(SourceLocation Loc) { 354 assert(!isStackEmpty()); 355 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar; 356 Stack.back().first.back().DefaultMapAttrLoc = Loc; 357 } 358 359 DefaultDataSharingAttributes getDefaultDSA() const { 360 return isStackEmpty() ? DSA_unspecified 361 : Stack.back().first.back().DefaultAttr; 362 } 363 SourceLocation getDefaultDSALocation() const { 364 return isStackEmpty() ? SourceLocation() 365 : Stack.back().first.back().DefaultAttrLoc; 366 } 367 DefaultMapAttributes getDefaultDMA() const { 368 return isStackEmpty() ? DMA_unspecified 369 : Stack.back().first.back().DefaultMapAttr; 370 } 371 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const { 372 return Stack.back().first[Level].DefaultMapAttr; 373 } 374 SourceLocation getDefaultDMALocation() const { 375 return isStackEmpty() ? SourceLocation() 376 : Stack.back().first.back().DefaultMapAttrLoc; 377 } 378 379 /// \brief Checks if the specified variable is a threadprivate. 380 bool isThreadPrivate(VarDecl *D) { 381 DSAVarData DVar = getTopDSA(D, false); 382 return isOpenMPThreadPrivate(DVar.CKind); 383 } 384 385 /// \brief Marks current region as ordered (it has an 'ordered' clause). 386 void setOrderedRegion(bool IsOrdered, Expr *Param) { 387 assert(!isStackEmpty()); 388 Stack.back().first.back().OrderedRegion.setInt(IsOrdered); 389 Stack.back().first.back().OrderedRegion.setPointer(Param); 390 } 391 /// \brief Returns true, if parent region is ordered (has associated 392 /// 'ordered' clause), false - otherwise. 393 bool isParentOrderedRegion() const { 394 if (isStackEmpty() || Stack.back().first.size() == 1) 395 return false; 396 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt(); 397 } 398 /// \brief Returns optional parameter for the ordered region. 399 Expr *getParentOrderedRegionParam() const { 400 if (isStackEmpty() || Stack.back().first.size() == 1) 401 return nullptr; 402 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer(); 403 } 404 /// \brief Marks current region as nowait (it has a 'nowait' clause). 405 void setNowaitRegion(bool IsNowait = true) { 406 assert(!isStackEmpty()); 407 Stack.back().first.back().NowaitRegion = IsNowait; 408 } 409 /// \brief Returns true, if parent region is nowait (has associated 410 /// 'nowait' clause), false - otherwise. 411 bool isParentNowaitRegion() const { 412 if (isStackEmpty() || Stack.back().first.size() == 1) 413 return false; 414 return std::next(Stack.back().first.rbegin())->NowaitRegion; 415 } 416 /// \brief Marks parent region as cancel region. 417 void setParentCancelRegion(bool Cancel = true) { 418 if (!isStackEmpty() && Stack.back().first.size() > 1) { 419 auto &StackElemRef = *std::next(Stack.back().first.rbegin()); 420 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel; 421 } 422 } 423 /// \brief Return true if current region has inner cancel construct. 424 bool isCancelRegion() const { 425 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion; 426 } 427 428 /// \brief Set collapse value for the region. 429 void setAssociatedLoops(unsigned Val) { 430 assert(!isStackEmpty()); 431 Stack.back().first.back().AssociatedLoops = Val; 432 } 433 /// \brief Return collapse value for region. 434 unsigned getAssociatedLoops() const { 435 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops; 436 } 437 438 /// \brief Marks current target region as one with closely nested teams 439 /// region. 440 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 441 if (!isStackEmpty() && Stack.back().first.size() > 1) { 442 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc = 443 TeamsRegionLoc; 444 } 445 } 446 /// \brief Returns true, if current region has closely nested teams region. 447 bool hasInnerTeamsRegion() const { 448 return getInnerTeamsRegionLoc().isValid(); 449 } 450 /// \brief Returns location of the nested teams region (if any). 451 SourceLocation getInnerTeamsRegionLoc() const { 452 return isStackEmpty() ? SourceLocation() 453 : Stack.back().first.back().InnerTeamsRegionLoc; 454 } 455 456 Scope *getCurScope() const { 457 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 458 } 459 Scope *getCurScope() { 460 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 461 } 462 SourceLocation getConstructLoc() { 463 return isStackEmpty() ? SourceLocation() 464 : Stack.back().first.back().ConstructLoc; 465 } 466 467 /// Do the check specified in \a Check to all component lists and return true 468 /// if any issue is found. 469 bool checkMappableExprComponentListsForDecl( 470 ValueDecl *VD, bool CurrentRegionOnly, 471 const llvm::function_ref< 472 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 473 OpenMPClauseKind)> &Check) { 474 if (isStackEmpty()) 475 return false; 476 auto SI = Stack.back().first.rbegin(); 477 auto SE = Stack.back().first.rend(); 478 479 if (SI == SE) 480 return false; 481 482 if (CurrentRegionOnly) { 483 SE = std::next(SI); 484 } else { 485 ++SI; 486 } 487 488 for (; SI != SE; ++SI) { 489 auto MI = SI->MappedExprComponents.find(VD); 490 if (MI != SI->MappedExprComponents.end()) 491 for (auto &L : MI->second.Components) 492 if (Check(L, MI->second.Kind)) 493 return true; 494 } 495 return false; 496 } 497 498 /// Do the check specified in \a Check to all component lists at a given level 499 /// and return true if any issue is found. 500 bool checkMappableExprComponentListsForDeclAtLevel( 501 ValueDecl *VD, unsigned Level, 502 const llvm::function_ref< 503 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 504 OpenMPClauseKind)> &Check) { 505 if (isStackEmpty()) 506 return false; 507 508 auto StartI = Stack.back().first.begin(); 509 auto EndI = Stack.back().first.end(); 510 if (std::distance(StartI, EndI) <= (int)Level) 511 return false; 512 std::advance(StartI, Level); 513 514 auto MI = StartI->MappedExprComponents.find(VD); 515 if (MI != StartI->MappedExprComponents.end()) 516 for (auto &L : MI->second.Components) 517 if (Check(L, MI->second.Kind)) 518 return true; 519 return false; 520 } 521 522 /// Create a new mappable expression component list associated with a given 523 /// declaration and initialize it with the provided list of components. 524 void addMappableExpressionComponents( 525 ValueDecl *VD, 526 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 527 OpenMPClauseKind WhereFoundClauseKind) { 528 assert(!isStackEmpty() && 529 "Not expecting to retrieve components from a empty stack!"); 530 auto &MEC = Stack.back().first.back().MappedExprComponents[VD]; 531 // Create new entry and append the new components there. 532 MEC.Components.resize(MEC.Components.size() + 1); 533 MEC.Components.back().append(Components.begin(), Components.end()); 534 MEC.Kind = WhereFoundClauseKind; 535 } 536 537 unsigned getNestingLevel() const { 538 assert(!isStackEmpty()); 539 return Stack.back().first.size() - 1; 540 } 541 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) { 542 assert(!isStackEmpty() && Stack.back().first.size() > 1); 543 auto &StackElem = *std::next(Stack.back().first.rbegin()); 544 assert(isOpenMPWorksharingDirective(StackElem.Directive)); 545 StackElem.DoacrossDepends.insert({C, OpsOffs}); 546 } 547 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 548 getDoacrossDependClauses() const { 549 assert(!isStackEmpty()); 550 auto &StackElem = Stack.back().first.back(); 551 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 552 auto &Ref = StackElem.DoacrossDepends; 553 return llvm::make_range(Ref.begin(), Ref.end()); 554 } 555 return llvm::make_range(StackElem.DoacrossDepends.end(), 556 StackElem.DoacrossDepends.end()); 557 } 558 }; 559 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 560 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || 561 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 562 } 563 } // namespace 564 565 static Expr *getExprAsWritten(Expr *E) { 566 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 567 E = ExprTemp->getSubExpr(); 568 569 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 570 E = MTE->GetTemporaryExpr(); 571 572 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 573 E = Binder->getSubExpr(); 574 575 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 576 E = ICE->getSubExprAsWritten(); 577 return E->IgnoreParens(); 578 } 579 580 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 581 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 582 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 583 D = ME->getMemberDecl(); 584 auto *VD = dyn_cast<VarDecl>(D); 585 auto *FD = dyn_cast<FieldDecl>(D); 586 if (VD != nullptr) { 587 VD = VD->getCanonicalDecl(); 588 D = VD; 589 } else { 590 assert(FD); 591 FD = FD->getCanonicalDecl(); 592 D = FD; 593 } 594 return D; 595 } 596 597 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter, 598 ValueDecl *D) { 599 D = getCanonicalDecl(D); 600 auto *VD = dyn_cast<VarDecl>(D); 601 auto *FD = dyn_cast<FieldDecl>(D); 602 DSAVarData DVar; 603 if (isStackEmpty() || Iter == Stack.back().first.rend()) { 604 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 605 // in a region but not in construct] 606 // File-scope or namespace-scope variables referenced in called routines 607 // in the region are shared unless they appear in a threadprivate 608 // directive. 609 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 610 DVar.CKind = OMPC_shared; 611 612 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 613 // in a region but not in construct] 614 // Variables with static storage duration that are declared in called 615 // routines in the region are shared. 616 if (VD && VD->hasGlobalStorage()) 617 DVar.CKind = OMPC_shared; 618 619 // Non-static data members are shared by default. 620 if (FD) 621 DVar.CKind = OMPC_shared; 622 623 return DVar; 624 } 625 626 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 627 // in a Construct, C/C++, predetermined, p.1] 628 // Variables with automatic storage duration that are declared in a scope 629 // inside the construct are private. 630 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 631 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 632 DVar.CKind = OMPC_private; 633 return DVar; 634 } 635 636 DVar.DKind = Iter->Directive; 637 // Explicitly specified attributes and local variables with predetermined 638 // attributes. 639 if (Iter->SharingMap.count(D)) { 640 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer(); 641 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy; 642 DVar.CKind = Iter->SharingMap[D].Attributes; 643 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 644 return DVar; 645 } 646 647 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 648 // in a Construct, C/C++, implicitly determined, p.1] 649 // In a parallel or task construct, the data-sharing attributes of these 650 // variables are determined by the default clause, if present. 651 switch (Iter->DefaultAttr) { 652 case DSA_shared: 653 DVar.CKind = OMPC_shared; 654 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 655 return DVar; 656 case DSA_none: 657 return DVar; 658 case DSA_unspecified: 659 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 660 // in a Construct, implicitly determined, p.2] 661 // In a parallel construct, if no default clause is present, these 662 // variables are shared. 663 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 664 if (isOpenMPParallelDirective(DVar.DKind) || 665 isOpenMPTeamsDirective(DVar.DKind)) { 666 DVar.CKind = OMPC_shared; 667 return DVar; 668 } 669 670 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 671 // in a Construct, implicitly determined, p.4] 672 // In a task construct, if no default clause is present, a variable that in 673 // the enclosing context is determined to be shared by all implicit tasks 674 // bound to the current team is shared. 675 if (isOpenMPTaskingDirective(DVar.DKind)) { 676 DSAVarData DVarTemp; 677 auto I = Iter, E = Stack.back().first.rend(); 678 do { 679 ++I; 680 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 681 // Referenced in a Construct, implicitly determined, p.6] 682 // In a task construct, if no default clause is present, a variable 683 // whose data-sharing attribute is not determined by the rules above is 684 // firstprivate. 685 DVarTemp = getDSA(I, D); 686 if (DVarTemp.CKind != OMPC_shared) { 687 DVar.RefExpr = nullptr; 688 DVar.CKind = OMPC_firstprivate; 689 return DVar; 690 } 691 } while (I != E && !isParallelOrTaskRegion(I->Directive)); 692 DVar.CKind = 693 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 694 return DVar; 695 } 696 } 697 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 698 // in a Construct, implicitly determined, p.3] 699 // For constructs other than task, if no default clause is present, these 700 // variables inherit their data-sharing attributes from the enclosing 701 // context. 702 return getDSA(++Iter, D); 703 } 704 705 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) { 706 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 707 D = getCanonicalDecl(D); 708 auto &StackElem = Stack.back().first.back(); 709 auto It = StackElem.AlignedMap.find(D); 710 if (It == StackElem.AlignedMap.end()) { 711 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 712 StackElem.AlignedMap[D] = NewDE; 713 return nullptr; 714 } else { 715 assert(It->second && "Unexpected nullptr expr in the aligned map"); 716 return It->second; 717 } 718 return nullptr; 719 } 720 721 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) { 722 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 723 D = getCanonicalDecl(D); 724 auto &StackElem = Stack.back().first.back(); 725 StackElem.LCVMap.insert( 726 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)}); 727 } 728 729 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) { 730 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 731 D = getCanonicalDecl(D); 732 auto &StackElem = Stack.back().first.back(); 733 auto It = StackElem.LCVMap.find(D); 734 if (It != StackElem.LCVMap.end()) 735 return It->second; 736 return {0, nullptr}; 737 } 738 739 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) { 740 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 741 "Data-sharing attributes stack is empty"); 742 D = getCanonicalDecl(D); 743 auto &StackElem = *std::next(Stack.back().first.rbegin()); 744 auto It = StackElem.LCVMap.find(D); 745 if (It != StackElem.LCVMap.end()) 746 return It->second; 747 return {0, nullptr}; 748 } 749 750 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) { 751 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 752 "Data-sharing attributes stack is empty"); 753 auto &StackElem = *std::next(Stack.back().first.rbegin()); 754 if (StackElem.LCVMap.size() < I) 755 return nullptr; 756 for (auto &Pair : StackElem.LCVMap) 757 if (Pair.second.first == I) 758 return Pair.first; 759 return nullptr; 760 } 761 762 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 763 DeclRefExpr *PrivateCopy) { 764 D = getCanonicalDecl(D); 765 if (A == OMPC_threadprivate) { 766 auto &Data = Threadprivates[D]; 767 Data.Attributes = A; 768 Data.RefExpr.setPointer(E); 769 Data.PrivateCopy = nullptr; 770 } else { 771 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 772 auto &Data = Stack.back().first.back().SharingMap[D]; 773 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 774 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 775 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 776 (isLoopControlVariable(D).first && A == OMPC_private)); 777 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 778 Data.RefExpr.setInt(/*IntVal=*/true); 779 return; 780 } 781 const bool IsLastprivate = 782 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 783 Data.Attributes = A; 784 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 785 Data.PrivateCopy = PrivateCopy; 786 if (PrivateCopy) { 787 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()]; 788 Data.Attributes = A; 789 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 790 Data.PrivateCopy = nullptr; 791 } 792 } 793 } 794 795 /// \brief Build a variable declaration for OpenMP loop iteration variable. 796 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 797 StringRef Name, const AttrVec *Attrs = nullptr) { 798 DeclContext *DC = SemaRef.CurContext; 799 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 800 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 801 VarDecl *Decl = 802 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 803 if (Attrs) { 804 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 805 I != E; ++I) 806 Decl->addAttr(*I); 807 } 808 Decl->setImplicit(); 809 return Decl; 810 } 811 812 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 813 SourceLocation Loc, 814 bool RefersToCapture = false) { 815 D->setReferenced(); 816 D->markUsed(S.Context); 817 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 818 SourceLocation(), D, RefersToCapture, Loc, Ty, 819 VK_LValue); 820 } 821 822 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 823 BinaryOperatorKind BOK) { 824 D = getCanonicalDecl(D); 825 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 826 assert( 827 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 828 "Additional reduction info may be specified only for reduction items."); 829 auto &ReductionData = Stack.back().first.back().ReductionMap[D]; 830 assert(ReductionData.ReductionRange.isInvalid() && 831 Stack.back().first.back().Directive == OMPD_taskgroup && 832 "Additional reduction info may be specified only once for reduction " 833 "items."); 834 ReductionData.set(BOK, SR); 835 Expr *&TaskgroupReductionRef = 836 Stack.back().first.back().TaskgroupReductionRef; 837 if (!TaskgroupReductionRef) { 838 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), 839 SemaRef.Context.VoidPtrTy, ".task_red."); 840 TaskgroupReductionRef = 841 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 842 } 843 } 844 845 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 846 const Expr *ReductionRef) { 847 D = getCanonicalDecl(D); 848 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 849 assert( 850 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 851 "Additional reduction info may be specified only for reduction items."); 852 auto &ReductionData = Stack.back().first.back().ReductionMap[D]; 853 assert(ReductionData.ReductionRange.isInvalid() && 854 Stack.back().first.back().Directive == OMPD_taskgroup && 855 "Additional reduction info may be specified only once for reduction " 856 "items."); 857 ReductionData.set(ReductionRef, SR); 858 Expr *&TaskgroupReductionRef = 859 Stack.back().first.back().TaskgroupReductionRef; 860 if (!TaskgroupReductionRef) { 861 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy, 862 ".task_red."); 863 TaskgroupReductionRef = 864 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 865 } 866 } 867 868 DSAStackTy::DSAVarData 869 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 870 BinaryOperatorKind &BOK, 871 Expr *&TaskgroupDescriptor) { 872 D = getCanonicalDecl(D); 873 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 874 if (Stack.back().first.empty()) 875 return DSAVarData(); 876 for (auto I = std::next(Stack.back().first.rbegin(), 1), 877 E = Stack.back().first.rend(); 878 I != E; std::advance(I, 1)) { 879 auto &Data = I->SharingMap[D]; 880 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 881 continue; 882 auto &ReductionData = I->ReductionMap[D]; 883 if (!ReductionData.ReductionOp || 884 ReductionData.ReductionOp.is<const Expr *>()) 885 return DSAVarData(); 886 SR = ReductionData.ReductionRange; 887 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 888 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 889 "expression for the descriptor is not " 890 "set."); 891 TaskgroupDescriptor = I->TaskgroupReductionRef; 892 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 893 Data.PrivateCopy, I->DefaultAttrLoc); 894 } 895 return DSAVarData(); 896 } 897 898 DSAStackTy::DSAVarData 899 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 900 const Expr *&ReductionRef, 901 Expr *&TaskgroupDescriptor) { 902 D = getCanonicalDecl(D); 903 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 904 if (Stack.back().first.empty()) 905 return DSAVarData(); 906 for (auto I = std::next(Stack.back().first.rbegin(), 1), 907 E = Stack.back().first.rend(); 908 I != E; std::advance(I, 1)) { 909 auto &Data = I->SharingMap[D]; 910 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 911 continue; 912 auto &ReductionData = I->ReductionMap[D]; 913 if (!ReductionData.ReductionOp || 914 !ReductionData.ReductionOp.is<const Expr *>()) 915 return DSAVarData(); 916 SR = ReductionData.ReductionRange; 917 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 918 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 919 "expression for the descriptor is not " 920 "set."); 921 TaskgroupDescriptor = I->TaskgroupReductionRef; 922 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 923 Data.PrivateCopy, I->DefaultAttrLoc); 924 } 925 return DSAVarData(); 926 } 927 928 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 929 D = D->getCanonicalDecl(); 930 if (!isStackEmpty() && Stack.back().first.size() > 1) { 931 reverse_iterator I = Iter, E = Stack.back().first.rend(); 932 Scope *TopScope = nullptr; 933 while (I != E && !isParallelOrTaskRegion(I->Directive)) 934 ++I; 935 if (I == E) 936 return false; 937 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 938 Scope *CurScope = getCurScope(); 939 while (CurScope != TopScope && !CurScope->isDeclScope(D)) 940 CurScope = CurScope->getParent(); 941 return CurScope != TopScope; 942 } 943 return false; 944 } 945 946 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) { 947 D = getCanonicalDecl(D); 948 DSAVarData DVar; 949 950 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 951 // in a Construct, C/C++, predetermined, p.1] 952 // Variables appearing in threadprivate directives are threadprivate. 953 auto *VD = dyn_cast<VarDecl>(D); 954 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 955 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 956 SemaRef.getLangOpts().OpenMPUseTLS && 957 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 958 (VD && VD->getStorageClass() == SC_Register && 959 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 960 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 961 D->getLocation()), 962 OMPC_threadprivate); 963 } 964 auto TI = Threadprivates.find(D); 965 if (TI != Threadprivates.end()) { 966 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 967 DVar.CKind = OMPC_threadprivate; 968 return DVar; 969 } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 970 DVar.RefExpr = buildDeclRefExpr( 971 SemaRef, VD, D->getType().getNonReferenceType(), 972 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 973 DVar.CKind = OMPC_threadprivate; 974 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 975 } 976 977 if (isStackEmpty()) 978 // Not in OpenMP execution region and top scope was already checked. 979 return DVar; 980 981 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 982 // in a Construct, C/C++, predetermined, p.4] 983 // Static data members are shared. 984 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 985 // in a Construct, C/C++, predetermined, p.7] 986 // Variables with static storage duration that are declared in a scope 987 // inside the construct are shared. 988 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; 989 if (VD && VD->isStaticDataMember()) { 990 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 991 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 992 return DVar; 993 994 DVar.CKind = OMPC_shared; 995 return DVar; 996 } 997 998 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 999 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 1000 Type = SemaRef.getASTContext().getBaseElementType(Type); 1001 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1002 // in a Construct, C/C++, predetermined, p.6] 1003 // Variables with const qualified type having no mutable member are 1004 // shared. 1005 CXXRecordDecl *RD = 1006 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 1007 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1008 if (auto *CTD = CTSD->getSpecializedTemplate()) 1009 RD = CTD->getTemplatedDecl(); 1010 if (IsConstant && 1011 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && 1012 RD->hasMutableFields())) { 1013 // Variables with const-qualified type having no mutable member may be 1014 // listed in a firstprivate clause, even if they are static data members. 1015 DSAVarData DVarTemp = hasDSA( 1016 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, 1017 MatchesAlways, FromParent); 1018 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 1019 return DVar; 1020 1021 DVar.CKind = OMPC_shared; 1022 return DVar; 1023 } 1024 1025 // Explicitly specified attributes and local variables with predetermined 1026 // attributes. 1027 auto I = Stack.back().first.rbegin(); 1028 auto EndI = Stack.back().first.rend(); 1029 if (FromParent && I != EndI) 1030 std::advance(I, 1); 1031 if (I->SharingMap.count(D)) { 1032 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); 1033 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; 1034 DVar.CKind = I->SharingMap[D].Attributes; 1035 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1036 DVar.DKind = I->Directive; 1037 } 1038 1039 return DVar; 1040 } 1041 1042 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1043 bool FromParent) { 1044 if (isStackEmpty()) { 1045 StackTy::reverse_iterator I; 1046 return getDSA(I, D); 1047 } 1048 D = getCanonicalDecl(D); 1049 auto StartI = Stack.back().first.rbegin(); 1050 auto EndI = Stack.back().first.rend(); 1051 if (FromParent && StartI != EndI) 1052 std::advance(StartI, 1); 1053 return getDSA(StartI, D); 1054 } 1055 1056 DSAStackTy::DSAVarData 1057 DSAStackTy::hasDSA(ValueDecl *D, 1058 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1059 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1060 bool FromParent) { 1061 if (isStackEmpty()) 1062 return {}; 1063 D = getCanonicalDecl(D); 1064 auto I = Stack.back().first.rbegin(); 1065 auto EndI = Stack.back().first.rend(); 1066 if (FromParent && I != EndI) 1067 std::advance(I, 1); 1068 for (; I != EndI; std::advance(I, 1)) { 1069 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 1070 continue; 1071 auto NewI = I; 1072 DSAVarData DVar = getDSA(NewI, D); 1073 if (I == NewI && CPred(DVar.CKind)) 1074 return DVar; 1075 } 1076 return {}; 1077 } 1078 1079 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1080 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1081 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1082 bool FromParent) { 1083 if (isStackEmpty()) 1084 return {}; 1085 D = getCanonicalDecl(D); 1086 auto StartI = Stack.back().first.rbegin(); 1087 auto EndI = Stack.back().first.rend(); 1088 if (FromParent && StartI != EndI) 1089 std::advance(StartI, 1); 1090 if (StartI == EndI || !DPred(StartI->Directive)) 1091 return {}; 1092 auto NewI = StartI; 1093 DSAVarData DVar = getDSA(NewI, D); 1094 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); 1095 } 1096 1097 bool DSAStackTy::hasExplicitDSA( 1098 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1099 unsigned Level, bool NotLastprivate) { 1100 if (CPred(ClauseKindMode)) 1101 return true; 1102 if (isStackEmpty()) 1103 return false; 1104 D = getCanonicalDecl(D); 1105 auto StartI = Stack.back().first.begin(); 1106 auto EndI = Stack.back().first.end(); 1107 if (std::distance(StartI, EndI) <= (int)Level) 1108 return false; 1109 std::advance(StartI, Level); 1110 return (StartI->SharingMap.count(D) > 0) && 1111 StartI->SharingMap[D].RefExpr.getPointer() && 1112 CPred(StartI->SharingMap[D].Attributes) && 1113 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt()); 1114 } 1115 1116 bool DSAStackTy::hasExplicitDirective( 1117 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1118 unsigned Level) { 1119 if (isStackEmpty()) 1120 return false; 1121 auto StartI = Stack.back().first.begin(); 1122 auto EndI = Stack.back().first.end(); 1123 if (std::distance(StartI, EndI) <= (int)Level) 1124 return false; 1125 std::advance(StartI, Level); 1126 return DPred(StartI->Directive); 1127 } 1128 1129 bool DSAStackTy::hasDirective( 1130 const llvm::function_ref<bool(OpenMPDirectiveKind, 1131 const DeclarationNameInfo &, SourceLocation)> 1132 &DPred, 1133 bool FromParent) { 1134 // We look only in the enclosing region. 1135 if (isStackEmpty()) 1136 return false; 1137 auto StartI = std::next(Stack.back().first.rbegin()); 1138 auto EndI = Stack.back().first.rend(); 1139 if (FromParent && StartI != EndI) 1140 StartI = std::next(StartI); 1141 for (auto I = StartI, EE = EndI; I != EE; ++I) { 1142 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1143 return true; 1144 } 1145 return false; 1146 } 1147 1148 void Sema::InitDataSharingAttributesStack() { 1149 VarDataSharingAttributesStack = new DSAStackTy(*this); 1150 } 1151 1152 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1153 1154 void Sema::pushOpenMPFunctionRegion() { 1155 DSAStack->pushFunction(); 1156 } 1157 1158 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1159 DSAStack->popFunction(OldFSI); 1160 } 1161 1162 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { 1163 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1164 1165 auto &Ctx = getASTContext(); 1166 bool IsByRef = true; 1167 1168 // Find the directive that is associated with the provided scope. 1169 D = cast<ValueDecl>(D->getCanonicalDecl()); 1170 auto Ty = D->getType(); 1171 1172 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1173 // This table summarizes how a given variable should be passed to the device 1174 // given its type and the clauses where it appears. This table is based on 1175 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1176 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1177 // 1178 // ========================================================================= 1179 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1180 // | |(tofrom:scalar)| | pvt | | | | 1181 // ========================================================================= 1182 // | scl | | | | - | | bycopy| 1183 // | scl | | - | x | - | - | bycopy| 1184 // | scl | | x | - | - | - | null | 1185 // | scl | x | | | - | | byref | 1186 // | scl | x | - | x | - | - | bycopy| 1187 // | scl | x | x | - | - | - | null | 1188 // | scl | | - | - | - | x | byref | 1189 // | scl | x | - | - | - | x | byref | 1190 // 1191 // | agg | n.a. | | | - | | byref | 1192 // | agg | n.a. | - | x | - | - | byref | 1193 // | agg | n.a. | x | - | - | - | null | 1194 // | agg | n.a. | - | - | - | x | byref | 1195 // | agg | n.a. | - | - | - | x[] | byref | 1196 // 1197 // | ptr | n.a. | | | - | | bycopy| 1198 // | ptr | n.a. | - | x | - | - | bycopy| 1199 // | ptr | n.a. | x | - | - | - | null | 1200 // | ptr | n.a. | - | - | - | x | byref | 1201 // | ptr | n.a. | - | - | - | x[] | bycopy| 1202 // | ptr | n.a. | - | - | x | | bycopy| 1203 // | ptr | n.a. | - | - | x | x | bycopy| 1204 // | ptr | n.a. | - | - | x | x[] | bycopy| 1205 // ========================================================================= 1206 // Legend: 1207 // scl - scalar 1208 // ptr - pointer 1209 // agg - aggregate 1210 // x - applies 1211 // - - invalid in this combination 1212 // [] - mapped with an array section 1213 // byref - should be mapped by reference 1214 // byval - should be mapped by value 1215 // null - initialize a local variable to null on the device 1216 // 1217 // Observations: 1218 // - All scalar declarations that show up in a map clause have to be passed 1219 // by reference, because they may have been mapped in the enclosing data 1220 // environment. 1221 // - If the scalar value does not fit the size of uintptr, it has to be 1222 // passed by reference, regardless the result in the table above. 1223 // - For pointers mapped by value that have either an implicit map or an 1224 // array section, the runtime library may pass the NULL value to the 1225 // device instead of the value passed to it by the compiler. 1226 1227 if (Ty->isReferenceType()) 1228 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1229 1230 // Locate map clauses and see if the variable being captured is referred to 1231 // in any of those clauses. Here we only care about variables, not fields, 1232 // because fields are part of aggregates. 1233 bool IsVariableUsedInMapClause = false; 1234 bool IsVariableAssociatedWithSection = false; 1235 1236 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1237 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 1238 MapExprComponents, 1239 OpenMPClauseKind WhereFoundClauseKind) { 1240 // Only the map clause information influences how a variable is 1241 // captured. E.g. is_device_ptr does not require changing the default 1242 // behavior. 1243 if (WhereFoundClauseKind != OMPC_map) 1244 return false; 1245 1246 auto EI = MapExprComponents.rbegin(); 1247 auto EE = MapExprComponents.rend(); 1248 1249 assert(EI != EE && "Invalid map expression!"); 1250 1251 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1252 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1253 1254 ++EI; 1255 if (EI == EE) 1256 return false; 1257 1258 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1259 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1260 isa<MemberExpr>(EI->getAssociatedExpression())) { 1261 IsVariableAssociatedWithSection = true; 1262 // There is nothing more we need to know about this variable. 1263 return true; 1264 } 1265 1266 // Keep looking for more map info. 1267 return false; 1268 }); 1269 1270 if (IsVariableUsedInMapClause) { 1271 // If variable is identified in a map clause it is always captured by 1272 // reference except if it is a pointer that is dereferenced somehow. 1273 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1274 } else { 1275 // By default, all the data that has a scalar type is mapped by copy. 1276 IsByRef = !Ty->isScalarType() || 1277 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar; 1278 } 1279 } 1280 1281 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1282 IsByRef = !DSAStack->hasExplicitDSA( 1283 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1284 Level, /*NotLastprivate=*/true); 1285 } 1286 1287 // When passing data by copy, we need to make sure it fits the uintptr size 1288 // and alignment, because the runtime library only deals with uintptr types. 1289 // If it does not fit the uintptr size, we need to pass the data by reference 1290 // instead. 1291 if (!IsByRef && 1292 (Ctx.getTypeSizeInChars(Ty) > 1293 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1294 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1295 IsByRef = true; 1296 } 1297 1298 return IsByRef; 1299 } 1300 1301 unsigned Sema::getOpenMPNestingLevel() const { 1302 assert(getLangOpts().OpenMP); 1303 return DSAStack->getNestingLevel(); 1304 } 1305 1306 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { 1307 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1308 D = getCanonicalDecl(D); 1309 1310 // If we are attempting to capture a global variable in a directive with 1311 // 'target' we return true so that this global is also mapped to the device. 1312 // 1313 // FIXME: If the declaration is enclosed in a 'declare target' directive, 1314 // then it should not be captured. Therefore, an extra check has to be 1315 // inserted here once support for 'declare target' is added. 1316 // 1317 auto *VD = dyn_cast<VarDecl>(D); 1318 if (VD && !VD->hasLocalStorage()) { 1319 if (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 1320 !DSAStack->isClauseParsingMode()) 1321 return VD; 1322 if (DSAStack->hasDirective( 1323 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1324 SourceLocation) -> bool { 1325 return isOpenMPTargetExecutionDirective(K); 1326 }, 1327 false)) 1328 return VD; 1329 } 1330 1331 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1332 (!DSAStack->isClauseParsingMode() || 1333 DSAStack->getParentDirective() != OMPD_unknown)) { 1334 auto &&Info = DSAStack->isLoopControlVariable(D); 1335 if (Info.first || 1336 (VD && VD->hasLocalStorage() && 1337 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 1338 (VD && DSAStack->isForceVarCapturing())) 1339 return VD ? VD : Info.second; 1340 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1341 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1342 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1343 DVarPrivate = DSAStack->hasDSA( 1344 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 1345 DSAStack->isClauseParsingMode()); 1346 if (DVarPrivate.CKind != OMPC_unknown) 1347 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1348 } 1349 return nullptr; 1350 } 1351 1352 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { 1353 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1354 return DSAStack->hasExplicitDSA( 1355 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, 1356 Level) || 1357 // Consider taskgroup reduction descriptor variable a private to avoid 1358 // possible capture in the region. 1359 (DSAStack->hasExplicitDirective( 1360 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; }, 1361 Level) && 1362 DSAStack->isTaskgroupReductionRef(D, Level)); 1363 } 1364 1365 void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) { 1366 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1367 D = getCanonicalDecl(D); 1368 OpenMPClauseKind OMPC = OMPC_unknown; 1369 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 1370 const unsigned NewLevel = I - 1; 1371 if (DSAStack->hasExplicitDSA(D, 1372 [&OMPC](const OpenMPClauseKind K) { 1373 if (isOpenMPPrivate(K)) { 1374 OMPC = K; 1375 return true; 1376 } 1377 return false; 1378 }, 1379 NewLevel)) 1380 break; 1381 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1382 D, NewLevel, 1383 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 1384 OpenMPClauseKind) { return true; })) { 1385 OMPC = OMPC_map; 1386 break; 1387 } 1388 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1389 NewLevel)) { 1390 OMPC = OMPC_firstprivate; 1391 break; 1392 } 1393 } 1394 if (OMPC != OMPC_unknown) 1395 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC)); 1396 } 1397 1398 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { 1399 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1400 // Return true if the current level is no longer enclosed in a target region. 1401 1402 auto *VD = dyn_cast<VarDecl>(D); 1403 return VD && !VD->hasLocalStorage() && 1404 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1405 Level); 1406 } 1407 1408 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1409 1410 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1411 const DeclarationNameInfo &DirName, 1412 Scope *CurScope, SourceLocation Loc) { 1413 DSAStack->push(DKind, DirName, CurScope, Loc); 1414 PushExpressionEvaluationContext( 1415 ExpressionEvaluationContext::PotentiallyEvaluated); 1416 } 1417 1418 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1419 DSAStack->setClauseParsingMode(K); 1420 } 1421 1422 void Sema::EndOpenMPClause() { 1423 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1424 } 1425 1426 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1427 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1428 // A variable of class type (or array thereof) that appears in a lastprivate 1429 // clause requires an accessible, unambiguous default constructor for the 1430 // class type, unless the list item is also specified in a firstprivate 1431 // clause. 1432 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1433 for (auto *C : D->clauses()) { 1434 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1435 SmallVector<Expr *, 8> PrivateCopies; 1436 for (auto *DE : Clause->varlists()) { 1437 if (DE->isValueDependent() || DE->isTypeDependent()) { 1438 PrivateCopies.push_back(nullptr); 1439 continue; 1440 } 1441 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1442 VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1443 QualType Type = VD->getType().getNonReferenceType(); 1444 auto DVar = DSAStack->getTopDSA(VD, false); 1445 if (DVar.CKind == OMPC_lastprivate) { 1446 // Generate helper private variable and initialize it with the 1447 // default value. The address of the original variable is replaced 1448 // by the address of the new private variable in CodeGen. This new 1449 // variable is not added to IdResolver, so the code in the OpenMP 1450 // region uses original variable for proper diagnostics. 1451 auto *VDPrivate = buildVarDecl( 1452 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1453 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); 1454 ActOnUninitializedDecl(VDPrivate); 1455 if (VDPrivate->isInvalidDecl()) 1456 continue; 1457 PrivateCopies.push_back(buildDeclRefExpr( 1458 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1459 } else { 1460 // The variable is also a firstprivate, so initialization sequence 1461 // for private copy is generated already. 1462 PrivateCopies.push_back(nullptr); 1463 } 1464 } 1465 // Set initializers to private copies if no errors were found. 1466 if (PrivateCopies.size() == Clause->varlist_size()) 1467 Clause->setPrivateCopies(PrivateCopies); 1468 } 1469 } 1470 } 1471 1472 DSAStack->pop(); 1473 DiscardCleanupsInEvaluationContext(); 1474 PopExpressionEvaluationContext(); 1475 } 1476 1477 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1478 Expr *NumIterations, Sema &SemaRef, 1479 Scope *S, DSAStackTy *Stack); 1480 1481 namespace { 1482 1483 class VarDeclFilterCCC : public CorrectionCandidateCallback { 1484 private: 1485 Sema &SemaRef; 1486 1487 public: 1488 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1489 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1490 NamedDecl *ND = Candidate.getCorrectionDecl(); 1491 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1492 return VD->hasGlobalStorage() && 1493 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1494 SemaRef.getCurScope()); 1495 } 1496 return false; 1497 } 1498 }; 1499 1500 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { 1501 private: 1502 Sema &SemaRef; 1503 1504 public: 1505 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1506 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1507 NamedDecl *ND = Candidate.getCorrectionDecl(); 1508 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 1509 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1510 SemaRef.getCurScope()); 1511 } 1512 return false; 1513 } 1514 }; 1515 1516 } // namespace 1517 1518 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1519 CXXScopeSpec &ScopeSpec, 1520 const DeclarationNameInfo &Id) { 1521 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1522 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1523 1524 if (Lookup.isAmbiguous()) 1525 return ExprError(); 1526 1527 VarDecl *VD; 1528 if (!Lookup.isSingleResult()) { 1529 if (TypoCorrection Corrected = CorrectTypo( 1530 Id, LookupOrdinaryName, CurScope, nullptr, 1531 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1532 diagnoseTypo(Corrected, 1533 PDiag(Lookup.empty() 1534 ? diag::err_undeclared_var_use_suggest 1535 : diag::err_omp_expected_var_arg_suggest) 1536 << Id.getName()); 1537 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1538 } else { 1539 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1540 : diag::err_omp_expected_var_arg) 1541 << Id.getName(); 1542 return ExprError(); 1543 } 1544 } else { 1545 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1546 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1547 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1548 return ExprError(); 1549 } 1550 } 1551 Lookup.suppressDiagnostics(); 1552 1553 // OpenMP [2.9.2, Syntax, C/C++] 1554 // Variables must be file-scope, namespace-scope, or static block-scope. 1555 if (!VD->hasGlobalStorage()) { 1556 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1557 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1558 bool IsDecl = 1559 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1560 Diag(VD->getLocation(), 1561 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1562 << VD; 1563 return ExprError(); 1564 } 1565 1566 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1567 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 1568 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1569 // A threadprivate directive for file-scope variables must appear outside 1570 // any definition or declaration. 1571 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1572 !getCurLexicalContext()->isTranslationUnit()) { 1573 Diag(Id.getLoc(), diag::err_omp_var_scope) 1574 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1575 bool IsDecl = 1576 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1577 Diag(VD->getLocation(), 1578 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1579 << VD; 1580 return ExprError(); 1581 } 1582 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1583 // A threadprivate directive for static class member variables must appear 1584 // in the class definition, in the same scope in which the member 1585 // variables are declared. 1586 if (CanonicalVD->isStaticDataMember() && 1587 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1588 Diag(Id.getLoc(), diag::err_omp_var_scope) 1589 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1590 bool IsDecl = 1591 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1592 Diag(VD->getLocation(), 1593 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1594 << VD; 1595 return ExprError(); 1596 } 1597 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1598 // A threadprivate directive for namespace-scope variables must appear 1599 // outside any definition or declaration other than the namespace 1600 // definition itself. 1601 if (CanonicalVD->getDeclContext()->isNamespace() && 1602 (!getCurLexicalContext()->isFileContext() || 1603 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1604 Diag(Id.getLoc(), diag::err_omp_var_scope) 1605 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1606 bool IsDecl = 1607 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1608 Diag(VD->getLocation(), 1609 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1610 << VD; 1611 return ExprError(); 1612 } 1613 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1614 // A threadprivate directive for static block-scope variables must appear 1615 // in the scope of the variable and not in a nested scope. 1616 if (CanonicalVD->isStaticLocal() && CurScope && 1617 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1618 Diag(Id.getLoc(), diag::err_omp_var_scope) 1619 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1620 bool IsDecl = 1621 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1622 Diag(VD->getLocation(), 1623 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1624 << VD; 1625 return ExprError(); 1626 } 1627 1628 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1629 // A threadprivate directive must lexically precede all references to any 1630 // of the variables in its list. 1631 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1632 Diag(Id.getLoc(), diag::err_omp_var_used) 1633 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1634 return ExprError(); 1635 } 1636 1637 QualType ExprType = VD->getType().getNonReferenceType(); 1638 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1639 SourceLocation(), VD, 1640 /*RefersToEnclosingVariableOrCapture=*/false, 1641 Id.getLoc(), ExprType, VK_LValue); 1642 } 1643 1644 Sema::DeclGroupPtrTy 1645 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1646 ArrayRef<Expr *> VarList) { 1647 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1648 CurContext->addDecl(D); 1649 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1650 } 1651 return nullptr; 1652 } 1653 1654 namespace { 1655 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1656 Sema &SemaRef; 1657 1658 public: 1659 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1660 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1661 if (VD->hasLocalStorage()) { 1662 SemaRef.Diag(E->getLocStart(), 1663 diag::err_omp_local_var_in_threadprivate_init) 1664 << E->getSourceRange(); 1665 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1666 << VD << VD->getSourceRange(); 1667 return true; 1668 } 1669 } 1670 return false; 1671 } 1672 bool VisitStmt(const Stmt *S) { 1673 for (auto Child : S->children()) { 1674 if (Child && Visit(Child)) 1675 return true; 1676 } 1677 return false; 1678 } 1679 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1680 }; 1681 } // namespace 1682 1683 OMPThreadPrivateDecl * 1684 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1685 SmallVector<Expr *, 8> Vars; 1686 for (auto &RefExpr : VarList) { 1687 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 1688 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 1689 SourceLocation ILoc = DE->getExprLoc(); 1690 1691 // Mark variable as used. 1692 VD->setReferenced(); 1693 VD->markUsed(Context); 1694 1695 QualType QType = VD->getType(); 1696 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1697 // It will be analyzed later. 1698 Vars.push_back(DE); 1699 continue; 1700 } 1701 1702 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1703 // A threadprivate variable must not have an incomplete type. 1704 if (RequireCompleteType(ILoc, VD->getType(), 1705 diag::err_omp_threadprivate_incomplete_type)) { 1706 continue; 1707 } 1708 1709 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1710 // A threadprivate variable must not have a reference type. 1711 if (VD->getType()->isReferenceType()) { 1712 Diag(ILoc, diag::err_omp_ref_type_arg) 1713 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1714 bool IsDecl = 1715 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1716 Diag(VD->getLocation(), 1717 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1718 << VD; 1719 continue; 1720 } 1721 1722 // Check if this is a TLS variable. If TLS is not being supported, produce 1723 // the corresponding diagnostic. 1724 if ((VD->getTLSKind() != VarDecl::TLS_None && 1725 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1726 getLangOpts().OpenMPUseTLS && 1727 getASTContext().getTargetInfo().isTLSSupported())) || 1728 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1729 !VD->isLocalVarDecl())) { 1730 Diag(ILoc, diag::err_omp_var_thread_local) 1731 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1732 bool IsDecl = 1733 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1734 Diag(VD->getLocation(), 1735 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1736 << VD; 1737 continue; 1738 } 1739 1740 // Check if initial value of threadprivate variable reference variable with 1741 // local storage (it is not supported by runtime). 1742 if (auto Init = VD->getAnyInitializer()) { 1743 LocalVarRefChecker Checker(*this); 1744 if (Checker.Visit(Init)) 1745 continue; 1746 } 1747 1748 Vars.push_back(RefExpr); 1749 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1750 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1751 Context, SourceRange(Loc, Loc))); 1752 if (auto *ML = Context.getASTMutationListener()) 1753 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1754 } 1755 OMPThreadPrivateDecl *D = nullptr; 1756 if (!Vars.empty()) { 1757 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1758 Vars); 1759 D->setAccess(AS_public); 1760 } 1761 return D; 1762 } 1763 1764 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 1765 const ValueDecl *D, DSAStackTy::DSAVarData DVar, 1766 bool IsLoopIterVar = false) { 1767 if (DVar.RefExpr) { 1768 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1769 << getOpenMPClauseName(DVar.CKind); 1770 return; 1771 } 1772 enum { 1773 PDSA_StaticMemberShared, 1774 PDSA_StaticLocalVarShared, 1775 PDSA_LoopIterVarPrivate, 1776 PDSA_LoopIterVarLinear, 1777 PDSA_LoopIterVarLastprivate, 1778 PDSA_ConstVarShared, 1779 PDSA_GlobalVarShared, 1780 PDSA_TaskVarFirstprivate, 1781 PDSA_LocalVarPrivate, 1782 PDSA_Implicit 1783 } Reason = PDSA_Implicit; 1784 bool ReportHint = false; 1785 auto ReportLoc = D->getLocation(); 1786 auto *VD = dyn_cast<VarDecl>(D); 1787 if (IsLoopIterVar) { 1788 if (DVar.CKind == OMPC_private) 1789 Reason = PDSA_LoopIterVarPrivate; 1790 else if (DVar.CKind == OMPC_lastprivate) 1791 Reason = PDSA_LoopIterVarLastprivate; 1792 else 1793 Reason = PDSA_LoopIterVarLinear; 1794 } else if (isOpenMPTaskingDirective(DVar.DKind) && 1795 DVar.CKind == OMPC_firstprivate) { 1796 Reason = PDSA_TaskVarFirstprivate; 1797 ReportLoc = DVar.ImplicitDSALoc; 1798 } else if (VD && VD->isStaticLocal()) 1799 Reason = PDSA_StaticLocalVarShared; 1800 else if (VD && VD->isStaticDataMember()) 1801 Reason = PDSA_StaticMemberShared; 1802 else if (VD && VD->isFileVarDecl()) 1803 Reason = PDSA_GlobalVarShared; 1804 else if (D->getType().isConstant(SemaRef.getASTContext())) 1805 Reason = PDSA_ConstVarShared; 1806 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 1807 ReportHint = true; 1808 Reason = PDSA_LocalVarPrivate; 1809 } 1810 if (Reason != PDSA_Implicit) { 1811 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 1812 << Reason << ReportHint 1813 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 1814 } else if (DVar.ImplicitDSALoc.isValid()) { 1815 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 1816 << getOpenMPClauseName(DVar.CKind); 1817 } 1818 } 1819 1820 namespace { 1821 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 1822 DSAStackTy *Stack; 1823 Sema &SemaRef; 1824 bool ErrorFound; 1825 CapturedStmt *CS; 1826 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 1827 llvm::SmallVector<Expr *, 8> ImplicitMap; 1828 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 1829 llvm::DenseSet<ValueDecl *> ImplicitDeclarations; 1830 1831 public: 1832 void VisitDeclRefExpr(DeclRefExpr *E) { 1833 if (E->isTypeDependent() || E->isValueDependent() || 1834 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1835 return; 1836 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1837 VD = VD->getCanonicalDecl(); 1838 // Skip internally declared variables. 1839 if (VD->hasLocalStorage() && !CS->capturesVariable(VD)) 1840 return; 1841 1842 auto DVar = Stack->getTopDSA(VD, false); 1843 // Check if the variable has explicit DSA set and stop analysis if it so. 1844 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 1845 return; 1846 1847 // Skip internally declared static variables. 1848 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD)) 1849 return; 1850 1851 auto ELoc = E->getExprLoc(); 1852 auto DKind = Stack->getCurrentDirective(); 1853 // The default(none) clause requires that each variable that is referenced 1854 // in the construct, and does not have a predetermined data-sharing 1855 // attribute, must have its data-sharing attribute explicitly determined 1856 // by being listed in a data-sharing attribute clause. 1857 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 1858 isParallelOrTaskRegion(DKind) && 1859 VarsWithInheritedDSA.count(VD) == 0) { 1860 VarsWithInheritedDSA[VD] = E; 1861 return; 1862 } 1863 1864 if (isOpenMPTargetExecutionDirective(DKind) && 1865 !Stack->isLoopControlVariable(VD).first) { 1866 if (!Stack->checkMappableExprComponentListsForDecl( 1867 VD, /*CurrentRegionOnly=*/true, 1868 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 1869 StackComponents, 1870 OpenMPClauseKind) { 1871 // Variable is used if it has been marked as an array, array 1872 // section or the variable iself. 1873 return StackComponents.size() == 1 || 1874 std::all_of( 1875 std::next(StackComponents.rbegin()), 1876 StackComponents.rend(), 1877 [](const OMPClauseMappableExprCommon:: 1878 MappableComponent &MC) { 1879 return MC.getAssociatedDeclaration() == 1880 nullptr && 1881 (isa<OMPArraySectionExpr>( 1882 MC.getAssociatedExpression()) || 1883 isa<ArraySubscriptExpr>( 1884 MC.getAssociatedExpression())); 1885 }); 1886 })) { 1887 bool IsFirstprivate = false; 1888 // By default lambdas are captured as firstprivates. 1889 if (const auto *RD = 1890 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 1891 IsFirstprivate = RD->isLambda(); 1892 IsFirstprivate = 1893 IsFirstprivate || 1894 (VD->getType().getNonReferenceType()->isScalarType() && 1895 Stack->getDefaultDMA() != DMA_tofrom_scalar); 1896 if (IsFirstprivate) 1897 ImplicitFirstprivate.emplace_back(E); 1898 else 1899 ImplicitMap.emplace_back(E); 1900 return; 1901 } 1902 } 1903 1904 // OpenMP [2.9.3.6, Restrictions, p.2] 1905 // A list item that appears in a reduction clause of the innermost 1906 // enclosing worksharing or parallel construct may not be accessed in an 1907 // explicit task. 1908 DVar = Stack->hasInnermostDSA( 1909 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1910 [](OpenMPDirectiveKind K) -> bool { 1911 return isOpenMPParallelDirective(K) || 1912 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1913 }, 1914 /*FromParent=*/true); 1915 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1916 ErrorFound = true; 1917 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1918 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 1919 return; 1920 } 1921 1922 // Define implicit data-sharing attributes for task. 1923 DVar = Stack->getImplicitDSA(VD, false); 1924 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1925 !Stack->isLoopControlVariable(VD).first) 1926 ImplicitFirstprivate.push_back(E); 1927 } 1928 } 1929 void VisitMemberExpr(MemberExpr *E) { 1930 if (E->isTypeDependent() || E->isValueDependent() || 1931 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1932 return; 1933 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 1934 if (!FD) 1935 return; 1936 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 1937 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 1938 auto DVar = Stack->getTopDSA(FD, false); 1939 // Check if the variable has explicit DSA set and stop analysis if it 1940 // so. 1941 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 1942 return; 1943 1944 if (isOpenMPTargetExecutionDirective(DKind) && 1945 !Stack->isLoopControlVariable(FD).first && 1946 !Stack->checkMappableExprComponentListsForDecl( 1947 FD, /*CurrentRegionOnly=*/true, 1948 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 1949 StackComponents, 1950 OpenMPClauseKind) { 1951 return isa<CXXThisExpr>( 1952 cast<MemberExpr>( 1953 StackComponents.back().getAssociatedExpression()) 1954 ->getBase() 1955 ->IgnoreParens()); 1956 })) { 1957 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 1958 // A bit-field cannot appear in a map clause. 1959 // 1960 if (FD->isBitField()) { 1961 SemaRef.Diag(E->getMemberLoc(), 1962 diag::err_omp_bit_fields_forbidden_in_clause) 1963 << E->getSourceRange() << getOpenMPClauseName(OMPC_map); 1964 return; 1965 } 1966 ImplicitMap.emplace_back(E); 1967 return; 1968 } 1969 1970 auto ELoc = E->getExprLoc(); 1971 // OpenMP [2.9.3.6, Restrictions, p.2] 1972 // A list item that appears in a reduction clause of the innermost 1973 // enclosing worksharing or parallel construct may not be accessed in 1974 // an explicit task. 1975 DVar = Stack->hasInnermostDSA( 1976 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1977 [](OpenMPDirectiveKind K) -> bool { 1978 return isOpenMPParallelDirective(K) || 1979 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1980 }, 1981 /*FromParent=*/true); 1982 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1983 ErrorFound = true; 1984 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1985 ReportOriginalDSA(SemaRef, Stack, FD, DVar); 1986 return; 1987 } 1988 1989 // Define implicit data-sharing attributes for task. 1990 DVar = Stack->getImplicitDSA(FD, false); 1991 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1992 !Stack->isLoopControlVariable(FD).first) 1993 ImplicitFirstprivate.push_back(E); 1994 return; 1995 } 1996 if (isOpenMPTargetExecutionDirective(DKind) && !FD->isBitField()) { 1997 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 1998 CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map); 1999 auto *VD = cast<ValueDecl>( 2000 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 2001 if (!Stack->checkMappableExprComponentListsForDecl( 2002 VD, /*CurrentRegionOnly=*/true, 2003 [&CurComponents]( 2004 OMPClauseMappableExprCommon::MappableExprComponentListRef 2005 StackComponents, 2006 OpenMPClauseKind) { 2007 auto CCI = CurComponents.rbegin(); 2008 auto CCE = CurComponents.rend(); 2009 for (const auto &SC : llvm::reverse(StackComponents)) { 2010 // Do both expressions have the same kind? 2011 if (CCI->getAssociatedExpression()->getStmtClass() != 2012 SC.getAssociatedExpression()->getStmtClass()) 2013 if (!(isa<OMPArraySectionExpr>( 2014 SC.getAssociatedExpression()) && 2015 isa<ArraySubscriptExpr>( 2016 CCI->getAssociatedExpression()))) 2017 return false; 2018 2019 Decl *CCD = CCI->getAssociatedDeclaration(); 2020 Decl *SCD = SC.getAssociatedDeclaration(); 2021 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 2022 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 2023 if (SCD != CCD) 2024 return false; 2025 std::advance(CCI, 1); 2026 if (CCI == CCE) 2027 break; 2028 } 2029 return true; 2030 })) { 2031 Visit(E->getBase()); 2032 } 2033 } else 2034 Visit(E->getBase()); 2035 } 2036 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 2037 for (auto *C : S->clauses()) { 2038 // Skip analysis of arguments of implicitly defined firstprivate clause 2039 // for task|target directives. 2040 // Skip analysis of arguments of implicitly defined map clause for target 2041 // directives. 2042 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 2043 C->isImplicit())) { 2044 for (auto *CC : C->children()) { 2045 if (CC) 2046 Visit(CC); 2047 } 2048 } 2049 } 2050 } 2051 void VisitStmt(Stmt *S) { 2052 for (auto *C : S->children()) { 2053 if (C && !isa<OMPExecutableDirective>(C)) 2054 Visit(C); 2055 } 2056 } 2057 2058 bool isErrorFound() { return ErrorFound; } 2059 ArrayRef<Expr *> getImplicitFirstprivate() const { 2060 return ImplicitFirstprivate; 2061 } 2062 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; } 2063 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() { 2064 return VarsWithInheritedDSA; 2065 } 2066 2067 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 2068 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 2069 }; 2070 } // namespace 2071 2072 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 2073 switch (DKind) { 2074 case OMPD_parallel: 2075 case OMPD_parallel_for: 2076 case OMPD_parallel_for_simd: 2077 case OMPD_parallel_sections: 2078 case OMPD_teams: 2079 case OMPD_teams_distribute: { 2080 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2081 QualType KmpInt32PtrTy = 2082 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2083 Sema::CapturedParamNameType Params[] = { 2084 std::make_pair(".global_tid.", KmpInt32PtrTy), 2085 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2086 std::make_pair(StringRef(), QualType()) // __context with shared vars 2087 }; 2088 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2089 Params); 2090 break; 2091 } 2092 case OMPD_target_teams: 2093 case OMPD_target_parallel: 2094 case OMPD_target_parallel_for: 2095 case OMPD_target_parallel_for_simd: { 2096 Sema::CapturedParamNameType ParamsTarget[] = { 2097 std::make_pair(StringRef(), QualType()) // __context with shared vars 2098 }; 2099 // Start a captured region for 'target' with no implicit parameters. 2100 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2101 ParamsTarget); 2102 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2103 QualType KmpInt32PtrTy = 2104 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2105 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 2106 std::make_pair(".global_tid.", KmpInt32PtrTy), 2107 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2108 std::make_pair(StringRef(), QualType()) // __context with shared vars 2109 }; 2110 // Start a captured region for 'teams' or 'parallel'. Both regions have 2111 // the same implicit parameters. 2112 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2113 ParamsTeamsOrParallel); 2114 break; 2115 } 2116 case OMPD_simd: 2117 case OMPD_for: 2118 case OMPD_for_simd: 2119 case OMPD_sections: 2120 case OMPD_section: 2121 case OMPD_single: 2122 case OMPD_master: 2123 case OMPD_critical: 2124 case OMPD_taskgroup: 2125 case OMPD_distribute: 2126 case OMPD_ordered: 2127 case OMPD_atomic: 2128 case OMPD_target_data: 2129 case OMPD_target: 2130 case OMPD_target_simd: { 2131 Sema::CapturedParamNameType Params[] = { 2132 std::make_pair(StringRef(), QualType()) // __context with shared vars 2133 }; 2134 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2135 Params); 2136 break; 2137 } 2138 case OMPD_task: { 2139 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2140 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2141 FunctionProtoType::ExtProtoInfo EPI; 2142 EPI.Variadic = true; 2143 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2144 Sema::CapturedParamNameType Params[] = { 2145 std::make_pair(".global_tid.", KmpInt32Ty), 2146 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2147 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 2148 std::make_pair(".copy_fn.", 2149 Context.getPointerType(CopyFnType).withConst()), 2150 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2151 std::make_pair(StringRef(), QualType()) // __context with shared vars 2152 }; 2153 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2154 Params); 2155 // Mark this captured region as inlined, because we don't use outlined 2156 // function directly. 2157 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2158 AlwaysInlineAttr::CreateImplicit( 2159 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2160 break; 2161 } 2162 case OMPD_taskloop: 2163 case OMPD_taskloop_simd: { 2164 QualType KmpInt32Ty = 2165 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 2166 QualType KmpUInt64Ty = 2167 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 2168 QualType KmpInt64Ty = 2169 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 2170 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2171 FunctionProtoType::ExtProtoInfo EPI; 2172 EPI.Variadic = true; 2173 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2174 Sema::CapturedParamNameType Params[] = { 2175 std::make_pair(".global_tid.", KmpInt32Ty), 2176 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2177 std::make_pair(".privates.", 2178 Context.VoidPtrTy.withConst().withRestrict()), 2179 std::make_pair( 2180 ".copy_fn.", 2181 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2182 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2183 std::make_pair(".lb.", KmpUInt64Ty), 2184 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 2185 std::make_pair(".liter.", KmpInt32Ty), 2186 std::make_pair(".reductions.", 2187 Context.VoidPtrTy.withConst().withRestrict()), 2188 std::make_pair(StringRef(), QualType()) // __context with shared vars 2189 }; 2190 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2191 Params); 2192 // Mark this captured region as inlined, because we don't use outlined 2193 // function directly. 2194 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2195 AlwaysInlineAttr::CreateImplicit( 2196 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2197 break; 2198 } 2199 case OMPD_distribute_parallel_for_simd: 2200 case OMPD_distribute_simd: 2201 case OMPD_distribute_parallel_for: 2202 case OMPD_teams_distribute_simd: 2203 case OMPD_teams_distribute_parallel_for_simd: 2204 case OMPD_teams_distribute_parallel_for: 2205 case OMPD_target_teams_distribute: 2206 case OMPD_target_teams_distribute_parallel_for: 2207 case OMPD_target_teams_distribute_parallel_for_simd: 2208 case OMPD_target_teams_distribute_simd: { 2209 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2210 QualType KmpInt32PtrTy = 2211 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2212 Sema::CapturedParamNameType Params[] = { 2213 std::make_pair(".global_tid.", KmpInt32PtrTy), 2214 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2215 std::make_pair(".previous.lb.", Context.getSizeType()), 2216 std::make_pair(".previous.ub.", Context.getSizeType()), 2217 std::make_pair(StringRef(), QualType()) // __context with shared vars 2218 }; 2219 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2220 Params); 2221 break; 2222 } 2223 case OMPD_threadprivate: 2224 case OMPD_taskyield: 2225 case OMPD_barrier: 2226 case OMPD_taskwait: 2227 case OMPD_cancellation_point: 2228 case OMPD_cancel: 2229 case OMPD_flush: 2230 case OMPD_target_enter_data: 2231 case OMPD_target_exit_data: 2232 case OMPD_declare_reduction: 2233 case OMPD_declare_simd: 2234 case OMPD_declare_target: 2235 case OMPD_end_declare_target: 2236 case OMPD_target_update: 2237 llvm_unreachable("OpenMP Directive is not allowed"); 2238 case OMPD_unknown: 2239 llvm_unreachable("Unknown OpenMP directive"); 2240 } 2241 } 2242 2243 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 2244 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2245 getOpenMPCaptureRegions(CaptureRegions, DKind); 2246 return CaptureRegions.size(); 2247 } 2248 2249 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 2250 Expr *CaptureExpr, bool WithInit, 2251 bool AsExpression) { 2252 assert(CaptureExpr); 2253 ASTContext &C = S.getASTContext(); 2254 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 2255 QualType Ty = Init->getType(); 2256 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 2257 if (S.getLangOpts().CPlusPlus) 2258 Ty = C.getLValueReferenceType(Ty); 2259 else { 2260 Ty = C.getPointerType(Ty); 2261 ExprResult Res = 2262 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 2263 if (!Res.isUsable()) 2264 return nullptr; 2265 Init = Res.get(); 2266 } 2267 WithInit = true; 2268 } 2269 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 2270 CaptureExpr->getLocStart()); 2271 if (!WithInit) 2272 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 2273 S.CurContext->addHiddenDecl(CED); 2274 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 2275 return CED; 2276 } 2277 2278 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2279 bool WithInit) { 2280 OMPCapturedExprDecl *CD; 2281 if (auto *VD = S.IsOpenMPCapturedDecl(D)) 2282 CD = cast<OMPCapturedExprDecl>(VD); 2283 else 2284 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 2285 /*AsExpression=*/false); 2286 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2287 CaptureExpr->getExprLoc()); 2288 } 2289 2290 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 2291 if (!Ref) { 2292 auto *CD = 2293 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), 2294 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); 2295 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2296 CaptureExpr->getExprLoc()); 2297 } 2298 ExprResult Res = Ref; 2299 if (!S.getLangOpts().CPlusPlus && 2300 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 2301 Ref->getType()->isPointerType()) 2302 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 2303 if (!Res.isUsable()) 2304 return ExprError(); 2305 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); 2306 } 2307 2308 namespace { 2309 // OpenMP directives parsed in this section are represented as a 2310 // CapturedStatement with an associated statement. If a syntax error 2311 // is detected during the parsing of the associated statement, the 2312 // compiler must abort processing and close the CapturedStatement. 2313 // 2314 // Combined directives such as 'target parallel' have more than one 2315 // nested CapturedStatements. This RAII ensures that we unwind out 2316 // of all the nested CapturedStatements when an error is found. 2317 class CaptureRegionUnwinderRAII { 2318 private: 2319 Sema &S; 2320 bool &ErrorFound; 2321 OpenMPDirectiveKind DKind; 2322 2323 public: 2324 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 2325 OpenMPDirectiveKind DKind) 2326 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 2327 ~CaptureRegionUnwinderRAII() { 2328 if (ErrorFound) { 2329 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 2330 while (--ThisCaptureLevel >= 0) 2331 S.ActOnCapturedRegionError(); 2332 } 2333 } 2334 }; 2335 } // namespace 2336 2337 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 2338 ArrayRef<OMPClause *> Clauses) { 2339 bool ErrorFound = false; 2340 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 2341 *this, ErrorFound, DSAStack->getCurrentDirective()); 2342 if (!S.isUsable()) { 2343 ErrorFound = true; 2344 return StmtError(); 2345 } 2346 2347 OMPOrderedClause *OC = nullptr; 2348 OMPScheduleClause *SC = nullptr; 2349 SmallVector<OMPLinearClause *, 4> LCs; 2350 SmallVector<OMPClauseWithPreInit *, 8> PICs; 2351 // This is required for proper codegen. 2352 for (auto *Clause : Clauses) { 2353 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 2354 Clause->getClauseKind() == OMPC_in_reduction) { 2355 // Capture taskgroup task_reduction descriptors inside the tasking regions 2356 // with the corresponding in_reduction items. 2357 auto *IRC = cast<OMPInReductionClause>(Clause); 2358 for (auto *E : IRC->taskgroup_descriptors()) 2359 if (E) 2360 MarkDeclarationsReferencedInExpr(E); 2361 } 2362 if (isOpenMPPrivate(Clause->getClauseKind()) || 2363 Clause->getClauseKind() == OMPC_copyprivate || 2364 (getLangOpts().OpenMPUseTLS && 2365 getASTContext().getTargetInfo().isTLSSupported() && 2366 Clause->getClauseKind() == OMPC_copyin)) { 2367 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 2368 // Mark all variables in private list clauses as used in inner region. 2369 for (auto *VarRef : Clause->children()) { 2370 if (auto *E = cast_or_null<Expr>(VarRef)) { 2371 MarkDeclarationsReferencedInExpr(E); 2372 } 2373 } 2374 DSAStack->setForceVarCapturing(/*V=*/false); 2375 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 2376 if (auto *C = OMPClauseWithPreInit::get(Clause)) 2377 PICs.push_back(C); 2378 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 2379 if (auto *E = C->getPostUpdateExpr()) 2380 MarkDeclarationsReferencedInExpr(E); 2381 } 2382 } 2383 if (Clause->getClauseKind() == OMPC_schedule) 2384 SC = cast<OMPScheduleClause>(Clause); 2385 else if (Clause->getClauseKind() == OMPC_ordered) 2386 OC = cast<OMPOrderedClause>(Clause); 2387 else if (Clause->getClauseKind() == OMPC_linear) 2388 LCs.push_back(cast<OMPLinearClause>(Clause)); 2389 } 2390 // OpenMP, 2.7.1 Loop Construct, Restrictions 2391 // The nonmonotonic modifier cannot be specified if an ordered clause is 2392 // specified. 2393 if (SC && 2394 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 2395 SC->getSecondScheduleModifier() == 2396 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 2397 OC) { 2398 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 2399 ? SC->getFirstScheduleModifierLoc() 2400 : SC->getSecondScheduleModifierLoc(), 2401 diag::err_omp_schedule_nonmonotonic_ordered) 2402 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2403 ErrorFound = true; 2404 } 2405 if (!LCs.empty() && OC && OC->getNumForLoops()) { 2406 for (auto *C : LCs) { 2407 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 2408 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2409 } 2410 ErrorFound = true; 2411 } 2412 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 2413 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 2414 OC->getNumForLoops()) { 2415 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 2416 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 2417 ErrorFound = true; 2418 } 2419 if (ErrorFound) { 2420 return StmtError(); 2421 } 2422 StmtResult SR = S; 2423 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2424 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 2425 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 2426 // Mark all variables in private list clauses as used in inner region. 2427 // Required for proper codegen of combined directives. 2428 // TODO: add processing for other clauses. 2429 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 2430 for (auto *C : PICs) { 2431 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 2432 // Find the particular capture region for the clause if the 2433 // directive is a combined one with multiple capture regions. 2434 // If the directive is not a combined one, the capture region 2435 // associated with the clause is OMPD_unknown and is generated 2436 // only once. 2437 if (CaptureRegion == ThisCaptureRegion || 2438 CaptureRegion == OMPD_unknown) { 2439 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 2440 for (auto *D : DS->decls()) 2441 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 2442 } 2443 } 2444 } 2445 } 2446 SR = ActOnCapturedRegionEnd(SR.get()); 2447 } 2448 return SR; 2449 } 2450 2451 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 2452 OpenMPDirectiveKind CancelRegion, 2453 SourceLocation StartLoc) { 2454 // CancelRegion is only needed for cancel and cancellation_point. 2455 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 2456 return false; 2457 2458 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 2459 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 2460 return false; 2461 2462 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 2463 << getOpenMPDirectiveName(CancelRegion); 2464 return true; 2465 } 2466 2467 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 2468 OpenMPDirectiveKind CurrentRegion, 2469 const DeclarationNameInfo &CurrentName, 2470 OpenMPDirectiveKind CancelRegion, 2471 SourceLocation StartLoc) { 2472 if (Stack->getCurScope()) { 2473 auto ParentRegion = Stack->getParentDirective(); 2474 auto OffendingRegion = ParentRegion; 2475 bool NestingProhibited = false; 2476 bool CloseNesting = true; 2477 bool OrphanSeen = false; 2478 enum { 2479 NoRecommend, 2480 ShouldBeInParallelRegion, 2481 ShouldBeInOrderedRegion, 2482 ShouldBeInTargetRegion, 2483 ShouldBeInTeamsRegion 2484 } Recommend = NoRecommend; 2485 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 2486 // OpenMP [2.16, Nesting of Regions] 2487 // OpenMP constructs may not be nested inside a simd region. 2488 // OpenMP [2.8.1,simd Construct, Restrictions] 2489 // An ordered construct with the simd clause is the only OpenMP 2490 // construct that can appear in the simd region. 2491 // Allowing a SIMD construct nested in another SIMD construct is an 2492 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 2493 // message. 2494 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 2495 ? diag::err_omp_prohibited_region_simd 2496 : diag::warn_omp_nesting_simd); 2497 return CurrentRegion != OMPD_simd; 2498 } 2499 if (ParentRegion == OMPD_atomic) { 2500 // OpenMP [2.16, Nesting of Regions] 2501 // OpenMP constructs may not be nested inside an atomic region. 2502 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 2503 return true; 2504 } 2505 if (CurrentRegion == OMPD_section) { 2506 // OpenMP [2.7.2, sections Construct, Restrictions] 2507 // Orphaned section directives are prohibited. That is, the section 2508 // directives must appear within the sections construct and must not be 2509 // encountered elsewhere in the sections region. 2510 if (ParentRegion != OMPD_sections && 2511 ParentRegion != OMPD_parallel_sections) { 2512 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 2513 << (ParentRegion != OMPD_unknown) 2514 << getOpenMPDirectiveName(ParentRegion); 2515 return true; 2516 } 2517 return false; 2518 } 2519 // Allow some constructs (except teams) to be orphaned (they could be 2520 // used in functions, called from OpenMP regions with the required 2521 // preconditions). 2522 if (ParentRegion == OMPD_unknown && 2523 !isOpenMPNestingTeamsDirective(CurrentRegion)) 2524 return false; 2525 if (CurrentRegion == OMPD_cancellation_point || 2526 CurrentRegion == OMPD_cancel) { 2527 // OpenMP [2.16, Nesting of Regions] 2528 // A cancellation point construct for which construct-type-clause is 2529 // taskgroup must be nested inside a task construct. A cancellation 2530 // point construct for which construct-type-clause is not taskgroup must 2531 // be closely nested inside an OpenMP construct that matches the type 2532 // specified in construct-type-clause. 2533 // A cancel construct for which construct-type-clause is taskgroup must be 2534 // nested inside a task construct. A cancel construct for which 2535 // construct-type-clause is not taskgroup must be closely nested inside an 2536 // OpenMP construct that matches the type specified in 2537 // construct-type-clause. 2538 NestingProhibited = 2539 !((CancelRegion == OMPD_parallel && 2540 (ParentRegion == OMPD_parallel || 2541 ParentRegion == OMPD_target_parallel)) || 2542 (CancelRegion == OMPD_for && 2543 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 2544 ParentRegion == OMPD_target_parallel_for)) || 2545 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 2546 (CancelRegion == OMPD_sections && 2547 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 2548 ParentRegion == OMPD_parallel_sections))); 2549 } else if (CurrentRegion == OMPD_master) { 2550 // OpenMP [2.16, Nesting of Regions] 2551 // A master region may not be closely nested inside a worksharing, 2552 // atomic, or explicit task region. 2553 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2554 isOpenMPTaskingDirective(ParentRegion); 2555 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 2556 // OpenMP [2.16, Nesting of Regions] 2557 // A critical region may not be nested (closely or otherwise) inside a 2558 // critical region with the same name. Note that this restriction is not 2559 // sufficient to prevent deadlock. 2560 SourceLocation PreviousCriticalLoc; 2561 bool DeadLock = Stack->hasDirective( 2562 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 2563 const DeclarationNameInfo &DNI, 2564 SourceLocation Loc) -> bool { 2565 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 2566 PreviousCriticalLoc = Loc; 2567 return true; 2568 } else 2569 return false; 2570 }, 2571 false /* skip top directive */); 2572 if (DeadLock) { 2573 SemaRef.Diag(StartLoc, 2574 diag::err_omp_prohibited_region_critical_same_name) 2575 << CurrentName.getName(); 2576 if (PreviousCriticalLoc.isValid()) 2577 SemaRef.Diag(PreviousCriticalLoc, 2578 diag::note_omp_previous_critical_region); 2579 return true; 2580 } 2581 } else if (CurrentRegion == OMPD_barrier) { 2582 // OpenMP [2.16, Nesting of Regions] 2583 // A barrier region may not be closely nested inside a worksharing, 2584 // explicit task, critical, ordered, atomic, or master region. 2585 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2586 isOpenMPTaskingDirective(ParentRegion) || 2587 ParentRegion == OMPD_master || 2588 ParentRegion == OMPD_critical || 2589 ParentRegion == OMPD_ordered; 2590 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2591 !isOpenMPParallelDirective(CurrentRegion) && 2592 !isOpenMPTeamsDirective(CurrentRegion)) { 2593 // OpenMP [2.16, Nesting of Regions] 2594 // A worksharing region may not be closely nested inside a worksharing, 2595 // explicit task, critical, ordered, atomic, or master region. 2596 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2597 isOpenMPTaskingDirective(ParentRegion) || 2598 ParentRegion == OMPD_master || 2599 ParentRegion == OMPD_critical || 2600 ParentRegion == OMPD_ordered; 2601 Recommend = ShouldBeInParallelRegion; 2602 } else if (CurrentRegion == OMPD_ordered) { 2603 // OpenMP [2.16, Nesting of Regions] 2604 // An ordered region may not be closely nested inside a critical, 2605 // atomic, or explicit task region. 2606 // An ordered region must be closely nested inside a loop region (or 2607 // parallel loop region) with an ordered clause. 2608 // OpenMP [2.8.1,simd Construct, Restrictions] 2609 // An ordered construct with the simd clause is the only OpenMP construct 2610 // that can appear in the simd region. 2611 NestingProhibited = ParentRegion == OMPD_critical || 2612 isOpenMPTaskingDirective(ParentRegion) || 2613 !(isOpenMPSimdDirective(ParentRegion) || 2614 Stack->isParentOrderedRegion()); 2615 Recommend = ShouldBeInOrderedRegion; 2616 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 2617 // OpenMP [2.16, Nesting of Regions] 2618 // If specified, a teams construct must be contained within a target 2619 // construct. 2620 NestingProhibited = ParentRegion != OMPD_target; 2621 OrphanSeen = ParentRegion == OMPD_unknown; 2622 Recommend = ShouldBeInTargetRegion; 2623 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 2624 } 2625 if (!NestingProhibited && 2626 !isOpenMPTargetExecutionDirective(CurrentRegion) && 2627 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 2628 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 2629 // OpenMP [2.16, Nesting of Regions] 2630 // distribute, parallel, parallel sections, parallel workshare, and the 2631 // parallel loop and parallel loop SIMD constructs are the only OpenMP 2632 // constructs that can be closely nested in the teams region. 2633 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 2634 !isOpenMPDistributeDirective(CurrentRegion); 2635 Recommend = ShouldBeInParallelRegion; 2636 } 2637 if (!NestingProhibited && 2638 isOpenMPNestingDistributeDirective(CurrentRegion)) { 2639 // OpenMP 4.5 [2.17 Nesting of Regions] 2640 // The region associated with the distribute construct must be strictly 2641 // nested inside a teams region 2642 NestingProhibited = 2643 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 2644 Recommend = ShouldBeInTeamsRegion; 2645 } 2646 if (!NestingProhibited && 2647 (isOpenMPTargetExecutionDirective(CurrentRegion) || 2648 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 2649 // OpenMP 4.5 [2.17 Nesting of Regions] 2650 // If a target, target update, target data, target enter data, or 2651 // target exit data construct is encountered during execution of a 2652 // target region, the behavior is unspecified. 2653 NestingProhibited = Stack->hasDirective( 2654 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2655 SourceLocation) -> bool { 2656 if (isOpenMPTargetExecutionDirective(K)) { 2657 OffendingRegion = K; 2658 return true; 2659 } else 2660 return false; 2661 }, 2662 false /* don't skip top directive */); 2663 CloseNesting = false; 2664 } 2665 if (NestingProhibited) { 2666 if (OrphanSeen) { 2667 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 2668 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 2669 } else { 2670 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 2671 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 2672 << Recommend << getOpenMPDirectiveName(CurrentRegion); 2673 } 2674 return true; 2675 } 2676 } 2677 return false; 2678 } 2679 2680 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 2681 ArrayRef<OMPClause *> Clauses, 2682 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 2683 bool ErrorFound = false; 2684 unsigned NamedModifiersNumber = 0; 2685 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 2686 OMPD_unknown + 1); 2687 SmallVector<SourceLocation, 4> NameModifierLoc; 2688 for (const auto *C : Clauses) { 2689 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 2690 // At most one if clause without a directive-name-modifier can appear on 2691 // the directive. 2692 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 2693 if (FoundNameModifiers[CurNM]) { 2694 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 2695 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 2696 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 2697 ErrorFound = true; 2698 } else if (CurNM != OMPD_unknown) { 2699 NameModifierLoc.push_back(IC->getNameModifierLoc()); 2700 ++NamedModifiersNumber; 2701 } 2702 FoundNameModifiers[CurNM] = IC; 2703 if (CurNM == OMPD_unknown) 2704 continue; 2705 // Check if the specified name modifier is allowed for the current 2706 // directive. 2707 // At most one if clause with the particular directive-name-modifier can 2708 // appear on the directive. 2709 bool MatchFound = false; 2710 for (auto NM : AllowedNameModifiers) { 2711 if (CurNM == NM) { 2712 MatchFound = true; 2713 break; 2714 } 2715 } 2716 if (!MatchFound) { 2717 S.Diag(IC->getNameModifierLoc(), 2718 diag::err_omp_wrong_if_directive_name_modifier) 2719 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 2720 ErrorFound = true; 2721 } 2722 } 2723 } 2724 // If any if clause on the directive includes a directive-name-modifier then 2725 // all if clauses on the directive must include a directive-name-modifier. 2726 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 2727 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 2728 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 2729 diag::err_omp_no_more_if_clause); 2730 } else { 2731 std::string Values; 2732 std::string Sep(", "); 2733 unsigned AllowedCnt = 0; 2734 unsigned TotalAllowedNum = 2735 AllowedNameModifiers.size() - NamedModifiersNumber; 2736 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 2737 ++Cnt) { 2738 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 2739 if (!FoundNameModifiers[NM]) { 2740 Values += "'"; 2741 Values += getOpenMPDirectiveName(NM); 2742 Values += "'"; 2743 if (AllowedCnt + 2 == TotalAllowedNum) 2744 Values += " or "; 2745 else if (AllowedCnt + 1 != TotalAllowedNum) 2746 Values += Sep; 2747 ++AllowedCnt; 2748 } 2749 } 2750 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 2751 diag::err_omp_unnamed_if_clause) 2752 << (TotalAllowedNum > 1) << Values; 2753 } 2754 for (auto Loc : NameModifierLoc) { 2755 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 2756 } 2757 ErrorFound = true; 2758 } 2759 return ErrorFound; 2760 } 2761 2762 StmtResult Sema::ActOnOpenMPExecutableDirective( 2763 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 2764 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 2765 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 2766 StmtResult Res = StmtError(); 2767 // First check CancelRegion which is then used in checkNestingOfRegions. 2768 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 2769 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 2770 StartLoc)) 2771 return StmtError(); 2772 2773 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 2774 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 2775 bool ErrorFound = false; 2776 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 2777 if (AStmt && !CurContext->isDependentContext()) { 2778 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2779 2780 // Check default data sharing attributes for referenced variables. 2781 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 2782 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 2783 Stmt *S = AStmt; 2784 while (--ThisCaptureLevel >= 0) 2785 S = cast<CapturedStmt>(S)->getCapturedStmt(); 2786 DSAChecker.Visit(S); 2787 if (DSAChecker.isErrorFound()) 2788 return StmtError(); 2789 // Generate list of implicitly defined firstprivate variables. 2790 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 2791 2792 SmallVector<Expr *, 4> ImplicitFirstprivates( 2793 DSAChecker.getImplicitFirstprivate().begin(), 2794 DSAChecker.getImplicitFirstprivate().end()); 2795 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(), 2796 DSAChecker.getImplicitMap().end()); 2797 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 2798 for (auto *C : Clauses) { 2799 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 2800 for (auto *E : IRC->taskgroup_descriptors()) 2801 if (E) 2802 ImplicitFirstprivates.emplace_back(E); 2803 } 2804 } 2805 if (!ImplicitFirstprivates.empty()) { 2806 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 2807 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 2808 SourceLocation())) { 2809 ClausesWithImplicit.push_back(Implicit); 2810 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 2811 ImplicitFirstprivates.size(); 2812 } else 2813 ErrorFound = true; 2814 } 2815 if (!ImplicitMaps.empty()) { 2816 if (OMPClause *Implicit = ActOnOpenMPMapClause( 2817 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, 2818 SourceLocation(), SourceLocation(), ImplicitMaps, 2819 SourceLocation(), SourceLocation(), SourceLocation())) { 2820 ClausesWithImplicit.emplace_back(Implicit); 2821 ErrorFound |= 2822 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size(); 2823 } else 2824 ErrorFound = true; 2825 } 2826 } 2827 2828 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 2829 switch (Kind) { 2830 case OMPD_parallel: 2831 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 2832 EndLoc); 2833 AllowedNameModifiers.push_back(OMPD_parallel); 2834 break; 2835 case OMPD_simd: 2836 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2837 VarsWithInheritedDSA); 2838 break; 2839 case OMPD_for: 2840 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2841 VarsWithInheritedDSA); 2842 break; 2843 case OMPD_for_simd: 2844 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2845 EndLoc, VarsWithInheritedDSA); 2846 break; 2847 case OMPD_sections: 2848 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 2849 EndLoc); 2850 break; 2851 case OMPD_section: 2852 assert(ClausesWithImplicit.empty() && 2853 "No clauses are allowed for 'omp section' directive"); 2854 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 2855 break; 2856 case OMPD_single: 2857 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 2858 EndLoc); 2859 break; 2860 case OMPD_master: 2861 assert(ClausesWithImplicit.empty() && 2862 "No clauses are allowed for 'omp master' directive"); 2863 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 2864 break; 2865 case OMPD_critical: 2866 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 2867 StartLoc, EndLoc); 2868 break; 2869 case OMPD_parallel_for: 2870 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 2871 EndLoc, VarsWithInheritedDSA); 2872 AllowedNameModifiers.push_back(OMPD_parallel); 2873 break; 2874 case OMPD_parallel_for_simd: 2875 Res = ActOnOpenMPParallelForSimdDirective( 2876 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2877 AllowedNameModifiers.push_back(OMPD_parallel); 2878 break; 2879 case OMPD_parallel_sections: 2880 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 2881 StartLoc, EndLoc); 2882 AllowedNameModifiers.push_back(OMPD_parallel); 2883 break; 2884 case OMPD_task: 2885 Res = 2886 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2887 AllowedNameModifiers.push_back(OMPD_task); 2888 break; 2889 case OMPD_taskyield: 2890 assert(ClausesWithImplicit.empty() && 2891 "No clauses are allowed for 'omp taskyield' directive"); 2892 assert(AStmt == nullptr && 2893 "No associated statement allowed for 'omp taskyield' directive"); 2894 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 2895 break; 2896 case OMPD_barrier: 2897 assert(ClausesWithImplicit.empty() && 2898 "No clauses are allowed for 'omp barrier' directive"); 2899 assert(AStmt == nullptr && 2900 "No associated statement allowed for 'omp barrier' directive"); 2901 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 2902 break; 2903 case OMPD_taskwait: 2904 assert(ClausesWithImplicit.empty() && 2905 "No clauses are allowed for 'omp taskwait' directive"); 2906 assert(AStmt == nullptr && 2907 "No associated statement allowed for 'omp taskwait' directive"); 2908 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 2909 break; 2910 case OMPD_taskgroup: 2911 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 2912 EndLoc); 2913 break; 2914 case OMPD_flush: 2915 assert(AStmt == nullptr && 2916 "No associated statement allowed for 'omp flush' directive"); 2917 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 2918 break; 2919 case OMPD_ordered: 2920 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 2921 EndLoc); 2922 break; 2923 case OMPD_atomic: 2924 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 2925 EndLoc); 2926 break; 2927 case OMPD_teams: 2928 Res = 2929 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2930 break; 2931 case OMPD_target: 2932 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 2933 EndLoc); 2934 AllowedNameModifiers.push_back(OMPD_target); 2935 break; 2936 case OMPD_target_parallel: 2937 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 2938 StartLoc, EndLoc); 2939 AllowedNameModifiers.push_back(OMPD_target); 2940 AllowedNameModifiers.push_back(OMPD_parallel); 2941 break; 2942 case OMPD_target_parallel_for: 2943 Res = ActOnOpenMPTargetParallelForDirective( 2944 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2945 AllowedNameModifiers.push_back(OMPD_target); 2946 AllowedNameModifiers.push_back(OMPD_parallel); 2947 break; 2948 case OMPD_cancellation_point: 2949 assert(ClausesWithImplicit.empty() && 2950 "No clauses are allowed for 'omp cancellation point' directive"); 2951 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 2952 "cancellation point' directive"); 2953 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 2954 break; 2955 case OMPD_cancel: 2956 assert(AStmt == nullptr && 2957 "No associated statement allowed for 'omp cancel' directive"); 2958 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 2959 CancelRegion); 2960 AllowedNameModifiers.push_back(OMPD_cancel); 2961 break; 2962 case OMPD_target_data: 2963 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 2964 EndLoc); 2965 AllowedNameModifiers.push_back(OMPD_target_data); 2966 break; 2967 case OMPD_target_enter_data: 2968 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 2969 EndLoc); 2970 AllowedNameModifiers.push_back(OMPD_target_enter_data); 2971 break; 2972 case OMPD_target_exit_data: 2973 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 2974 EndLoc); 2975 AllowedNameModifiers.push_back(OMPD_target_exit_data); 2976 break; 2977 case OMPD_taskloop: 2978 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 2979 EndLoc, VarsWithInheritedDSA); 2980 AllowedNameModifiers.push_back(OMPD_taskloop); 2981 break; 2982 case OMPD_taskloop_simd: 2983 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2984 EndLoc, VarsWithInheritedDSA); 2985 AllowedNameModifiers.push_back(OMPD_taskloop); 2986 break; 2987 case OMPD_distribute: 2988 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 2989 EndLoc, VarsWithInheritedDSA); 2990 break; 2991 case OMPD_target_update: 2992 assert(!AStmt && "Statement is not allowed for target update"); 2993 Res = 2994 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); 2995 AllowedNameModifiers.push_back(OMPD_target_update); 2996 break; 2997 case OMPD_distribute_parallel_for: 2998 Res = ActOnOpenMPDistributeParallelForDirective( 2999 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3000 AllowedNameModifiers.push_back(OMPD_parallel); 3001 break; 3002 case OMPD_distribute_parallel_for_simd: 3003 Res = ActOnOpenMPDistributeParallelForSimdDirective( 3004 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3005 AllowedNameModifiers.push_back(OMPD_parallel); 3006 break; 3007 case OMPD_distribute_simd: 3008 Res = ActOnOpenMPDistributeSimdDirective( 3009 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3010 break; 3011 case OMPD_target_parallel_for_simd: 3012 Res = ActOnOpenMPTargetParallelForSimdDirective( 3013 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3014 AllowedNameModifiers.push_back(OMPD_target); 3015 AllowedNameModifiers.push_back(OMPD_parallel); 3016 break; 3017 case OMPD_target_simd: 3018 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3019 EndLoc, VarsWithInheritedDSA); 3020 AllowedNameModifiers.push_back(OMPD_target); 3021 break; 3022 case OMPD_teams_distribute: 3023 Res = ActOnOpenMPTeamsDistributeDirective( 3024 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3025 break; 3026 case OMPD_teams_distribute_simd: 3027 Res = ActOnOpenMPTeamsDistributeSimdDirective( 3028 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3029 break; 3030 case OMPD_teams_distribute_parallel_for_simd: 3031 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 3032 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3033 AllowedNameModifiers.push_back(OMPD_parallel); 3034 break; 3035 case OMPD_teams_distribute_parallel_for: 3036 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 3037 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3038 AllowedNameModifiers.push_back(OMPD_parallel); 3039 break; 3040 case OMPD_target_teams: 3041 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 3042 EndLoc); 3043 AllowedNameModifiers.push_back(OMPD_target); 3044 break; 3045 case OMPD_target_teams_distribute: 3046 Res = ActOnOpenMPTargetTeamsDistributeDirective( 3047 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3048 AllowedNameModifiers.push_back(OMPD_target); 3049 break; 3050 case OMPD_target_teams_distribute_parallel_for: 3051 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 3052 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3053 AllowedNameModifiers.push_back(OMPD_target); 3054 AllowedNameModifiers.push_back(OMPD_parallel); 3055 break; 3056 case OMPD_target_teams_distribute_parallel_for_simd: 3057 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 3058 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3059 AllowedNameModifiers.push_back(OMPD_target); 3060 AllowedNameModifiers.push_back(OMPD_parallel); 3061 break; 3062 case OMPD_target_teams_distribute_simd: 3063 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 3064 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3065 AllowedNameModifiers.push_back(OMPD_target); 3066 break; 3067 case OMPD_declare_target: 3068 case OMPD_end_declare_target: 3069 case OMPD_threadprivate: 3070 case OMPD_declare_reduction: 3071 case OMPD_declare_simd: 3072 llvm_unreachable("OpenMP Directive is not allowed"); 3073 case OMPD_unknown: 3074 llvm_unreachable("Unknown OpenMP directive"); 3075 } 3076 3077 for (auto P : VarsWithInheritedDSA) { 3078 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 3079 << P.first << P.second->getSourceRange(); 3080 } 3081 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 3082 3083 if (!AllowedNameModifiers.empty()) 3084 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 3085 ErrorFound; 3086 3087 if (ErrorFound) 3088 return StmtError(); 3089 return Res; 3090 } 3091 3092 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 3093 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 3094 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 3095 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 3096 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 3097 assert(Aligneds.size() == Alignments.size()); 3098 assert(Linears.size() == LinModifiers.size()); 3099 assert(Linears.size() == Steps.size()); 3100 if (!DG || DG.get().isNull()) 3101 return DeclGroupPtrTy(); 3102 3103 if (!DG.get().isSingleDecl()) { 3104 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 3105 return DG; 3106 } 3107 auto *ADecl = DG.get().getSingleDecl(); 3108 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 3109 ADecl = FTD->getTemplatedDecl(); 3110 3111 auto *FD = dyn_cast<FunctionDecl>(ADecl); 3112 if (!FD) { 3113 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 3114 return DeclGroupPtrTy(); 3115 } 3116 3117 // OpenMP [2.8.2, declare simd construct, Description] 3118 // The parameter of the simdlen clause must be a constant positive integer 3119 // expression. 3120 ExprResult SL; 3121 if (Simdlen) 3122 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 3123 // OpenMP [2.8.2, declare simd construct, Description] 3124 // The special this pointer can be used as if was one of the arguments to the 3125 // function in any of the linear, aligned, or uniform clauses. 3126 // The uniform clause declares one or more arguments to have an invariant 3127 // value for all concurrent invocations of the function in the execution of a 3128 // single SIMD loop. 3129 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 3130 Expr *UniformedLinearThis = nullptr; 3131 for (auto *E : Uniforms) { 3132 E = E->IgnoreParenImpCasts(); 3133 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3134 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 3135 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3136 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3137 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 3138 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 3139 continue; 3140 } 3141 if (isa<CXXThisExpr>(E)) { 3142 UniformedLinearThis = E; 3143 continue; 3144 } 3145 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3146 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3147 } 3148 // OpenMP [2.8.2, declare simd construct, Description] 3149 // The aligned clause declares that the object to which each list item points 3150 // is aligned to the number of bytes expressed in the optional parameter of 3151 // the aligned clause. 3152 // The special this pointer can be used as if was one of the arguments to the 3153 // function in any of the linear, aligned, or uniform clauses. 3154 // The type of list items appearing in the aligned clause must be array, 3155 // pointer, reference to array, or reference to pointer. 3156 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 3157 Expr *AlignedThis = nullptr; 3158 for (auto *E : Aligneds) { 3159 E = E->IgnoreParenImpCasts(); 3160 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3161 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3162 auto *CanonPVD = PVD->getCanonicalDecl(); 3163 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3164 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3165 ->getCanonicalDecl() == CanonPVD) { 3166 // OpenMP [2.8.1, simd construct, Restrictions] 3167 // A list-item cannot appear in more than one aligned clause. 3168 if (AlignedArgs.count(CanonPVD) > 0) { 3169 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3170 << 1 << E->getSourceRange(); 3171 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 3172 diag::note_omp_explicit_dsa) 3173 << getOpenMPClauseName(OMPC_aligned); 3174 continue; 3175 } 3176 AlignedArgs[CanonPVD] = E; 3177 QualType QTy = PVD->getType() 3178 .getNonReferenceType() 3179 .getUnqualifiedType() 3180 .getCanonicalType(); 3181 const Type *Ty = QTy.getTypePtrOrNull(); 3182 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 3183 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 3184 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 3185 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 3186 } 3187 continue; 3188 } 3189 } 3190 if (isa<CXXThisExpr>(E)) { 3191 if (AlignedThis) { 3192 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3193 << 2 << E->getSourceRange(); 3194 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 3195 << getOpenMPClauseName(OMPC_aligned); 3196 } 3197 AlignedThis = E; 3198 continue; 3199 } 3200 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3201 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3202 } 3203 // The optional parameter of the aligned clause, alignment, must be a constant 3204 // positive integer expression. If no optional parameter is specified, 3205 // implementation-defined default alignments for SIMD instructions on the 3206 // target platforms are assumed. 3207 SmallVector<Expr *, 4> NewAligns; 3208 for (auto *E : Alignments) { 3209 ExprResult Align; 3210 if (E) 3211 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 3212 NewAligns.push_back(Align.get()); 3213 } 3214 // OpenMP [2.8.2, declare simd construct, Description] 3215 // The linear clause declares one or more list items to be private to a SIMD 3216 // lane and to have a linear relationship with respect to the iteration space 3217 // of a loop. 3218 // The special this pointer can be used as if was one of the arguments to the 3219 // function in any of the linear, aligned, or uniform clauses. 3220 // When a linear-step expression is specified in a linear clause it must be 3221 // either a constant integer expression or an integer-typed parameter that is 3222 // specified in a uniform clause on the directive. 3223 llvm::DenseMap<Decl *, Expr *> LinearArgs; 3224 const bool IsUniformedThis = UniformedLinearThis != nullptr; 3225 auto MI = LinModifiers.begin(); 3226 for (auto *E : Linears) { 3227 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 3228 ++MI; 3229 E = E->IgnoreParenImpCasts(); 3230 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3231 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3232 auto *CanonPVD = PVD->getCanonicalDecl(); 3233 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3234 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3235 ->getCanonicalDecl() == CanonPVD) { 3236 // OpenMP [2.15.3.7, linear Clause, Restrictions] 3237 // A list-item cannot appear in more than one linear clause. 3238 if (LinearArgs.count(CanonPVD) > 0) { 3239 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3240 << getOpenMPClauseName(OMPC_linear) 3241 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 3242 Diag(LinearArgs[CanonPVD]->getExprLoc(), 3243 diag::note_omp_explicit_dsa) 3244 << getOpenMPClauseName(OMPC_linear); 3245 continue; 3246 } 3247 // Each argument can appear in at most one uniform or linear clause. 3248 if (UniformedArgs.count(CanonPVD) > 0) { 3249 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3250 << getOpenMPClauseName(OMPC_linear) 3251 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 3252 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 3253 diag::note_omp_explicit_dsa) 3254 << getOpenMPClauseName(OMPC_uniform); 3255 continue; 3256 } 3257 LinearArgs[CanonPVD] = E; 3258 if (E->isValueDependent() || E->isTypeDependent() || 3259 E->isInstantiationDependent() || 3260 E->containsUnexpandedParameterPack()) 3261 continue; 3262 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 3263 PVD->getOriginalType()); 3264 continue; 3265 } 3266 } 3267 if (isa<CXXThisExpr>(E)) { 3268 if (UniformedLinearThis) { 3269 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3270 << getOpenMPClauseName(OMPC_linear) 3271 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 3272 << E->getSourceRange(); 3273 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 3274 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 3275 : OMPC_linear); 3276 continue; 3277 } 3278 UniformedLinearThis = E; 3279 if (E->isValueDependent() || E->isTypeDependent() || 3280 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3281 continue; 3282 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 3283 E->getType()); 3284 continue; 3285 } 3286 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3287 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3288 } 3289 Expr *Step = nullptr; 3290 Expr *NewStep = nullptr; 3291 SmallVector<Expr *, 4> NewSteps; 3292 for (auto *E : Steps) { 3293 // Skip the same step expression, it was checked already. 3294 if (Step == E || !E) { 3295 NewSteps.push_back(E ? NewStep : nullptr); 3296 continue; 3297 } 3298 Step = E; 3299 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 3300 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3301 auto *CanonPVD = PVD->getCanonicalDecl(); 3302 if (UniformedArgs.count(CanonPVD) == 0) { 3303 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 3304 << Step->getSourceRange(); 3305 } else if (E->isValueDependent() || E->isTypeDependent() || 3306 E->isInstantiationDependent() || 3307 E->containsUnexpandedParameterPack() || 3308 CanonPVD->getType()->hasIntegerRepresentation()) 3309 NewSteps.push_back(Step); 3310 else { 3311 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 3312 << Step->getSourceRange(); 3313 } 3314 continue; 3315 } 3316 NewStep = Step; 3317 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 3318 !Step->isInstantiationDependent() && 3319 !Step->containsUnexpandedParameterPack()) { 3320 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 3321 .get(); 3322 if (NewStep) 3323 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 3324 } 3325 NewSteps.push_back(NewStep); 3326 } 3327 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 3328 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 3329 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 3330 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 3331 const_cast<Expr **>(Linears.data()), Linears.size(), 3332 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 3333 NewSteps.data(), NewSteps.size(), SR); 3334 ADecl->addAttr(NewAttr); 3335 return ConvertDeclToDeclGroup(ADecl); 3336 } 3337 3338 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 3339 Stmt *AStmt, 3340 SourceLocation StartLoc, 3341 SourceLocation EndLoc) { 3342 if (!AStmt) 3343 return StmtError(); 3344 3345 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3346 // 1.2.2 OpenMP Language Terminology 3347 // Structured block - An executable statement with a single entry at the 3348 // top and a single exit at the bottom. 3349 // The point of exit cannot be a branch out of the structured block. 3350 // longjmp() and throw() must not violate the entry/exit criteria. 3351 CS->getCapturedDecl()->setNothrow(); 3352 3353 getCurFunction()->setHasBranchProtectedScope(); 3354 3355 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 3356 DSAStack->isCancelRegion()); 3357 } 3358 3359 namespace { 3360 /// \brief Helper class for checking canonical form of the OpenMP loops and 3361 /// extracting iteration space of each loop in the loop nest, that will be used 3362 /// for IR generation. 3363 class OpenMPIterationSpaceChecker { 3364 /// \brief Reference to Sema. 3365 Sema &SemaRef; 3366 /// \brief A location for diagnostics (when there is no some better location). 3367 SourceLocation DefaultLoc; 3368 /// \brief A location for diagnostics (when increment is not compatible). 3369 SourceLocation ConditionLoc; 3370 /// \brief A source location for referring to loop init later. 3371 SourceRange InitSrcRange; 3372 /// \brief A source location for referring to condition later. 3373 SourceRange ConditionSrcRange; 3374 /// \brief A source location for referring to increment later. 3375 SourceRange IncrementSrcRange; 3376 /// \brief Loop variable. 3377 ValueDecl *LCDecl = nullptr; 3378 /// \brief Reference to loop variable. 3379 Expr *LCRef = nullptr; 3380 /// \brief Lower bound (initializer for the var). 3381 Expr *LB = nullptr; 3382 /// \brief Upper bound. 3383 Expr *UB = nullptr; 3384 /// \brief Loop step (increment). 3385 Expr *Step = nullptr; 3386 /// \brief This flag is true when condition is one of: 3387 /// Var < UB 3388 /// Var <= UB 3389 /// UB > Var 3390 /// UB >= Var 3391 bool TestIsLessOp = false; 3392 /// \brief This flag is true when condition is strict ( < or > ). 3393 bool TestIsStrictOp = false; 3394 /// \brief This flag is true when step is subtracted on each iteration. 3395 bool SubtractStep = false; 3396 3397 public: 3398 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 3399 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 3400 /// \brief Check init-expr for canonical loop form and save loop counter 3401 /// variable - #Var and its initialization value - #LB. 3402 bool CheckInit(Stmt *S, bool EmitDiags = true); 3403 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 3404 /// for less/greater and for strict/non-strict comparison. 3405 bool CheckCond(Expr *S); 3406 /// \brief Check incr-expr for canonical loop form and return true if it 3407 /// does not conform, otherwise save loop step (#Step). 3408 bool CheckInc(Expr *S); 3409 /// \brief Return the loop counter variable. 3410 ValueDecl *GetLoopDecl() const { return LCDecl; } 3411 /// \brief Return the reference expression to loop counter variable. 3412 Expr *GetLoopDeclRefExpr() const { return LCRef; } 3413 /// \brief Source range of the loop init. 3414 SourceRange GetInitSrcRange() const { return InitSrcRange; } 3415 /// \brief Source range of the loop condition. 3416 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 3417 /// \brief Source range of the loop increment. 3418 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 3419 /// \brief True if the step should be subtracted. 3420 bool ShouldSubtractStep() const { return SubtractStep; } 3421 /// \brief Build the expression to calculate the number of iterations. 3422 Expr * 3423 BuildNumIterations(Scope *S, const bool LimitedType, 3424 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3425 /// \brief Build the precondition expression for the loops. 3426 Expr *BuildPreCond(Scope *S, Expr *Cond, 3427 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3428 /// \brief Build reference expression to the counter be used for codegen. 3429 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 3430 DSAStackTy &DSA) const; 3431 /// \brief Build reference expression to the private counter be used for 3432 /// codegen. 3433 Expr *BuildPrivateCounterVar() const; 3434 /// \brief Build initialization of the counter be used for codegen. 3435 Expr *BuildCounterInit() const; 3436 /// \brief Build step of the counter be used for codegen. 3437 Expr *BuildCounterStep() const; 3438 /// \brief Return true if any expression is dependent. 3439 bool Dependent() const; 3440 3441 private: 3442 /// \brief Check the right-hand side of an assignment in the increment 3443 /// expression. 3444 bool CheckIncRHS(Expr *RHS); 3445 /// \brief Helper to set loop counter variable and its initializer. 3446 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 3447 /// \brief Helper to set upper bound. 3448 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 3449 SourceLocation SL); 3450 /// \brief Helper to set loop increment. 3451 bool SetStep(Expr *NewStep, bool Subtract); 3452 }; 3453 3454 bool OpenMPIterationSpaceChecker::Dependent() const { 3455 if (!LCDecl) { 3456 assert(!LB && !UB && !Step); 3457 return false; 3458 } 3459 return LCDecl->getType()->isDependentType() || 3460 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 3461 (Step && Step->isValueDependent()); 3462 } 3463 3464 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 3465 Expr *NewLCRefExpr, 3466 Expr *NewLB) { 3467 // State consistency checking to ensure correct usage. 3468 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 3469 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3470 if (!NewLCDecl || !NewLB) 3471 return true; 3472 LCDecl = getCanonicalDecl(NewLCDecl); 3473 LCRef = NewLCRefExpr; 3474 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 3475 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3476 if ((Ctor->isCopyOrMoveConstructor() || 3477 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3478 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3479 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 3480 LB = NewLB; 3481 return false; 3482 } 3483 3484 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 3485 SourceRange SR, SourceLocation SL) { 3486 // State consistency checking to ensure correct usage. 3487 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 3488 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3489 if (!NewUB) 3490 return true; 3491 UB = NewUB; 3492 TestIsLessOp = LessOp; 3493 TestIsStrictOp = StrictOp; 3494 ConditionSrcRange = SR; 3495 ConditionLoc = SL; 3496 return false; 3497 } 3498 3499 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 3500 // State consistency checking to ensure correct usage. 3501 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 3502 if (!NewStep) 3503 return true; 3504 if (!NewStep->isValueDependent()) { 3505 // Check that the step is integer expression. 3506 SourceLocation StepLoc = NewStep->getLocStart(); 3507 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 3508 StepLoc, getExprAsWritten(NewStep)); 3509 if (Val.isInvalid()) 3510 return true; 3511 NewStep = Val.get(); 3512 3513 // OpenMP [2.6, Canonical Loop Form, Restrictions] 3514 // If test-expr is of form var relational-op b and relational-op is < or 3515 // <= then incr-expr must cause var to increase on each iteration of the 3516 // loop. If test-expr is of form var relational-op b and relational-op is 3517 // > or >= then incr-expr must cause var to decrease on each iteration of 3518 // the loop. 3519 // If test-expr is of form b relational-op var and relational-op is < or 3520 // <= then incr-expr must cause var to decrease on each iteration of the 3521 // loop. If test-expr is of form b relational-op var and relational-op is 3522 // > or >= then incr-expr must cause var to increase on each iteration of 3523 // the loop. 3524 llvm::APSInt Result; 3525 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 3526 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 3527 bool IsConstNeg = 3528 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 3529 bool IsConstPos = 3530 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 3531 bool IsConstZero = IsConstant && !Result.getBoolValue(); 3532 if (UB && (IsConstZero || 3533 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 3534 : (IsConstPos || (IsUnsigned && !Subtract))))) { 3535 SemaRef.Diag(NewStep->getExprLoc(), 3536 diag::err_omp_loop_incr_not_compatible) 3537 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 3538 SemaRef.Diag(ConditionLoc, 3539 diag::note_omp_loop_cond_requres_compatible_incr) 3540 << TestIsLessOp << ConditionSrcRange; 3541 return true; 3542 } 3543 if (TestIsLessOp == Subtract) { 3544 NewStep = 3545 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 3546 .get(); 3547 Subtract = !Subtract; 3548 } 3549 } 3550 3551 Step = NewStep; 3552 SubtractStep = Subtract; 3553 return false; 3554 } 3555 3556 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 3557 // Check init-expr for canonical loop form and save loop counter 3558 // variable - #Var and its initialization value - #LB. 3559 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 3560 // var = lb 3561 // integer-type var = lb 3562 // random-access-iterator-type var = lb 3563 // pointer-type var = lb 3564 // 3565 if (!S) { 3566 if (EmitDiags) { 3567 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 3568 } 3569 return true; 3570 } 3571 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3572 if (!ExprTemp->cleanupsHaveSideEffects()) 3573 S = ExprTemp->getSubExpr(); 3574 3575 InitSrcRange = S->getSourceRange(); 3576 if (Expr *E = dyn_cast<Expr>(S)) 3577 S = E->IgnoreParens(); 3578 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3579 if (BO->getOpcode() == BO_Assign) { 3580 auto *LHS = BO->getLHS()->IgnoreParens(); 3581 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3582 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3583 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3584 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3585 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 3586 } 3587 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3588 if (ME->isArrow() && 3589 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3590 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3591 } 3592 } 3593 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 3594 if (DS->isSingleDecl()) { 3595 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 3596 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 3597 // Accept non-canonical init form here but emit ext. warning. 3598 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 3599 SemaRef.Diag(S->getLocStart(), 3600 diag::ext_omp_loop_not_canonical_init) 3601 << S->getSourceRange(); 3602 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 3603 } 3604 } 3605 } 3606 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3607 if (CE->getOperator() == OO_Equal) { 3608 auto *LHS = CE->getArg(0); 3609 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3610 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3611 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3612 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3613 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 3614 } 3615 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3616 if (ME->isArrow() && 3617 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3618 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3619 } 3620 } 3621 } 3622 3623 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3624 return false; 3625 if (EmitDiags) { 3626 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 3627 << S->getSourceRange(); 3628 } 3629 return true; 3630 } 3631 3632 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 3633 /// variable (which may be the loop variable) if possible. 3634 static const ValueDecl *GetInitLCDecl(Expr *E) { 3635 if (!E) 3636 return nullptr; 3637 E = getExprAsWritten(E); 3638 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 3639 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3640 if ((Ctor->isCopyOrMoveConstructor() || 3641 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3642 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3643 E = CE->getArg(0)->IgnoreParenImpCasts(); 3644 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 3645 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 3646 return getCanonicalDecl(VD); 3647 } 3648 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 3649 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3650 return getCanonicalDecl(ME->getMemberDecl()); 3651 return nullptr; 3652 } 3653 3654 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 3655 // Check test-expr for canonical form, save upper-bound UB, flags for 3656 // less/greater and for strict/non-strict comparison. 3657 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3658 // var relational-op b 3659 // b relational-op var 3660 // 3661 if (!S) { 3662 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 3663 return true; 3664 } 3665 S = getExprAsWritten(S); 3666 SourceLocation CondLoc = S->getLocStart(); 3667 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3668 if (BO->isRelationalOp()) { 3669 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3670 return SetUB(BO->getRHS(), 3671 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 3672 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3673 BO->getSourceRange(), BO->getOperatorLoc()); 3674 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 3675 return SetUB(BO->getLHS(), 3676 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 3677 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3678 BO->getSourceRange(), BO->getOperatorLoc()); 3679 } 3680 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3681 if (CE->getNumArgs() == 2) { 3682 auto Op = CE->getOperator(); 3683 switch (Op) { 3684 case OO_Greater: 3685 case OO_GreaterEqual: 3686 case OO_Less: 3687 case OO_LessEqual: 3688 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3689 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 3690 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3691 CE->getOperatorLoc()); 3692 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 3693 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 3694 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3695 CE->getOperatorLoc()); 3696 break; 3697 default: 3698 break; 3699 } 3700 } 3701 } 3702 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3703 return false; 3704 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 3705 << S->getSourceRange() << LCDecl; 3706 return true; 3707 } 3708 3709 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 3710 // RHS of canonical loop form increment can be: 3711 // var + incr 3712 // incr + var 3713 // var - incr 3714 // 3715 RHS = RHS->IgnoreParenImpCasts(); 3716 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 3717 if (BO->isAdditiveOp()) { 3718 bool IsAdd = BO->getOpcode() == BO_Add; 3719 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3720 return SetStep(BO->getRHS(), !IsAdd); 3721 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 3722 return SetStep(BO->getLHS(), false); 3723 } 3724 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 3725 bool IsAdd = CE->getOperator() == OO_Plus; 3726 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 3727 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3728 return SetStep(CE->getArg(1), !IsAdd); 3729 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 3730 return SetStep(CE->getArg(0), false); 3731 } 3732 } 3733 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3734 return false; 3735 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3736 << RHS->getSourceRange() << LCDecl; 3737 return true; 3738 } 3739 3740 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 3741 // Check incr-expr for canonical loop form and return true if it 3742 // does not conform. 3743 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3744 // ++var 3745 // var++ 3746 // --var 3747 // var-- 3748 // var += incr 3749 // var -= incr 3750 // var = var + incr 3751 // var = incr + var 3752 // var = var - incr 3753 // 3754 if (!S) { 3755 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 3756 return true; 3757 } 3758 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3759 if (!ExprTemp->cleanupsHaveSideEffects()) 3760 S = ExprTemp->getSubExpr(); 3761 3762 IncrementSrcRange = S->getSourceRange(); 3763 S = S->IgnoreParens(); 3764 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 3765 if (UO->isIncrementDecrementOp() && 3766 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 3767 return SetStep(SemaRef 3768 .ActOnIntegerConstant(UO->getLocStart(), 3769 (UO->isDecrementOp() ? -1 : 1)) 3770 .get(), 3771 false); 3772 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3773 switch (BO->getOpcode()) { 3774 case BO_AddAssign: 3775 case BO_SubAssign: 3776 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3777 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 3778 break; 3779 case BO_Assign: 3780 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3781 return CheckIncRHS(BO->getRHS()); 3782 break; 3783 default: 3784 break; 3785 } 3786 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3787 switch (CE->getOperator()) { 3788 case OO_PlusPlus: 3789 case OO_MinusMinus: 3790 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3791 return SetStep(SemaRef 3792 .ActOnIntegerConstant( 3793 CE->getLocStart(), 3794 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 3795 .get(), 3796 false); 3797 break; 3798 case OO_PlusEqual: 3799 case OO_MinusEqual: 3800 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3801 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 3802 break; 3803 case OO_Equal: 3804 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3805 return CheckIncRHS(CE->getArg(1)); 3806 break; 3807 default: 3808 break; 3809 } 3810 } 3811 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3812 return false; 3813 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3814 << S->getSourceRange() << LCDecl; 3815 return true; 3816 } 3817 3818 static ExprResult 3819 tryBuildCapture(Sema &SemaRef, Expr *Capture, 3820 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3821 if (SemaRef.CurContext->isDependentContext()) 3822 return ExprResult(Capture); 3823 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 3824 return SemaRef.PerformImplicitConversion( 3825 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 3826 /*AllowExplicit=*/true); 3827 auto I = Captures.find(Capture); 3828 if (I != Captures.end()) 3829 return buildCapture(SemaRef, Capture, I->second); 3830 DeclRefExpr *Ref = nullptr; 3831 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 3832 Captures[Capture] = Ref; 3833 return Res; 3834 } 3835 3836 /// \brief Build the expression to calculate the number of iterations. 3837 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 3838 Scope *S, const bool LimitedType, 3839 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3840 ExprResult Diff; 3841 auto VarType = LCDecl->getType().getNonReferenceType(); 3842 if (VarType->isIntegerType() || VarType->isPointerType() || 3843 SemaRef.getLangOpts().CPlusPlus) { 3844 // Upper - Lower 3845 auto *UBExpr = TestIsLessOp ? UB : LB; 3846 auto *LBExpr = TestIsLessOp ? LB : UB; 3847 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 3848 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 3849 if (!Upper || !Lower) 3850 return nullptr; 3851 3852 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 3853 3854 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 3855 // BuildBinOp already emitted error, this one is to point user to upper 3856 // and lower bound, and to tell what is passed to 'operator-'. 3857 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 3858 << Upper->getSourceRange() << Lower->getSourceRange(); 3859 return nullptr; 3860 } 3861 } 3862 3863 if (!Diff.isUsable()) 3864 return nullptr; 3865 3866 // Upper - Lower [- 1] 3867 if (TestIsStrictOp) 3868 Diff = SemaRef.BuildBinOp( 3869 S, DefaultLoc, BO_Sub, Diff.get(), 3870 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3871 if (!Diff.isUsable()) 3872 return nullptr; 3873 3874 // Upper - Lower [- 1] + Step 3875 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 3876 if (!NewStep.isUsable()) 3877 return nullptr; 3878 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 3879 if (!Diff.isUsable()) 3880 return nullptr; 3881 3882 // Parentheses (for dumping/debugging purposes only). 3883 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 3884 if (!Diff.isUsable()) 3885 return nullptr; 3886 3887 // (Upper - Lower [- 1] + Step) / Step 3888 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 3889 if (!Diff.isUsable()) 3890 return nullptr; 3891 3892 // OpenMP runtime requires 32-bit or 64-bit loop variables. 3893 QualType Type = Diff.get()->getType(); 3894 auto &C = SemaRef.Context; 3895 bool UseVarType = VarType->hasIntegerRepresentation() && 3896 C.getTypeSize(Type) > C.getTypeSize(VarType); 3897 if (!Type->isIntegerType() || UseVarType) { 3898 unsigned NewSize = 3899 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 3900 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 3901 : Type->hasSignedIntegerRepresentation(); 3902 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 3903 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 3904 Diff = SemaRef.PerformImplicitConversion( 3905 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 3906 if (!Diff.isUsable()) 3907 return nullptr; 3908 } 3909 } 3910 if (LimitedType) { 3911 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 3912 if (NewSize != C.getTypeSize(Type)) { 3913 if (NewSize < C.getTypeSize(Type)) { 3914 assert(NewSize == 64 && "incorrect loop var size"); 3915 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 3916 << InitSrcRange << ConditionSrcRange; 3917 } 3918 QualType NewType = C.getIntTypeForBitwidth( 3919 NewSize, Type->hasSignedIntegerRepresentation() || 3920 C.getTypeSize(Type) < NewSize); 3921 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 3922 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 3923 Sema::AA_Converting, true); 3924 if (!Diff.isUsable()) 3925 return nullptr; 3926 } 3927 } 3928 } 3929 3930 return Diff.get(); 3931 } 3932 3933 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 3934 Scope *S, Expr *Cond, 3935 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3936 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 3937 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3938 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3939 3940 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 3941 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 3942 if (!NewLB.isUsable() || !NewUB.isUsable()) 3943 return nullptr; 3944 3945 auto CondExpr = SemaRef.BuildBinOp( 3946 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 3947 : (TestIsStrictOp ? BO_GT : BO_GE), 3948 NewLB.get(), NewUB.get()); 3949 if (CondExpr.isUsable()) { 3950 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 3951 SemaRef.Context.BoolTy)) 3952 CondExpr = SemaRef.PerformImplicitConversion( 3953 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 3954 /*AllowExplicit=*/true); 3955 } 3956 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3957 // Otherwise use original loop conditon and evaluate it in runtime. 3958 return CondExpr.isUsable() ? CondExpr.get() : Cond; 3959 } 3960 3961 /// \brief Build reference expression to the counter be used for codegen. 3962 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 3963 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 3964 auto *VD = dyn_cast<VarDecl>(LCDecl); 3965 if (!VD) { 3966 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 3967 auto *Ref = buildDeclRefExpr( 3968 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 3969 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 3970 // If the loop control decl is explicitly marked as private, do not mark it 3971 // as captured again. 3972 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 3973 Captures.insert(std::make_pair(LCRef, Ref)); 3974 return Ref; 3975 } 3976 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 3977 DefaultLoc); 3978 } 3979 3980 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 3981 if (LCDecl && !LCDecl->isInvalidDecl()) { 3982 auto Type = LCDecl->getType().getNonReferenceType(); 3983 auto *PrivateVar = 3984 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 3985 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 3986 if (PrivateVar->isInvalidDecl()) 3987 return nullptr; 3988 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 3989 } 3990 return nullptr; 3991 } 3992 3993 /// \brief Build initialization of the counter to be used for codegen. 3994 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 3995 3996 /// \brief Build step of the counter be used for codegen. 3997 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 3998 3999 /// \brief Iteration space of a single for loop. 4000 struct LoopIterationSpace final { 4001 /// \brief Condition of the loop. 4002 Expr *PreCond = nullptr; 4003 /// \brief This expression calculates the number of iterations in the loop. 4004 /// It is always possible to calculate it before starting the loop. 4005 Expr *NumIterations = nullptr; 4006 /// \brief The loop counter variable. 4007 Expr *CounterVar = nullptr; 4008 /// \brief Private loop counter variable. 4009 Expr *PrivateCounterVar = nullptr; 4010 /// \brief This is initializer for the initial value of #CounterVar. 4011 Expr *CounterInit = nullptr; 4012 /// \brief This is step for the #CounterVar used to generate its update: 4013 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 4014 Expr *CounterStep = nullptr; 4015 /// \brief Should step be subtracted? 4016 bool Subtract = false; 4017 /// \brief Source range of the loop init. 4018 SourceRange InitSrcRange; 4019 /// \brief Source range of the loop condition. 4020 SourceRange CondSrcRange; 4021 /// \brief Source range of the loop increment. 4022 SourceRange IncSrcRange; 4023 }; 4024 4025 } // namespace 4026 4027 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 4028 assert(getLangOpts().OpenMP && "OpenMP is not active."); 4029 assert(Init && "Expected loop in canonical form."); 4030 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 4031 if (AssociatedLoops > 0 && 4032 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 4033 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 4034 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 4035 if (auto *D = ISC.GetLoopDecl()) { 4036 auto *VD = dyn_cast<VarDecl>(D); 4037 if (!VD) { 4038 if (auto *Private = IsOpenMPCapturedDecl(D)) 4039 VD = Private; 4040 else { 4041 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 4042 /*WithInit=*/false); 4043 VD = cast<VarDecl>(Ref->getDecl()); 4044 } 4045 } 4046 DSAStack->addLoopControlVariable(D, VD); 4047 } 4048 } 4049 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 4050 } 4051 } 4052 4053 /// \brief Called on a for stmt to check and extract its iteration space 4054 /// for further processing (such as collapsing). 4055 static bool CheckOpenMPIterationSpace( 4056 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 4057 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 4058 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 4059 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 4060 LoopIterationSpace &ResultIterSpace, 4061 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4062 // OpenMP [2.6, Canonical Loop Form] 4063 // for (init-expr; test-expr; incr-expr) structured-block 4064 auto *For = dyn_cast_or_null<ForStmt>(S); 4065 if (!For) { 4066 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 4067 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 4068 << getOpenMPDirectiveName(DKind) << NestedLoopCount 4069 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 4070 if (NestedLoopCount > 1) { 4071 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 4072 SemaRef.Diag(DSA.getConstructLoc(), 4073 diag::note_omp_collapse_ordered_expr) 4074 << 2 << CollapseLoopCountExpr->getSourceRange() 4075 << OrderedLoopCountExpr->getSourceRange(); 4076 else if (CollapseLoopCountExpr) 4077 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4078 diag::note_omp_collapse_ordered_expr) 4079 << 0 << CollapseLoopCountExpr->getSourceRange(); 4080 else 4081 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4082 diag::note_omp_collapse_ordered_expr) 4083 << 1 << OrderedLoopCountExpr->getSourceRange(); 4084 } 4085 return true; 4086 } 4087 assert(For->getBody()); 4088 4089 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 4090 4091 // Check init. 4092 auto Init = For->getInit(); 4093 if (ISC.CheckInit(Init)) 4094 return true; 4095 4096 bool HasErrors = false; 4097 4098 // Check loop variable's type. 4099 if (auto *LCDecl = ISC.GetLoopDecl()) { 4100 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 4101 4102 // OpenMP [2.6, Canonical Loop Form] 4103 // Var is one of the following: 4104 // A variable of signed or unsigned integer type. 4105 // For C++, a variable of a random access iterator type. 4106 // For C, a variable of a pointer type. 4107 auto VarType = LCDecl->getType().getNonReferenceType(); 4108 if (!VarType->isDependentType() && !VarType->isIntegerType() && 4109 !VarType->isPointerType() && 4110 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 4111 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 4112 << SemaRef.getLangOpts().CPlusPlus; 4113 HasErrors = true; 4114 } 4115 4116 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 4117 // a Construct 4118 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4119 // parallel for construct is (are) private. 4120 // The loop iteration variable in the associated for-loop of a simd 4121 // construct with just one associated for-loop is linear with a 4122 // constant-linear-step that is the increment of the associated for-loop. 4123 // Exclude loop var from the list of variables with implicitly defined data 4124 // sharing attributes. 4125 VarsWithImplicitDSA.erase(LCDecl); 4126 4127 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4128 // in a Construct, C/C++]. 4129 // The loop iteration variable in the associated for-loop of a simd 4130 // construct with just one associated for-loop may be listed in a linear 4131 // clause with a constant-linear-step that is the increment of the 4132 // associated for-loop. 4133 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4134 // parallel for construct may be listed in a private or lastprivate clause. 4135 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 4136 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 4137 // declared in the loop and it is predetermined as a private. 4138 auto PredeterminedCKind = 4139 isOpenMPSimdDirective(DKind) 4140 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 4141 : OMPC_private; 4142 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4143 DVar.CKind != PredeterminedCKind) || 4144 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 4145 isOpenMPDistributeDirective(DKind)) && 4146 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4147 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 4148 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 4149 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 4150 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 4151 << getOpenMPClauseName(PredeterminedCKind); 4152 if (DVar.RefExpr == nullptr) 4153 DVar.CKind = PredeterminedCKind; 4154 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 4155 HasErrors = true; 4156 } else if (LoopDeclRefExpr != nullptr) { 4157 // Make the loop iteration variable private (for worksharing constructs), 4158 // linear (for simd directives with the only one associated loop) or 4159 // lastprivate (for simd directives with several collapsed or ordered 4160 // loops). 4161 if (DVar.CKind == OMPC_unknown) 4162 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 4163 [](OpenMPDirectiveKind) -> bool { return true; }, 4164 /*FromParent=*/false); 4165 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 4166 } 4167 4168 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 4169 4170 // Check test-expr. 4171 HasErrors |= ISC.CheckCond(For->getCond()); 4172 4173 // Check incr-expr. 4174 HasErrors |= ISC.CheckInc(For->getInc()); 4175 } 4176 4177 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 4178 return HasErrors; 4179 4180 // Build the loop's iteration space representation. 4181 ResultIterSpace.PreCond = 4182 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 4183 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 4184 DSA.getCurScope(), 4185 (isOpenMPWorksharingDirective(DKind) || 4186 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 4187 Captures); 4188 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 4189 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 4190 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 4191 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 4192 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 4193 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 4194 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 4195 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 4196 4197 HasErrors |= (ResultIterSpace.PreCond == nullptr || 4198 ResultIterSpace.NumIterations == nullptr || 4199 ResultIterSpace.CounterVar == nullptr || 4200 ResultIterSpace.PrivateCounterVar == nullptr || 4201 ResultIterSpace.CounterInit == nullptr || 4202 ResultIterSpace.CounterStep == nullptr); 4203 4204 return HasErrors; 4205 } 4206 4207 /// \brief Build 'VarRef = Start. 4208 static ExprResult 4209 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 4210 ExprResult Start, 4211 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4212 // Build 'VarRef = Start. 4213 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 4214 if (!NewStart.isUsable()) 4215 return ExprError(); 4216 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 4217 VarRef.get()->getType())) { 4218 NewStart = SemaRef.PerformImplicitConversion( 4219 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 4220 /*AllowExplicit=*/true); 4221 if (!NewStart.isUsable()) 4222 return ExprError(); 4223 } 4224 4225 auto Init = 4226 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4227 return Init; 4228 } 4229 4230 /// \brief Build 'VarRef = Start + Iter * Step'. 4231 static ExprResult 4232 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 4233 ExprResult VarRef, ExprResult Start, ExprResult Iter, 4234 ExprResult Step, bool Subtract, 4235 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 4236 // Add parentheses (for debugging purposes only). 4237 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 4238 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 4239 !Step.isUsable()) 4240 return ExprError(); 4241 4242 ExprResult NewStep = Step; 4243 if (Captures) 4244 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 4245 if (NewStep.isInvalid()) 4246 return ExprError(); 4247 ExprResult Update = 4248 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 4249 if (!Update.isUsable()) 4250 return ExprError(); 4251 4252 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 4253 // 'VarRef = Start (+|-) Iter * Step'. 4254 ExprResult NewStart = Start; 4255 if (Captures) 4256 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 4257 if (NewStart.isInvalid()) 4258 return ExprError(); 4259 4260 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 4261 ExprResult SavedUpdate = Update; 4262 ExprResult UpdateVal; 4263 if (VarRef.get()->getType()->isOverloadableType() || 4264 NewStart.get()->getType()->isOverloadableType() || 4265 Update.get()->getType()->isOverloadableType()) { 4266 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4267 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4268 Update = 4269 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4270 if (Update.isUsable()) { 4271 UpdateVal = 4272 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 4273 VarRef.get(), SavedUpdate.get()); 4274 if (UpdateVal.isUsable()) { 4275 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 4276 UpdateVal.get()); 4277 } 4278 } 4279 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4280 } 4281 4282 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 4283 if (!Update.isUsable() || !UpdateVal.isUsable()) { 4284 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 4285 NewStart.get(), SavedUpdate.get()); 4286 if (!Update.isUsable()) 4287 return ExprError(); 4288 4289 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 4290 VarRef.get()->getType())) { 4291 Update = SemaRef.PerformImplicitConversion( 4292 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 4293 if (!Update.isUsable()) 4294 return ExprError(); 4295 } 4296 4297 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 4298 } 4299 return Update; 4300 } 4301 4302 /// \brief Convert integer expression \a E to make it have at least \a Bits 4303 /// bits. 4304 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 4305 if (E == nullptr) 4306 return ExprError(); 4307 auto &C = SemaRef.Context; 4308 QualType OldType = E->getType(); 4309 unsigned HasBits = C.getTypeSize(OldType); 4310 if (HasBits >= Bits) 4311 return ExprResult(E); 4312 // OK to convert to signed, because new type has more bits than old. 4313 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 4314 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 4315 true); 4316 } 4317 4318 /// \brief Check if the given expression \a E is a constant integer that fits 4319 /// into \a Bits bits. 4320 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 4321 if (E == nullptr) 4322 return false; 4323 llvm::APSInt Result; 4324 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 4325 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 4326 return false; 4327 } 4328 4329 /// Build preinits statement for the given declarations. 4330 static Stmt *buildPreInits(ASTContext &Context, 4331 MutableArrayRef<Decl *> PreInits) { 4332 if (!PreInits.empty()) { 4333 return new (Context) DeclStmt( 4334 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 4335 SourceLocation(), SourceLocation()); 4336 } 4337 return nullptr; 4338 } 4339 4340 /// Build preinits statement for the given declarations. 4341 static Stmt * 4342 buildPreInits(ASTContext &Context, 4343 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4344 if (!Captures.empty()) { 4345 SmallVector<Decl *, 16> PreInits; 4346 for (auto &Pair : Captures) 4347 PreInits.push_back(Pair.second->getDecl()); 4348 return buildPreInits(Context, PreInits); 4349 } 4350 return nullptr; 4351 } 4352 4353 /// Build postupdate expression for the given list of postupdates expressions. 4354 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 4355 Expr *PostUpdate = nullptr; 4356 if (!PostUpdates.empty()) { 4357 for (auto *E : PostUpdates) { 4358 Expr *ConvE = S.BuildCStyleCastExpr( 4359 E->getExprLoc(), 4360 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 4361 E->getExprLoc(), E) 4362 .get(); 4363 PostUpdate = PostUpdate 4364 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 4365 PostUpdate, ConvE) 4366 .get() 4367 : ConvE; 4368 } 4369 } 4370 return PostUpdate; 4371 } 4372 4373 /// \brief Called on a for stmt to check itself and nested loops (if any). 4374 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 4375 /// number of collapsed loops otherwise. 4376 static unsigned 4377 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 4378 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 4379 DSAStackTy &DSA, 4380 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 4381 OMPLoopDirective::HelperExprs &Built) { 4382 unsigned NestedLoopCount = 1; 4383 if (CollapseLoopCountExpr) { 4384 // Found 'collapse' clause - calculate collapse number. 4385 llvm::APSInt Result; 4386 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 4387 NestedLoopCount = Result.getLimitedValue(); 4388 } 4389 if (OrderedLoopCountExpr) { 4390 // Found 'ordered' clause - calculate collapse number. 4391 llvm::APSInt Result; 4392 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 4393 if (Result.getLimitedValue() < NestedLoopCount) { 4394 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4395 diag::err_omp_wrong_ordered_loop_count) 4396 << OrderedLoopCountExpr->getSourceRange(); 4397 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4398 diag::note_collapse_loop_count) 4399 << CollapseLoopCountExpr->getSourceRange(); 4400 } 4401 NestedLoopCount = Result.getLimitedValue(); 4402 } 4403 } 4404 // This is helper routine for loop directives (e.g., 'for', 'simd', 4405 // 'for simd', etc.). 4406 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 4407 SmallVector<LoopIterationSpace, 4> IterSpaces; 4408 IterSpaces.resize(NestedLoopCount); 4409 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 4410 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 4411 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 4412 NestedLoopCount, CollapseLoopCountExpr, 4413 OrderedLoopCountExpr, VarsWithImplicitDSA, 4414 IterSpaces[Cnt], Captures)) 4415 return 0; 4416 // Move on to the next nested for loop, or to the loop body. 4417 // OpenMP [2.8.1, simd construct, Restrictions] 4418 // All loops associated with the construct must be perfectly nested; that 4419 // is, there must be no intervening code nor any OpenMP directive between 4420 // any two loops. 4421 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 4422 } 4423 4424 Built.clear(/* size */ NestedLoopCount); 4425 4426 if (SemaRef.CurContext->isDependentContext()) 4427 return NestedLoopCount; 4428 4429 // An example of what is generated for the following code: 4430 // 4431 // #pragma omp simd collapse(2) ordered(2) 4432 // for (i = 0; i < NI; ++i) 4433 // for (k = 0; k < NK; ++k) 4434 // for (j = J0; j < NJ; j+=2) { 4435 // <loop body> 4436 // } 4437 // 4438 // We generate the code below. 4439 // Note: the loop body may be outlined in CodeGen. 4440 // Note: some counters may be C++ classes, operator- is used to find number of 4441 // iterations and operator+= to calculate counter value. 4442 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 4443 // or i64 is currently supported). 4444 // 4445 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 4446 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 4447 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 4448 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 4449 // // similar updates for vars in clauses (e.g. 'linear') 4450 // <loop body (using local i and j)> 4451 // } 4452 // i = NI; // assign final values of counters 4453 // j = NJ; 4454 // 4455 4456 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 4457 // the iteration counts of the collapsed for loops. 4458 // Precondition tests if there is at least one iteration (all conditions are 4459 // true). 4460 auto PreCond = ExprResult(IterSpaces[0].PreCond); 4461 auto N0 = IterSpaces[0].NumIterations; 4462 ExprResult LastIteration32 = WidenIterationCount( 4463 32 /* Bits */, SemaRef 4464 .PerformImplicitConversion( 4465 N0->IgnoreImpCasts(), N0->getType(), 4466 Sema::AA_Converting, /*AllowExplicit=*/true) 4467 .get(), 4468 SemaRef); 4469 ExprResult LastIteration64 = WidenIterationCount( 4470 64 /* Bits */, SemaRef 4471 .PerformImplicitConversion( 4472 N0->IgnoreImpCasts(), N0->getType(), 4473 Sema::AA_Converting, /*AllowExplicit=*/true) 4474 .get(), 4475 SemaRef); 4476 4477 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 4478 return NestedLoopCount; 4479 4480 auto &C = SemaRef.Context; 4481 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 4482 4483 Scope *CurScope = DSA.getCurScope(); 4484 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 4485 if (PreCond.isUsable()) { 4486 PreCond = 4487 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 4488 PreCond.get(), IterSpaces[Cnt].PreCond); 4489 } 4490 auto N = IterSpaces[Cnt].NumIterations; 4491 SourceLocation Loc = N->getExprLoc(); 4492 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 4493 if (LastIteration32.isUsable()) 4494 LastIteration32 = SemaRef.BuildBinOp( 4495 CurScope, Loc, BO_Mul, LastIteration32.get(), 4496 SemaRef 4497 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4498 Sema::AA_Converting, 4499 /*AllowExplicit=*/true) 4500 .get()); 4501 if (LastIteration64.isUsable()) 4502 LastIteration64 = SemaRef.BuildBinOp( 4503 CurScope, Loc, BO_Mul, LastIteration64.get(), 4504 SemaRef 4505 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4506 Sema::AA_Converting, 4507 /*AllowExplicit=*/true) 4508 .get()); 4509 } 4510 4511 // Choose either the 32-bit or 64-bit version. 4512 ExprResult LastIteration = LastIteration64; 4513 if (LastIteration32.isUsable() && 4514 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 4515 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 4516 FitsInto( 4517 32 /* Bits */, 4518 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 4519 LastIteration64.get(), SemaRef))) 4520 LastIteration = LastIteration32; 4521 QualType VType = LastIteration.get()->getType(); 4522 QualType RealVType = VType; 4523 QualType StrideVType = VType; 4524 if (isOpenMPTaskLoopDirective(DKind)) { 4525 VType = 4526 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 4527 StrideVType = 4528 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 4529 } 4530 4531 if (!LastIteration.isUsable()) 4532 return 0; 4533 4534 // Save the number of iterations. 4535 ExprResult NumIterations = LastIteration; 4536 { 4537 LastIteration = SemaRef.BuildBinOp( 4538 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 4539 LastIteration.get(), 4540 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4541 if (!LastIteration.isUsable()) 4542 return 0; 4543 } 4544 4545 // Calculate the last iteration number beforehand instead of doing this on 4546 // each iteration. Do not do this if the number of iterations may be kfold-ed. 4547 llvm::APSInt Result; 4548 bool IsConstant = 4549 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 4550 ExprResult CalcLastIteration; 4551 if (!IsConstant) { 4552 ExprResult SaveRef = 4553 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 4554 LastIteration = SaveRef; 4555 4556 // Prepare SaveRef + 1. 4557 NumIterations = SemaRef.BuildBinOp( 4558 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 4559 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4560 if (!NumIterations.isUsable()) 4561 return 0; 4562 } 4563 4564 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 4565 4566 // Build variables passed into runtime, necessary for worksharing directives. 4567 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 4568 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4569 isOpenMPDistributeDirective(DKind)) { 4570 // Lower bound variable, initialized with zero. 4571 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 4572 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 4573 SemaRef.AddInitializerToDecl(LBDecl, 4574 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4575 /*DirectInit*/ false); 4576 4577 // Upper bound variable, initialized with last iteration number. 4578 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 4579 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 4580 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 4581 /*DirectInit*/ false); 4582 4583 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 4584 // This will be used to implement clause 'lastprivate'. 4585 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 4586 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 4587 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 4588 SemaRef.AddInitializerToDecl(ILDecl, 4589 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4590 /*DirectInit*/ false); 4591 4592 // Stride variable returned by runtime (we initialize it to 1 by default). 4593 VarDecl *STDecl = 4594 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 4595 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 4596 SemaRef.AddInitializerToDecl(STDecl, 4597 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 4598 /*DirectInit*/ false); 4599 4600 // Build expression: UB = min(UB, LastIteration) 4601 // It is necessary for CodeGen of directives with static scheduling. 4602 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 4603 UB.get(), LastIteration.get()); 4604 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4605 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 4606 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 4607 CondOp.get()); 4608 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 4609 4610 // If we have a combined directive that combines 'distribute', 'for' or 4611 // 'simd' we need to be able to access the bounds of the schedule of the 4612 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 4613 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 4614 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4615 4616 // Lower bound variable, initialized with zero. 4617 VarDecl *CombLBDecl = 4618 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 4619 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 4620 SemaRef.AddInitializerToDecl( 4621 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4622 /*DirectInit*/ false); 4623 4624 // Upper bound variable, initialized with last iteration number. 4625 VarDecl *CombUBDecl = 4626 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 4627 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 4628 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 4629 /*DirectInit*/ false); 4630 4631 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 4632 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 4633 ExprResult CombCondOp = 4634 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 4635 LastIteration.get(), CombUB.get()); 4636 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 4637 CombCondOp.get()); 4638 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get()); 4639 4640 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 4641 // We expect to have at least 2 more parameters than the 'parallel' 4642 // directive does - the lower and upper bounds of the previous schedule. 4643 assert(CD->getNumParams() >= 4 && 4644 "Unexpected number of parameters in loop combined directive"); 4645 4646 // Set the proper type for the bounds given what we learned from the 4647 // enclosed loops. 4648 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 4649 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 4650 4651 // Previous lower and upper bounds are obtained from the region 4652 // parameters. 4653 PrevLB = 4654 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 4655 PrevUB = 4656 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 4657 } 4658 } 4659 4660 // Build the iteration variable and its initialization before loop. 4661 ExprResult IV; 4662 ExprResult Init, CombInit; 4663 { 4664 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 4665 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 4666 Expr *RHS = 4667 (isOpenMPWorksharingDirective(DKind) || 4668 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4669 ? LB.get() 4670 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4671 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 4672 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 4673 4674 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4675 Expr *CombRHS = 4676 (isOpenMPWorksharingDirective(DKind) || 4677 isOpenMPTaskLoopDirective(DKind) || 4678 isOpenMPDistributeDirective(DKind)) 4679 ? CombLB.get() 4680 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4681 CombInit = 4682 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 4683 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get()); 4684 } 4685 } 4686 4687 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 4688 SourceLocation CondLoc; 4689 ExprResult Cond = 4690 (isOpenMPWorksharingDirective(DKind) || 4691 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4692 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 4693 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 4694 NumIterations.get()); 4695 ExprResult CombCond; 4696 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4697 CombCond = 4698 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get()); 4699 } 4700 // Loop increment (IV = IV + 1) 4701 SourceLocation IncLoc; 4702 ExprResult Inc = 4703 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 4704 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 4705 if (!Inc.isUsable()) 4706 return 0; 4707 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 4708 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 4709 if (!Inc.isUsable()) 4710 return 0; 4711 4712 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 4713 // Used for directives with static scheduling. 4714 // In combined construct, add combined version that use CombLB and CombUB 4715 // base variables for the update 4716 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 4717 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4718 isOpenMPDistributeDirective(DKind)) { 4719 // LB + ST 4720 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 4721 if (!NextLB.isUsable()) 4722 return 0; 4723 // LB = LB + ST 4724 NextLB = 4725 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 4726 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 4727 if (!NextLB.isUsable()) 4728 return 0; 4729 // UB + ST 4730 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 4731 if (!NextUB.isUsable()) 4732 return 0; 4733 // UB = UB + ST 4734 NextUB = 4735 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 4736 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 4737 if (!NextUB.isUsable()) 4738 return 0; 4739 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4740 CombNextLB = 4741 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 4742 if (!NextLB.isUsable()) 4743 return 0; 4744 // LB = LB + ST 4745 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 4746 CombNextLB.get()); 4747 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get()); 4748 if (!CombNextLB.isUsable()) 4749 return 0; 4750 // UB + ST 4751 CombNextUB = 4752 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 4753 if (!CombNextUB.isUsable()) 4754 return 0; 4755 // UB = UB + ST 4756 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 4757 CombNextUB.get()); 4758 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get()); 4759 if (!CombNextUB.isUsable()) 4760 return 0; 4761 } 4762 } 4763 4764 // Create increment expression for distribute loop when combined in a same 4765 // directive with for as IV = IV + ST; ensure upper bound expression based 4766 // on PrevUB instead of NumIterations - used to implement 'for' when found 4767 // in combination with 'distribute', like in 'distribute parallel for' 4768 SourceLocation DistIncLoc; 4769 ExprResult DistCond, DistInc, PrevEUB; 4770 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4771 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()); 4772 assert(DistCond.isUsable() && "distribute cond expr was not built"); 4773 4774 DistInc = 4775 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 4776 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4777 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 4778 DistInc.get()); 4779 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get()); 4780 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4781 4782 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 4783 // construct 4784 SourceLocation DistEUBLoc; 4785 ExprResult IsUBGreater = 4786 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 4787 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4788 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 4789 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 4790 CondOp.get()); 4791 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get()); 4792 } 4793 4794 // Build updates and final values of the loop counters. 4795 bool HasErrors = false; 4796 Built.Counters.resize(NestedLoopCount); 4797 Built.Inits.resize(NestedLoopCount); 4798 Built.Updates.resize(NestedLoopCount); 4799 Built.Finals.resize(NestedLoopCount); 4800 SmallVector<Expr *, 4> LoopMultipliers; 4801 { 4802 ExprResult Div; 4803 // Go from inner nested loop to outer. 4804 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4805 LoopIterationSpace &IS = IterSpaces[Cnt]; 4806 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 4807 // Build: Iter = (IV / Div) % IS.NumIters 4808 // where Div is product of previous iterations' IS.NumIters. 4809 ExprResult Iter; 4810 if (Div.isUsable()) { 4811 Iter = 4812 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 4813 } else { 4814 Iter = IV; 4815 assert((Cnt == (int)NestedLoopCount - 1) && 4816 "unusable div expected on first iteration only"); 4817 } 4818 4819 if (Cnt != 0 && Iter.isUsable()) 4820 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 4821 IS.NumIterations); 4822 if (!Iter.isUsable()) { 4823 HasErrors = true; 4824 break; 4825 } 4826 4827 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 4828 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 4829 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 4830 IS.CounterVar->getExprLoc(), 4831 /*RefersToCapture=*/true); 4832 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 4833 IS.CounterInit, Captures); 4834 if (!Init.isUsable()) { 4835 HasErrors = true; 4836 break; 4837 } 4838 ExprResult Update = BuildCounterUpdate( 4839 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 4840 IS.CounterStep, IS.Subtract, &Captures); 4841 if (!Update.isUsable()) { 4842 HasErrors = true; 4843 break; 4844 } 4845 4846 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 4847 ExprResult Final = BuildCounterUpdate( 4848 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 4849 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 4850 if (!Final.isUsable()) { 4851 HasErrors = true; 4852 break; 4853 } 4854 4855 // Build Div for the next iteration: Div <- Div * IS.NumIters 4856 if (Cnt != 0) { 4857 if (Div.isUnset()) 4858 Div = IS.NumIterations; 4859 else 4860 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 4861 IS.NumIterations); 4862 4863 // Add parentheses (for debugging purposes only). 4864 if (Div.isUsable()) 4865 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 4866 if (!Div.isUsable()) { 4867 HasErrors = true; 4868 break; 4869 } 4870 LoopMultipliers.push_back(Div.get()); 4871 } 4872 if (!Update.isUsable() || !Final.isUsable()) { 4873 HasErrors = true; 4874 break; 4875 } 4876 // Save results 4877 Built.Counters[Cnt] = IS.CounterVar; 4878 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 4879 Built.Inits[Cnt] = Init.get(); 4880 Built.Updates[Cnt] = Update.get(); 4881 Built.Finals[Cnt] = Final.get(); 4882 } 4883 } 4884 4885 if (HasErrors) 4886 return 0; 4887 4888 // Save results 4889 Built.IterationVarRef = IV.get(); 4890 Built.LastIteration = LastIteration.get(); 4891 Built.NumIterations = NumIterations.get(); 4892 Built.CalcLastIteration = 4893 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 4894 Built.PreCond = PreCond.get(); 4895 Built.PreInits = buildPreInits(C, Captures); 4896 Built.Cond = Cond.get(); 4897 Built.Init = Init.get(); 4898 Built.Inc = Inc.get(); 4899 Built.LB = LB.get(); 4900 Built.UB = UB.get(); 4901 Built.IL = IL.get(); 4902 Built.ST = ST.get(); 4903 Built.EUB = EUB.get(); 4904 Built.NLB = NextLB.get(); 4905 Built.NUB = NextUB.get(); 4906 Built.PrevLB = PrevLB.get(); 4907 Built.PrevUB = PrevUB.get(); 4908 Built.DistInc = DistInc.get(); 4909 Built.PrevEUB = PrevEUB.get(); 4910 Built.DistCombinedFields.LB = CombLB.get(); 4911 Built.DistCombinedFields.UB = CombUB.get(); 4912 Built.DistCombinedFields.EUB = CombEUB.get(); 4913 Built.DistCombinedFields.Init = CombInit.get(); 4914 Built.DistCombinedFields.Cond = CombCond.get(); 4915 Built.DistCombinedFields.NLB = CombNextLB.get(); 4916 Built.DistCombinedFields.NUB = CombNextUB.get(); 4917 4918 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 4919 // Fill data for doacross depend clauses. 4920 for (auto Pair : DSA.getDoacrossDependClauses()) { 4921 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 4922 Pair.first->setCounterValue(CounterVal); 4923 else { 4924 if (NestedLoopCount != Pair.second.size() || 4925 NestedLoopCount != LoopMultipliers.size() + 1) { 4926 // Erroneous case - clause has some problems. 4927 Pair.first->setCounterValue(CounterVal); 4928 continue; 4929 } 4930 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 4931 auto I = Pair.second.rbegin(); 4932 auto IS = IterSpaces.rbegin(); 4933 auto ILM = LoopMultipliers.rbegin(); 4934 Expr *UpCounterVal = CounterVal; 4935 Expr *Multiplier = nullptr; 4936 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4937 if (I->first) { 4938 assert(IS->CounterStep); 4939 Expr *NormalizedOffset = 4940 SemaRef 4941 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 4942 I->first, IS->CounterStep) 4943 .get(); 4944 if (Multiplier) { 4945 NormalizedOffset = 4946 SemaRef 4947 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 4948 NormalizedOffset, Multiplier) 4949 .get(); 4950 } 4951 assert(I->second == OO_Plus || I->second == OO_Minus); 4952 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 4953 UpCounterVal = SemaRef 4954 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 4955 UpCounterVal, NormalizedOffset) 4956 .get(); 4957 } 4958 Multiplier = *ILM; 4959 ++I; 4960 ++IS; 4961 ++ILM; 4962 } 4963 Pair.first->setCounterValue(UpCounterVal); 4964 } 4965 } 4966 4967 return NestedLoopCount; 4968 } 4969 4970 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 4971 auto CollapseClauses = 4972 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 4973 if (CollapseClauses.begin() != CollapseClauses.end()) 4974 return (*CollapseClauses.begin())->getNumForLoops(); 4975 return nullptr; 4976 } 4977 4978 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 4979 auto OrderedClauses = 4980 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 4981 if (OrderedClauses.begin() != OrderedClauses.end()) 4982 return (*OrderedClauses.begin())->getNumForLoops(); 4983 return nullptr; 4984 } 4985 4986 static bool checkSimdlenSafelenSpecified(Sema &S, 4987 const ArrayRef<OMPClause *> Clauses) { 4988 OMPSafelenClause *Safelen = nullptr; 4989 OMPSimdlenClause *Simdlen = nullptr; 4990 4991 for (auto *Clause : Clauses) { 4992 if (Clause->getClauseKind() == OMPC_safelen) 4993 Safelen = cast<OMPSafelenClause>(Clause); 4994 else if (Clause->getClauseKind() == OMPC_simdlen) 4995 Simdlen = cast<OMPSimdlenClause>(Clause); 4996 if (Safelen && Simdlen) 4997 break; 4998 } 4999 5000 if (Simdlen && Safelen) { 5001 llvm::APSInt SimdlenRes, SafelenRes; 5002 auto SimdlenLength = Simdlen->getSimdlen(); 5003 auto SafelenLength = Safelen->getSafelen(); 5004 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 5005 SimdlenLength->isInstantiationDependent() || 5006 SimdlenLength->containsUnexpandedParameterPack()) 5007 return false; 5008 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 5009 SafelenLength->isInstantiationDependent() || 5010 SafelenLength->containsUnexpandedParameterPack()) 5011 return false; 5012 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 5013 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 5014 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 5015 // If both simdlen and safelen clauses are specified, the value of the 5016 // simdlen parameter must be less than or equal to the value of the safelen 5017 // parameter. 5018 if (SimdlenRes > SafelenRes) { 5019 S.Diag(SimdlenLength->getExprLoc(), 5020 diag::err_omp_wrong_simdlen_safelen_values) 5021 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 5022 return true; 5023 } 5024 } 5025 return false; 5026 } 5027 5028 StmtResult Sema::ActOnOpenMPSimdDirective( 5029 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5030 SourceLocation EndLoc, 5031 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5032 if (!AStmt) 5033 return StmtError(); 5034 5035 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5036 OMPLoopDirective::HelperExprs B; 5037 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5038 // define the nested loops number. 5039 unsigned NestedLoopCount = CheckOpenMPLoop( 5040 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5041 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5042 if (NestedLoopCount == 0) 5043 return StmtError(); 5044 5045 assert((CurContext->isDependentContext() || B.builtAll()) && 5046 "omp simd loop exprs were not built"); 5047 5048 if (!CurContext->isDependentContext()) { 5049 // Finalize the clauses that need pre-built expressions for CodeGen. 5050 for (auto C : Clauses) { 5051 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5052 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5053 B.NumIterations, *this, CurScope, 5054 DSAStack)) 5055 return StmtError(); 5056 } 5057 } 5058 5059 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5060 return StmtError(); 5061 5062 getCurFunction()->setHasBranchProtectedScope(); 5063 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5064 Clauses, AStmt, B); 5065 } 5066 5067 StmtResult Sema::ActOnOpenMPForDirective( 5068 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5069 SourceLocation EndLoc, 5070 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5071 if (!AStmt) 5072 return StmtError(); 5073 5074 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5075 OMPLoopDirective::HelperExprs B; 5076 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5077 // define the nested loops number. 5078 unsigned NestedLoopCount = CheckOpenMPLoop( 5079 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5080 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5081 if (NestedLoopCount == 0) 5082 return StmtError(); 5083 5084 assert((CurContext->isDependentContext() || B.builtAll()) && 5085 "omp for loop exprs were not built"); 5086 5087 if (!CurContext->isDependentContext()) { 5088 // Finalize the clauses that need pre-built expressions for CodeGen. 5089 for (auto C : Clauses) { 5090 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5091 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5092 B.NumIterations, *this, CurScope, 5093 DSAStack)) 5094 return StmtError(); 5095 } 5096 } 5097 5098 getCurFunction()->setHasBranchProtectedScope(); 5099 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5100 Clauses, AStmt, B, DSAStack->isCancelRegion()); 5101 } 5102 5103 StmtResult Sema::ActOnOpenMPForSimdDirective( 5104 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5105 SourceLocation EndLoc, 5106 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5107 if (!AStmt) 5108 return StmtError(); 5109 5110 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5111 OMPLoopDirective::HelperExprs B; 5112 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5113 // define the nested loops number. 5114 unsigned NestedLoopCount = 5115 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 5116 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5117 VarsWithImplicitDSA, B); 5118 if (NestedLoopCount == 0) 5119 return StmtError(); 5120 5121 assert((CurContext->isDependentContext() || B.builtAll()) && 5122 "omp for simd loop exprs were not built"); 5123 5124 if (!CurContext->isDependentContext()) { 5125 // Finalize the clauses that need pre-built expressions for CodeGen. 5126 for (auto C : Clauses) { 5127 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5128 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5129 B.NumIterations, *this, CurScope, 5130 DSAStack)) 5131 return StmtError(); 5132 } 5133 } 5134 5135 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5136 return StmtError(); 5137 5138 getCurFunction()->setHasBranchProtectedScope(); 5139 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5140 Clauses, AStmt, B); 5141 } 5142 5143 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 5144 Stmt *AStmt, 5145 SourceLocation StartLoc, 5146 SourceLocation EndLoc) { 5147 if (!AStmt) 5148 return StmtError(); 5149 5150 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5151 auto BaseStmt = AStmt; 5152 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5153 BaseStmt = CS->getCapturedStmt(); 5154 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5155 auto S = C->children(); 5156 if (S.begin() == S.end()) 5157 return StmtError(); 5158 // All associated statements must be '#pragma omp section' except for 5159 // the first one. 5160 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5161 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5162 if (SectionStmt) 5163 Diag(SectionStmt->getLocStart(), 5164 diag::err_omp_sections_substmt_not_section); 5165 return StmtError(); 5166 } 5167 cast<OMPSectionDirective>(SectionStmt) 5168 ->setHasCancel(DSAStack->isCancelRegion()); 5169 } 5170 } else { 5171 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 5172 return StmtError(); 5173 } 5174 5175 getCurFunction()->setHasBranchProtectedScope(); 5176 5177 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5178 DSAStack->isCancelRegion()); 5179 } 5180 5181 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 5182 SourceLocation StartLoc, 5183 SourceLocation EndLoc) { 5184 if (!AStmt) 5185 return StmtError(); 5186 5187 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5188 5189 getCurFunction()->setHasBranchProtectedScope(); 5190 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 5191 5192 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 5193 DSAStack->isCancelRegion()); 5194 } 5195 5196 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 5197 Stmt *AStmt, 5198 SourceLocation StartLoc, 5199 SourceLocation EndLoc) { 5200 if (!AStmt) 5201 return StmtError(); 5202 5203 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5204 5205 getCurFunction()->setHasBranchProtectedScope(); 5206 5207 // OpenMP [2.7.3, single Construct, Restrictions] 5208 // The copyprivate clause must not be used with the nowait clause. 5209 OMPClause *Nowait = nullptr; 5210 OMPClause *Copyprivate = nullptr; 5211 for (auto *Clause : Clauses) { 5212 if (Clause->getClauseKind() == OMPC_nowait) 5213 Nowait = Clause; 5214 else if (Clause->getClauseKind() == OMPC_copyprivate) 5215 Copyprivate = Clause; 5216 if (Copyprivate && Nowait) { 5217 Diag(Copyprivate->getLocStart(), 5218 diag::err_omp_single_copyprivate_with_nowait); 5219 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 5220 return StmtError(); 5221 } 5222 } 5223 5224 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5225 } 5226 5227 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 5228 SourceLocation StartLoc, 5229 SourceLocation EndLoc) { 5230 if (!AStmt) 5231 return StmtError(); 5232 5233 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5234 5235 getCurFunction()->setHasBranchProtectedScope(); 5236 5237 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 5238 } 5239 5240 StmtResult Sema::ActOnOpenMPCriticalDirective( 5241 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 5242 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5243 if (!AStmt) 5244 return StmtError(); 5245 5246 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5247 5248 bool ErrorFound = false; 5249 llvm::APSInt Hint; 5250 SourceLocation HintLoc; 5251 bool DependentHint = false; 5252 for (auto *C : Clauses) { 5253 if (C->getClauseKind() == OMPC_hint) { 5254 if (!DirName.getName()) { 5255 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 5256 ErrorFound = true; 5257 } 5258 Expr *E = cast<OMPHintClause>(C)->getHint(); 5259 if (E->isTypeDependent() || E->isValueDependent() || 5260 E->isInstantiationDependent()) 5261 DependentHint = true; 5262 else { 5263 Hint = E->EvaluateKnownConstInt(Context); 5264 HintLoc = C->getLocStart(); 5265 } 5266 } 5267 } 5268 if (ErrorFound) 5269 return StmtError(); 5270 auto Pair = DSAStack->getCriticalWithHint(DirName); 5271 if (Pair.first && DirName.getName() && !DependentHint) { 5272 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 5273 Diag(StartLoc, diag::err_omp_critical_with_hint); 5274 if (HintLoc.isValid()) { 5275 Diag(HintLoc, diag::note_omp_critical_hint_here) 5276 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 5277 } else 5278 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 5279 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 5280 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 5281 << 1 5282 << C->getHint()->EvaluateKnownConstInt(Context).toString( 5283 /*Radix=*/10, /*Signed=*/false); 5284 } else 5285 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 5286 } 5287 } 5288 5289 getCurFunction()->setHasBranchProtectedScope(); 5290 5291 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 5292 Clauses, AStmt); 5293 if (!Pair.first && DirName.getName() && !DependentHint) 5294 DSAStack->addCriticalWithHint(Dir, Hint); 5295 return Dir; 5296 } 5297 5298 StmtResult Sema::ActOnOpenMPParallelForDirective( 5299 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5300 SourceLocation EndLoc, 5301 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5302 if (!AStmt) 5303 return StmtError(); 5304 5305 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5306 // 1.2.2 OpenMP Language Terminology 5307 // Structured block - An executable statement with a single entry at the 5308 // top and a single exit at the bottom. 5309 // The point of exit cannot be a branch out of the structured block. 5310 // longjmp() and throw() must not violate the entry/exit criteria. 5311 CS->getCapturedDecl()->setNothrow(); 5312 5313 OMPLoopDirective::HelperExprs B; 5314 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5315 // define the nested loops number. 5316 unsigned NestedLoopCount = 5317 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 5318 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5319 VarsWithImplicitDSA, B); 5320 if (NestedLoopCount == 0) 5321 return StmtError(); 5322 5323 assert((CurContext->isDependentContext() || B.builtAll()) && 5324 "omp parallel for loop exprs were not built"); 5325 5326 if (!CurContext->isDependentContext()) { 5327 // Finalize the clauses that need pre-built expressions for CodeGen. 5328 for (auto C : Clauses) { 5329 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5330 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5331 B.NumIterations, *this, CurScope, 5332 DSAStack)) 5333 return StmtError(); 5334 } 5335 } 5336 5337 getCurFunction()->setHasBranchProtectedScope(); 5338 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 5339 NestedLoopCount, Clauses, AStmt, B, 5340 DSAStack->isCancelRegion()); 5341 } 5342 5343 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 5344 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5345 SourceLocation EndLoc, 5346 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5347 if (!AStmt) 5348 return StmtError(); 5349 5350 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5351 // 1.2.2 OpenMP Language Terminology 5352 // Structured block - An executable statement with a single entry at the 5353 // top and a single exit at the bottom. 5354 // The point of exit cannot be a branch out of the structured block. 5355 // longjmp() and throw() must not violate the entry/exit criteria. 5356 CS->getCapturedDecl()->setNothrow(); 5357 5358 OMPLoopDirective::HelperExprs B; 5359 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5360 // define the nested loops number. 5361 unsigned NestedLoopCount = 5362 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 5363 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5364 VarsWithImplicitDSA, B); 5365 if (NestedLoopCount == 0) 5366 return StmtError(); 5367 5368 if (!CurContext->isDependentContext()) { 5369 // Finalize the clauses that need pre-built expressions for CodeGen. 5370 for (auto C : Clauses) { 5371 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5372 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5373 B.NumIterations, *this, CurScope, 5374 DSAStack)) 5375 return StmtError(); 5376 } 5377 } 5378 5379 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5380 return StmtError(); 5381 5382 getCurFunction()->setHasBranchProtectedScope(); 5383 return OMPParallelForSimdDirective::Create( 5384 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 5385 } 5386 5387 StmtResult 5388 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 5389 Stmt *AStmt, SourceLocation StartLoc, 5390 SourceLocation EndLoc) { 5391 if (!AStmt) 5392 return StmtError(); 5393 5394 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5395 auto BaseStmt = AStmt; 5396 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5397 BaseStmt = CS->getCapturedStmt(); 5398 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5399 auto S = C->children(); 5400 if (S.begin() == S.end()) 5401 return StmtError(); 5402 // All associated statements must be '#pragma omp section' except for 5403 // the first one. 5404 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5405 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5406 if (SectionStmt) 5407 Diag(SectionStmt->getLocStart(), 5408 diag::err_omp_parallel_sections_substmt_not_section); 5409 return StmtError(); 5410 } 5411 cast<OMPSectionDirective>(SectionStmt) 5412 ->setHasCancel(DSAStack->isCancelRegion()); 5413 } 5414 } else { 5415 Diag(AStmt->getLocStart(), 5416 diag::err_omp_parallel_sections_not_compound_stmt); 5417 return StmtError(); 5418 } 5419 5420 getCurFunction()->setHasBranchProtectedScope(); 5421 5422 return OMPParallelSectionsDirective::Create( 5423 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 5424 } 5425 5426 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 5427 Stmt *AStmt, SourceLocation StartLoc, 5428 SourceLocation EndLoc) { 5429 if (!AStmt) 5430 return StmtError(); 5431 5432 auto *CS = cast<CapturedStmt>(AStmt); 5433 // 1.2.2 OpenMP Language Terminology 5434 // Structured block - An executable statement with a single entry at the 5435 // top and a single exit at the bottom. 5436 // The point of exit cannot be a branch out of the structured block. 5437 // longjmp() and throw() must not violate the entry/exit criteria. 5438 CS->getCapturedDecl()->setNothrow(); 5439 5440 getCurFunction()->setHasBranchProtectedScope(); 5441 5442 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5443 DSAStack->isCancelRegion()); 5444 } 5445 5446 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 5447 SourceLocation EndLoc) { 5448 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 5449 } 5450 5451 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 5452 SourceLocation EndLoc) { 5453 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 5454 } 5455 5456 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 5457 SourceLocation EndLoc) { 5458 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 5459 } 5460 5461 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 5462 Stmt *AStmt, 5463 SourceLocation StartLoc, 5464 SourceLocation EndLoc) { 5465 if (!AStmt) 5466 return StmtError(); 5467 5468 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5469 5470 getCurFunction()->setHasBranchProtectedScope(); 5471 5472 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 5473 AStmt, 5474 DSAStack->getTaskgroupReductionRef()); 5475 } 5476 5477 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 5478 SourceLocation StartLoc, 5479 SourceLocation EndLoc) { 5480 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 5481 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 5482 } 5483 5484 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 5485 Stmt *AStmt, 5486 SourceLocation StartLoc, 5487 SourceLocation EndLoc) { 5488 OMPClause *DependFound = nullptr; 5489 OMPClause *DependSourceClause = nullptr; 5490 OMPClause *DependSinkClause = nullptr; 5491 bool ErrorFound = false; 5492 OMPThreadsClause *TC = nullptr; 5493 OMPSIMDClause *SC = nullptr; 5494 for (auto *C : Clauses) { 5495 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 5496 DependFound = C; 5497 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 5498 if (DependSourceClause) { 5499 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 5500 << getOpenMPDirectiveName(OMPD_ordered) 5501 << getOpenMPClauseName(OMPC_depend) << 2; 5502 ErrorFound = true; 5503 } else 5504 DependSourceClause = C; 5505 if (DependSinkClause) { 5506 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5507 << 0; 5508 ErrorFound = true; 5509 } 5510 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 5511 if (DependSourceClause) { 5512 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5513 << 1; 5514 ErrorFound = true; 5515 } 5516 DependSinkClause = C; 5517 } 5518 } else if (C->getClauseKind() == OMPC_threads) 5519 TC = cast<OMPThreadsClause>(C); 5520 else if (C->getClauseKind() == OMPC_simd) 5521 SC = cast<OMPSIMDClause>(C); 5522 } 5523 if (!ErrorFound && !SC && 5524 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 5525 // OpenMP [2.8.1,simd Construct, Restrictions] 5526 // An ordered construct with the simd clause is the only OpenMP construct 5527 // that can appear in the simd region. 5528 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 5529 ErrorFound = true; 5530 } else if (DependFound && (TC || SC)) { 5531 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 5532 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 5533 ErrorFound = true; 5534 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 5535 Diag(DependFound->getLocStart(), 5536 diag::err_omp_ordered_directive_without_param); 5537 ErrorFound = true; 5538 } else if (TC || Clauses.empty()) { 5539 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 5540 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 5541 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 5542 << (TC != nullptr); 5543 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 5544 ErrorFound = true; 5545 } 5546 } 5547 if ((!AStmt && !DependFound) || ErrorFound) 5548 return StmtError(); 5549 5550 if (AStmt) { 5551 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5552 5553 getCurFunction()->setHasBranchProtectedScope(); 5554 } 5555 5556 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5557 } 5558 5559 namespace { 5560 /// \brief Helper class for checking expression in 'omp atomic [update]' 5561 /// construct. 5562 class OpenMPAtomicUpdateChecker { 5563 /// \brief Error results for atomic update expressions. 5564 enum ExprAnalysisErrorCode { 5565 /// \brief A statement is not an expression statement. 5566 NotAnExpression, 5567 /// \brief Expression is not builtin binary or unary operation. 5568 NotABinaryOrUnaryExpression, 5569 /// \brief Unary operation is not post-/pre- increment/decrement operation. 5570 NotAnUnaryIncDecExpression, 5571 /// \brief An expression is not of scalar type. 5572 NotAScalarType, 5573 /// \brief A binary operation is not an assignment operation. 5574 NotAnAssignmentOp, 5575 /// \brief RHS part of the binary operation is not a binary expression. 5576 NotABinaryExpression, 5577 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 5578 /// expression. 5579 NotABinaryOperator, 5580 /// \brief RHS binary operation does not have reference to the updated LHS 5581 /// part. 5582 NotAnUpdateExpression, 5583 /// \brief No errors is found. 5584 NoError 5585 }; 5586 /// \brief Reference to Sema. 5587 Sema &SemaRef; 5588 /// \brief A location for note diagnostics (when error is found). 5589 SourceLocation NoteLoc; 5590 /// \brief 'x' lvalue part of the source atomic expression. 5591 Expr *X; 5592 /// \brief 'expr' rvalue part of the source atomic expression. 5593 Expr *E; 5594 /// \brief Helper expression of the form 5595 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5596 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5597 Expr *UpdateExpr; 5598 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 5599 /// important for non-associative operations. 5600 bool IsXLHSInRHSPart; 5601 BinaryOperatorKind Op; 5602 SourceLocation OpLoc; 5603 /// \brief true if the source expression is a postfix unary operation, false 5604 /// if it is a prefix unary operation. 5605 bool IsPostfixUpdate; 5606 5607 public: 5608 OpenMPAtomicUpdateChecker(Sema &SemaRef) 5609 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 5610 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 5611 /// \brief Check specified statement that it is suitable for 'atomic update' 5612 /// constructs and extract 'x', 'expr' and Operation from the original 5613 /// expression. If DiagId and NoteId == 0, then only check is performed 5614 /// without error notification. 5615 /// \param DiagId Diagnostic which should be emitted if error is found. 5616 /// \param NoteId Diagnostic note for the main error message. 5617 /// \return true if statement is not an update expression, false otherwise. 5618 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 5619 /// \brief Return the 'x' lvalue part of the source atomic expression. 5620 Expr *getX() const { return X; } 5621 /// \brief Return the 'expr' rvalue part of the source atomic expression. 5622 Expr *getExpr() const { return E; } 5623 /// \brief Return the update expression used in calculation of the updated 5624 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5625 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5626 Expr *getUpdateExpr() const { return UpdateExpr; } 5627 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 5628 /// false otherwise. 5629 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 5630 5631 /// \brief true if the source expression is a postfix unary operation, false 5632 /// if it is a prefix unary operation. 5633 bool isPostfixUpdate() const { return IsPostfixUpdate; } 5634 5635 private: 5636 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 5637 unsigned NoteId = 0); 5638 }; 5639 } // namespace 5640 5641 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 5642 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 5643 ExprAnalysisErrorCode ErrorFound = NoError; 5644 SourceLocation ErrorLoc, NoteLoc; 5645 SourceRange ErrorRange, NoteRange; 5646 // Allowed constructs are: 5647 // x = x binop expr; 5648 // x = expr binop x; 5649 if (AtomicBinOp->getOpcode() == BO_Assign) { 5650 X = AtomicBinOp->getLHS(); 5651 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 5652 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 5653 if (AtomicInnerBinOp->isMultiplicativeOp() || 5654 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 5655 AtomicInnerBinOp->isBitwiseOp()) { 5656 Op = AtomicInnerBinOp->getOpcode(); 5657 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 5658 auto *LHS = AtomicInnerBinOp->getLHS(); 5659 auto *RHS = AtomicInnerBinOp->getRHS(); 5660 llvm::FoldingSetNodeID XId, LHSId, RHSId; 5661 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 5662 /*Canonical=*/true); 5663 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 5664 /*Canonical=*/true); 5665 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 5666 /*Canonical=*/true); 5667 if (XId == LHSId) { 5668 E = RHS; 5669 IsXLHSInRHSPart = true; 5670 } else if (XId == RHSId) { 5671 E = LHS; 5672 IsXLHSInRHSPart = false; 5673 } else { 5674 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5675 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5676 NoteLoc = X->getExprLoc(); 5677 NoteRange = X->getSourceRange(); 5678 ErrorFound = NotAnUpdateExpression; 5679 } 5680 } else { 5681 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5682 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5683 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 5684 NoteRange = SourceRange(NoteLoc, NoteLoc); 5685 ErrorFound = NotABinaryOperator; 5686 } 5687 } else { 5688 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 5689 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 5690 ErrorFound = NotABinaryExpression; 5691 } 5692 } else { 5693 ErrorLoc = AtomicBinOp->getExprLoc(); 5694 ErrorRange = AtomicBinOp->getSourceRange(); 5695 NoteLoc = AtomicBinOp->getOperatorLoc(); 5696 NoteRange = SourceRange(NoteLoc, NoteLoc); 5697 ErrorFound = NotAnAssignmentOp; 5698 } 5699 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5700 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5701 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5702 return true; 5703 } else if (SemaRef.CurContext->isDependentContext()) 5704 E = X = UpdateExpr = nullptr; 5705 return ErrorFound != NoError; 5706 } 5707 5708 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 5709 unsigned NoteId) { 5710 ExprAnalysisErrorCode ErrorFound = NoError; 5711 SourceLocation ErrorLoc, NoteLoc; 5712 SourceRange ErrorRange, NoteRange; 5713 // Allowed constructs are: 5714 // x++; 5715 // x--; 5716 // ++x; 5717 // --x; 5718 // x binop= expr; 5719 // x = x binop expr; 5720 // x = expr binop x; 5721 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 5722 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 5723 if (AtomicBody->getType()->isScalarType() || 5724 AtomicBody->isInstantiationDependent()) { 5725 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 5726 AtomicBody->IgnoreParenImpCasts())) { 5727 // Check for Compound Assignment Operation 5728 Op = BinaryOperator::getOpForCompoundAssignment( 5729 AtomicCompAssignOp->getOpcode()); 5730 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 5731 E = AtomicCompAssignOp->getRHS(); 5732 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 5733 IsXLHSInRHSPart = true; 5734 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 5735 AtomicBody->IgnoreParenImpCasts())) { 5736 // Check for Binary Operation 5737 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 5738 return true; 5739 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 5740 AtomicBody->IgnoreParenImpCasts())) { 5741 // Check for Unary Operation 5742 if (AtomicUnaryOp->isIncrementDecrementOp()) { 5743 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 5744 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 5745 OpLoc = AtomicUnaryOp->getOperatorLoc(); 5746 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 5747 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 5748 IsXLHSInRHSPart = true; 5749 } else { 5750 ErrorFound = NotAnUnaryIncDecExpression; 5751 ErrorLoc = AtomicUnaryOp->getExprLoc(); 5752 ErrorRange = AtomicUnaryOp->getSourceRange(); 5753 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 5754 NoteRange = SourceRange(NoteLoc, NoteLoc); 5755 } 5756 } else if (!AtomicBody->isInstantiationDependent()) { 5757 ErrorFound = NotABinaryOrUnaryExpression; 5758 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 5759 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 5760 } 5761 } else { 5762 ErrorFound = NotAScalarType; 5763 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 5764 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5765 } 5766 } else { 5767 ErrorFound = NotAnExpression; 5768 NoteLoc = ErrorLoc = S->getLocStart(); 5769 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5770 } 5771 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5772 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5773 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5774 return true; 5775 } else if (SemaRef.CurContext->isDependentContext()) 5776 E = X = UpdateExpr = nullptr; 5777 if (ErrorFound == NoError && E && X) { 5778 // Build an update expression of form 'OpaqueValueExpr(x) binop 5779 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 5780 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 5781 auto *OVEX = new (SemaRef.getASTContext()) 5782 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 5783 auto *OVEExpr = new (SemaRef.getASTContext()) 5784 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 5785 auto Update = 5786 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 5787 IsXLHSInRHSPart ? OVEExpr : OVEX); 5788 if (Update.isInvalid()) 5789 return true; 5790 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 5791 Sema::AA_Casting); 5792 if (Update.isInvalid()) 5793 return true; 5794 UpdateExpr = Update.get(); 5795 } 5796 return ErrorFound != NoError; 5797 } 5798 5799 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 5800 Stmt *AStmt, 5801 SourceLocation StartLoc, 5802 SourceLocation EndLoc) { 5803 if (!AStmt) 5804 return StmtError(); 5805 5806 auto *CS = cast<CapturedStmt>(AStmt); 5807 // 1.2.2 OpenMP Language Terminology 5808 // Structured block - An executable statement with a single entry at the 5809 // top and a single exit at the bottom. 5810 // The point of exit cannot be a branch out of the structured block. 5811 // longjmp() and throw() must not violate the entry/exit criteria. 5812 OpenMPClauseKind AtomicKind = OMPC_unknown; 5813 SourceLocation AtomicKindLoc; 5814 for (auto *C : Clauses) { 5815 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 5816 C->getClauseKind() == OMPC_update || 5817 C->getClauseKind() == OMPC_capture) { 5818 if (AtomicKind != OMPC_unknown) { 5819 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 5820 << SourceRange(C->getLocStart(), C->getLocEnd()); 5821 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 5822 << getOpenMPClauseName(AtomicKind); 5823 } else { 5824 AtomicKind = C->getClauseKind(); 5825 AtomicKindLoc = C->getLocStart(); 5826 } 5827 } 5828 } 5829 5830 auto Body = CS->getCapturedStmt(); 5831 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 5832 Body = EWC->getSubExpr(); 5833 5834 Expr *X = nullptr; 5835 Expr *V = nullptr; 5836 Expr *E = nullptr; 5837 Expr *UE = nullptr; 5838 bool IsXLHSInRHSPart = false; 5839 bool IsPostfixUpdate = false; 5840 // OpenMP [2.12.6, atomic Construct] 5841 // In the next expressions: 5842 // * x and v (as applicable) are both l-value expressions with scalar type. 5843 // * During the execution of an atomic region, multiple syntactic 5844 // occurrences of x must designate the same storage location. 5845 // * Neither of v and expr (as applicable) may access the storage location 5846 // designated by x. 5847 // * Neither of x and expr (as applicable) may access the storage location 5848 // designated by v. 5849 // * expr is an expression with scalar type. 5850 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 5851 // * binop, binop=, ++, and -- are not overloaded operators. 5852 // * The expression x binop expr must be numerically equivalent to x binop 5853 // (expr). This requirement is satisfied if the operators in expr have 5854 // precedence greater than binop, or by using parentheses around expr or 5855 // subexpressions of expr. 5856 // * The expression expr binop x must be numerically equivalent to (expr) 5857 // binop x. This requirement is satisfied if the operators in expr have 5858 // precedence equal to or greater than binop, or by using parentheses around 5859 // expr or subexpressions of expr. 5860 // * For forms that allow multiple occurrences of x, the number of times 5861 // that x is evaluated is unspecified. 5862 if (AtomicKind == OMPC_read) { 5863 enum { 5864 NotAnExpression, 5865 NotAnAssignmentOp, 5866 NotAScalarType, 5867 NotAnLValue, 5868 NoError 5869 } ErrorFound = NoError; 5870 SourceLocation ErrorLoc, NoteLoc; 5871 SourceRange ErrorRange, NoteRange; 5872 // If clause is read: 5873 // v = x; 5874 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5875 auto *AtomicBinOp = 5876 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5877 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5878 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5879 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 5880 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5881 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 5882 if (!X->isLValue() || !V->isLValue()) { 5883 auto NotLValueExpr = X->isLValue() ? V : X; 5884 ErrorFound = NotAnLValue; 5885 ErrorLoc = AtomicBinOp->getExprLoc(); 5886 ErrorRange = AtomicBinOp->getSourceRange(); 5887 NoteLoc = NotLValueExpr->getExprLoc(); 5888 NoteRange = NotLValueExpr->getSourceRange(); 5889 } 5890 } else if (!X->isInstantiationDependent() || 5891 !V->isInstantiationDependent()) { 5892 auto NotScalarExpr = 5893 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5894 ? V 5895 : X; 5896 ErrorFound = NotAScalarType; 5897 ErrorLoc = AtomicBinOp->getExprLoc(); 5898 ErrorRange = AtomicBinOp->getSourceRange(); 5899 NoteLoc = NotScalarExpr->getExprLoc(); 5900 NoteRange = NotScalarExpr->getSourceRange(); 5901 } 5902 } else if (!AtomicBody->isInstantiationDependent()) { 5903 ErrorFound = NotAnAssignmentOp; 5904 ErrorLoc = AtomicBody->getExprLoc(); 5905 ErrorRange = AtomicBody->getSourceRange(); 5906 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5907 : AtomicBody->getExprLoc(); 5908 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5909 : AtomicBody->getSourceRange(); 5910 } 5911 } else { 5912 ErrorFound = NotAnExpression; 5913 NoteLoc = ErrorLoc = Body->getLocStart(); 5914 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5915 } 5916 if (ErrorFound != NoError) { 5917 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 5918 << ErrorRange; 5919 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5920 << NoteRange; 5921 return StmtError(); 5922 } else if (CurContext->isDependentContext()) 5923 V = X = nullptr; 5924 } else if (AtomicKind == OMPC_write) { 5925 enum { 5926 NotAnExpression, 5927 NotAnAssignmentOp, 5928 NotAScalarType, 5929 NotAnLValue, 5930 NoError 5931 } ErrorFound = NoError; 5932 SourceLocation ErrorLoc, NoteLoc; 5933 SourceRange ErrorRange, NoteRange; 5934 // If clause is write: 5935 // x = expr; 5936 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5937 auto *AtomicBinOp = 5938 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5939 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5940 X = AtomicBinOp->getLHS(); 5941 E = AtomicBinOp->getRHS(); 5942 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5943 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 5944 if (!X->isLValue()) { 5945 ErrorFound = NotAnLValue; 5946 ErrorLoc = AtomicBinOp->getExprLoc(); 5947 ErrorRange = AtomicBinOp->getSourceRange(); 5948 NoteLoc = X->getExprLoc(); 5949 NoteRange = X->getSourceRange(); 5950 } 5951 } else if (!X->isInstantiationDependent() || 5952 !E->isInstantiationDependent()) { 5953 auto NotScalarExpr = 5954 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5955 ? E 5956 : X; 5957 ErrorFound = NotAScalarType; 5958 ErrorLoc = AtomicBinOp->getExprLoc(); 5959 ErrorRange = AtomicBinOp->getSourceRange(); 5960 NoteLoc = NotScalarExpr->getExprLoc(); 5961 NoteRange = NotScalarExpr->getSourceRange(); 5962 } 5963 } else if (!AtomicBody->isInstantiationDependent()) { 5964 ErrorFound = NotAnAssignmentOp; 5965 ErrorLoc = AtomicBody->getExprLoc(); 5966 ErrorRange = AtomicBody->getSourceRange(); 5967 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5968 : AtomicBody->getExprLoc(); 5969 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5970 : AtomicBody->getSourceRange(); 5971 } 5972 } else { 5973 ErrorFound = NotAnExpression; 5974 NoteLoc = ErrorLoc = Body->getLocStart(); 5975 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5976 } 5977 if (ErrorFound != NoError) { 5978 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 5979 << ErrorRange; 5980 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5981 << NoteRange; 5982 return StmtError(); 5983 } else if (CurContext->isDependentContext()) 5984 E = X = nullptr; 5985 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 5986 // If clause is update: 5987 // x++; 5988 // x--; 5989 // ++x; 5990 // --x; 5991 // x binop= expr; 5992 // x = x binop expr; 5993 // x = expr binop x; 5994 OpenMPAtomicUpdateChecker Checker(*this); 5995 if (Checker.checkStatement( 5996 Body, (AtomicKind == OMPC_update) 5997 ? diag::err_omp_atomic_update_not_expression_statement 5998 : diag::err_omp_atomic_not_expression_statement, 5999 diag::note_omp_atomic_update)) 6000 return StmtError(); 6001 if (!CurContext->isDependentContext()) { 6002 E = Checker.getExpr(); 6003 X = Checker.getX(); 6004 UE = Checker.getUpdateExpr(); 6005 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6006 } 6007 } else if (AtomicKind == OMPC_capture) { 6008 enum { 6009 NotAnAssignmentOp, 6010 NotACompoundStatement, 6011 NotTwoSubstatements, 6012 NotASpecificExpression, 6013 NoError 6014 } ErrorFound = NoError; 6015 SourceLocation ErrorLoc, NoteLoc; 6016 SourceRange ErrorRange, NoteRange; 6017 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 6018 // If clause is a capture: 6019 // v = x++; 6020 // v = x--; 6021 // v = ++x; 6022 // v = --x; 6023 // v = x binop= expr; 6024 // v = x = x binop expr; 6025 // v = x = expr binop x; 6026 auto *AtomicBinOp = 6027 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6028 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6029 V = AtomicBinOp->getLHS(); 6030 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6031 OpenMPAtomicUpdateChecker Checker(*this); 6032 if (Checker.checkStatement( 6033 Body, diag::err_omp_atomic_capture_not_expression_statement, 6034 diag::note_omp_atomic_update)) 6035 return StmtError(); 6036 E = Checker.getExpr(); 6037 X = Checker.getX(); 6038 UE = Checker.getUpdateExpr(); 6039 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6040 IsPostfixUpdate = Checker.isPostfixUpdate(); 6041 } else if (!AtomicBody->isInstantiationDependent()) { 6042 ErrorLoc = AtomicBody->getExprLoc(); 6043 ErrorRange = AtomicBody->getSourceRange(); 6044 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6045 : AtomicBody->getExprLoc(); 6046 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6047 : AtomicBody->getSourceRange(); 6048 ErrorFound = NotAnAssignmentOp; 6049 } 6050 if (ErrorFound != NoError) { 6051 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 6052 << ErrorRange; 6053 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6054 return StmtError(); 6055 } else if (CurContext->isDependentContext()) { 6056 UE = V = E = X = nullptr; 6057 } 6058 } else { 6059 // If clause is a capture: 6060 // { v = x; x = expr; } 6061 // { v = x; x++; } 6062 // { v = x; x--; } 6063 // { v = x; ++x; } 6064 // { v = x; --x; } 6065 // { v = x; x binop= expr; } 6066 // { v = x; x = x binop expr; } 6067 // { v = x; x = expr binop x; } 6068 // { x++; v = x; } 6069 // { x--; v = x; } 6070 // { ++x; v = x; } 6071 // { --x; v = x; } 6072 // { x binop= expr; v = x; } 6073 // { x = x binop expr; v = x; } 6074 // { x = expr binop x; v = x; } 6075 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 6076 // Check that this is { expr1; expr2; } 6077 if (CS->size() == 2) { 6078 auto *First = CS->body_front(); 6079 auto *Second = CS->body_back(); 6080 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 6081 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 6082 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 6083 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 6084 // Need to find what subexpression is 'v' and what is 'x'. 6085 OpenMPAtomicUpdateChecker Checker(*this); 6086 bool IsUpdateExprFound = !Checker.checkStatement(Second); 6087 BinaryOperator *BinOp = nullptr; 6088 if (IsUpdateExprFound) { 6089 BinOp = dyn_cast<BinaryOperator>(First); 6090 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6091 } 6092 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6093 // { v = x; x++; } 6094 // { v = x; x--; } 6095 // { v = x; ++x; } 6096 // { v = x; --x; } 6097 // { v = x; x binop= expr; } 6098 // { v = x; x = x binop expr; } 6099 // { v = x; x = expr binop x; } 6100 // Check that the first expression has form v = x. 6101 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6102 llvm::FoldingSetNodeID XId, PossibleXId; 6103 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6104 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6105 IsUpdateExprFound = XId == PossibleXId; 6106 if (IsUpdateExprFound) { 6107 V = BinOp->getLHS(); 6108 X = Checker.getX(); 6109 E = Checker.getExpr(); 6110 UE = Checker.getUpdateExpr(); 6111 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6112 IsPostfixUpdate = true; 6113 } 6114 } 6115 if (!IsUpdateExprFound) { 6116 IsUpdateExprFound = !Checker.checkStatement(First); 6117 BinOp = nullptr; 6118 if (IsUpdateExprFound) { 6119 BinOp = dyn_cast<BinaryOperator>(Second); 6120 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6121 } 6122 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6123 // { x++; v = x; } 6124 // { x--; v = x; } 6125 // { ++x; v = x; } 6126 // { --x; v = x; } 6127 // { x binop= expr; v = x; } 6128 // { x = x binop expr; v = x; } 6129 // { x = expr binop x; v = x; } 6130 // Check that the second expression has form v = x. 6131 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6132 llvm::FoldingSetNodeID XId, PossibleXId; 6133 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6134 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6135 IsUpdateExprFound = XId == PossibleXId; 6136 if (IsUpdateExprFound) { 6137 V = BinOp->getLHS(); 6138 X = Checker.getX(); 6139 E = Checker.getExpr(); 6140 UE = Checker.getUpdateExpr(); 6141 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6142 IsPostfixUpdate = false; 6143 } 6144 } 6145 } 6146 if (!IsUpdateExprFound) { 6147 // { v = x; x = expr; } 6148 auto *FirstExpr = dyn_cast<Expr>(First); 6149 auto *SecondExpr = dyn_cast<Expr>(Second); 6150 if (!FirstExpr || !SecondExpr || 6151 !(FirstExpr->isInstantiationDependent() || 6152 SecondExpr->isInstantiationDependent())) { 6153 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 6154 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 6155 ErrorFound = NotAnAssignmentOp; 6156 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 6157 : First->getLocStart(); 6158 NoteRange = ErrorRange = FirstBinOp 6159 ? FirstBinOp->getSourceRange() 6160 : SourceRange(ErrorLoc, ErrorLoc); 6161 } else { 6162 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 6163 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 6164 ErrorFound = NotAnAssignmentOp; 6165 NoteLoc = ErrorLoc = SecondBinOp 6166 ? SecondBinOp->getOperatorLoc() 6167 : Second->getLocStart(); 6168 NoteRange = ErrorRange = 6169 SecondBinOp ? SecondBinOp->getSourceRange() 6170 : SourceRange(ErrorLoc, ErrorLoc); 6171 } else { 6172 auto *PossibleXRHSInFirst = 6173 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 6174 auto *PossibleXLHSInSecond = 6175 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 6176 llvm::FoldingSetNodeID X1Id, X2Id; 6177 PossibleXRHSInFirst->Profile(X1Id, Context, 6178 /*Canonical=*/true); 6179 PossibleXLHSInSecond->Profile(X2Id, Context, 6180 /*Canonical=*/true); 6181 IsUpdateExprFound = X1Id == X2Id; 6182 if (IsUpdateExprFound) { 6183 V = FirstBinOp->getLHS(); 6184 X = SecondBinOp->getLHS(); 6185 E = SecondBinOp->getRHS(); 6186 UE = nullptr; 6187 IsXLHSInRHSPart = false; 6188 IsPostfixUpdate = true; 6189 } else { 6190 ErrorFound = NotASpecificExpression; 6191 ErrorLoc = FirstBinOp->getExprLoc(); 6192 ErrorRange = FirstBinOp->getSourceRange(); 6193 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 6194 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 6195 } 6196 } 6197 } 6198 } 6199 } 6200 } else { 6201 NoteLoc = ErrorLoc = Body->getLocStart(); 6202 NoteRange = ErrorRange = 6203 SourceRange(Body->getLocStart(), Body->getLocStart()); 6204 ErrorFound = NotTwoSubstatements; 6205 } 6206 } else { 6207 NoteLoc = ErrorLoc = Body->getLocStart(); 6208 NoteRange = ErrorRange = 6209 SourceRange(Body->getLocStart(), Body->getLocStart()); 6210 ErrorFound = NotACompoundStatement; 6211 } 6212 if (ErrorFound != NoError) { 6213 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 6214 << ErrorRange; 6215 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6216 return StmtError(); 6217 } else if (CurContext->isDependentContext()) { 6218 UE = V = E = X = nullptr; 6219 } 6220 } 6221 } 6222 6223 getCurFunction()->setHasBranchProtectedScope(); 6224 6225 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6226 X, V, E, UE, IsXLHSInRHSPart, 6227 IsPostfixUpdate); 6228 } 6229 6230 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 6231 Stmt *AStmt, 6232 SourceLocation StartLoc, 6233 SourceLocation EndLoc) { 6234 if (!AStmt) 6235 return StmtError(); 6236 6237 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6238 // 1.2.2 OpenMP Language Terminology 6239 // Structured block - An executable statement with a single entry at the 6240 // top and a single exit at the bottom. 6241 // The point of exit cannot be a branch out of the structured block. 6242 // longjmp() and throw() must not violate the entry/exit criteria. 6243 CS->getCapturedDecl()->setNothrow(); 6244 6245 // OpenMP [2.16, Nesting of Regions] 6246 // If specified, a teams construct must be contained within a target 6247 // construct. That target construct must contain no statements or directives 6248 // outside of the teams construct. 6249 if (DSAStack->hasInnerTeamsRegion()) { 6250 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 6251 bool OMPTeamsFound = true; 6252 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 6253 auto I = CS->body_begin(); 6254 while (I != CS->body_end()) { 6255 auto *OED = dyn_cast<OMPExecutableDirective>(*I); 6256 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 6257 OMPTeamsFound = false; 6258 break; 6259 } 6260 ++I; 6261 } 6262 assert(I != CS->body_end() && "Not found statement"); 6263 S = *I; 6264 } else { 6265 auto *OED = dyn_cast<OMPExecutableDirective>(S); 6266 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 6267 } 6268 if (!OMPTeamsFound) { 6269 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 6270 Diag(DSAStack->getInnerTeamsRegionLoc(), 6271 diag::note_omp_nested_teams_construct_here); 6272 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 6273 << isa<OMPExecutableDirective>(S); 6274 return StmtError(); 6275 } 6276 } 6277 6278 getCurFunction()->setHasBranchProtectedScope(); 6279 6280 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6281 } 6282 6283 StmtResult 6284 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 6285 Stmt *AStmt, SourceLocation StartLoc, 6286 SourceLocation EndLoc) { 6287 if (!AStmt) 6288 return StmtError(); 6289 6290 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6291 // 1.2.2 OpenMP Language Terminology 6292 // Structured block - An executable statement with a single entry at the 6293 // top and a single exit at the bottom. 6294 // The point of exit cannot be a branch out of the structured block. 6295 // longjmp() and throw() must not violate the entry/exit criteria. 6296 CS->getCapturedDecl()->setNothrow(); 6297 6298 getCurFunction()->setHasBranchProtectedScope(); 6299 6300 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6301 AStmt); 6302 } 6303 6304 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 6305 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6306 SourceLocation EndLoc, 6307 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6308 if (!AStmt) 6309 return StmtError(); 6310 6311 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6312 // 1.2.2 OpenMP Language Terminology 6313 // Structured block - An executable statement with a single entry at the 6314 // top and a single exit at the bottom. 6315 // The point of exit cannot be a branch out of the structured block. 6316 // longjmp() and throw() must not violate the entry/exit criteria. 6317 CS->getCapturedDecl()->setNothrow(); 6318 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 6319 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6320 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6321 // 1.2.2 OpenMP Language Terminology 6322 // Structured block - An executable statement with a single entry at the 6323 // top and a single exit at the bottom. 6324 // The point of exit cannot be a branch out of the structured block. 6325 // longjmp() and throw() must not violate the entry/exit criteria. 6326 CS->getCapturedDecl()->setNothrow(); 6327 } 6328 6329 OMPLoopDirective::HelperExprs B; 6330 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6331 // define the nested loops number. 6332 unsigned NestedLoopCount = 6333 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 6334 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 6335 VarsWithImplicitDSA, B); 6336 if (NestedLoopCount == 0) 6337 return StmtError(); 6338 6339 assert((CurContext->isDependentContext() || B.builtAll()) && 6340 "omp target parallel for loop exprs were not built"); 6341 6342 if (!CurContext->isDependentContext()) { 6343 // Finalize the clauses that need pre-built expressions for CodeGen. 6344 for (auto C : Clauses) { 6345 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6346 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6347 B.NumIterations, *this, CurScope, 6348 DSAStack)) 6349 return StmtError(); 6350 } 6351 } 6352 6353 getCurFunction()->setHasBranchProtectedScope(); 6354 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 6355 NestedLoopCount, Clauses, AStmt, 6356 B, DSAStack->isCancelRegion()); 6357 } 6358 6359 /// Check for existence of a map clause in the list of clauses. 6360 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 6361 const OpenMPClauseKind K) { 6362 return llvm::any_of( 6363 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 6364 } 6365 6366 template <typename... Params> 6367 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 6368 const Params... ClauseTypes) { 6369 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 6370 } 6371 6372 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 6373 Stmt *AStmt, 6374 SourceLocation StartLoc, 6375 SourceLocation EndLoc) { 6376 if (!AStmt) 6377 return StmtError(); 6378 6379 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6380 6381 // OpenMP [2.10.1, Restrictions, p. 97] 6382 // At least one map clause must appear on the directive. 6383 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { 6384 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6385 << "'map' or 'use_device_ptr'" 6386 << getOpenMPDirectiveName(OMPD_target_data); 6387 return StmtError(); 6388 } 6389 6390 getCurFunction()->setHasBranchProtectedScope(); 6391 6392 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6393 AStmt); 6394 } 6395 6396 StmtResult 6397 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 6398 SourceLocation StartLoc, 6399 SourceLocation EndLoc) { 6400 // OpenMP [2.10.2, Restrictions, p. 99] 6401 // At least one map clause must appear on the directive. 6402 if (!hasClauses(Clauses, OMPC_map)) { 6403 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6404 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 6405 return StmtError(); 6406 } 6407 6408 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, 6409 Clauses); 6410 } 6411 6412 StmtResult 6413 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 6414 SourceLocation StartLoc, 6415 SourceLocation EndLoc) { 6416 // OpenMP [2.10.3, Restrictions, p. 102] 6417 // At least one map clause must appear on the directive. 6418 if (!hasClauses(Clauses, OMPC_map)) { 6419 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6420 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 6421 return StmtError(); 6422 } 6423 6424 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses); 6425 } 6426 6427 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 6428 SourceLocation StartLoc, 6429 SourceLocation EndLoc) { 6430 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 6431 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 6432 return StmtError(); 6433 } 6434 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses); 6435 } 6436 6437 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 6438 Stmt *AStmt, SourceLocation StartLoc, 6439 SourceLocation EndLoc) { 6440 if (!AStmt) 6441 return StmtError(); 6442 6443 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6444 // 1.2.2 OpenMP Language Terminology 6445 // Structured block - An executable statement with a single entry at the 6446 // top and a single exit at the bottom. 6447 // The point of exit cannot be a branch out of the structured block. 6448 // longjmp() and throw() must not violate the entry/exit criteria. 6449 CS->getCapturedDecl()->setNothrow(); 6450 6451 getCurFunction()->setHasBranchProtectedScope(); 6452 6453 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6454 } 6455 6456 StmtResult 6457 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 6458 SourceLocation EndLoc, 6459 OpenMPDirectiveKind CancelRegion) { 6460 if (DSAStack->isParentNowaitRegion()) { 6461 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 6462 return StmtError(); 6463 } 6464 if (DSAStack->isParentOrderedRegion()) { 6465 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 6466 return StmtError(); 6467 } 6468 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 6469 CancelRegion); 6470 } 6471 6472 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 6473 SourceLocation StartLoc, 6474 SourceLocation EndLoc, 6475 OpenMPDirectiveKind CancelRegion) { 6476 if (DSAStack->isParentNowaitRegion()) { 6477 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 6478 return StmtError(); 6479 } 6480 if (DSAStack->isParentOrderedRegion()) { 6481 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 6482 return StmtError(); 6483 } 6484 DSAStack->setParentCancelRegion(/*Cancel=*/true); 6485 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6486 CancelRegion); 6487 } 6488 6489 static bool checkGrainsizeNumTasksClauses(Sema &S, 6490 ArrayRef<OMPClause *> Clauses) { 6491 OMPClause *PrevClause = nullptr; 6492 bool ErrorFound = false; 6493 for (auto *C : Clauses) { 6494 if (C->getClauseKind() == OMPC_grainsize || 6495 C->getClauseKind() == OMPC_num_tasks) { 6496 if (!PrevClause) 6497 PrevClause = C; 6498 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 6499 S.Diag(C->getLocStart(), 6500 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 6501 << getOpenMPClauseName(C->getClauseKind()) 6502 << getOpenMPClauseName(PrevClause->getClauseKind()); 6503 S.Diag(PrevClause->getLocStart(), 6504 diag::note_omp_previous_grainsize_num_tasks) 6505 << getOpenMPClauseName(PrevClause->getClauseKind()); 6506 ErrorFound = true; 6507 } 6508 } 6509 } 6510 return ErrorFound; 6511 } 6512 6513 static bool checkReductionClauseWithNogroup(Sema &S, 6514 ArrayRef<OMPClause *> Clauses) { 6515 OMPClause *ReductionClause = nullptr; 6516 OMPClause *NogroupClause = nullptr; 6517 for (auto *C : Clauses) { 6518 if (C->getClauseKind() == OMPC_reduction) { 6519 ReductionClause = C; 6520 if (NogroupClause) 6521 break; 6522 continue; 6523 } 6524 if (C->getClauseKind() == OMPC_nogroup) { 6525 NogroupClause = C; 6526 if (ReductionClause) 6527 break; 6528 continue; 6529 } 6530 } 6531 if (ReductionClause && NogroupClause) { 6532 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup) 6533 << SourceRange(NogroupClause->getLocStart(), 6534 NogroupClause->getLocEnd()); 6535 return true; 6536 } 6537 return false; 6538 } 6539 6540 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 6541 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6542 SourceLocation EndLoc, 6543 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6544 if (!AStmt) 6545 return StmtError(); 6546 6547 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6548 OMPLoopDirective::HelperExprs B; 6549 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6550 // define the nested loops number. 6551 unsigned NestedLoopCount = 6552 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 6553 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6554 VarsWithImplicitDSA, B); 6555 if (NestedLoopCount == 0) 6556 return StmtError(); 6557 6558 assert((CurContext->isDependentContext() || B.builtAll()) && 6559 "omp for loop exprs were not built"); 6560 6561 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6562 // The grainsize clause and num_tasks clause are mutually exclusive and may 6563 // not appear on the same taskloop directive. 6564 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6565 return StmtError(); 6566 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6567 // If a reduction clause is present on the taskloop directive, the nogroup 6568 // clause must not be specified. 6569 if (checkReductionClauseWithNogroup(*this, Clauses)) 6570 return StmtError(); 6571 6572 getCurFunction()->setHasBranchProtectedScope(); 6573 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 6574 NestedLoopCount, Clauses, AStmt, B); 6575 } 6576 6577 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 6578 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6579 SourceLocation EndLoc, 6580 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6581 if (!AStmt) 6582 return StmtError(); 6583 6584 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6585 OMPLoopDirective::HelperExprs B; 6586 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6587 // define the nested loops number. 6588 unsigned NestedLoopCount = 6589 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 6590 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6591 VarsWithImplicitDSA, B); 6592 if (NestedLoopCount == 0) 6593 return StmtError(); 6594 6595 assert((CurContext->isDependentContext() || B.builtAll()) && 6596 "omp for loop exprs were not built"); 6597 6598 if (!CurContext->isDependentContext()) { 6599 // Finalize the clauses that need pre-built expressions for CodeGen. 6600 for (auto C : Clauses) { 6601 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6602 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6603 B.NumIterations, *this, CurScope, 6604 DSAStack)) 6605 return StmtError(); 6606 } 6607 } 6608 6609 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6610 // The grainsize clause and num_tasks clause are mutually exclusive and may 6611 // not appear on the same taskloop directive. 6612 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6613 return StmtError(); 6614 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6615 // If a reduction clause is present on the taskloop directive, the nogroup 6616 // clause must not be specified. 6617 if (checkReductionClauseWithNogroup(*this, Clauses)) 6618 return StmtError(); 6619 6620 getCurFunction()->setHasBranchProtectedScope(); 6621 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 6622 NestedLoopCount, Clauses, AStmt, B); 6623 } 6624 6625 StmtResult Sema::ActOnOpenMPDistributeDirective( 6626 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6627 SourceLocation EndLoc, 6628 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6629 if (!AStmt) 6630 return StmtError(); 6631 6632 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6633 OMPLoopDirective::HelperExprs B; 6634 // In presence of clause 'collapse' with number of loops, it will 6635 // define the nested loops number. 6636 unsigned NestedLoopCount = 6637 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 6638 nullptr /*ordered not a clause on distribute*/, AStmt, 6639 *this, *DSAStack, VarsWithImplicitDSA, B); 6640 if (NestedLoopCount == 0) 6641 return StmtError(); 6642 6643 assert((CurContext->isDependentContext() || B.builtAll()) && 6644 "omp for loop exprs were not built"); 6645 6646 getCurFunction()->setHasBranchProtectedScope(); 6647 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 6648 NestedLoopCount, Clauses, AStmt, B); 6649 } 6650 6651 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 6652 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6653 SourceLocation EndLoc, 6654 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6655 if (!AStmt) 6656 return StmtError(); 6657 6658 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6659 // 1.2.2 OpenMP Language Terminology 6660 // Structured block - An executable statement with a single entry at the 6661 // top and a single exit at the bottom. 6662 // The point of exit cannot be a branch out of the structured block. 6663 // longjmp() and throw() must not violate the entry/exit criteria. 6664 CS->getCapturedDecl()->setNothrow(); 6665 6666 OMPLoopDirective::HelperExprs B; 6667 // In presence of clause 'collapse' with number of loops, it will 6668 // define the nested loops number. 6669 unsigned NestedLoopCount = CheckOpenMPLoop( 6670 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6671 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6672 VarsWithImplicitDSA, B); 6673 if (NestedLoopCount == 0) 6674 return StmtError(); 6675 6676 assert((CurContext->isDependentContext() || B.builtAll()) && 6677 "omp for loop exprs were not built"); 6678 6679 getCurFunction()->setHasBranchProtectedScope(); 6680 return OMPDistributeParallelForDirective::Create( 6681 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6682 } 6683 6684 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 6685 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6686 SourceLocation EndLoc, 6687 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6688 if (!AStmt) 6689 return StmtError(); 6690 6691 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6692 // 1.2.2 OpenMP Language Terminology 6693 // Structured block - An executable statement with a single entry at the 6694 // top and a single exit at the bottom. 6695 // The point of exit cannot be a branch out of the structured block. 6696 // longjmp() and throw() must not violate the entry/exit criteria. 6697 CS->getCapturedDecl()->setNothrow(); 6698 6699 OMPLoopDirective::HelperExprs B; 6700 // In presence of clause 'collapse' with number of loops, it will 6701 // define the nested loops number. 6702 unsigned NestedLoopCount = CheckOpenMPLoop( 6703 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6704 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6705 VarsWithImplicitDSA, B); 6706 if (NestedLoopCount == 0) 6707 return StmtError(); 6708 6709 assert((CurContext->isDependentContext() || B.builtAll()) && 6710 "omp for loop exprs were not built"); 6711 6712 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6713 return StmtError(); 6714 6715 getCurFunction()->setHasBranchProtectedScope(); 6716 return OMPDistributeParallelForSimdDirective::Create( 6717 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6718 } 6719 6720 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 6721 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6722 SourceLocation EndLoc, 6723 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6724 if (!AStmt) 6725 return StmtError(); 6726 6727 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6728 // 1.2.2 OpenMP Language Terminology 6729 // Structured block - An executable statement with a single entry at the 6730 // top and a single exit at the bottom. 6731 // The point of exit cannot be a branch out of the structured block. 6732 // longjmp() and throw() must not violate the entry/exit criteria. 6733 CS->getCapturedDecl()->setNothrow(); 6734 6735 OMPLoopDirective::HelperExprs B; 6736 // In presence of clause 'collapse' with number of loops, it will 6737 // define the nested loops number. 6738 unsigned NestedLoopCount = 6739 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 6740 nullptr /*ordered not a clause on distribute*/, AStmt, 6741 *this, *DSAStack, VarsWithImplicitDSA, B); 6742 if (NestedLoopCount == 0) 6743 return StmtError(); 6744 6745 assert((CurContext->isDependentContext() || B.builtAll()) && 6746 "omp for loop exprs were not built"); 6747 6748 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6749 return StmtError(); 6750 6751 getCurFunction()->setHasBranchProtectedScope(); 6752 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 6753 NestedLoopCount, Clauses, AStmt, B); 6754 } 6755 6756 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 6757 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6758 SourceLocation EndLoc, 6759 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6760 if (!AStmt) 6761 return StmtError(); 6762 6763 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6764 // 1.2.2 OpenMP Language Terminology 6765 // Structured block - An executable statement with a single entry at the 6766 // top and a single exit at the bottom. 6767 // The point of exit cannot be a branch out of the structured block. 6768 // longjmp() and throw() must not violate the entry/exit criteria. 6769 CS->getCapturedDecl()->setNothrow(); 6770 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 6771 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6772 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6773 // 1.2.2 OpenMP Language Terminology 6774 // Structured block - An executable statement with a single entry at the 6775 // top and a single exit at the bottom. 6776 // The point of exit cannot be a branch out of the structured block. 6777 // longjmp() and throw() must not violate the entry/exit criteria. 6778 CS->getCapturedDecl()->setNothrow(); 6779 } 6780 6781 OMPLoopDirective::HelperExprs B; 6782 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6783 // define the nested loops number. 6784 unsigned NestedLoopCount = CheckOpenMPLoop( 6785 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 6786 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 6787 VarsWithImplicitDSA, B); 6788 if (NestedLoopCount == 0) 6789 return StmtError(); 6790 6791 assert((CurContext->isDependentContext() || B.builtAll()) && 6792 "omp target parallel for simd loop exprs were not built"); 6793 6794 if (!CurContext->isDependentContext()) { 6795 // Finalize the clauses that need pre-built expressions for CodeGen. 6796 for (auto C : Clauses) { 6797 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6798 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6799 B.NumIterations, *this, CurScope, 6800 DSAStack)) 6801 return StmtError(); 6802 } 6803 } 6804 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6805 return StmtError(); 6806 6807 getCurFunction()->setHasBranchProtectedScope(); 6808 return OMPTargetParallelForSimdDirective::Create( 6809 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6810 } 6811 6812 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 6813 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6814 SourceLocation EndLoc, 6815 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6816 if (!AStmt) 6817 return StmtError(); 6818 6819 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6820 // 1.2.2 OpenMP Language Terminology 6821 // Structured block - An executable statement with a single entry at the 6822 // top and a single exit at the bottom. 6823 // The point of exit cannot be a branch out of the structured block. 6824 // longjmp() and throw() must not violate the entry/exit criteria. 6825 CS->getCapturedDecl()->setNothrow(); 6826 6827 OMPLoopDirective::HelperExprs B; 6828 // In presence of clause 'collapse' with number of loops, it will define the 6829 // nested loops number. 6830 unsigned NestedLoopCount = 6831 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 6832 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6833 VarsWithImplicitDSA, B); 6834 if (NestedLoopCount == 0) 6835 return StmtError(); 6836 6837 assert((CurContext->isDependentContext() || B.builtAll()) && 6838 "omp target simd loop exprs were not built"); 6839 6840 if (!CurContext->isDependentContext()) { 6841 // Finalize the clauses that need pre-built expressions for CodeGen. 6842 for (auto C : Clauses) { 6843 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6844 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6845 B.NumIterations, *this, CurScope, 6846 DSAStack)) 6847 return StmtError(); 6848 } 6849 } 6850 6851 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6852 return StmtError(); 6853 6854 getCurFunction()->setHasBranchProtectedScope(); 6855 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 6856 NestedLoopCount, Clauses, AStmt, B); 6857 } 6858 6859 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 6860 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6861 SourceLocation EndLoc, 6862 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6863 if (!AStmt) 6864 return StmtError(); 6865 6866 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6867 // 1.2.2 OpenMP Language Terminology 6868 // Structured block - An executable statement with a single entry at the 6869 // top and a single exit at the bottom. 6870 // The point of exit cannot be a branch out of the structured block. 6871 // longjmp() and throw() must not violate the entry/exit criteria. 6872 CS->getCapturedDecl()->setNothrow(); 6873 6874 OMPLoopDirective::HelperExprs B; 6875 // In presence of clause 'collapse' with number of loops, it will 6876 // define the nested loops number. 6877 unsigned NestedLoopCount = 6878 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 6879 nullptr /*ordered not a clause on distribute*/, AStmt, 6880 *this, *DSAStack, VarsWithImplicitDSA, B); 6881 if (NestedLoopCount == 0) 6882 return StmtError(); 6883 6884 assert((CurContext->isDependentContext() || B.builtAll()) && 6885 "omp teams distribute loop exprs were not built"); 6886 6887 getCurFunction()->setHasBranchProtectedScope(); 6888 return OMPTeamsDistributeDirective::Create( 6889 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6890 } 6891 6892 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 6893 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6894 SourceLocation EndLoc, 6895 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6896 if (!AStmt) 6897 return StmtError(); 6898 6899 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6900 // 1.2.2 OpenMP Language Terminology 6901 // Structured block - An executable statement with a single entry at the 6902 // top and a single exit at the bottom. 6903 // The point of exit cannot be a branch out of the structured block. 6904 // longjmp() and throw() must not violate the entry/exit criteria. 6905 CS->getCapturedDecl()->setNothrow(); 6906 6907 OMPLoopDirective::HelperExprs B; 6908 // In presence of clause 'collapse' with number of loops, it will 6909 // define the nested loops number. 6910 unsigned NestedLoopCount = CheckOpenMPLoop( 6911 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6912 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6913 VarsWithImplicitDSA, B); 6914 6915 if (NestedLoopCount == 0) 6916 return StmtError(); 6917 6918 assert((CurContext->isDependentContext() || B.builtAll()) && 6919 "omp teams distribute simd loop exprs were not built"); 6920 6921 if (!CurContext->isDependentContext()) { 6922 // Finalize the clauses that need pre-built expressions for CodeGen. 6923 for (auto C : Clauses) { 6924 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6925 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6926 B.NumIterations, *this, CurScope, 6927 DSAStack)) 6928 return StmtError(); 6929 } 6930 } 6931 6932 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6933 return StmtError(); 6934 6935 getCurFunction()->setHasBranchProtectedScope(); 6936 return OMPTeamsDistributeSimdDirective::Create( 6937 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6938 } 6939 6940 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6941 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6942 SourceLocation EndLoc, 6943 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6944 if (!AStmt) 6945 return StmtError(); 6946 6947 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6948 // 1.2.2 OpenMP Language Terminology 6949 // Structured block - An executable statement with a single entry at the 6950 // top and a single exit at the bottom. 6951 // The point of exit cannot be a branch out of the structured block. 6952 // longjmp() and throw() must not violate the entry/exit criteria. 6953 CS->getCapturedDecl()->setNothrow(); 6954 6955 OMPLoopDirective::HelperExprs B; 6956 // In presence of clause 'collapse' with number of loops, it will 6957 // define the nested loops number. 6958 auto NestedLoopCount = CheckOpenMPLoop( 6959 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6960 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6961 VarsWithImplicitDSA, B); 6962 6963 if (NestedLoopCount == 0) 6964 return StmtError(); 6965 6966 assert((CurContext->isDependentContext() || B.builtAll()) && 6967 "omp for loop exprs were not built"); 6968 6969 if (!CurContext->isDependentContext()) { 6970 // Finalize the clauses that need pre-built expressions for CodeGen. 6971 for (auto C : Clauses) { 6972 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6973 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6974 B.NumIterations, *this, CurScope, 6975 DSAStack)) 6976 return StmtError(); 6977 } 6978 } 6979 6980 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6981 return StmtError(); 6982 6983 getCurFunction()->setHasBranchProtectedScope(); 6984 return OMPTeamsDistributeParallelForSimdDirective::Create( 6985 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6986 } 6987 6988 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 6989 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6990 SourceLocation EndLoc, 6991 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6992 if (!AStmt) 6993 return StmtError(); 6994 6995 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6996 // 1.2.2 OpenMP Language Terminology 6997 // Structured block - An executable statement with a single entry at the 6998 // top and a single exit at the bottom. 6999 // The point of exit cannot be a branch out of the structured block. 7000 // longjmp() and throw() must not violate the entry/exit criteria. 7001 CS->getCapturedDecl()->setNothrow(); 7002 7003 OMPLoopDirective::HelperExprs B; 7004 // In presence of clause 'collapse' with number of loops, it will 7005 // define the nested loops number. 7006 unsigned NestedLoopCount = CheckOpenMPLoop( 7007 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7008 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7009 VarsWithImplicitDSA, B); 7010 7011 if (NestedLoopCount == 0) 7012 return StmtError(); 7013 7014 assert((CurContext->isDependentContext() || B.builtAll()) && 7015 "omp for loop exprs were not built"); 7016 7017 if (!CurContext->isDependentContext()) { 7018 // Finalize the clauses that need pre-built expressions for CodeGen. 7019 for (auto C : Clauses) { 7020 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7021 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7022 B.NumIterations, *this, CurScope, 7023 DSAStack)) 7024 return StmtError(); 7025 } 7026 } 7027 7028 getCurFunction()->setHasBranchProtectedScope(); 7029 return OMPTeamsDistributeParallelForDirective::Create( 7030 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7031 } 7032 7033 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 7034 Stmt *AStmt, 7035 SourceLocation StartLoc, 7036 SourceLocation EndLoc) { 7037 if (!AStmt) 7038 return StmtError(); 7039 7040 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7041 // 1.2.2 OpenMP Language Terminology 7042 // Structured block - An executable statement with a single entry at the 7043 // top and a single exit at the bottom. 7044 // The point of exit cannot be a branch out of the structured block. 7045 // longjmp() and throw() must not violate the entry/exit criteria. 7046 CS->getCapturedDecl()->setNothrow(); 7047 7048 getCurFunction()->setHasBranchProtectedScope(); 7049 7050 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 7051 AStmt); 7052 } 7053 7054 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 7055 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7056 SourceLocation EndLoc, 7057 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7058 if (!AStmt) 7059 return StmtError(); 7060 7061 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7062 // 1.2.2 OpenMP Language Terminology 7063 // Structured block - An executable statement with a single entry at the 7064 // top and a single exit at the bottom. 7065 // The point of exit cannot be a branch out of the structured block. 7066 // longjmp() and throw() must not violate the entry/exit criteria. 7067 CS->getCapturedDecl()->setNothrow(); 7068 7069 OMPLoopDirective::HelperExprs B; 7070 // In presence of clause 'collapse' with number of loops, it will 7071 // define the nested loops number. 7072 auto NestedLoopCount = CheckOpenMPLoop( 7073 OMPD_target_teams_distribute, 7074 getCollapseNumberExpr(Clauses), 7075 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7076 VarsWithImplicitDSA, B); 7077 if (NestedLoopCount == 0) 7078 return StmtError(); 7079 7080 assert((CurContext->isDependentContext() || B.builtAll()) && 7081 "omp target teams distribute loop exprs were not built"); 7082 7083 getCurFunction()->setHasBranchProtectedScope(); 7084 return OMPTargetTeamsDistributeDirective::Create( 7085 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7086 } 7087 7088 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 7089 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7090 SourceLocation EndLoc, 7091 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7092 if (!AStmt) 7093 return StmtError(); 7094 7095 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7096 // 1.2.2 OpenMP Language Terminology 7097 // Structured block - An executable statement with a single entry at the 7098 // top and a single exit at the bottom. 7099 // The point of exit cannot be a branch out of the structured block. 7100 // longjmp() and throw() must not violate the entry/exit criteria. 7101 CS->getCapturedDecl()->setNothrow(); 7102 7103 OMPLoopDirective::HelperExprs B; 7104 // In presence of clause 'collapse' with number of loops, it will 7105 // define the nested loops number. 7106 auto NestedLoopCount = CheckOpenMPLoop( 7107 OMPD_target_teams_distribute_parallel_for, 7108 getCollapseNumberExpr(Clauses), 7109 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7110 VarsWithImplicitDSA, B); 7111 if (NestedLoopCount == 0) 7112 return StmtError(); 7113 7114 assert((CurContext->isDependentContext() || B.builtAll()) && 7115 "omp target teams distribute parallel for loop exprs were not built"); 7116 7117 if (!CurContext->isDependentContext()) { 7118 // Finalize the clauses that need pre-built expressions for CodeGen. 7119 for (auto C : Clauses) { 7120 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7121 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7122 B.NumIterations, *this, CurScope, 7123 DSAStack)) 7124 return StmtError(); 7125 } 7126 } 7127 7128 getCurFunction()->setHasBranchProtectedScope(); 7129 return OMPTargetTeamsDistributeParallelForDirective::Create( 7130 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7131 } 7132 7133 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 7134 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7135 SourceLocation EndLoc, 7136 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7137 if (!AStmt) 7138 return StmtError(); 7139 7140 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7141 // 1.2.2 OpenMP Language Terminology 7142 // Structured block - An executable statement with a single entry at the 7143 // top and a single exit at the bottom. 7144 // The point of exit cannot be a branch out of the structured block. 7145 // longjmp() and throw() must not violate the entry/exit criteria. 7146 CS->getCapturedDecl()->setNothrow(); 7147 7148 OMPLoopDirective::HelperExprs B; 7149 // In presence of clause 'collapse' with number of loops, it will 7150 // define the nested loops number. 7151 auto NestedLoopCount = CheckOpenMPLoop( 7152 OMPD_target_teams_distribute_parallel_for_simd, 7153 getCollapseNumberExpr(Clauses), 7154 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7155 VarsWithImplicitDSA, B); 7156 if (NestedLoopCount == 0) 7157 return StmtError(); 7158 7159 assert((CurContext->isDependentContext() || B.builtAll()) && 7160 "omp target teams distribute parallel for simd loop exprs were not " 7161 "built"); 7162 7163 if (!CurContext->isDependentContext()) { 7164 // Finalize the clauses that need pre-built expressions for CodeGen. 7165 for (auto C : Clauses) { 7166 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7167 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7168 B.NumIterations, *this, CurScope, 7169 DSAStack)) 7170 return StmtError(); 7171 } 7172 } 7173 7174 getCurFunction()->setHasBranchProtectedScope(); 7175 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 7176 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7177 } 7178 7179 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 7180 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7181 SourceLocation EndLoc, 7182 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7183 if (!AStmt) 7184 return StmtError(); 7185 7186 auto *CS = cast<CapturedStmt>(AStmt); 7187 // 1.2.2 OpenMP Language Terminology 7188 // Structured block - An executable statement with a single entry at the 7189 // top and a single exit at the bottom. 7190 // The point of exit cannot be a branch out of the structured block. 7191 // longjmp() and throw() must not violate the entry/exit criteria. 7192 CS->getCapturedDecl()->setNothrow(); 7193 7194 OMPLoopDirective::HelperExprs B; 7195 // In presence of clause 'collapse' with number of loops, it will 7196 // define the nested loops number. 7197 auto NestedLoopCount = CheckOpenMPLoop( 7198 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 7199 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7200 VarsWithImplicitDSA, B); 7201 if (NestedLoopCount == 0) 7202 return StmtError(); 7203 7204 assert((CurContext->isDependentContext() || B.builtAll()) && 7205 "omp target teams distribute simd loop exprs were not built"); 7206 7207 getCurFunction()->setHasBranchProtectedScope(); 7208 return OMPTargetTeamsDistributeSimdDirective::Create( 7209 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7210 } 7211 7212 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 7213 SourceLocation StartLoc, 7214 SourceLocation LParenLoc, 7215 SourceLocation EndLoc) { 7216 OMPClause *Res = nullptr; 7217 switch (Kind) { 7218 case OMPC_final: 7219 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 7220 break; 7221 case OMPC_num_threads: 7222 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 7223 break; 7224 case OMPC_safelen: 7225 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 7226 break; 7227 case OMPC_simdlen: 7228 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 7229 break; 7230 case OMPC_collapse: 7231 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 7232 break; 7233 case OMPC_ordered: 7234 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 7235 break; 7236 case OMPC_device: 7237 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 7238 break; 7239 case OMPC_num_teams: 7240 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 7241 break; 7242 case OMPC_thread_limit: 7243 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 7244 break; 7245 case OMPC_priority: 7246 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 7247 break; 7248 case OMPC_grainsize: 7249 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 7250 break; 7251 case OMPC_num_tasks: 7252 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 7253 break; 7254 case OMPC_hint: 7255 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 7256 break; 7257 case OMPC_if: 7258 case OMPC_default: 7259 case OMPC_proc_bind: 7260 case OMPC_schedule: 7261 case OMPC_private: 7262 case OMPC_firstprivate: 7263 case OMPC_lastprivate: 7264 case OMPC_shared: 7265 case OMPC_reduction: 7266 case OMPC_task_reduction: 7267 case OMPC_in_reduction: 7268 case OMPC_linear: 7269 case OMPC_aligned: 7270 case OMPC_copyin: 7271 case OMPC_copyprivate: 7272 case OMPC_nowait: 7273 case OMPC_untied: 7274 case OMPC_mergeable: 7275 case OMPC_threadprivate: 7276 case OMPC_flush: 7277 case OMPC_read: 7278 case OMPC_write: 7279 case OMPC_update: 7280 case OMPC_capture: 7281 case OMPC_seq_cst: 7282 case OMPC_depend: 7283 case OMPC_threads: 7284 case OMPC_simd: 7285 case OMPC_map: 7286 case OMPC_nogroup: 7287 case OMPC_dist_schedule: 7288 case OMPC_defaultmap: 7289 case OMPC_unknown: 7290 case OMPC_uniform: 7291 case OMPC_to: 7292 case OMPC_from: 7293 case OMPC_use_device_ptr: 7294 case OMPC_is_device_ptr: 7295 llvm_unreachable("Clause is not allowed."); 7296 } 7297 return Res; 7298 } 7299 7300 // An OpenMP directive such as 'target parallel' has two captured regions: 7301 // for the 'target' and 'parallel' respectively. This function returns 7302 // the region in which to capture expressions associated with a clause. 7303 // A return value of OMPD_unknown signifies that the expression should not 7304 // be captured. 7305 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 7306 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 7307 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 7308 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7309 7310 switch (CKind) { 7311 case OMPC_if: 7312 switch (DKind) { 7313 case OMPD_target_parallel: 7314 case OMPD_target_parallel_for: 7315 case OMPD_target_parallel_for_simd: 7316 // If this clause applies to the nested 'parallel' region, capture within 7317 // the 'target' region, otherwise do not capture. 7318 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 7319 CaptureRegion = OMPD_target; 7320 break; 7321 case OMPD_cancel: 7322 case OMPD_parallel: 7323 case OMPD_parallel_sections: 7324 case OMPD_parallel_for: 7325 case OMPD_parallel_for_simd: 7326 case OMPD_target: 7327 case OMPD_target_simd: 7328 case OMPD_target_teams: 7329 case OMPD_target_teams_distribute: 7330 case OMPD_target_teams_distribute_simd: 7331 case OMPD_target_teams_distribute_parallel_for: 7332 case OMPD_target_teams_distribute_parallel_for_simd: 7333 case OMPD_teams_distribute_parallel_for: 7334 case OMPD_teams_distribute_parallel_for_simd: 7335 case OMPD_distribute_parallel_for: 7336 case OMPD_distribute_parallel_for_simd: 7337 case OMPD_task: 7338 case OMPD_taskloop: 7339 case OMPD_taskloop_simd: 7340 case OMPD_target_data: 7341 case OMPD_target_enter_data: 7342 case OMPD_target_exit_data: 7343 case OMPD_target_update: 7344 // Do not capture if-clause expressions. 7345 break; 7346 case OMPD_threadprivate: 7347 case OMPD_taskyield: 7348 case OMPD_barrier: 7349 case OMPD_taskwait: 7350 case OMPD_cancellation_point: 7351 case OMPD_flush: 7352 case OMPD_declare_reduction: 7353 case OMPD_declare_simd: 7354 case OMPD_declare_target: 7355 case OMPD_end_declare_target: 7356 case OMPD_teams: 7357 case OMPD_simd: 7358 case OMPD_for: 7359 case OMPD_for_simd: 7360 case OMPD_sections: 7361 case OMPD_section: 7362 case OMPD_single: 7363 case OMPD_master: 7364 case OMPD_critical: 7365 case OMPD_taskgroup: 7366 case OMPD_distribute: 7367 case OMPD_ordered: 7368 case OMPD_atomic: 7369 case OMPD_distribute_simd: 7370 case OMPD_teams_distribute: 7371 case OMPD_teams_distribute_simd: 7372 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 7373 case OMPD_unknown: 7374 llvm_unreachable("Unknown OpenMP directive"); 7375 } 7376 break; 7377 case OMPC_num_threads: 7378 switch (DKind) { 7379 case OMPD_target_parallel: 7380 case OMPD_target_parallel_for: 7381 case OMPD_target_parallel_for_simd: 7382 CaptureRegion = OMPD_target; 7383 break; 7384 case OMPD_cancel: 7385 case OMPD_parallel: 7386 case OMPD_parallel_sections: 7387 case OMPD_parallel_for: 7388 case OMPD_parallel_for_simd: 7389 case OMPD_target: 7390 case OMPD_target_simd: 7391 case OMPD_target_teams: 7392 case OMPD_target_teams_distribute: 7393 case OMPD_target_teams_distribute_simd: 7394 case OMPD_target_teams_distribute_parallel_for: 7395 case OMPD_target_teams_distribute_parallel_for_simd: 7396 case OMPD_teams_distribute_parallel_for: 7397 case OMPD_teams_distribute_parallel_for_simd: 7398 case OMPD_distribute_parallel_for: 7399 case OMPD_distribute_parallel_for_simd: 7400 case OMPD_task: 7401 case OMPD_taskloop: 7402 case OMPD_taskloop_simd: 7403 case OMPD_target_data: 7404 case OMPD_target_enter_data: 7405 case OMPD_target_exit_data: 7406 case OMPD_target_update: 7407 // Do not capture num_threads-clause expressions. 7408 break; 7409 case OMPD_threadprivate: 7410 case OMPD_taskyield: 7411 case OMPD_barrier: 7412 case OMPD_taskwait: 7413 case OMPD_cancellation_point: 7414 case OMPD_flush: 7415 case OMPD_declare_reduction: 7416 case OMPD_declare_simd: 7417 case OMPD_declare_target: 7418 case OMPD_end_declare_target: 7419 case OMPD_teams: 7420 case OMPD_simd: 7421 case OMPD_for: 7422 case OMPD_for_simd: 7423 case OMPD_sections: 7424 case OMPD_section: 7425 case OMPD_single: 7426 case OMPD_master: 7427 case OMPD_critical: 7428 case OMPD_taskgroup: 7429 case OMPD_distribute: 7430 case OMPD_ordered: 7431 case OMPD_atomic: 7432 case OMPD_distribute_simd: 7433 case OMPD_teams_distribute: 7434 case OMPD_teams_distribute_simd: 7435 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 7436 case OMPD_unknown: 7437 llvm_unreachable("Unknown OpenMP directive"); 7438 } 7439 break; 7440 case OMPC_num_teams: 7441 switch (DKind) { 7442 case OMPD_target_teams: 7443 CaptureRegion = OMPD_target; 7444 break; 7445 case OMPD_cancel: 7446 case OMPD_parallel: 7447 case OMPD_parallel_sections: 7448 case OMPD_parallel_for: 7449 case OMPD_parallel_for_simd: 7450 case OMPD_target: 7451 case OMPD_target_simd: 7452 case OMPD_target_parallel: 7453 case OMPD_target_parallel_for: 7454 case OMPD_target_parallel_for_simd: 7455 case OMPD_target_teams_distribute: 7456 case OMPD_target_teams_distribute_simd: 7457 case OMPD_target_teams_distribute_parallel_for: 7458 case OMPD_target_teams_distribute_parallel_for_simd: 7459 case OMPD_teams_distribute_parallel_for: 7460 case OMPD_teams_distribute_parallel_for_simd: 7461 case OMPD_distribute_parallel_for: 7462 case OMPD_distribute_parallel_for_simd: 7463 case OMPD_task: 7464 case OMPD_taskloop: 7465 case OMPD_taskloop_simd: 7466 case OMPD_target_data: 7467 case OMPD_target_enter_data: 7468 case OMPD_target_exit_data: 7469 case OMPD_target_update: 7470 case OMPD_teams: 7471 case OMPD_teams_distribute: 7472 case OMPD_teams_distribute_simd: 7473 // Do not capture num_teams-clause expressions. 7474 break; 7475 case OMPD_threadprivate: 7476 case OMPD_taskyield: 7477 case OMPD_barrier: 7478 case OMPD_taskwait: 7479 case OMPD_cancellation_point: 7480 case OMPD_flush: 7481 case OMPD_declare_reduction: 7482 case OMPD_declare_simd: 7483 case OMPD_declare_target: 7484 case OMPD_end_declare_target: 7485 case OMPD_simd: 7486 case OMPD_for: 7487 case OMPD_for_simd: 7488 case OMPD_sections: 7489 case OMPD_section: 7490 case OMPD_single: 7491 case OMPD_master: 7492 case OMPD_critical: 7493 case OMPD_taskgroup: 7494 case OMPD_distribute: 7495 case OMPD_ordered: 7496 case OMPD_atomic: 7497 case OMPD_distribute_simd: 7498 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 7499 case OMPD_unknown: 7500 llvm_unreachable("Unknown OpenMP directive"); 7501 } 7502 break; 7503 case OMPC_thread_limit: 7504 switch (DKind) { 7505 case OMPD_target_teams: 7506 CaptureRegion = OMPD_target; 7507 break; 7508 case OMPD_cancel: 7509 case OMPD_parallel: 7510 case OMPD_parallel_sections: 7511 case OMPD_parallel_for: 7512 case OMPD_parallel_for_simd: 7513 case OMPD_target: 7514 case OMPD_target_simd: 7515 case OMPD_target_parallel: 7516 case OMPD_target_parallel_for: 7517 case OMPD_target_parallel_for_simd: 7518 case OMPD_target_teams_distribute: 7519 case OMPD_target_teams_distribute_simd: 7520 case OMPD_target_teams_distribute_parallel_for: 7521 case OMPD_target_teams_distribute_parallel_for_simd: 7522 case OMPD_teams_distribute_parallel_for: 7523 case OMPD_teams_distribute_parallel_for_simd: 7524 case OMPD_distribute_parallel_for: 7525 case OMPD_distribute_parallel_for_simd: 7526 case OMPD_task: 7527 case OMPD_taskloop: 7528 case OMPD_taskloop_simd: 7529 case OMPD_target_data: 7530 case OMPD_target_enter_data: 7531 case OMPD_target_exit_data: 7532 case OMPD_target_update: 7533 case OMPD_teams: 7534 case OMPD_teams_distribute: 7535 case OMPD_teams_distribute_simd: 7536 // Do not capture thread_limit-clause expressions. 7537 break; 7538 case OMPD_threadprivate: 7539 case OMPD_taskyield: 7540 case OMPD_barrier: 7541 case OMPD_taskwait: 7542 case OMPD_cancellation_point: 7543 case OMPD_flush: 7544 case OMPD_declare_reduction: 7545 case OMPD_declare_simd: 7546 case OMPD_declare_target: 7547 case OMPD_end_declare_target: 7548 case OMPD_simd: 7549 case OMPD_for: 7550 case OMPD_for_simd: 7551 case OMPD_sections: 7552 case OMPD_section: 7553 case OMPD_single: 7554 case OMPD_master: 7555 case OMPD_critical: 7556 case OMPD_taskgroup: 7557 case OMPD_distribute: 7558 case OMPD_ordered: 7559 case OMPD_atomic: 7560 case OMPD_distribute_simd: 7561 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 7562 case OMPD_unknown: 7563 llvm_unreachable("Unknown OpenMP directive"); 7564 } 7565 break; 7566 case OMPC_schedule: 7567 switch (DKind) { 7568 case OMPD_target_parallel_for: 7569 case OMPD_target_parallel_for_simd: 7570 CaptureRegion = OMPD_target; 7571 break; 7572 case OMPD_parallel_for: 7573 case OMPD_parallel_for_simd: 7574 case OMPD_target_teams_distribute_parallel_for: 7575 case OMPD_target_teams_distribute_parallel_for_simd: 7576 case OMPD_teams_distribute_parallel_for: 7577 case OMPD_teams_distribute_parallel_for_simd: 7578 case OMPD_distribute_parallel_for: 7579 case OMPD_distribute_parallel_for_simd: 7580 // Do not capture thread_limit-clause expressions. 7581 break; 7582 case OMPD_task: 7583 case OMPD_taskloop: 7584 case OMPD_taskloop_simd: 7585 case OMPD_target_data: 7586 case OMPD_target_enter_data: 7587 case OMPD_target_exit_data: 7588 case OMPD_target_update: 7589 case OMPD_teams: 7590 case OMPD_teams_distribute: 7591 case OMPD_teams_distribute_simd: 7592 case OMPD_target_teams_distribute: 7593 case OMPD_target_teams_distribute_simd: 7594 case OMPD_target: 7595 case OMPD_target_simd: 7596 case OMPD_target_parallel: 7597 case OMPD_cancel: 7598 case OMPD_parallel: 7599 case OMPD_parallel_sections: 7600 case OMPD_threadprivate: 7601 case OMPD_taskyield: 7602 case OMPD_barrier: 7603 case OMPD_taskwait: 7604 case OMPD_cancellation_point: 7605 case OMPD_flush: 7606 case OMPD_declare_reduction: 7607 case OMPD_declare_simd: 7608 case OMPD_declare_target: 7609 case OMPD_end_declare_target: 7610 case OMPD_simd: 7611 case OMPD_for: 7612 case OMPD_for_simd: 7613 case OMPD_sections: 7614 case OMPD_section: 7615 case OMPD_single: 7616 case OMPD_master: 7617 case OMPD_critical: 7618 case OMPD_taskgroup: 7619 case OMPD_distribute: 7620 case OMPD_ordered: 7621 case OMPD_atomic: 7622 case OMPD_distribute_simd: 7623 case OMPD_target_teams: 7624 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 7625 case OMPD_unknown: 7626 llvm_unreachable("Unknown OpenMP directive"); 7627 } 7628 break; 7629 case OMPC_dist_schedule: 7630 case OMPC_firstprivate: 7631 case OMPC_lastprivate: 7632 case OMPC_reduction: 7633 case OMPC_task_reduction: 7634 case OMPC_in_reduction: 7635 case OMPC_linear: 7636 case OMPC_default: 7637 case OMPC_proc_bind: 7638 case OMPC_final: 7639 case OMPC_safelen: 7640 case OMPC_simdlen: 7641 case OMPC_collapse: 7642 case OMPC_private: 7643 case OMPC_shared: 7644 case OMPC_aligned: 7645 case OMPC_copyin: 7646 case OMPC_copyprivate: 7647 case OMPC_ordered: 7648 case OMPC_nowait: 7649 case OMPC_untied: 7650 case OMPC_mergeable: 7651 case OMPC_threadprivate: 7652 case OMPC_flush: 7653 case OMPC_read: 7654 case OMPC_write: 7655 case OMPC_update: 7656 case OMPC_capture: 7657 case OMPC_seq_cst: 7658 case OMPC_depend: 7659 case OMPC_device: 7660 case OMPC_threads: 7661 case OMPC_simd: 7662 case OMPC_map: 7663 case OMPC_priority: 7664 case OMPC_grainsize: 7665 case OMPC_nogroup: 7666 case OMPC_num_tasks: 7667 case OMPC_hint: 7668 case OMPC_defaultmap: 7669 case OMPC_unknown: 7670 case OMPC_uniform: 7671 case OMPC_to: 7672 case OMPC_from: 7673 case OMPC_use_device_ptr: 7674 case OMPC_is_device_ptr: 7675 llvm_unreachable("Unexpected OpenMP clause."); 7676 } 7677 return CaptureRegion; 7678 } 7679 7680 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 7681 Expr *Condition, SourceLocation StartLoc, 7682 SourceLocation LParenLoc, 7683 SourceLocation NameModifierLoc, 7684 SourceLocation ColonLoc, 7685 SourceLocation EndLoc) { 7686 Expr *ValExpr = Condition; 7687 Stmt *HelperValStmt = nullptr; 7688 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7689 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7690 !Condition->isInstantiationDependent() && 7691 !Condition->containsUnexpandedParameterPack()) { 7692 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7693 if (Val.isInvalid()) 7694 return nullptr; 7695 7696 ValExpr = MakeFullExpr(Val.get()).get(); 7697 7698 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7699 CaptureRegion = 7700 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 7701 if (CaptureRegion != OMPD_unknown) { 7702 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7703 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7704 HelperValStmt = buildPreInits(Context, Captures); 7705 } 7706 } 7707 7708 return new (Context) 7709 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 7710 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 7711 } 7712 7713 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 7714 SourceLocation StartLoc, 7715 SourceLocation LParenLoc, 7716 SourceLocation EndLoc) { 7717 Expr *ValExpr = Condition; 7718 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7719 !Condition->isInstantiationDependent() && 7720 !Condition->containsUnexpandedParameterPack()) { 7721 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7722 if (Val.isInvalid()) 7723 return nullptr; 7724 7725 ValExpr = MakeFullExpr(Val.get()).get(); 7726 } 7727 7728 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 7729 } 7730 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 7731 Expr *Op) { 7732 if (!Op) 7733 return ExprError(); 7734 7735 class IntConvertDiagnoser : public ICEConvertDiagnoser { 7736 public: 7737 IntConvertDiagnoser() 7738 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 7739 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 7740 QualType T) override { 7741 return S.Diag(Loc, diag::err_omp_not_integral) << T; 7742 } 7743 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 7744 QualType T) override { 7745 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 7746 } 7747 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 7748 QualType T, 7749 QualType ConvTy) override { 7750 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 7751 } 7752 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 7753 QualType ConvTy) override { 7754 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7755 << ConvTy->isEnumeralType() << ConvTy; 7756 } 7757 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 7758 QualType T) override { 7759 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 7760 } 7761 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 7762 QualType ConvTy) override { 7763 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7764 << ConvTy->isEnumeralType() << ConvTy; 7765 } 7766 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 7767 QualType) override { 7768 llvm_unreachable("conversion functions are permitted"); 7769 } 7770 } ConvertDiagnoser; 7771 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 7772 } 7773 7774 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 7775 OpenMPClauseKind CKind, 7776 bool StrictlyPositive) { 7777 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 7778 !ValExpr->isInstantiationDependent()) { 7779 SourceLocation Loc = ValExpr->getExprLoc(); 7780 ExprResult Value = 7781 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 7782 if (Value.isInvalid()) 7783 return false; 7784 7785 ValExpr = Value.get(); 7786 // The expression must evaluate to a non-negative integer value. 7787 llvm::APSInt Result; 7788 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 7789 Result.isSigned() && 7790 !((!StrictlyPositive && Result.isNonNegative()) || 7791 (StrictlyPositive && Result.isStrictlyPositive()))) { 7792 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 7793 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7794 << ValExpr->getSourceRange(); 7795 return false; 7796 } 7797 } 7798 return true; 7799 } 7800 7801 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 7802 SourceLocation StartLoc, 7803 SourceLocation LParenLoc, 7804 SourceLocation EndLoc) { 7805 Expr *ValExpr = NumThreads; 7806 Stmt *HelperValStmt = nullptr; 7807 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7808 7809 // OpenMP [2.5, Restrictions] 7810 // The num_threads expression must evaluate to a positive integer value. 7811 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 7812 /*StrictlyPositive=*/true)) 7813 return nullptr; 7814 7815 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7816 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 7817 if (CaptureRegion != OMPD_unknown) { 7818 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7819 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7820 HelperValStmt = buildPreInits(Context, Captures); 7821 } 7822 7823 return new (Context) OMPNumThreadsClause( 7824 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 7825 } 7826 7827 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 7828 OpenMPClauseKind CKind, 7829 bool StrictlyPositive) { 7830 if (!E) 7831 return ExprError(); 7832 if (E->isValueDependent() || E->isTypeDependent() || 7833 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 7834 return E; 7835 llvm::APSInt Result; 7836 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 7837 if (ICE.isInvalid()) 7838 return ExprError(); 7839 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 7840 (!StrictlyPositive && !Result.isNonNegative())) { 7841 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 7842 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7843 << E->getSourceRange(); 7844 return ExprError(); 7845 } 7846 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 7847 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 7848 << E->getSourceRange(); 7849 return ExprError(); 7850 } 7851 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 7852 DSAStack->setAssociatedLoops(Result.getExtValue()); 7853 else if (CKind == OMPC_ordered) 7854 DSAStack->setAssociatedLoops(Result.getExtValue()); 7855 return ICE; 7856 } 7857 7858 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 7859 SourceLocation LParenLoc, 7860 SourceLocation EndLoc) { 7861 // OpenMP [2.8.1, simd construct, Description] 7862 // The parameter of the safelen clause must be a constant 7863 // positive integer expression. 7864 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 7865 if (Safelen.isInvalid()) 7866 return nullptr; 7867 return new (Context) 7868 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 7869 } 7870 7871 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 7872 SourceLocation LParenLoc, 7873 SourceLocation EndLoc) { 7874 // OpenMP [2.8.1, simd construct, Description] 7875 // The parameter of the simdlen clause must be a constant 7876 // positive integer expression. 7877 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 7878 if (Simdlen.isInvalid()) 7879 return nullptr; 7880 return new (Context) 7881 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 7882 } 7883 7884 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 7885 SourceLocation StartLoc, 7886 SourceLocation LParenLoc, 7887 SourceLocation EndLoc) { 7888 // OpenMP [2.7.1, loop construct, Description] 7889 // OpenMP [2.8.1, simd construct, Description] 7890 // OpenMP [2.9.6, distribute construct, Description] 7891 // The parameter of the collapse clause must be a constant 7892 // positive integer expression. 7893 ExprResult NumForLoopsResult = 7894 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 7895 if (NumForLoopsResult.isInvalid()) 7896 return nullptr; 7897 return new (Context) 7898 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 7899 } 7900 7901 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 7902 SourceLocation EndLoc, 7903 SourceLocation LParenLoc, 7904 Expr *NumForLoops) { 7905 // OpenMP [2.7.1, loop construct, Description] 7906 // OpenMP [2.8.1, simd construct, Description] 7907 // OpenMP [2.9.6, distribute construct, Description] 7908 // The parameter of the ordered clause must be a constant 7909 // positive integer expression if any. 7910 if (NumForLoops && LParenLoc.isValid()) { 7911 ExprResult NumForLoopsResult = 7912 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 7913 if (NumForLoopsResult.isInvalid()) 7914 return nullptr; 7915 NumForLoops = NumForLoopsResult.get(); 7916 } else 7917 NumForLoops = nullptr; 7918 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 7919 return new (Context) 7920 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 7921 } 7922 7923 OMPClause *Sema::ActOnOpenMPSimpleClause( 7924 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 7925 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 7926 OMPClause *Res = nullptr; 7927 switch (Kind) { 7928 case OMPC_default: 7929 Res = 7930 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 7931 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 7932 break; 7933 case OMPC_proc_bind: 7934 Res = ActOnOpenMPProcBindClause( 7935 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 7936 LParenLoc, EndLoc); 7937 break; 7938 case OMPC_if: 7939 case OMPC_final: 7940 case OMPC_num_threads: 7941 case OMPC_safelen: 7942 case OMPC_simdlen: 7943 case OMPC_collapse: 7944 case OMPC_schedule: 7945 case OMPC_private: 7946 case OMPC_firstprivate: 7947 case OMPC_lastprivate: 7948 case OMPC_shared: 7949 case OMPC_reduction: 7950 case OMPC_task_reduction: 7951 case OMPC_in_reduction: 7952 case OMPC_linear: 7953 case OMPC_aligned: 7954 case OMPC_copyin: 7955 case OMPC_copyprivate: 7956 case OMPC_ordered: 7957 case OMPC_nowait: 7958 case OMPC_untied: 7959 case OMPC_mergeable: 7960 case OMPC_threadprivate: 7961 case OMPC_flush: 7962 case OMPC_read: 7963 case OMPC_write: 7964 case OMPC_update: 7965 case OMPC_capture: 7966 case OMPC_seq_cst: 7967 case OMPC_depend: 7968 case OMPC_device: 7969 case OMPC_threads: 7970 case OMPC_simd: 7971 case OMPC_map: 7972 case OMPC_num_teams: 7973 case OMPC_thread_limit: 7974 case OMPC_priority: 7975 case OMPC_grainsize: 7976 case OMPC_nogroup: 7977 case OMPC_num_tasks: 7978 case OMPC_hint: 7979 case OMPC_dist_schedule: 7980 case OMPC_defaultmap: 7981 case OMPC_unknown: 7982 case OMPC_uniform: 7983 case OMPC_to: 7984 case OMPC_from: 7985 case OMPC_use_device_ptr: 7986 case OMPC_is_device_ptr: 7987 llvm_unreachable("Clause is not allowed."); 7988 } 7989 return Res; 7990 } 7991 7992 static std::string 7993 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 7994 ArrayRef<unsigned> Exclude = llvm::None) { 7995 std::string Values; 7996 unsigned Bound = Last >= 2 ? Last - 2 : 0; 7997 unsigned Skipped = Exclude.size(); 7998 auto S = Exclude.begin(), E = Exclude.end(); 7999 for (unsigned i = First; i < Last; ++i) { 8000 if (std::find(S, E, i) != E) { 8001 --Skipped; 8002 continue; 8003 } 8004 Values += "'"; 8005 Values += getOpenMPSimpleClauseTypeName(K, i); 8006 Values += "'"; 8007 if (i == Bound - Skipped) 8008 Values += " or "; 8009 else if (i != Bound + 1 - Skipped) 8010 Values += ", "; 8011 } 8012 return Values; 8013 } 8014 8015 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 8016 SourceLocation KindKwLoc, 8017 SourceLocation StartLoc, 8018 SourceLocation LParenLoc, 8019 SourceLocation EndLoc) { 8020 if (Kind == OMPC_DEFAULT_unknown) { 8021 static_assert(OMPC_DEFAULT_unknown > 0, 8022 "OMPC_DEFAULT_unknown not greater than 0"); 8023 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 8024 << getListOfPossibleValues(OMPC_default, /*First=*/0, 8025 /*Last=*/OMPC_DEFAULT_unknown) 8026 << getOpenMPClauseName(OMPC_default); 8027 return nullptr; 8028 } 8029 switch (Kind) { 8030 case OMPC_DEFAULT_none: 8031 DSAStack->setDefaultDSANone(KindKwLoc); 8032 break; 8033 case OMPC_DEFAULT_shared: 8034 DSAStack->setDefaultDSAShared(KindKwLoc); 8035 break; 8036 case OMPC_DEFAULT_unknown: 8037 llvm_unreachable("Clause kind is not allowed."); 8038 break; 8039 } 8040 return new (Context) 8041 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 8042 } 8043 8044 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 8045 SourceLocation KindKwLoc, 8046 SourceLocation StartLoc, 8047 SourceLocation LParenLoc, 8048 SourceLocation EndLoc) { 8049 if (Kind == OMPC_PROC_BIND_unknown) { 8050 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 8051 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 8052 /*Last=*/OMPC_PROC_BIND_unknown) 8053 << getOpenMPClauseName(OMPC_proc_bind); 8054 return nullptr; 8055 } 8056 return new (Context) 8057 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 8058 } 8059 8060 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 8061 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 8062 SourceLocation StartLoc, SourceLocation LParenLoc, 8063 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 8064 SourceLocation EndLoc) { 8065 OMPClause *Res = nullptr; 8066 switch (Kind) { 8067 case OMPC_schedule: 8068 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 8069 assert(Argument.size() == NumberOfElements && 8070 ArgumentLoc.size() == NumberOfElements); 8071 Res = ActOnOpenMPScheduleClause( 8072 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 8073 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 8074 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 8075 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 8076 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 8077 break; 8078 case OMPC_if: 8079 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 8080 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 8081 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 8082 DelimLoc, EndLoc); 8083 break; 8084 case OMPC_dist_schedule: 8085 Res = ActOnOpenMPDistScheduleClause( 8086 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 8087 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 8088 break; 8089 case OMPC_defaultmap: 8090 enum { Modifier, DefaultmapKind }; 8091 Res = ActOnOpenMPDefaultmapClause( 8092 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 8093 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 8094 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 8095 EndLoc); 8096 break; 8097 case OMPC_final: 8098 case OMPC_num_threads: 8099 case OMPC_safelen: 8100 case OMPC_simdlen: 8101 case OMPC_collapse: 8102 case OMPC_default: 8103 case OMPC_proc_bind: 8104 case OMPC_private: 8105 case OMPC_firstprivate: 8106 case OMPC_lastprivate: 8107 case OMPC_shared: 8108 case OMPC_reduction: 8109 case OMPC_task_reduction: 8110 case OMPC_in_reduction: 8111 case OMPC_linear: 8112 case OMPC_aligned: 8113 case OMPC_copyin: 8114 case OMPC_copyprivate: 8115 case OMPC_ordered: 8116 case OMPC_nowait: 8117 case OMPC_untied: 8118 case OMPC_mergeable: 8119 case OMPC_threadprivate: 8120 case OMPC_flush: 8121 case OMPC_read: 8122 case OMPC_write: 8123 case OMPC_update: 8124 case OMPC_capture: 8125 case OMPC_seq_cst: 8126 case OMPC_depend: 8127 case OMPC_device: 8128 case OMPC_threads: 8129 case OMPC_simd: 8130 case OMPC_map: 8131 case OMPC_num_teams: 8132 case OMPC_thread_limit: 8133 case OMPC_priority: 8134 case OMPC_grainsize: 8135 case OMPC_nogroup: 8136 case OMPC_num_tasks: 8137 case OMPC_hint: 8138 case OMPC_unknown: 8139 case OMPC_uniform: 8140 case OMPC_to: 8141 case OMPC_from: 8142 case OMPC_use_device_ptr: 8143 case OMPC_is_device_ptr: 8144 llvm_unreachable("Clause is not allowed."); 8145 } 8146 return Res; 8147 } 8148 8149 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 8150 OpenMPScheduleClauseModifier M2, 8151 SourceLocation M1Loc, SourceLocation M2Loc) { 8152 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 8153 SmallVector<unsigned, 2> Excluded; 8154 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 8155 Excluded.push_back(M2); 8156 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 8157 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 8158 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 8159 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 8160 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 8161 << getListOfPossibleValues(OMPC_schedule, 8162 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 8163 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 8164 Excluded) 8165 << getOpenMPClauseName(OMPC_schedule); 8166 return true; 8167 } 8168 return false; 8169 } 8170 8171 OMPClause *Sema::ActOnOpenMPScheduleClause( 8172 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 8173 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 8174 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 8175 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 8176 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 8177 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 8178 return nullptr; 8179 // OpenMP, 2.7.1, Loop Construct, Restrictions 8180 // Either the monotonic modifier or the nonmonotonic modifier can be specified 8181 // but not both. 8182 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 8183 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 8184 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 8185 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 8186 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 8187 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 8188 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 8189 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 8190 return nullptr; 8191 } 8192 if (Kind == OMPC_SCHEDULE_unknown) { 8193 std::string Values; 8194 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 8195 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 8196 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 8197 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 8198 Exclude); 8199 } else { 8200 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 8201 /*Last=*/OMPC_SCHEDULE_unknown); 8202 } 8203 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 8204 << Values << getOpenMPClauseName(OMPC_schedule); 8205 return nullptr; 8206 } 8207 // OpenMP, 2.7.1, Loop Construct, Restrictions 8208 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 8209 // schedule(guided). 8210 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 8211 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 8212 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 8213 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 8214 diag::err_omp_schedule_nonmonotonic_static); 8215 return nullptr; 8216 } 8217 Expr *ValExpr = ChunkSize; 8218 Stmt *HelperValStmt = nullptr; 8219 if (ChunkSize) { 8220 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 8221 !ChunkSize->isInstantiationDependent() && 8222 !ChunkSize->containsUnexpandedParameterPack()) { 8223 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 8224 ExprResult Val = 8225 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 8226 if (Val.isInvalid()) 8227 return nullptr; 8228 8229 ValExpr = Val.get(); 8230 8231 // OpenMP [2.7.1, Restrictions] 8232 // chunk_size must be a loop invariant integer expression with a positive 8233 // value. 8234 llvm::APSInt Result; 8235 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 8236 if (Result.isSigned() && !Result.isStrictlyPositive()) { 8237 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 8238 << "schedule" << 1 << ChunkSize->getSourceRange(); 8239 return nullptr; 8240 } 8241 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 8242 !CurContext->isDependentContext()) { 8243 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 8244 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 8245 HelperValStmt = buildPreInits(Context, Captures); 8246 } 8247 } 8248 } 8249 8250 return new (Context) 8251 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 8252 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 8253 } 8254 8255 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 8256 SourceLocation StartLoc, 8257 SourceLocation EndLoc) { 8258 OMPClause *Res = nullptr; 8259 switch (Kind) { 8260 case OMPC_ordered: 8261 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 8262 break; 8263 case OMPC_nowait: 8264 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 8265 break; 8266 case OMPC_untied: 8267 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 8268 break; 8269 case OMPC_mergeable: 8270 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 8271 break; 8272 case OMPC_read: 8273 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 8274 break; 8275 case OMPC_write: 8276 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 8277 break; 8278 case OMPC_update: 8279 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 8280 break; 8281 case OMPC_capture: 8282 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 8283 break; 8284 case OMPC_seq_cst: 8285 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 8286 break; 8287 case OMPC_threads: 8288 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 8289 break; 8290 case OMPC_simd: 8291 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 8292 break; 8293 case OMPC_nogroup: 8294 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 8295 break; 8296 case OMPC_if: 8297 case OMPC_final: 8298 case OMPC_num_threads: 8299 case OMPC_safelen: 8300 case OMPC_simdlen: 8301 case OMPC_collapse: 8302 case OMPC_schedule: 8303 case OMPC_private: 8304 case OMPC_firstprivate: 8305 case OMPC_lastprivate: 8306 case OMPC_shared: 8307 case OMPC_reduction: 8308 case OMPC_task_reduction: 8309 case OMPC_in_reduction: 8310 case OMPC_linear: 8311 case OMPC_aligned: 8312 case OMPC_copyin: 8313 case OMPC_copyprivate: 8314 case OMPC_default: 8315 case OMPC_proc_bind: 8316 case OMPC_threadprivate: 8317 case OMPC_flush: 8318 case OMPC_depend: 8319 case OMPC_device: 8320 case OMPC_map: 8321 case OMPC_num_teams: 8322 case OMPC_thread_limit: 8323 case OMPC_priority: 8324 case OMPC_grainsize: 8325 case OMPC_num_tasks: 8326 case OMPC_hint: 8327 case OMPC_dist_schedule: 8328 case OMPC_defaultmap: 8329 case OMPC_unknown: 8330 case OMPC_uniform: 8331 case OMPC_to: 8332 case OMPC_from: 8333 case OMPC_use_device_ptr: 8334 case OMPC_is_device_ptr: 8335 llvm_unreachable("Clause is not allowed."); 8336 } 8337 return Res; 8338 } 8339 8340 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 8341 SourceLocation EndLoc) { 8342 DSAStack->setNowaitRegion(); 8343 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 8344 } 8345 8346 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 8347 SourceLocation EndLoc) { 8348 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 8349 } 8350 8351 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 8352 SourceLocation EndLoc) { 8353 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 8354 } 8355 8356 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 8357 SourceLocation EndLoc) { 8358 return new (Context) OMPReadClause(StartLoc, EndLoc); 8359 } 8360 8361 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 8362 SourceLocation EndLoc) { 8363 return new (Context) OMPWriteClause(StartLoc, EndLoc); 8364 } 8365 8366 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 8367 SourceLocation EndLoc) { 8368 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 8369 } 8370 8371 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 8372 SourceLocation EndLoc) { 8373 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 8374 } 8375 8376 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 8377 SourceLocation EndLoc) { 8378 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 8379 } 8380 8381 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 8382 SourceLocation EndLoc) { 8383 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 8384 } 8385 8386 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 8387 SourceLocation EndLoc) { 8388 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 8389 } 8390 8391 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 8392 SourceLocation EndLoc) { 8393 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 8394 } 8395 8396 OMPClause *Sema::ActOnOpenMPVarListClause( 8397 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 8398 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 8399 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 8400 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 8401 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 8402 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 8403 SourceLocation DepLinMapLoc) { 8404 OMPClause *Res = nullptr; 8405 switch (Kind) { 8406 case OMPC_private: 8407 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8408 break; 8409 case OMPC_firstprivate: 8410 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8411 break; 8412 case OMPC_lastprivate: 8413 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8414 break; 8415 case OMPC_shared: 8416 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 8417 break; 8418 case OMPC_reduction: 8419 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8420 EndLoc, ReductionIdScopeSpec, ReductionId); 8421 break; 8422 case OMPC_task_reduction: 8423 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8424 EndLoc, ReductionIdScopeSpec, 8425 ReductionId); 8426 break; 8427 case OMPC_in_reduction: 8428 Res = 8429 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8430 EndLoc, ReductionIdScopeSpec, ReductionId); 8431 break; 8432 case OMPC_linear: 8433 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 8434 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 8435 break; 8436 case OMPC_aligned: 8437 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 8438 ColonLoc, EndLoc); 8439 break; 8440 case OMPC_copyin: 8441 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 8442 break; 8443 case OMPC_copyprivate: 8444 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8445 break; 8446 case OMPC_flush: 8447 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 8448 break; 8449 case OMPC_depend: 8450 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 8451 StartLoc, LParenLoc, EndLoc); 8452 break; 8453 case OMPC_map: 8454 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 8455 DepLinMapLoc, ColonLoc, VarList, StartLoc, 8456 LParenLoc, EndLoc); 8457 break; 8458 case OMPC_to: 8459 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 8460 break; 8461 case OMPC_from: 8462 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 8463 break; 8464 case OMPC_use_device_ptr: 8465 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 8466 break; 8467 case OMPC_is_device_ptr: 8468 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 8469 break; 8470 case OMPC_if: 8471 case OMPC_final: 8472 case OMPC_num_threads: 8473 case OMPC_safelen: 8474 case OMPC_simdlen: 8475 case OMPC_collapse: 8476 case OMPC_default: 8477 case OMPC_proc_bind: 8478 case OMPC_schedule: 8479 case OMPC_ordered: 8480 case OMPC_nowait: 8481 case OMPC_untied: 8482 case OMPC_mergeable: 8483 case OMPC_threadprivate: 8484 case OMPC_read: 8485 case OMPC_write: 8486 case OMPC_update: 8487 case OMPC_capture: 8488 case OMPC_seq_cst: 8489 case OMPC_device: 8490 case OMPC_threads: 8491 case OMPC_simd: 8492 case OMPC_num_teams: 8493 case OMPC_thread_limit: 8494 case OMPC_priority: 8495 case OMPC_grainsize: 8496 case OMPC_nogroup: 8497 case OMPC_num_tasks: 8498 case OMPC_hint: 8499 case OMPC_dist_schedule: 8500 case OMPC_defaultmap: 8501 case OMPC_unknown: 8502 case OMPC_uniform: 8503 llvm_unreachable("Clause is not allowed."); 8504 } 8505 return Res; 8506 } 8507 8508 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 8509 ExprObjectKind OK, SourceLocation Loc) { 8510 ExprResult Res = BuildDeclRefExpr( 8511 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 8512 if (!Res.isUsable()) 8513 return ExprError(); 8514 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 8515 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 8516 if (!Res.isUsable()) 8517 return ExprError(); 8518 } 8519 if (VK != VK_LValue && Res.get()->isGLValue()) { 8520 Res = DefaultLvalueConversion(Res.get()); 8521 if (!Res.isUsable()) 8522 return ExprError(); 8523 } 8524 return Res; 8525 } 8526 8527 static std::pair<ValueDecl *, bool> 8528 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 8529 SourceRange &ERange, bool AllowArraySection = false) { 8530 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 8531 RefExpr->containsUnexpandedParameterPack()) 8532 return std::make_pair(nullptr, true); 8533 8534 // OpenMP [3.1, C/C++] 8535 // A list item is a variable name. 8536 // OpenMP [2.9.3.3, Restrictions, p.1] 8537 // A variable that is part of another variable (as an array or 8538 // structure element) cannot appear in a private clause. 8539 RefExpr = RefExpr->IgnoreParens(); 8540 enum { 8541 NoArrayExpr = -1, 8542 ArraySubscript = 0, 8543 OMPArraySection = 1 8544 } IsArrayExpr = NoArrayExpr; 8545 if (AllowArraySection) { 8546 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 8547 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 8548 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 8549 Base = TempASE->getBase()->IgnoreParenImpCasts(); 8550 RefExpr = Base; 8551 IsArrayExpr = ArraySubscript; 8552 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 8553 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 8554 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 8555 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 8556 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 8557 Base = TempASE->getBase()->IgnoreParenImpCasts(); 8558 RefExpr = Base; 8559 IsArrayExpr = OMPArraySection; 8560 } 8561 } 8562 ELoc = RefExpr->getExprLoc(); 8563 ERange = RefExpr->getSourceRange(); 8564 RefExpr = RefExpr->IgnoreParenImpCasts(); 8565 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 8566 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 8567 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 8568 (S.getCurrentThisType().isNull() || !ME || 8569 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 8570 !isa<FieldDecl>(ME->getMemberDecl()))) { 8571 if (IsArrayExpr != NoArrayExpr) 8572 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 8573 << ERange; 8574 else { 8575 S.Diag(ELoc, 8576 AllowArraySection 8577 ? diag::err_omp_expected_var_name_member_expr_or_array_item 8578 : diag::err_omp_expected_var_name_member_expr) 8579 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 8580 } 8581 return std::make_pair(nullptr, false); 8582 } 8583 return std::make_pair( 8584 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 8585 } 8586 8587 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 8588 SourceLocation StartLoc, 8589 SourceLocation LParenLoc, 8590 SourceLocation EndLoc) { 8591 SmallVector<Expr *, 8> Vars; 8592 SmallVector<Expr *, 8> PrivateCopies; 8593 for (auto &RefExpr : VarList) { 8594 assert(RefExpr && "NULL expr in OpenMP private clause."); 8595 SourceLocation ELoc; 8596 SourceRange ERange; 8597 Expr *SimpleRefExpr = RefExpr; 8598 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8599 if (Res.second) { 8600 // It will be analyzed later. 8601 Vars.push_back(RefExpr); 8602 PrivateCopies.push_back(nullptr); 8603 } 8604 ValueDecl *D = Res.first; 8605 if (!D) 8606 continue; 8607 8608 QualType Type = D->getType(); 8609 auto *VD = dyn_cast<VarDecl>(D); 8610 8611 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8612 // A variable that appears in a private clause must not have an incomplete 8613 // type or a reference type. 8614 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 8615 continue; 8616 Type = Type.getNonReferenceType(); 8617 8618 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8619 // in a Construct] 8620 // Variables with the predetermined data-sharing attributes may not be 8621 // listed in data-sharing attributes clauses, except for the cases 8622 // listed below. For these exceptions only, listing a predetermined 8623 // variable in a data-sharing attribute clause is allowed and overrides 8624 // the variable's predetermined data-sharing attributes. 8625 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8626 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 8627 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8628 << getOpenMPClauseName(OMPC_private); 8629 ReportOriginalDSA(*this, DSAStack, D, DVar); 8630 continue; 8631 } 8632 8633 auto CurrDir = DSAStack->getCurrentDirective(); 8634 // Variably modified types are not supported for tasks. 8635 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8636 isOpenMPTaskingDirective(CurrDir)) { 8637 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8638 << getOpenMPClauseName(OMPC_private) << Type 8639 << getOpenMPDirectiveName(CurrDir); 8640 bool IsDecl = 8641 !VD || 8642 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8643 Diag(D->getLocation(), 8644 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8645 << D; 8646 continue; 8647 } 8648 8649 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8650 // A list item cannot appear in both a map clause and a data-sharing 8651 // attribute clause on the same construct 8652 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 8653 CurrDir == OMPD_target_teams || 8654 CurrDir == OMPD_target_teams_distribute || 8655 CurrDir == OMPD_target_teams_distribute_parallel_for || 8656 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 8657 CurrDir == OMPD_target_teams_distribute_simd || 8658 CurrDir == OMPD_target_parallel_for_simd || 8659 CurrDir == OMPD_target_parallel_for) { 8660 OpenMPClauseKind ConflictKind; 8661 if (DSAStack->checkMappableExprComponentListsForDecl( 8662 VD, /*CurrentRegionOnly=*/true, 8663 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 8664 OpenMPClauseKind WhereFoundClauseKind) -> bool { 8665 ConflictKind = WhereFoundClauseKind; 8666 return true; 8667 })) { 8668 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 8669 << getOpenMPClauseName(OMPC_private) 8670 << getOpenMPClauseName(ConflictKind) 8671 << getOpenMPDirectiveName(CurrDir); 8672 ReportOriginalDSA(*this, DSAStack, D, DVar); 8673 continue; 8674 } 8675 } 8676 8677 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 8678 // A variable of class type (or array thereof) that appears in a private 8679 // clause requires an accessible, unambiguous default constructor for the 8680 // class type. 8681 // Generate helper private variable and initialize it with the default 8682 // value. The address of the original variable is replaced by the address of 8683 // the new private variable in CodeGen. This new variable is not added to 8684 // IdResolver, so the code in the OpenMP region uses original variable for 8685 // proper diagnostics. 8686 Type = Type.getUnqualifiedType(); 8687 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8688 D->hasAttrs() ? &D->getAttrs() : nullptr); 8689 ActOnUninitializedDecl(VDPrivate); 8690 if (VDPrivate->isInvalidDecl()) 8691 continue; 8692 auto VDPrivateRefExpr = buildDeclRefExpr( 8693 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 8694 8695 DeclRefExpr *Ref = nullptr; 8696 if (!VD && !CurContext->isDependentContext()) 8697 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8698 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 8699 Vars.push_back((VD || CurContext->isDependentContext()) 8700 ? RefExpr->IgnoreParens() 8701 : Ref); 8702 PrivateCopies.push_back(VDPrivateRefExpr); 8703 } 8704 8705 if (Vars.empty()) 8706 return nullptr; 8707 8708 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 8709 PrivateCopies); 8710 } 8711 8712 namespace { 8713 class DiagsUninitializedSeveretyRAII { 8714 private: 8715 DiagnosticsEngine &Diags; 8716 SourceLocation SavedLoc; 8717 bool IsIgnored; 8718 8719 public: 8720 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 8721 bool IsIgnored) 8722 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 8723 if (!IsIgnored) { 8724 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 8725 /*Map*/ diag::Severity::Ignored, Loc); 8726 } 8727 } 8728 ~DiagsUninitializedSeveretyRAII() { 8729 if (!IsIgnored) 8730 Diags.popMappings(SavedLoc); 8731 } 8732 }; 8733 } 8734 8735 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 8736 SourceLocation StartLoc, 8737 SourceLocation LParenLoc, 8738 SourceLocation EndLoc) { 8739 SmallVector<Expr *, 8> Vars; 8740 SmallVector<Expr *, 8> PrivateCopies; 8741 SmallVector<Expr *, 8> Inits; 8742 SmallVector<Decl *, 4> ExprCaptures; 8743 bool IsImplicitClause = 8744 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 8745 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 8746 8747 for (auto &RefExpr : VarList) { 8748 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 8749 SourceLocation ELoc; 8750 SourceRange ERange; 8751 Expr *SimpleRefExpr = RefExpr; 8752 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8753 if (Res.second) { 8754 // It will be analyzed later. 8755 Vars.push_back(RefExpr); 8756 PrivateCopies.push_back(nullptr); 8757 Inits.push_back(nullptr); 8758 } 8759 ValueDecl *D = Res.first; 8760 if (!D) 8761 continue; 8762 8763 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 8764 QualType Type = D->getType(); 8765 auto *VD = dyn_cast<VarDecl>(D); 8766 8767 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8768 // A variable that appears in a private clause must not have an incomplete 8769 // type or a reference type. 8770 if (RequireCompleteType(ELoc, Type, 8771 diag::err_omp_firstprivate_incomplete_type)) 8772 continue; 8773 Type = Type.getNonReferenceType(); 8774 8775 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 8776 // A variable of class type (or array thereof) that appears in a private 8777 // clause requires an accessible, unambiguous copy constructor for the 8778 // class type. 8779 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 8780 8781 // If an implicit firstprivate variable found it was checked already. 8782 DSAStackTy::DSAVarData TopDVar; 8783 if (!IsImplicitClause) { 8784 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8785 TopDVar = DVar; 8786 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8787 bool IsConstant = ElemType.isConstant(Context); 8788 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 8789 // A list item that specifies a given variable may not appear in more 8790 // than one clause on the same directive, except that a variable may be 8791 // specified in both firstprivate and lastprivate clauses. 8792 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8793 // A list item may appear in a firstprivate or lastprivate clause but not 8794 // both. 8795 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 8796 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) && 8797 DVar.RefExpr) { 8798 Diag(ELoc, diag::err_omp_wrong_dsa) 8799 << getOpenMPClauseName(DVar.CKind) 8800 << getOpenMPClauseName(OMPC_firstprivate); 8801 ReportOriginalDSA(*this, DSAStack, D, DVar); 8802 continue; 8803 } 8804 8805 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8806 // in a Construct] 8807 // Variables with the predetermined data-sharing attributes may not be 8808 // listed in data-sharing attributes clauses, except for the cases 8809 // listed below. For these exceptions only, listing a predetermined 8810 // variable in a data-sharing attribute clause is allowed and overrides 8811 // the variable's predetermined data-sharing attributes. 8812 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8813 // in a Construct, C/C++, p.2] 8814 // Variables with const-qualified type having no mutable member may be 8815 // listed in a firstprivate clause, even if they are static data members. 8816 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 8817 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 8818 Diag(ELoc, diag::err_omp_wrong_dsa) 8819 << getOpenMPClauseName(DVar.CKind) 8820 << getOpenMPClauseName(OMPC_firstprivate); 8821 ReportOriginalDSA(*this, DSAStack, D, DVar); 8822 continue; 8823 } 8824 8825 // OpenMP [2.9.3.4, Restrictions, p.2] 8826 // A list item that is private within a parallel region must not appear 8827 // in a firstprivate clause on a worksharing construct if any of the 8828 // worksharing regions arising from the worksharing construct ever bind 8829 // to any of the parallel regions arising from the parallel construct. 8830 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8831 // A list item that is private within a teams region must not appear in a 8832 // firstprivate clause on a distribute construct if any of the distribute 8833 // regions arising from the distribute construct ever bind to any of the 8834 // teams regions arising from the teams construct. 8835 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8836 // A list item that appears in a reduction clause of a teams construct 8837 // must not appear in a firstprivate clause on a distribute construct if 8838 // any of the distribute regions arising from the distribute construct 8839 // ever bind to any of the teams regions arising from the teams construct. 8840 if ((isOpenMPWorksharingDirective(CurrDir) || 8841 isOpenMPDistributeDirective(CurrDir)) && 8842 !isOpenMPParallelDirective(CurrDir) && 8843 !isOpenMPTeamsDirective(CurrDir)) { 8844 DVar = DSAStack->getImplicitDSA(D, true); 8845 if (DVar.CKind != OMPC_shared && 8846 (isOpenMPParallelDirective(DVar.DKind) || 8847 isOpenMPTeamsDirective(DVar.DKind) || 8848 DVar.DKind == OMPD_unknown)) { 8849 Diag(ELoc, diag::err_omp_required_access) 8850 << getOpenMPClauseName(OMPC_firstprivate) 8851 << getOpenMPClauseName(OMPC_shared); 8852 ReportOriginalDSA(*this, DSAStack, D, DVar); 8853 continue; 8854 } 8855 } 8856 // OpenMP [2.9.3.4, Restrictions, p.3] 8857 // A list item that appears in a reduction clause of a parallel construct 8858 // must not appear in a firstprivate clause on a worksharing or task 8859 // construct if any of the worksharing or task regions arising from the 8860 // worksharing or task construct ever bind to any of the parallel regions 8861 // arising from the parallel construct. 8862 // OpenMP [2.9.3.4, Restrictions, p.4] 8863 // A list item that appears in a reduction clause in worksharing 8864 // construct must not appear in a firstprivate clause in a task construct 8865 // encountered during execution of any of the worksharing regions arising 8866 // from the worksharing construct. 8867 if (isOpenMPTaskingDirective(CurrDir)) { 8868 DVar = DSAStack->hasInnermostDSA( 8869 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8870 [](OpenMPDirectiveKind K) -> bool { 8871 return isOpenMPParallelDirective(K) || 8872 isOpenMPWorksharingDirective(K) || 8873 isOpenMPTeamsDirective(K); 8874 }, 8875 /*FromParent=*/true); 8876 if (DVar.CKind == OMPC_reduction && 8877 (isOpenMPParallelDirective(DVar.DKind) || 8878 isOpenMPWorksharingDirective(DVar.DKind) || 8879 isOpenMPTeamsDirective(DVar.DKind))) { 8880 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 8881 << getOpenMPDirectiveName(DVar.DKind); 8882 ReportOriginalDSA(*this, DSAStack, D, DVar); 8883 continue; 8884 } 8885 } 8886 8887 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8888 // A list item cannot appear in both a map clause and a data-sharing 8889 // attribute clause on the same construct 8890 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 8891 CurrDir == OMPD_target_teams || 8892 CurrDir == OMPD_target_teams_distribute || 8893 CurrDir == OMPD_target_teams_distribute_parallel_for || 8894 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 8895 CurrDir == OMPD_target_teams_distribute_simd || 8896 CurrDir == OMPD_target_parallel_for_simd || 8897 CurrDir == OMPD_target_parallel_for) { 8898 OpenMPClauseKind ConflictKind; 8899 if (DSAStack->checkMappableExprComponentListsForDecl( 8900 VD, /*CurrentRegionOnly=*/true, 8901 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 8902 OpenMPClauseKind WhereFoundClauseKind) -> bool { 8903 ConflictKind = WhereFoundClauseKind; 8904 return true; 8905 })) { 8906 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 8907 << getOpenMPClauseName(OMPC_firstprivate) 8908 << getOpenMPClauseName(ConflictKind) 8909 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8910 ReportOriginalDSA(*this, DSAStack, D, DVar); 8911 continue; 8912 } 8913 } 8914 } 8915 8916 // Variably modified types are not supported for tasks. 8917 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8918 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 8919 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8920 << getOpenMPClauseName(OMPC_firstprivate) << Type 8921 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8922 bool IsDecl = 8923 !VD || 8924 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8925 Diag(D->getLocation(), 8926 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8927 << D; 8928 continue; 8929 } 8930 8931 Type = Type.getUnqualifiedType(); 8932 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8933 D->hasAttrs() ? &D->getAttrs() : nullptr); 8934 // Generate helper private variable and initialize it with the value of the 8935 // original variable. The address of the original variable is replaced by 8936 // the address of the new private variable in the CodeGen. This new variable 8937 // is not added to IdResolver, so the code in the OpenMP region uses 8938 // original variable for proper diagnostics and variable capturing. 8939 Expr *VDInitRefExpr = nullptr; 8940 // For arrays generate initializer for single element and replace it by the 8941 // original array element in CodeGen. 8942 if (Type->isArrayType()) { 8943 auto VDInit = 8944 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 8945 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 8946 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 8947 ElemType = ElemType.getUnqualifiedType(); 8948 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 8949 ".firstprivate.temp"); 8950 InitializedEntity Entity = 8951 InitializedEntity::InitializeVariable(VDInitTemp); 8952 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 8953 8954 InitializationSequence InitSeq(*this, Entity, Kind, Init); 8955 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 8956 if (Result.isInvalid()) 8957 VDPrivate->setInvalidDecl(); 8958 else 8959 VDPrivate->setInit(Result.getAs<Expr>()); 8960 // Remove temp variable declaration. 8961 Context.Deallocate(VDInitTemp); 8962 } else { 8963 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 8964 ".firstprivate.temp"); 8965 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 8966 RefExpr->getExprLoc()); 8967 AddInitializerToDecl(VDPrivate, 8968 DefaultLvalueConversion(VDInitRefExpr).get(), 8969 /*DirectInit=*/false); 8970 } 8971 if (VDPrivate->isInvalidDecl()) { 8972 if (IsImplicitClause) { 8973 Diag(RefExpr->getExprLoc(), 8974 diag::note_omp_task_predetermined_firstprivate_here); 8975 } 8976 continue; 8977 } 8978 CurContext->addDecl(VDPrivate); 8979 auto VDPrivateRefExpr = buildDeclRefExpr( 8980 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 8981 RefExpr->getExprLoc()); 8982 DeclRefExpr *Ref = nullptr; 8983 if (!VD && !CurContext->isDependentContext()) { 8984 if (TopDVar.CKind == OMPC_lastprivate) 8985 Ref = TopDVar.PrivateCopy; 8986 else { 8987 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8988 if (!IsOpenMPCapturedDecl(D)) 8989 ExprCaptures.push_back(Ref->getDecl()); 8990 } 8991 } 8992 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 8993 Vars.push_back((VD || CurContext->isDependentContext()) 8994 ? RefExpr->IgnoreParens() 8995 : Ref); 8996 PrivateCopies.push_back(VDPrivateRefExpr); 8997 Inits.push_back(VDInitRefExpr); 8998 } 8999 9000 if (Vars.empty()) 9001 return nullptr; 9002 9003 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9004 Vars, PrivateCopies, Inits, 9005 buildPreInits(Context, ExprCaptures)); 9006 } 9007 9008 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 9009 SourceLocation StartLoc, 9010 SourceLocation LParenLoc, 9011 SourceLocation EndLoc) { 9012 SmallVector<Expr *, 8> Vars; 9013 SmallVector<Expr *, 8> SrcExprs; 9014 SmallVector<Expr *, 8> DstExprs; 9015 SmallVector<Expr *, 8> AssignmentOps; 9016 SmallVector<Decl *, 4> ExprCaptures; 9017 SmallVector<Expr *, 4> ExprPostUpdates; 9018 for (auto &RefExpr : VarList) { 9019 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 9020 SourceLocation ELoc; 9021 SourceRange ERange; 9022 Expr *SimpleRefExpr = RefExpr; 9023 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9024 if (Res.second) { 9025 // It will be analyzed later. 9026 Vars.push_back(RefExpr); 9027 SrcExprs.push_back(nullptr); 9028 DstExprs.push_back(nullptr); 9029 AssignmentOps.push_back(nullptr); 9030 } 9031 ValueDecl *D = Res.first; 9032 if (!D) 9033 continue; 9034 9035 QualType Type = D->getType(); 9036 auto *VD = dyn_cast<VarDecl>(D); 9037 9038 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 9039 // A variable that appears in a lastprivate clause must not have an 9040 // incomplete type or a reference type. 9041 if (RequireCompleteType(ELoc, Type, 9042 diag::err_omp_lastprivate_incomplete_type)) 9043 continue; 9044 Type = Type.getNonReferenceType(); 9045 9046 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9047 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 9048 // in a Construct] 9049 // Variables with the predetermined data-sharing attributes may not be 9050 // listed in data-sharing attributes clauses, except for the cases 9051 // listed below. 9052 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 9053 // A list item may appear in a firstprivate or lastprivate clause but not 9054 // both. 9055 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9056 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 9057 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) && 9058 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 9059 Diag(ELoc, diag::err_omp_wrong_dsa) 9060 << getOpenMPClauseName(DVar.CKind) 9061 << getOpenMPClauseName(OMPC_lastprivate); 9062 ReportOriginalDSA(*this, DSAStack, D, DVar); 9063 continue; 9064 } 9065 9066 // OpenMP [2.14.3.5, Restrictions, p.2] 9067 // A list item that is private within a parallel region, or that appears in 9068 // the reduction clause of a parallel construct, must not appear in a 9069 // lastprivate clause on a worksharing construct if any of the corresponding 9070 // worksharing regions ever binds to any of the corresponding parallel 9071 // regions. 9072 DSAStackTy::DSAVarData TopDVar = DVar; 9073 if (isOpenMPWorksharingDirective(CurrDir) && 9074 !isOpenMPParallelDirective(CurrDir) && 9075 !isOpenMPTeamsDirective(CurrDir)) { 9076 DVar = DSAStack->getImplicitDSA(D, true); 9077 if (DVar.CKind != OMPC_shared) { 9078 Diag(ELoc, diag::err_omp_required_access) 9079 << getOpenMPClauseName(OMPC_lastprivate) 9080 << getOpenMPClauseName(OMPC_shared); 9081 ReportOriginalDSA(*this, DSAStack, D, DVar); 9082 continue; 9083 } 9084 } 9085 9086 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 9087 // A variable of class type (or array thereof) that appears in a 9088 // lastprivate clause requires an accessible, unambiguous default 9089 // constructor for the class type, unless the list item is also specified 9090 // in a firstprivate clause. 9091 // A variable of class type (or array thereof) that appears in a 9092 // lastprivate clause requires an accessible, unambiguous copy assignment 9093 // operator for the class type. 9094 Type = Context.getBaseElementType(Type).getNonReferenceType(); 9095 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 9096 Type.getUnqualifiedType(), ".lastprivate.src", 9097 D->hasAttrs() ? &D->getAttrs() : nullptr); 9098 auto *PseudoSrcExpr = 9099 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 9100 auto *DstVD = 9101 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 9102 D->hasAttrs() ? &D->getAttrs() : nullptr); 9103 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 9104 // For arrays generate assignment operation for single element and replace 9105 // it by the original array element in CodeGen. 9106 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 9107 PseudoDstExpr, PseudoSrcExpr); 9108 if (AssignmentOp.isInvalid()) 9109 continue; 9110 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 9111 /*DiscardedValue=*/true); 9112 if (AssignmentOp.isInvalid()) 9113 continue; 9114 9115 DeclRefExpr *Ref = nullptr; 9116 if (!VD && !CurContext->isDependentContext()) { 9117 if (TopDVar.CKind == OMPC_firstprivate) 9118 Ref = TopDVar.PrivateCopy; 9119 else { 9120 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9121 if (!IsOpenMPCapturedDecl(D)) 9122 ExprCaptures.push_back(Ref->getDecl()); 9123 } 9124 if (TopDVar.CKind == OMPC_firstprivate || 9125 (!IsOpenMPCapturedDecl(D) && 9126 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 9127 ExprResult RefRes = DefaultLvalueConversion(Ref); 9128 if (!RefRes.isUsable()) 9129 continue; 9130 ExprResult PostUpdateRes = 9131 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 9132 RefRes.get()); 9133 if (!PostUpdateRes.isUsable()) 9134 continue; 9135 ExprPostUpdates.push_back( 9136 IgnoredValueConversions(PostUpdateRes.get()).get()); 9137 } 9138 } 9139 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 9140 Vars.push_back((VD || CurContext->isDependentContext()) 9141 ? RefExpr->IgnoreParens() 9142 : Ref); 9143 SrcExprs.push_back(PseudoSrcExpr); 9144 DstExprs.push_back(PseudoDstExpr); 9145 AssignmentOps.push_back(AssignmentOp.get()); 9146 } 9147 9148 if (Vars.empty()) 9149 return nullptr; 9150 9151 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9152 Vars, SrcExprs, DstExprs, AssignmentOps, 9153 buildPreInits(Context, ExprCaptures), 9154 buildPostUpdate(*this, ExprPostUpdates)); 9155 } 9156 9157 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 9158 SourceLocation StartLoc, 9159 SourceLocation LParenLoc, 9160 SourceLocation EndLoc) { 9161 SmallVector<Expr *, 8> Vars; 9162 for (auto &RefExpr : VarList) { 9163 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 9164 SourceLocation ELoc; 9165 SourceRange ERange; 9166 Expr *SimpleRefExpr = RefExpr; 9167 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9168 if (Res.second) { 9169 // It will be analyzed later. 9170 Vars.push_back(RefExpr); 9171 } 9172 ValueDecl *D = Res.first; 9173 if (!D) 9174 continue; 9175 9176 auto *VD = dyn_cast<VarDecl>(D); 9177 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9178 // in a Construct] 9179 // Variables with the predetermined data-sharing attributes may not be 9180 // listed in data-sharing attributes clauses, except for the cases 9181 // listed below. For these exceptions only, listing a predetermined 9182 // variable in a data-sharing attribute clause is allowed and overrides 9183 // the variable's predetermined data-sharing attributes. 9184 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9185 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 9186 DVar.RefExpr) { 9187 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9188 << getOpenMPClauseName(OMPC_shared); 9189 ReportOriginalDSA(*this, DSAStack, D, DVar); 9190 continue; 9191 } 9192 9193 DeclRefExpr *Ref = nullptr; 9194 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 9195 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9196 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 9197 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 9198 ? RefExpr->IgnoreParens() 9199 : Ref); 9200 } 9201 9202 if (Vars.empty()) 9203 return nullptr; 9204 9205 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 9206 } 9207 9208 namespace { 9209 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 9210 DSAStackTy *Stack; 9211 9212 public: 9213 bool VisitDeclRefExpr(DeclRefExpr *E) { 9214 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 9215 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 9216 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 9217 return false; 9218 if (DVar.CKind != OMPC_unknown) 9219 return true; 9220 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 9221 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 9222 /*FromParent=*/true); 9223 if (DVarPrivate.CKind != OMPC_unknown) 9224 return true; 9225 return false; 9226 } 9227 return false; 9228 } 9229 bool VisitStmt(Stmt *S) { 9230 for (auto Child : S->children()) { 9231 if (Child && Visit(Child)) 9232 return true; 9233 } 9234 return false; 9235 } 9236 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 9237 }; 9238 } // namespace 9239 9240 namespace { 9241 // Transform MemberExpression for specified FieldDecl of current class to 9242 // DeclRefExpr to specified OMPCapturedExprDecl. 9243 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 9244 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 9245 ValueDecl *Field; 9246 DeclRefExpr *CapturedExpr; 9247 9248 public: 9249 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 9250 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 9251 9252 ExprResult TransformMemberExpr(MemberExpr *E) { 9253 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 9254 E->getMemberDecl() == Field) { 9255 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 9256 return CapturedExpr; 9257 } 9258 return BaseTransform::TransformMemberExpr(E); 9259 } 9260 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 9261 }; 9262 } // namespace 9263 9264 template <typename T> 9265 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 9266 const llvm::function_ref<T(ValueDecl *)> &Gen) { 9267 for (auto &Set : Lookups) { 9268 for (auto *D : Set) { 9269 if (auto Res = Gen(cast<ValueDecl>(D))) 9270 return Res; 9271 } 9272 } 9273 return T(); 9274 } 9275 9276 static ExprResult 9277 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 9278 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 9279 const DeclarationNameInfo &ReductionId, QualType Ty, 9280 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 9281 if (ReductionIdScopeSpec.isInvalid()) 9282 return ExprError(); 9283 SmallVector<UnresolvedSet<8>, 4> Lookups; 9284 if (S) { 9285 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 9286 Lookup.suppressDiagnostics(); 9287 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 9288 auto *D = Lookup.getRepresentativeDecl(); 9289 do { 9290 S = S->getParent(); 9291 } while (S && !S->isDeclScope(D)); 9292 if (S) 9293 S = S->getParent(); 9294 Lookups.push_back(UnresolvedSet<8>()); 9295 Lookups.back().append(Lookup.begin(), Lookup.end()); 9296 Lookup.clear(); 9297 } 9298 } else if (auto *ULE = 9299 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 9300 Lookups.push_back(UnresolvedSet<8>()); 9301 Decl *PrevD = nullptr; 9302 for (auto *D : ULE->decls()) { 9303 if (D == PrevD) 9304 Lookups.push_back(UnresolvedSet<8>()); 9305 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 9306 Lookups.back().addDecl(DRD); 9307 PrevD = D; 9308 } 9309 } 9310 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 9311 Ty->isInstantiationDependentType() || 9312 Ty->containsUnexpandedParameterPack() || 9313 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 9314 return !D->isInvalidDecl() && 9315 (D->getType()->isDependentType() || 9316 D->getType()->isInstantiationDependentType() || 9317 D->getType()->containsUnexpandedParameterPack()); 9318 })) { 9319 UnresolvedSet<8> ResSet; 9320 for (auto &Set : Lookups) { 9321 ResSet.append(Set.begin(), Set.end()); 9322 // The last item marks the end of all declarations at the specified scope. 9323 ResSet.addDecl(Set[Set.size() - 1]); 9324 } 9325 return UnresolvedLookupExpr::Create( 9326 SemaRef.Context, /*NamingClass=*/nullptr, 9327 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 9328 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 9329 } 9330 if (auto *VD = filterLookupForUDR<ValueDecl *>( 9331 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 9332 if (!D->isInvalidDecl() && 9333 SemaRef.Context.hasSameType(D->getType(), Ty)) 9334 return D; 9335 return nullptr; 9336 })) 9337 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 9338 if (auto *VD = filterLookupForUDR<ValueDecl *>( 9339 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 9340 if (!D->isInvalidDecl() && 9341 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 9342 !Ty.isMoreQualifiedThan(D->getType())) 9343 return D; 9344 return nullptr; 9345 })) { 9346 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9347 /*DetectVirtual=*/false); 9348 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 9349 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 9350 VD->getType().getUnqualifiedType()))) { 9351 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 9352 /*DiagID=*/0) != 9353 Sema::AR_inaccessible) { 9354 SemaRef.BuildBasePathArray(Paths, BasePath); 9355 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 9356 } 9357 } 9358 } 9359 } 9360 if (ReductionIdScopeSpec.isSet()) { 9361 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 9362 return ExprError(); 9363 } 9364 return ExprEmpty(); 9365 } 9366 9367 namespace { 9368 /// Data for the reduction-based clauses. 9369 struct ReductionData { 9370 /// List of original reduction items. 9371 SmallVector<Expr *, 8> Vars; 9372 /// List of private copies of the reduction items. 9373 SmallVector<Expr *, 8> Privates; 9374 /// LHS expressions for the reduction_op expressions. 9375 SmallVector<Expr *, 8> LHSs; 9376 /// RHS expressions for the reduction_op expressions. 9377 SmallVector<Expr *, 8> RHSs; 9378 /// Reduction operation expression. 9379 SmallVector<Expr *, 8> ReductionOps; 9380 /// Taskgroup descriptors for the corresponding reduction items in 9381 /// in_reduction clauses. 9382 SmallVector<Expr *, 8> TaskgroupDescriptors; 9383 /// List of captures for clause. 9384 SmallVector<Decl *, 4> ExprCaptures; 9385 /// List of postupdate expressions. 9386 SmallVector<Expr *, 4> ExprPostUpdates; 9387 ReductionData() = delete; 9388 /// Reserves required memory for the reduction data. 9389 ReductionData(unsigned Size) { 9390 Vars.reserve(Size); 9391 Privates.reserve(Size); 9392 LHSs.reserve(Size); 9393 RHSs.reserve(Size); 9394 ReductionOps.reserve(Size); 9395 TaskgroupDescriptors.reserve(Size); 9396 ExprCaptures.reserve(Size); 9397 ExprPostUpdates.reserve(Size); 9398 } 9399 /// Stores reduction item and reduction operation only (required for dependent 9400 /// reduction item). 9401 void push(Expr *Item, Expr *ReductionOp) { 9402 Vars.emplace_back(Item); 9403 Privates.emplace_back(nullptr); 9404 LHSs.emplace_back(nullptr); 9405 RHSs.emplace_back(nullptr); 9406 ReductionOps.emplace_back(ReductionOp); 9407 TaskgroupDescriptors.emplace_back(nullptr); 9408 } 9409 /// Stores reduction data. 9410 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 9411 Expr *TaskgroupDescriptor) { 9412 Vars.emplace_back(Item); 9413 Privates.emplace_back(Private); 9414 LHSs.emplace_back(LHS); 9415 RHSs.emplace_back(RHS); 9416 ReductionOps.emplace_back(ReductionOp); 9417 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 9418 } 9419 }; 9420 } // namespace 9421 9422 static bool CheckOMPArraySectionConstantForReduction( 9423 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 9424 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 9425 const Expr *Length = OASE->getLength(); 9426 if (Length == nullptr) { 9427 // For array sections of the form [1:] or [:], we would need to analyze 9428 // the lower bound... 9429 if (OASE->getColonLoc().isValid()) 9430 return false; 9431 9432 // This is an array subscript which has implicit length 1! 9433 SingleElement = true; 9434 ArraySizes.push_back(llvm::APSInt::get(1)); 9435 } else { 9436 llvm::APSInt ConstantLengthValue; 9437 if (!Length->EvaluateAsInt(ConstantLengthValue, Context)) 9438 return false; 9439 9440 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 9441 ArraySizes.push_back(ConstantLengthValue); 9442 } 9443 9444 // Get the base of this array section and walk up from there. 9445 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 9446 9447 // We require length = 1 for all array sections except the right-most to 9448 // guarantee that the memory region is contiguous and has no holes in it. 9449 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 9450 Length = TempOASE->getLength(); 9451 if (Length == nullptr) { 9452 // For array sections of the form [1:] or [:], we would need to analyze 9453 // the lower bound... 9454 if (OASE->getColonLoc().isValid()) 9455 return false; 9456 9457 // This is an array subscript which has implicit length 1! 9458 ArraySizes.push_back(llvm::APSInt::get(1)); 9459 } else { 9460 llvm::APSInt ConstantLengthValue; 9461 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) || 9462 ConstantLengthValue.getSExtValue() != 1) 9463 return false; 9464 9465 ArraySizes.push_back(ConstantLengthValue); 9466 } 9467 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 9468 } 9469 9470 // If we have a single element, we don't need to add the implicit lengths. 9471 if (!SingleElement) { 9472 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 9473 // Has implicit length 1! 9474 ArraySizes.push_back(llvm::APSInt::get(1)); 9475 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9476 } 9477 } 9478 9479 // This array section can be privatized as a single value or as a constant 9480 // sized array. 9481 return true; 9482 } 9483 9484 static bool ActOnOMPReductionKindClause( 9485 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 9486 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 9487 SourceLocation ColonLoc, SourceLocation EndLoc, 9488 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 9489 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 9490 auto DN = ReductionId.getName(); 9491 auto OOK = DN.getCXXOverloadedOperator(); 9492 BinaryOperatorKind BOK = BO_Comma; 9493 9494 ASTContext &Context = S.Context; 9495 // OpenMP [2.14.3.6, reduction clause] 9496 // C 9497 // reduction-identifier is either an identifier or one of the following 9498 // operators: +, -, *, &, |, ^, && and || 9499 // C++ 9500 // reduction-identifier is either an id-expression or one of the following 9501 // operators: +, -, *, &, |, ^, && and || 9502 switch (OOK) { 9503 case OO_Plus: 9504 case OO_Minus: 9505 BOK = BO_Add; 9506 break; 9507 case OO_Star: 9508 BOK = BO_Mul; 9509 break; 9510 case OO_Amp: 9511 BOK = BO_And; 9512 break; 9513 case OO_Pipe: 9514 BOK = BO_Or; 9515 break; 9516 case OO_Caret: 9517 BOK = BO_Xor; 9518 break; 9519 case OO_AmpAmp: 9520 BOK = BO_LAnd; 9521 break; 9522 case OO_PipePipe: 9523 BOK = BO_LOr; 9524 break; 9525 case OO_New: 9526 case OO_Delete: 9527 case OO_Array_New: 9528 case OO_Array_Delete: 9529 case OO_Slash: 9530 case OO_Percent: 9531 case OO_Tilde: 9532 case OO_Exclaim: 9533 case OO_Equal: 9534 case OO_Less: 9535 case OO_Greater: 9536 case OO_LessEqual: 9537 case OO_GreaterEqual: 9538 case OO_PlusEqual: 9539 case OO_MinusEqual: 9540 case OO_StarEqual: 9541 case OO_SlashEqual: 9542 case OO_PercentEqual: 9543 case OO_CaretEqual: 9544 case OO_AmpEqual: 9545 case OO_PipeEqual: 9546 case OO_LessLess: 9547 case OO_GreaterGreater: 9548 case OO_LessLessEqual: 9549 case OO_GreaterGreaterEqual: 9550 case OO_EqualEqual: 9551 case OO_ExclaimEqual: 9552 case OO_PlusPlus: 9553 case OO_MinusMinus: 9554 case OO_Comma: 9555 case OO_ArrowStar: 9556 case OO_Arrow: 9557 case OO_Call: 9558 case OO_Subscript: 9559 case OO_Conditional: 9560 case OO_Coawait: 9561 case NUM_OVERLOADED_OPERATORS: 9562 llvm_unreachable("Unexpected reduction identifier"); 9563 case OO_None: 9564 if (auto *II = DN.getAsIdentifierInfo()) { 9565 if (II->isStr("max")) 9566 BOK = BO_GT; 9567 else if (II->isStr("min")) 9568 BOK = BO_LT; 9569 } 9570 break; 9571 } 9572 SourceRange ReductionIdRange; 9573 if (ReductionIdScopeSpec.isValid()) 9574 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 9575 else 9576 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 9577 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 9578 9579 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 9580 bool FirstIter = true; 9581 for (auto RefExpr : VarList) { 9582 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 9583 // OpenMP [2.1, C/C++] 9584 // A list item is a variable or array section, subject to the restrictions 9585 // specified in Section 2.4 on page 42 and in each of the sections 9586 // describing clauses and directives for which a list appears. 9587 // OpenMP [2.14.3.3, Restrictions, p.1] 9588 // A variable that is part of another variable (as an array or 9589 // structure element) cannot appear in a private clause. 9590 if (!FirstIter && IR != ER) 9591 ++IR; 9592 FirstIter = false; 9593 SourceLocation ELoc; 9594 SourceRange ERange; 9595 Expr *SimpleRefExpr = RefExpr; 9596 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 9597 /*AllowArraySection=*/true); 9598 if (Res.second) { 9599 // Try to find 'declare reduction' corresponding construct before using 9600 // builtin/overloaded operators. 9601 QualType Type = Context.DependentTy; 9602 CXXCastPath BasePath; 9603 ExprResult DeclareReductionRef = buildDeclareReductionRef( 9604 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 9605 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 9606 Expr *ReductionOp = nullptr; 9607 if (S.CurContext->isDependentContext() && 9608 (DeclareReductionRef.isUnset() || 9609 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 9610 ReductionOp = DeclareReductionRef.get(); 9611 // It will be analyzed later. 9612 RD.push(RefExpr, ReductionOp); 9613 } 9614 ValueDecl *D = Res.first; 9615 if (!D) 9616 continue; 9617 9618 Expr *TaskgroupDescriptor = nullptr; 9619 QualType Type; 9620 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 9621 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 9622 if (ASE) 9623 Type = ASE->getType().getNonReferenceType(); 9624 else if (OASE) { 9625 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 9626 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 9627 Type = ATy->getElementType(); 9628 else 9629 Type = BaseType->getPointeeType(); 9630 Type = Type.getNonReferenceType(); 9631 } else 9632 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 9633 auto *VD = dyn_cast<VarDecl>(D); 9634 9635 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9636 // A variable that appears in a private clause must not have an incomplete 9637 // type or a reference type. 9638 if (S.RequireCompleteType(ELoc, Type, 9639 diag::err_omp_reduction_incomplete_type)) 9640 continue; 9641 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9642 // A list item that appears in a reduction clause must not be 9643 // const-qualified. 9644 if (Type.getNonReferenceType().isConstant(Context)) { 9645 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange; 9646 if (!ASE && !OASE) { 9647 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9648 VarDecl::DeclarationOnly; 9649 S.Diag(D->getLocation(), 9650 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9651 << D; 9652 } 9653 continue; 9654 } 9655 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 9656 // If a list-item is a reference type then it must bind to the same object 9657 // for all threads of the team. 9658 if (!ASE && !OASE && VD) { 9659 VarDecl *VDDef = VD->getDefinition(); 9660 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 9661 DSARefChecker Check(Stack); 9662 if (Check.Visit(VDDef->getInit())) { 9663 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 9664 << getOpenMPClauseName(ClauseKind) << ERange; 9665 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 9666 continue; 9667 } 9668 } 9669 } 9670 9671 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 9672 // in a Construct] 9673 // Variables with the predetermined data-sharing attributes may not be 9674 // listed in data-sharing attributes clauses, except for the cases 9675 // listed below. For these exceptions only, listing a predetermined 9676 // variable in a data-sharing attribute clause is allowed and overrides 9677 // the variable's predetermined data-sharing attributes. 9678 // OpenMP [2.14.3.6, Restrictions, p.3] 9679 // Any number of reduction clauses can be specified on the directive, 9680 // but a list item can appear only once in the reduction clauses for that 9681 // directive. 9682 DSAStackTy::DSAVarData DVar; 9683 DVar = Stack->getTopDSA(D, false); 9684 if (DVar.CKind == OMPC_reduction) { 9685 S.Diag(ELoc, diag::err_omp_once_referenced) 9686 << getOpenMPClauseName(ClauseKind); 9687 if (DVar.RefExpr) 9688 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 9689 continue; 9690 } else if (DVar.CKind != OMPC_unknown) { 9691 S.Diag(ELoc, diag::err_omp_wrong_dsa) 9692 << getOpenMPClauseName(DVar.CKind) 9693 << getOpenMPClauseName(OMPC_reduction); 9694 ReportOriginalDSA(S, Stack, D, DVar); 9695 continue; 9696 } 9697 9698 // OpenMP [2.14.3.6, Restrictions, p.1] 9699 // A list item that appears in a reduction clause of a worksharing 9700 // construct must be shared in the parallel regions to which any of the 9701 // worksharing regions arising from the worksharing construct bind. 9702 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 9703 if (isOpenMPWorksharingDirective(CurrDir) && 9704 !isOpenMPParallelDirective(CurrDir) && 9705 !isOpenMPTeamsDirective(CurrDir)) { 9706 DVar = Stack->getImplicitDSA(D, true); 9707 if (DVar.CKind != OMPC_shared) { 9708 S.Diag(ELoc, diag::err_omp_required_access) 9709 << getOpenMPClauseName(OMPC_reduction) 9710 << getOpenMPClauseName(OMPC_shared); 9711 ReportOriginalDSA(S, Stack, D, DVar); 9712 continue; 9713 } 9714 } 9715 9716 // Try to find 'declare reduction' corresponding construct before using 9717 // builtin/overloaded operators. 9718 CXXCastPath BasePath; 9719 ExprResult DeclareReductionRef = buildDeclareReductionRef( 9720 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 9721 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 9722 if (DeclareReductionRef.isInvalid()) 9723 continue; 9724 if (S.CurContext->isDependentContext() && 9725 (DeclareReductionRef.isUnset() || 9726 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 9727 RD.push(RefExpr, DeclareReductionRef.get()); 9728 continue; 9729 } 9730 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 9731 // Not allowed reduction identifier is found. 9732 S.Diag(ReductionId.getLocStart(), 9733 diag::err_omp_unknown_reduction_identifier) 9734 << Type << ReductionIdRange; 9735 continue; 9736 } 9737 9738 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9739 // The type of a list item that appears in a reduction clause must be valid 9740 // for the reduction-identifier. For a max or min reduction in C, the type 9741 // of the list item must be an allowed arithmetic data type: char, int, 9742 // float, double, or _Bool, possibly modified with long, short, signed, or 9743 // unsigned. For a max or min reduction in C++, the type of the list item 9744 // must be an allowed arithmetic data type: char, wchar_t, int, float, 9745 // double, or bool, possibly modified with long, short, signed, or unsigned. 9746 if (DeclareReductionRef.isUnset()) { 9747 if ((BOK == BO_GT || BOK == BO_LT) && 9748 !(Type->isScalarType() || 9749 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 9750 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 9751 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 9752 if (!ASE && !OASE) { 9753 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9754 VarDecl::DeclarationOnly; 9755 S.Diag(D->getLocation(), 9756 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9757 << D; 9758 } 9759 continue; 9760 } 9761 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 9762 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 9763 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 9764 << getOpenMPClauseName(ClauseKind); 9765 if (!ASE && !OASE) { 9766 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9767 VarDecl::DeclarationOnly; 9768 S.Diag(D->getLocation(), 9769 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9770 << D; 9771 } 9772 continue; 9773 } 9774 } 9775 9776 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 9777 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 9778 D->hasAttrs() ? &D->getAttrs() : nullptr); 9779 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 9780 D->hasAttrs() ? &D->getAttrs() : nullptr); 9781 auto PrivateTy = Type; 9782 9783 // Try if we can determine constant lengths for all array sections and avoid 9784 // the VLA. 9785 bool ConstantLengthOASE = false; 9786 if (OASE) { 9787 bool SingleElement; 9788 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 9789 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction( 9790 Context, OASE, SingleElement, ArraySizes); 9791 9792 // If we don't have a single element, we must emit a constant array type. 9793 if (ConstantLengthOASE && !SingleElement) { 9794 for (auto &Size : ArraySizes) { 9795 PrivateTy = Context.getConstantArrayType( 9796 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0); 9797 } 9798 } 9799 } 9800 9801 if ((OASE && !ConstantLengthOASE) || 9802 (!OASE && !ASE && 9803 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 9804 // For arrays/array sections only: 9805 // Create pseudo array type for private copy. The size for this array will 9806 // be generated during codegen. 9807 // For array subscripts or single variables Private Ty is the same as Type 9808 // (type of the variable or single array element). 9809 PrivateTy = Context.getVariableArrayType( 9810 Type, 9811 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue), 9812 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 9813 } else if (!ASE && !OASE && 9814 Context.getAsArrayType(D->getType().getNonReferenceType())) 9815 PrivateTy = D->getType().getNonReferenceType(); 9816 // Private copy. 9817 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(), 9818 D->hasAttrs() ? &D->getAttrs() : nullptr); 9819 // Add initializer for private variable. 9820 Expr *Init = nullptr; 9821 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 9822 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 9823 if (DeclareReductionRef.isUsable()) { 9824 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 9825 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 9826 if (DRD->getInitializer()) { 9827 Init = DRDRef; 9828 RHSVD->setInit(DRDRef); 9829 RHSVD->setInitStyle(VarDecl::CallInit); 9830 } 9831 } else { 9832 switch (BOK) { 9833 case BO_Add: 9834 case BO_Xor: 9835 case BO_Or: 9836 case BO_LOr: 9837 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 9838 if (Type->isScalarType() || Type->isAnyComplexType()) 9839 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 9840 break; 9841 case BO_Mul: 9842 case BO_LAnd: 9843 if (Type->isScalarType() || Type->isAnyComplexType()) { 9844 // '*' and '&&' reduction ops - initializer is '1'. 9845 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 9846 } 9847 break; 9848 case BO_And: { 9849 // '&' reduction op - initializer is '~0'. 9850 QualType OrigType = Type; 9851 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 9852 Type = ComplexTy->getElementType(); 9853 if (Type->isRealFloatingType()) { 9854 llvm::APFloat InitValue = 9855 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 9856 /*isIEEE=*/true); 9857 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9858 Type, ELoc); 9859 } else if (Type->isScalarType()) { 9860 auto Size = Context.getTypeSize(Type); 9861 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 9862 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 9863 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9864 } 9865 if (Init && OrigType->isAnyComplexType()) { 9866 // Init = 0xFFFF + 0xFFFFi; 9867 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 9868 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 9869 } 9870 Type = OrigType; 9871 break; 9872 } 9873 case BO_LT: 9874 case BO_GT: { 9875 // 'min' reduction op - initializer is 'Largest representable number in 9876 // the reduction list item type'. 9877 // 'max' reduction op - initializer is 'Least representable number in 9878 // the reduction list item type'. 9879 if (Type->isIntegerType() || Type->isPointerType()) { 9880 bool IsSigned = Type->hasSignedIntegerRepresentation(); 9881 auto Size = Context.getTypeSize(Type); 9882 QualType IntTy = 9883 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 9884 llvm::APInt InitValue = 9885 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 9886 : llvm::APInt::getMinValue(Size) 9887 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 9888 : llvm::APInt::getMaxValue(Size); 9889 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9890 if (Type->isPointerType()) { 9891 // Cast to pointer type. 9892 auto CastExpr = S.BuildCStyleCastExpr( 9893 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 9894 if (CastExpr.isInvalid()) 9895 continue; 9896 Init = CastExpr.get(); 9897 } 9898 } else if (Type->isRealFloatingType()) { 9899 llvm::APFloat InitValue = llvm::APFloat::getLargest( 9900 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 9901 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9902 Type, ELoc); 9903 } 9904 break; 9905 } 9906 case BO_PtrMemD: 9907 case BO_PtrMemI: 9908 case BO_MulAssign: 9909 case BO_Div: 9910 case BO_Rem: 9911 case BO_Sub: 9912 case BO_Shl: 9913 case BO_Shr: 9914 case BO_LE: 9915 case BO_GE: 9916 case BO_EQ: 9917 case BO_NE: 9918 case BO_AndAssign: 9919 case BO_XorAssign: 9920 case BO_OrAssign: 9921 case BO_Assign: 9922 case BO_AddAssign: 9923 case BO_SubAssign: 9924 case BO_DivAssign: 9925 case BO_RemAssign: 9926 case BO_ShlAssign: 9927 case BO_ShrAssign: 9928 case BO_Comma: 9929 llvm_unreachable("Unexpected reduction operation"); 9930 } 9931 } 9932 if (Init && DeclareReductionRef.isUnset()) 9933 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 9934 else if (!Init) 9935 S.ActOnUninitializedDecl(RHSVD); 9936 if (RHSVD->isInvalidDecl()) 9937 continue; 9938 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 9939 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 9940 << Type << ReductionIdRange; 9941 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9942 VarDecl::DeclarationOnly; 9943 S.Diag(D->getLocation(), 9944 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9945 << D; 9946 continue; 9947 } 9948 // Store initializer for single element in private copy. Will be used during 9949 // codegen. 9950 PrivateVD->setInit(RHSVD->getInit()); 9951 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 9952 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 9953 ExprResult ReductionOp; 9954 if (DeclareReductionRef.isUsable()) { 9955 QualType RedTy = DeclareReductionRef.get()->getType(); 9956 QualType PtrRedTy = Context.getPointerType(RedTy); 9957 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 9958 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 9959 if (!BasePath.empty()) { 9960 LHS = S.DefaultLvalueConversion(LHS.get()); 9961 RHS = S.DefaultLvalueConversion(RHS.get()); 9962 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9963 CK_UncheckedDerivedToBase, LHS.get(), 9964 &BasePath, LHS.get()->getValueKind()); 9965 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9966 CK_UncheckedDerivedToBase, RHS.get(), 9967 &BasePath, RHS.get()->getValueKind()); 9968 } 9969 FunctionProtoType::ExtProtoInfo EPI; 9970 QualType Params[] = {PtrRedTy, PtrRedTy}; 9971 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 9972 auto *OVE = new (Context) OpaqueValueExpr( 9973 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 9974 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 9975 Expr *Args[] = {LHS.get(), RHS.get()}; 9976 ReductionOp = new (Context) 9977 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 9978 } else { 9979 ReductionOp = S.BuildBinOp( 9980 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 9981 if (ReductionOp.isUsable()) { 9982 if (BOK != BO_LT && BOK != BO_GT) { 9983 ReductionOp = 9984 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), 9985 BO_Assign, LHSDRE, ReductionOp.get()); 9986 } else { 9987 auto *ConditionalOp = new (Context) 9988 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE, 9989 Type, VK_LValue, OK_Ordinary); 9990 ReductionOp = 9991 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), 9992 BO_Assign, LHSDRE, ConditionalOp); 9993 } 9994 if (ReductionOp.isUsable()) 9995 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get()); 9996 } 9997 if (!ReductionOp.isUsable()) 9998 continue; 9999 } 10000 10001 // OpenMP [2.15.4.6, Restrictions, p.2] 10002 // A list item that appears in an in_reduction clause of a task construct 10003 // must appear in a task_reduction clause of a construct associated with a 10004 // taskgroup region that includes the participating task in its taskgroup 10005 // set. The construct associated with the innermost region that meets this 10006 // condition must specify the same reduction-identifier as the in_reduction 10007 // clause. 10008 if (ClauseKind == OMPC_in_reduction) { 10009 SourceRange ParentSR; 10010 BinaryOperatorKind ParentBOK; 10011 const Expr *ParentReductionOp; 10012 Expr *ParentBOKTD, *ParentReductionOpTD; 10013 DSAStackTy::DSAVarData ParentBOKDSA = 10014 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 10015 ParentBOKTD); 10016 DSAStackTy::DSAVarData ParentReductionOpDSA = 10017 Stack->getTopMostTaskgroupReductionData( 10018 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 10019 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 10020 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 10021 if (!IsParentBOK && !IsParentReductionOp) { 10022 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction); 10023 continue; 10024 } 10025 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 10026 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK || 10027 IsParentReductionOp) { 10028 bool EmitError = true; 10029 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 10030 llvm::FoldingSetNodeID RedId, ParentRedId; 10031 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 10032 DeclareReductionRef.get()->Profile(RedId, Context, 10033 /*Canonical=*/true); 10034 EmitError = RedId != ParentRedId; 10035 } 10036 if (EmitError) { 10037 S.Diag(ReductionId.getLocStart(), 10038 diag::err_omp_reduction_identifier_mismatch) 10039 << ReductionIdRange << RefExpr->getSourceRange(); 10040 S.Diag(ParentSR.getBegin(), 10041 diag::note_omp_previous_reduction_identifier) 10042 << ParentSR 10043 << (IsParentBOK ? ParentBOKDSA.RefExpr 10044 : ParentReductionOpDSA.RefExpr) 10045 ->getSourceRange(); 10046 continue; 10047 } 10048 } 10049 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 10050 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined."); 10051 } 10052 10053 DeclRefExpr *Ref = nullptr; 10054 Expr *VarsExpr = RefExpr->IgnoreParens(); 10055 if (!VD && !S.CurContext->isDependentContext()) { 10056 if (ASE || OASE) { 10057 TransformExprToCaptures RebuildToCapture(S, D); 10058 VarsExpr = 10059 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 10060 Ref = RebuildToCapture.getCapturedExpr(); 10061 } else { 10062 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 10063 } 10064 if (!S.IsOpenMPCapturedDecl(D)) { 10065 RD.ExprCaptures.emplace_back(Ref->getDecl()); 10066 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 10067 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 10068 if (!RefRes.isUsable()) 10069 continue; 10070 ExprResult PostUpdateRes = 10071 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 10072 RefRes.get()); 10073 if (!PostUpdateRes.isUsable()) 10074 continue; 10075 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 10076 Stack->getCurrentDirective() == OMPD_taskgroup) { 10077 S.Diag(RefExpr->getExprLoc(), 10078 diag::err_omp_reduction_non_addressable_expression) 10079 << RefExpr->getSourceRange(); 10080 continue; 10081 } 10082 RD.ExprPostUpdates.emplace_back( 10083 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 10084 } 10085 } 10086 } 10087 // All reduction items are still marked as reduction (to do not increase 10088 // code base size). 10089 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 10090 if (CurrDir == OMPD_taskgroup) { 10091 if (DeclareReductionRef.isUsable()) 10092 Stack->addTaskgroupReductionData(D, ReductionIdRange, 10093 DeclareReductionRef.get()); 10094 else 10095 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 10096 } 10097 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 10098 TaskgroupDescriptor); 10099 } 10100 return RD.Vars.empty(); 10101 } 10102 10103 OMPClause *Sema::ActOnOpenMPReductionClause( 10104 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10105 SourceLocation ColonLoc, SourceLocation EndLoc, 10106 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10107 ArrayRef<Expr *> UnresolvedReductions) { 10108 ReductionData RD(VarList.size()); 10109 10110 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 10111 StartLoc, LParenLoc, ColonLoc, EndLoc, 10112 ReductionIdScopeSpec, ReductionId, 10113 UnresolvedReductions, RD)) 10114 return nullptr; 10115 10116 return OMPReductionClause::Create( 10117 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 10118 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 10119 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 10120 buildPreInits(Context, RD.ExprCaptures), 10121 buildPostUpdate(*this, RD.ExprPostUpdates)); 10122 } 10123 10124 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 10125 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10126 SourceLocation ColonLoc, SourceLocation EndLoc, 10127 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10128 ArrayRef<Expr *> UnresolvedReductions) { 10129 ReductionData RD(VarList.size()); 10130 10131 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, 10132 VarList, StartLoc, LParenLoc, ColonLoc, 10133 EndLoc, ReductionIdScopeSpec, ReductionId, 10134 UnresolvedReductions, RD)) 10135 return nullptr; 10136 10137 return OMPTaskReductionClause::Create( 10138 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 10139 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 10140 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 10141 buildPreInits(Context, RD.ExprCaptures), 10142 buildPostUpdate(*this, RD.ExprPostUpdates)); 10143 } 10144 10145 OMPClause *Sema::ActOnOpenMPInReductionClause( 10146 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10147 SourceLocation ColonLoc, SourceLocation EndLoc, 10148 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10149 ArrayRef<Expr *> UnresolvedReductions) { 10150 ReductionData RD(VarList.size()); 10151 10152 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 10153 StartLoc, LParenLoc, ColonLoc, EndLoc, 10154 ReductionIdScopeSpec, ReductionId, 10155 UnresolvedReductions, RD)) 10156 return nullptr; 10157 10158 return OMPInReductionClause::Create( 10159 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 10160 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 10161 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 10162 buildPreInits(Context, RD.ExprCaptures), 10163 buildPostUpdate(*this, RD.ExprPostUpdates)); 10164 } 10165 10166 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 10167 SourceLocation LinLoc) { 10168 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 10169 LinKind == OMPC_LINEAR_unknown) { 10170 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 10171 return true; 10172 } 10173 return false; 10174 } 10175 10176 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 10177 OpenMPLinearClauseKind LinKind, 10178 QualType Type) { 10179 auto *VD = dyn_cast_or_null<VarDecl>(D); 10180 // A variable must not have an incomplete type or a reference type. 10181 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 10182 return true; 10183 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 10184 !Type->isReferenceType()) { 10185 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 10186 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 10187 return true; 10188 } 10189 Type = Type.getNonReferenceType(); 10190 10191 // A list item must not be const-qualified. 10192 if (Type.isConstant(Context)) { 10193 Diag(ELoc, diag::err_omp_const_variable) 10194 << getOpenMPClauseName(OMPC_linear); 10195 if (D) { 10196 bool IsDecl = 10197 !VD || 10198 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10199 Diag(D->getLocation(), 10200 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10201 << D; 10202 } 10203 return true; 10204 } 10205 10206 // A list item must be of integral or pointer type. 10207 Type = Type.getUnqualifiedType().getCanonicalType(); 10208 const auto *Ty = Type.getTypePtrOrNull(); 10209 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 10210 !Ty->isPointerType())) { 10211 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 10212 if (D) { 10213 bool IsDecl = 10214 !VD || 10215 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10216 Diag(D->getLocation(), 10217 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10218 << D; 10219 } 10220 return true; 10221 } 10222 return false; 10223 } 10224 10225 OMPClause *Sema::ActOnOpenMPLinearClause( 10226 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 10227 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 10228 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 10229 SmallVector<Expr *, 8> Vars; 10230 SmallVector<Expr *, 8> Privates; 10231 SmallVector<Expr *, 8> Inits; 10232 SmallVector<Decl *, 4> ExprCaptures; 10233 SmallVector<Expr *, 4> ExprPostUpdates; 10234 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 10235 LinKind = OMPC_LINEAR_val; 10236 for (auto &RefExpr : VarList) { 10237 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10238 SourceLocation ELoc; 10239 SourceRange ERange; 10240 Expr *SimpleRefExpr = RefExpr; 10241 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10242 /*AllowArraySection=*/false); 10243 if (Res.second) { 10244 // It will be analyzed later. 10245 Vars.push_back(RefExpr); 10246 Privates.push_back(nullptr); 10247 Inits.push_back(nullptr); 10248 } 10249 ValueDecl *D = Res.first; 10250 if (!D) 10251 continue; 10252 10253 QualType Type = D->getType(); 10254 auto *VD = dyn_cast<VarDecl>(D); 10255 10256 // OpenMP [2.14.3.7, linear clause] 10257 // A list-item cannot appear in more than one linear clause. 10258 // A list-item that appears in a linear clause cannot appear in any 10259 // other data-sharing attribute clause. 10260 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 10261 if (DVar.RefExpr) { 10262 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 10263 << getOpenMPClauseName(OMPC_linear); 10264 ReportOriginalDSA(*this, DSAStack, D, DVar); 10265 continue; 10266 } 10267 10268 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 10269 continue; 10270 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 10271 10272 // Build private copy of original var. 10273 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 10274 D->hasAttrs() ? &D->getAttrs() : nullptr); 10275 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 10276 // Build var to save initial value. 10277 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 10278 Expr *InitExpr; 10279 DeclRefExpr *Ref = nullptr; 10280 if (!VD && !CurContext->isDependentContext()) { 10281 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 10282 if (!IsOpenMPCapturedDecl(D)) { 10283 ExprCaptures.push_back(Ref->getDecl()); 10284 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 10285 ExprResult RefRes = DefaultLvalueConversion(Ref); 10286 if (!RefRes.isUsable()) 10287 continue; 10288 ExprResult PostUpdateRes = 10289 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 10290 SimpleRefExpr, RefRes.get()); 10291 if (!PostUpdateRes.isUsable()) 10292 continue; 10293 ExprPostUpdates.push_back( 10294 IgnoredValueConversions(PostUpdateRes.get()).get()); 10295 } 10296 } 10297 } 10298 if (LinKind == OMPC_LINEAR_uval) 10299 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 10300 else 10301 InitExpr = VD ? SimpleRefExpr : Ref; 10302 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 10303 /*DirectInit=*/false); 10304 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 10305 10306 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 10307 Vars.push_back((VD || CurContext->isDependentContext()) 10308 ? RefExpr->IgnoreParens() 10309 : Ref); 10310 Privates.push_back(PrivateRef); 10311 Inits.push_back(InitRef); 10312 } 10313 10314 if (Vars.empty()) 10315 return nullptr; 10316 10317 Expr *StepExpr = Step; 10318 Expr *CalcStepExpr = nullptr; 10319 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 10320 !Step->isInstantiationDependent() && 10321 !Step->containsUnexpandedParameterPack()) { 10322 SourceLocation StepLoc = Step->getLocStart(); 10323 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 10324 if (Val.isInvalid()) 10325 return nullptr; 10326 StepExpr = Val.get(); 10327 10328 // Build var to save the step value. 10329 VarDecl *SaveVar = 10330 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 10331 ExprResult SaveRef = 10332 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 10333 ExprResult CalcStep = 10334 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 10335 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 10336 10337 // Warn about zero linear step (it would be probably better specified as 10338 // making corresponding variables 'const'). 10339 llvm::APSInt Result; 10340 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 10341 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 10342 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 10343 << (Vars.size() > 1); 10344 if (!IsConstant && CalcStep.isUsable()) { 10345 // Calculate the step beforehand instead of doing this on each iteration. 10346 // (This is not used if the number of iterations may be kfold-ed). 10347 CalcStepExpr = CalcStep.get(); 10348 } 10349 } 10350 10351 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 10352 ColonLoc, EndLoc, Vars, Privates, Inits, 10353 StepExpr, CalcStepExpr, 10354 buildPreInits(Context, ExprCaptures), 10355 buildPostUpdate(*this, ExprPostUpdates)); 10356 } 10357 10358 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 10359 Expr *NumIterations, Sema &SemaRef, 10360 Scope *S, DSAStackTy *Stack) { 10361 // Walk the vars and build update/final expressions for the CodeGen. 10362 SmallVector<Expr *, 8> Updates; 10363 SmallVector<Expr *, 8> Finals; 10364 Expr *Step = Clause.getStep(); 10365 Expr *CalcStep = Clause.getCalcStep(); 10366 // OpenMP [2.14.3.7, linear clause] 10367 // If linear-step is not specified it is assumed to be 1. 10368 if (Step == nullptr) 10369 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 10370 else if (CalcStep) { 10371 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 10372 } 10373 bool HasErrors = false; 10374 auto CurInit = Clause.inits().begin(); 10375 auto CurPrivate = Clause.privates().begin(); 10376 auto LinKind = Clause.getModifier(); 10377 for (auto &RefExpr : Clause.varlists()) { 10378 SourceLocation ELoc; 10379 SourceRange ERange; 10380 Expr *SimpleRefExpr = RefExpr; 10381 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 10382 /*AllowArraySection=*/false); 10383 ValueDecl *D = Res.first; 10384 if (Res.second || !D) { 10385 Updates.push_back(nullptr); 10386 Finals.push_back(nullptr); 10387 HasErrors = true; 10388 continue; 10389 } 10390 auto &&Info = Stack->isLoopControlVariable(D); 10391 Expr *InitExpr = *CurInit; 10392 10393 // Build privatized reference to the current linear var. 10394 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 10395 Expr *CapturedRef; 10396 if (LinKind == OMPC_LINEAR_uval) 10397 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 10398 else 10399 CapturedRef = 10400 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 10401 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 10402 /*RefersToCapture=*/true); 10403 10404 // Build update: Var = InitExpr + IV * Step 10405 ExprResult Update; 10406 if (!Info.first) { 10407 Update = 10408 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 10409 InitExpr, IV, Step, /* Subtract */ false); 10410 } else 10411 Update = *CurPrivate; 10412 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 10413 /*DiscardedValue=*/true); 10414 10415 // Build final: Var = InitExpr + NumIterations * Step 10416 ExprResult Final; 10417 if (!Info.first) { 10418 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 10419 InitExpr, NumIterations, Step, 10420 /* Subtract */ false); 10421 } else 10422 Final = *CurPrivate; 10423 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 10424 /*DiscardedValue=*/true); 10425 10426 if (!Update.isUsable() || !Final.isUsable()) { 10427 Updates.push_back(nullptr); 10428 Finals.push_back(nullptr); 10429 HasErrors = true; 10430 } else { 10431 Updates.push_back(Update.get()); 10432 Finals.push_back(Final.get()); 10433 } 10434 ++CurInit; 10435 ++CurPrivate; 10436 } 10437 Clause.setUpdates(Updates); 10438 Clause.setFinals(Finals); 10439 return HasErrors; 10440 } 10441 10442 OMPClause *Sema::ActOnOpenMPAlignedClause( 10443 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 10444 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 10445 10446 SmallVector<Expr *, 8> Vars; 10447 for (auto &RefExpr : VarList) { 10448 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10449 SourceLocation ELoc; 10450 SourceRange ERange; 10451 Expr *SimpleRefExpr = RefExpr; 10452 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10453 /*AllowArraySection=*/false); 10454 if (Res.second) { 10455 // It will be analyzed later. 10456 Vars.push_back(RefExpr); 10457 } 10458 ValueDecl *D = Res.first; 10459 if (!D) 10460 continue; 10461 10462 QualType QType = D->getType(); 10463 auto *VD = dyn_cast<VarDecl>(D); 10464 10465 // OpenMP [2.8.1, simd construct, Restrictions] 10466 // The type of list items appearing in the aligned clause must be 10467 // array, pointer, reference to array, or reference to pointer. 10468 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 10469 const Type *Ty = QType.getTypePtrOrNull(); 10470 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 10471 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 10472 << QType << getLangOpts().CPlusPlus << ERange; 10473 bool IsDecl = 10474 !VD || 10475 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10476 Diag(D->getLocation(), 10477 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10478 << D; 10479 continue; 10480 } 10481 10482 // OpenMP [2.8.1, simd construct, Restrictions] 10483 // A list-item cannot appear in more than one aligned clause. 10484 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 10485 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 10486 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 10487 << getOpenMPClauseName(OMPC_aligned); 10488 continue; 10489 } 10490 10491 DeclRefExpr *Ref = nullptr; 10492 if (!VD && IsOpenMPCapturedDecl(D)) 10493 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 10494 Vars.push_back(DefaultFunctionArrayConversion( 10495 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 10496 .get()); 10497 } 10498 10499 // OpenMP [2.8.1, simd construct, Description] 10500 // The parameter of the aligned clause, alignment, must be a constant 10501 // positive integer expression. 10502 // If no optional parameter is specified, implementation-defined default 10503 // alignments for SIMD instructions on the target platforms are assumed. 10504 if (Alignment != nullptr) { 10505 ExprResult AlignResult = 10506 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 10507 if (AlignResult.isInvalid()) 10508 return nullptr; 10509 Alignment = AlignResult.get(); 10510 } 10511 if (Vars.empty()) 10512 return nullptr; 10513 10514 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 10515 EndLoc, Vars, Alignment); 10516 } 10517 10518 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 10519 SourceLocation StartLoc, 10520 SourceLocation LParenLoc, 10521 SourceLocation EndLoc) { 10522 SmallVector<Expr *, 8> Vars; 10523 SmallVector<Expr *, 8> SrcExprs; 10524 SmallVector<Expr *, 8> DstExprs; 10525 SmallVector<Expr *, 8> AssignmentOps; 10526 for (auto &RefExpr : VarList) { 10527 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 10528 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 10529 // It will be analyzed later. 10530 Vars.push_back(RefExpr); 10531 SrcExprs.push_back(nullptr); 10532 DstExprs.push_back(nullptr); 10533 AssignmentOps.push_back(nullptr); 10534 continue; 10535 } 10536 10537 SourceLocation ELoc = RefExpr->getExprLoc(); 10538 // OpenMP [2.1, C/C++] 10539 // A list item is a variable name. 10540 // OpenMP [2.14.4.1, Restrictions, p.1] 10541 // A list item that appears in a copyin clause must be threadprivate. 10542 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 10543 if (!DE || !isa<VarDecl>(DE->getDecl())) { 10544 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 10545 << 0 << RefExpr->getSourceRange(); 10546 continue; 10547 } 10548 10549 Decl *D = DE->getDecl(); 10550 VarDecl *VD = cast<VarDecl>(D); 10551 10552 QualType Type = VD->getType(); 10553 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 10554 // It will be analyzed later. 10555 Vars.push_back(DE); 10556 SrcExprs.push_back(nullptr); 10557 DstExprs.push_back(nullptr); 10558 AssignmentOps.push_back(nullptr); 10559 continue; 10560 } 10561 10562 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 10563 // A list item that appears in a copyin clause must be threadprivate. 10564 if (!DSAStack->isThreadPrivate(VD)) { 10565 Diag(ELoc, diag::err_omp_required_access) 10566 << getOpenMPClauseName(OMPC_copyin) 10567 << getOpenMPDirectiveName(OMPD_threadprivate); 10568 continue; 10569 } 10570 10571 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 10572 // A variable of class type (or array thereof) that appears in a 10573 // copyin clause requires an accessible, unambiguous copy assignment 10574 // operator for the class type. 10575 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 10576 auto *SrcVD = 10577 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 10578 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 10579 auto *PseudoSrcExpr = buildDeclRefExpr( 10580 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 10581 auto *DstVD = 10582 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 10583 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 10584 auto *PseudoDstExpr = 10585 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 10586 // For arrays generate assignment operation for single element and replace 10587 // it by the original array element in CodeGen. 10588 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 10589 PseudoDstExpr, PseudoSrcExpr); 10590 if (AssignmentOp.isInvalid()) 10591 continue; 10592 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 10593 /*DiscardedValue=*/true); 10594 if (AssignmentOp.isInvalid()) 10595 continue; 10596 10597 DSAStack->addDSA(VD, DE, OMPC_copyin); 10598 Vars.push_back(DE); 10599 SrcExprs.push_back(PseudoSrcExpr); 10600 DstExprs.push_back(PseudoDstExpr); 10601 AssignmentOps.push_back(AssignmentOp.get()); 10602 } 10603 10604 if (Vars.empty()) 10605 return nullptr; 10606 10607 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 10608 SrcExprs, DstExprs, AssignmentOps); 10609 } 10610 10611 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 10612 SourceLocation StartLoc, 10613 SourceLocation LParenLoc, 10614 SourceLocation EndLoc) { 10615 SmallVector<Expr *, 8> Vars; 10616 SmallVector<Expr *, 8> SrcExprs; 10617 SmallVector<Expr *, 8> DstExprs; 10618 SmallVector<Expr *, 8> AssignmentOps; 10619 for (auto &RefExpr : VarList) { 10620 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10621 SourceLocation ELoc; 10622 SourceRange ERange; 10623 Expr *SimpleRefExpr = RefExpr; 10624 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10625 /*AllowArraySection=*/false); 10626 if (Res.second) { 10627 // It will be analyzed later. 10628 Vars.push_back(RefExpr); 10629 SrcExprs.push_back(nullptr); 10630 DstExprs.push_back(nullptr); 10631 AssignmentOps.push_back(nullptr); 10632 } 10633 ValueDecl *D = Res.first; 10634 if (!D) 10635 continue; 10636 10637 QualType Type = D->getType(); 10638 auto *VD = dyn_cast<VarDecl>(D); 10639 10640 // OpenMP [2.14.4.2, Restrictions, p.2] 10641 // A list item that appears in a copyprivate clause may not appear in a 10642 // private or firstprivate clause on the single construct. 10643 if (!VD || !DSAStack->isThreadPrivate(VD)) { 10644 auto DVar = DSAStack->getTopDSA(D, false); 10645 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 10646 DVar.RefExpr) { 10647 Diag(ELoc, diag::err_omp_wrong_dsa) 10648 << getOpenMPClauseName(DVar.CKind) 10649 << getOpenMPClauseName(OMPC_copyprivate); 10650 ReportOriginalDSA(*this, DSAStack, D, DVar); 10651 continue; 10652 } 10653 10654 // OpenMP [2.11.4.2, Restrictions, p.1] 10655 // All list items that appear in a copyprivate clause must be either 10656 // threadprivate or private in the enclosing context. 10657 if (DVar.CKind == OMPC_unknown) { 10658 DVar = DSAStack->getImplicitDSA(D, false); 10659 if (DVar.CKind == OMPC_shared) { 10660 Diag(ELoc, diag::err_omp_required_access) 10661 << getOpenMPClauseName(OMPC_copyprivate) 10662 << "threadprivate or private in the enclosing context"; 10663 ReportOriginalDSA(*this, DSAStack, D, DVar); 10664 continue; 10665 } 10666 } 10667 } 10668 10669 // Variably modified types are not supported. 10670 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 10671 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 10672 << getOpenMPClauseName(OMPC_copyprivate) << Type 10673 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 10674 bool IsDecl = 10675 !VD || 10676 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10677 Diag(D->getLocation(), 10678 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10679 << D; 10680 continue; 10681 } 10682 10683 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 10684 // A variable of class type (or array thereof) that appears in a 10685 // copyin clause requires an accessible, unambiguous copy assignment 10686 // operator for the class type. 10687 Type = Context.getBaseElementType(Type.getNonReferenceType()) 10688 .getUnqualifiedType(); 10689 auto *SrcVD = 10690 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 10691 D->hasAttrs() ? &D->getAttrs() : nullptr); 10692 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 10693 auto *DstVD = 10694 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 10695 D->hasAttrs() ? &D->getAttrs() : nullptr); 10696 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 10697 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 10698 PseudoDstExpr, PseudoSrcExpr); 10699 if (AssignmentOp.isInvalid()) 10700 continue; 10701 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 10702 /*DiscardedValue=*/true); 10703 if (AssignmentOp.isInvalid()) 10704 continue; 10705 10706 // No need to mark vars as copyprivate, they are already threadprivate or 10707 // implicitly private. 10708 assert(VD || IsOpenMPCapturedDecl(D)); 10709 Vars.push_back( 10710 VD ? RefExpr->IgnoreParens() 10711 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 10712 SrcExprs.push_back(PseudoSrcExpr); 10713 DstExprs.push_back(PseudoDstExpr); 10714 AssignmentOps.push_back(AssignmentOp.get()); 10715 } 10716 10717 if (Vars.empty()) 10718 return nullptr; 10719 10720 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10721 Vars, SrcExprs, DstExprs, AssignmentOps); 10722 } 10723 10724 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 10725 SourceLocation StartLoc, 10726 SourceLocation LParenLoc, 10727 SourceLocation EndLoc) { 10728 if (VarList.empty()) 10729 return nullptr; 10730 10731 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 10732 } 10733 10734 OMPClause * 10735 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 10736 SourceLocation DepLoc, SourceLocation ColonLoc, 10737 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10738 SourceLocation LParenLoc, SourceLocation EndLoc) { 10739 if (DSAStack->getCurrentDirective() == OMPD_ordered && 10740 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 10741 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 10742 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 10743 return nullptr; 10744 } 10745 if (DSAStack->getCurrentDirective() != OMPD_ordered && 10746 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 10747 DepKind == OMPC_DEPEND_sink)) { 10748 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 10749 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 10750 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 10751 /*Last=*/OMPC_DEPEND_unknown, Except) 10752 << getOpenMPClauseName(OMPC_depend); 10753 return nullptr; 10754 } 10755 SmallVector<Expr *, 8> Vars; 10756 DSAStackTy::OperatorOffsetTy OpsOffs; 10757 llvm::APSInt DepCounter(/*BitWidth=*/32); 10758 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 10759 if (DepKind == OMPC_DEPEND_sink) { 10760 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 10761 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 10762 TotalDepCount.setIsUnsigned(/*Val=*/true); 10763 } 10764 } 10765 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || 10766 DSAStack->getParentOrderedRegionParam()) { 10767 for (auto &RefExpr : VarList) { 10768 assert(RefExpr && "NULL expr in OpenMP shared clause."); 10769 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 10770 // It will be analyzed later. 10771 Vars.push_back(RefExpr); 10772 continue; 10773 } 10774 10775 SourceLocation ELoc = RefExpr->getExprLoc(); 10776 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 10777 if (DepKind == OMPC_DEPEND_sink) { 10778 if (DepCounter >= TotalDepCount) { 10779 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 10780 continue; 10781 } 10782 ++DepCounter; 10783 // OpenMP [2.13.9, Summary] 10784 // depend(dependence-type : vec), where dependence-type is: 10785 // 'sink' and where vec is the iteration vector, which has the form: 10786 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 10787 // where n is the value specified by the ordered clause in the loop 10788 // directive, xi denotes the loop iteration variable of the i-th nested 10789 // loop associated with the loop directive, and di is a constant 10790 // non-negative integer. 10791 if (CurContext->isDependentContext()) { 10792 // It will be analyzed later. 10793 Vars.push_back(RefExpr); 10794 continue; 10795 } 10796 SimpleExpr = SimpleExpr->IgnoreImplicit(); 10797 OverloadedOperatorKind OOK = OO_None; 10798 SourceLocation OOLoc; 10799 Expr *LHS = SimpleExpr; 10800 Expr *RHS = nullptr; 10801 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 10802 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 10803 OOLoc = BO->getOperatorLoc(); 10804 LHS = BO->getLHS()->IgnoreParenImpCasts(); 10805 RHS = BO->getRHS()->IgnoreParenImpCasts(); 10806 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 10807 OOK = OCE->getOperator(); 10808 OOLoc = OCE->getOperatorLoc(); 10809 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10810 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 10811 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 10812 OOK = MCE->getMethodDecl() 10813 ->getNameInfo() 10814 .getName() 10815 .getCXXOverloadedOperator(); 10816 OOLoc = MCE->getCallee()->getExprLoc(); 10817 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 10818 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10819 } 10820 SourceLocation ELoc; 10821 SourceRange ERange; 10822 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 10823 /*AllowArraySection=*/false); 10824 if (Res.second) { 10825 // It will be analyzed later. 10826 Vars.push_back(RefExpr); 10827 } 10828 ValueDecl *D = Res.first; 10829 if (!D) 10830 continue; 10831 10832 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 10833 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 10834 continue; 10835 } 10836 if (RHS) { 10837 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 10838 RHS, OMPC_depend, /*StrictlyPositive=*/false); 10839 if (RHSRes.isInvalid()) 10840 continue; 10841 } 10842 if (!CurContext->isDependentContext() && 10843 DSAStack->getParentOrderedRegionParam() && 10844 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 10845 ValueDecl* VD = DSAStack->getParentLoopControlVariable( 10846 DepCounter.getZExtValue()); 10847 if (VD) { 10848 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 10849 << 1 << VD; 10850 } else { 10851 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 10852 } 10853 continue; 10854 } 10855 OpsOffs.push_back({RHS, OOK}); 10856 } else { 10857 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 10858 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 10859 (ASE && 10860 !ASE->getBase() 10861 ->getType() 10862 .getNonReferenceType() 10863 ->isPointerType() && 10864 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 10865 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 10866 << RefExpr->getSourceRange(); 10867 continue; 10868 } 10869 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 10870 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 10871 ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, 10872 RefExpr->IgnoreParenImpCasts()); 10873 getDiagnostics().setSuppressAllDiagnostics(Suppress); 10874 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) { 10875 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 10876 << RefExpr->getSourceRange(); 10877 continue; 10878 } 10879 } 10880 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 10881 } 10882 10883 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 10884 TotalDepCount > VarList.size() && 10885 DSAStack->getParentOrderedRegionParam() && 10886 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 10887 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1 10888 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 10889 } 10890 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 10891 Vars.empty()) 10892 return nullptr; 10893 } 10894 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10895 DepKind, DepLoc, ColonLoc, Vars); 10896 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) 10897 DSAStack->addDoacrossDependClause(C, OpsOffs); 10898 return C; 10899 } 10900 10901 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 10902 SourceLocation LParenLoc, 10903 SourceLocation EndLoc) { 10904 Expr *ValExpr = Device; 10905 Stmt *HelperValStmt = nullptr; 10906 10907 // OpenMP [2.9.1, Restrictions] 10908 // The device expression must evaluate to a non-negative integer value. 10909 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 10910 /*StrictlyPositive=*/false)) 10911 return nullptr; 10912 10913 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 10914 if (isOpenMPTargetExecutionDirective(DKind) && 10915 !CurContext->isDependentContext()) { 10916 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 10917 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 10918 HelperValStmt = buildPreInits(Context, Captures); 10919 } 10920 10921 return new (Context) 10922 OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc); 10923 } 10924 10925 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 10926 DSAStackTy *Stack, QualType QTy) { 10927 NamedDecl *ND; 10928 if (QTy->isIncompleteType(&ND)) { 10929 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 10930 return false; 10931 } 10932 return true; 10933 } 10934 10935 /// \brief Return true if it can be proven that the provided array expression 10936 /// (array section or array subscript) does NOT specify the whole size of the 10937 /// array whose base type is \a BaseQTy. 10938 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 10939 const Expr *E, 10940 QualType BaseQTy) { 10941 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10942 10943 // If this is an array subscript, it refers to the whole size if the size of 10944 // the dimension is constant and equals 1. Also, an array section assumes the 10945 // format of an array subscript if no colon is used. 10946 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 10947 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10948 return ATy->getSize().getSExtValue() != 1; 10949 // Size can't be evaluated statically. 10950 return false; 10951 } 10952 10953 assert(OASE && "Expecting array section if not an array subscript."); 10954 auto *LowerBound = OASE->getLowerBound(); 10955 auto *Length = OASE->getLength(); 10956 10957 // If there is a lower bound that does not evaluates to zero, we are not 10958 // covering the whole dimension. 10959 if (LowerBound) { 10960 llvm::APSInt ConstLowerBound; 10961 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 10962 return false; // Can't get the integer value as a constant. 10963 if (ConstLowerBound.getSExtValue()) 10964 return true; 10965 } 10966 10967 // If we don't have a length we covering the whole dimension. 10968 if (!Length) 10969 return false; 10970 10971 // If the base is a pointer, we don't have a way to get the size of the 10972 // pointee. 10973 if (BaseQTy->isPointerType()) 10974 return false; 10975 10976 // We can only check if the length is the same as the size of the dimension 10977 // if we have a constant array. 10978 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 10979 if (!CATy) 10980 return false; 10981 10982 llvm::APSInt ConstLength; 10983 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10984 return false; // Can't get the integer value as a constant. 10985 10986 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 10987 } 10988 10989 // Return true if it can be proven that the provided array expression (array 10990 // section or array subscript) does NOT specify a single element of the array 10991 // whose base type is \a BaseQTy. 10992 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 10993 const Expr *E, 10994 QualType BaseQTy) { 10995 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10996 10997 // An array subscript always refer to a single element. Also, an array section 10998 // assumes the format of an array subscript if no colon is used. 10999 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 11000 return false; 11001 11002 assert(OASE && "Expecting array section if not an array subscript."); 11003 auto *Length = OASE->getLength(); 11004 11005 // If we don't have a length we have to check if the array has unitary size 11006 // for this dimension. Also, we should always expect a length if the base type 11007 // is pointer. 11008 if (!Length) { 11009 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 11010 return ATy->getSize().getSExtValue() != 1; 11011 // We cannot assume anything. 11012 return false; 11013 } 11014 11015 // Check if the length evaluates to 1. 11016 llvm::APSInt ConstLength; 11017 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 11018 return false; // Can't get the integer value as a constant. 11019 11020 return ConstLength.getSExtValue() != 1; 11021 } 11022 11023 // Return the expression of the base of the mappable expression or null if it 11024 // cannot be determined and do all the necessary checks to see if the expression 11025 // is valid as a standalone mappable expression. In the process, record all the 11026 // components of the expression. 11027 static Expr *CheckMapClauseExpressionBase( 11028 Sema &SemaRef, Expr *E, 11029 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 11030 OpenMPClauseKind CKind) { 11031 SourceLocation ELoc = E->getExprLoc(); 11032 SourceRange ERange = E->getSourceRange(); 11033 11034 // The base of elements of list in a map clause have to be either: 11035 // - a reference to variable or field. 11036 // - a member expression. 11037 // - an array expression. 11038 // 11039 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 11040 // reference to 'r'. 11041 // 11042 // If we have: 11043 // 11044 // struct SS { 11045 // Bla S; 11046 // foo() { 11047 // #pragma omp target map (S.Arr[:12]); 11048 // } 11049 // } 11050 // 11051 // We want to retrieve the member expression 'this->S'; 11052 11053 Expr *RelevantExpr = nullptr; 11054 11055 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 11056 // If a list item is an array section, it must specify contiguous storage. 11057 // 11058 // For this restriction it is sufficient that we make sure only references 11059 // to variables or fields and array expressions, and that no array sections 11060 // exist except in the rightmost expression (unless they cover the whole 11061 // dimension of the array). E.g. these would be invalid: 11062 // 11063 // r.ArrS[3:5].Arr[6:7] 11064 // 11065 // r.ArrS[3:5].x 11066 // 11067 // but these would be valid: 11068 // r.ArrS[3].Arr[6:7] 11069 // 11070 // r.ArrS[3].x 11071 11072 bool AllowUnitySizeArraySection = true; 11073 bool AllowWholeSizeArraySection = true; 11074 11075 while (!RelevantExpr) { 11076 E = E->IgnoreParenImpCasts(); 11077 11078 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 11079 if (!isa<VarDecl>(CurE->getDecl())) 11080 break; 11081 11082 RelevantExpr = CurE; 11083 11084 // If we got a reference to a declaration, we should not expect any array 11085 // section before that. 11086 AllowUnitySizeArraySection = false; 11087 AllowWholeSizeArraySection = false; 11088 11089 // Record the component. 11090 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent( 11091 CurE, CurE->getDecl())); 11092 continue; 11093 } 11094 11095 if (auto *CurE = dyn_cast<MemberExpr>(E)) { 11096 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 11097 11098 if (isa<CXXThisExpr>(BaseE)) 11099 // We found a base expression: this->Val. 11100 RelevantExpr = CurE; 11101 else 11102 E = BaseE; 11103 11104 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 11105 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 11106 << CurE->getSourceRange(); 11107 break; 11108 } 11109 11110 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 11111 11112 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 11113 // A bit-field cannot appear in a map clause. 11114 // 11115 if (FD->isBitField()) { 11116 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 11117 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 11118 break; 11119 } 11120 11121 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11122 // If the type of a list item is a reference to a type T then the type 11123 // will be considered to be T for all purposes of this clause. 11124 QualType CurType = BaseE->getType().getNonReferenceType(); 11125 11126 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 11127 // A list item cannot be a variable that is a member of a structure with 11128 // a union type. 11129 // 11130 if (auto *RT = CurType->getAs<RecordType>()) 11131 if (RT->isUnionType()) { 11132 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 11133 << CurE->getSourceRange(); 11134 break; 11135 } 11136 11137 // If we got a member expression, we should not expect any array section 11138 // before that: 11139 // 11140 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 11141 // If a list item is an element of a structure, only the rightmost symbol 11142 // of the variable reference can be an array section. 11143 // 11144 AllowUnitySizeArraySection = false; 11145 AllowWholeSizeArraySection = false; 11146 11147 // Record the component. 11148 CurComponents.push_back( 11149 OMPClauseMappableExprCommon::MappableComponent(CurE, FD)); 11150 continue; 11151 } 11152 11153 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 11154 E = CurE->getBase()->IgnoreParenImpCasts(); 11155 11156 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 11157 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 11158 << 0 << CurE->getSourceRange(); 11159 break; 11160 } 11161 11162 // If we got an array subscript that express the whole dimension we 11163 // can have any array expressions before. If it only expressing part of 11164 // the dimension, we can only have unitary-size array expressions. 11165 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 11166 E->getType())) 11167 AllowWholeSizeArraySection = false; 11168 11169 // Record the component - we don't have any declaration associated. 11170 CurComponents.push_back( 11171 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 11172 continue; 11173 } 11174 11175 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 11176 E = CurE->getBase()->IgnoreParenImpCasts(); 11177 11178 auto CurType = 11179 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 11180 11181 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11182 // If the type of a list item is a reference to a type T then the type 11183 // will be considered to be T for all purposes of this clause. 11184 if (CurType->isReferenceType()) 11185 CurType = CurType->getPointeeType(); 11186 11187 bool IsPointer = CurType->isAnyPointerType(); 11188 11189 if (!IsPointer && !CurType->isArrayType()) { 11190 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 11191 << 0 << CurE->getSourceRange(); 11192 break; 11193 } 11194 11195 bool NotWhole = 11196 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 11197 bool NotUnity = 11198 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 11199 11200 if (AllowWholeSizeArraySection) { 11201 // Any array section is currently allowed. Allowing a whole size array 11202 // section implies allowing a unity array section as well. 11203 // 11204 // If this array section refers to the whole dimension we can still 11205 // accept other array sections before this one, except if the base is a 11206 // pointer. Otherwise, only unitary sections are accepted. 11207 if (NotWhole || IsPointer) 11208 AllowWholeSizeArraySection = false; 11209 } else if (AllowUnitySizeArraySection && NotUnity) { 11210 // A unity or whole array section is not allowed and that is not 11211 // compatible with the properties of the current array section. 11212 SemaRef.Diag( 11213 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 11214 << CurE->getSourceRange(); 11215 break; 11216 } 11217 11218 // Record the component - we don't have any declaration associated. 11219 CurComponents.push_back( 11220 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 11221 continue; 11222 } 11223 11224 // If nothing else worked, this is not a valid map clause expression. 11225 SemaRef.Diag(ELoc, 11226 diag::err_omp_expected_named_var_member_or_array_expression) 11227 << ERange; 11228 break; 11229 } 11230 11231 return RelevantExpr; 11232 } 11233 11234 // Return true if expression E associated with value VD has conflicts with other 11235 // map information. 11236 static bool CheckMapConflicts( 11237 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 11238 bool CurrentRegionOnly, 11239 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 11240 OpenMPClauseKind CKind) { 11241 assert(VD && E); 11242 SourceLocation ELoc = E->getExprLoc(); 11243 SourceRange ERange = E->getSourceRange(); 11244 11245 // In order to easily check the conflicts we need to match each component of 11246 // the expression under test with the components of the expressions that are 11247 // already in the stack. 11248 11249 assert(!CurComponents.empty() && "Map clause expression with no components!"); 11250 assert(CurComponents.back().getAssociatedDeclaration() == VD && 11251 "Map clause expression with unexpected base!"); 11252 11253 // Variables to help detecting enclosing problems in data environment nests. 11254 bool IsEnclosedByDataEnvironmentExpr = false; 11255 const Expr *EnclosingExpr = nullptr; 11256 11257 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 11258 VD, CurrentRegionOnly, 11259 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 11260 StackComponents, 11261 OpenMPClauseKind) -> bool { 11262 11263 assert(!StackComponents.empty() && 11264 "Map clause expression with no components!"); 11265 assert(StackComponents.back().getAssociatedDeclaration() == VD && 11266 "Map clause expression with unexpected base!"); 11267 11268 // The whole expression in the stack. 11269 auto *RE = StackComponents.front().getAssociatedExpression(); 11270 11271 // Expressions must start from the same base. Here we detect at which 11272 // point both expressions diverge from each other and see if we can 11273 // detect if the memory referred to both expressions is contiguous and 11274 // do not overlap. 11275 auto CI = CurComponents.rbegin(); 11276 auto CE = CurComponents.rend(); 11277 auto SI = StackComponents.rbegin(); 11278 auto SE = StackComponents.rend(); 11279 for (; CI != CE && SI != SE; ++CI, ++SI) { 11280 11281 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 11282 // At most one list item can be an array item derived from a given 11283 // variable in map clauses of the same construct. 11284 if (CurrentRegionOnly && 11285 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 11286 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 11287 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 11288 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 11289 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 11290 diag::err_omp_multiple_array_items_in_map_clause) 11291 << CI->getAssociatedExpression()->getSourceRange(); 11292 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 11293 diag::note_used_here) 11294 << SI->getAssociatedExpression()->getSourceRange(); 11295 return true; 11296 } 11297 11298 // Do both expressions have the same kind? 11299 if (CI->getAssociatedExpression()->getStmtClass() != 11300 SI->getAssociatedExpression()->getStmtClass()) 11301 break; 11302 11303 // Are we dealing with different variables/fields? 11304 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 11305 break; 11306 } 11307 // Check if the extra components of the expressions in the enclosing 11308 // data environment are redundant for the current base declaration. 11309 // If they are, the maps completely overlap, which is legal. 11310 for (; SI != SE; ++SI) { 11311 QualType Type; 11312 if (auto *ASE = 11313 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 11314 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 11315 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>( 11316 SI->getAssociatedExpression())) { 11317 auto *E = OASE->getBase()->IgnoreParenImpCasts(); 11318 Type = 11319 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 11320 } 11321 if (Type.isNull() || Type->isAnyPointerType() || 11322 CheckArrayExpressionDoesNotReferToWholeSize( 11323 SemaRef, SI->getAssociatedExpression(), Type)) 11324 break; 11325 } 11326 11327 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 11328 // List items of map clauses in the same construct must not share 11329 // original storage. 11330 // 11331 // If the expressions are exactly the same or one is a subset of the 11332 // other, it means they are sharing storage. 11333 if (CI == CE && SI == SE) { 11334 if (CurrentRegionOnly) { 11335 if (CKind == OMPC_map) 11336 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 11337 else { 11338 assert(CKind == OMPC_to || CKind == OMPC_from); 11339 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 11340 << ERange; 11341 } 11342 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 11343 << RE->getSourceRange(); 11344 return true; 11345 } else { 11346 // If we find the same expression in the enclosing data environment, 11347 // that is legal. 11348 IsEnclosedByDataEnvironmentExpr = true; 11349 return false; 11350 } 11351 } 11352 11353 QualType DerivedType = 11354 std::prev(CI)->getAssociatedDeclaration()->getType(); 11355 SourceLocation DerivedLoc = 11356 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 11357 11358 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11359 // If the type of a list item is a reference to a type T then the type 11360 // will be considered to be T for all purposes of this clause. 11361 DerivedType = DerivedType.getNonReferenceType(); 11362 11363 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 11364 // A variable for which the type is pointer and an array section 11365 // derived from that variable must not appear as list items of map 11366 // clauses of the same construct. 11367 // 11368 // Also, cover one of the cases in: 11369 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 11370 // If any part of the original storage of a list item has corresponding 11371 // storage in the device data environment, all of the original storage 11372 // must have corresponding storage in the device data environment. 11373 // 11374 if (DerivedType->isAnyPointerType()) { 11375 if (CI == CE || SI == SE) { 11376 SemaRef.Diag( 11377 DerivedLoc, 11378 diag::err_omp_pointer_mapped_along_with_derived_section) 11379 << DerivedLoc; 11380 } else { 11381 assert(CI != CE && SI != SE); 11382 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) 11383 << DerivedLoc; 11384 } 11385 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 11386 << RE->getSourceRange(); 11387 return true; 11388 } 11389 11390 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 11391 // List items of map clauses in the same construct must not share 11392 // original storage. 11393 // 11394 // An expression is a subset of the other. 11395 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 11396 if (CKind == OMPC_map) 11397 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 11398 else { 11399 assert(CKind == OMPC_to || CKind == OMPC_from); 11400 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 11401 << ERange; 11402 } 11403 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 11404 << RE->getSourceRange(); 11405 return true; 11406 } 11407 11408 // The current expression uses the same base as other expression in the 11409 // data environment but does not contain it completely. 11410 if (!CurrentRegionOnly && SI != SE) 11411 EnclosingExpr = RE; 11412 11413 // The current expression is a subset of the expression in the data 11414 // environment. 11415 IsEnclosedByDataEnvironmentExpr |= 11416 (!CurrentRegionOnly && CI != CE && SI == SE); 11417 11418 return false; 11419 }); 11420 11421 if (CurrentRegionOnly) 11422 return FoundError; 11423 11424 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 11425 // If any part of the original storage of a list item has corresponding 11426 // storage in the device data environment, all of the original storage must 11427 // have corresponding storage in the device data environment. 11428 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 11429 // If a list item is an element of a structure, and a different element of 11430 // the structure has a corresponding list item in the device data environment 11431 // prior to a task encountering the construct associated with the map clause, 11432 // then the list item must also have a corresponding list item in the device 11433 // data environment prior to the task encountering the construct. 11434 // 11435 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 11436 SemaRef.Diag(ELoc, 11437 diag::err_omp_original_storage_is_shared_and_does_not_contain) 11438 << ERange; 11439 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 11440 << EnclosingExpr->getSourceRange(); 11441 return true; 11442 } 11443 11444 return FoundError; 11445 } 11446 11447 namespace { 11448 // Utility struct that gathers all the related lists associated with a mappable 11449 // expression. 11450 struct MappableVarListInfo final { 11451 // The list of expressions. 11452 ArrayRef<Expr *> VarList; 11453 // The list of processed expressions. 11454 SmallVector<Expr *, 16> ProcessedVarList; 11455 // The mappble components for each expression. 11456 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 11457 // The base declaration of the variable. 11458 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 11459 11460 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 11461 // We have a list of components and base declarations for each entry in the 11462 // variable list. 11463 VarComponents.reserve(VarList.size()); 11464 VarBaseDeclarations.reserve(VarList.size()); 11465 } 11466 }; 11467 } 11468 11469 // Check the validity of the provided variable list for the provided clause kind 11470 // \a CKind. In the check process the valid expressions, and mappable expression 11471 // components and variables are extracted and used to fill \a Vars, 11472 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 11473 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 11474 static void 11475 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 11476 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 11477 SourceLocation StartLoc, 11478 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 11479 bool IsMapTypeImplicit = false) { 11480 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 11481 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 11482 "Unexpected clause kind with mappable expressions!"); 11483 11484 // Keep track of the mappable components and base declarations in this clause. 11485 // Each entry in the list is going to have a list of components associated. We 11486 // record each set of the components so that we can build the clause later on. 11487 // In the end we should have the same amount of declarations and component 11488 // lists. 11489 11490 for (auto &RE : MVLI.VarList) { 11491 assert(RE && "Null expr in omp to/from/map clause"); 11492 SourceLocation ELoc = RE->getExprLoc(); 11493 11494 auto *VE = RE->IgnoreParenLValueCasts(); 11495 11496 if (VE->isValueDependent() || VE->isTypeDependent() || 11497 VE->isInstantiationDependent() || 11498 VE->containsUnexpandedParameterPack()) { 11499 // We can only analyze this information once the missing information is 11500 // resolved. 11501 MVLI.ProcessedVarList.push_back(RE); 11502 continue; 11503 } 11504 11505 auto *SimpleExpr = RE->IgnoreParenCasts(); 11506 11507 if (!RE->IgnoreParenImpCasts()->isLValue()) { 11508 SemaRef.Diag(ELoc, 11509 diag::err_omp_expected_named_var_member_or_array_expression) 11510 << RE->getSourceRange(); 11511 continue; 11512 } 11513 11514 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 11515 ValueDecl *CurDeclaration = nullptr; 11516 11517 // Obtain the array or member expression bases if required. Also, fill the 11518 // components array with all the components identified in the process. 11519 auto *BE = 11520 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind); 11521 if (!BE) 11522 continue; 11523 11524 assert(!CurComponents.empty() && 11525 "Invalid mappable expression information."); 11526 11527 // For the following checks, we rely on the base declaration which is 11528 // expected to be associated with the last component. The declaration is 11529 // expected to be a variable or a field (if 'this' is being mapped). 11530 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 11531 assert(CurDeclaration && "Null decl on map clause."); 11532 assert( 11533 CurDeclaration->isCanonicalDecl() && 11534 "Expecting components to have associated only canonical declarations."); 11535 11536 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 11537 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 11538 11539 assert((VD || FD) && "Only variables or fields are expected here!"); 11540 (void)FD; 11541 11542 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 11543 // threadprivate variables cannot appear in a map clause. 11544 // OpenMP 4.5 [2.10.5, target update Construct] 11545 // threadprivate variables cannot appear in a from clause. 11546 if (VD && DSAS->isThreadPrivate(VD)) { 11547 auto DVar = DSAS->getTopDSA(VD, false); 11548 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 11549 << getOpenMPClauseName(CKind); 11550 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 11551 continue; 11552 } 11553 11554 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 11555 // A list item cannot appear in both a map clause and a data-sharing 11556 // attribute clause on the same construct. 11557 11558 // Check conflicts with other map clause expressions. We check the conflicts 11559 // with the current construct separately from the enclosing data 11560 // environment, because the restrictions are different. We only have to 11561 // check conflicts across regions for the map clauses. 11562 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 11563 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 11564 break; 11565 if (CKind == OMPC_map && 11566 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 11567 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 11568 break; 11569 11570 // OpenMP 4.5 [2.10.5, target update Construct] 11571 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11572 // If the type of a list item is a reference to a type T then the type will 11573 // be considered to be T for all purposes of this clause. 11574 QualType Type = CurDeclaration->getType().getNonReferenceType(); 11575 11576 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 11577 // A list item in a to or from clause must have a mappable type. 11578 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 11579 // A list item must have a mappable type. 11580 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 11581 DSAS, Type)) 11582 continue; 11583 11584 if (CKind == OMPC_map) { 11585 // target enter data 11586 // OpenMP [2.10.2, Restrictions, p. 99] 11587 // A map-type must be specified in all map clauses and must be either 11588 // to or alloc. 11589 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 11590 if (DKind == OMPD_target_enter_data && 11591 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 11592 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 11593 << (IsMapTypeImplicit ? 1 : 0) 11594 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 11595 << getOpenMPDirectiveName(DKind); 11596 continue; 11597 } 11598 11599 // target exit_data 11600 // OpenMP [2.10.3, Restrictions, p. 102] 11601 // A map-type must be specified in all map clauses and must be either 11602 // from, release, or delete. 11603 if (DKind == OMPD_target_exit_data && 11604 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 11605 MapType == OMPC_MAP_delete)) { 11606 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 11607 << (IsMapTypeImplicit ? 1 : 0) 11608 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 11609 << getOpenMPDirectiveName(DKind); 11610 continue; 11611 } 11612 11613 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 11614 // A list item cannot appear in both a map clause and a data-sharing 11615 // attribute clause on the same construct 11616 if ((DKind == OMPD_target || DKind == OMPD_target_teams || 11617 DKind == OMPD_target_teams_distribute || 11618 DKind == OMPD_target_teams_distribute_parallel_for || 11619 DKind == OMPD_target_teams_distribute_parallel_for_simd || 11620 DKind == OMPD_target_teams_distribute_simd) && VD) { 11621 auto DVar = DSAS->getTopDSA(VD, false); 11622 if (isOpenMPPrivate(DVar.CKind)) { 11623 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 11624 << getOpenMPClauseName(DVar.CKind) 11625 << getOpenMPClauseName(OMPC_map) 11626 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 11627 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 11628 continue; 11629 } 11630 } 11631 } 11632 11633 // Save the current expression. 11634 MVLI.ProcessedVarList.push_back(RE); 11635 11636 // Store the components in the stack so that they can be used to check 11637 // against other clauses later on. 11638 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 11639 /*WhereFoundClauseKind=*/OMPC_map); 11640 11641 // Save the components and declaration to create the clause. For purposes of 11642 // the clause creation, any component list that has has base 'this' uses 11643 // null as base declaration. 11644 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11645 MVLI.VarComponents.back().append(CurComponents.begin(), 11646 CurComponents.end()); 11647 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 11648 : CurDeclaration); 11649 } 11650 } 11651 11652 OMPClause * 11653 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 11654 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 11655 SourceLocation MapLoc, SourceLocation ColonLoc, 11656 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 11657 SourceLocation LParenLoc, SourceLocation EndLoc) { 11658 MappableVarListInfo MVLI(VarList); 11659 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 11660 MapType, IsMapTypeImplicit); 11661 11662 // We need to produce a map clause even if we don't have variables so that 11663 // other diagnostics related with non-existing map clauses are accurate. 11664 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11665 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11666 MVLI.VarComponents, MapTypeModifier, MapType, 11667 IsMapTypeImplicit, MapLoc); 11668 } 11669 11670 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 11671 TypeResult ParsedType) { 11672 assert(ParsedType.isUsable()); 11673 11674 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 11675 if (ReductionType.isNull()) 11676 return QualType(); 11677 11678 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 11679 // A type name in a declare reduction directive cannot be a function type, an 11680 // array type, a reference type, or a type qualified with const, volatile or 11681 // restrict. 11682 if (ReductionType.hasQualifiers()) { 11683 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 11684 return QualType(); 11685 } 11686 11687 if (ReductionType->isFunctionType()) { 11688 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 11689 return QualType(); 11690 } 11691 if (ReductionType->isReferenceType()) { 11692 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 11693 return QualType(); 11694 } 11695 if (ReductionType->isArrayType()) { 11696 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 11697 return QualType(); 11698 } 11699 return ReductionType; 11700 } 11701 11702 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 11703 Scope *S, DeclContext *DC, DeclarationName Name, 11704 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 11705 AccessSpecifier AS, Decl *PrevDeclInScope) { 11706 SmallVector<Decl *, 8> Decls; 11707 Decls.reserve(ReductionTypes.size()); 11708 11709 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 11710 forRedeclarationInCurContext()); 11711 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 11712 // A reduction-identifier may not be re-declared in the current scope for the 11713 // same type or for a type that is compatible according to the base language 11714 // rules. 11715 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 11716 OMPDeclareReductionDecl *PrevDRD = nullptr; 11717 bool InCompoundScope = true; 11718 if (S != nullptr) { 11719 // Find previous declaration with the same name not referenced in other 11720 // declarations. 11721 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 11722 InCompoundScope = 11723 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 11724 LookupName(Lookup, S); 11725 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 11726 /*AllowInlineNamespace=*/false); 11727 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 11728 auto Filter = Lookup.makeFilter(); 11729 while (Filter.hasNext()) { 11730 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 11731 if (InCompoundScope) { 11732 auto I = UsedAsPrevious.find(PrevDecl); 11733 if (I == UsedAsPrevious.end()) 11734 UsedAsPrevious[PrevDecl] = false; 11735 if (auto *D = PrevDecl->getPrevDeclInScope()) 11736 UsedAsPrevious[D] = true; 11737 } 11738 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 11739 PrevDecl->getLocation(); 11740 } 11741 Filter.done(); 11742 if (InCompoundScope) { 11743 for (auto &PrevData : UsedAsPrevious) { 11744 if (!PrevData.second) { 11745 PrevDRD = PrevData.first; 11746 break; 11747 } 11748 } 11749 } 11750 } else if (PrevDeclInScope != nullptr) { 11751 auto *PrevDRDInScope = PrevDRD = 11752 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 11753 do { 11754 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 11755 PrevDRDInScope->getLocation(); 11756 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 11757 } while (PrevDRDInScope != nullptr); 11758 } 11759 for (auto &TyData : ReductionTypes) { 11760 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 11761 bool Invalid = false; 11762 if (I != PreviousRedeclTypes.end()) { 11763 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 11764 << TyData.first; 11765 Diag(I->second, diag::note_previous_definition); 11766 Invalid = true; 11767 } 11768 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 11769 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 11770 Name, TyData.first, PrevDRD); 11771 DC->addDecl(DRD); 11772 DRD->setAccess(AS); 11773 Decls.push_back(DRD); 11774 if (Invalid) 11775 DRD->setInvalidDecl(); 11776 else 11777 PrevDRD = DRD; 11778 } 11779 11780 return DeclGroupPtrTy::make( 11781 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 11782 } 11783 11784 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 11785 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11786 11787 // Enter new function scope. 11788 PushFunctionScope(); 11789 getCurFunction()->setHasBranchProtectedScope(); 11790 getCurFunction()->setHasOMPDeclareReductionCombiner(); 11791 11792 if (S != nullptr) 11793 PushDeclContext(S, DRD); 11794 else 11795 CurContext = DRD; 11796 11797 PushExpressionEvaluationContext( 11798 ExpressionEvaluationContext::PotentiallyEvaluated); 11799 11800 QualType ReductionType = DRD->getType(); 11801 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 11802 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 11803 // uses semantics of argument handles by value, but it should be passed by 11804 // reference. C lang does not support references, so pass all parameters as 11805 // pointers. 11806 // Create 'T omp_in;' variable. 11807 auto *OmpInParm = 11808 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 11809 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 11810 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 11811 // uses semantics of argument handles by value, but it should be passed by 11812 // reference. C lang does not support references, so pass all parameters as 11813 // pointers. 11814 // Create 'T omp_out;' variable. 11815 auto *OmpOutParm = 11816 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 11817 if (S != nullptr) { 11818 PushOnScopeChains(OmpInParm, S); 11819 PushOnScopeChains(OmpOutParm, S); 11820 } else { 11821 DRD->addDecl(OmpInParm); 11822 DRD->addDecl(OmpOutParm); 11823 } 11824 } 11825 11826 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 11827 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11828 DiscardCleanupsInEvaluationContext(); 11829 PopExpressionEvaluationContext(); 11830 11831 PopDeclContext(); 11832 PopFunctionScopeInfo(); 11833 11834 if (Combiner != nullptr) 11835 DRD->setCombiner(Combiner); 11836 else 11837 DRD->setInvalidDecl(); 11838 } 11839 11840 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 11841 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11842 11843 // Enter new function scope. 11844 PushFunctionScope(); 11845 getCurFunction()->setHasBranchProtectedScope(); 11846 11847 if (S != nullptr) 11848 PushDeclContext(S, DRD); 11849 else 11850 CurContext = DRD; 11851 11852 PushExpressionEvaluationContext( 11853 ExpressionEvaluationContext::PotentiallyEvaluated); 11854 11855 QualType ReductionType = DRD->getType(); 11856 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 11857 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 11858 // uses semantics of argument handles by value, but it should be passed by 11859 // reference. C lang does not support references, so pass all parameters as 11860 // pointers. 11861 // Create 'T omp_priv;' variable. 11862 auto *OmpPrivParm = 11863 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 11864 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 11865 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 11866 // uses semantics of argument handles by value, but it should be passed by 11867 // reference. C lang does not support references, so pass all parameters as 11868 // pointers. 11869 // Create 'T omp_orig;' variable. 11870 auto *OmpOrigParm = 11871 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 11872 if (S != nullptr) { 11873 PushOnScopeChains(OmpPrivParm, S); 11874 PushOnScopeChains(OmpOrigParm, S); 11875 } else { 11876 DRD->addDecl(OmpPrivParm); 11877 DRD->addDecl(OmpOrigParm); 11878 } 11879 return OmpPrivParm; 11880 } 11881 11882 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 11883 VarDecl *OmpPrivParm) { 11884 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11885 DiscardCleanupsInEvaluationContext(); 11886 PopExpressionEvaluationContext(); 11887 11888 PopDeclContext(); 11889 PopFunctionScopeInfo(); 11890 11891 if (Initializer != nullptr) { 11892 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 11893 } else if (OmpPrivParm->hasInit()) { 11894 DRD->setInitializer(OmpPrivParm->getInit(), 11895 OmpPrivParm->isDirectInit() 11896 ? OMPDeclareReductionDecl::DirectInit 11897 : OMPDeclareReductionDecl::CopyInit); 11898 } else { 11899 DRD->setInvalidDecl(); 11900 } 11901 } 11902 11903 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 11904 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 11905 for (auto *D : DeclReductions.get()) { 11906 if (IsValid) { 11907 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11908 if (S != nullptr) 11909 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 11910 } else 11911 D->setInvalidDecl(); 11912 } 11913 return DeclReductions; 11914 } 11915 11916 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 11917 SourceLocation StartLoc, 11918 SourceLocation LParenLoc, 11919 SourceLocation EndLoc) { 11920 Expr *ValExpr = NumTeams; 11921 Stmt *HelperValStmt = nullptr; 11922 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11923 11924 // OpenMP [teams Constrcut, Restrictions] 11925 // The num_teams expression must evaluate to a positive integer value. 11926 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 11927 /*StrictlyPositive=*/true)) 11928 return nullptr; 11929 11930 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11931 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 11932 if (CaptureRegion != OMPD_unknown) { 11933 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11934 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11935 HelperValStmt = buildPreInits(Context, Captures); 11936 } 11937 11938 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 11939 StartLoc, LParenLoc, EndLoc); 11940 } 11941 11942 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 11943 SourceLocation StartLoc, 11944 SourceLocation LParenLoc, 11945 SourceLocation EndLoc) { 11946 Expr *ValExpr = ThreadLimit; 11947 Stmt *HelperValStmt = nullptr; 11948 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11949 11950 // OpenMP [teams Constrcut, Restrictions] 11951 // The thread_limit expression must evaluate to a positive integer value. 11952 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 11953 /*StrictlyPositive=*/true)) 11954 return nullptr; 11955 11956 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11957 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 11958 if (CaptureRegion != OMPD_unknown) { 11959 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11960 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11961 HelperValStmt = buildPreInits(Context, Captures); 11962 } 11963 11964 return new (Context) OMPThreadLimitClause( 11965 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 11966 } 11967 11968 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 11969 SourceLocation StartLoc, 11970 SourceLocation LParenLoc, 11971 SourceLocation EndLoc) { 11972 Expr *ValExpr = Priority; 11973 11974 // OpenMP [2.9.1, task Constrcut] 11975 // The priority-value is a non-negative numerical scalar expression. 11976 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 11977 /*StrictlyPositive=*/false)) 11978 return nullptr; 11979 11980 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11981 } 11982 11983 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 11984 SourceLocation StartLoc, 11985 SourceLocation LParenLoc, 11986 SourceLocation EndLoc) { 11987 Expr *ValExpr = Grainsize; 11988 11989 // OpenMP [2.9.2, taskloop Constrcut] 11990 // The parameter of the grainsize clause must be a positive integer 11991 // expression. 11992 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 11993 /*StrictlyPositive=*/true)) 11994 return nullptr; 11995 11996 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11997 } 11998 11999 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 12000 SourceLocation StartLoc, 12001 SourceLocation LParenLoc, 12002 SourceLocation EndLoc) { 12003 Expr *ValExpr = NumTasks; 12004 12005 // OpenMP [2.9.2, taskloop Constrcut] 12006 // The parameter of the num_tasks clause must be a positive integer 12007 // expression. 12008 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 12009 /*StrictlyPositive=*/true)) 12010 return nullptr; 12011 12012 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 12013 } 12014 12015 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 12016 SourceLocation LParenLoc, 12017 SourceLocation EndLoc) { 12018 // OpenMP [2.13.2, critical construct, Description] 12019 // ... where hint-expression is an integer constant expression that evaluates 12020 // to a valid lock hint. 12021 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 12022 if (HintExpr.isInvalid()) 12023 return nullptr; 12024 return new (Context) 12025 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 12026 } 12027 12028 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 12029 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 12030 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 12031 SourceLocation EndLoc) { 12032 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 12033 std::string Values; 12034 Values += "'"; 12035 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 12036 Values += "'"; 12037 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 12038 << Values << getOpenMPClauseName(OMPC_dist_schedule); 12039 return nullptr; 12040 } 12041 Expr *ValExpr = ChunkSize; 12042 Stmt *HelperValStmt = nullptr; 12043 if (ChunkSize) { 12044 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 12045 !ChunkSize->isInstantiationDependent() && 12046 !ChunkSize->containsUnexpandedParameterPack()) { 12047 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 12048 ExprResult Val = 12049 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 12050 if (Val.isInvalid()) 12051 return nullptr; 12052 12053 ValExpr = Val.get(); 12054 12055 // OpenMP [2.7.1, Restrictions] 12056 // chunk_size must be a loop invariant integer expression with a positive 12057 // value. 12058 llvm::APSInt Result; 12059 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 12060 if (Result.isSigned() && !Result.isStrictlyPositive()) { 12061 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 12062 << "dist_schedule" << ChunkSize->getSourceRange(); 12063 return nullptr; 12064 } 12065 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 12066 !CurContext->isDependentContext()) { 12067 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 12068 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12069 HelperValStmt = buildPreInits(Context, Captures); 12070 } 12071 } 12072 } 12073 12074 return new (Context) 12075 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 12076 Kind, ValExpr, HelperValStmt); 12077 } 12078 12079 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 12080 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 12081 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 12082 SourceLocation KindLoc, SourceLocation EndLoc) { 12083 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 12084 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 12085 std::string Value; 12086 SourceLocation Loc; 12087 Value += "'"; 12088 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 12089 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 12090 OMPC_DEFAULTMAP_MODIFIER_tofrom); 12091 Loc = MLoc; 12092 } else { 12093 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 12094 OMPC_DEFAULTMAP_scalar); 12095 Loc = KindLoc; 12096 } 12097 Value += "'"; 12098 Diag(Loc, diag::err_omp_unexpected_clause_value) 12099 << Value << getOpenMPClauseName(OMPC_defaultmap); 12100 return nullptr; 12101 } 12102 DSAStack->setDefaultDMAToFromScalar(StartLoc); 12103 12104 return new (Context) 12105 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 12106 } 12107 12108 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 12109 DeclContext *CurLexicalContext = getCurLexicalContext(); 12110 if (!CurLexicalContext->isFileContext() && 12111 !CurLexicalContext->isExternCContext() && 12112 !CurLexicalContext->isExternCXXContext() && 12113 !isa<CXXRecordDecl>(CurLexicalContext) && 12114 !isa<ClassTemplateDecl>(CurLexicalContext) && 12115 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 12116 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 12117 Diag(Loc, diag::err_omp_region_not_file_context); 12118 return false; 12119 } 12120 if (IsInOpenMPDeclareTargetContext) { 12121 Diag(Loc, diag::err_omp_enclosed_declare_target); 12122 return false; 12123 } 12124 12125 IsInOpenMPDeclareTargetContext = true; 12126 return true; 12127 } 12128 12129 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 12130 assert(IsInOpenMPDeclareTargetContext && 12131 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 12132 12133 IsInOpenMPDeclareTargetContext = false; 12134 } 12135 12136 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 12137 CXXScopeSpec &ScopeSpec, 12138 const DeclarationNameInfo &Id, 12139 OMPDeclareTargetDeclAttr::MapTypeTy MT, 12140 NamedDeclSetType &SameDirectiveDecls) { 12141 LookupResult Lookup(*this, Id, LookupOrdinaryName); 12142 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 12143 12144 if (Lookup.isAmbiguous()) 12145 return; 12146 Lookup.suppressDiagnostics(); 12147 12148 if (!Lookup.isSingleResult()) { 12149 if (TypoCorrection Corrected = 12150 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 12151 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 12152 CTK_ErrorRecovery)) { 12153 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 12154 << Id.getName()); 12155 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 12156 return; 12157 } 12158 12159 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 12160 return; 12161 } 12162 12163 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 12164 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 12165 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 12166 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 12167 12168 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 12169 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 12170 ND->addAttr(A); 12171 if (ASTMutationListener *ML = Context.getASTMutationListener()) 12172 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 12173 checkDeclIsAllowedInOpenMPTarget(nullptr, ND); 12174 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 12175 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 12176 << Id.getName(); 12177 } 12178 } else 12179 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 12180 } 12181 12182 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 12183 Sema &SemaRef, Decl *D) { 12184 if (!D) 12185 return; 12186 Decl *LD = nullptr; 12187 if (isa<TagDecl>(D)) { 12188 LD = cast<TagDecl>(D)->getDefinition(); 12189 } else if (isa<VarDecl>(D)) { 12190 LD = cast<VarDecl>(D)->getDefinition(); 12191 12192 // If this is an implicit variable that is legal and we do not need to do 12193 // anything. 12194 if (cast<VarDecl>(D)->isImplicit()) { 12195 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12196 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 12197 D->addAttr(A); 12198 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 12199 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12200 return; 12201 } 12202 12203 } else if (isa<FunctionDecl>(D)) { 12204 const FunctionDecl *FD = nullptr; 12205 if (cast<FunctionDecl>(D)->hasBody(FD)) 12206 LD = const_cast<FunctionDecl *>(FD); 12207 12208 // If the definition is associated with the current declaration in the 12209 // target region (it can be e.g. a lambda) that is legal and we do not need 12210 // to do anything else. 12211 if (LD == D) { 12212 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12213 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 12214 D->addAttr(A); 12215 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 12216 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12217 return; 12218 } 12219 } 12220 if (!LD) 12221 LD = D; 12222 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 12223 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 12224 // Outlined declaration is not declared target. 12225 if (LD->isOutOfLine()) { 12226 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 12227 SemaRef.Diag(SL, diag::note_used_here) << SR; 12228 } else { 12229 DeclContext *DC = LD->getDeclContext(); 12230 while (DC) { 12231 if (isa<FunctionDecl>(DC) && 12232 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 12233 break; 12234 DC = DC->getParent(); 12235 } 12236 if (DC) 12237 return; 12238 12239 // Is not declared in target context. 12240 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 12241 SemaRef.Diag(SL, diag::note_used_here) << SR; 12242 } 12243 // Mark decl as declared target to prevent further diagnostic. 12244 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12245 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 12246 D->addAttr(A); 12247 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 12248 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12249 } 12250 } 12251 12252 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 12253 Sema &SemaRef, DSAStackTy *Stack, 12254 ValueDecl *VD) { 12255 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 12256 return true; 12257 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) 12258 return false; 12259 return true; 12260 } 12261 12262 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) { 12263 if (!D || D->isInvalidDecl()) 12264 return; 12265 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 12266 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 12267 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 12268 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12269 if (DSAStack->isThreadPrivate(VD)) { 12270 Diag(SL, diag::err_omp_threadprivate_in_target); 12271 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 12272 return; 12273 } 12274 } 12275 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 12276 // Problem if any with var declared with incomplete type will be reported 12277 // as normal, so no need to check it here. 12278 if ((E || !VD->getType()->isIncompleteType()) && 12279 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 12280 // Mark decl as declared target to prevent further diagnostic. 12281 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { 12282 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12283 Context, OMPDeclareTargetDeclAttr::MT_To); 12284 VD->addAttr(A); 12285 if (ASTMutationListener *ML = Context.getASTMutationListener()) 12286 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 12287 } 12288 return; 12289 } 12290 } 12291 if (!E) { 12292 // Checking declaration inside declare target region. 12293 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 12294 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { 12295 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12296 Context, OMPDeclareTargetDeclAttr::MT_To); 12297 D->addAttr(A); 12298 if (ASTMutationListener *ML = Context.getASTMutationListener()) 12299 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12300 } 12301 return; 12302 } 12303 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 12304 } 12305 12306 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 12307 SourceLocation StartLoc, 12308 SourceLocation LParenLoc, 12309 SourceLocation EndLoc) { 12310 MappableVarListInfo MVLI(VarList); 12311 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 12312 if (MVLI.ProcessedVarList.empty()) 12313 return nullptr; 12314 12315 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12316 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 12317 MVLI.VarComponents); 12318 } 12319 12320 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 12321 SourceLocation StartLoc, 12322 SourceLocation LParenLoc, 12323 SourceLocation EndLoc) { 12324 MappableVarListInfo MVLI(VarList); 12325 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 12326 if (MVLI.ProcessedVarList.empty()) 12327 return nullptr; 12328 12329 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12330 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 12331 MVLI.VarComponents); 12332 } 12333 12334 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 12335 SourceLocation StartLoc, 12336 SourceLocation LParenLoc, 12337 SourceLocation EndLoc) { 12338 MappableVarListInfo MVLI(VarList); 12339 SmallVector<Expr *, 8> PrivateCopies; 12340 SmallVector<Expr *, 8> Inits; 12341 12342 for (auto &RefExpr : VarList) { 12343 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 12344 SourceLocation ELoc; 12345 SourceRange ERange; 12346 Expr *SimpleRefExpr = RefExpr; 12347 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12348 if (Res.second) { 12349 // It will be analyzed later. 12350 MVLI.ProcessedVarList.push_back(RefExpr); 12351 PrivateCopies.push_back(nullptr); 12352 Inits.push_back(nullptr); 12353 } 12354 ValueDecl *D = Res.first; 12355 if (!D) 12356 continue; 12357 12358 QualType Type = D->getType(); 12359 Type = Type.getNonReferenceType().getUnqualifiedType(); 12360 12361 auto *VD = dyn_cast<VarDecl>(D); 12362 12363 // Item should be a pointer or reference to pointer. 12364 if (!Type->isPointerType()) { 12365 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 12366 << 0 << RefExpr->getSourceRange(); 12367 continue; 12368 } 12369 12370 // Build the private variable and the expression that refers to it. 12371 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 12372 D->hasAttrs() ? &D->getAttrs() : nullptr); 12373 if (VDPrivate->isInvalidDecl()) 12374 continue; 12375 12376 CurContext->addDecl(VDPrivate); 12377 auto VDPrivateRefExpr = buildDeclRefExpr( 12378 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 12379 12380 // Add temporary variable to initialize the private copy of the pointer. 12381 auto *VDInit = 12382 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 12383 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 12384 RefExpr->getExprLoc()); 12385 AddInitializerToDecl(VDPrivate, 12386 DefaultLvalueConversion(VDInitRefExpr).get(), 12387 /*DirectInit=*/false); 12388 12389 // If required, build a capture to implement the privatization initialized 12390 // with the current list item value. 12391 DeclRefExpr *Ref = nullptr; 12392 if (!VD) 12393 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 12394 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 12395 PrivateCopies.push_back(VDPrivateRefExpr); 12396 Inits.push_back(VDInitRefExpr); 12397 12398 // We need to add a data sharing attribute for this variable to make sure it 12399 // is correctly captured. A variable that shows up in a use_device_ptr has 12400 // similar properties of a first private variable. 12401 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 12402 12403 // Create a mappable component for the list item. List items in this clause 12404 // only need a component. 12405 MVLI.VarBaseDeclarations.push_back(D); 12406 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 12407 MVLI.VarComponents.back().push_back( 12408 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 12409 } 12410 12411 if (MVLI.ProcessedVarList.empty()) 12412 return nullptr; 12413 12414 return OMPUseDevicePtrClause::Create( 12415 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 12416 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 12417 } 12418 12419 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 12420 SourceLocation StartLoc, 12421 SourceLocation LParenLoc, 12422 SourceLocation EndLoc) { 12423 MappableVarListInfo MVLI(VarList); 12424 for (auto &RefExpr : VarList) { 12425 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 12426 SourceLocation ELoc; 12427 SourceRange ERange; 12428 Expr *SimpleRefExpr = RefExpr; 12429 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12430 if (Res.second) { 12431 // It will be analyzed later. 12432 MVLI.ProcessedVarList.push_back(RefExpr); 12433 } 12434 ValueDecl *D = Res.first; 12435 if (!D) 12436 continue; 12437 12438 QualType Type = D->getType(); 12439 // item should be a pointer or array or reference to pointer or array 12440 if (!Type.getNonReferenceType()->isPointerType() && 12441 !Type.getNonReferenceType()->isArrayType()) { 12442 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 12443 << 0 << RefExpr->getSourceRange(); 12444 continue; 12445 } 12446 12447 // Check if the declaration in the clause does not show up in any data 12448 // sharing attribute. 12449 auto DVar = DSAStack->getTopDSA(D, false); 12450 if (isOpenMPPrivate(DVar.CKind)) { 12451 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 12452 << getOpenMPClauseName(DVar.CKind) 12453 << getOpenMPClauseName(OMPC_is_device_ptr) 12454 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 12455 ReportOriginalDSA(*this, DSAStack, D, DVar); 12456 continue; 12457 } 12458 12459 Expr *ConflictExpr; 12460 if (DSAStack->checkMappableExprComponentListsForDecl( 12461 D, /*CurrentRegionOnly=*/true, 12462 [&ConflictExpr]( 12463 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 12464 OpenMPClauseKind) -> bool { 12465 ConflictExpr = R.front().getAssociatedExpression(); 12466 return true; 12467 })) { 12468 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 12469 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 12470 << ConflictExpr->getSourceRange(); 12471 continue; 12472 } 12473 12474 // Store the components in the stack so that they can be used to check 12475 // against other clauses later on. 12476 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 12477 DSAStack->addMappableExpressionComponents( 12478 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 12479 12480 // Record the expression we've just processed. 12481 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 12482 12483 // Create a mappable component for the list item. List items in this clause 12484 // only need a component. We use a null declaration to signal fields in 12485 // 'this'. 12486 assert((isa<DeclRefExpr>(SimpleRefExpr) || 12487 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 12488 "Unexpected device pointer expression!"); 12489 MVLI.VarBaseDeclarations.push_back( 12490 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 12491 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 12492 MVLI.VarComponents.back().push_back(MC); 12493 } 12494 12495 if (MVLI.ProcessedVarList.empty()) 12496 return nullptr; 12497 12498 return OMPIsDevicePtrClause::Create( 12499 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 12500 MVLI.VarBaseDeclarations, MVLI.VarComponents); 12501 } 12502