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 } 970 971 if (isStackEmpty()) 972 // Not in OpenMP execution region and top scope was already checked. 973 return DVar; 974 975 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 976 // in a Construct, C/C++, predetermined, p.4] 977 // Static data members are shared. 978 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 979 // in a Construct, C/C++, predetermined, p.7] 980 // Variables with static storage duration that are declared in a scope 981 // inside the construct are shared. 982 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; 983 if (VD && VD->isStaticDataMember()) { 984 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 985 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 986 return DVar; 987 988 DVar.CKind = OMPC_shared; 989 return DVar; 990 } 991 992 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 993 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 994 Type = SemaRef.getASTContext().getBaseElementType(Type); 995 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 996 // in a Construct, C/C++, predetermined, p.6] 997 // Variables with const qualified type having no mutable member are 998 // shared. 999 CXXRecordDecl *RD = 1000 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 1001 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1002 if (auto *CTD = CTSD->getSpecializedTemplate()) 1003 RD = CTD->getTemplatedDecl(); 1004 if (IsConstant && 1005 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && 1006 RD->hasMutableFields())) { 1007 // Variables with const-qualified type having no mutable member may be 1008 // listed in a firstprivate clause, even if they are static data members. 1009 DSAVarData DVarTemp = hasDSA( 1010 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, 1011 MatchesAlways, FromParent); 1012 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 1013 return DVar; 1014 1015 DVar.CKind = OMPC_shared; 1016 return DVar; 1017 } 1018 1019 // Explicitly specified attributes and local variables with predetermined 1020 // attributes. 1021 auto I = Stack.back().first.rbegin(); 1022 auto EndI = Stack.back().first.rend(); 1023 if (FromParent && I != EndI) 1024 std::advance(I, 1); 1025 if (I->SharingMap.count(D)) { 1026 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); 1027 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; 1028 DVar.CKind = I->SharingMap[D].Attributes; 1029 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1030 DVar.DKind = I->Directive; 1031 } 1032 1033 return DVar; 1034 } 1035 1036 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1037 bool FromParent) { 1038 if (isStackEmpty()) { 1039 StackTy::reverse_iterator I; 1040 return getDSA(I, D); 1041 } 1042 D = getCanonicalDecl(D); 1043 auto StartI = Stack.back().first.rbegin(); 1044 auto EndI = Stack.back().first.rend(); 1045 if (FromParent && StartI != EndI) 1046 std::advance(StartI, 1); 1047 return getDSA(StartI, D); 1048 } 1049 1050 DSAStackTy::DSAVarData 1051 DSAStackTy::hasDSA(ValueDecl *D, 1052 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1053 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1054 bool FromParent) { 1055 if (isStackEmpty()) 1056 return {}; 1057 D = getCanonicalDecl(D); 1058 auto I = Stack.back().first.rbegin(); 1059 auto EndI = Stack.back().first.rend(); 1060 if (FromParent && I != EndI) 1061 std::advance(I, 1); 1062 for (; I != EndI; std::advance(I, 1)) { 1063 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 1064 continue; 1065 auto NewI = I; 1066 DSAVarData DVar = getDSA(NewI, D); 1067 if (I == NewI && CPred(DVar.CKind)) 1068 return DVar; 1069 } 1070 return {}; 1071 } 1072 1073 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1074 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1075 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1076 bool FromParent) { 1077 if (isStackEmpty()) 1078 return {}; 1079 D = getCanonicalDecl(D); 1080 auto StartI = Stack.back().first.rbegin(); 1081 auto EndI = Stack.back().first.rend(); 1082 if (FromParent && StartI != EndI) 1083 std::advance(StartI, 1); 1084 if (StartI == EndI || !DPred(StartI->Directive)) 1085 return {}; 1086 auto NewI = StartI; 1087 DSAVarData DVar = getDSA(NewI, D); 1088 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); 1089 } 1090 1091 bool DSAStackTy::hasExplicitDSA( 1092 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1093 unsigned Level, bool NotLastprivate) { 1094 if (CPred(ClauseKindMode)) 1095 return true; 1096 if (isStackEmpty()) 1097 return false; 1098 D = getCanonicalDecl(D); 1099 auto StartI = Stack.back().first.begin(); 1100 auto EndI = Stack.back().first.end(); 1101 if (std::distance(StartI, EndI) <= (int)Level) 1102 return false; 1103 std::advance(StartI, Level); 1104 return (StartI->SharingMap.count(D) > 0) && 1105 StartI->SharingMap[D].RefExpr.getPointer() && 1106 CPred(StartI->SharingMap[D].Attributes) && 1107 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt()); 1108 } 1109 1110 bool DSAStackTy::hasExplicitDirective( 1111 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1112 unsigned Level) { 1113 if (isStackEmpty()) 1114 return false; 1115 auto StartI = Stack.back().first.begin(); 1116 auto EndI = Stack.back().first.end(); 1117 if (std::distance(StartI, EndI) <= (int)Level) 1118 return false; 1119 std::advance(StartI, Level); 1120 return DPred(StartI->Directive); 1121 } 1122 1123 bool DSAStackTy::hasDirective( 1124 const llvm::function_ref<bool(OpenMPDirectiveKind, 1125 const DeclarationNameInfo &, SourceLocation)> 1126 &DPred, 1127 bool FromParent) { 1128 // We look only in the enclosing region. 1129 if (isStackEmpty()) 1130 return false; 1131 auto StartI = std::next(Stack.back().first.rbegin()); 1132 auto EndI = Stack.back().first.rend(); 1133 if (FromParent && StartI != EndI) 1134 StartI = std::next(StartI); 1135 for (auto I = StartI, EE = EndI; I != EE; ++I) { 1136 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1137 return true; 1138 } 1139 return false; 1140 } 1141 1142 void Sema::InitDataSharingAttributesStack() { 1143 VarDataSharingAttributesStack = new DSAStackTy(*this); 1144 } 1145 1146 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1147 1148 void Sema::pushOpenMPFunctionRegion() { 1149 DSAStack->pushFunction(); 1150 } 1151 1152 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1153 DSAStack->popFunction(OldFSI); 1154 } 1155 1156 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { 1157 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1158 1159 auto &Ctx = getASTContext(); 1160 bool IsByRef = true; 1161 1162 // Find the directive that is associated with the provided scope. 1163 D = cast<ValueDecl>(D->getCanonicalDecl()); 1164 auto Ty = D->getType(); 1165 1166 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1167 // This table summarizes how a given variable should be passed to the device 1168 // given its type and the clauses where it appears. This table is based on 1169 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1170 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1171 // 1172 // ========================================================================= 1173 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1174 // | |(tofrom:scalar)| | pvt | | | | 1175 // ========================================================================= 1176 // | scl | | | | - | | bycopy| 1177 // | scl | | - | x | - | - | bycopy| 1178 // | scl | | x | - | - | - | null | 1179 // | scl | x | | | - | | byref | 1180 // | scl | x | - | x | - | - | bycopy| 1181 // | scl | x | x | - | - | - | null | 1182 // | scl | | - | - | - | x | byref | 1183 // | scl | x | - | - | - | x | byref | 1184 // 1185 // | agg | n.a. | | | - | | byref | 1186 // | agg | n.a. | - | x | - | - | byref | 1187 // | agg | n.a. | x | - | - | - | null | 1188 // | agg | n.a. | - | - | - | x | byref | 1189 // | agg | n.a. | - | - | - | x[] | byref | 1190 // 1191 // | ptr | n.a. | | | - | | bycopy| 1192 // | ptr | n.a. | - | x | - | - | bycopy| 1193 // | ptr | n.a. | x | - | - | - | null | 1194 // | ptr | n.a. | - | - | - | x | byref | 1195 // | ptr | n.a. | - | - | - | x[] | bycopy| 1196 // | ptr | n.a. | - | - | x | | bycopy| 1197 // | ptr | n.a. | - | - | x | x | bycopy| 1198 // | ptr | n.a. | - | - | x | x[] | bycopy| 1199 // ========================================================================= 1200 // Legend: 1201 // scl - scalar 1202 // ptr - pointer 1203 // agg - aggregate 1204 // x - applies 1205 // - - invalid in this combination 1206 // [] - mapped with an array section 1207 // byref - should be mapped by reference 1208 // byval - should be mapped by value 1209 // null - initialize a local variable to null on the device 1210 // 1211 // Observations: 1212 // - All scalar declarations that show up in a map clause have to be passed 1213 // by reference, because they may have been mapped in the enclosing data 1214 // environment. 1215 // - If the scalar value does not fit the size of uintptr, it has to be 1216 // passed by reference, regardless the result in the table above. 1217 // - For pointers mapped by value that have either an implicit map or an 1218 // array section, the runtime library may pass the NULL value to the 1219 // device instead of the value passed to it by the compiler. 1220 1221 if (Ty->isReferenceType()) 1222 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1223 1224 // Locate map clauses and see if the variable being captured is referred to 1225 // in any of those clauses. Here we only care about variables, not fields, 1226 // because fields are part of aggregates. 1227 bool IsVariableUsedInMapClause = false; 1228 bool IsVariableAssociatedWithSection = false; 1229 1230 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1231 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 1232 MapExprComponents, 1233 OpenMPClauseKind WhereFoundClauseKind) { 1234 // Only the map clause information influences how a variable is 1235 // captured. E.g. is_device_ptr does not require changing the default 1236 // behavior. 1237 if (WhereFoundClauseKind != OMPC_map) 1238 return false; 1239 1240 auto EI = MapExprComponents.rbegin(); 1241 auto EE = MapExprComponents.rend(); 1242 1243 assert(EI != EE && "Invalid map expression!"); 1244 1245 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1246 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1247 1248 ++EI; 1249 if (EI == EE) 1250 return false; 1251 1252 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1253 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1254 isa<MemberExpr>(EI->getAssociatedExpression())) { 1255 IsVariableAssociatedWithSection = true; 1256 // There is nothing more we need to know about this variable. 1257 return true; 1258 } 1259 1260 // Keep looking for more map info. 1261 return false; 1262 }); 1263 1264 if (IsVariableUsedInMapClause) { 1265 // If variable is identified in a map clause it is always captured by 1266 // reference except if it is a pointer that is dereferenced somehow. 1267 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1268 } else { 1269 // By default, all the data that has a scalar type is mapped by copy. 1270 IsByRef = !Ty->isScalarType() || 1271 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar; 1272 } 1273 } 1274 1275 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1276 IsByRef = !DSAStack->hasExplicitDSA( 1277 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1278 Level, /*NotLastprivate=*/true); 1279 } 1280 1281 // When passing data by copy, we need to make sure it fits the uintptr size 1282 // and alignment, because the runtime library only deals with uintptr types. 1283 // If it does not fit the uintptr size, we need to pass the data by reference 1284 // instead. 1285 if (!IsByRef && 1286 (Ctx.getTypeSizeInChars(Ty) > 1287 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1288 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1289 IsByRef = true; 1290 } 1291 1292 return IsByRef; 1293 } 1294 1295 unsigned Sema::getOpenMPNestingLevel() const { 1296 assert(getLangOpts().OpenMP); 1297 return DSAStack->getNestingLevel(); 1298 } 1299 1300 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { 1301 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1302 D = getCanonicalDecl(D); 1303 1304 // If we are attempting to capture a global variable in a directive with 1305 // 'target' we return true so that this global is also mapped to the device. 1306 // 1307 // FIXME: If the declaration is enclosed in a 'declare target' directive, 1308 // then it should not be captured. Therefore, an extra check has to be 1309 // inserted here once support for 'declare target' is added. 1310 // 1311 auto *VD = dyn_cast<VarDecl>(D); 1312 if (VD && !VD->hasLocalStorage()) { 1313 if (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 1314 !DSAStack->isClauseParsingMode()) 1315 return VD; 1316 if (DSAStack->hasDirective( 1317 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1318 SourceLocation) -> bool { 1319 return isOpenMPTargetExecutionDirective(K); 1320 }, 1321 false)) 1322 return VD; 1323 } 1324 1325 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1326 (!DSAStack->isClauseParsingMode() || 1327 DSAStack->getParentDirective() != OMPD_unknown)) { 1328 auto &&Info = DSAStack->isLoopControlVariable(D); 1329 if (Info.first || 1330 (VD && VD->hasLocalStorage() && 1331 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 1332 (VD && DSAStack->isForceVarCapturing())) 1333 return VD ? VD : Info.second; 1334 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1335 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1336 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1337 DVarPrivate = DSAStack->hasDSA( 1338 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 1339 DSAStack->isClauseParsingMode()); 1340 if (DVarPrivate.CKind != OMPC_unknown) 1341 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1342 } 1343 return nullptr; 1344 } 1345 1346 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { 1347 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1348 return DSAStack->hasExplicitDSA( 1349 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, 1350 Level) || 1351 // Consider taskgroup reduction descriptor variable a private to avoid 1352 // possible capture in the region. 1353 (DSAStack->hasExplicitDirective( 1354 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; }, 1355 Level) && 1356 DSAStack->isTaskgroupReductionRef(D, Level)); 1357 } 1358 1359 void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) { 1360 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1361 D = getCanonicalDecl(D); 1362 OpenMPClauseKind OMPC = OMPC_unknown; 1363 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 1364 const unsigned NewLevel = I - 1; 1365 if (DSAStack->hasExplicitDSA(D, 1366 [&OMPC](const OpenMPClauseKind K) { 1367 if (isOpenMPPrivate(K)) { 1368 OMPC = K; 1369 return true; 1370 } 1371 return false; 1372 }, 1373 NewLevel)) 1374 break; 1375 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1376 D, NewLevel, 1377 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 1378 OpenMPClauseKind) { return true; })) { 1379 OMPC = OMPC_map; 1380 break; 1381 } 1382 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1383 NewLevel)) { 1384 OMPC = OMPC_firstprivate; 1385 break; 1386 } 1387 } 1388 if (OMPC != OMPC_unknown) 1389 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC)); 1390 } 1391 1392 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { 1393 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1394 // Return true if the current level is no longer enclosed in a target region. 1395 1396 auto *VD = dyn_cast<VarDecl>(D); 1397 return VD && !VD->hasLocalStorage() && 1398 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1399 Level); 1400 } 1401 1402 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1403 1404 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1405 const DeclarationNameInfo &DirName, 1406 Scope *CurScope, SourceLocation Loc) { 1407 DSAStack->push(DKind, DirName, CurScope, Loc); 1408 PushExpressionEvaluationContext( 1409 ExpressionEvaluationContext::PotentiallyEvaluated); 1410 } 1411 1412 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1413 DSAStack->setClauseParsingMode(K); 1414 } 1415 1416 void Sema::EndOpenMPClause() { 1417 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1418 } 1419 1420 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1421 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1422 // A variable of class type (or array thereof) that appears in a lastprivate 1423 // clause requires an accessible, unambiguous default constructor for the 1424 // class type, unless the list item is also specified in a firstprivate 1425 // clause. 1426 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1427 for (auto *C : D->clauses()) { 1428 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1429 SmallVector<Expr *, 8> PrivateCopies; 1430 for (auto *DE : Clause->varlists()) { 1431 if (DE->isValueDependent() || DE->isTypeDependent()) { 1432 PrivateCopies.push_back(nullptr); 1433 continue; 1434 } 1435 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1436 VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1437 QualType Type = VD->getType().getNonReferenceType(); 1438 auto DVar = DSAStack->getTopDSA(VD, false); 1439 if (DVar.CKind == OMPC_lastprivate) { 1440 // Generate helper private variable and initialize it with the 1441 // default value. The address of the original variable is replaced 1442 // by the address of the new private variable in CodeGen. This new 1443 // variable is not added to IdResolver, so the code in the OpenMP 1444 // region uses original variable for proper diagnostics. 1445 auto *VDPrivate = buildVarDecl( 1446 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1447 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); 1448 ActOnUninitializedDecl(VDPrivate); 1449 if (VDPrivate->isInvalidDecl()) 1450 continue; 1451 PrivateCopies.push_back(buildDeclRefExpr( 1452 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1453 } else { 1454 // The variable is also a firstprivate, so initialization sequence 1455 // for private copy is generated already. 1456 PrivateCopies.push_back(nullptr); 1457 } 1458 } 1459 // Set initializers to private copies if no errors were found. 1460 if (PrivateCopies.size() == Clause->varlist_size()) 1461 Clause->setPrivateCopies(PrivateCopies); 1462 } 1463 } 1464 } 1465 1466 DSAStack->pop(); 1467 DiscardCleanupsInEvaluationContext(); 1468 PopExpressionEvaluationContext(); 1469 } 1470 1471 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1472 Expr *NumIterations, Sema &SemaRef, 1473 Scope *S, DSAStackTy *Stack); 1474 1475 namespace { 1476 1477 class VarDeclFilterCCC : public CorrectionCandidateCallback { 1478 private: 1479 Sema &SemaRef; 1480 1481 public: 1482 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1483 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1484 NamedDecl *ND = Candidate.getCorrectionDecl(); 1485 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1486 return VD->hasGlobalStorage() && 1487 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1488 SemaRef.getCurScope()); 1489 } 1490 return false; 1491 } 1492 }; 1493 1494 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { 1495 private: 1496 Sema &SemaRef; 1497 1498 public: 1499 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1500 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1501 NamedDecl *ND = Candidate.getCorrectionDecl(); 1502 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 1503 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1504 SemaRef.getCurScope()); 1505 } 1506 return false; 1507 } 1508 }; 1509 1510 } // namespace 1511 1512 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1513 CXXScopeSpec &ScopeSpec, 1514 const DeclarationNameInfo &Id) { 1515 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1516 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1517 1518 if (Lookup.isAmbiguous()) 1519 return ExprError(); 1520 1521 VarDecl *VD; 1522 if (!Lookup.isSingleResult()) { 1523 if (TypoCorrection Corrected = CorrectTypo( 1524 Id, LookupOrdinaryName, CurScope, nullptr, 1525 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1526 diagnoseTypo(Corrected, 1527 PDiag(Lookup.empty() 1528 ? diag::err_undeclared_var_use_suggest 1529 : diag::err_omp_expected_var_arg_suggest) 1530 << Id.getName()); 1531 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1532 } else { 1533 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1534 : diag::err_omp_expected_var_arg) 1535 << Id.getName(); 1536 return ExprError(); 1537 } 1538 } else { 1539 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1540 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1541 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1542 return ExprError(); 1543 } 1544 } 1545 Lookup.suppressDiagnostics(); 1546 1547 // OpenMP [2.9.2, Syntax, C/C++] 1548 // Variables must be file-scope, namespace-scope, or static block-scope. 1549 if (!VD->hasGlobalStorage()) { 1550 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1551 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1552 bool IsDecl = 1553 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1554 Diag(VD->getLocation(), 1555 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1556 << VD; 1557 return ExprError(); 1558 } 1559 1560 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1561 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 1562 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1563 // A threadprivate directive for file-scope variables must appear outside 1564 // any definition or declaration. 1565 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1566 !getCurLexicalContext()->isTranslationUnit()) { 1567 Diag(Id.getLoc(), diag::err_omp_var_scope) 1568 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1569 bool IsDecl = 1570 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1571 Diag(VD->getLocation(), 1572 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1573 << VD; 1574 return ExprError(); 1575 } 1576 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1577 // A threadprivate directive for static class member variables must appear 1578 // in the class definition, in the same scope in which the member 1579 // variables are declared. 1580 if (CanonicalVD->isStaticDataMember() && 1581 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1582 Diag(Id.getLoc(), diag::err_omp_var_scope) 1583 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1584 bool IsDecl = 1585 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1586 Diag(VD->getLocation(), 1587 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1588 << VD; 1589 return ExprError(); 1590 } 1591 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1592 // A threadprivate directive for namespace-scope variables must appear 1593 // outside any definition or declaration other than the namespace 1594 // definition itself. 1595 if (CanonicalVD->getDeclContext()->isNamespace() && 1596 (!getCurLexicalContext()->isFileContext() || 1597 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1598 Diag(Id.getLoc(), diag::err_omp_var_scope) 1599 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1600 bool IsDecl = 1601 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1602 Diag(VD->getLocation(), 1603 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1604 << VD; 1605 return ExprError(); 1606 } 1607 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1608 // A threadprivate directive for static block-scope variables must appear 1609 // in the scope of the variable and not in a nested scope. 1610 if (CanonicalVD->isStaticLocal() && CurScope && 1611 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1612 Diag(Id.getLoc(), diag::err_omp_var_scope) 1613 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1614 bool IsDecl = 1615 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1616 Diag(VD->getLocation(), 1617 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1618 << VD; 1619 return ExprError(); 1620 } 1621 1622 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1623 // A threadprivate directive must lexically precede all references to any 1624 // of the variables in its list. 1625 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1626 Diag(Id.getLoc(), diag::err_omp_var_used) 1627 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1628 return ExprError(); 1629 } 1630 1631 QualType ExprType = VD->getType().getNonReferenceType(); 1632 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1633 SourceLocation(), VD, 1634 /*RefersToEnclosingVariableOrCapture=*/false, 1635 Id.getLoc(), ExprType, VK_LValue); 1636 } 1637 1638 Sema::DeclGroupPtrTy 1639 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1640 ArrayRef<Expr *> VarList) { 1641 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1642 CurContext->addDecl(D); 1643 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1644 } 1645 return nullptr; 1646 } 1647 1648 namespace { 1649 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1650 Sema &SemaRef; 1651 1652 public: 1653 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1654 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1655 if (VD->hasLocalStorage()) { 1656 SemaRef.Diag(E->getLocStart(), 1657 diag::err_omp_local_var_in_threadprivate_init) 1658 << E->getSourceRange(); 1659 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1660 << VD << VD->getSourceRange(); 1661 return true; 1662 } 1663 } 1664 return false; 1665 } 1666 bool VisitStmt(const Stmt *S) { 1667 for (auto Child : S->children()) { 1668 if (Child && Visit(Child)) 1669 return true; 1670 } 1671 return false; 1672 } 1673 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1674 }; 1675 } // namespace 1676 1677 OMPThreadPrivateDecl * 1678 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1679 SmallVector<Expr *, 8> Vars; 1680 for (auto &RefExpr : VarList) { 1681 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 1682 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 1683 SourceLocation ILoc = DE->getExprLoc(); 1684 1685 // Mark variable as used. 1686 VD->setReferenced(); 1687 VD->markUsed(Context); 1688 1689 QualType QType = VD->getType(); 1690 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1691 // It will be analyzed later. 1692 Vars.push_back(DE); 1693 continue; 1694 } 1695 1696 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1697 // A threadprivate variable must not have an incomplete type. 1698 if (RequireCompleteType(ILoc, VD->getType(), 1699 diag::err_omp_threadprivate_incomplete_type)) { 1700 continue; 1701 } 1702 1703 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1704 // A threadprivate variable must not have a reference type. 1705 if (VD->getType()->isReferenceType()) { 1706 Diag(ILoc, diag::err_omp_ref_type_arg) 1707 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1708 bool IsDecl = 1709 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1710 Diag(VD->getLocation(), 1711 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1712 << VD; 1713 continue; 1714 } 1715 1716 // Check if this is a TLS variable. If TLS is not being supported, produce 1717 // the corresponding diagnostic. 1718 if ((VD->getTLSKind() != VarDecl::TLS_None && 1719 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1720 getLangOpts().OpenMPUseTLS && 1721 getASTContext().getTargetInfo().isTLSSupported())) || 1722 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1723 !VD->isLocalVarDecl())) { 1724 Diag(ILoc, diag::err_omp_var_thread_local) 1725 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1726 bool IsDecl = 1727 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1728 Diag(VD->getLocation(), 1729 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1730 << VD; 1731 continue; 1732 } 1733 1734 // Check if initial value of threadprivate variable reference variable with 1735 // local storage (it is not supported by runtime). 1736 if (auto Init = VD->getAnyInitializer()) { 1737 LocalVarRefChecker Checker(*this); 1738 if (Checker.Visit(Init)) 1739 continue; 1740 } 1741 1742 Vars.push_back(RefExpr); 1743 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1744 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1745 Context, SourceRange(Loc, Loc))); 1746 if (auto *ML = Context.getASTMutationListener()) 1747 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1748 } 1749 OMPThreadPrivateDecl *D = nullptr; 1750 if (!Vars.empty()) { 1751 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1752 Vars); 1753 D->setAccess(AS_public); 1754 } 1755 return D; 1756 } 1757 1758 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 1759 const ValueDecl *D, DSAStackTy::DSAVarData DVar, 1760 bool IsLoopIterVar = false) { 1761 if (DVar.RefExpr) { 1762 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1763 << getOpenMPClauseName(DVar.CKind); 1764 return; 1765 } 1766 enum { 1767 PDSA_StaticMemberShared, 1768 PDSA_StaticLocalVarShared, 1769 PDSA_LoopIterVarPrivate, 1770 PDSA_LoopIterVarLinear, 1771 PDSA_LoopIterVarLastprivate, 1772 PDSA_ConstVarShared, 1773 PDSA_GlobalVarShared, 1774 PDSA_TaskVarFirstprivate, 1775 PDSA_LocalVarPrivate, 1776 PDSA_Implicit 1777 } Reason = PDSA_Implicit; 1778 bool ReportHint = false; 1779 auto ReportLoc = D->getLocation(); 1780 auto *VD = dyn_cast<VarDecl>(D); 1781 if (IsLoopIterVar) { 1782 if (DVar.CKind == OMPC_private) 1783 Reason = PDSA_LoopIterVarPrivate; 1784 else if (DVar.CKind == OMPC_lastprivate) 1785 Reason = PDSA_LoopIterVarLastprivate; 1786 else 1787 Reason = PDSA_LoopIterVarLinear; 1788 } else if (isOpenMPTaskingDirective(DVar.DKind) && 1789 DVar.CKind == OMPC_firstprivate) { 1790 Reason = PDSA_TaskVarFirstprivate; 1791 ReportLoc = DVar.ImplicitDSALoc; 1792 } else if (VD && VD->isStaticLocal()) 1793 Reason = PDSA_StaticLocalVarShared; 1794 else if (VD && VD->isStaticDataMember()) 1795 Reason = PDSA_StaticMemberShared; 1796 else if (VD && VD->isFileVarDecl()) 1797 Reason = PDSA_GlobalVarShared; 1798 else if (D->getType().isConstant(SemaRef.getASTContext())) 1799 Reason = PDSA_ConstVarShared; 1800 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 1801 ReportHint = true; 1802 Reason = PDSA_LocalVarPrivate; 1803 } 1804 if (Reason != PDSA_Implicit) { 1805 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 1806 << Reason << ReportHint 1807 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 1808 } else if (DVar.ImplicitDSALoc.isValid()) { 1809 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 1810 << getOpenMPClauseName(DVar.CKind); 1811 } 1812 } 1813 1814 namespace { 1815 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 1816 DSAStackTy *Stack; 1817 Sema &SemaRef; 1818 bool ErrorFound; 1819 CapturedStmt *CS; 1820 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 1821 llvm::SmallVector<Expr *, 8> ImplicitMap; 1822 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 1823 llvm::DenseSet<ValueDecl *> ImplicitDeclarations; 1824 1825 public: 1826 void VisitDeclRefExpr(DeclRefExpr *E) { 1827 if (E->isTypeDependent() || E->isValueDependent() || 1828 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1829 return; 1830 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1831 VD = VD->getCanonicalDecl(); 1832 // Skip internally declared variables. 1833 if (VD->hasLocalStorage() && !CS->capturesVariable(VD)) 1834 return; 1835 1836 auto DVar = Stack->getTopDSA(VD, false); 1837 // Check if the variable has explicit DSA set and stop analysis if it so. 1838 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 1839 return; 1840 1841 // Skip internally declared static variables. 1842 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD)) 1843 return; 1844 1845 auto ELoc = E->getExprLoc(); 1846 auto DKind = Stack->getCurrentDirective(); 1847 // The default(none) clause requires that each variable that is referenced 1848 // in the construct, and does not have a predetermined data-sharing 1849 // attribute, must have its data-sharing attribute explicitly determined 1850 // by being listed in a data-sharing attribute clause. 1851 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 1852 isParallelOrTaskRegion(DKind) && 1853 VarsWithInheritedDSA.count(VD) == 0) { 1854 VarsWithInheritedDSA[VD] = E; 1855 return; 1856 } 1857 1858 if (isOpenMPTargetExecutionDirective(DKind) && 1859 !Stack->isLoopControlVariable(VD).first) { 1860 if (!Stack->checkMappableExprComponentListsForDecl( 1861 VD, /*CurrentRegionOnly=*/true, 1862 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 1863 StackComponents, 1864 OpenMPClauseKind) { 1865 // Variable is used if it has been marked as an array, array 1866 // section or the variable iself. 1867 return StackComponents.size() == 1 || 1868 std::all_of( 1869 std::next(StackComponents.rbegin()), 1870 StackComponents.rend(), 1871 [](const OMPClauseMappableExprCommon:: 1872 MappableComponent &MC) { 1873 return MC.getAssociatedDeclaration() == 1874 nullptr && 1875 (isa<OMPArraySectionExpr>( 1876 MC.getAssociatedExpression()) || 1877 isa<ArraySubscriptExpr>( 1878 MC.getAssociatedExpression())); 1879 }); 1880 })) { 1881 bool IsFirstprivate = false; 1882 // By default lambdas are captured as firstprivates. 1883 if (const auto *RD = 1884 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 1885 IsFirstprivate = RD->isLambda(); 1886 IsFirstprivate = 1887 IsFirstprivate || 1888 (VD->getType().getNonReferenceType()->isScalarType() && 1889 Stack->getDefaultDMA() != DMA_tofrom_scalar); 1890 if (IsFirstprivate) 1891 ImplicitFirstprivate.emplace_back(E); 1892 else 1893 ImplicitMap.emplace_back(E); 1894 return; 1895 } 1896 } 1897 1898 // OpenMP [2.9.3.6, Restrictions, p.2] 1899 // A list item that appears in a reduction clause of the innermost 1900 // enclosing worksharing or parallel construct may not be accessed in an 1901 // explicit task. 1902 DVar = Stack->hasInnermostDSA( 1903 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1904 [](OpenMPDirectiveKind K) -> bool { 1905 return isOpenMPParallelDirective(K) || 1906 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1907 }, 1908 /*FromParent=*/true); 1909 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1910 ErrorFound = true; 1911 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1912 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 1913 return; 1914 } 1915 1916 // Define implicit data-sharing attributes for task. 1917 DVar = Stack->getImplicitDSA(VD, false); 1918 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1919 !Stack->isLoopControlVariable(VD).first) 1920 ImplicitFirstprivate.push_back(E); 1921 } 1922 } 1923 void VisitMemberExpr(MemberExpr *E) { 1924 if (E->isTypeDependent() || E->isValueDependent() || 1925 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1926 return; 1927 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 1928 if (!FD) 1929 return; 1930 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 1931 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 1932 auto DVar = Stack->getTopDSA(FD, false); 1933 // Check if the variable has explicit DSA set and stop analysis if it 1934 // so. 1935 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 1936 return; 1937 1938 if (isOpenMPTargetExecutionDirective(DKind) && 1939 !Stack->isLoopControlVariable(FD).first && 1940 !Stack->checkMappableExprComponentListsForDecl( 1941 FD, /*CurrentRegionOnly=*/true, 1942 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 1943 StackComponents, 1944 OpenMPClauseKind) { 1945 return isa<CXXThisExpr>( 1946 cast<MemberExpr>( 1947 StackComponents.back().getAssociatedExpression()) 1948 ->getBase() 1949 ->IgnoreParens()); 1950 })) { 1951 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 1952 // A bit-field cannot appear in a map clause. 1953 // 1954 if (FD->isBitField()) { 1955 SemaRef.Diag(E->getMemberLoc(), 1956 diag::err_omp_bit_fields_forbidden_in_clause) 1957 << E->getSourceRange() << getOpenMPClauseName(OMPC_map); 1958 return; 1959 } 1960 ImplicitMap.emplace_back(E); 1961 return; 1962 } 1963 1964 auto ELoc = E->getExprLoc(); 1965 // OpenMP [2.9.3.6, Restrictions, p.2] 1966 // A list item that appears in a reduction clause of the innermost 1967 // enclosing worksharing or parallel construct may not be accessed in 1968 // an explicit task. 1969 DVar = Stack->hasInnermostDSA( 1970 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1971 [](OpenMPDirectiveKind K) -> bool { 1972 return isOpenMPParallelDirective(K) || 1973 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1974 }, 1975 /*FromParent=*/true); 1976 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1977 ErrorFound = true; 1978 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1979 ReportOriginalDSA(SemaRef, Stack, FD, DVar); 1980 return; 1981 } 1982 1983 // Define implicit data-sharing attributes for task. 1984 DVar = Stack->getImplicitDSA(FD, false); 1985 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1986 !Stack->isLoopControlVariable(FD).first) 1987 ImplicitFirstprivate.push_back(E); 1988 return; 1989 } 1990 if (isOpenMPTargetExecutionDirective(DKind) && !FD->isBitField()) { 1991 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 1992 CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map); 1993 auto *VD = cast<ValueDecl>( 1994 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 1995 if (!Stack->checkMappableExprComponentListsForDecl( 1996 VD, /*CurrentRegionOnly=*/true, 1997 [&CurComponents]( 1998 OMPClauseMappableExprCommon::MappableExprComponentListRef 1999 StackComponents, 2000 OpenMPClauseKind) { 2001 auto CCI = CurComponents.rbegin(); 2002 auto CCE = CurComponents.rend(); 2003 for (const auto &SC : llvm::reverse(StackComponents)) { 2004 // Do both expressions have the same kind? 2005 if (CCI->getAssociatedExpression()->getStmtClass() != 2006 SC.getAssociatedExpression()->getStmtClass()) 2007 if (!(isa<OMPArraySectionExpr>( 2008 SC.getAssociatedExpression()) && 2009 isa<ArraySubscriptExpr>( 2010 CCI->getAssociatedExpression()))) 2011 return false; 2012 2013 Decl *CCD = CCI->getAssociatedDeclaration(); 2014 Decl *SCD = SC.getAssociatedDeclaration(); 2015 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 2016 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 2017 if (SCD != CCD) 2018 return false; 2019 std::advance(CCI, 1); 2020 if (CCI == CCE) 2021 break; 2022 } 2023 return true; 2024 })) { 2025 Visit(E->getBase()); 2026 } 2027 } else 2028 Visit(E->getBase()); 2029 } 2030 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 2031 for (auto *C : S->clauses()) { 2032 // Skip analysis of arguments of implicitly defined firstprivate clause 2033 // for task|target directives. 2034 // Skip analysis of arguments of implicitly defined map clause for target 2035 // directives. 2036 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 2037 C->isImplicit())) { 2038 for (auto *CC : C->children()) { 2039 if (CC) 2040 Visit(CC); 2041 } 2042 } 2043 } 2044 } 2045 void VisitStmt(Stmt *S) { 2046 for (auto *C : S->children()) { 2047 if (C && !isa<OMPExecutableDirective>(C)) 2048 Visit(C); 2049 } 2050 } 2051 2052 bool isErrorFound() { return ErrorFound; } 2053 ArrayRef<Expr *> getImplicitFirstprivate() const { 2054 return ImplicitFirstprivate; 2055 } 2056 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; } 2057 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() { 2058 return VarsWithInheritedDSA; 2059 } 2060 2061 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 2062 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 2063 }; 2064 } // namespace 2065 2066 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 2067 switch (DKind) { 2068 case OMPD_parallel: 2069 case OMPD_parallel_for: 2070 case OMPD_parallel_for_simd: 2071 case OMPD_parallel_sections: 2072 case OMPD_teams: 2073 case OMPD_teams_distribute: { 2074 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2075 QualType KmpInt32PtrTy = 2076 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2077 Sema::CapturedParamNameType Params[] = { 2078 std::make_pair(".global_tid.", KmpInt32PtrTy), 2079 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2080 std::make_pair(StringRef(), QualType()) // __context with shared vars 2081 }; 2082 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2083 Params); 2084 break; 2085 } 2086 case OMPD_target_teams: 2087 case OMPD_target_parallel: { 2088 Sema::CapturedParamNameType ParamsTarget[] = { 2089 std::make_pair(StringRef(), QualType()) // __context with shared vars 2090 }; 2091 // Start a captured region for 'target' with no implicit parameters. 2092 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2093 ParamsTarget); 2094 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2095 QualType KmpInt32PtrTy = 2096 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2097 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 2098 std::make_pair(".global_tid.", KmpInt32PtrTy), 2099 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2100 std::make_pair(StringRef(), QualType()) // __context with shared vars 2101 }; 2102 // Start a captured region for 'teams' or 'parallel'. Both regions have 2103 // the same implicit parameters. 2104 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2105 ParamsTeamsOrParallel); 2106 break; 2107 } 2108 case OMPD_simd: 2109 case OMPD_for: 2110 case OMPD_for_simd: 2111 case OMPD_sections: 2112 case OMPD_section: 2113 case OMPD_single: 2114 case OMPD_master: 2115 case OMPD_critical: 2116 case OMPD_taskgroup: 2117 case OMPD_distribute: 2118 case OMPD_ordered: 2119 case OMPD_atomic: 2120 case OMPD_target_data: 2121 case OMPD_target: 2122 case OMPD_target_parallel_for: 2123 case OMPD_target_parallel_for_simd: 2124 case OMPD_target_simd: { 2125 Sema::CapturedParamNameType Params[] = { 2126 std::make_pair(StringRef(), QualType()) // __context with shared vars 2127 }; 2128 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2129 Params); 2130 break; 2131 } 2132 case OMPD_task: { 2133 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2134 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2135 FunctionProtoType::ExtProtoInfo EPI; 2136 EPI.Variadic = true; 2137 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2138 Sema::CapturedParamNameType Params[] = { 2139 std::make_pair(".global_tid.", KmpInt32Ty), 2140 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2141 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 2142 std::make_pair(".copy_fn.", 2143 Context.getPointerType(CopyFnType).withConst()), 2144 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2145 std::make_pair(StringRef(), QualType()) // __context with shared vars 2146 }; 2147 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2148 Params); 2149 // Mark this captured region as inlined, because we don't use outlined 2150 // function directly. 2151 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2152 AlwaysInlineAttr::CreateImplicit( 2153 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2154 break; 2155 } 2156 case OMPD_taskloop: 2157 case OMPD_taskloop_simd: { 2158 QualType KmpInt32Ty = 2159 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 2160 QualType KmpUInt64Ty = 2161 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 2162 QualType KmpInt64Ty = 2163 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 2164 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2165 FunctionProtoType::ExtProtoInfo EPI; 2166 EPI.Variadic = true; 2167 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2168 Sema::CapturedParamNameType Params[] = { 2169 std::make_pair(".global_tid.", KmpInt32Ty), 2170 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2171 std::make_pair(".privates.", 2172 Context.VoidPtrTy.withConst().withRestrict()), 2173 std::make_pair( 2174 ".copy_fn.", 2175 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2176 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2177 std::make_pair(".lb.", KmpUInt64Ty), 2178 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 2179 std::make_pair(".liter.", KmpInt32Ty), 2180 std::make_pair(".reductions.", 2181 Context.VoidPtrTy.withConst().withRestrict()), 2182 std::make_pair(StringRef(), QualType()) // __context with shared vars 2183 }; 2184 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2185 Params); 2186 // Mark this captured region as inlined, because we don't use outlined 2187 // function directly. 2188 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2189 AlwaysInlineAttr::CreateImplicit( 2190 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2191 break; 2192 } 2193 case OMPD_distribute_parallel_for_simd: 2194 case OMPD_distribute_simd: 2195 case OMPD_distribute_parallel_for: 2196 case OMPD_teams_distribute_simd: 2197 case OMPD_teams_distribute_parallel_for_simd: 2198 case OMPD_teams_distribute_parallel_for: 2199 case OMPD_target_teams_distribute: 2200 case OMPD_target_teams_distribute_parallel_for: 2201 case OMPD_target_teams_distribute_parallel_for_simd: 2202 case OMPD_target_teams_distribute_simd: { 2203 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2204 QualType KmpInt32PtrTy = 2205 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2206 Sema::CapturedParamNameType Params[] = { 2207 std::make_pair(".global_tid.", KmpInt32PtrTy), 2208 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2209 std::make_pair(".previous.lb.", Context.getSizeType()), 2210 std::make_pair(".previous.ub.", Context.getSizeType()), 2211 std::make_pair(StringRef(), QualType()) // __context with shared vars 2212 }; 2213 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2214 Params); 2215 break; 2216 } 2217 case OMPD_threadprivate: 2218 case OMPD_taskyield: 2219 case OMPD_barrier: 2220 case OMPD_taskwait: 2221 case OMPD_cancellation_point: 2222 case OMPD_cancel: 2223 case OMPD_flush: 2224 case OMPD_target_enter_data: 2225 case OMPD_target_exit_data: 2226 case OMPD_declare_reduction: 2227 case OMPD_declare_simd: 2228 case OMPD_declare_target: 2229 case OMPD_end_declare_target: 2230 case OMPD_target_update: 2231 llvm_unreachable("OpenMP Directive is not allowed"); 2232 case OMPD_unknown: 2233 llvm_unreachable("Unknown OpenMP directive"); 2234 } 2235 } 2236 2237 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 2238 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2239 getOpenMPCaptureRegions(CaptureRegions, DKind); 2240 return CaptureRegions.size(); 2241 } 2242 2243 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 2244 Expr *CaptureExpr, bool WithInit, 2245 bool AsExpression) { 2246 assert(CaptureExpr); 2247 ASTContext &C = S.getASTContext(); 2248 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 2249 QualType Ty = Init->getType(); 2250 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 2251 if (S.getLangOpts().CPlusPlus) 2252 Ty = C.getLValueReferenceType(Ty); 2253 else { 2254 Ty = C.getPointerType(Ty); 2255 ExprResult Res = 2256 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 2257 if (!Res.isUsable()) 2258 return nullptr; 2259 Init = Res.get(); 2260 } 2261 WithInit = true; 2262 } 2263 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 2264 CaptureExpr->getLocStart()); 2265 if (!WithInit) 2266 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 2267 S.CurContext->addHiddenDecl(CED); 2268 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 2269 return CED; 2270 } 2271 2272 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2273 bool WithInit) { 2274 OMPCapturedExprDecl *CD; 2275 if (auto *VD = S.IsOpenMPCapturedDecl(D)) 2276 CD = cast<OMPCapturedExprDecl>(VD); 2277 else 2278 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 2279 /*AsExpression=*/false); 2280 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2281 CaptureExpr->getExprLoc()); 2282 } 2283 2284 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 2285 if (!Ref) { 2286 auto *CD = 2287 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), 2288 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); 2289 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2290 CaptureExpr->getExprLoc()); 2291 } 2292 ExprResult Res = Ref; 2293 if (!S.getLangOpts().CPlusPlus && 2294 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 2295 Ref->getType()->isPointerType()) 2296 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 2297 if (!Res.isUsable()) 2298 return ExprError(); 2299 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); 2300 } 2301 2302 namespace { 2303 // OpenMP directives parsed in this section are represented as a 2304 // CapturedStatement with an associated statement. If a syntax error 2305 // is detected during the parsing of the associated statement, the 2306 // compiler must abort processing and close the CapturedStatement. 2307 // 2308 // Combined directives such as 'target parallel' have more than one 2309 // nested CapturedStatements. This RAII ensures that we unwind out 2310 // of all the nested CapturedStatements when an error is found. 2311 class CaptureRegionUnwinderRAII { 2312 private: 2313 Sema &S; 2314 bool &ErrorFound; 2315 OpenMPDirectiveKind DKind; 2316 2317 public: 2318 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 2319 OpenMPDirectiveKind DKind) 2320 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 2321 ~CaptureRegionUnwinderRAII() { 2322 if (ErrorFound) { 2323 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 2324 while (--ThisCaptureLevel >= 0) 2325 S.ActOnCapturedRegionError(); 2326 } 2327 } 2328 }; 2329 } // namespace 2330 2331 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 2332 ArrayRef<OMPClause *> Clauses) { 2333 bool ErrorFound = false; 2334 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 2335 *this, ErrorFound, DSAStack->getCurrentDirective()); 2336 if (!S.isUsable()) { 2337 ErrorFound = true; 2338 return StmtError(); 2339 } 2340 2341 OMPOrderedClause *OC = nullptr; 2342 OMPScheduleClause *SC = nullptr; 2343 SmallVector<OMPLinearClause *, 4> LCs; 2344 SmallVector<OMPClauseWithPreInit *, 8> PICs; 2345 // This is required for proper codegen. 2346 for (auto *Clause : Clauses) { 2347 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 2348 Clause->getClauseKind() == OMPC_in_reduction) { 2349 // Capture taskgroup task_reduction descriptors inside the tasking regions 2350 // with the corresponding in_reduction items. 2351 auto *IRC = cast<OMPInReductionClause>(Clause); 2352 for (auto *E : IRC->taskgroup_descriptors()) 2353 if (E) 2354 MarkDeclarationsReferencedInExpr(E); 2355 } 2356 if (isOpenMPPrivate(Clause->getClauseKind()) || 2357 Clause->getClauseKind() == OMPC_copyprivate || 2358 (getLangOpts().OpenMPUseTLS && 2359 getASTContext().getTargetInfo().isTLSSupported() && 2360 Clause->getClauseKind() == OMPC_copyin)) { 2361 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 2362 // Mark all variables in private list clauses as used in inner region. 2363 for (auto *VarRef : Clause->children()) { 2364 if (auto *E = cast_or_null<Expr>(VarRef)) { 2365 MarkDeclarationsReferencedInExpr(E); 2366 } 2367 } 2368 DSAStack->setForceVarCapturing(/*V=*/false); 2369 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 2370 if (auto *C = OMPClauseWithPreInit::get(Clause)) 2371 PICs.push_back(C); 2372 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 2373 if (auto *E = C->getPostUpdateExpr()) 2374 MarkDeclarationsReferencedInExpr(E); 2375 } 2376 } 2377 if (Clause->getClauseKind() == OMPC_schedule) 2378 SC = cast<OMPScheduleClause>(Clause); 2379 else if (Clause->getClauseKind() == OMPC_ordered) 2380 OC = cast<OMPOrderedClause>(Clause); 2381 else if (Clause->getClauseKind() == OMPC_linear) 2382 LCs.push_back(cast<OMPLinearClause>(Clause)); 2383 } 2384 // OpenMP, 2.7.1 Loop Construct, Restrictions 2385 // The nonmonotonic modifier cannot be specified if an ordered clause is 2386 // specified. 2387 if (SC && 2388 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 2389 SC->getSecondScheduleModifier() == 2390 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 2391 OC) { 2392 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 2393 ? SC->getFirstScheduleModifierLoc() 2394 : SC->getSecondScheduleModifierLoc(), 2395 diag::err_omp_schedule_nonmonotonic_ordered) 2396 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2397 ErrorFound = true; 2398 } 2399 if (!LCs.empty() && OC && OC->getNumForLoops()) { 2400 for (auto *C : LCs) { 2401 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 2402 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2403 } 2404 ErrorFound = true; 2405 } 2406 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 2407 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 2408 OC->getNumForLoops()) { 2409 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 2410 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 2411 ErrorFound = true; 2412 } 2413 if (ErrorFound) { 2414 return StmtError(); 2415 } 2416 StmtResult SR = S; 2417 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2418 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 2419 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 2420 // Mark all variables in private list clauses as used in inner region. 2421 // Required for proper codegen of combined directives. 2422 // TODO: add processing for other clauses. 2423 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 2424 for (auto *C : PICs) { 2425 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 2426 // Find the particular capture region for the clause if the 2427 // directive is a combined one with multiple capture regions. 2428 // If the directive is not a combined one, the capture region 2429 // associated with the clause is OMPD_unknown and is generated 2430 // only once. 2431 if (CaptureRegion == ThisCaptureRegion || 2432 CaptureRegion == OMPD_unknown) { 2433 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 2434 for (auto *D : DS->decls()) 2435 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 2436 } 2437 } 2438 } 2439 } 2440 SR = ActOnCapturedRegionEnd(SR.get()); 2441 } 2442 return SR; 2443 } 2444 2445 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 2446 OpenMPDirectiveKind CancelRegion, 2447 SourceLocation StartLoc) { 2448 // CancelRegion is only needed for cancel and cancellation_point. 2449 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 2450 return false; 2451 2452 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 2453 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 2454 return false; 2455 2456 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 2457 << getOpenMPDirectiveName(CancelRegion); 2458 return true; 2459 } 2460 2461 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 2462 OpenMPDirectiveKind CurrentRegion, 2463 const DeclarationNameInfo &CurrentName, 2464 OpenMPDirectiveKind CancelRegion, 2465 SourceLocation StartLoc) { 2466 if (Stack->getCurScope()) { 2467 auto ParentRegion = Stack->getParentDirective(); 2468 auto OffendingRegion = ParentRegion; 2469 bool NestingProhibited = false; 2470 bool CloseNesting = true; 2471 bool OrphanSeen = false; 2472 enum { 2473 NoRecommend, 2474 ShouldBeInParallelRegion, 2475 ShouldBeInOrderedRegion, 2476 ShouldBeInTargetRegion, 2477 ShouldBeInTeamsRegion 2478 } Recommend = NoRecommend; 2479 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 2480 // OpenMP [2.16, Nesting of Regions] 2481 // OpenMP constructs may not be nested inside a simd region. 2482 // OpenMP [2.8.1,simd Construct, Restrictions] 2483 // An ordered construct with the simd clause is the only OpenMP 2484 // construct that can appear in the simd region. 2485 // Allowing a SIMD construct nested in another SIMD construct is an 2486 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 2487 // message. 2488 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 2489 ? diag::err_omp_prohibited_region_simd 2490 : diag::warn_omp_nesting_simd); 2491 return CurrentRegion != OMPD_simd; 2492 } 2493 if (ParentRegion == OMPD_atomic) { 2494 // OpenMP [2.16, Nesting of Regions] 2495 // OpenMP constructs may not be nested inside an atomic region. 2496 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 2497 return true; 2498 } 2499 if (CurrentRegion == OMPD_section) { 2500 // OpenMP [2.7.2, sections Construct, Restrictions] 2501 // Orphaned section directives are prohibited. That is, the section 2502 // directives must appear within the sections construct and must not be 2503 // encountered elsewhere in the sections region. 2504 if (ParentRegion != OMPD_sections && 2505 ParentRegion != OMPD_parallel_sections) { 2506 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 2507 << (ParentRegion != OMPD_unknown) 2508 << getOpenMPDirectiveName(ParentRegion); 2509 return true; 2510 } 2511 return false; 2512 } 2513 // Allow some constructs (except teams) to be orphaned (they could be 2514 // used in functions, called from OpenMP regions with the required 2515 // preconditions). 2516 if (ParentRegion == OMPD_unknown && 2517 !isOpenMPNestingTeamsDirective(CurrentRegion)) 2518 return false; 2519 if (CurrentRegion == OMPD_cancellation_point || 2520 CurrentRegion == OMPD_cancel) { 2521 // OpenMP [2.16, Nesting of Regions] 2522 // A cancellation point construct for which construct-type-clause is 2523 // taskgroup must be nested inside a task construct. A cancellation 2524 // point construct for which construct-type-clause is not taskgroup must 2525 // be closely nested inside an OpenMP construct that matches the type 2526 // specified in construct-type-clause. 2527 // A cancel construct for which construct-type-clause is taskgroup must be 2528 // nested inside a task construct. A cancel construct for which 2529 // construct-type-clause is not taskgroup must be closely nested inside an 2530 // OpenMP construct that matches the type specified in 2531 // construct-type-clause. 2532 NestingProhibited = 2533 !((CancelRegion == OMPD_parallel && 2534 (ParentRegion == OMPD_parallel || 2535 ParentRegion == OMPD_target_parallel)) || 2536 (CancelRegion == OMPD_for && 2537 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 2538 ParentRegion == OMPD_target_parallel_for)) || 2539 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 2540 (CancelRegion == OMPD_sections && 2541 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 2542 ParentRegion == OMPD_parallel_sections))); 2543 } else if (CurrentRegion == OMPD_master) { 2544 // OpenMP [2.16, Nesting of Regions] 2545 // A master region may not be closely nested inside a worksharing, 2546 // atomic, or explicit task region. 2547 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2548 isOpenMPTaskingDirective(ParentRegion); 2549 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 2550 // OpenMP [2.16, Nesting of Regions] 2551 // A critical region may not be nested (closely or otherwise) inside a 2552 // critical region with the same name. Note that this restriction is not 2553 // sufficient to prevent deadlock. 2554 SourceLocation PreviousCriticalLoc; 2555 bool DeadLock = Stack->hasDirective( 2556 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 2557 const DeclarationNameInfo &DNI, 2558 SourceLocation Loc) -> bool { 2559 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 2560 PreviousCriticalLoc = Loc; 2561 return true; 2562 } else 2563 return false; 2564 }, 2565 false /* skip top directive */); 2566 if (DeadLock) { 2567 SemaRef.Diag(StartLoc, 2568 diag::err_omp_prohibited_region_critical_same_name) 2569 << CurrentName.getName(); 2570 if (PreviousCriticalLoc.isValid()) 2571 SemaRef.Diag(PreviousCriticalLoc, 2572 diag::note_omp_previous_critical_region); 2573 return true; 2574 } 2575 } else if (CurrentRegion == OMPD_barrier) { 2576 // OpenMP [2.16, Nesting of Regions] 2577 // A barrier region may not be closely nested inside a worksharing, 2578 // explicit task, critical, ordered, atomic, or master region. 2579 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2580 isOpenMPTaskingDirective(ParentRegion) || 2581 ParentRegion == OMPD_master || 2582 ParentRegion == OMPD_critical || 2583 ParentRegion == OMPD_ordered; 2584 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2585 !isOpenMPParallelDirective(CurrentRegion) && 2586 !isOpenMPTeamsDirective(CurrentRegion)) { 2587 // OpenMP [2.16, Nesting of Regions] 2588 // A worksharing region may not be closely nested inside a worksharing, 2589 // explicit task, critical, ordered, atomic, or master region. 2590 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2591 isOpenMPTaskingDirective(ParentRegion) || 2592 ParentRegion == OMPD_master || 2593 ParentRegion == OMPD_critical || 2594 ParentRegion == OMPD_ordered; 2595 Recommend = ShouldBeInParallelRegion; 2596 } else if (CurrentRegion == OMPD_ordered) { 2597 // OpenMP [2.16, Nesting of Regions] 2598 // An ordered region may not be closely nested inside a critical, 2599 // atomic, or explicit task region. 2600 // An ordered region must be closely nested inside a loop region (or 2601 // parallel loop region) with an ordered clause. 2602 // OpenMP [2.8.1,simd Construct, Restrictions] 2603 // An ordered construct with the simd clause is the only OpenMP construct 2604 // that can appear in the simd region. 2605 NestingProhibited = ParentRegion == OMPD_critical || 2606 isOpenMPTaskingDirective(ParentRegion) || 2607 !(isOpenMPSimdDirective(ParentRegion) || 2608 Stack->isParentOrderedRegion()); 2609 Recommend = ShouldBeInOrderedRegion; 2610 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 2611 // OpenMP [2.16, Nesting of Regions] 2612 // If specified, a teams construct must be contained within a target 2613 // construct. 2614 NestingProhibited = ParentRegion != OMPD_target; 2615 OrphanSeen = ParentRegion == OMPD_unknown; 2616 Recommend = ShouldBeInTargetRegion; 2617 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 2618 } 2619 if (!NestingProhibited && 2620 !isOpenMPTargetExecutionDirective(CurrentRegion) && 2621 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 2622 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 2623 // OpenMP [2.16, Nesting of Regions] 2624 // distribute, parallel, parallel sections, parallel workshare, and the 2625 // parallel loop and parallel loop SIMD constructs are the only OpenMP 2626 // constructs that can be closely nested in the teams region. 2627 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 2628 !isOpenMPDistributeDirective(CurrentRegion); 2629 Recommend = ShouldBeInParallelRegion; 2630 } 2631 if (!NestingProhibited && 2632 isOpenMPNestingDistributeDirective(CurrentRegion)) { 2633 // OpenMP 4.5 [2.17 Nesting of Regions] 2634 // The region associated with the distribute construct must be strictly 2635 // nested inside a teams region 2636 NestingProhibited = 2637 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 2638 Recommend = ShouldBeInTeamsRegion; 2639 } 2640 if (!NestingProhibited && 2641 (isOpenMPTargetExecutionDirective(CurrentRegion) || 2642 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 2643 // OpenMP 4.5 [2.17 Nesting of Regions] 2644 // If a target, target update, target data, target enter data, or 2645 // target exit data construct is encountered during execution of a 2646 // target region, the behavior is unspecified. 2647 NestingProhibited = Stack->hasDirective( 2648 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2649 SourceLocation) -> bool { 2650 if (isOpenMPTargetExecutionDirective(K)) { 2651 OffendingRegion = K; 2652 return true; 2653 } else 2654 return false; 2655 }, 2656 false /* don't skip top directive */); 2657 CloseNesting = false; 2658 } 2659 if (NestingProhibited) { 2660 if (OrphanSeen) { 2661 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 2662 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 2663 } else { 2664 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 2665 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 2666 << Recommend << getOpenMPDirectiveName(CurrentRegion); 2667 } 2668 return true; 2669 } 2670 } 2671 return false; 2672 } 2673 2674 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 2675 ArrayRef<OMPClause *> Clauses, 2676 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 2677 bool ErrorFound = false; 2678 unsigned NamedModifiersNumber = 0; 2679 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 2680 OMPD_unknown + 1); 2681 SmallVector<SourceLocation, 4> NameModifierLoc; 2682 for (const auto *C : Clauses) { 2683 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 2684 // At most one if clause without a directive-name-modifier can appear on 2685 // the directive. 2686 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 2687 if (FoundNameModifiers[CurNM]) { 2688 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 2689 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 2690 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 2691 ErrorFound = true; 2692 } else if (CurNM != OMPD_unknown) { 2693 NameModifierLoc.push_back(IC->getNameModifierLoc()); 2694 ++NamedModifiersNumber; 2695 } 2696 FoundNameModifiers[CurNM] = IC; 2697 if (CurNM == OMPD_unknown) 2698 continue; 2699 // Check if the specified name modifier is allowed for the current 2700 // directive. 2701 // At most one if clause with the particular directive-name-modifier can 2702 // appear on the directive. 2703 bool MatchFound = false; 2704 for (auto NM : AllowedNameModifiers) { 2705 if (CurNM == NM) { 2706 MatchFound = true; 2707 break; 2708 } 2709 } 2710 if (!MatchFound) { 2711 S.Diag(IC->getNameModifierLoc(), 2712 diag::err_omp_wrong_if_directive_name_modifier) 2713 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 2714 ErrorFound = true; 2715 } 2716 } 2717 } 2718 // If any if clause on the directive includes a directive-name-modifier then 2719 // all if clauses on the directive must include a directive-name-modifier. 2720 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 2721 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 2722 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 2723 diag::err_omp_no_more_if_clause); 2724 } else { 2725 std::string Values; 2726 std::string Sep(", "); 2727 unsigned AllowedCnt = 0; 2728 unsigned TotalAllowedNum = 2729 AllowedNameModifiers.size() - NamedModifiersNumber; 2730 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 2731 ++Cnt) { 2732 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 2733 if (!FoundNameModifiers[NM]) { 2734 Values += "'"; 2735 Values += getOpenMPDirectiveName(NM); 2736 Values += "'"; 2737 if (AllowedCnt + 2 == TotalAllowedNum) 2738 Values += " or "; 2739 else if (AllowedCnt + 1 != TotalAllowedNum) 2740 Values += Sep; 2741 ++AllowedCnt; 2742 } 2743 } 2744 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 2745 diag::err_omp_unnamed_if_clause) 2746 << (TotalAllowedNum > 1) << Values; 2747 } 2748 for (auto Loc : NameModifierLoc) { 2749 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 2750 } 2751 ErrorFound = true; 2752 } 2753 return ErrorFound; 2754 } 2755 2756 StmtResult Sema::ActOnOpenMPExecutableDirective( 2757 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 2758 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 2759 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 2760 StmtResult Res = StmtError(); 2761 // First check CancelRegion which is then used in checkNestingOfRegions. 2762 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 2763 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 2764 StartLoc)) 2765 return StmtError(); 2766 2767 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 2768 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 2769 bool ErrorFound = false; 2770 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 2771 if (AStmt && !CurContext->isDependentContext()) { 2772 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2773 2774 // Check default data sharing attributes for referenced variables. 2775 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 2776 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 2777 Stmt *S = AStmt; 2778 while (--ThisCaptureLevel >= 0) 2779 S = cast<CapturedStmt>(S)->getCapturedStmt(); 2780 DSAChecker.Visit(S); 2781 if (DSAChecker.isErrorFound()) 2782 return StmtError(); 2783 // Generate list of implicitly defined firstprivate variables. 2784 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 2785 2786 SmallVector<Expr *, 4> ImplicitFirstprivates( 2787 DSAChecker.getImplicitFirstprivate().begin(), 2788 DSAChecker.getImplicitFirstprivate().end()); 2789 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(), 2790 DSAChecker.getImplicitMap().end()); 2791 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 2792 for (auto *C : Clauses) { 2793 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 2794 for (auto *E : IRC->taskgroup_descriptors()) 2795 if (E) 2796 ImplicitFirstprivates.emplace_back(E); 2797 } 2798 } 2799 if (!ImplicitFirstprivates.empty()) { 2800 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 2801 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 2802 SourceLocation())) { 2803 ClausesWithImplicit.push_back(Implicit); 2804 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 2805 ImplicitFirstprivates.size(); 2806 } else 2807 ErrorFound = true; 2808 } 2809 if (!ImplicitMaps.empty()) { 2810 if (OMPClause *Implicit = ActOnOpenMPMapClause( 2811 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, 2812 SourceLocation(), SourceLocation(), ImplicitMaps, 2813 SourceLocation(), SourceLocation(), SourceLocation())) { 2814 ClausesWithImplicit.emplace_back(Implicit); 2815 ErrorFound |= 2816 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size(); 2817 } else 2818 ErrorFound = true; 2819 } 2820 } 2821 2822 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 2823 switch (Kind) { 2824 case OMPD_parallel: 2825 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 2826 EndLoc); 2827 AllowedNameModifiers.push_back(OMPD_parallel); 2828 break; 2829 case OMPD_simd: 2830 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2831 VarsWithInheritedDSA); 2832 break; 2833 case OMPD_for: 2834 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2835 VarsWithInheritedDSA); 2836 break; 2837 case OMPD_for_simd: 2838 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2839 EndLoc, VarsWithInheritedDSA); 2840 break; 2841 case OMPD_sections: 2842 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 2843 EndLoc); 2844 break; 2845 case OMPD_section: 2846 assert(ClausesWithImplicit.empty() && 2847 "No clauses are allowed for 'omp section' directive"); 2848 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 2849 break; 2850 case OMPD_single: 2851 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 2852 EndLoc); 2853 break; 2854 case OMPD_master: 2855 assert(ClausesWithImplicit.empty() && 2856 "No clauses are allowed for 'omp master' directive"); 2857 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 2858 break; 2859 case OMPD_critical: 2860 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 2861 StartLoc, EndLoc); 2862 break; 2863 case OMPD_parallel_for: 2864 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 2865 EndLoc, VarsWithInheritedDSA); 2866 AllowedNameModifiers.push_back(OMPD_parallel); 2867 break; 2868 case OMPD_parallel_for_simd: 2869 Res = ActOnOpenMPParallelForSimdDirective( 2870 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2871 AllowedNameModifiers.push_back(OMPD_parallel); 2872 break; 2873 case OMPD_parallel_sections: 2874 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 2875 StartLoc, EndLoc); 2876 AllowedNameModifiers.push_back(OMPD_parallel); 2877 break; 2878 case OMPD_task: 2879 Res = 2880 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2881 AllowedNameModifiers.push_back(OMPD_task); 2882 break; 2883 case OMPD_taskyield: 2884 assert(ClausesWithImplicit.empty() && 2885 "No clauses are allowed for 'omp taskyield' directive"); 2886 assert(AStmt == nullptr && 2887 "No associated statement allowed for 'omp taskyield' directive"); 2888 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 2889 break; 2890 case OMPD_barrier: 2891 assert(ClausesWithImplicit.empty() && 2892 "No clauses are allowed for 'omp barrier' directive"); 2893 assert(AStmt == nullptr && 2894 "No associated statement allowed for 'omp barrier' directive"); 2895 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 2896 break; 2897 case OMPD_taskwait: 2898 assert(ClausesWithImplicit.empty() && 2899 "No clauses are allowed for 'omp taskwait' directive"); 2900 assert(AStmt == nullptr && 2901 "No associated statement allowed for 'omp taskwait' directive"); 2902 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 2903 break; 2904 case OMPD_taskgroup: 2905 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 2906 EndLoc); 2907 break; 2908 case OMPD_flush: 2909 assert(AStmt == nullptr && 2910 "No associated statement allowed for 'omp flush' directive"); 2911 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 2912 break; 2913 case OMPD_ordered: 2914 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 2915 EndLoc); 2916 break; 2917 case OMPD_atomic: 2918 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 2919 EndLoc); 2920 break; 2921 case OMPD_teams: 2922 Res = 2923 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2924 break; 2925 case OMPD_target: 2926 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 2927 EndLoc); 2928 AllowedNameModifiers.push_back(OMPD_target); 2929 break; 2930 case OMPD_target_parallel: 2931 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 2932 StartLoc, EndLoc); 2933 AllowedNameModifiers.push_back(OMPD_target); 2934 AllowedNameModifiers.push_back(OMPD_parallel); 2935 break; 2936 case OMPD_target_parallel_for: 2937 Res = ActOnOpenMPTargetParallelForDirective( 2938 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2939 AllowedNameModifiers.push_back(OMPD_target); 2940 AllowedNameModifiers.push_back(OMPD_parallel); 2941 break; 2942 case OMPD_cancellation_point: 2943 assert(ClausesWithImplicit.empty() && 2944 "No clauses are allowed for 'omp cancellation point' directive"); 2945 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 2946 "cancellation point' directive"); 2947 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 2948 break; 2949 case OMPD_cancel: 2950 assert(AStmt == nullptr && 2951 "No associated statement allowed for 'omp cancel' directive"); 2952 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 2953 CancelRegion); 2954 AllowedNameModifiers.push_back(OMPD_cancel); 2955 break; 2956 case OMPD_target_data: 2957 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 2958 EndLoc); 2959 AllowedNameModifiers.push_back(OMPD_target_data); 2960 break; 2961 case OMPD_target_enter_data: 2962 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 2963 EndLoc); 2964 AllowedNameModifiers.push_back(OMPD_target_enter_data); 2965 break; 2966 case OMPD_target_exit_data: 2967 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 2968 EndLoc); 2969 AllowedNameModifiers.push_back(OMPD_target_exit_data); 2970 break; 2971 case OMPD_taskloop: 2972 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 2973 EndLoc, VarsWithInheritedDSA); 2974 AllowedNameModifiers.push_back(OMPD_taskloop); 2975 break; 2976 case OMPD_taskloop_simd: 2977 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2978 EndLoc, VarsWithInheritedDSA); 2979 AllowedNameModifiers.push_back(OMPD_taskloop); 2980 break; 2981 case OMPD_distribute: 2982 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 2983 EndLoc, VarsWithInheritedDSA); 2984 break; 2985 case OMPD_target_update: 2986 assert(!AStmt && "Statement is not allowed for target update"); 2987 Res = 2988 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); 2989 AllowedNameModifiers.push_back(OMPD_target_update); 2990 break; 2991 case OMPD_distribute_parallel_for: 2992 Res = ActOnOpenMPDistributeParallelForDirective( 2993 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2994 AllowedNameModifiers.push_back(OMPD_parallel); 2995 break; 2996 case OMPD_distribute_parallel_for_simd: 2997 Res = ActOnOpenMPDistributeParallelForSimdDirective( 2998 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2999 AllowedNameModifiers.push_back(OMPD_parallel); 3000 break; 3001 case OMPD_distribute_simd: 3002 Res = ActOnOpenMPDistributeSimdDirective( 3003 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3004 break; 3005 case OMPD_target_parallel_for_simd: 3006 Res = ActOnOpenMPTargetParallelForSimdDirective( 3007 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3008 AllowedNameModifiers.push_back(OMPD_target); 3009 AllowedNameModifiers.push_back(OMPD_parallel); 3010 break; 3011 case OMPD_target_simd: 3012 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3013 EndLoc, VarsWithInheritedDSA); 3014 AllowedNameModifiers.push_back(OMPD_target); 3015 break; 3016 case OMPD_teams_distribute: 3017 Res = ActOnOpenMPTeamsDistributeDirective( 3018 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3019 break; 3020 case OMPD_teams_distribute_simd: 3021 Res = ActOnOpenMPTeamsDistributeSimdDirective( 3022 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3023 break; 3024 case OMPD_teams_distribute_parallel_for_simd: 3025 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 3026 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3027 AllowedNameModifiers.push_back(OMPD_parallel); 3028 break; 3029 case OMPD_teams_distribute_parallel_for: 3030 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 3031 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3032 AllowedNameModifiers.push_back(OMPD_parallel); 3033 break; 3034 case OMPD_target_teams: 3035 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 3036 EndLoc); 3037 AllowedNameModifiers.push_back(OMPD_target); 3038 break; 3039 case OMPD_target_teams_distribute: 3040 Res = ActOnOpenMPTargetTeamsDistributeDirective( 3041 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3042 AllowedNameModifiers.push_back(OMPD_target); 3043 break; 3044 case OMPD_target_teams_distribute_parallel_for: 3045 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 3046 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3047 AllowedNameModifiers.push_back(OMPD_target); 3048 AllowedNameModifiers.push_back(OMPD_parallel); 3049 break; 3050 case OMPD_target_teams_distribute_parallel_for_simd: 3051 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 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_simd: 3057 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 3058 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3059 AllowedNameModifiers.push_back(OMPD_target); 3060 break; 3061 case OMPD_declare_target: 3062 case OMPD_end_declare_target: 3063 case OMPD_threadprivate: 3064 case OMPD_declare_reduction: 3065 case OMPD_declare_simd: 3066 llvm_unreachable("OpenMP Directive is not allowed"); 3067 case OMPD_unknown: 3068 llvm_unreachable("Unknown OpenMP directive"); 3069 } 3070 3071 for (auto P : VarsWithInheritedDSA) { 3072 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 3073 << P.first << P.second->getSourceRange(); 3074 } 3075 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 3076 3077 if (!AllowedNameModifiers.empty()) 3078 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 3079 ErrorFound; 3080 3081 if (ErrorFound) 3082 return StmtError(); 3083 return Res; 3084 } 3085 3086 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 3087 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 3088 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 3089 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 3090 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 3091 assert(Aligneds.size() == Alignments.size()); 3092 assert(Linears.size() == LinModifiers.size()); 3093 assert(Linears.size() == Steps.size()); 3094 if (!DG || DG.get().isNull()) 3095 return DeclGroupPtrTy(); 3096 3097 if (!DG.get().isSingleDecl()) { 3098 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 3099 return DG; 3100 } 3101 auto *ADecl = DG.get().getSingleDecl(); 3102 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 3103 ADecl = FTD->getTemplatedDecl(); 3104 3105 auto *FD = dyn_cast<FunctionDecl>(ADecl); 3106 if (!FD) { 3107 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 3108 return DeclGroupPtrTy(); 3109 } 3110 3111 // OpenMP [2.8.2, declare simd construct, Description] 3112 // The parameter of the simdlen clause must be a constant positive integer 3113 // expression. 3114 ExprResult SL; 3115 if (Simdlen) 3116 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 3117 // OpenMP [2.8.2, declare simd construct, Description] 3118 // The special this pointer can be used as if was one of the arguments to the 3119 // function in any of the linear, aligned, or uniform clauses. 3120 // The uniform clause declares one or more arguments to have an invariant 3121 // value for all concurrent invocations of the function in the execution of a 3122 // single SIMD loop. 3123 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 3124 Expr *UniformedLinearThis = nullptr; 3125 for (auto *E : Uniforms) { 3126 E = E->IgnoreParenImpCasts(); 3127 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3128 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 3129 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3130 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3131 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 3132 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 3133 continue; 3134 } 3135 if (isa<CXXThisExpr>(E)) { 3136 UniformedLinearThis = E; 3137 continue; 3138 } 3139 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3140 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3141 } 3142 // OpenMP [2.8.2, declare simd construct, Description] 3143 // The aligned clause declares that the object to which each list item points 3144 // is aligned to the number of bytes expressed in the optional parameter of 3145 // the aligned clause. 3146 // The special this pointer can be used as if was one of the arguments to the 3147 // function in any of the linear, aligned, or uniform clauses. 3148 // The type of list items appearing in the aligned clause must be array, 3149 // pointer, reference to array, or reference to pointer. 3150 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 3151 Expr *AlignedThis = nullptr; 3152 for (auto *E : Aligneds) { 3153 E = E->IgnoreParenImpCasts(); 3154 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3155 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3156 auto *CanonPVD = PVD->getCanonicalDecl(); 3157 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3158 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3159 ->getCanonicalDecl() == CanonPVD) { 3160 // OpenMP [2.8.1, simd construct, Restrictions] 3161 // A list-item cannot appear in more than one aligned clause. 3162 if (AlignedArgs.count(CanonPVD) > 0) { 3163 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3164 << 1 << E->getSourceRange(); 3165 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 3166 diag::note_omp_explicit_dsa) 3167 << getOpenMPClauseName(OMPC_aligned); 3168 continue; 3169 } 3170 AlignedArgs[CanonPVD] = E; 3171 QualType QTy = PVD->getType() 3172 .getNonReferenceType() 3173 .getUnqualifiedType() 3174 .getCanonicalType(); 3175 const Type *Ty = QTy.getTypePtrOrNull(); 3176 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 3177 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 3178 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 3179 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 3180 } 3181 continue; 3182 } 3183 } 3184 if (isa<CXXThisExpr>(E)) { 3185 if (AlignedThis) { 3186 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3187 << 2 << E->getSourceRange(); 3188 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 3189 << getOpenMPClauseName(OMPC_aligned); 3190 } 3191 AlignedThis = E; 3192 continue; 3193 } 3194 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3195 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3196 } 3197 // The optional parameter of the aligned clause, alignment, must be a constant 3198 // positive integer expression. If no optional parameter is specified, 3199 // implementation-defined default alignments for SIMD instructions on the 3200 // target platforms are assumed. 3201 SmallVector<Expr *, 4> NewAligns; 3202 for (auto *E : Alignments) { 3203 ExprResult Align; 3204 if (E) 3205 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 3206 NewAligns.push_back(Align.get()); 3207 } 3208 // OpenMP [2.8.2, declare simd construct, Description] 3209 // The linear clause declares one or more list items to be private to a SIMD 3210 // lane and to have a linear relationship with respect to the iteration space 3211 // of a loop. 3212 // The special this pointer can be used as if was one of the arguments to the 3213 // function in any of the linear, aligned, or uniform clauses. 3214 // When a linear-step expression is specified in a linear clause it must be 3215 // either a constant integer expression or an integer-typed parameter that is 3216 // specified in a uniform clause on the directive. 3217 llvm::DenseMap<Decl *, Expr *> LinearArgs; 3218 const bool IsUniformedThis = UniformedLinearThis != nullptr; 3219 auto MI = LinModifiers.begin(); 3220 for (auto *E : Linears) { 3221 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 3222 ++MI; 3223 E = E->IgnoreParenImpCasts(); 3224 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3225 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3226 auto *CanonPVD = PVD->getCanonicalDecl(); 3227 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3228 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3229 ->getCanonicalDecl() == CanonPVD) { 3230 // OpenMP [2.15.3.7, linear Clause, Restrictions] 3231 // A list-item cannot appear in more than one linear clause. 3232 if (LinearArgs.count(CanonPVD) > 0) { 3233 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3234 << getOpenMPClauseName(OMPC_linear) 3235 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 3236 Diag(LinearArgs[CanonPVD]->getExprLoc(), 3237 diag::note_omp_explicit_dsa) 3238 << getOpenMPClauseName(OMPC_linear); 3239 continue; 3240 } 3241 // Each argument can appear in at most one uniform or linear clause. 3242 if (UniformedArgs.count(CanonPVD) > 0) { 3243 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3244 << getOpenMPClauseName(OMPC_linear) 3245 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 3246 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 3247 diag::note_omp_explicit_dsa) 3248 << getOpenMPClauseName(OMPC_uniform); 3249 continue; 3250 } 3251 LinearArgs[CanonPVD] = E; 3252 if (E->isValueDependent() || E->isTypeDependent() || 3253 E->isInstantiationDependent() || 3254 E->containsUnexpandedParameterPack()) 3255 continue; 3256 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 3257 PVD->getOriginalType()); 3258 continue; 3259 } 3260 } 3261 if (isa<CXXThisExpr>(E)) { 3262 if (UniformedLinearThis) { 3263 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3264 << getOpenMPClauseName(OMPC_linear) 3265 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 3266 << E->getSourceRange(); 3267 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 3268 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 3269 : OMPC_linear); 3270 continue; 3271 } 3272 UniformedLinearThis = E; 3273 if (E->isValueDependent() || E->isTypeDependent() || 3274 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3275 continue; 3276 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 3277 E->getType()); 3278 continue; 3279 } 3280 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3281 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3282 } 3283 Expr *Step = nullptr; 3284 Expr *NewStep = nullptr; 3285 SmallVector<Expr *, 4> NewSteps; 3286 for (auto *E : Steps) { 3287 // Skip the same step expression, it was checked already. 3288 if (Step == E || !E) { 3289 NewSteps.push_back(E ? NewStep : nullptr); 3290 continue; 3291 } 3292 Step = E; 3293 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 3294 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3295 auto *CanonPVD = PVD->getCanonicalDecl(); 3296 if (UniformedArgs.count(CanonPVD) == 0) { 3297 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 3298 << Step->getSourceRange(); 3299 } else if (E->isValueDependent() || E->isTypeDependent() || 3300 E->isInstantiationDependent() || 3301 E->containsUnexpandedParameterPack() || 3302 CanonPVD->getType()->hasIntegerRepresentation()) 3303 NewSteps.push_back(Step); 3304 else { 3305 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 3306 << Step->getSourceRange(); 3307 } 3308 continue; 3309 } 3310 NewStep = Step; 3311 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 3312 !Step->isInstantiationDependent() && 3313 !Step->containsUnexpandedParameterPack()) { 3314 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 3315 .get(); 3316 if (NewStep) 3317 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 3318 } 3319 NewSteps.push_back(NewStep); 3320 } 3321 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 3322 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 3323 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 3324 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 3325 const_cast<Expr **>(Linears.data()), Linears.size(), 3326 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 3327 NewSteps.data(), NewSteps.size(), SR); 3328 ADecl->addAttr(NewAttr); 3329 return ConvertDeclToDeclGroup(ADecl); 3330 } 3331 3332 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 3333 Stmt *AStmt, 3334 SourceLocation StartLoc, 3335 SourceLocation EndLoc) { 3336 if (!AStmt) 3337 return StmtError(); 3338 3339 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3340 // 1.2.2 OpenMP Language Terminology 3341 // Structured block - An executable statement with a single entry at the 3342 // top and a single exit at the bottom. 3343 // The point of exit cannot be a branch out of the structured block. 3344 // longjmp() and throw() must not violate the entry/exit criteria. 3345 CS->getCapturedDecl()->setNothrow(); 3346 3347 getCurFunction()->setHasBranchProtectedScope(); 3348 3349 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 3350 DSAStack->isCancelRegion()); 3351 } 3352 3353 namespace { 3354 /// \brief Helper class for checking canonical form of the OpenMP loops and 3355 /// extracting iteration space of each loop in the loop nest, that will be used 3356 /// for IR generation. 3357 class OpenMPIterationSpaceChecker { 3358 /// \brief Reference to Sema. 3359 Sema &SemaRef; 3360 /// \brief A location for diagnostics (when there is no some better location). 3361 SourceLocation DefaultLoc; 3362 /// \brief A location for diagnostics (when increment is not compatible). 3363 SourceLocation ConditionLoc; 3364 /// \brief A source location for referring to loop init later. 3365 SourceRange InitSrcRange; 3366 /// \brief A source location for referring to condition later. 3367 SourceRange ConditionSrcRange; 3368 /// \brief A source location for referring to increment later. 3369 SourceRange IncrementSrcRange; 3370 /// \brief Loop variable. 3371 ValueDecl *LCDecl = nullptr; 3372 /// \brief Reference to loop variable. 3373 Expr *LCRef = nullptr; 3374 /// \brief Lower bound (initializer for the var). 3375 Expr *LB = nullptr; 3376 /// \brief Upper bound. 3377 Expr *UB = nullptr; 3378 /// \brief Loop step (increment). 3379 Expr *Step = nullptr; 3380 /// \brief This flag is true when condition is one of: 3381 /// Var < UB 3382 /// Var <= UB 3383 /// UB > Var 3384 /// UB >= Var 3385 bool TestIsLessOp = false; 3386 /// \brief This flag is true when condition is strict ( < or > ). 3387 bool TestIsStrictOp = false; 3388 /// \brief This flag is true when step is subtracted on each iteration. 3389 bool SubtractStep = false; 3390 3391 public: 3392 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 3393 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 3394 /// \brief Check init-expr for canonical loop form and save loop counter 3395 /// variable - #Var and its initialization value - #LB. 3396 bool CheckInit(Stmt *S, bool EmitDiags = true); 3397 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 3398 /// for less/greater and for strict/non-strict comparison. 3399 bool CheckCond(Expr *S); 3400 /// \brief Check incr-expr for canonical loop form and return true if it 3401 /// does not conform, otherwise save loop step (#Step). 3402 bool CheckInc(Expr *S); 3403 /// \brief Return the loop counter variable. 3404 ValueDecl *GetLoopDecl() const { return LCDecl; } 3405 /// \brief Return the reference expression to loop counter variable. 3406 Expr *GetLoopDeclRefExpr() const { return LCRef; } 3407 /// \brief Source range of the loop init. 3408 SourceRange GetInitSrcRange() const { return InitSrcRange; } 3409 /// \brief Source range of the loop condition. 3410 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 3411 /// \brief Source range of the loop increment. 3412 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 3413 /// \brief True if the step should be subtracted. 3414 bool ShouldSubtractStep() const { return SubtractStep; } 3415 /// \brief Build the expression to calculate the number of iterations. 3416 Expr * 3417 BuildNumIterations(Scope *S, const bool LimitedType, 3418 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3419 /// \brief Build the precondition expression for the loops. 3420 Expr *BuildPreCond(Scope *S, Expr *Cond, 3421 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3422 /// \brief Build reference expression to the counter be used for codegen. 3423 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 3424 DSAStackTy &DSA) const; 3425 /// \brief Build reference expression to the private counter be used for 3426 /// codegen. 3427 Expr *BuildPrivateCounterVar() const; 3428 /// \brief Build initialization of the counter be used for codegen. 3429 Expr *BuildCounterInit() const; 3430 /// \brief Build step of the counter be used for codegen. 3431 Expr *BuildCounterStep() const; 3432 /// \brief Return true if any expression is dependent. 3433 bool Dependent() const; 3434 3435 private: 3436 /// \brief Check the right-hand side of an assignment in the increment 3437 /// expression. 3438 bool CheckIncRHS(Expr *RHS); 3439 /// \brief Helper to set loop counter variable and its initializer. 3440 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 3441 /// \brief Helper to set upper bound. 3442 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 3443 SourceLocation SL); 3444 /// \brief Helper to set loop increment. 3445 bool SetStep(Expr *NewStep, bool Subtract); 3446 }; 3447 3448 bool OpenMPIterationSpaceChecker::Dependent() const { 3449 if (!LCDecl) { 3450 assert(!LB && !UB && !Step); 3451 return false; 3452 } 3453 return LCDecl->getType()->isDependentType() || 3454 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 3455 (Step && Step->isValueDependent()); 3456 } 3457 3458 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 3459 Expr *NewLCRefExpr, 3460 Expr *NewLB) { 3461 // State consistency checking to ensure correct usage. 3462 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 3463 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3464 if (!NewLCDecl || !NewLB) 3465 return true; 3466 LCDecl = getCanonicalDecl(NewLCDecl); 3467 LCRef = NewLCRefExpr; 3468 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 3469 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3470 if ((Ctor->isCopyOrMoveConstructor() || 3471 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3472 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3473 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 3474 LB = NewLB; 3475 return false; 3476 } 3477 3478 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 3479 SourceRange SR, SourceLocation SL) { 3480 // State consistency checking to ensure correct usage. 3481 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 3482 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3483 if (!NewUB) 3484 return true; 3485 UB = NewUB; 3486 TestIsLessOp = LessOp; 3487 TestIsStrictOp = StrictOp; 3488 ConditionSrcRange = SR; 3489 ConditionLoc = SL; 3490 return false; 3491 } 3492 3493 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 3494 // State consistency checking to ensure correct usage. 3495 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 3496 if (!NewStep) 3497 return true; 3498 if (!NewStep->isValueDependent()) { 3499 // Check that the step is integer expression. 3500 SourceLocation StepLoc = NewStep->getLocStart(); 3501 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 3502 StepLoc, getExprAsWritten(NewStep)); 3503 if (Val.isInvalid()) 3504 return true; 3505 NewStep = Val.get(); 3506 3507 // OpenMP [2.6, Canonical Loop Form, Restrictions] 3508 // If test-expr is of form var relational-op b and relational-op is < or 3509 // <= then incr-expr must cause var to increase on each iteration of the 3510 // loop. If test-expr is of form var relational-op b and relational-op is 3511 // > or >= then incr-expr must cause var to decrease on each iteration of 3512 // the loop. 3513 // If test-expr is of form b relational-op var and relational-op is < or 3514 // <= then incr-expr must cause var to decrease on each iteration of the 3515 // loop. If test-expr is of form b relational-op var and relational-op is 3516 // > or >= then incr-expr must cause var to increase on each iteration of 3517 // the loop. 3518 llvm::APSInt Result; 3519 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 3520 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 3521 bool IsConstNeg = 3522 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 3523 bool IsConstPos = 3524 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 3525 bool IsConstZero = IsConstant && !Result.getBoolValue(); 3526 if (UB && (IsConstZero || 3527 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 3528 : (IsConstPos || (IsUnsigned && !Subtract))))) { 3529 SemaRef.Diag(NewStep->getExprLoc(), 3530 diag::err_omp_loop_incr_not_compatible) 3531 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 3532 SemaRef.Diag(ConditionLoc, 3533 diag::note_omp_loop_cond_requres_compatible_incr) 3534 << TestIsLessOp << ConditionSrcRange; 3535 return true; 3536 } 3537 if (TestIsLessOp == Subtract) { 3538 NewStep = 3539 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 3540 .get(); 3541 Subtract = !Subtract; 3542 } 3543 } 3544 3545 Step = NewStep; 3546 SubtractStep = Subtract; 3547 return false; 3548 } 3549 3550 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 3551 // Check init-expr for canonical loop form and save loop counter 3552 // variable - #Var and its initialization value - #LB. 3553 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 3554 // var = lb 3555 // integer-type var = lb 3556 // random-access-iterator-type var = lb 3557 // pointer-type var = lb 3558 // 3559 if (!S) { 3560 if (EmitDiags) { 3561 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 3562 } 3563 return true; 3564 } 3565 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3566 if (!ExprTemp->cleanupsHaveSideEffects()) 3567 S = ExprTemp->getSubExpr(); 3568 3569 InitSrcRange = S->getSourceRange(); 3570 if (Expr *E = dyn_cast<Expr>(S)) 3571 S = E->IgnoreParens(); 3572 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3573 if (BO->getOpcode() == BO_Assign) { 3574 auto *LHS = BO->getLHS()->IgnoreParens(); 3575 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3576 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3577 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3578 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3579 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 3580 } 3581 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3582 if (ME->isArrow() && 3583 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3584 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3585 } 3586 } 3587 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 3588 if (DS->isSingleDecl()) { 3589 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 3590 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 3591 // Accept non-canonical init form here but emit ext. warning. 3592 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 3593 SemaRef.Diag(S->getLocStart(), 3594 diag::ext_omp_loop_not_canonical_init) 3595 << S->getSourceRange(); 3596 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 3597 } 3598 } 3599 } 3600 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3601 if (CE->getOperator() == OO_Equal) { 3602 auto *LHS = CE->getArg(0); 3603 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3604 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3605 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3606 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3607 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 3608 } 3609 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3610 if (ME->isArrow() && 3611 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3612 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3613 } 3614 } 3615 } 3616 3617 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3618 return false; 3619 if (EmitDiags) { 3620 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 3621 << S->getSourceRange(); 3622 } 3623 return true; 3624 } 3625 3626 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 3627 /// variable (which may be the loop variable) if possible. 3628 static const ValueDecl *GetInitLCDecl(Expr *E) { 3629 if (!E) 3630 return nullptr; 3631 E = getExprAsWritten(E); 3632 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 3633 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3634 if ((Ctor->isCopyOrMoveConstructor() || 3635 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3636 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3637 E = CE->getArg(0)->IgnoreParenImpCasts(); 3638 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 3639 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 3640 return getCanonicalDecl(VD); 3641 } 3642 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 3643 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3644 return getCanonicalDecl(ME->getMemberDecl()); 3645 return nullptr; 3646 } 3647 3648 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 3649 // Check test-expr for canonical form, save upper-bound UB, flags for 3650 // less/greater and for strict/non-strict comparison. 3651 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3652 // var relational-op b 3653 // b relational-op var 3654 // 3655 if (!S) { 3656 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 3657 return true; 3658 } 3659 S = getExprAsWritten(S); 3660 SourceLocation CondLoc = S->getLocStart(); 3661 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3662 if (BO->isRelationalOp()) { 3663 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3664 return SetUB(BO->getRHS(), 3665 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 3666 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3667 BO->getSourceRange(), BO->getOperatorLoc()); 3668 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 3669 return SetUB(BO->getLHS(), 3670 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 3671 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3672 BO->getSourceRange(), BO->getOperatorLoc()); 3673 } 3674 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3675 if (CE->getNumArgs() == 2) { 3676 auto Op = CE->getOperator(); 3677 switch (Op) { 3678 case OO_Greater: 3679 case OO_GreaterEqual: 3680 case OO_Less: 3681 case OO_LessEqual: 3682 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3683 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 3684 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3685 CE->getOperatorLoc()); 3686 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 3687 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 3688 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3689 CE->getOperatorLoc()); 3690 break; 3691 default: 3692 break; 3693 } 3694 } 3695 } 3696 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3697 return false; 3698 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 3699 << S->getSourceRange() << LCDecl; 3700 return true; 3701 } 3702 3703 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 3704 // RHS of canonical loop form increment can be: 3705 // var + incr 3706 // incr + var 3707 // var - incr 3708 // 3709 RHS = RHS->IgnoreParenImpCasts(); 3710 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 3711 if (BO->isAdditiveOp()) { 3712 bool IsAdd = BO->getOpcode() == BO_Add; 3713 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3714 return SetStep(BO->getRHS(), !IsAdd); 3715 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 3716 return SetStep(BO->getLHS(), false); 3717 } 3718 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 3719 bool IsAdd = CE->getOperator() == OO_Plus; 3720 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 3721 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3722 return SetStep(CE->getArg(1), !IsAdd); 3723 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 3724 return SetStep(CE->getArg(0), false); 3725 } 3726 } 3727 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3728 return false; 3729 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3730 << RHS->getSourceRange() << LCDecl; 3731 return true; 3732 } 3733 3734 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 3735 // Check incr-expr for canonical loop form and return true if it 3736 // does not conform. 3737 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3738 // ++var 3739 // var++ 3740 // --var 3741 // var-- 3742 // var += incr 3743 // var -= incr 3744 // var = var + incr 3745 // var = incr + var 3746 // var = var - incr 3747 // 3748 if (!S) { 3749 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 3750 return true; 3751 } 3752 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3753 if (!ExprTemp->cleanupsHaveSideEffects()) 3754 S = ExprTemp->getSubExpr(); 3755 3756 IncrementSrcRange = S->getSourceRange(); 3757 S = S->IgnoreParens(); 3758 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 3759 if (UO->isIncrementDecrementOp() && 3760 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 3761 return SetStep(SemaRef 3762 .ActOnIntegerConstant(UO->getLocStart(), 3763 (UO->isDecrementOp() ? -1 : 1)) 3764 .get(), 3765 false); 3766 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3767 switch (BO->getOpcode()) { 3768 case BO_AddAssign: 3769 case BO_SubAssign: 3770 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3771 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 3772 break; 3773 case BO_Assign: 3774 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3775 return CheckIncRHS(BO->getRHS()); 3776 break; 3777 default: 3778 break; 3779 } 3780 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3781 switch (CE->getOperator()) { 3782 case OO_PlusPlus: 3783 case OO_MinusMinus: 3784 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3785 return SetStep(SemaRef 3786 .ActOnIntegerConstant( 3787 CE->getLocStart(), 3788 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 3789 .get(), 3790 false); 3791 break; 3792 case OO_PlusEqual: 3793 case OO_MinusEqual: 3794 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3795 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 3796 break; 3797 case OO_Equal: 3798 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3799 return CheckIncRHS(CE->getArg(1)); 3800 break; 3801 default: 3802 break; 3803 } 3804 } 3805 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3806 return false; 3807 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3808 << S->getSourceRange() << LCDecl; 3809 return true; 3810 } 3811 3812 static ExprResult 3813 tryBuildCapture(Sema &SemaRef, Expr *Capture, 3814 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3815 if (SemaRef.CurContext->isDependentContext()) 3816 return ExprResult(Capture); 3817 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 3818 return SemaRef.PerformImplicitConversion( 3819 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 3820 /*AllowExplicit=*/true); 3821 auto I = Captures.find(Capture); 3822 if (I != Captures.end()) 3823 return buildCapture(SemaRef, Capture, I->second); 3824 DeclRefExpr *Ref = nullptr; 3825 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 3826 Captures[Capture] = Ref; 3827 return Res; 3828 } 3829 3830 /// \brief Build the expression to calculate the number of iterations. 3831 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 3832 Scope *S, const bool LimitedType, 3833 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3834 ExprResult Diff; 3835 auto VarType = LCDecl->getType().getNonReferenceType(); 3836 if (VarType->isIntegerType() || VarType->isPointerType() || 3837 SemaRef.getLangOpts().CPlusPlus) { 3838 // Upper - Lower 3839 auto *UBExpr = TestIsLessOp ? UB : LB; 3840 auto *LBExpr = TestIsLessOp ? LB : UB; 3841 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 3842 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 3843 if (!Upper || !Lower) 3844 return nullptr; 3845 3846 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 3847 3848 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 3849 // BuildBinOp already emitted error, this one is to point user to upper 3850 // and lower bound, and to tell what is passed to 'operator-'. 3851 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 3852 << Upper->getSourceRange() << Lower->getSourceRange(); 3853 return nullptr; 3854 } 3855 } 3856 3857 if (!Diff.isUsable()) 3858 return nullptr; 3859 3860 // Upper - Lower [- 1] 3861 if (TestIsStrictOp) 3862 Diff = SemaRef.BuildBinOp( 3863 S, DefaultLoc, BO_Sub, Diff.get(), 3864 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3865 if (!Diff.isUsable()) 3866 return nullptr; 3867 3868 // Upper - Lower [- 1] + Step 3869 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 3870 if (!NewStep.isUsable()) 3871 return nullptr; 3872 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 3873 if (!Diff.isUsable()) 3874 return nullptr; 3875 3876 // Parentheses (for dumping/debugging purposes only). 3877 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 3878 if (!Diff.isUsable()) 3879 return nullptr; 3880 3881 // (Upper - Lower [- 1] + Step) / Step 3882 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 3883 if (!Diff.isUsable()) 3884 return nullptr; 3885 3886 // OpenMP runtime requires 32-bit or 64-bit loop variables. 3887 QualType Type = Diff.get()->getType(); 3888 auto &C = SemaRef.Context; 3889 bool UseVarType = VarType->hasIntegerRepresentation() && 3890 C.getTypeSize(Type) > C.getTypeSize(VarType); 3891 if (!Type->isIntegerType() || UseVarType) { 3892 unsigned NewSize = 3893 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 3894 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 3895 : Type->hasSignedIntegerRepresentation(); 3896 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 3897 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 3898 Diff = SemaRef.PerformImplicitConversion( 3899 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 3900 if (!Diff.isUsable()) 3901 return nullptr; 3902 } 3903 } 3904 if (LimitedType) { 3905 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 3906 if (NewSize != C.getTypeSize(Type)) { 3907 if (NewSize < C.getTypeSize(Type)) { 3908 assert(NewSize == 64 && "incorrect loop var size"); 3909 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 3910 << InitSrcRange << ConditionSrcRange; 3911 } 3912 QualType NewType = C.getIntTypeForBitwidth( 3913 NewSize, Type->hasSignedIntegerRepresentation() || 3914 C.getTypeSize(Type) < NewSize); 3915 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 3916 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 3917 Sema::AA_Converting, true); 3918 if (!Diff.isUsable()) 3919 return nullptr; 3920 } 3921 } 3922 } 3923 3924 return Diff.get(); 3925 } 3926 3927 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 3928 Scope *S, Expr *Cond, 3929 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3930 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 3931 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3932 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3933 3934 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 3935 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 3936 if (!NewLB.isUsable() || !NewUB.isUsable()) 3937 return nullptr; 3938 3939 auto CondExpr = SemaRef.BuildBinOp( 3940 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 3941 : (TestIsStrictOp ? BO_GT : BO_GE), 3942 NewLB.get(), NewUB.get()); 3943 if (CondExpr.isUsable()) { 3944 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 3945 SemaRef.Context.BoolTy)) 3946 CondExpr = SemaRef.PerformImplicitConversion( 3947 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 3948 /*AllowExplicit=*/true); 3949 } 3950 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3951 // Otherwise use original loop conditon and evaluate it in runtime. 3952 return CondExpr.isUsable() ? CondExpr.get() : Cond; 3953 } 3954 3955 /// \brief Build reference expression to the counter be used for codegen. 3956 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 3957 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 3958 auto *VD = dyn_cast<VarDecl>(LCDecl); 3959 if (!VD) { 3960 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 3961 auto *Ref = buildDeclRefExpr( 3962 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 3963 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 3964 // If the loop control decl is explicitly marked as private, do not mark it 3965 // as captured again. 3966 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 3967 Captures.insert(std::make_pair(LCRef, Ref)); 3968 return Ref; 3969 } 3970 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 3971 DefaultLoc); 3972 } 3973 3974 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 3975 if (LCDecl && !LCDecl->isInvalidDecl()) { 3976 auto Type = LCDecl->getType().getNonReferenceType(); 3977 auto *PrivateVar = 3978 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 3979 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 3980 if (PrivateVar->isInvalidDecl()) 3981 return nullptr; 3982 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 3983 } 3984 return nullptr; 3985 } 3986 3987 /// \brief Build initialization of the counter to be used for codegen. 3988 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 3989 3990 /// \brief Build step of the counter be used for codegen. 3991 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 3992 3993 /// \brief Iteration space of a single for loop. 3994 struct LoopIterationSpace final { 3995 /// \brief Condition of the loop. 3996 Expr *PreCond = nullptr; 3997 /// \brief This expression calculates the number of iterations in the loop. 3998 /// It is always possible to calculate it before starting the loop. 3999 Expr *NumIterations = nullptr; 4000 /// \brief The loop counter variable. 4001 Expr *CounterVar = nullptr; 4002 /// \brief Private loop counter variable. 4003 Expr *PrivateCounterVar = nullptr; 4004 /// \brief This is initializer for the initial value of #CounterVar. 4005 Expr *CounterInit = nullptr; 4006 /// \brief This is step for the #CounterVar used to generate its update: 4007 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 4008 Expr *CounterStep = nullptr; 4009 /// \brief Should step be subtracted? 4010 bool Subtract = false; 4011 /// \brief Source range of the loop init. 4012 SourceRange InitSrcRange; 4013 /// \brief Source range of the loop condition. 4014 SourceRange CondSrcRange; 4015 /// \brief Source range of the loop increment. 4016 SourceRange IncSrcRange; 4017 }; 4018 4019 } // namespace 4020 4021 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 4022 assert(getLangOpts().OpenMP && "OpenMP is not active."); 4023 assert(Init && "Expected loop in canonical form."); 4024 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 4025 if (AssociatedLoops > 0 && 4026 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 4027 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 4028 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 4029 if (auto *D = ISC.GetLoopDecl()) { 4030 auto *VD = dyn_cast<VarDecl>(D); 4031 if (!VD) { 4032 if (auto *Private = IsOpenMPCapturedDecl(D)) 4033 VD = Private; 4034 else { 4035 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 4036 /*WithInit=*/false); 4037 VD = cast<VarDecl>(Ref->getDecl()); 4038 } 4039 } 4040 DSAStack->addLoopControlVariable(D, VD); 4041 } 4042 } 4043 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 4044 } 4045 } 4046 4047 /// \brief Called on a for stmt to check and extract its iteration space 4048 /// for further processing (such as collapsing). 4049 static bool CheckOpenMPIterationSpace( 4050 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 4051 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 4052 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 4053 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 4054 LoopIterationSpace &ResultIterSpace, 4055 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4056 // OpenMP [2.6, Canonical Loop Form] 4057 // for (init-expr; test-expr; incr-expr) structured-block 4058 auto *For = dyn_cast_or_null<ForStmt>(S); 4059 if (!For) { 4060 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 4061 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 4062 << getOpenMPDirectiveName(DKind) << NestedLoopCount 4063 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 4064 if (NestedLoopCount > 1) { 4065 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 4066 SemaRef.Diag(DSA.getConstructLoc(), 4067 diag::note_omp_collapse_ordered_expr) 4068 << 2 << CollapseLoopCountExpr->getSourceRange() 4069 << OrderedLoopCountExpr->getSourceRange(); 4070 else if (CollapseLoopCountExpr) 4071 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4072 diag::note_omp_collapse_ordered_expr) 4073 << 0 << CollapseLoopCountExpr->getSourceRange(); 4074 else 4075 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4076 diag::note_omp_collapse_ordered_expr) 4077 << 1 << OrderedLoopCountExpr->getSourceRange(); 4078 } 4079 return true; 4080 } 4081 assert(For->getBody()); 4082 4083 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 4084 4085 // Check init. 4086 auto Init = For->getInit(); 4087 if (ISC.CheckInit(Init)) 4088 return true; 4089 4090 bool HasErrors = false; 4091 4092 // Check loop variable's type. 4093 if (auto *LCDecl = ISC.GetLoopDecl()) { 4094 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 4095 4096 // OpenMP [2.6, Canonical Loop Form] 4097 // Var is one of the following: 4098 // A variable of signed or unsigned integer type. 4099 // For C++, a variable of a random access iterator type. 4100 // For C, a variable of a pointer type. 4101 auto VarType = LCDecl->getType().getNonReferenceType(); 4102 if (!VarType->isDependentType() && !VarType->isIntegerType() && 4103 !VarType->isPointerType() && 4104 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 4105 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 4106 << SemaRef.getLangOpts().CPlusPlus; 4107 HasErrors = true; 4108 } 4109 4110 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 4111 // a Construct 4112 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4113 // parallel for construct is (are) private. 4114 // The loop iteration variable in the associated for-loop of a simd 4115 // construct with just one associated for-loop is linear with a 4116 // constant-linear-step that is the increment of the associated for-loop. 4117 // Exclude loop var from the list of variables with implicitly defined data 4118 // sharing attributes. 4119 VarsWithImplicitDSA.erase(LCDecl); 4120 4121 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4122 // in a Construct, C/C++]. 4123 // The loop iteration variable in the associated for-loop of a simd 4124 // construct with just one associated for-loop may be listed in a linear 4125 // clause with a constant-linear-step that is the increment of the 4126 // associated for-loop. 4127 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4128 // parallel for construct may be listed in a private or lastprivate clause. 4129 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 4130 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 4131 // declared in the loop and it is predetermined as a private. 4132 auto PredeterminedCKind = 4133 isOpenMPSimdDirective(DKind) 4134 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 4135 : OMPC_private; 4136 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4137 DVar.CKind != PredeterminedCKind) || 4138 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 4139 isOpenMPDistributeDirective(DKind)) && 4140 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4141 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 4142 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 4143 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 4144 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 4145 << getOpenMPClauseName(PredeterminedCKind); 4146 if (DVar.RefExpr == nullptr) 4147 DVar.CKind = PredeterminedCKind; 4148 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 4149 HasErrors = true; 4150 } else if (LoopDeclRefExpr != nullptr) { 4151 // Make the loop iteration variable private (for worksharing constructs), 4152 // linear (for simd directives with the only one associated loop) or 4153 // lastprivate (for simd directives with several collapsed or ordered 4154 // loops). 4155 if (DVar.CKind == OMPC_unknown) 4156 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 4157 [](OpenMPDirectiveKind) -> bool { return true; }, 4158 /*FromParent=*/false); 4159 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 4160 } 4161 4162 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 4163 4164 // Check test-expr. 4165 HasErrors |= ISC.CheckCond(For->getCond()); 4166 4167 // Check incr-expr. 4168 HasErrors |= ISC.CheckInc(For->getInc()); 4169 } 4170 4171 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 4172 return HasErrors; 4173 4174 // Build the loop's iteration space representation. 4175 ResultIterSpace.PreCond = 4176 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 4177 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 4178 DSA.getCurScope(), 4179 (isOpenMPWorksharingDirective(DKind) || 4180 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 4181 Captures); 4182 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 4183 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 4184 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 4185 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 4186 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 4187 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 4188 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 4189 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 4190 4191 HasErrors |= (ResultIterSpace.PreCond == nullptr || 4192 ResultIterSpace.NumIterations == nullptr || 4193 ResultIterSpace.CounterVar == nullptr || 4194 ResultIterSpace.PrivateCounterVar == nullptr || 4195 ResultIterSpace.CounterInit == nullptr || 4196 ResultIterSpace.CounterStep == nullptr); 4197 4198 return HasErrors; 4199 } 4200 4201 /// \brief Build 'VarRef = Start. 4202 static ExprResult 4203 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 4204 ExprResult Start, 4205 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4206 // Build 'VarRef = Start. 4207 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 4208 if (!NewStart.isUsable()) 4209 return ExprError(); 4210 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 4211 VarRef.get()->getType())) { 4212 NewStart = SemaRef.PerformImplicitConversion( 4213 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 4214 /*AllowExplicit=*/true); 4215 if (!NewStart.isUsable()) 4216 return ExprError(); 4217 } 4218 4219 auto Init = 4220 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4221 return Init; 4222 } 4223 4224 /// \brief Build 'VarRef = Start + Iter * Step'. 4225 static ExprResult 4226 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 4227 ExprResult VarRef, ExprResult Start, ExprResult Iter, 4228 ExprResult Step, bool Subtract, 4229 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 4230 // Add parentheses (for debugging purposes only). 4231 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 4232 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 4233 !Step.isUsable()) 4234 return ExprError(); 4235 4236 ExprResult NewStep = Step; 4237 if (Captures) 4238 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 4239 if (NewStep.isInvalid()) 4240 return ExprError(); 4241 ExprResult Update = 4242 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 4243 if (!Update.isUsable()) 4244 return ExprError(); 4245 4246 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 4247 // 'VarRef = Start (+|-) Iter * Step'. 4248 ExprResult NewStart = Start; 4249 if (Captures) 4250 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 4251 if (NewStart.isInvalid()) 4252 return ExprError(); 4253 4254 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 4255 ExprResult SavedUpdate = Update; 4256 ExprResult UpdateVal; 4257 if (VarRef.get()->getType()->isOverloadableType() || 4258 NewStart.get()->getType()->isOverloadableType() || 4259 Update.get()->getType()->isOverloadableType()) { 4260 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4261 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4262 Update = 4263 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4264 if (Update.isUsable()) { 4265 UpdateVal = 4266 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 4267 VarRef.get(), SavedUpdate.get()); 4268 if (UpdateVal.isUsable()) { 4269 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 4270 UpdateVal.get()); 4271 } 4272 } 4273 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4274 } 4275 4276 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 4277 if (!Update.isUsable() || !UpdateVal.isUsable()) { 4278 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 4279 NewStart.get(), SavedUpdate.get()); 4280 if (!Update.isUsable()) 4281 return ExprError(); 4282 4283 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 4284 VarRef.get()->getType())) { 4285 Update = SemaRef.PerformImplicitConversion( 4286 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 4287 if (!Update.isUsable()) 4288 return ExprError(); 4289 } 4290 4291 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 4292 } 4293 return Update; 4294 } 4295 4296 /// \brief Convert integer expression \a E to make it have at least \a Bits 4297 /// bits. 4298 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 4299 if (E == nullptr) 4300 return ExprError(); 4301 auto &C = SemaRef.Context; 4302 QualType OldType = E->getType(); 4303 unsigned HasBits = C.getTypeSize(OldType); 4304 if (HasBits >= Bits) 4305 return ExprResult(E); 4306 // OK to convert to signed, because new type has more bits than old. 4307 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 4308 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 4309 true); 4310 } 4311 4312 /// \brief Check if the given expression \a E is a constant integer that fits 4313 /// into \a Bits bits. 4314 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 4315 if (E == nullptr) 4316 return false; 4317 llvm::APSInt Result; 4318 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 4319 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 4320 return false; 4321 } 4322 4323 /// Build preinits statement for the given declarations. 4324 static Stmt *buildPreInits(ASTContext &Context, 4325 MutableArrayRef<Decl *> PreInits) { 4326 if (!PreInits.empty()) { 4327 return new (Context) DeclStmt( 4328 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 4329 SourceLocation(), SourceLocation()); 4330 } 4331 return nullptr; 4332 } 4333 4334 /// Build preinits statement for the given declarations. 4335 static Stmt * 4336 buildPreInits(ASTContext &Context, 4337 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4338 if (!Captures.empty()) { 4339 SmallVector<Decl *, 16> PreInits; 4340 for (auto &Pair : Captures) 4341 PreInits.push_back(Pair.second->getDecl()); 4342 return buildPreInits(Context, PreInits); 4343 } 4344 return nullptr; 4345 } 4346 4347 /// Build postupdate expression for the given list of postupdates expressions. 4348 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 4349 Expr *PostUpdate = nullptr; 4350 if (!PostUpdates.empty()) { 4351 for (auto *E : PostUpdates) { 4352 Expr *ConvE = S.BuildCStyleCastExpr( 4353 E->getExprLoc(), 4354 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 4355 E->getExprLoc(), E) 4356 .get(); 4357 PostUpdate = PostUpdate 4358 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 4359 PostUpdate, ConvE) 4360 .get() 4361 : ConvE; 4362 } 4363 } 4364 return PostUpdate; 4365 } 4366 4367 /// \brief Called on a for stmt to check itself and nested loops (if any). 4368 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 4369 /// number of collapsed loops otherwise. 4370 static unsigned 4371 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 4372 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 4373 DSAStackTy &DSA, 4374 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 4375 OMPLoopDirective::HelperExprs &Built) { 4376 unsigned NestedLoopCount = 1; 4377 if (CollapseLoopCountExpr) { 4378 // Found 'collapse' clause - calculate collapse number. 4379 llvm::APSInt Result; 4380 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 4381 NestedLoopCount = Result.getLimitedValue(); 4382 } 4383 if (OrderedLoopCountExpr) { 4384 // Found 'ordered' clause - calculate collapse number. 4385 llvm::APSInt Result; 4386 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 4387 if (Result.getLimitedValue() < NestedLoopCount) { 4388 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4389 diag::err_omp_wrong_ordered_loop_count) 4390 << OrderedLoopCountExpr->getSourceRange(); 4391 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4392 diag::note_collapse_loop_count) 4393 << CollapseLoopCountExpr->getSourceRange(); 4394 } 4395 NestedLoopCount = Result.getLimitedValue(); 4396 } 4397 } 4398 // This is helper routine for loop directives (e.g., 'for', 'simd', 4399 // 'for simd', etc.). 4400 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 4401 SmallVector<LoopIterationSpace, 4> IterSpaces; 4402 IterSpaces.resize(NestedLoopCount); 4403 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 4404 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 4405 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 4406 NestedLoopCount, CollapseLoopCountExpr, 4407 OrderedLoopCountExpr, VarsWithImplicitDSA, 4408 IterSpaces[Cnt], Captures)) 4409 return 0; 4410 // Move on to the next nested for loop, or to the loop body. 4411 // OpenMP [2.8.1, simd construct, Restrictions] 4412 // All loops associated with the construct must be perfectly nested; that 4413 // is, there must be no intervening code nor any OpenMP directive between 4414 // any two loops. 4415 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 4416 } 4417 4418 Built.clear(/* size */ NestedLoopCount); 4419 4420 if (SemaRef.CurContext->isDependentContext()) 4421 return NestedLoopCount; 4422 4423 // An example of what is generated for the following code: 4424 // 4425 // #pragma omp simd collapse(2) ordered(2) 4426 // for (i = 0; i < NI; ++i) 4427 // for (k = 0; k < NK; ++k) 4428 // for (j = J0; j < NJ; j+=2) { 4429 // <loop body> 4430 // } 4431 // 4432 // We generate the code below. 4433 // Note: the loop body may be outlined in CodeGen. 4434 // Note: some counters may be C++ classes, operator- is used to find number of 4435 // iterations and operator+= to calculate counter value. 4436 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 4437 // or i64 is currently supported). 4438 // 4439 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 4440 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 4441 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 4442 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 4443 // // similar updates for vars in clauses (e.g. 'linear') 4444 // <loop body (using local i and j)> 4445 // } 4446 // i = NI; // assign final values of counters 4447 // j = NJ; 4448 // 4449 4450 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 4451 // the iteration counts of the collapsed for loops. 4452 // Precondition tests if there is at least one iteration (all conditions are 4453 // true). 4454 auto PreCond = ExprResult(IterSpaces[0].PreCond); 4455 auto N0 = IterSpaces[0].NumIterations; 4456 ExprResult LastIteration32 = WidenIterationCount( 4457 32 /* Bits */, SemaRef 4458 .PerformImplicitConversion( 4459 N0->IgnoreImpCasts(), N0->getType(), 4460 Sema::AA_Converting, /*AllowExplicit=*/true) 4461 .get(), 4462 SemaRef); 4463 ExprResult LastIteration64 = WidenIterationCount( 4464 64 /* Bits */, SemaRef 4465 .PerformImplicitConversion( 4466 N0->IgnoreImpCasts(), N0->getType(), 4467 Sema::AA_Converting, /*AllowExplicit=*/true) 4468 .get(), 4469 SemaRef); 4470 4471 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 4472 return NestedLoopCount; 4473 4474 auto &C = SemaRef.Context; 4475 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 4476 4477 Scope *CurScope = DSA.getCurScope(); 4478 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 4479 if (PreCond.isUsable()) { 4480 PreCond = 4481 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 4482 PreCond.get(), IterSpaces[Cnt].PreCond); 4483 } 4484 auto N = IterSpaces[Cnt].NumIterations; 4485 SourceLocation Loc = N->getExprLoc(); 4486 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 4487 if (LastIteration32.isUsable()) 4488 LastIteration32 = SemaRef.BuildBinOp( 4489 CurScope, Loc, BO_Mul, LastIteration32.get(), 4490 SemaRef 4491 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4492 Sema::AA_Converting, 4493 /*AllowExplicit=*/true) 4494 .get()); 4495 if (LastIteration64.isUsable()) 4496 LastIteration64 = SemaRef.BuildBinOp( 4497 CurScope, Loc, BO_Mul, LastIteration64.get(), 4498 SemaRef 4499 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4500 Sema::AA_Converting, 4501 /*AllowExplicit=*/true) 4502 .get()); 4503 } 4504 4505 // Choose either the 32-bit or 64-bit version. 4506 ExprResult LastIteration = LastIteration64; 4507 if (LastIteration32.isUsable() && 4508 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 4509 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 4510 FitsInto( 4511 32 /* Bits */, 4512 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 4513 LastIteration64.get(), SemaRef))) 4514 LastIteration = LastIteration32; 4515 QualType VType = LastIteration.get()->getType(); 4516 QualType RealVType = VType; 4517 QualType StrideVType = VType; 4518 if (isOpenMPTaskLoopDirective(DKind)) { 4519 VType = 4520 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 4521 StrideVType = 4522 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 4523 } 4524 4525 if (!LastIteration.isUsable()) 4526 return 0; 4527 4528 // Save the number of iterations. 4529 ExprResult NumIterations = LastIteration; 4530 { 4531 LastIteration = SemaRef.BuildBinOp( 4532 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 4533 LastIteration.get(), 4534 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4535 if (!LastIteration.isUsable()) 4536 return 0; 4537 } 4538 4539 // Calculate the last iteration number beforehand instead of doing this on 4540 // each iteration. Do not do this if the number of iterations may be kfold-ed. 4541 llvm::APSInt Result; 4542 bool IsConstant = 4543 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 4544 ExprResult CalcLastIteration; 4545 if (!IsConstant) { 4546 ExprResult SaveRef = 4547 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 4548 LastIteration = SaveRef; 4549 4550 // Prepare SaveRef + 1. 4551 NumIterations = SemaRef.BuildBinOp( 4552 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 4553 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4554 if (!NumIterations.isUsable()) 4555 return 0; 4556 } 4557 4558 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 4559 4560 // Build variables passed into runtime, necessary for worksharing directives. 4561 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 4562 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4563 isOpenMPDistributeDirective(DKind)) { 4564 // Lower bound variable, initialized with zero. 4565 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 4566 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 4567 SemaRef.AddInitializerToDecl(LBDecl, 4568 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4569 /*DirectInit*/ false); 4570 4571 // Upper bound variable, initialized with last iteration number. 4572 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 4573 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 4574 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 4575 /*DirectInit*/ false); 4576 4577 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 4578 // This will be used to implement clause 'lastprivate'. 4579 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 4580 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 4581 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 4582 SemaRef.AddInitializerToDecl(ILDecl, 4583 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4584 /*DirectInit*/ false); 4585 4586 // Stride variable returned by runtime (we initialize it to 1 by default). 4587 VarDecl *STDecl = 4588 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 4589 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 4590 SemaRef.AddInitializerToDecl(STDecl, 4591 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 4592 /*DirectInit*/ false); 4593 4594 // Build expression: UB = min(UB, LastIteration) 4595 // It is necessary for CodeGen of directives with static scheduling. 4596 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 4597 UB.get(), LastIteration.get()); 4598 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4599 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 4600 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 4601 CondOp.get()); 4602 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 4603 4604 // If we have a combined directive that combines 'distribute', 'for' or 4605 // 'simd' we need to be able to access the bounds of the schedule of the 4606 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 4607 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 4608 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4609 4610 // Lower bound variable, initialized with zero. 4611 VarDecl *CombLBDecl = 4612 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 4613 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 4614 SemaRef.AddInitializerToDecl( 4615 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4616 /*DirectInit*/ false); 4617 4618 // Upper bound variable, initialized with last iteration number. 4619 VarDecl *CombUBDecl = 4620 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 4621 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 4622 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 4623 /*DirectInit*/ false); 4624 4625 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 4626 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 4627 ExprResult CombCondOp = 4628 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 4629 LastIteration.get(), CombUB.get()); 4630 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 4631 CombCondOp.get()); 4632 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get()); 4633 4634 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 4635 // We expect to have at least 2 more parameters than the 'parallel' 4636 // directive does - the lower and upper bounds of the previous schedule. 4637 assert(CD->getNumParams() >= 4 && 4638 "Unexpected number of parameters in loop combined directive"); 4639 4640 // Set the proper type for the bounds given what we learned from the 4641 // enclosed loops. 4642 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 4643 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 4644 4645 // Previous lower and upper bounds are obtained from the region 4646 // parameters. 4647 PrevLB = 4648 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 4649 PrevUB = 4650 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 4651 } 4652 } 4653 4654 // Build the iteration variable and its initialization before loop. 4655 ExprResult IV; 4656 ExprResult Init, CombInit; 4657 { 4658 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 4659 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 4660 Expr *RHS = 4661 (isOpenMPWorksharingDirective(DKind) || 4662 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4663 ? LB.get() 4664 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4665 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 4666 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 4667 4668 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4669 Expr *CombRHS = 4670 (isOpenMPWorksharingDirective(DKind) || 4671 isOpenMPTaskLoopDirective(DKind) || 4672 isOpenMPDistributeDirective(DKind)) 4673 ? CombLB.get() 4674 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4675 CombInit = 4676 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 4677 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get()); 4678 } 4679 } 4680 4681 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 4682 SourceLocation CondLoc; 4683 ExprResult Cond = 4684 (isOpenMPWorksharingDirective(DKind) || 4685 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4686 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 4687 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 4688 NumIterations.get()); 4689 ExprResult CombCond; 4690 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4691 CombCond = 4692 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get()); 4693 } 4694 // Loop increment (IV = IV + 1) 4695 SourceLocation IncLoc; 4696 ExprResult Inc = 4697 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 4698 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 4699 if (!Inc.isUsable()) 4700 return 0; 4701 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 4702 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 4703 if (!Inc.isUsable()) 4704 return 0; 4705 4706 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 4707 // Used for directives with static scheduling. 4708 // In combined construct, add combined version that use CombLB and CombUB 4709 // base variables for the update 4710 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 4711 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4712 isOpenMPDistributeDirective(DKind)) { 4713 // LB + ST 4714 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 4715 if (!NextLB.isUsable()) 4716 return 0; 4717 // LB = LB + ST 4718 NextLB = 4719 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 4720 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 4721 if (!NextLB.isUsable()) 4722 return 0; 4723 // UB + ST 4724 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 4725 if (!NextUB.isUsable()) 4726 return 0; 4727 // UB = UB + ST 4728 NextUB = 4729 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 4730 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 4731 if (!NextUB.isUsable()) 4732 return 0; 4733 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4734 CombNextLB = 4735 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 4736 if (!NextLB.isUsable()) 4737 return 0; 4738 // LB = LB + ST 4739 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 4740 CombNextLB.get()); 4741 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get()); 4742 if (!CombNextLB.isUsable()) 4743 return 0; 4744 // UB + ST 4745 CombNextUB = 4746 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 4747 if (!CombNextUB.isUsable()) 4748 return 0; 4749 // UB = UB + ST 4750 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 4751 CombNextUB.get()); 4752 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get()); 4753 if (!CombNextUB.isUsable()) 4754 return 0; 4755 } 4756 } 4757 4758 // Create increment expression for distribute loop when combined in a same 4759 // directive with for as IV = IV + ST; ensure upper bound expression based 4760 // on PrevUB instead of NumIterations - used to implement 'for' when found 4761 // in combination with 'distribute', like in 'distribute parallel for' 4762 SourceLocation DistIncLoc; 4763 ExprResult DistCond, DistInc, PrevEUB; 4764 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4765 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()); 4766 assert(DistCond.isUsable() && "distribute cond expr was not built"); 4767 4768 DistInc = 4769 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 4770 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4771 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 4772 DistInc.get()); 4773 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get()); 4774 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4775 4776 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 4777 // construct 4778 SourceLocation DistEUBLoc; 4779 ExprResult IsUBGreater = 4780 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 4781 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4782 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 4783 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 4784 CondOp.get()); 4785 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get()); 4786 } 4787 4788 // Build updates and final values of the loop counters. 4789 bool HasErrors = false; 4790 Built.Counters.resize(NestedLoopCount); 4791 Built.Inits.resize(NestedLoopCount); 4792 Built.Updates.resize(NestedLoopCount); 4793 Built.Finals.resize(NestedLoopCount); 4794 SmallVector<Expr *, 4> LoopMultipliers; 4795 { 4796 ExprResult Div; 4797 // Go from inner nested loop to outer. 4798 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4799 LoopIterationSpace &IS = IterSpaces[Cnt]; 4800 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 4801 // Build: Iter = (IV / Div) % IS.NumIters 4802 // where Div is product of previous iterations' IS.NumIters. 4803 ExprResult Iter; 4804 if (Div.isUsable()) { 4805 Iter = 4806 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 4807 } else { 4808 Iter = IV; 4809 assert((Cnt == (int)NestedLoopCount - 1) && 4810 "unusable div expected on first iteration only"); 4811 } 4812 4813 if (Cnt != 0 && Iter.isUsable()) 4814 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 4815 IS.NumIterations); 4816 if (!Iter.isUsable()) { 4817 HasErrors = true; 4818 break; 4819 } 4820 4821 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 4822 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 4823 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 4824 IS.CounterVar->getExprLoc(), 4825 /*RefersToCapture=*/true); 4826 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 4827 IS.CounterInit, Captures); 4828 if (!Init.isUsable()) { 4829 HasErrors = true; 4830 break; 4831 } 4832 ExprResult Update = BuildCounterUpdate( 4833 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 4834 IS.CounterStep, IS.Subtract, &Captures); 4835 if (!Update.isUsable()) { 4836 HasErrors = true; 4837 break; 4838 } 4839 4840 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 4841 ExprResult Final = BuildCounterUpdate( 4842 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 4843 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 4844 if (!Final.isUsable()) { 4845 HasErrors = true; 4846 break; 4847 } 4848 4849 // Build Div for the next iteration: Div <- Div * IS.NumIters 4850 if (Cnt != 0) { 4851 if (Div.isUnset()) 4852 Div = IS.NumIterations; 4853 else 4854 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 4855 IS.NumIterations); 4856 4857 // Add parentheses (for debugging purposes only). 4858 if (Div.isUsable()) 4859 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 4860 if (!Div.isUsable()) { 4861 HasErrors = true; 4862 break; 4863 } 4864 LoopMultipliers.push_back(Div.get()); 4865 } 4866 if (!Update.isUsable() || !Final.isUsable()) { 4867 HasErrors = true; 4868 break; 4869 } 4870 // Save results 4871 Built.Counters[Cnt] = IS.CounterVar; 4872 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 4873 Built.Inits[Cnt] = Init.get(); 4874 Built.Updates[Cnt] = Update.get(); 4875 Built.Finals[Cnt] = Final.get(); 4876 } 4877 } 4878 4879 if (HasErrors) 4880 return 0; 4881 4882 // Save results 4883 Built.IterationVarRef = IV.get(); 4884 Built.LastIteration = LastIteration.get(); 4885 Built.NumIterations = NumIterations.get(); 4886 Built.CalcLastIteration = 4887 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 4888 Built.PreCond = PreCond.get(); 4889 Built.PreInits = buildPreInits(C, Captures); 4890 Built.Cond = Cond.get(); 4891 Built.Init = Init.get(); 4892 Built.Inc = Inc.get(); 4893 Built.LB = LB.get(); 4894 Built.UB = UB.get(); 4895 Built.IL = IL.get(); 4896 Built.ST = ST.get(); 4897 Built.EUB = EUB.get(); 4898 Built.NLB = NextLB.get(); 4899 Built.NUB = NextUB.get(); 4900 Built.PrevLB = PrevLB.get(); 4901 Built.PrevUB = PrevUB.get(); 4902 Built.DistInc = DistInc.get(); 4903 Built.PrevEUB = PrevEUB.get(); 4904 Built.DistCombinedFields.LB = CombLB.get(); 4905 Built.DistCombinedFields.UB = CombUB.get(); 4906 Built.DistCombinedFields.EUB = CombEUB.get(); 4907 Built.DistCombinedFields.Init = CombInit.get(); 4908 Built.DistCombinedFields.Cond = CombCond.get(); 4909 Built.DistCombinedFields.NLB = CombNextLB.get(); 4910 Built.DistCombinedFields.NUB = CombNextUB.get(); 4911 4912 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 4913 // Fill data for doacross depend clauses. 4914 for (auto Pair : DSA.getDoacrossDependClauses()) { 4915 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 4916 Pair.first->setCounterValue(CounterVal); 4917 else { 4918 if (NestedLoopCount != Pair.second.size() || 4919 NestedLoopCount != LoopMultipliers.size() + 1) { 4920 // Erroneous case - clause has some problems. 4921 Pair.first->setCounterValue(CounterVal); 4922 continue; 4923 } 4924 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 4925 auto I = Pair.second.rbegin(); 4926 auto IS = IterSpaces.rbegin(); 4927 auto ILM = LoopMultipliers.rbegin(); 4928 Expr *UpCounterVal = CounterVal; 4929 Expr *Multiplier = nullptr; 4930 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4931 if (I->first) { 4932 assert(IS->CounterStep); 4933 Expr *NormalizedOffset = 4934 SemaRef 4935 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 4936 I->first, IS->CounterStep) 4937 .get(); 4938 if (Multiplier) { 4939 NormalizedOffset = 4940 SemaRef 4941 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 4942 NormalizedOffset, Multiplier) 4943 .get(); 4944 } 4945 assert(I->second == OO_Plus || I->second == OO_Minus); 4946 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 4947 UpCounterVal = SemaRef 4948 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 4949 UpCounterVal, NormalizedOffset) 4950 .get(); 4951 } 4952 Multiplier = *ILM; 4953 ++I; 4954 ++IS; 4955 ++ILM; 4956 } 4957 Pair.first->setCounterValue(UpCounterVal); 4958 } 4959 } 4960 4961 return NestedLoopCount; 4962 } 4963 4964 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 4965 auto CollapseClauses = 4966 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 4967 if (CollapseClauses.begin() != CollapseClauses.end()) 4968 return (*CollapseClauses.begin())->getNumForLoops(); 4969 return nullptr; 4970 } 4971 4972 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 4973 auto OrderedClauses = 4974 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 4975 if (OrderedClauses.begin() != OrderedClauses.end()) 4976 return (*OrderedClauses.begin())->getNumForLoops(); 4977 return nullptr; 4978 } 4979 4980 static bool checkSimdlenSafelenSpecified(Sema &S, 4981 const ArrayRef<OMPClause *> Clauses) { 4982 OMPSafelenClause *Safelen = nullptr; 4983 OMPSimdlenClause *Simdlen = nullptr; 4984 4985 for (auto *Clause : Clauses) { 4986 if (Clause->getClauseKind() == OMPC_safelen) 4987 Safelen = cast<OMPSafelenClause>(Clause); 4988 else if (Clause->getClauseKind() == OMPC_simdlen) 4989 Simdlen = cast<OMPSimdlenClause>(Clause); 4990 if (Safelen && Simdlen) 4991 break; 4992 } 4993 4994 if (Simdlen && Safelen) { 4995 llvm::APSInt SimdlenRes, SafelenRes; 4996 auto SimdlenLength = Simdlen->getSimdlen(); 4997 auto SafelenLength = Safelen->getSafelen(); 4998 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 4999 SimdlenLength->isInstantiationDependent() || 5000 SimdlenLength->containsUnexpandedParameterPack()) 5001 return false; 5002 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 5003 SafelenLength->isInstantiationDependent() || 5004 SafelenLength->containsUnexpandedParameterPack()) 5005 return false; 5006 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 5007 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 5008 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 5009 // If both simdlen and safelen clauses are specified, the value of the 5010 // simdlen parameter must be less than or equal to the value of the safelen 5011 // parameter. 5012 if (SimdlenRes > SafelenRes) { 5013 S.Diag(SimdlenLength->getExprLoc(), 5014 diag::err_omp_wrong_simdlen_safelen_values) 5015 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 5016 return true; 5017 } 5018 } 5019 return false; 5020 } 5021 5022 StmtResult Sema::ActOnOpenMPSimdDirective( 5023 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5024 SourceLocation EndLoc, 5025 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5026 if (!AStmt) 5027 return StmtError(); 5028 5029 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5030 OMPLoopDirective::HelperExprs B; 5031 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5032 // define the nested loops number. 5033 unsigned NestedLoopCount = CheckOpenMPLoop( 5034 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5035 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5036 if (NestedLoopCount == 0) 5037 return StmtError(); 5038 5039 assert((CurContext->isDependentContext() || B.builtAll()) && 5040 "omp simd loop exprs were not built"); 5041 5042 if (!CurContext->isDependentContext()) { 5043 // Finalize the clauses that need pre-built expressions for CodeGen. 5044 for (auto C : Clauses) { 5045 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5046 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5047 B.NumIterations, *this, CurScope, 5048 DSAStack)) 5049 return StmtError(); 5050 } 5051 } 5052 5053 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5054 return StmtError(); 5055 5056 getCurFunction()->setHasBranchProtectedScope(); 5057 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5058 Clauses, AStmt, B); 5059 } 5060 5061 StmtResult Sema::ActOnOpenMPForDirective( 5062 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5063 SourceLocation EndLoc, 5064 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5065 if (!AStmt) 5066 return StmtError(); 5067 5068 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5069 OMPLoopDirective::HelperExprs B; 5070 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5071 // define the nested loops number. 5072 unsigned NestedLoopCount = CheckOpenMPLoop( 5073 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5074 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5075 if (NestedLoopCount == 0) 5076 return StmtError(); 5077 5078 assert((CurContext->isDependentContext() || B.builtAll()) && 5079 "omp for loop exprs were not built"); 5080 5081 if (!CurContext->isDependentContext()) { 5082 // Finalize the clauses that need pre-built expressions for CodeGen. 5083 for (auto C : Clauses) { 5084 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5085 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5086 B.NumIterations, *this, CurScope, 5087 DSAStack)) 5088 return StmtError(); 5089 } 5090 } 5091 5092 getCurFunction()->setHasBranchProtectedScope(); 5093 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5094 Clauses, AStmt, B, DSAStack->isCancelRegion()); 5095 } 5096 5097 StmtResult Sema::ActOnOpenMPForSimdDirective( 5098 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5099 SourceLocation EndLoc, 5100 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5101 if (!AStmt) 5102 return StmtError(); 5103 5104 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5105 OMPLoopDirective::HelperExprs B; 5106 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5107 // define the nested loops number. 5108 unsigned NestedLoopCount = 5109 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 5110 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5111 VarsWithImplicitDSA, B); 5112 if (NestedLoopCount == 0) 5113 return StmtError(); 5114 5115 assert((CurContext->isDependentContext() || B.builtAll()) && 5116 "omp for simd loop exprs were not built"); 5117 5118 if (!CurContext->isDependentContext()) { 5119 // Finalize the clauses that need pre-built expressions for CodeGen. 5120 for (auto C : Clauses) { 5121 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5122 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5123 B.NumIterations, *this, CurScope, 5124 DSAStack)) 5125 return StmtError(); 5126 } 5127 } 5128 5129 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5130 return StmtError(); 5131 5132 getCurFunction()->setHasBranchProtectedScope(); 5133 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5134 Clauses, AStmt, B); 5135 } 5136 5137 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 5138 Stmt *AStmt, 5139 SourceLocation StartLoc, 5140 SourceLocation EndLoc) { 5141 if (!AStmt) 5142 return StmtError(); 5143 5144 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5145 auto BaseStmt = AStmt; 5146 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5147 BaseStmt = CS->getCapturedStmt(); 5148 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5149 auto S = C->children(); 5150 if (S.begin() == S.end()) 5151 return StmtError(); 5152 // All associated statements must be '#pragma omp section' except for 5153 // the first one. 5154 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5155 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5156 if (SectionStmt) 5157 Diag(SectionStmt->getLocStart(), 5158 diag::err_omp_sections_substmt_not_section); 5159 return StmtError(); 5160 } 5161 cast<OMPSectionDirective>(SectionStmt) 5162 ->setHasCancel(DSAStack->isCancelRegion()); 5163 } 5164 } else { 5165 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 5166 return StmtError(); 5167 } 5168 5169 getCurFunction()->setHasBranchProtectedScope(); 5170 5171 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5172 DSAStack->isCancelRegion()); 5173 } 5174 5175 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 5176 SourceLocation StartLoc, 5177 SourceLocation EndLoc) { 5178 if (!AStmt) 5179 return StmtError(); 5180 5181 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5182 5183 getCurFunction()->setHasBranchProtectedScope(); 5184 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 5185 5186 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 5187 DSAStack->isCancelRegion()); 5188 } 5189 5190 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 5191 Stmt *AStmt, 5192 SourceLocation StartLoc, 5193 SourceLocation EndLoc) { 5194 if (!AStmt) 5195 return StmtError(); 5196 5197 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5198 5199 getCurFunction()->setHasBranchProtectedScope(); 5200 5201 // OpenMP [2.7.3, single Construct, Restrictions] 5202 // The copyprivate clause must not be used with the nowait clause. 5203 OMPClause *Nowait = nullptr; 5204 OMPClause *Copyprivate = nullptr; 5205 for (auto *Clause : Clauses) { 5206 if (Clause->getClauseKind() == OMPC_nowait) 5207 Nowait = Clause; 5208 else if (Clause->getClauseKind() == OMPC_copyprivate) 5209 Copyprivate = Clause; 5210 if (Copyprivate && Nowait) { 5211 Diag(Copyprivate->getLocStart(), 5212 diag::err_omp_single_copyprivate_with_nowait); 5213 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 5214 return StmtError(); 5215 } 5216 } 5217 5218 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5219 } 5220 5221 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 5222 SourceLocation StartLoc, 5223 SourceLocation EndLoc) { 5224 if (!AStmt) 5225 return StmtError(); 5226 5227 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5228 5229 getCurFunction()->setHasBranchProtectedScope(); 5230 5231 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 5232 } 5233 5234 StmtResult Sema::ActOnOpenMPCriticalDirective( 5235 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 5236 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5237 if (!AStmt) 5238 return StmtError(); 5239 5240 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5241 5242 bool ErrorFound = false; 5243 llvm::APSInt Hint; 5244 SourceLocation HintLoc; 5245 bool DependentHint = false; 5246 for (auto *C : Clauses) { 5247 if (C->getClauseKind() == OMPC_hint) { 5248 if (!DirName.getName()) { 5249 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 5250 ErrorFound = true; 5251 } 5252 Expr *E = cast<OMPHintClause>(C)->getHint(); 5253 if (E->isTypeDependent() || E->isValueDependent() || 5254 E->isInstantiationDependent()) 5255 DependentHint = true; 5256 else { 5257 Hint = E->EvaluateKnownConstInt(Context); 5258 HintLoc = C->getLocStart(); 5259 } 5260 } 5261 } 5262 if (ErrorFound) 5263 return StmtError(); 5264 auto Pair = DSAStack->getCriticalWithHint(DirName); 5265 if (Pair.first && DirName.getName() && !DependentHint) { 5266 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 5267 Diag(StartLoc, diag::err_omp_critical_with_hint); 5268 if (HintLoc.isValid()) { 5269 Diag(HintLoc, diag::note_omp_critical_hint_here) 5270 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 5271 } else 5272 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 5273 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 5274 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 5275 << 1 5276 << C->getHint()->EvaluateKnownConstInt(Context).toString( 5277 /*Radix=*/10, /*Signed=*/false); 5278 } else 5279 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 5280 } 5281 } 5282 5283 getCurFunction()->setHasBranchProtectedScope(); 5284 5285 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 5286 Clauses, AStmt); 5287 if (!Pair.first && DirName.getName() && !DependentHint) 5288 DSAStack->addCriticalWithHint(Dir, Hint); 5289 return Dir; 5290 } 5291 5292 StmtResult Sema::ActOnOpenMPParallelForDirective( 5293 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5294 SourceLocation EndLoc, 5295 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5296 if (!AStmt) 5297 return StmtError(); 5298 5299 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5300 // 1.2.2 OpenMP Language Terminology 5301 // Structured block - An executable statement with a single entry at the 5302 // top and a single exit at the bottom. 5303 // The point of exit cannot be a branch out of the structured block. 5304 // longjmp() and throw() must not violate the entry/exit criteria. 5305 CS->getCapturedDecl()->setNothrow(); 5306 5307 OMPLoopDirective::HelperExprs B; 5308 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5309 // define the nested loops number. 5310 unsigned NestedLoopCount = 5311 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 5312 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5313 VarsWithImplicitDSA, B); 5314 if (NestedLoopCount == 0) 5315 return StmtError(); 5316 5317 assert((CurContext->isDependentContext() || B.builtAll()) && 5318 "omp parallel for loop exprs were not built"); 5319 5320 if (!CurContext->isDependentContext()) { 5321 // Finalize the clauses that need pre-built expressions for CodeGen. 5322 for (auto C : Clauses) { 5323 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5324 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5325 B.NumIterations, *this, CurScope, 5326 DSAStack)) 5327 return StmtError(); 5328 } 5329 } 5330 5331 getCurFunction()->setHasBranchProtectedScope(); 5332 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 5333 NestedLoopCount, Clauses, AStmt, B, 5334 DSAStack->isCancelRegion()); 5335 } 5336 5337 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 5338 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5339 SourceLocation EndLoc, 5340 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5341 if (!AStmt) 5342 return StmtError(); 5343 5344 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5345 // 1.2.2 OpenMP Language Terminology 5346 // Structured block - An executable statement with a single entry at the 5347 // top and a single exit at the bottom. 5348 // The point of exit cannot be a branch out of the structured block. 5349 // longjmp() and throw() must not violate the entry/exit criteria. 5350 CS->getCapturedDecl()->setNothrow(); 5351 5352 OMPLoopDirective::HelperExprs B; 5353 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5354 // define the nested loops number. 5355 unsigned NestedLoopCount = 5356 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 5357 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5358 VarsWithImplicitDSA, B); 5359 if (NestedLoopCount == 0) 5360 return StmtError(); 5361 5362 if (!CurContext->isDependentContext()) { 5363 // Finalize the clauses that need pre-built expressions for CodeGen. 5364 for (auto C : Clauses) { 5365 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5366 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5367 B.NumIterations, *this, CurScope, 5368 DSAStack)) 5369 return StmtError(); 5370 } 5371 } 5372 5373 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5374 return StmtError(); 5375 5376 getCurFunction()->setHasBranchProtectedScope(); 5377 return OMPParallelForSimdDirective::Create( 5378 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 5379 } 5380 5381 StmtResult 5382 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 5383 Stmt *AStmt, SourceLocation StartLoc, 5384 SourceLocation EndLoc) { 5385 if (!AStmt) 5386 return StmtError(); 5387 5388 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5389 auto BaseStmt = AStmt; 5390 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5391 BaseStmt = CS->getCapturedStmt(); 5392 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5393 auto S = C->children(); 5394 if (S.begin() == S.end()) 5395 return StmtError(); 5396 // All associated statements must be '#pragma omp section' except for 5397 // the first one. 5398 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5399 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5400 if (SectionStmt) 5401 Diag(SectionStmt->getLocStart(), 5402 diag::err_omp_parallel_sections_substmt_not_section); 5403 return StmtError(); 5404 } 5405 cast<OMPSectionDirective>(SectionStmt) 5406 ->setHasCancel(DSAStack->isCancelRegion()); 5407 } 5408 } else { 5409 Diag(AStmt->getLocStart(), 5410 diag::err_omp_parallel_sections_not_compound_stmt); 5411 return StmtError(); 5412 } 5413 5414 getCurFunction()->setHasBranchProtectedScope(); 5415 5416 return OMPParallelSectionsDirective::Create( 5417 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 5418 } 5419 5420 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 5421 Stmt *AStmt, SourceLocation StartLoc, 5422 SourceLocation EndLoc) { 5423 if (!AStmt) 5424 return StmtError(); 5425 5426 auto *CS = cast<CapturedStmt>(AStmt); 5427 // 1.2.2 OpenMP Language Terminology 5428 // Structured block - An executable statement with a single entry at the 5429 // top and a single exit at the bottom. 5430 // The point of exit cannot be a branch out of the structured block. 5431 // longjmp() and throw() must not violate the entry/exit criteria. 5432 CS->getCapturedDecl()->setNothrow(); 5433 5434 getCurFunction()->setHasBranchProtectedScope(); 5435 5436 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5437 DSAStack->isCancelRegion()); 5438 } 5439 5440 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 5441 SourceLocation EndLoc) { 5442 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 5443 } 5444 5445 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 5446 SourceLocation EndLoc) { 5447 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 5448 } 5449 5450 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 5451 SourceLocation EndLoc) { 5452 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 5453 } 5454 5455 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 5456 Stmt *AStmt, 5457 SourceLocation StartLoc, 5458 SourceLocation EndLoc) { 5459 if (!AStmt) 5460 return StmtError(); 5461 5462 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5463 5464 getCurFunction()->setHasBranchProtectedScope(); 5465 5466 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 5467 AStmt, 5468 DSAStack->getTaskgroupReductionRef()); 5469 } 5470 5471 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 5472 SourceLocation StartLoc, 5473 SourceLocation EndLoc) { 5474 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 5475 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 5476 } 5477 5478 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 5479 Stmt *AStmt, 5480 SourceLocation StartLoc, 5481 SourceLocation EndLoc) { 5482 OMPClause *DependFound = nullptr; 5483 OMPClause *DependSourceClause = nullptr; 5484 OMPClause *DependSinkClause = nullptr; 5485 bool ErrorFound = false; 5486 OMPThreadsClause *TC = nullptr; 5487 OMPSIMDClause *SC = nullptr; 5488 for (auto *C : Clauses) { 5489 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 5490 DependFound = C; 5491 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 5492 if (DependSourceClause) { 5493 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 5494 << getOpenMPDirectiveName(OMPD_ordered) 5495 << getOpenMPClauseName(OMPC_depend) << 2; 5496 ErrorFound = true; 5497 } else 5498 DependSourceClause = C; 5499 if (DependSinkClause) { 5500 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5501 << 0; 5502 ErrorFound = true; 5503 } 5504 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 5505 if (DependSourceClause) { 5506 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5507 << 1; 5508 ErrorFound = true; 5509 } 5510 DependSinkClause = C; 5511 } 5512 } else if (C->getClauseKind() == OMPC_threads) 5513 TC = cast<OMPThreadsClause>(C); 5514 else if (C->getClauseKind() == OMPC_simd) 5515 SC = cast<OMPSIMDClause>(C); 5516 } 5517 if (!ErrorFound && !SC && 5518 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 5519 // OpenMP [2.8.1,simd Construct, Restrictions] 5520 // An ordered construct with the simd clause is the only OpenMP construct 5521 // that can appear in the simd region. 5522 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 5523 ErrorFound = true; 5524 } else if (DependFound && (TC || SC)) { 5525 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 5526 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 5527 ErrorFound = true; 5528 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 5529 Diag(DependFound->getLocStart(), 5530 diag::err_omp_ordered_directive_without_param); 5531 ErrorFound = true; 5532 } else if (TC || Clauses.empty()) { 5533 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 5534 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 5535 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 5536 << (TC != nullptr); 5537 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 5538 ErrorFound = true; 5539 } 5540 } 5541 if ((!AStmt && !DependFound) || ErrorFound) 5542 return StmtError(); 5543 5544 if (AStmt) { 5545 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5546 5547 getCurFunction()->setHasBranchProtectedScope(); 5548 } 5549 5550 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5551 } 5552 5553 namespace { 5554 /// \brief Helper class for checking expression in 'omp atomic [update]' 5555 /// construct. 5556 class OpenMPAtomicUpdateChecker { 5557 /// \brief Error results for atomic update expressions. 5558 enum ExprAnalysisErrorCode { 5559 /// \brief A statement is not an expression statement. 5560 NotAnExpression, 5561 /// \brief Expression is not builtin binary or unary operation. 5562 NotABinaryOrUnaryExpression, 5563 /// \brief Unary operation is not post-/pre- increment/decrement operation. 5564 NotAnUnaryIncDecExpression, 5565 /// \brief An expression is not of scalar type. 5566 NotAScalarType, 5567 /// \brief A binary operation is not an assignment operation. 5568 NotAnAssignmentOp, 5569 /// \brief RHS part of the binary operation is not a binary expression. 5570 NotABinaryExpression, 5571 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 5572 /// expression. 5573 NotABinaryOperator, 5574 /// \brief RHS binary operation does not have reference to the updated LHS 5575 /// part. 5576 NotAnUpdateExpression, 5577 /// \brief No errors is found. 5578 NoError 5579 }; 5580 /// \brief Reference to Sema. 5581 Sema &SemaRef; 5582 /// \brief A location for note diagnostics (when error is found). 5583 SourceLocation NoteLoc; 5584 /// \brief 'x' lvalue part of the source atomic expression. 5585 Expr *X; 5586 /// \brief 'expr' rvalue part of the source atomic expression. 5587 Expr *E; 5588 /// \brief Helper expression of the form 5589 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5590 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5591 Expr *UpdateExpr; 5592 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 5593 /// important for non-associative operations. 5594 bool IsXLHSInRHSPart; 5595 BinaryOperatorKind Op; 5596 SourceLocation OpLoc; 5597 /// \brief true if the source expression is a postfix unary operation, false 5598 /// if it is a prefix unary operation. 5599 bool IsPostfixUpdate; 5600 5601 public: 5602 OpenMPAtomicUpdateChecker(Sema &SemaRef) 5603 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 5604 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 5605 /// \brief Check specified statement that it is suitable for 'atomic update' 5606 /// constructs and extract 'x', 'expr' and Operation from the original 5607 /// expression. If DiagId and NoteId == 0, then only check is performed 5608 /// without error notification. 5609 /// \param DiagId Diagnostic which should be emitted if error is found. 5610 /// \param NoteId Diagnostic note for the main error message. 5611 /// \return true if statement is not an update expression, false otherwise. 5612 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 5613 /// \brief Return the 'x' lvalue part of the source atomic expression. 5614 Expr *getX() const { return X; } 5615 /// \brief Return the 'expr' rvalue part of the source atomic expression. 5616 Expr *getExpr() const { return E; } 5617 /// \brief Return the update expression used in calculation of the updated 5618 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5619 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5620 Expr *getUpdateExpr() const { return UpdateExpr; } 5621 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 5622 /// false otherwise. 5623 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 5624 5625 /// \brief true if the source expression is a postfix unary operation, false 5626 /// if it is a prefix unary operation. 5627 bool isPostfixUpdate() const { return IsPostfixUpdate; } 5628 5629 private: 5630 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 5631 unsigned NoteId = 0); 5632 }; 5633 } // namespace 5634 5635 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 5636 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 5637 ExprAnalysisErrorCode ErrorFound = NoError; 5638 SourceLocation ErrorLoc, NoteLoc; 5639 SourceRange ErrorRange, NoteRange; 5640 // Allowed constructs are: 5641 // x = x binop expr; 5642 // x = expr binop x; 5643 if (AtomicBinOp->getOpcode() == BO_Assign) { 5644 X = AtomicBinOp->getLHS(); 5645 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 5646 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 5647 if (AtomicInnerBinOp->isMultiplicativeOp() || 5648 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 5649 AtomicInnerBinOp->isBitwiseOp()) { 5650 Op = AtomicInnerBinOp->getOpcode(); 5651 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 5652 auto *LHS = AtomicInnerBinOp->getLHS(); 5653 auto *RHS = AtomicInnerBinOp->getRHS(); 5654 llvm::FoldingSetNodeID XId, LHSId, RHSId; 5655 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 5656 /*Canonical=*/true); 5657 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 5658 /*Canonical=*/true); 5659 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 5660 /*Canonical=*/true); 5661 if (XId == LHSId) { 5662 E = RHS; 5663 IsXLHSInRHSPart = true; 5664 } else if (XId == RHSId) { 5665 E = LHS; 5666 IsXLHSInRHSPart = false; 5667 } else { 5668 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5669 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5670 NoteLoc = X->getExprLoc(); 5671 NoteRange = X->getSourceRange(); 5672 ErrorFound = NotAnUpdateExpression; 5673 } 5674 } else { 5675 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5676 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5677 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 5678 NoteRange = SourceRange(NoteLoc, NoteLoc); 5679 ErrorFound = NotABinaryOperator; 5680 } 5681 } else { 5682 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 5683 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 5684 ErrorFound = NotABinaryExpression; 5685 } 5686 } else { 5687 ErrorLoc = AtomicBinOp->getExprLoc(); 5688 ErrorRange = AtomicBinOp->getSourceRange(); 5689 NoteLoc = AtomicBinOp->getOperatorLoc(); 5690 NoteRange = SourceRange(NoteLoc, NoteLoc); 5691 ErrorFound = NotAnAssignmentOp; 5692 } 5693 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5694 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5695 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5696 return true; 5697 } else if (SemaRef.CurContext->isDependentContext()) 5698 E = X = UpdateExpr = nullptr; 5699 return ErrorFound != NoError; 5700 } 5701 5702 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 5703 unsigned NoteId) { 5704 ExprAnalysisErrorCode ErrorFound = NoError; 5705 SourceLocation ErrorLoc, NoteLoc; 5706 SourceRange ErrorRange, NoteRange; 5707 // Allowed constructs are: 5708 // x++; 5709 // x--; 5710 // ++x; 5711 // --x; 5712 // x binop= expr; 5713 // x = x binop expr; 5714 // x = expr binop x; 5715 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 5716 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 5717 if (AtomicBody->getType()->isScalarType() || 5718 AtomicBody->isInstantiationDependent()) { 5719 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 5720 AtomicBody->IgnoreParenImpCasts())) { 5721 // Check for Compound Assignment Operation 5722 Op = BinaryOperator::getOpForCompoundAssignment( 5723 AtomicCompAssignOp->getOpcode()); 5724 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 5725 E = AtomicCompAssignOp->getRHS(); 5726 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 5727 IsXLHSInRHSPart = true; 5728 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 5729 AtomicBody->IgnoreParenImpCasts())) { 5730 // Check for Binary Operation 5731 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 5732 return true; 5733 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 5734 AtomicBody->IgnoreParenImpCasts())) { 5735 // Check for Unary Operation 5736 if (AtomicUnaryOp->isIncrementDecrementOp()) { 5737 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 5738 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 5739 OpLoc = AtomicUnaryOp->getOperatorLoc(); 5740 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 5741 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 5742 IsXLHSInRHSPart = true; 5743 } else { 5744 ErrorFound = NotAnUnaryIncDecExpression; 5745 ErrorLoc = AtomicUnaryOp->getExprLoc(); 5746 ErrorRange = AtomicUnaryOp->getSourceRange(); 5747 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 5748 NoteRange = SourceRange(NoteLoc, NoteLoc); 5749 } 5750 } else if (!AtomicBody->isInstantiationDependent()) { 5751 ErrorFound = NotABinaryOrUnaryExpression; 5752 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 5753 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 5754 } 5755 } else { 5756 ErrorFound = NotAScalarType; 5757 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 5758 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5759 } 5760 } else { 5761 ErrorFound = NotAnExpression; 5762 NoteLoc = ErrorLoc = S->getLocStart(); 5763 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5764 } 5765 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5766 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5767 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5768 return true; 5769 } else if (SemaRef.CurContext->isDependentContext()) 5770 E = X = UpdateExpr = nullptr; 5771 if (ErrorFound == NoError && E && X) { 5772 // Build an update expression of form 'OpaqueValueExpr(x) binop 5773 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 5774 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 5775 auto *OVEX = new (SemaRef.getASTContext()) 5776 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 5777 auto *OVEExpr = new (SemaRef.getASTContext()) 5778 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 5779 auto Update = 5780 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 5781 IsXLHSInRHSPart ? OVEExpr : OVEX); 5782 if (Update.isInvalid()) 5783 return true; 5784 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 5785 Sema::AA_Casting); 5786 if (Update.isInvalid()) 5787 return true; 5788 UpdateExpr = Update.get(); 5789 } 5790 return ErrorFound != NoError; 5791 } 5792 5793 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 5794 Stmt *AStmt, 5795 SourceLocation StartLoc, 5796 SourceLocation EndLoc) { 5797 if (!AStmt) 5798 return StmtError(); 5799 5800 auto *CS = cast<CapturedStmt>(AStmt); 5801 // 1.2.2 OpenMP Language Terminology 5802 // Structured block - An executable statement with a single entry at the 5803 // top and a single exit at the bottom. 5804 // The point of exit cannot be a branch out of the structured block. 5805 // longjmp() and throw() must not violate the entry/exit criteria. 5806 OpenMPClauseKind AtomicKind = OMPC_unknown; 5807 SourceLocation AtomicKindLoc; 5808 for (auto *C : Clauses) { 5809 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 5810 C->getClauseKind() == OMPC_update || 5811 C->getClauseKind() == OMPC_capture) { 5812 if (AtomicKind != OMPC_unknown) { 5813 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 5814 << SourceRange(C->getLocStart(), C->getLocEnd()); 5815 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 5816 << getOpenMPClauseName(AtomicKind); 5817 } else { 5818 AtomicKind = C->getClauseKind(); 5819 AtomicKindLoc = C->getLocStart(); 5820 } 5821 } 5822 } 5823 5824 auto Body = CS->getCapturedStmt(); 5825 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 5826 Body = EWC->getSubExpr(); 5827 5828 Expr *X = nullptr; 5829 Expr *V = nullptr; 5830 Expr *E = nullptr; 5831 Expr *UE = nullptr; 5832 bool IsXLHSInRHSPart = false; 5833 bool IsPostfixUpdate = false; 5834 // OpenMP [2.12.6, atomic Construct] 5835 // In the next expressions: 5836 // * x and v (as applicable) are both l-value expressions with scalar type. 5837 // * During the execution of an atomic region, multiple syntactic 5838 // occurrences of x must designate the same storage location. 5839 // * Neither of v and expr (as applicable) may access the storage location 5840 // designated by x. 5841 // * Neither of x and expr (as applicable) may access the storage location 5842 // designated by v. 5843 // * expr is an expression with scalar type. 5844 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 5845 // * binop, binop=, ++, and -- are not overloaded operators. 5846 // * The expression x binop expr must be numerically equivalent to x binop 5847 // (expr). This requirement is satisfied if the operators in expr have 5848 // precedence greater than binop, or by using parentheses around expr or 5849 // subexpressions of expr. 5850 // * The expression expr binop x must be numerically equivalent to (expr) 5851 // binop x. This requirement is satisfied if the operators in expr have 5852 // precedence equal to or greater than binop, or by using parentheses around 5853 // expr or subexpressions of expr. 5854 // * For forms that allow multiple occurrences of x, the number of times 5855 // that x is evaluated is unspecified. 5856 if (AtomicKind == OMPC_read) { 5857 enum { 5858 NotAnExpression, 5859 NotAnAssignmentOp, 5860 NotAScalarType, 5861 NotAnLValue, 5862 NoError 5863 } ErrorFound = NoError; 5864 SourceLocation ErrorLoc, NoteLoc; 5865 SourceRange ErrorRange, NoteRange; 5866 // If clause is read: 5867 // v = x; 5868 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5869 auto *AtomicBinOp = 5870 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5871 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5872 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5873 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 5874 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5875 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 5876 if (!X->isLValue() || !V->isLValue()) { 5877 auto NotLValueExpr = X->isLValue() ? V : X; 5878 ErrorFound = NotAnLValue; 5879 ErrorLoc = AtomicBinOp->getExprLoc(); 5880 ErrorRange = AtomicBinOp->getSourceRange(); 5881 NoteLoc = NotLValueExpr->getExprLoc(); 5882 NoteRange = NotLValueExpr->getSourceRange(); 5883 } 5884 } else if (!X->isInstantiationDependent() || 5885 !V->isInstantiationDependent()) { 5886 auto NotScalarExpr = 5887 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5888 ? V 5889 : X; 5890 ErrorFound = NotAScalarType; 5891 ErrorLoc = AtomicBinOp->getExprLoc(); 5892 ErrorRange = AtomicBinOp->getSourceRange(); 5893 NoteLoc = NotScalarExpr->getExprLoc(); 5894 NoteRange = NotScalarExpr->getSourceRange(); 5895 } 5896 } else if (!AtomicBody->isInstantiationDependent()) { 5897 ErrorFound = NotAnAssignmentOp; 5898 ErrorLoc = AtomicBody->getExprLoc(); 5899 ErrorRange = AtomicBody->getSourceRange(); 5900 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5901 : AtomicBody->getExprLoc(); 5902 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5903 : AtomicBody->getSourceRange(); 5904 } 5905 } else { 5906 ErrorFound = NotAnExpression; 5907 NoteLoc = ErrorLoc = Body->getLocStart(); 5908 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5909 } 5910 if (ErrorFound != NoError) { 5911 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 5912 << ErrorRange; 5913 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5914 << NoteRange; 5915 return StmtError(); 5916 } else if (CurContext->isDependentContext()) 5917 V = X = nullptr; 5918 } else if (AtomicKind == OMPC_write) { 5919 enum { 5920 NotAnExpression, 5921 NotAnAssignmentOp, 5922 NotAScalarType, 5923 NotAnLValue, 5924 NoError 5925 } ErrorFound = NoError; 5926 SourceLocation ErrorLoc, NoteLoc; 5927 SourceRange ErrorRange, NoteRange; 5928 // If clause is write: 5929 // x = expr; 5930 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5931 auto *AtomicBinOp = 5932 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5933 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5934 X = AtomicBinOp->getLHS(); 5935 E = AtomicBinOp->getRHS(); 5936 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5937 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 5938 if (!X->isLValue()) { 5939 ErrorFound = NotAnLValue; 5940 ErrorLoc = AtomicBinOp->getExprLoc(); 5941 ErrorRange = AtomicBinOp->getSourceRange(); 5942 NoteLoc = X->getExprLoc(); 5943 NoteRange = X->getSourceRange(); 5944 } 5945 } else if (!X->isInstantiationDependent() || 5946 !E->isInstantiationDependent()) { 5947 auto NotScalarExpr = 5948 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5949 ? E 5950 : X; 5951 ErrorFound = NotAScalarType; 5952 ErrorLoc = AtomicBinOp->getExprLoc(); 5953 ErrorRange = AtomicBinOp->getSourceRange(); 5954 NoteLoc = NotScalarExpr->getExprLoc(); 5955 NoteRange = NotScalarExpr->getSourceRange(); 5956 } 5957 } else if (!AtomicBody->isInstantiationDependent()) { 5958 ErrorFound = NotAnAssignmentOp; 5959 ErrorLoc = AtomicBody->getExprLoc(); 5960 ErrorRange = AtomicBody->getSourceRange(); 5961 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5962 : AtomicBody->getExprLoc(); 5963 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5964 : AtomicBody->getSourceRange(); 5965 } 5966 } else { 5967 ErrorFound = NotAnExpression; 5968 NoteLoc = ErrorLoc = Body->getLocStart(); 5969 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5970 } 5971 if (ErrorFound != NoError) { 5972 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 5973 << ErrorRange; 5974 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5975 << NoteRange; 5976 return StmtError(); 5977 } else if (CurContext->isDependentContext()) 5978 E = X = nullptr; 5979 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 5980 // If clause is update: 5981 // x++; 5982 // x--; 5983 // ++x; 5984 // --x; 5985 // x binop= expr; 5986 // x = x binop expr; 5987 // x = expr binop x; 5988 OpenMPAtomicUpdateChecker Checker(*this); 5989 if (Checker.checkStatement( 5990 Body, (AtomicKind == OMPC_update) 5991 ? diag::err_omp_atomic_update_not_expression_statement 5992 : diag::err_omp_atomic_not_expression_statement, 5993 diag::note_omp_atomic_update)) 5994 return StmtError(); 5995 if (!CurContext->isDependentContext()) { 5996 E = Checker.getExpr(); 5997 X = Checker.getX(); 5998 UE = Checker.getUpdateExpr(); 5999 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6000 } 6001 } else if (AtomicKind == OMPC_capture) { 6002 enum { 6003 NotAnAssignmentOp, 6004 NotACompoundStatement, 6005 NotTwoSubstatements, 6006 NotASpecificExpression, 6007 NoError 6008 } ErrorFound = NoError; 6009 SourceLocation ErrorLoc, NoteLoc; 6010 SourceRange ErrorRange, NoteRange; 6011 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 6012 // If clause is a capture: 6013 // v = x++; 6014 // v = x--; 6015 // v = ++x; 6016 // v = --x; 6017 // v = x binop= expr; 6018 // v = x = x binop expr; 6019 // v = x = expr binop x; 6020 auto *AtomicBinOp = 6021 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6022 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6023 V = AtomicBinOp->getLHS(); 6024 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6025 OpenMPAtomicUpdateChecker Checker(*this); 6026 if (Checker.checkStatement( 6027 Body, diag::err_omp_atomic_capture_not_expression_statement, 6028 diag::note_omp_atomic_update)) 6029 return StmtError(); 6030 E = Checker.getExpr(); 6031 X = Checker.getX(); 6032 UE = Checker.getUpdateExpr(); 6033 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6034 IsPostfixUpdate = Checker.isPostfixUpdate(); 6035 } else if (!AtomicBody->isInstantiationDependent()) { 6036 ErrorLoc = AtomicBody->getExprLoc(); 6037 ErrorRange = AtomicBody->getSourceRange(); 6038 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6039 : AtomicBody->getExprLoc(); 6040 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6041 : AtomicBody->getSourceRange(); 6042 ErrorFound = NotAnAssignmentOp; 6043 } 6044 if (ErrorFound != NoError) { 6045 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 6046 << ErrorRange; 6047 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6048 return StmtError(); 6049 } else if (CurContext->isDependentContext()) { 6050 UE = V = E = X = nullptr; 6051 } 6052 } else { 6053 // If clause is a capture: 6054 // { v = x; x = expr; } 6055 // { v = x; x++; } 6056 // { v = x; x--; } 6057 // { v = x; ++x; } 6058 // { v = x; --x; } 6059 // { v = x; x binop= expr; } 6060 // { v = x; x = x binop expr; } 6061 // { v = x; x = expr binop x; } 6062 // { x++; v = x; } 6063 // { x--; v = x; } 6064 // { ++x; v = x; } 6065 // { --x; v = x; } 6066 // { x binop= expr; v = x; } 6067 // { x = x binop expr; v = x; } 6068 // { x = expr binop x; v = x; } 6069 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 6070 // Check that this is { expr1; expr2; } 6071 if (CS->size() == 2) { 6072 auto *First = CS->body_front(); 6073 auto *Second = CS->body_back(); 6074 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 6075 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 6076 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 6077 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 6078 // Need to find what subexpression is 'v' and what is 'x'. 6079 OpenMPAtomicUpdateChecker Checker(*this); 6080 bool IsUpdateExprFound = !Checker.checkStatement(Second); 6081 BinaryOperator *BinOp = nullptr; 6082 if (IsUpdateExprFound) { 6083 BinOp = dyn_cast<BinaryOperator>(First); 6084 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6085 } 6086 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6087 // { v = x; x++; } 6088 // { v = x; x--; } 6089 // { v = x; ++x; } 6090 // { v = x; --x; } 6091 // { v = x; x binop= expr; } 6092 // { v = x; x = x binop expr; } 6093 // { v = x; x = expr binop x; } 6094 // Check that the first expression has form v = x. 6095 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6096 llvm::FoldingSetNodeID XId, PossibleXId; 6097 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6098 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6099 IsUpdateExprFound = XId == PossibleXId; 6100 if (IsUpdateExprFound) { 6101 V = BinOp->getLHS(); 6102 X = Checker.getX(); 6103 E = Checker.getExpr(); 6104 UE = Checker.getUpdateExpr(); 6105 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6106 IsPostfixUpdate = true; 6107 } 6108 } 6109 if (!IsUpdateExprFound) { 6110 IsUpdateExprFound = !Checker.checkStatement(First); 6111 BinOp = nullptr; 6112 if (IsUpdateExprFound) { 6113 BinOp = dyn_cast<BinaryOperator>(Second); 6114 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6115 } 6116 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6117 // { x++; v = x; } 6118 // { x--; v = x; } 6119 // { ++x; v = x; } 6120 // { --x; v = x; } 6121 // { x binop= expr; v = x; } 6122 // { x = x binop expr; v = x; } 6123 // { x = expr binop x; v = x; } 6124 // Check that the second expression has form v = x. 6125 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6126 llvm::FoldingSetNodeID XId, PossibleXId; 6127 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6128 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6129 IsUpdateExprFound = XId == PossibleXId; 6130 if (IsUpdateExprFound) { 6131 V = BinOp->getLHS(); 6132 X = Checker.getX(); 6133 E = Checker.getExpr(); 6134 UE = Checker.getUpdateExpr(); 6135 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6136 IsPostfixUpdate = false; 6137 } 6138 } 6139 } 6140 if (!IsUpdateExprFound) { 6141 // { v = x; x = expr; } 6142 auto *FirstExpr = dyn_cast<Expr>(First); 6143 auto *SecondExpr = dyn_cast<Expr>(Second); 6144 if (!FirstExpr || !SecondExpr || 6145 !(FirstExpr->isInstantiationDependent() || 6146 SecondExpr->isInstantiationDependent())) { 6147 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 6148 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 6149 ErrorFound = NotAnAssignmentOp; 6150 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 6151 : First->getLocStart(); 6152 NoteRange = ErrorRange = FirstBinOp 6153 ? FirstBinOp->getSourceRange() 6154 : SourceRange(ErrorLoc, ErrorLoc); 6155 } else { 6156 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 6157 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 6158 ErrorFound = NotAnAssignmentOp; 6159 NoteLoc = ErrorLoc = SecondBinOp 6160 ? SecondBinOp->getOperatorLoc() 6161 : Second->getLocStart(); 6162 NoteRange = ErrorRange = 6163 SecondBinOp ? SecondBinOp->getSourceRange() 6164 : SourceRange(ErrorLoc, ErrorLoc); 6165 } else { 6166 auto *PossibleXRHSInFirst = 6167 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 6168 auto *PossibleXLHSInSecond = 6169 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 6170 llvm::FoldingSetNodeID X1Id, X2Id; 6171 PossibleXRHSInFirst->Profile(X1Id, Context, 6172 /*Canonical=*/true); 6173 PossibleXLHSInSecond->Profile(X2Id, Context, 6174 /*Canonical=*/true); 6175 IsUpdateExprFound = X1Id == X2Id; 6176 if (IsUpdateExprFound) { 6177 V = FirstBinOp->getLHS(); 6178 X = SecondBinOp->getLHS(); 6179 E = SecondBinOp->getRHS(); 6180 UE = nullptr; 6181 IsXLHSInRHSPart = false; 6182 IsPostfixUpdate = true; 6183 } else { 6184 ErrorFound = NotASpecificExpression; 6185 ErrorLoc = FirstBinOp->getExprLoc(); 6186 ErrorRange = FirstBinOp->getSourceRange(); 6187 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 6188 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 6189 } 6190 } 6191 } 6192 } 6193 } 6194 } else { 6195 NoteLoc = ErrorLoc = Body->getLocStart(); 6196 NoteRange = ErrorRange = 6197 SourceRange(Body->getLocStart(), Body->getLocStart()); 6198 ErrorFound = NotTwoSubstatements; 6199 } 6200 } else { 6201 NoteLoc = ErrorLoc = Body->getLocStart(); 6202 NoteRange = ErrorRange = 6203 SourceRange(Body->getLocStart(), Body->getLocStart()); 6204 ErrorFound = NotACompoundStatement; 6205 } 6206 if (ErrorFound != NoError) { 6207 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 6208 << ErrorRange; 6209 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6210 return StmtError(); 6211 } else if (CurContext->isDependentContext()) { 6212 UE = V = E = X = nullptr; 6213 } 6214 } 6215 } 6216 6217 getCurFunction()->setHasBranchProtectedScope(); 6218 6219 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6220 X, V, E, UE, IsXLHSInRHSPart, 6221 IsPostfixUpdate); 6222 } 6223 6224 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 6225 Stmt *AStmt, 6226 SourceLocation StartLoc, 6227 SourceLocation EndLoc) { 6228 if (!AStmt) 6229 return StmtError(); 6230 6231 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6232 // 1.2.2 OpenMP Language Terminology 6233 // Structured block - An executable statement with a single entry at the 6234 // top and a single exit at the bottom. 6235 // The point of exit cannot be a branch out of the structured block. 6236 // longjmp() and throw() must not violate the entry/exit criteria. 6237 CS->getCapturedDecl()->setNothrow(); 6238 6239 // OpenMP [2.16, Nesting of Regions] 6240 // If specified, a teams construct must be contained within a target 6241 // construct. That target construct must contain no statements or directives 6242 // outside of the teams construct. 6243 if (DSAStack->hasInnerTeamsRegion()) { 6244 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 6245 bool OMPTeamsFound = true; 6246 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 6247 auto I = CS->body_begin(); 6248 while (I != CS->body_end()) { 6249 auto *OED = dyn_cast<OMPExecutableDirective>(*I); 6250 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 6251 OMPTeamsFound = false; 6252 break; 6253 } 6254 ++I; 6255 } 6256 assert(I != CS->body_end() && "Not found statement"); 6257 S = *I; 6258 } else { 6259 auto *OED = dyn_cast<OMPExecutableDirective>(S); 6260 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 6261 } 6262 if (!OMPTeamsFound) { 6263 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 6264 Diag(DSAStack->getInnerTeamsRegionLoc(), 6265 diag::note_omp_nested_teams_construct_here); 6266 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 6267 << isa<OMPExecutableDirective>(S); 6268 return StmtError(); 6269 } 6270 } 6271 6272 getCurFunction()->setHasBranchProtectedScope(); 6273 6274 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6275 } 6276 6277 StmtResult 6278 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 6279 Stmt *AStmt, SourceLocation StartLoc, 6280 SourceLocation EndLoc) { 6281 if (!AStmt) 6282 return StmtError(); 6283 6284 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6285 // 1.2.2 OpenMP Language Terminology 6286 // Structured block - An executable statement with a single entry at the 6287 // top and a single exit at the bottom. 6288 // The point of exit cannot be a branch out of the structured block. 6289 // longjmp() and throw() must not violate the entry/exit criteria. 6290 CS->getCapturedDecl()->setNothrow(); 6291 6292 getCurFunction()->setHasBranchProtectedScope(); 6293 6294 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6295 AStmt); 6296 } 6297 6298 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 6299 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6300 SourceLocation EndLoc, 6301 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6302 if (!AStmt) 6303 return StmtError(); 6304 6305 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6306 // 1.2.2 OpenMP Language Terminology 6307 // Structured block - An executable statement with a single entry at the 6308 // top and a single exit at the bottom. 6309 // The point of exit cannot be a branch out of the structured block. 6310 // longjmp() and throw() must not violate the entry/exit criteria. 6311 CS->getCapturedDecl()->setNothrow(); 6312 6313 OMPLoopDirective::HelperExprs B; 6314 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6315 // define the nested loops number. 6316 unsigned NestedLoopCount = 6317 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 6318 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6319 VarsWithImplicitDSA, B); 6320 if (NestedLoopCount == 0) 6321 return StmtError(); 6322 6323 assert((CurContext->isDependentContext() || B.builtAll()) && 6324 "omp target parallel for loop exprs were not built"); 6325 6326 if (!CurContext->isDependentContext()) { 6327 // Finalize the clauses that need pre-built expressions for CodeGen. 6328 for (auto C : Clauses) { 6329 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6330 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6331 B.NumIterations, *this, CurScope, 6332 DSAStack)) 6333 return StmtError(); 6334 } 6335 } 6336 6337 getCurFunction()->setHasBranchProtectedScope(); 6338 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 6339 NestedLoopCount, Clauses, AStmt, 6340 B, DSAStack->isCancelRegion()); 6341 } 6342 6343 /// Check for existence of a map clause in the list of clauses. 6344 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 6345 const OpenMPClauseKind K) { 6346 return llvm::any_of( 6347 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 6348 } 6349 6350 template <typename... Params> 6351 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 6352 const Params... ClauseTypes) { 6353 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 6354 } 6355 6356 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 6357 Stmt *AStmt, 6358 SourceLocation StartLoc, 6359 SourceLocation EndLoc) { 6360 if (!AStmt) 6361 return StmtError(); 6362 6363 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6364 6365 // OpenMP [2.10.1, Restrictions, p. 97] 6366 // At least one map clause must appear on the directive. 6367 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { 6368 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6369 << "'map' or 'use_device_ptr'" 6370 << getOpenMPDirectiveName(OMPD_target_data); 6371 return StmtError(); 6372 } 6373 6374 getCurFunction()->setHasBranchProtectedScope(); 6375 6376 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6377 AStmt); 6378 } 6379 6380 StmtResult 6381 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 6382 SourceLocation StartLoc, 6383 SourceLocation EndLoc) { 6384 // OpenMP [2.10.2, Restrictions, p. 99] 6385 // At least one map clause must appear on the directive. 6386 if (!hasClauses(Clauses, OMPC_map)) { 6387 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6388 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 6389 return StmtError(); 6390 } 6391 6392 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, 6393 Clauses); 6394 } 6395 6396 StmtResult 6397 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 6398 SourceLocation StartLoc, 6399 SourceLocation EndLoc) { 6400 // OpenMP [2.10.3, Restrictions, p. 102] 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_exit_data); 6405 return StmtError(); 6406 } 6407 6408 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses); 6409 } 6410 6411 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 6412 SourceLocation StartLoc, 6413 SourceLocation EndLoc) { 6414 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 6415 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 6416 return StmtError(); 6417 } 6418 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses); 6419 } 6420 6421 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 6422 Stmt *AStmt, SourceLocation StartLoc, 6423 SourceLocation EndLoc) { 6424 if (!AStmt) 6425 return StmtError(); 6426 6427 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6428 // 1.2.2 OpenMP Language Terminology 6429 // Structured block - An executable statement with a single entry at the 6430 // top and a single exit at the bottom. 6431 // The point of exit cannot be a branch out of the structured block. 6432 // longjmp() and throw() must not violate the entry/exit criteria. 6433 CS->getCapturedDecl()->setNothrow(); 6434 6435 getCurFunction()->setHasBranchProtectedScope(); 6436 6437 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6438 } 6439 6440 StmtResult 6441 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 6442 SourceLocation EndLoc, 6443 OpenMPDirectiveKind CancelRegion) { 6444 if (DSAStack->isParentNowaitRegion()) { 6445 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 6446 return StmtError(); 6447 } 6448 if (DSAStack->isParentOrderedRegion()) { 6449 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 6450 return StmtError(); 6451 } 6452 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 6453 CancelRegion); 6454 } 6455 6456 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 6457 SourceLocation StartLoc, 6458 SourceLocation EndLoc, 6459 OpenMPDirectiveKind CancelRegion) { 6460 if (DSAStack->isParentNowaitRegion()) { 6461 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 6462 return StmtError(); 6463 } 6464 if (DSAStack->isParentOrderedRegion()) { 6465 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 6466 return StmtError(); 6467 } 6468 DSAStack->setParentCancelRegion(/*Cancel=*/true); 6469 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6470 CancelRegion); 6471 } 6472 6473 static bool checkGrainsizeNumTasksClauses(Sema &S, 6474 ArrayRef<OMPClause *> Clauses) { 6475 OMPClause *PrevClause = nullptr; 6476 bool ErrorFound = false; 6477 for (auto *C : Clauses) { 6478 if (C->getClauseKind() == OMPC_grainsize || 6479 C->getClauseKind() == OMPC_num_tasks) { 6480 if (!PrevClause) 6481 PrevClause = C; 6482 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 6483 S.Diag(C->getLocStart(), 6484 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 6485 << getOpenMPClauseName(C->getClauseKind()) 6486 << getOpenMPClauseName(PrevClause->getClauseKind()); 6487 S.Diag(PrevClause->getLocStart(), 6488 diag::note_omp_previous_grainsize_num_tasks) 6489 << getOpenMPClauseName(PrevClause->getClauseKind()); 6490 ErrorFound = true; 6491 } 6492 } 6493 } 6494 return ErrorFound; 6495 } 6496 6497 static bool checkReductionClauseWithNogroup(Sema &S, 6498 ArrayRef<OMPClause *> Clauses) { 6499 OMPClause *ReductionClause = nullptr; 6500 OMPClause *NogroupClause = nullptr; 6501 for (auto *C : Clauses) { 6502 if (C->getClauseKind() == OMPC_reduction) { 6503 ReductionClause = C; 6504 if (NogroupClause) 6505 break; 6506 continue; 6507 } 6508 if (C->getClauseKind() == OMPC_nogroup) { 6509 NogroupClause = C; 6510 if (ReductionClause) 6511 break; 6512 continue; 6513 } 6514 } 6515 if (ReductionClause && NogroupClause) { 6516 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup) 6517 << SourceRange(NogroupClause->getLocStart(), 6518 NogroupClause->getLocEnd()); 6519 return true; 6520 } 6521 return false; 6522 } 6523 6524 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 6525 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6526 SourceLocation EndLoc, 6527 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6528 if (!AStmt) 6529 return StmtError(); 6530 6531 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6532 OMPLoopDirective::HelperExprs B; 6533 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6534 // define the nested loops number. 6535 unsigned NestedLoopCount = 6536 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 6537 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6538 VarsWithImplicitDSA, B); 6539 if (NestedLoopCount == 0) 6540 return StmtError(); 6541 6542 assert((CurContext->isDependentContext() || B.builtAll()) && 6543 "omp for loop exprs were not built"); 6544 6545 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6546 // The grainsize clause and num_tasks clause are mutually exclusive and may 6547 // not appear on the same taskloop directive. 6548 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6549 return StmtError(); 6550 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6551 // If a reduction clause is present on the taskloop directive, the nogroup 6552 // clause must not be specified. 6553 if (checkReductionClauseWithNogroup(*this, Clauses)) 6554 return StmtError(); 6555 6556 getCurFunction()->setHasBranchProtectedScope(); 6557 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 6558 NestedLoopCount, Clauses, AStmt, B); 6559 } 6560 6561 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 6562 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6563 SourceLocation EndLoc, 6564 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6565 if (!AStmt) 6566 return StmtError(); 6567 6568 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6569 OMPLoopDirective::HelperExprs B; 6570 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6571 // define the nested loops number. 6572 unsigned NestedLoopCount = 6573 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 6574 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6575 VarsWithImplicitDSA, B); 6576 if (NestedLoopCount == 0) 6577 return StmtError(); 6578 6579 assert((CurContext->isDependentContext() || B.builtAll()) && 6580 "omp for loop exprs were not built"); 6581 6582 if (!CurContext->isDependentContext()) { 6583 // Finalize the clauses that need pre-built expressions for CodeGen. 6584 for (auto C : Clauses) { 6585 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6586 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6587 B.NumIterations, *this, CurScope, 6588 DSAStack)) 6589 return StmtError(); 6590 } 6591 } 6592 6593 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6594 // The grainsize clause and num_tasks clause are mutually exclusive and may 6595 // not appear on the same taskloop directive. 6596 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6597 return StmtError(); 6598 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6599 // If a reduction clause is present on the taskloop directive, the nogroup 6600 // clause must not be specified. 6601 if (checkReductionClauseWithNogroup(*this, Clauses)) 6602 return StmtError(); 6603 6604 getCurFunction()->setHasBranchProtectedScope(); 6605 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 6606 NestedLoopCount, Clauses, AStmt, B); 6607 } 6608 6609 StmtResult Sema::ActOnOpenMPDistributeDirective( 6610 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6611 SourceLocation EndLoc, 6612 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6613 if (!AStmt) 6614 return StmtError(); 6615 6616 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6617 OMPLoopDirective::HelperExprs B; 6618 // In presence of clause 'collapse' with number of loops, it will 6619 // define the nested loops number. 6620 unsigned NestedLoopCount = 6621 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 6622 nullptr /*ordered not a clause on distribute*/, AStmt, 6623 *this, *DSAStack, VarsWithImplicitDSA, B); 6624 if (NestedLoopCount == 0) 6625 return StmtError(); 6626 6627 assert((CurContext->isDependentContext() || B.builtAll()) && 6628 "omp for loop exprs were not built"); 6629 6630 getCurFunction()->setHasBranchProtectedScope(); 6631 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 6632 NestedLoopCount, Clauses, AStmt, B); 6633 } 6634 6635 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 6636 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6637 SourceLocation EndLoc, 6638 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6639 if (!AStmt) 6640 return StmtError(); 6641 6642 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6643 // 1.2.2 OpenMP Language Terminology 6644 // Structured block - An executable statement with a single entry at the 6645 // top and a single exit at the bottom. 6646 // The point of exit cannot be a branch out of the structured block. 6647 // longjmp() and throw() must not violate the entry/exit criteria. 6648 CS->getCapturedDecl()->setNothrow(); 6649 6650 OMPLoopDirective::HelperExprs B; 6651 // In presence of clause 'collapse' with number of loops, it will 6652 // define the nested loops number. 6653 unsigned NestedLoopCount = CheckOpenMPLoop( 6654 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6655 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6656 VarsWithImplicitDSA, B); 6657 if (NestedLoopCount == 0) 6658 return StmtError(); 6659 6660 assert((CurContext->isDependentContext() || B.builtAll()) && 6661 "omp for loop exprs were not built"); 6662 6663 getCurFunction()->setHasBranchProtectedScope(); 6664 return OMPDistributeParallelForDirective::Create( 6665 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6666 } 6667 6668 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 6669 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6670 SourceLocation EndLoc, 6671 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6672 if (!AStmt) 6673 return StmtError(); 6674 6675 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6676 // 1.2.2 OpenMP Language Terminology 6677 // Structured block - An executable statement with a single entry at the 6678 // top and a single exit at the bottom. 6679 // The point of exit cannot be a branch out of the structured block. 6680 // longjmp() and throw() must not violate the entry/exit criteria. 6681 CS->getCapturedDecl()->setNothrow(); 6682 6683 OMPLoopDirective::HelperExprs B; 6684 // In presence of clause 'collapse' with number of loops, it will 6685 // define the nested loops number. 6686 unsigned NestedLoopCount = CheckOpenMPLoop( 6687 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6688 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6689 VarsWithImplicitDSA, B); 6690 if (NestedLoopCount == 0) 6691 return StmtError(); 6692 6693 assert((CurContext->isDependentContext() || B.builtAll()) && 6694 "omp for loop exprs were not built"); 6695 6696 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6697 return StmtError(); 6698 6699 getCurFunction()->setHasBranchProtectedScope(); 6700 return OMPDistributeParallelForSimdDirective::Create( 6701 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6702 } 6703 6704 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 6705 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6706 SourceLocation EndLoc, 6707 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6708 if (!AStmt) 6709 return StmtError(); 6710 6711 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6712 // 1.2.2 OpenMP Language Terminology 6713 // Structured block - An executable statement with a single entry at the 6714 // top and a single exit at the bottom. 6715 // The point of exit cannot be a branch out of the structured block. 6716 // longjmp() and throw() must not violate the entry/exit criteria. 6717 CS->getCapturedDecl()->setNothrow(); 6718 6719 OMPLoopDirective::HelperExprs B; 6720 // In presence of clause 'collapse' with number of loops, it will 6721 // define the nested loops number. 6722 unsigned NestedLoopCount = 6723 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 6724 nullptr /*ordered not a clause on distribute*/, AStmt, 6725 *this, *DSAStack, VarsWithImplicitDSA, B); 6726 if (NestedLoopCount == 0) 6727 return StmtError(); 6728 6729 assert((CurContext->isDependentContext() || B.builtAll()) && 6730 "omp for loop exprs were not built"); 6731 6732 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6733 return StmtError(); 6734 6735 getCurFunction()->setHasBranchProtectedScope(); 6736 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 6737 NestedLoopCount, Clauses, AStmt, B); 6738 } 6739 6740 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 6741 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6742 SourceLocation EndLoc, 6743 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6744 if (!AStmt) 6745 return StmtError(); 6746 6747 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6748 // 1.2.2 OpenMP Language Terminology 6749 // Structured block - An executable statement with a single entry at the 6750 // top and a single exit at the bottom. 6751 // The point of exit cannot be a branch out of the structured block. 6752 // longjmp() and throw() must not violate the entry/exit criteria. 6753 CS->getCapturedDecl()->setNothrow(); 6754 6755 OMPLoopDirective::HelperExprs B; 6756 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6757 // define the nested loops number. 6758 unsigned NestedLoopCount = CheckOpenMPLoop( 6759 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 6760 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6761 VarsWithImplicitDSA, B); 6762 if (NestedLoopCount == 0) 6763 return StmtError(); 6764 6765 assert((CurContext->isDependentContext() || B.builtAll()) && 6766 "omp target parallel for simd loop exprs were not built"); 6767 6768 if (!CurContext->isDependentContext()) { 6769 // Finalize the clauses that need pre-built expressions for CodeGen. 6770 for (auto C : Clauses) { 6771 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6772 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6773 B.NumIterations, *this, CurScope, 6774 DSAStack)) 6775 return StmtError(); 6776 } 6777 } 6778 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6779 return StmtError(); 6780 6781 getCurFunction()->setHasBranchProtectedScope(); 6782 return OMPTargetParallelForSimdDirective::Create( 6783 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6784 } 6785 6786 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 6787 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6788 SourceLocation EndLoc, 6789 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6790 if (!AStmt) 6791 return StmtError(); 6792 6793 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6794 // 1.2.2 OpenMP Language Terminology 6795 // Structured block - An executable statement with a single entry at the 6796 // top and a single exit at the bottom. 6797 // The point of exit cannot be a branch out of the structured block. 6798 // longjmp() and throw() must not violate the entry/exit criteria. 6799 CS->getCapturedDecl()->setNothrow(); 6800 6801 OMPLoopDirective::HelperExprs B; 6802 // In presence of clause 'collapse' with number of loops, it will define the 6803 // nested loops number. 6804 unsigned NestedLoopCount = 6805 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 6806 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6807 VarsWithImplicitDSA, B); 6808 if (NestedLoopCount == 0) 6809 return StmtError(); 6810 6811 assert((CurContext->isDependentContext() || B.builtAll()) && 6812 "omp target simd loop exprs were not built"); 6813 6814 if (!CurContext->isDependentContext()) { 6815 // Finalize the clauses that need pre-built expressions for CodeGen. 6816 for (auto C : Clauses) { 6817 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6818 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6819 B.NumIterations, *this, CurScope, 6820 DSAStack)) 6821 return StmtError(); 6822 } 6823 } 6824 6825 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6826 return StmtError(); 6827 6828 getCurFunction()->setHasBranchProtectedScope(); 6829 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 6830 NestedLoopCount, Clauses, AStmt, B); 6831 } 6832 6833 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 6834 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6835 SourceLocation EndLoc, 6836 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6837 if (!AStmt) 6838 return StmtError(); 6839 6840 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6841 // 1.2.2 OpenMP Language Terminology 6842 // Structured block - An executable statement with a single entry at the 6843 // top and a single exit at the bottom. 6844 // The point of exit cannot be a branch out of the structured block. 6845 // longjmp() and throw() must not violate the entry/exit criteria. 6846 CS->getCapturedDecl()->setNothrow(); 6847 6848 OMPLoopDirective::HelperExprs B; 6849 // In presence of clause 'collapse' with number of loops, it will 6850 // define the nested loops number. 6851 unsigned NestedLoopCount = 6852 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 6853 nullptr /*ordered not a clause on distribute*/, AStmt, 6854 *this, *DSAStack, VarsWithImplicitDSA, B); 6855 if (NestedLoopCount == 0) 6856 return StmtError(); 6857 6858 assert((CurContext->isDependentContext() || B.builtAll()) && 6859 "omp teams distribute loop exprs were not built"); 6860 6861 getCurFunction()->setHasBranchProtectedScope(); 6862 return OMPTeamsDistributeDirective::Create( 6863 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6864 } 6865 6866 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 6867 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6868 SourceLocation EndLoc, 6869 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6870 if (!AStmt) 6871 return StmtError(); 6872 6873 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6874 // 1.2.2 OpenMP Language Terminology 6875 // Structured block - An executable statement with a single entry at the 6876 // top and a single exit at the bottom. 6877 // The point of exit cannot be a branch out of the structured block. 6878 // longjmp() and throw() must not violate the entry/exit criteria. 6879 CS->getCapturedDecl()->setNothrow(); 6880 6881 OMPLoopDirective::HelperExprs B; 6882 // In presence of clause 'collapse' with number of loops, it will 6883 // define the nested loops number. 6884 unsigned NestedLoopCount = CheckOpenMPLoop( 6885 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6886 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6887 VarsWithImplicitDSA, B); 6888 6889 if (NestedLoopCount == 0) 6890 return StmtError(); 6891 6892 assert((CurContext->isDependentContext() || B.builtAll()) && 6893 "omp teams distribute simd loop exprs were not built"); 6894 6895 if (!CurContext->isDependentContext()) { 6896 // Finalize the clauses that need pre-built expressions for CodeGen. 6897 for (auto C : Clauses) { 6898 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6899 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6900 B.NumIterations, *this, CurScope, 6901 DSAStack)) 6902 return StmtError(); 6903 } 6904 } 6905 6906 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6907 return StmtError(); 6908 6909 getCurFunction()->setHasBranchProtectedScope(); 6910 return OMPTeamsDistributeSimdDirective::Create( 6911 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6912 } 6913 6914 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6915 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6916 SourceLocation EndLoc, 6917 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6918 if (!AStmt) 6919 return StmtError(); 6920 6921 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6922 // 1.2.2 OpenMP Language Terminology 6923 // Structured block - An executable statement with a single entry at the 6924 // top and a single exit at the bottom. 6925 // The point of exit cannot be a branch out of the structured block. 6926 // longjmp() and throw() must not violate the entry/exit criteria. 6927 CS->getCapturedDecl()->setNothrow(); 6928 6929 OMPLoopDirective::HelperExprs B; 6930 // In presence of clause 'collapse' with number of loops, it will 6931 // define the nested loops number. 6932 auto NestedLoopCount = CheckOpenMPLoop( 6933 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6934 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6935 VarsWithImplicitDSA, B); 6936 6937 if (NestedLoopCount == 0) 6938 return StmtError(); 6939 6940 assert((CurContext->isDependentContext() || B.builtAll()) && 6941 "omp for loop exprs were not built"); 6942 6943 if (!CurContext->isDependentContext()) { 6944 // Finalize the clauses that need pre-built expressions for CodeGen. 6945 for (auto C : Clauses) { 6946 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6947 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6948 B.NumIterations, *this, CurScope, 6949 DSAStack)) 6950 return StmtError(); 6951 } 6952 } 6953 6954 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6955 return StmtError(); 6956 6957 getCurFunction()->setHasBranchProtectedScope(); 6958 return OMPTeamsDistributeParallelForSimdDirective::Create( 6959 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6960 } 6961 6962 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 6963 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6964 SourceLocation EndLoc, 6965 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6966 if (!AStmt) 6967 return StmtError(); 6968 6969 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6970 // 1.2.2 OpenMP Language Terminology 6971 // Structured block - An executable statement with a single entry at the 6972 // top and a single exit at the bottom. 6973 // The point of exit cannot be a branch out of the structured block. 6974 // longjmp() and throw() must not violate the entry/exit criteria. 6975 CS->getCapturedDecl()->setNothrow(); 6976 6977 OMPLoopDirective::HelperExprs B; 6978 // In presence of clause 'collapse' with number of loops, it will 6979 // define the nested loops number. 6980 unsigned NestedLoopCount = CheckOpenMPLoop( 6981 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6982 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6983 VarsWithImplicitDSA, B); 6984 6985 if (NestedLoopCount == 0) 6986 return StmtError(); 6987 6988 assert((CurContext->isDependentContext() || B.builtAll()) && 6989 "omp for loop exprs were not built"); 6990 6991 if (!CurContext->isDependentContext()) { 6992 // Finalize the clauses that need pre-built expressions for CodeGen. 6993 for (auto C : Clauses) { 6994 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6995 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6996 B.NumIterations, *this, CurScope, 6997 DSAStack)) 6998 return StmtError(); 6999 } 7000 } 7001 7002 getCurFunction()->setHasBranchProtectedScope(); 7003 return OMPTeamsDistributeParallelForDirective::Create( 7004 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7005 } 7006 7007 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 7008 Stmt *AStmt, 7009 SourceLocation StartLoc, 7010 SourceLocation EndLoc) { 7011 if (!AStmt) 7012 return StmtError(); 7013 7014 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7015 // 1.2.2 OpenMP Language Terminology 7016 // Structured block - An executable statement with a single entry at the 7017 // top and a single exit at the bottom. 7018 // The point of exit cannot be a branch out of the structured block. 7019 // longjmp() and throw() must not violate the entry/exit criteria. 7020 CS->getCapturedDecl()->setNothrow(); 7021 7022 getCurFunction()->setHasBranchProtectedScope(); 7023 7024 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 7025 AStmt); 7026 } 7027 7028 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 7029 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7030 SourceLocation EndLoc, 7031 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7032 if (!AStmt) 7033 return StmtError(); 7034 7035 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7036 // 1.2.2 OpenMP Language Terminology 7037 // Structured block - An executable statement with a single entry at the 7038 // top and a single exit at the bottom. 7039 // The point of exit cannot be a branch out of the structured block. 7040 // longjmp() and throw() must not violate the entry/exit criteria. 7041 CS->getCapturedDecl()->setNothrow(); 7042 7043 OMPLoopDirective::HelperExprs B; 7044 // In presence of clause 'collapse' with number of loops, it will 7045 // define the nested loops number. 7046 auto NestedLoopCount = CheckOpenMPLoop( 7047 OMPD_target_teams_distribute, 7048 getCollapseNumberExpr(Clauses), 7049 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7050 VarsWithImplicitDSA, B); 7051 if (NestedLoopCount == 0) 7052 return StmtError(); 7053 7054 assert((CurContext->isDependentContext() || B.builtAll()) && 7055 "omp target teams distribute loop exprs were not built"); 7056 7057 getCurFunction()->setHasBranchProtectedScope(); 7058 return OMPTargetTeamsDistributeDirective::Create( 7059 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7060 } 7061 7062 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 7063 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7064 SourceLocation EndLoc, 7065 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7066 if (!AStmt) 7067 return StmtError(); 7068 7069 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7070 // 1.2.2 OpenMP Language Terminology 7071 // Structured block - An executable statement with a single entry at the 7072 // top and a single exit at the bottom. 7073 // The point of exit cannot be a branch out of the structured block. 7074 // longjmp() and throw() must not violate the entry/exit criteria. 7075 CS->getCapturedDecl()->setNothrow(); 7076 7077 OMPLoopDirective::HelperExprs B; 7078 // In presence of clause 'collapse' with number of loops, it will 7079 // define the nested loops number. 7080 auto NestedLoopCount = CheckOpenMPLoop( 7081 OMPD_target_teams_distribute_parallel_for, 7082 getCollapseNumberExpr(Clauses), 7083 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7084 VarsWithImplicitDSA, B); 7085 if (NestedLoopCount == 0) 7086 return StmtError(); 7087 7088 assert((CurContext->isDependentContext() || B.builtAll()) && 7089 "omp target teams distribute parallel for loop exprs were not built"); 7090 7091 if (!CurContext->isDependentContext()) { 7092 // Finalize the clauses that need pre-built expressions for CodeGen. 7093 for (auto C : Clauses) { 7094 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7095 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7096 B.NumIterations, *this, CurScope, 7097 DSAStack)) 7098 return StmtError(); 7099 } 7100 } 7101 7102 getCurFunction()->setHasBranchProtectedScope(); 7103 return OMPTargetTeamsDistributeParallelForDirective::Create( 7104 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7105 } 7106 7107 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 7108 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7109 SourceLocation EndLoc, 7110 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7111 if (!AStmt) 7112 return StmtError(); 7113 7114 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7115 // 1.2.2 OpenMP Language Terminology 7116 // Structured block - An executable statement with a single entry at the 7117 // top and a single exit at the bottom. 7118 // The point of exit cannot be a branch out of the structured block. 7119 // longjmp() and throw() must not violate the entry/exit criteria. 7120 CS->getCapturedDecl()->setNothrow(); 7121 7122 OMPLoopDirective::HelperExprs B; 7123 // In presence of clause 'collapse' with number of loops, it will 7124 // define the nested loops number. 7125 auto NestedLoopCount = CheckOpenMPLoop( 7126 OMPD_target_teams_distribute_parallel_for_simd, 7127 getCollapseNumberExpr(Clauses), 7128 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7129 VarsWithImplicitDSA, B); 7130 if (NestedLoopCount == 0) 7131 return StmtError(); 7132 7133 assert((CurContext->isDependentContext() || B.builtAll()) && 7134 "omp target teams distribute parallel for simd loop exprs were not " 7135 "built"); 7136 7137 if (!CurContext->isDependentContext()) { 7138 // Finalize the clauses that need pre-built expressions for CodeGen. 7139 for (auto C : Clauses) { 7140 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7141 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7142 B.NumIterations, *this, CurScope, 7143 DSAStack)) 7144 return StmtError(); 7145 } 7146 } 7147 7148 getCurFunction()->setHasBranchProtectedScope(); 7149 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 7150 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7151 } 7152 7153 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 7154 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7155 SourceLocation EndLoc, 7156 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7157 if (!AStmt) 7158 return StmtError(); 7159 7160 auto *CS = cast<CapturedStmt>(AStmt); 7161 // 1.2.2 OpenMP Language Terminology 7162 // Structured block - An executable statement with a single entry at the 7163 // top and a single exit at the bottom. 7164 // The point of exit cannot be a branch out of the structured block. 7165 // longjmp() and throw() must not violate the entry/exit criteria. 7166 CS->getCapturedDecl()->setNothrow(); 7167 7168 OMPLoopDirective::HelperExprs B; 7169 // In presence of clause 'collapse' with number of loops, it will 7170 // define the nested loops number. 7171 auto NestedLoopCount = CheckOpenMPLoop( 7172 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 7173 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7174 VarsWithImplicitDSA, B); 7175 if (NestedLoopCount == 0) 7176 return StmtError(); 7177 7178 assert((CurContext->isDependentContext() || B.builtAll()) && 7179 "omp target teams distribute simd loop exprs were not built"); 7180 7181 getCurFunction()->setHasBranchProtectedScope(); 7182 return OMPTargetTeamsDistributeSimdDirective::Create( 7183 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7184 } 7185 7186 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 7187 SourceLocation StartLoc, 7188 SourceLocation LParenLoc, 7189 SourceLocation EndLoc) { 7190 OMPClause *Res = nullptr; 7191 switch (Kind) { 7192 case OMPC_final: 7193 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 7194 break; 7195 case OMPC_num_threads: 7196 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 7197 break; 7198 case OMPC_safelen: 7199 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 7200 break; 7201 case OMPC_simdlen: 7202 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 7203 break; 7204 case OMPC_collapse: 7205 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 7206 break; 7207 case OMPC_ordered: 7208 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 7209 break; 7210 case OMPC_device: 7211 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 7212 break; 7213 case OMPC_num_teams: 7214 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 7215 break; 7216 case OMPC_thread_limit: 7217 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 7218 break; 7219 case OMPC_priority: 7220 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 7221 break; 7222 case OMPC_grainsize: 7223 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 7224 break; 7225 case OMPC_num_tasks: 7226 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 7227 break; 7228 case OMPC_hint: 7229 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 7230 break; 7231 case OMPC_if: 7232 case OMPC_default: 7233 case OMPC_proc_bind: 7234 case OMPC_schedule: 7235 case OMPC_private: 7236 case OMPC_firstprivate: 7237 case OMPC_lastprivate: 7238 case OMPC_shared: 7239 case OMPC_reduction: 7240 case OMPC_task_reduction: 7241 case OMPC_in_reduction: 7242 case OMPC_linear: 7243 case OMPC_aligned: 7244 case OMPC_copyin: 7245 case OMPC_copyprivate: 7246 case OMPC_nowait: 7247 case OMPC_untied: 7248 case OMPC_mergeable: 7249 case OMPC_threadprivate: 7250 case OMPC_flush: 7251 case OMPC_read: 7252 case OMPC_write: 7253 case OMPC_update: 7254 case OMPC_capture: 7255 case OMPC_seq_cst: 7256 case OMPC_depend: 7257 case OMPC_threads: 7258 case OMPC_simd: 7259 case OMPC_map: 7260 case OMPC_nogroup: 7261 case OMPC_dist_schedule: 7262 case OMPC_defaultmap: 7263 case OMPC_unknown: 7264 case OMPC_uniform: 7265 case OMPC_to: 7266 case OMPC_from: 7267 case OMPC_use_device_ptr: 7268 case OMPC_is_device_ptr: 7269 llvm_unreachable("Clause is not allowed."); 7270 } 7271 return Res; 7272 } 7273 7274 // An OpenMP directive such as 'target parallel' has two captured regions: 7275 // for the 'target' and 'parallel' respectively. This function returns 7276 // the region in which to capture expressions associated with a clause. 7277 // A return value of OMPD_unknown signifies that the expression should not 7278 // be captured. 7279 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 7280 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 7281 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 7282 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7283 7284 switch (CKind) { 7285 case OMPC_if: 7286 switch (DKind) { 7287 case OMPD_target_parallel: 7288 // If this clause applies to the nested 'parallel' region, capture within 7289 // the 'target' region, otherwise do not capture. 7290 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 7291 CaptureRegion = OMPD_target; 7292 break; 7293 case OMPD_cancel: 7294 case OMPD_parallel: 7295 case OMPD_parallel_sections: 7296 case OMPD_parallel_for: 7297 case OMPD_parallel_for_simd: 7298 case OMPD_target: 7299 case OMPD_target_simd: 7300 case OMPD_target_parallel_for: 7301 case OMPD_target_parallel_for_simd: 7302 case OMPD_target_teams: 7303 case OMPD_target_teams_distribute: 7304 case OMPD_target_teams_distribute_simd: 7305 case OMPD_target_teams_distribute_parallel_for: 7306 case OMPD_target_teams_distribute_parallel_for_simd: 7307 case OMPD_teams_distribute_parallel_for: 7308 case OMPD_teams_distribute_parallel_for_simd: 7309 case OMPD_distribute_parallel_for: 7310 case OMPD_distribute_parallel_for_simd: 7311 case OMPD_task: 7312 case OMPD_taskloop: 7313 case OMPD_taskloop_simd: 7314 case OMPD_target_data: 7315 case OMPD_target_enter_data: 7316 case OMPD_target_exit_data: 7317 case OMPD_target_update: 7318 // Do not capture if-clause expressions. 7319 break; 7320 case OMPD_threadprivate: 7321 case OMPD_taskyield: 7322 case OMPD_barrier: 7323 case OMPD_taskwait: 7324 case OMPD_cancellation_point: 7325 case OMPD_flush: 7326 case OMPD_declare_reduction: 7327 case OMPD_declare_simd: 7328 case OMPD_declare_target: 7329 case OMPD_end_declare_target: 7330 case OMPD_teams: 7331 case OMPD_simd: 7332 case OMPD_for: 7333 case OMPD_for_simd: 7334 case OMPD_sections: 7335 case OMPD_section: 7336 case OMPD_single: 7337 case OMPD_master: 7338 case OMPD_critical: 7339 case OMPD_taskgroup: 7340 case OMPD_distribute: 7341 case OMPD_ordered: 7342 case OMPD_atomic: 7343 case OMPD_distribute_simd: 7344 case OMPD_teams_distribute: 7345 case OMPD_teams_distribute_simd: 7346 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 7347 case OMPD_unknown: 7348 llvm_unreachable("Unknown OpenMP directive"); 7349 } 7350 break; 7351 case OMPC_num_threads: 7352 switch (DKind) { 7353 case OMPD_target_parallel: 7354 CaptureRegion = OMPD_target; 7355 break; 7356 case OMPD_cancel: 7357 case OMPD_parallel: 7358 case OMPD_parallel_sections: 7359 case OMPD_parallel_for: 7360 case OMPD_parallel_for_simd: 7361 case OMPD_target: 7362 case OMPD_target_simd: 7363 case OMPD_target_parallel_for: 7364 case OMPD_target_parallel_for_simd: 7365 case OMPD_target_teams: 7366 case OMPD_target_teams_distribute: 7367 case OMPD_target_teams_distribute_simd: 7368 case OMPD_target_teams_distribute_parallel_for: 7369 case OMPD_target_teams_distribute_parallel_for_simd: 7370 case OMPD_teams_distribute_parallel_for: 7371 case OMPD_teams_distribute_parallel_for_simd: 7372 case OMPD_distribute_parallel_for: 7373 case OMPD_distribute_parallel_for_simd: 7374 case OMPD_task: 7375 case OMPD_taskloop: 7376 case OMPD_taskloop_simd: 7377 case OMPD_target_data: 7378 case OMPD_target_enter_data: 7379 case OMPD_target_exit_data: 7380 case OMPD_target_update: 7381 // Do not capture num_threads-clause expressions. 7382 break; 7383 case OMPD_threadprivate: 7384 case OMPD_taskyield: 7385 case OMPD_barrier: 7386 case OMPD_taskwait: 7387 case OMPD_cancellation_point: 7388 case OMPD_flush: 7389 case OMPD_declare_reduction: 7390 case OMPD_declare_simd: 7391 case OMPD_declare_target: 7392 case OMPD_end_declare_target: 7393 case OMPD_teams: 7394 case OMPD_simd: 7395 case OMPD_for: 7396 case OMPD_for_simd: 7397 case OMPD_sections: 7398 case OMPD_section: 7399 case OMPD_single: 7400 case OMPD_master: 7401 case OMPD_critical: 7402 case OMPD_taskgroup: 7403 case OMPD_distribute: 7404 case OMPD_ordered: 7405 case OMPD_atomic: 7406 case OMPD_distribute_simd: 7407 case OMPD_teams_distribute: 7408 case OMPD_teams_distribute_simd: 7409 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 7410 case OMPD_unknown: 7411 llvm_unreachable("Unknown OpenMP directive"); 7412 } 7413 break; 7414 case OMPC_num_teams: 7415 switch (DKind) { 7416 case OMPD_target_teams: 7417 CaptureRegion = OMPD_target; 7418 break; 7419 case OMPD_cancel: 7420 case OMPD_parallel: 7421 case OMPD_parallel_sections: 7422 case OMPD_parallel_for: 7423 case OMPD_parallel_for_simd: 7424 case OMPD_target: 7425 case OMPD_target_simd: 7426 case OMPD_target_parallel: 7427 case OMPD_target_parallel_for: 7428 case OMPD_target_parallel_for_simd: 7429 case OMPD_target_teams_distribute: 7430 case OMPD_target_teams_distribute_simd: 7431 case OMPD_target_teams_distribute_parallel_for: 7432 case OMPD_target_teams_distribute_parallel_for_simd: 7433 case OMPD_teams_distribute_parallel_for: 7434 case OMPD_teams_distribute_parallel_for_simd: 7435 case OMPD_distribute_parallel_for: 7436 case OMPD_distribute_parallel_for_simd: 7437 case OMPD_task: 7438 case OMPD_taskloop: 7439 case OMPD_taskloop_simd: 7440 case OMPD_target_data: 7441 case OMPD_target_enter_data: 7442 case OMPD_target_exit_data: 7443 case OMPD_target_update: 7444 case OMPD_teams: 7445 case OMPD_teams_distribute: 7446 case OMPD_teams_distribute_simd: 7447 // Do not capture num_teams-clause expressions. 7448 break; 7449 case OMPD_threadprivate: 7450 case OMPD_taskyield: 7451 case OMPD_barrier: 7452 case OMPD_taskwait: 7453 case OMPD_cancellation_point: 7454 case OMPD_flush: 7455 case OMPD_declare_reduction: 7456 case OMPD_declare_simd: 7457 case OMPD_declare_target: 7458 case OMPD_end_declare_target: 7459 case OMPD_simd: 7460 case OMPD_for: 7461 case OMPD_for_simd: 7462 case OMPD_sections: 7463 case OMPD_section: 7464 case OMPD_single: 7465 case OMPD_master: 7466 case OMPD_critical: 7467 case OMPD_taskgroup: 7468 case OMPD_distribute: 7469 case OMPD_ordered: 7470 case OMPD_atomic: 7471 case OMPD_distribute_simd: 7472 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 7473 case OMPD_unknown: 7474 llvm_unreachable("Unknown OpenMP directive"); 7475 } 7476 break; 7477 case OMPC_thread_limit: 7478 switch (DKind) { 7479 case OMPD_target_teams: 7480 CaptureRegion = OMPD_target; 7481 break; 7482 case OMPD_cancel: 7483 case OMPD_parallel: 7484 case OMPD_parallel_sections: 7485 case OMPD_parallel_for: 7486 case OMPD_parallel_for_simd: 7487 case OMPD_target: 7488 case OMPD_target_simd: 7489 case OMPD_target_parallel: 7490 case OMPD_target_parallel_for: 7491 case OMPD_target_parallel_for_simd: 7492 case OMPD_target_teams_distribute: 7493 case OMPD_target_teams_distribute_simd: 7494 case OMPD_target_teams_distribute_parallel_for: 7495 case OMPD_target_teams_distribute_parallel_for_simd: 7496 case OMPD_teams_distribute_parallel_for: 7497 case OMPD_teams_distribute_parallel_for_simd: 7498 case OMPD_distribute_parallel_for: 7499 case OMPD_distribute_parallel_for_simd: 7500 case OMPD_task: 7501 case OMPD_taskloop: 7502 case OMPD_taskloop_simd: 7503 case OMPD_target_data: 7504 case OMPD_target_enter_data: 7505 case OMPD_target_exit_data: 7506 case OMPD_target_update: 7507 case OMPD_teams: 7508 case OMPD_teams_distribute: 7509 case OMPD_teams_distribute_simd: 7510 // Do not capture thread_limit-clause expressions. 7511 break; 7512 case OMPD_threadprivate: 7513 case OMPD_taskyield: 7514 case OMPD_barrier: 7515 case OMPD_taskwait: 7516 case OMPD_cancellation_point: 7517 case OMPD_flush: 7518 case OMPD_declare_reduction: 7519 case OMPD_declare_simd: 7520 case OMPD_declare_target: 7521 case OMPD_end_declare_target: 7522 case OMPD_simd: 7523 case OMPD_for: 7524 case OMPD_for_simd: 7525 case OMPD_sections: 7526 case OMPD_section: 7527 case OMPD_single: 7528 case OMPD_master: 7529 case OMPD_critical: 7530 case OMPD_taskgroup: 7531 case OMPD_distribute: 7532 case OMPD_ordered: 7533 case OMPD_atomic: 7534 case OMPD_distribute_simd: 7535 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 7536 case OMPD_unknown: 7537 llvm_unreachable("Unknown OpenMP directive"); 7538 } 7539 break; 7540 case OMPC_schedule: 7541 case OMPC_dist_schedule: 7542 case OMPC_firstprivate: 7543 case OMPC_lastprivate: 7544 case OMPC_reduction: 7545 case OMPC_task_reduction: 7546 case OMPC_in_reduction: 7547 case OMPC_linear: 7548 case OMPC_default: 7549 case OMPC_proc_bind: 7550 case OMPC_final: 7551 case OMPC_safelen: 7552 case OMPC_simdlen: 7553 case OMPC_collapse: 7554 case OMPC_private: 7555 case OMPC_shared: 7556 case OMPC_aligned: 7557 case OMPC_copyin: 7558 case OMPC_copyprivate: 7559 case OMPC_ordered: 7560 case OMPC_nowait: 7561 case OMPC_untied: 7562 case OMPC_mergeable: 7563 case OMPC_threadprivate: 7564 case OMPC_flush: 7565 case OMPC_read: 7566 case OMPC_write: 7567 case OMPC_update: 7568 case OMPC_capture: 7569 case OMPC_seq_cst: 7570 case OMPC_depend: 7571 case OMPC_device: 7572 case OMPC_threads: 7573 case OMPC_simd: 7574 case OMPC_map: 7575 case OMPC_priority: 7576 case OMPC_grainsize: 7577 case OMPC_nogroup: 7578 case OMPC_num_tasks: 7579 case OMPC_hint: 7580 case OMPC_defaultmap: 7581 case OMPC_unknown: 7582 case OMPC_uniform: 7583 case OMPC_to: 7584 case OMPC_from: 7585 case OMPC_use_device_ptr: 7586 case OMPC_is_device_ptr: 7587 llvm_unreachable("Unexpected OpenMP clause."); 7588 } 7589 return CaptureRegion; 7590 } 7591 7592 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 7593 Expr *Condition, SourceLocation StartLoc, 7594 SourceLocation LParenLoc, 7595 SourceLocation NameModifierLoc, 7596 SourceLocation ColonLoc, 7597 SourceLocation EndLoc) { 7598 Expr *ValExpr = Condition; 7599 Stmt *HelperValStmt = nullptr; 7600 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7601 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7602 !Condition->isInstantiationDependent() && 7603 !Condition->containsUnexpandedParameterPack()) { 7604 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7605 if (Val.isInvalid()) 7606 return nullptr; 7607 7608 ValExpr = MakeFullExpr(Val.get()).get(); 7609 7610 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7611 CaptureRegion = 7612 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 7613 if (CaptureRegion != OMPD_unknown) { 7614 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7615 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7616 HelperValStmt = buildPreInits(Context, Captures); 7617 } 7618 } 7619 7620 return new (Context) 7621 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 7622 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 7623 } 7624 7625 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 7626 SourceLocation StartLoc, 7627 SourceLocation LParenLoc, 7628 SourceLocation EndLoc) { 7629 Expr *ValExpr = Condition; 7630 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7631 !Condition->isInstantiationDependent() && 7632 !Condition->containsUnexpandedParameterPack()) { 7633 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7634 if (Val.isInvalid()) 7635 return nullptr; 7636 7637 ValExpr = MakeFullExpr(Val.get()).get(); 7638 } 7639 7640 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 7641 } 7642 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 7643 Expr *Op) { 7644 if (!Op) 7645 return ExprError(); 7646 7647 class IntConvertDiagnoser : public ICEConvertDiagnoser { 7648 public: 7649 IntConvertDiagnoser() 7650 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 7651 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 7652 QualType T) override { 7653 return S.Diag(Loc, diag::err_omp_not_integral) << T; 7654 } 7655 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 7656 QualType T) override { 7657 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 7658 } 7659 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 7660 QualType T, 7661 QualType ConvTy) override { 7662 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 7663 } 7664 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 7665 QualType ConvTy) override { 7666 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7667 << ConvTy->isEnumeralType() << ConvTy; 7668 } 7669 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 7670 QualType T) override { 7671 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 7672 } 7673 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 7674 QualType ConvTy) override { 7675 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7676 << ConvTy->isEnumeralType() << ConvTy; 7677 } 7678 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 7679 QualType) override { 7680 llvm_unreachable("conversion functions are permitted"); 7681 } 7682 } ConvertDiagnoser; 7683 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 7684 } 7685 7686 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 7687 OpenMPClauseKind CKind, 7688 bool StrictlyPositive) { 7689 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 7690 !ValExpr->isInstantiationDependent()) { 7691 SourceLocation Loc = ValExpr->getExprLoc(); 7692 ExprResult Value = 7693 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 7694 if (Value.isInvalid()) 7695 return false; 7696 7697 ValExpr = Value.get(); 7698 // The expression must evaluate to a non-negative integer value. 7699 llvm::APSInt Result; 7700 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 7701 Result.isSigned() && 7702 !((!StrictlyPositive && Result.isNonNegative()) || 7703 (StrictlyPositive && Result.isStrictlyPositive()))) { 7704 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 7705 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7706 << ValExpr->getSourceRange(); 7707 return false; 7708 } 7709 } 7710 return true; 7711 } 7712 7713 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 7714 SourceLocation StartLoc, 7715 SourceLocation LParenLoc, 7716 SourceLocation EndLoc) { 7717 Expr *ValExpr = NumThreads; 7718 Stmt *HelperValStmt = nullptr; 7719 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7720 7721 // OpenMP [2.5, Restrictions] 7722 // The num_threads expression must evaluate to a positive integer value. 7723 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 7724 /*StrictlyPositive=*/true)) 7725 return nullptr; 7726 7727 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7728 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 7729 if (CaptureRegion != OMPD_unknown) { 7730 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7731 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7732 HelperValStmt = buildPreInits(Context, Captures); 7733 } 7734 7735 return new (Context) OMPNumThreadsClause( 7736 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 7737 } 7738 7739 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 7740 OpenMPClauseKind CKind, 7741 bool StrictlyPositive) { 7742 if (!E) 7743 return ExprError(); 7744 if (E->isValueDependent() || E->isTypeDependent() || 7745 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 7746 return E; 7747 llvm::APSInt Result; 7748 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 7749 if (ICE.isInvalid()) 7750 return ExprError(); 7751 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 7752 (!StrictlyPositive && !Result.isNonNegative())) { 7753 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 7754 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7755 << E->getSourceRange(); 7756 return ExprError(); 7757 } 7758 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 7759 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 7760 << E->getSourceRange(); 7761 return ExprError(); 7762 } 7763 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 7764 DSAStack->setAssociatedLoops(Result.getExtValue()); 7765 else if (CKind == OMPC_ordered) 7766 DSAStack->setAssociatedLoops(Result.getExtValue()); 7767 return ICE; 7768 } 7769 7770 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 7771 SourceLocation LParenLoc, 7772 SourceLocation EndLoc) { 7773 // OpenMP [2.8.1, simd construct, Description] 7774 // The parameter of the safelen clause must be a constant 7775 // positive integer expression. 7776 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 7777 if (Safelen.isInvalid()) 7778 return nullptr; 7779 return new (Context) 7780 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 7781 } 7782 7783 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 7784 SourceLocation LParenLoc, 7785 SourceLocation EndLoc) { 7786 // OpenMP [2.8.1, simd construct, Description] 7787 // The parameter of the simdlen clause must be a constant 7788 // positive integer expression. 7789 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 7790 if (Simdlen.isInvalid()) 7791 return nullptr; 7792 return new (Context) 7793 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 7794 } 7795 7796 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 7797 SourceLocation StartLoc, 7798 SourceLocation LParenLoc, 7799 SourceLocation EndLoc) { 7800 // OpenMP [2.7.1, loop construct, Description] 7801 // OpenMP [2.8.1, simd construct, Description] 7802 // OpenMP [2.9.6, distribute construct, Description] 7803 // The parameter of the collapse clause must be a constant 7804 // positive integer expression. 7805 ExprResult NumForLoopsResult = 7806 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 7807 if (NumForLoopsResult.isInvalid()) 7808 return nullptr; 7809 return new (Context) 7810 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 7811 } 7812 7813 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 7814 SourceLocation EndLoc, 7815 SourceLocation LParenLoc, 7816 Expr *NumForLoops) { 7817 // OpenMP [2.7.1, loop construct, Description] 7818 // OpenMP [2.8.1, simd construct, Description] 7819 // OpenMP [2.9.6, distribute construct, Description] 7820 // The parameter of the ordered clause must be a constant 7821 // positive integer expression if any. 7822 if (NumForLoops && LParenLoc.isValid()) { 7823 ExprResult NumForLoopsResult = 7824 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 7825 if (NumForLoopsResult.isInvalid()) 7826 return nullptr; 7827 NumForLoops = NumForLoopsResult.get(); 7828 } else 7829 NumForLoops = nullptr; 7830 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 7831 return new (Context) 7832 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 7833 } 7834 7835 OMPClause *Sema::ActOnOpenMPSimpleClause( 7836 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 7837 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 7838 OMPClause *Res = nullptr; 7839 switch (Kind) { 7840 case OMPC_default: 7841 Res = 7842 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 7843 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 7844 break; 7845 case OMPC_proc_bind: 7846 Res = ActOnOpenMPProcBindClause( 7847 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 7848 LParenLoc, EndLoc); 7849 break; 7850 case OMPC_if: 7851 case OMPC_final: 7852 case OMPC_num_threads: 7853 case OMPC_safelen: 7854 case OMPC_simdlen: 7855 case OMPC_collapse: 7856 case OMPC_schedule: 7857 case OMPC_private: 7858 case OMPC_firstprivate: 7859 case OMPC_lastprivate: 7860 case OMPC_shared: 7861 case OMPC_reduction: 7862 case OMPC_task_reduction: 7863 case OMPC_in_reduction: 7864 case OMPC_linear: 7865 case OMPC_aligned: 7866 case OMPC_copyin: 7867 case OMPC_copyprivate: 7868 case OMPC_ordered: 7869 case OMPC_nowait: 7870 case OMPC_untied: 7871 case OMPC_mergeable: 7872 case OMPC_threadprivate: 7873 case OMPC_flush: 7874 case OMPC_read: 7875 case OMPC_write: 7876 case OMPC_update: 7877 case OMPC_capture: 7878 case OMPC_seq_cst: 7879 case OMPC_depend: 7880 case OMPC_device: 7881 case OMPC_threads: 7882 case OMPC_simd: 7883 case OMPC_map: 7884 case OMPC_num_teams: 7885 case OMPC_thread_limit: 7886 case OMPC_priority: 7887 case OMPC_grainsize: 7888 case OMPC_nogroup: 7889 case OMPC_num_tasks: 7890 case OMPC_hint: 7891 case OMPC_dist_schedule: 7892 case OMPC_defaultmap: 7893 case OMPC_unknown: 7894 case OMPC_uniform: 7895 case OMPC_to: 7896 case OMPC_from: 7897 case OMPC_use_device_ptr: 7898 case OMPC_is_device_ptr: 7899 llvm_unreachable("Clause is not allowed."); 7900 } 7901 return Res; 7902 } 7903 7904 static std::string 7905 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 7906 ArrayRef<unsigned> Exclude = llvm::None) { 7907 std::string Values; 7908 unsigned Bound = Last >= 2 ? Last - 2 : 0; 7909 unsigned Skipped = Exclude.size(); 7910 auto S = Exclude.begin(), E = Exclude.end(); 7911 for (unsigned i = First; i < Last; ++i) { 7912 if (std::find(S, E, i) != E) { 7913 --Skipped; 7914 continue; 7915 } 7916 Values += "'"; 7917 Values += getOpenMPSimpleClauseTypeName(K, i); 7918 Values += "'"; 7919 if (i == Bound - Skipped) 7920 Values += " or "; 7921 else if (i != Bound + 1 - Skipped) 7922 Values += ", "; 7923 } 7924 return Values; 7925 } 7926 7927 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 7928 SourceLocation KindKwLoc, 7929 SourceLocation StartLoc, 7930 SourceLocation LParenLoc, 7931 SourceLocation EndLoc) { 7932 if (Kind == OMPC_DEFAULT_unknown) { 7933 static_assert(OMPC_DEFAULT_unknown > 0, 7934 "OMPC_DEFAULT_unknown not greater than 0"); 7935 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7936 << getListOfPossibleValues(OMPC_default, /*First=*/0, 7937 /*Last=*/OMPC_DEFAULT_unknown) 7938 << getOpenMPClauseName(OMPC_default); 7939 return nullptr; 7940 } 7941 switch (Kind) { 7942 case OMPC_DEFAULT_none: 7943 DSAStack->setDefaultDSANone(KindKwLoc); 7944 break; 7945 case OMPC_DEFAULT_shared: 7946 DSAStack->setDefaultDSAShared(KindKwLoc); 7947 break; 7948 case OMPC_DEFAULT_unknown: 7949 llvm_unreachable("Clause kind is not allowed."); 7950 break; 7951 } 7952 return new (Context) 7953 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7954 } 7955 7956 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 7957 SourceLocation KindKwLoc, 7958 SourceLocation StartLoc, 7959 SourceLocation LParenLoc, 7960 SourceLocation EndLoc) { 7961 if (Kind == OMPC_PROC_BIND_unknown) { 7962 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7963 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 7964 /*Last=*/OMPC_PROC_BIND_unknown) 7965 << getOpenMPClauseName(OMPC_proc_bind); 7966 return nullptr; 7967 } 7968 return new (Context) 7969 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7970 } 7971 7972 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 7973 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 7974 SourceLocation StartLoc, SourceLocation LParenLoc, 7975 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 7976 SourceLocation EndLoc) { 7977 OMPClause *Res = nullptr; 7978 switch (Kind) { 7979 case OMPC_schedule: 7980 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 7981 assert(Argument.size() == NumberOfElements && 7982 ArgumentLoc.size() == NumberOfElements); 7983 Res = ActOnOpenMPScheduleClause( 7984 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 7985 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 7986 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 7987 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 7988 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 7989 break; 7990 case OMPC_if: 7991 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 7992 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 7993 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 7994 DelimLoc, EndLoc); 7995 break; 7996 case OMPC_dist_schedule: 7997 Res = ActOnOpenMPDistScheduleClause( 7998 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 7999 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 8000 break; 8001 case OMPC_defaultmap: 8002 enum { Modifier, DefaultmapKind }; 8003 Res = ActOnOpenMPDefaultmapClause( 8004 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 8005 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 8006 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 8007 EndLoc); 8008 break; 8009 case OMPC_final: 8010 case OMPC_num_threads: 8011 case OMPC_safelen: 8012 case OMPC_simdlen: 8013 case OMPC_collapse: 8014 case OMPC_default: 8015 case OMPC_proc_bind: 8016 case OMPC_private: 8017 case OMPC_firstprivate: 8018 case OMPC_lastprivate: 8019 case OMPC_shared: 8020 case OMPC_reduction: 8021 case OMPC_task_reduction: 8022 case OMPC_in_reduction: 8023 case OMPC_linear: 8024 case OMPC_aligned: 8025 case OMPC_copyin: 8026 case OMPC_copyprivate: 8027 case OMPC_ordered: 8028 case OMPC_nowait: 8029 case OMPC_untied: 8030 case OMPC_mergeable: 8031 case OMPC_threadprivate: 8032 case OMPC_flush: 8033 case OMPC_read: 8034 case OMPC_write: 8035 case OMPC_update: 8036 case OMPC_capture: 8037 case OMPC_seq_cst: 8038 case OMPC_depend: 8039 case OMPC_device: 8040 case OMPC_threads: 8041 case OMPC_simd: 8042 case OMPC_map: 8043 case OMPC_num_teams: 8044 case OMPC_thread_limit: 8045 case OMPC_priority: 8046 case OMPC_grainsize: 8047 case OMPC_nogroup: 8048 case OMPC_num_tasks: 8049 case OMPC_hint: 8050 case OMPC_unknown: 8051 case OMPC_uniform: 8052 case OMPC_to: 8053 case OMPC_from: 8054 case OMPC_use_device_ptr: 8055 case OMPC_is_device_ptr: 8056 llvm_unreachable("Clause is not allowed."); 8057 } 8058 return Res; 8059 } 8060 8061 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 8062 OpenMPScheduleClauseModifier M2, 8063 SourceLocation M1Loc, SourceLocation M2Loc) { 8064 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 8065 SmallVector<unsigned, 2> Excluded; 8066 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 8067 Excluded.push_back(M2); 8068 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 8069 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 8070 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 8071 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 8072 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 8073 << getListOfPossibleValues(OMPC_schedule, 8074 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 8075 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 8076 Excluded) 8077 << getOpenMPClauseName(OMPC_schedule); 8078 return true; 8079 } 8080 return false; 8081 } 8082 8083 OMPClause *Sema::ActOnOpenMPScheduleClause( 8084 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 8085 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 8086 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 8087 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 8088 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 8089 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 8090 return nullptr; 8091 // OpenMP, 2.7.1, Loop Construct, Restrictions 8092 // Either the monotonic modifier or the nonmonotonic modifier can be specified 8093 // but not both. 8094 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 8095 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 8096 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 8097 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 8098 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 8099 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 8100 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 8101 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 8102 return nullptr; 8103 } 8104 if (Kind == OMPC_SCHEDULE_unknown) { 8105 std::string Values; 8106 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 8107 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 8108 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 8109 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 8110 Exclude); 8111 } else { 8112 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 8113 /*Last=*/OMPC_SCHEDULE_unknown); 8114 } 8115 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 8116 << Values << getOpenMPClauseName(OMPC_schedule); 8117 return nullptr; 8118 } 8119 // OpenMP, 2.7.1, Loop Construct, Restrictions 8120 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 8121 // schedule(guided). 8122 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 8123 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 8124 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 8125 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 8126 diag::err_omp_schedule_nonmonotonic_static); 8127 return nullptr; 8128 } 8129 Expr *ValExpr = ChunkSize; 8130 Stmt *HelperValStmt = nullptr; 8131 if (ChunkSize) { 8132 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 8133 !ChunkSize->isInstantiationDependent() && 8134 !ChunkSize->containsUnexpandedParameterPack()) { 8135 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 8136 ExprResult Val = 8137 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 8138 if (Val.isInvalid()) 8139 return nullptr; 8140 8141 ValExpr = Val.get(); 8142 8143 // OpenMP [2.7.1, Restrictions] 8144 // chunk_size must be a loop invariant integer expression with a positive 8145 // value. 8146 llvm::APSInt Result; 8147 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 8148 if (Result.isSigned() && !Result.isStrictlyPositive()) { 8149 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 8150 << "schedule" << 1 << ChunkSize->getSourceRange(); 8151 return nullptr; 8152 } 8153 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 8154 !CurContext->isDependentContext()) { 8155 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 8156 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 8157 HelperValStmt = buildPreInits(Context, Captures); 8158 } 8159 } 8160 } 8161 8162 return new (Context) 8163 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 8164 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 8165 } 8166 8167 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 8168 SourceLocation StartLoc, 8169 SourceLocation EndLoc) { 8170 OMPClause *Res = nullptr; 8171 switch (Kind) { 8172 case OMPC_ordered: 8173 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 8174 break; 8175 case OMPC_nowait: 8176 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 8177 break; 8178 case OMPC_untied: 8179 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 8180 break; 8181 case OMPC_mergeable: 8182 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 8183 break; 8184 case OMPC_read: 8185 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 8186 break; 8187 case OMPC_write: 8188 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 8189 break; 8190 case OMPC_update: 8191 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 8192 break; 8193 case OMPC_capture: 8194 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 8195 break; 8196 case OMPC_seq_cst: 8197 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 8198 break; 8199 case OMPC_threads: 8200 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 8201 break; 8202 case OMPC_simd: 8203 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 8204 break; 8205 case OMPC_nogroup: 8206 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 8207 break; 8208 case OMPC_if: 8209 case OMPC_final: 8210 case OMPC_num_threads: 8211 case OMPC_safelen: 8212 case OMPC_simdlen: 8213 case OMPC_collapse: 8214 case OMPC_schedule: 8215 case OMPC_private: 8216 case OMPC_firstprivate: 8217 case OMPC_lastprivate: 8218 case OMPC_shared: 8219 case OMPC_reduction: 8220 case OMPC_task_reduction: 8221 case OMPC_in_reduction: 8222 case OMPC_linear: 8223 case OMPC_aligned: 8224 case OMPC_copyin: 8225 case OMPC_copyprivate: 8226 case OMPC_default: 8227 case OMPC_proc_bind: 8228 case OMPC_threadprivate: 8229 case OMPC_flush: 8230 case OMPC_depend: 8231 case OMPC_device: 8232 case OMPC_map: 8233 case OMPC_num_teams: 8234 case OMPC_thread_limit: 8235 case OMPC_priority: 8236 case OMPC_grainsize: 8237 case OMPC_num_tasks: 8238 case OMPC_hint: 8239 case OMPC_dist_schedule: 8240 case OMPC_defaultmap: 8241 case OMPC_unknown: 8242 case OMPC_uniform: 8243 case OMPC_to: 8244 case OMPC_from: 8245 case OMPC_use_device_ptr: 8246 case OMPC_is_device_ptr: 8247 llvm_unreachable("Clause is not allowed."); 8248 } 8249 return Res; 8250 } 8251 8252 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 8253 SourceLocation EndLoc) { 8254 DSAStack->setNowaitRegion(); 8255 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 8256 } 8257 8258 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 8259 SourceLocation EndLoc) { 8260 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 8261 } 8262 8263 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 8264 SourceLocation EndLoc) { 8265 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 8266 } 8267 8268 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 8269 SourceLocation EndLoc) { 8270 return new (Context) OMPReadClause(StartLoc, EndLoc); 8271 } 8272 8273 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 8274 SourceLocation EndLoc) { 8275 return new (Context) OMPWriteClause(StartLoc, EndLoc); 8276 } 8277 8278 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 8279 SourceLocation EndLoc) { 8280 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 8281 } 8282 8283 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 8284 SourceLocation EndLoc) { 8285 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 8286 } 8287 8288 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 8289 SourceLocation EndLoc) { 8290 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 8291 } 8292 8293 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 8294 SourceLocation EndLoc) { 8295 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 8296 } 8297 8298 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 8299 SourceLocation EndLoc) { 8300 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 8301 } 8302 8303 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 8304 SourceLocation EndLoc) { 8305 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 8306 } 8307 8308 OMPClause *Sema::ActOnOpenMPVarListClause( 8309 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 8310 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 8311 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 8312 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 8313 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 8314 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 8315 SourceLocation DepLinMapLoc) { 8316 OMPClause *Res = nullptr; 8317 switch (Kind) { 8318 case OMPC_private: 8319 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8320 break; 8321 case OMPC_firstprivate: 8322 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8323 break; 8324 case OMPC_lastprivate: 8325 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8326 break; 8327 case OMPC_shared: 8328 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 8329 break; 8330 case OMPC_reduction: 8331 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8332 EndLoc, ReductionIdScopeSpec, ReductionId); 8333 break; 8334 case OMPC_task_reduction: 8335 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8336 EndLoc, ReductionIdScopeSpec, 8337 ReductionId); 8338 break; 8339 case OMPC_in_reduction: 8340 Res = 8341 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8342 EndLoc, ReductionIdScopeSpec, ReductionId); 8343 break; 8344 case OMPC_linear: 8345 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 8346 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 8347 break; 8348 case OMPC_aligned: 8349 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 8350 ColonLoc, EndLoc); 8351 break; 8352 case OMPC_copyin: 8353 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 8354 break; 8355 case OMPC_copyprivate: 8356 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8357 break; 8358 case OMPC_flush: 8359 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 8360 break; 8361 case OMPC_depend: 8362 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 8363 StartLoc, LParenLoc, EndLoc); 8364 break; 8365 case OMPC_map: 8366 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 8367 DepLinMapLoc, ColonLoc, VarList, StartLoc, 8368 LParenLoc, EndLoc); 8369 break; 8370 case OMPC_to: 8371 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 8372 break; 8373 case OMPC_from: 8374 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 8375 break; 8376 case OMPC_use_device_ptr: 8377 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 8378 break; 8379 case OMPC_is_device_ptr: 8380 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 8381 break; 8382 case OMPC_if: 8383 case OMPC_final: 8384 case OMPC_num_threads: 8385 case OMPC_safelen: 8386 case OMPC_simdlen: 8387 case OMPC_collapse: 8388 case OMPC_default: 8389 case OMPC_proc_bind: 8390 case OMPC_schedule: 8391 case OMPC_ordered: 8392 case OMPC_nowait: 8393 case OMPC_untied: 8394 case OMPC_mergeable: 8395 case OMPC_threadprivate: 8396 case OMPC_read: 8397 case OMPC_write: 8398 case OMPC_update: 8399 case OMPC_capture: 8400 case OMPC_seq_cst: 8401 case OMPC_device: 8402 case OMPC_threads: 8403 case OMPC_simd: 8404 case OMPC_num_teams: 8405 case OMPC_thread_limit: 8406 case OMPC_priority: 8407 case OMPC_grainsize: 8408 case OMPC_nogroup: 8409 case OMPC_num_tasks: 8410 case OMPC_hint: 8411 case OMPC_dist_schedule: 8412 case OMPC_defaultmap: 8413 case OMPC_unknown: 8414 case OMPC_uniform: 8415 llvm_unreachable("Clause is not allowed."); 8416 } 8417 return Res; 8418 } 8419 8420 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 8421 ExprObjectKind OK, SourceLocation Loc) { 8422 ExprResult Res = BuildDeclRefExpr( 8423 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 8424 if (!Res.isUsable()) 8425 return ExprError(); 8426 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 8427 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 8428 if (!Res.isUsable()) 8429 return ExprError(); 8430 } 8431 if (VK != VK_LValue && Res.get()->isGLValue()) { 8432 Res = DefaultLvalueConversion(Res.get()); 8433 if (!Res.isUsable()) 8434 return ExprError(); 8435 } 8436 return Res; 8437 } 8438 8439 static std::pair<ValueDecl *, bool> 8440 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 8441 SourceRange &ERange, bool AllowArraySection = false) { 8442 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 8443 RefExpr->containsUnexpandedParameterPack()) 8444 return std::make_pair(nullptr, true); 8445 8446 // OpenMP [3.1, C/C++] 8447 // A list item is a variable name. 8448 // OpenMP [2.9.3.3, Restrictions, p.1] 8449 // A variable that is part of another variable (as an array or 8450 // structure element) cannot appear in a private clause. 8451 RefExpr = RefExpr->IgnoreParens(); 8452 enum { 8453 NoArrayExpr = -1, 8454 ArraySubscript = 0, 8455 OMPArraySection = 1 8456 } IsArrayExpr = NoArrayExpr; 8457 if (AllowArraySection) { 8458 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 8459 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 8460 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 8461 Base = TempASE->getBase()->IgnoreParenImpCasts(); 8462 RefExpr = Base; 8463 IsArrayExpr = ArraySubscript; 8464 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 8465 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 8466 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 8467 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 8468 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 8469 Base = TempASE->getBase()->IgnoreParenImpCasts(); 8470 RefExpr = Base; 8471 IsArrayExpr = OMPArraySection; 8472 } 8473 } 8474 ELoc = RefExpr->getExprLoc(); 8475 ERange = RefExpr->getSourceRange(); 8476 RefExpr = RefExpr->IgnoreParenImpCasts(); 8477 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 8478 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 8479 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 8480 (S.getCurrentThisType().isNull() || !ME || 8481 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 8482 !isa<FieldDecl>(ME->getMemberDecl()))) { 8483 if (IsArrayExpr != NoArrayExpr) 8484 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 8485 << ERange; 8486 else { 8487 S.Diag(ELoc, 8488 AllowArraySection 8489 ? diag::err_omp_expected_var_name_member_expr_or_array_item 8490 : diag::err_omp_expected_var_name_member_expr) 8491 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 8492 } 8493 return std::make_pair(nullptr, false); 8494 } 8495 return std::make_pair( 8496 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 8497 } 8498 8499 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 8500 SourceLocation StartLoc, 8501 SourceLocation LParenLoc, 8502 SourceLocation EndLoc) { 8503 SmallVector<Expr *, 8> Vars; 8504 SmallVector<Expr *, 8> PrivateCopies; 8505 for (auto &RefExpr : VarList) { 8506 assert(RefExpr && "NULL expr in OpenMP private clause."); 8507 SourceLocation ELoc; 8508 SourceRange ERange; 8509 Expr *SimpleRefExpr = RefExpr; 8510 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8511 if (Res.second) { 8512 // It will be analyzed later. 8513 Vars.push_back(RefExpr); 8514 PrivateCopies.push_back(nullptr); 8515 } 8516 ValueDecl *D = Res.first; 8517 if (!D) 8518 continue; 8519 8520 QualType Type = D->getType(); 8521 auto *VD = dyn_cast<VarDecl>(D); 8522 8523 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8524 // A variable that appears in a private clause must not have an incomplete 8525 // type or a reference type. 8526 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 8527 continue; 8528 Type = Type.getNonReferenceType(); 8529 8530 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8531 // in a Construct] 8532 // Variables with the predetermined data-sharing attributes may not be 8533 // listed in data-sharing attributes clauses, except for the cases 8534 // listed below. For these exceptions only, listing a predetermined 8535 // variable in a data-sharing attribute clause is allowed and overrides 8536 // the variable's predetermined data-sharing attributes. 8537 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8538 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 8539 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8540 << getOpenMPClauseName(OMPC_private); 8541 ReportOriginalDSA(*this, DSAStack, D, DVar); 8542 continue; 8543 } 8544 8545 auto CurrDir = DSAStack->getCurrentDirective(); 8546 // Variably modified types are not supported for tasks. 8547 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8548 isOpenMPTaskingDirective(CurrDir)) { 8549 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8550 << getOpenMPClauseName(OMPC_private) << Type 8551 << getOpenMPDirectiveName(CurrDir); 8552 bool IsDecl = 8553 !VD || 8554 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8555 Diag(D->getLocation(), 8556 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8557 << D; 8558 continue; 8559 } 8560 8561 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8562 // A list item cannot appear in both a map clause and a data-sharing 8563 // attribute clause on the same construct 8564 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 8565 CurrDir == OMPD_target_teams || 8566 CurrDir == OMPD_target_teams_distribute || 8567 CurrDir == OMPD_target_teams_distribute_parallel_for || 8568 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 8569 CurrDir == OMPD_target_teams_distribute_simd || 8570 CurrDir == OMPD_target_parallel_for_simd || 8571 CurrDir == OMPD_target_parallel_for) { 8572 OpenMPClauseKind ConflictKind; 8573 if (DSAStack->checkMappableExprComponentListsForDecl( 8574 VD, /*CurrentRegionOnly=*/true, 8575 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 8576 OpenMPClauseKind WhereFoundClauseKind) -> bool { 8577 ConflictKind = WhereFoundClauseKind; 8578 return true; 8579 })) { 8580 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 8581 << getOpenMPClauseName(OMPC_private) 8582 << getOpenMPClauseName(ConflictKind) 8583 << getOpenMPDirectiveName(CurrDir); 8584 ReportOriginalDSA(*this, DSAStack, D, DVar); 8585 continue; 8586 } 8587 } 8588 8589 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 8590 // A variable of class type (or array thereof) that appears in a private 8591 // clause requires an accessible, unambiguous default constructor for the 8592 // class type. 8593 // Generate helper private variable and initialize it with the default 8594 // value. The address of the original variable is replaced by the address of 8595 // the new private variable in CodeGen. This new variable is not added to 8596 // IdResolver, so the code in the OpenMP region uses original variable for 8597 // proper diagnostics. 8598 Type = Type.getUnqualifiedType(); 8599 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8600 D->hasAttrs() ? &D->getAttrs() : nullptr); 8601 ActOnUninitializedDecl(VDPrivate); 8602 if (VDPrivate->isInvalidDecl()) 8603 continue; 8604 auto VDPrivateRefExpr = buildDeclRefExpr( 8605 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 8606 8607 DeclRefExpr *Ref = nullptr; 8608 if (!VD && !CurContext->isDependentContext()) 8609 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8610 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 8611 Vars.push_back((VD || CurContext->isDependentContext()) 8612 ? RefExpr->IgnoreParens() 8613 : Ref); 8614 PrivateCopies.push_back(VDPrivateRefExpr); 8615 } 8616 8617 if (Vars.empty()) 8618 return nullptr; 8619 8620 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 8621 PrivateCopies); 8622 } 8623 8624 namespace { 8625 class DiagsUninitializedSeveretyRAII { 8626 private: 8627 DiagnosticsEngine &Diags; 8628 SourceLocation SavedLoc; 8629 bool IsIgnored; 8630 8631 public: 8632 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 8633 bool IsIgnored) 8634 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 8635 if (!IsIgnored) { 8636 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 8637 /*Map*/ diag::Severity::Ignored, Loc); 8638 } 8639 } 8640 ~DiagsUninitializedSeveretyRAII() { 8641 if (!IsIgnored) 8642 Diags.popMappings(SavedLoc); 8643 } 8644 }; 8645 } 8646 8647 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 8648 SourceLocation StartLoc, 8649 SourceLocation LParenLoc, 8650 SourceLocation EndLoc) { 8651 SmallVector<Expr *, 8> Vars; 8652 SmallVector<Expr *, 8> PrivateCopies; 8653 SmallVector<Expr *, 8> Inits; 8654 SmallVector<Decl *, 4> ExprCaptures; 8655 bool IsImplicitClause = 8656 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 8657 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 8658 8659 for (auto &RefExpr : VarList) { 8660 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 8661 SourceLocation ELoc; 8662 SourceRange ERange; 8663 Expr *SimpleRefExpr = RefExpr; 8664 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8665 if (Res.second) { 8666 // It will be analyzed later. 8667 Vars.push_back(RefExpr); 8668 PrivateCopies.push_back(nullptr); 8669 Inits.push_back(nullptr); 8670 } 8671 ValueDecl *D = Res.first; 8672 if (!D) 8673 continue; 8674 8675 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 8676 QualType Type = D->getType(); 8677 auto *VD = dyn_cast<VarDecl>(D); 8678 8679 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8680 // A variable that appears in a private clause must not have an incomplete 8681 // type or a reference type. 8682 if (RequireCompleteType(ELoc, Type, 8683 diag::err_omp_firstprivate_incomplete_type)) 8684 continue; 8685 Type = Type.getNonReferenceType(); 8686 8687 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 8688 // A variable of class type (or array thereof) that appears in a private 8689 // clause requires an accessible, unambiguous copy constructor for the 8690 // class type. 8691 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 8692 8693 // If an implicit firstprivate variable found it was checked already. 8694 DSAStackTy::DSAVarData TopDVar; 8695 if (!IsImplicitClause) { 8696 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8697 TopDVar = DVar; 8698 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8699 bool IsConstant = ElemType.isConstant(Context); 8700 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 8701 // A list item that specifies a given variable may not appear in more 8702 // than one clause on the same directive, except that a variable may be 8703 // specified in both firstprivate and lastprivate clauses. 8704 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8705 // A list item may appear in a firstprivate or lastprivate clause but not 8706 // both. 8707 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 8708 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) && 8709 DVar.RefExpr) { 8710 Diag(ELoc, diag::err_omp_wrong_dsa) 8711 << getOpenMPClauseName(DVar.CKind) 8712 << getOpenMPClauseName(OMPC_firstprivate); 8713 ReportOriginalDSA(*this, DSAStack, D, DVar); 8714 continue; 8715 } 8716 8717 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8718 // in a Construct] 8719 // Variables with the predetermined data-sharing attributes may not be 8720 // listed in data-sharing attributes clauses, except for the cases 8721 // listed below. For these exceptions only, listing a predetermined 8722 // variable in a data-sharing attribute clause is allowed and overrides 8723 // the variable's predetermined data-sharing attributes. 8724 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8725 // in a Construct, C/C++, p.2] 8726 // Variables with const-qualified type having no mutable member may be 8727 // listed in a firstprivate clause, even if they are static data members. 8728 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 8729 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 8730 Diag(ELoc, diag::err_omp_wrong_dsa) 8731 << getOpenMPClauseName(DVar.CKind) 8732 << getOpenMPClauseName(OMPC_firstprivate); 8733 ReportOriginalDSA(*this, DSAStack, D, DVar); 8734 continue; 8735 } 8736 8737 // OpenMP [2.9.3.4, Restrictions, p.2] 8738 // A list item that is private within a parallel region must not appear 8739 // in a firstprivate clause on a worksharing construct if any of the 8740 // worksharing regions arising from the worksharing construct ever bind 8741 // to any of the parallel regions arising from the parallel construct. 8742 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8743 // A list item that is private within a teams region must not appear in a 8744 // firstprivate clause on a distribute construct if any of the distribute 8745 // regions arising from the distribute construct ever bind to any of the 8746 // teams regions arising from the teams construct. 8747 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8748 // A list item that appears in a reduction clause of a teams construct 8749 // must not appear in a firstprivate clause on a distribute construct if 8750 // any of the distribute regions arising from the distribute construct 8751 // ever bind to any of the teams regions arising from the teams construct. 8752 if ((isOpenMPWorksharingDirective(CurrDir) || 8753 isOpenMPDistributeDirective(CurrDir)) && 8754 !isOpenMPParallelDirective(CurrDir) && 8755 !isOpenMPTeamsDirective(CurrDir)) { 8756 DVar = DSAStack->getImplicitDSA(D, true); 8757 if (DVar.CKind != OMPC_shared && 8758 (isOpenMPParallelDirective(DVar.DKind) || 8759 isOpenMPTeamsDirective(DVar.DKind) || 8760 DVar.DKind == OMPD_unknown)) { 8761 Diag(ELoc, diag::err_omp_required_access) 8762 << getOpenMPClauseName(OMPC_firstprivate) 8763 << getOpenMPClauseName(OMPC_shared); 8764 ReportOriginalDSA(*this, DSAStack, D, DVar); 8765 continue; 8766 } 8767 } 8768 // OpenMP [2.9.3.4, Restrictions, p.3] 8769 // A list item that appears in a reduction clause of a parallel construct 8770 // must not appear in a firstprivate clause on a worksharing or task 8771 // construct if any of the worksharing or task regions arising from the 8772 // worksharing or task construct ever bind to any of the parallel regions 8773 // arising from the parallel construct. 8774 // OpenMP [2.9.3.4, Restrictions, p.4] 8775 // A list item that appears in a reduction clause in worksharing 8776 // construct must not appear in a firstprivate clause in a task construct 8777 // encountered during execution of any of the worksharing regions arising 8778 // from the worksharing construct. 8779 if (isOpenMPTaskingDirective(CurrDir)) { 8780 DVar = DSAStack->hasInnermostDSA( 8781 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8782 [](OpenMPDirectiveKind K) -> bool { 8783 return isOpenMPParallelDirective(K) || 8784 isOpenMPWorksharingDirective(K) || 8785 isOpenMPTeamsDirective(K); 8786 }, 8787 /*FromParent=*/true); 8788 if (DVar.CKind == OMPC_reduction && 8789 (isOpenMPParallelDirective(DVar.DKind) || 8790 isOpenMPWorksharingDirective(DVar.DKind) || 8791 isOpenMPTeamsDirective(DVar.DKind))) { 8792 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 8793 << getOpenMPDirectiveName(DVar.DKind); 8794 ReportOriginalDSA(*this, DSAStack, D, DVar); 8795 continue; 8796 } 8797 } 8798 8799 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8800 // A list item cannot appear in both a map clause and a data-sharing 8801 // attribute clause on the same construct 8802 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 8803 CurrDir == OMPD_target_teams || 8804 CurrDir == OMPD_target_teams_distribute || 8805 CurrDir == OMPD_target_teams_distribute_parallel_for || 8806 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 8807 CurrDir == OMPD_target_teams_distribute_simd || 8808 CurrDir == OMPD_target_parallel_for_simd || 8809 CurrDir == OMPD_target_parallel_for) { 8810 OpenMPClauseKind ConflictKind; 8811 if (DSAStack->checkMappableExprComponentListsForDecl( 8812 VD, /*CurrentRegionOnly=*/true, 8813 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 8814 OpenMPClauseKind WhereFoundClauseKind) -> bool { 8815 ConflictKind = WhereFoundClauseKind; 8816 return true; 8817 })) { 8818 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 8819 << getOpenMPClauseName(OMPC_firstprivate) 8820 << getOpenMPClauseName(ConflictKind) 8821 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8822 ReportOriginalDSA(*this, DSAStack, D, DVar); 8823 continue; 8824 } 8825 } 8826 } 8827 8828 // Variably modified types are not supported for tasks. 8829 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8830 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 8831 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8832 << getOpenMPClauseName(OMPC_firstprivate) << Type 8833 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8834 bool IsDecl = 8835 !VD || 8836 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8837 Diag(D->getLocation(), 8838 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8839 << D; 8840 continue; 8841 } 8842 8843 Type = Type.getUnqualifiedType(); 8844 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8845 D->hasAttrs() ? &D->getAttrs() : nullptr); 8846 // Generate helper private variable and initialize it with the value of the 8847 // original variable. The address of the original variable is replaced by 8848 // the address of the new private variable in the CodeGen. This new variable 8849 // is not added to IdResolver, so the code in the OpenMP region uses 8850 // original variable for proper diagnostics and variable capturing. 8851 Expr *VDInitRefExpr = nullptr; 8852 // For arrays generate initializer for single element and replace it by the 8853 // original array element in CodeGen. 8854 if (Type->isArrayType()) { 8855 auto VDInit = 8856 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 8857 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 8858 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 8859 ElemType = ElemType.getUnqualifiedType(); 8860 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 8861 ".firstprivate.temp"); 8862 InitializedEntity Entity = 8863 InitializedEntity::InitializeVariable(VDInitTemp); 8864 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 8865 8866 InitializationSequence InitSeq(*this, Entity, Kind, Init); 8867 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 8868 if (Result.isInvalid()) 8869 VDPrivate->setInvalidDecl(); 8870 else 8871 VDPrivate->setInit(Result.getAs<Expr>()); 8872 // Remove temp variable declaration. 8873 Context.Deallocate(VDInitTemp); 8874 } else { 8875 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 8876 ".firstprivate.temp"); 8877 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 8878 RefExpr->getExprLoc()); 8879 AddInitializerToDecl(VDPrivate, 8880 DefaultLvalueConversion(VDInitRefExpr).get(), 8881 /*DirectInit=*/false); 8882 } 8883 if (VDPrivate->isInvalidDecl()) { 8884 if (IsImplicitClause) { 8885 Diag(RefExpr->getExprLoc(), 8886 diag::note_omp_task_predetermined_firstprivate_here); 8887 } 8888 continue; 8889 } 8890 CurContext->addDecl(VDPrivate); 8891 auto VDPrivateRefExpr = buildDeclRefExpr( 8892 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 8893 RefExpr->getExprLoc()); 8894 DeclRefExpr *Ref = nullptr; 8895 if (!VD && !CurContext->isDependentContext()) { 8896 if (TopDVar.CKind == OMPC_lastprivate) 8897 Ref = TopDVar.PrivateCopy; 8898 else { 8899 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8900 if (!IsOpenMPCapturedDecl(D)) 8901 ExprCaptures.push_back(Ref->getDecl()); 8902 } 8903 } 8904 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 8905 Vars.push_back((VD || CurContext->isDependentContext()) 8906 ? RefExpr->IgnoreParens() 8907 : Ref); 8908 PrivateCopies.push_back(VDPrivateRefExpr); 8909 Inits.push_back(VDInitRefExpr); 8910 } 8911 8912 if (Vars.empty()) 8913 return nullptr; 8914 8915 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8916 Vars, PrivateCopies, Inits, 8917 buildPreInits(Context, ExprCaptures)); 8918 } 8919 8920 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 8921 SourceLocation StartLoc, 8922 SourceLocation LParenLoc, 8923 SourceLocation EndLoc) { 8924 SmallVector<Expr *, 8> Vars; 8925 SmallVector<Expr *, 8> SrcExprs; 8926 SmallVector<Expr *, 8> DstExprs; 8927 SmallVector<Expr *, 8> AssignmentOps; 8928 SmallVector<Decl *, 4> ExprCaptures; 8929 SmallVector<Expr *, 4> ExprPostUpdates; 8930 for (auto &RefExpr : VarList) { 8931 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8932 SourceLocation ELoc; 8933 SourceRange ERange; 8934 Expr *SimpleRefExpr = RefExpr; 8935 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8936 if (Res.second) { 8937 // It will be analyzed later. 8938 Vars.push_back(RefExpr); 8939 SrcExprs.push_back(nullptr); 8940 DstExprs.push_back(nullptr); 8941 AssignmentOps.push_back(nullptr); 8942 } 8943 ValueDecl *D = Res.first; 8944 if (!D) 8945 continue; 8946 8947 QualType Type = D->getType(); 8948 auto *VD = dyn_cast<VarDecl>(D); 8949 8950 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 8951 // A variable that appears in a lastprivate clause must not have an 8952 // incomplete type or a reference type. 8953 if (RequireCompleteType(ELoc, Type, 8954 diag::err_omp_lastprivate_incomplete_type)) 8955 continue; 8956 Type = Type.getNonReferenceType(); 8957 8958 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8959 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8960 // in a Construct] 8961 // Variables with the predetermined data-sharing attributes may not be 8962 // listed in data-sharing attributes clauses, except for the cases 8963 // listed below. 8964 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8965 // A list item may appear in a firstprivate or lastprivate clause but not 8966 // both. 8967 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8968 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 8969 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) && 8970 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 8971 Diag(ELoc, diag::err_omp_wrong_dsa) 8972 << getOpenMPClauseName(DVar.CKind) 8973 << getOpenMPClauseName(OMPC_lastprivate); 8974 ReportOriginalDSA(*this, DSAStack, D, DVar); 8975 continue; 8976 } 8977 8978 // OpenMP [2.14.3.5, Restrictions, p.2] 8979 // A list item that is private within a parallel region, or that appears in 8980 // the reduction clause of a parallel construct, must not appear in a 8981 // lastprivate clause on a worksharing construct if any of the corresponding 8982 // worksharing regions ever binds to any of the corresponding parallel 8983 // regions. 8984 DSAStackTy::DSAVarData TopDVar = DVar; 8985 if (isOpenMPWorksharingDirective(CurrDir) && 8986 !isOpenMPParallelDirective(CurrDir) && 8987 !isOpenMPTeamsDirective(CurrDir)) { 8988 DVar = DSAStack->getImplicitDSA(D, true); 8989 if (DVar.CKind != OMPC_shared) { 8990 Diag(ELoc, diag::err_omp_required_access) 8991 << getOpenMPClauseName(OMPC_lastprivate) 8992 << getOpenMPClauseName(OMPC_shared); 8993 ReportOriginalDSA(*this, DSAStack, D, DVar); 8994 continue; 8995 } 8996 } 8997 8998 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 8999 // A variable of class type (or array thereof) that appears in a 9000 // lastprivate clause requires an accessible, unambiguous default 9001 // constructor for the class type, unless the list item is also specified 9002 // in a firstprivate clause. 9003 // A variable of class type (or array thereof) that appears in a 9004 // lastprivate clause requires an accessible, unambiguous copy assignment 9005 // operator for the class type. 9006 Type = Context.getBaseElementType(Type).getNonReferenceType(); 9007 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 9008 Type.getUnqualifiedType(), ".lastprivate.src", 9009 D->hasAttrs() ? &D->getAttrs() : nullptr); 9010 auto *PseudoSrcExpr = 9011 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 9012 auto *DstVD = 9013 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 9014 D->hasAttrs() ? &D->getAttrs() : nullptr); 9015 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 9016 // For arrays generate assignment operation for single element and replace 9017 // it by the original array element in CodeGen. 9018 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 9019 PseudoDstExpr, PseudoSrcExpr); 9020 if (AssignmentOp.isInvalid()) 9021 continue; 9022 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 9023 /*DiscardedValue=*/true); 9024 if (AssignmentOp.isInvalid()) 9025 continue; 9026 9027 DeclRefExpr *Ref = nullptr; 9028 if (!VD && !CurContext->isDependentContext()) { 9029 if (TopDVar.CKind == OMPC_firstprivate) 9030 Ref = TopDVar.PrivateCopy; 9031 else { 9032 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9033 if (!IsOpenMPCapturedDecl(D)) 9034 ExprCaptures.push_back(Ref->getDecl()); 9035 } 9036 if (TopDVar.CKind == OMPC_firstprivate || 9037 (!IsOpenMPCapturedDecl(D) && 9038 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 9039 ExprResult RefRes = DefaultLvalueConversion(Ref); 9040 if (!RefRes.isUsable()) 9041 continue; 9042 ExprResult PostUpdateRes = 9043 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 9044 RefRes.get()); 9045 if (!PostUpdateRes.isUsable()) 9046 continue; 9047 ExprPostUpdates.push_back( 9048 IgnoredValueConversions(PostUpdateRes.get()).get()); 9049 } 9050 } 9051 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 9052 Vars.push_back((VD || CurContext->isDependentContext()) 9053 ? RefExpr->IgnoreParens() 9054 : Ref); 9055 SrcExprs.push_back(PseudoSrcExpr); 9056 DstExprs.push_back(PseudoDstExpr); 9057 AssignmentOps.push_back(AssignmentOp.get()); 9058 } 9059 9060 if (Vars.empty()) 9061 return nullptr; 9062 9063 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9064 Vars, SrcExprs, DstExprs, AssignmentOps, 9065 buildPreInits(Context, ExprCaptures), 9066 buildPostUpdate(*this, ExprPostUpdates)); 9067 } 9068 9069 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 9070 SourceLocation StartLoc, 9071 SourceLocation LParenLoc, 9072 SourceLocation EndLoc) { 9073 SmallVector<Expr *, 8> Vars; 9074 for (auto &RefExpr : VarList) { 9075 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 9076 SourceLocation ELoc; 9077 SourceRange ERange; 9078 Expr *SimpleRefExpr = RefExpr; 9079 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9080 if (Res.second) { 9081 // It will be analyzed later. 9082 Vars.push_back(RefExpr); 9083 } 9084 ValueDecl *D = Res.first; 9085 if (!D) 9086 continue; 9087 9088 auto *VD = dyn_cast<VarDecl>(D); 9089 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9090 // in a Construct] 9091 // Variables with the predetermined data-sharing attributes may not be 9092 // listed in data-sharing attributes clauses, except for the cases 9093 // listed below. For these exceptions only, listing a predetermined 9094 // variable in a data-sharing attribute clause is allowed and overrides 9095 // the variable's predetermined data-sharing attributes. 9096 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9097 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 9098 DVar.RefExpr) { 9099 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9100 << getOpenMPClauseName(OMPC_shared); 9101 ReportOriginalDSA(*this, DSAStack, D, DVar); 9102 continue; 9103 } 9104 9105 DeclRefExpr *Ref = nullptr; 9106 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 9107 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9108 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 9109 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 9110 ? RefExpr->IgnoreParens() 9111 : Ref); 9112 } 9113 9114 if (Vars.empty()) 9115 return nullptr; 9116 9117 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 9118 } 9119 9120 namespace { 9121 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 9122 DSAStackTy *Stack; 9123 9124 public: 9125 bool VisitDeclRefExpr(DeclRefExpr *E) { 9126 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 9127 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 9128 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 9129 return false; 9130 if (DVar.CKind != OMPC_unknown) 9131 return true; 9132 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 9133 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 9134 /*FromParent=*/true); 9135 if (DVarPrivate.CKind != OMPC_unknown) 9136 return true; 9137 return false; 9138 } 9139 return false; 9140 } 9141 bool VisitStmt(Stmt *S) { 9142 for (auto Child : S->children()) { 9143 if (Child && Visit(Child)) 9144 return true; 9145 } 9146 return false; 9147 } 9148 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 9149 }; 9150 } // namespace 9151 9152 namespace { 9153 // Transform MemberExpression for specified FieldDecl of current class to 9154 // DeclRefExpr to specified OMPCapturedExprDecl. 9155 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 9156 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 9157 ValueDecl *Field; 9158 DeclRefExpr *CapturedExpr; 9159 9160 public: 9161 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 9162 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 9163 9164 ExprResult TransformMemberExpr(MemberExpr *E) { 9165 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 9166 E->getMemberDecl() == Field) { 9167 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 9168 return CapturedExpr; 9169 } 9170 return BaseTransform::TransformMemberExpr(E); 9171 } 9172 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 9173 }; 9174 } // namespace 9175 9176 template <typename T> 9177 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 9178 const llvm::function_ref<T(ValueDecl *)> &Gen) { 9179 for (auto &Set : Lookups) { 9180 for (auto *D : Set) { 9181 if (auto Res = Gen(cast<ValueDecl>(D))) 9182 return Res; 9183 } 9184 } 9185 return T(); 9186 } 9187 9188 static ExprResult 9189 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 9190 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 9191 const DeclarationNameInfo &ReductionId, QualType Ty, 9192 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 9193 if (ReductionIdScopeSpec.isInvalid()) 9194 return ExprError(); 9195 SmallVector<UnresolvedSet<8>, 4> Lookups; 9196 if (S) { 9197 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 9198 Lookup.suppressDiagnostics(); 9199 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 9200 auto *D = Lookup.getRepresentativeDecl(); 9201 do { 9202 S = S->getParent(); 9203 } while (S && !S->isDeclScope(D)); 9204 if (S) 9205 S = S->getParent(); 9206 Lookups.push_back(UnresolvedSet<8>()); 9207 Lookups.back().append(Lookup.begin(), Lookup.end()); 9208 Lookup.clear(); 9209 } 9210 } else if (auto *ULE = 9211 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 9212 Lookups.push_back(UnresolvedSet<8>()); 9213 Decl *PrevD = nullptr; 9214 for (auto *D : ULE->decls()) { 9215 if (D == PrevD) 9216 Lookups.push_back(UnresolvedSet<8>()); 9217 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 9218 Lookups.back().addDecl(DRD); 9219 PrevD = D; 9220 } 9221 } 9222 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 9223 Ty->isInstantiationDependentType() || 9224 Ty->containsUnexpandedParameterPack() || 9225 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 9226 return !D->isInvalidDecl() && 9227 (D->getType()->isDependentType() || 9228 D->getType()->isInstantiationDependentType() || 9229 D->getType()->containsUnexpandedParameterPack()); 9230 })) { 9231 UnresolvedSet<8> ResSet; 9232 for (auto &Set : Lookups) { 9233 ResSet.append(Set.begin(), Set.end()); 9234 // The last item marks the end of all declarations at the specified scope. 9235 ResSet.addDecl(Set[Set.size() - 1]); 9236 } 9237 return UnresolvedLookupExpr::Create( 9238 SemaRef.Context, /*NamingClass=*/nullptr, 9239 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 9240 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 9241 } 9242 if (auto *VD = filterLookupForUDR<ValueDecl *>( 9243 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 9244 if (!D->isInvalidDecl() && 9245 SemaRef.Context.hasSameType(D->getType(), Ty)) 9246 return D; 9247 return nullptr; 9248 })) 9249 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 9250 if (auto *VD = filterLookupForUDR<ValueDecl *>( 9251 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 9252 if (!D->isInvalidDecl() && 9253 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 9254 !Ty.isMoreQualifiedThan(D->getType())) 9255 return D; 9256 return nullptr; 9257 })) { 9258 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9259 /*DetectVirtual=*/false); 9260 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 9261 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 9262 VD->getType().getUnqualifiedType()))) { 9263 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 9264 /*DiagID=*/0) != 9265 Sema::AR_inaccessible) { 9266 SemaRef.BuildBasePathArray(Paths, BasePath); 9267 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 9268 } 9269 } 9270 } 9271 } 9272 if (ReductionIdScopeSpec.isSet()) { 9273 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 9274 return ExprError(); 9275 } 9276 return ExprEmpty(); 9277 } 9278 9279 namespace { 9280 /// Data for the reduction-based clauses. 9281 struct ReductionData { 9282 /// List of original reduction items. 9283 SmallVector<Expr *, 8> Vars; 9284 /// List of private copies of the reduction items. 9285 SmallVector<Expr *, 8> Privates; 9286 /// LHS expressions for the reduction_op expressions. 9287 SmallVector<Expr *, 8> LHSs; 9288 /// RHS expressions for the reduction_op expressions. 9289 SmallVector<Expr *, 8> RHSs; 9290 /// Reduction operation expression. 9291 SmallVector<Expr *, 8> ReductionOps; 9292 /// Taskgroup descriptors for the corresponding reduction items in 9293 /// in_reduction clauses. 9294 SmallVector<Expr *, 8> TaskgroupDescriptors; 9295 /// List of captures for clause. 9296 SmallVector<Decl *, 4> ExprCaptures; 9297 /// List of postupdate expressions. 9298 SmallVector<Expr *, 4> ExprPostUpdates; 9299 ReductionData() = delete; 9300 /// Reserves required memory for the reduction data. 9301 ReductionData(unsigned Size) { 9302 Vars.reserve(Size); 9303 Privates.reserve(Size); 9304 LHSs.reserve(Size); 9305 RHSs.reserve(Size); 9306 ReductionOps.reserve(Size); 9307 TaskgroupDescriptors.reserve(Size); 9308 ExprCaptures.reserve(Size); 9309 ExprPostUpdates.reserve(Size); 9310 } 9311 /// Stores reduction item and reduction operation only (required for dependent 9312 /// reduction item). 9313 void push(Expr *Item, Expr *ReductionOp) { 9314 Vars.emplace_back(Item); 9315 Privates.emplace_back(nullptr); 9316 LHSs.emplace_back(nullptr); 9317 RHSs.emplace_back(nullptr); 9318 ReductionOps.emplace_back(ReductionOp); 9319 TaskgroupDescriptors.emplace_back(nullptr); 9320 } 9321 /// Stores reduction data. 9322 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 9323 Expr *TaskgroupDescriptor) { 9324 Vars.emplace_back(Item); 9325 Privates.emplace_back(Private); 9326 LHSs.emplace_back(LHS); 9327 RHSs.emplace_back(RHS); 9328 ReductionOps.emplace_back(ReductionOp); 9329 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 9330 } 9331 }; 9332 } // namespace 9333 9334 static bool CheckOMPArraySectionConstantForReduction( 9335 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 9336 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 9337 const Expr *Length = OASE->getLength(); 9338 if (Length == nullptr) { 9339 // For array sections of the form [1:] or [:], we would need to analyze 9340 // the lower bound... 9341 if (OASE->getColonLoc().isValid()) 9342 return false; 9343 9344 // This is an array subscript which has implicit length 1! 9345 SingleElement = true; 9346 ArraySizes.push_back(llvm::APSInt::get(1)); 9347 } else { 9348 llvm::APSInt ConstantLengthValue; 9349 if (!Length->EvaluateAsInt(ConstantLengthValue, Context)) 9350 return false; 9351 9352 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 9353 ArraySizes.push_back(ConstantLengthValue); 9354 } 9355 9356 // Get the base of this array section and walk up from there. 9357 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 9358 9359 // We require length = 1 for all array sections except the right-most to 9360 // guarantee that the memory region is contiguous and has no holes in it. 9361 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 9362 Length = TempOASE->getLength(); 9363 if (Length == nullptr) { 9364 // For array sections of the form [1:] or [:], we would need to analyze 9365 // the lower bound... 9366 if (OASE->getColonLoc().isValid()) 9367 return false; 9368 9369 // This is an array subscript which has implicit length 1! 9370 ArraySizes.push_back(llvm::APSInt::get(1)); 9371 } else { 9372 llvm::APSInt ConstantLengthValue; 9373 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) || 9374 ConstantLengthValue.getSExtValue() != 1) 9375 return false; 9376 9377 ArraySizes.push_back(ConstantLengthValue); 9378 } 9379 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 9380 } 9381 9382 // If we have a single element, we don't need to add the implicit lengths. 9383 if (!SingleElement) { 9384 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 9385 // Has implicit length 1! 9386 ArraySizes.push_back(llvm::APSInt::get(1)); 9387 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9388 } 9389 } 9390 9391 // This array section can be privatized as a single value or as a constant 9392 // sized array. 9393 return true; 9394 } 9395 9396 static bool ActOnOMPReductionKindClause( 9397 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 9398 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 9399 SourceLocation ColonLoc, SourceLocation EndLoc, 9400 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 9401 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 9402 auto DN = ReductionId.getName(); 9403 auto OOK = DN.getCXXOverloadedOperator(); 9404 BinaryOperatorKind BOK = BO_Comma; 9405 9406 ASTContext &Context = S.Context; 9407 // OpenMP [2.14.3.6, reduction clause] 9408 // C 9409 // reduction-identifier is either an identifier or one of the following 9410 // operators: +, -, *, &, |, ^, && and || 9411 // C++ 9412 // reduction-identifier is either an id-expression or one of the following 9413 // operators: +, -, *, &, |, ^, && and || 9414 switch (OOK) { 9415 case OO_Plus: 9416 case OO_Minus: 9417 BOK = BO_Add; 9418 break; 9419 case OO_Star: 9420 BOK = BO_Mul; 9421 break; 9422 case OO_Amp: 9423 BOK = BO_And; 9424 break; 9425 case OO_Pipe: 9426 BOK = BO_Or; 9427 break; 9428 case OO_Caret: 9429 BOK = BO_Xor; 9430 break; 9431 case OO_AmpAmp: 9432 BOK = BO_LAnd; 9433 break; 9434 case OO_PipePipe: 9435 BOK = BO_LOr; 9436 break; 9437 case OO_New: 9438 case OO_Delete: 9439 case OO_Array_New: 9440 case OO_Array_Delete: 9441 case OO_Slash: 9442 case OO_Percent: 9443 case OO_Tilde: 9444 case OO_Exclaim: 9445 case OO_Equal: 9446 case OO_Less: 9447 case OO_Greater: 9448 case OO_LessEqual: 9449 case OO_GreaterEqual: 9450 case OO_PlusEqual: 9451 case OO_MinusEqual: 9452 case OO_StarEqual: 9453 case OO_SlashEqual: 9454 case OO_PercentEqual: 9455 case OO_CaretEqual: 9456 case OO_AmpEqual: 9457 case OO_PipeEqual: 9458 case OO_LessLess: 9459 case OO_GreaterGreater: 9460 case OO_LessLessEqual: 9461 case OO_GreaterGreaterEqual: 9462 case OO_EqualEqual: 9463 case OO_ExclaimEqual: 9464 case OO_PlusPlus: 9465 case OO_MinusMinus: 9466 case OO_Comma: 9467 case OO_ArrowStar: 9468 case OO_Arrow: 9469 case OO_Call: 9470 case OO_Subscript: 9471 case OO_Conditional: 9472 case OO_Coawait: 9473 case NUM_OVERLOADED_OPERATORS: 9474 llvm_unreachable("Unexpected reduction identifier"); 9475 case OO_None: 9476 if (auto *II = DN.getAsIdentifierInfo()) { 9477 if (II->isStr("max")) 9478 BOK = BO_GT; 9479 else if (II->isStr("min")) 9480 BOK = BO_LT; 9481 } 9482 break; 9483 } 9484 SourceRange ReductionIdRange; 9485 if (ReductionIdScopeSpec.isValid()) 9486 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 9487 else 9488 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 9489 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 9490 9491 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 9492 bool FirstIter = true; 9493 for (auto RefExpr : VarList) { 9494 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 9495 // OpenMP [2.1, C/C++] 9496 // A list item is a variable or array section, subject to the restrictions 9497 // specified in Section 2.4 on page 42 and in each of the sections 9498 // describing clauses and directives for which a list appears. 9499 // OpenMP [2.14.3.3, Restrictions, p.1] 9500 // A variable that is part of another variable (as an array or 9501 // structure element) cannot appear in a private clause. 9502 if (!FirstIter && IR != ER) 9503 ++IR; 9504 FirstIter = false; 9505 SourceLocation ELoc; 9506 SourceRange ERange; 9507 Expr *SimpleRefExpr = RefExpr; 9508 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 9509 /*AllowArraySection=*/true); 9510 if (Res.second) { 9511 // Try to find 'declare reduction' corresponding construct before using 9512 // builtin/overloaded operators. 9513 QualType Type = Context.DependentTy; 9514 CXXCastPath BasePath; 9515 ExprResult DeclareReductionRef = buildDeclareReductionRef( 9516 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 9517 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 9518 Expr *ReductionOp = nullptr; 9519 if (S.CurContext->isDependentContext() && 9520 (DeclareReductionRef.isUnset() || 9521 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 9522 ReductionOp = DeclareReductionRef.get(); 9523 // It will be analyzed later. 9524 RD.push(RefExpr, ReductionOp); 9525 } 9526 ValueDecl *D = Res.first; 9527 if (!D) 9528 continue; 9529 9530 Expr *TaskgroupDescriptor = nullptr; 9531 QualType Type; 9532 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 9533 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 9534 if (ASE) 9535 Type = ASE->getType().getNonReferenceType(); 9536 else if (OASE) { 9537 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 9538 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 9539 Type = ATy->getElementType(); 9540 else 9541 Type = BaseType->getPointeeType(); 9542 Type = Type.getNonReferenceType(); 9543 } else 9544 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 9545 auto *VD = dyn_cast<VarDecl>(D); 9546 9547 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9548 // A variable that appears in a private clause must not have an incomplete 9549 // type or a reference type. 9550 if (S.RequireCompleteType(ELoc, Type, 9551 diag::err_omp_reduction_incomplete_type)) 9552 continue; 9553 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9554 // A list item that appears in a reduction clause must not be 9555 // const-qualified. 9556 if (Type.getNonReferenceType().isConstant(Context)) { 9557 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange; 9558 if (!ASE && !OASE) { 9559 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9560 VarDecl::DeclarationOnly; 9561 S.Diag(D->getLocation(), 9562 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9563 << D; 9564 } 9565 continue; 9566 } 9567 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 9568 // If a list-item is a reference type then it must bind to the same object 9569 // for all threads of the team. 9570 if (!ASE && !OASE && VD) { 9571 VarDecl *VDDef = VD->getDefinition(); 9572 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 9573 DSARefChecker Check(Stack); 9574 if (Check.Visit(VDDef->getInit())) { 9575 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 9576 << getOpenMPClauseName(ClauseKind) << ERange; 9577 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 9578 continue; 9579 } 9580 } 9581 } 9582 9583 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 9584 // in a Construct] 9585 // Variables with the predetermined data-sharing attributes may not be 9586 // listed in data-sharing attributes clauses, except for the cases 9587 // listed below. For these exceptions only, listing a predetermined 9588 // variable in a data-sharing attribute clause is allowed and overrides 9589 // the variable's predetermined data-sharing attributes. 9590 // OpenMP [2.14.3.6, Restrictions, p.3] 9591 // Any number of reduction clauses can be specified on the directive, 9592 // but a list item can appear only once in the reduction clauses for that 9593 // directive. 9594 DSAStackTy::DSAVarData DVar; 9595 DVar = Stack->getTopDSA(D, false); 9596 if (DVar.CKind == OMPC_reduction) { 9597 S.Diag(ELoc, diag::err_omp_once_referenced) 9598 << getOpenMPClauseName(ClauseKind); 9599 if (DVar.RefExpr) 9600 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 9601 continue; 9602 } else if (DVar.CKind != OMPC_unknown) { 9603 S.Diag(ELoc, diag::err_omp_wrong_dsa) 9604 << getOpenMPClauseName(DVar.CKind) 9605 << getOpenMPClauseName(OMPC_reduction); 9606 ReportOriginalDSA(S, Stack, D, DVar); 9607 continue; 9608 } 9609 9610 // OpenMP [2.14.3.6, Restrictions, p.1] 9611 // A list item that appears in a reduction clause of a worksharing 9612 // construct must be shared in the parallel regions to which any of the 9613 // worksharing regions arising from the worksharing construct bind. 9614 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 9615 if (isOpenMPWorksharingDirective(CurrDir) && 9616 !isOpenMPParallelDirective(CurrDir) && 9617 !isOpenMPTeamsDirective(CurrDir)) { 9618 DVar = Stack->getImplicitDSA(D, true); 9619 if (DVar.CKind != OMPC_shared) { 9620 S.Diag(ELoc, diag::err_omp_required_access) 9621 << getOpenMPClauseName(OMPC_reduction) 9622 << getOpenMPClauseName(OMPC_shared); 9623 ReportOriginalDSA(S, Stack, D, DVar); 9624 continue; 9625 } 9626 } 9627 9628 // Try to find 'declare reduction' corresponding construct before using 9629 // builtin/overloaded operators. 9630 CXXCastPath BasePath; 9631 ExprResult DeclareReductionRef = buildDeclareReductionRef( 9632 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 9633 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 9634 if (DeclareReductionRef.isInvalid()) 9635 continue; 9636 if (S.CurContext->isDependentContext() && 9637 (DeclareReductionRef.isUnset() || 9638 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 9639 RD.push(RefExpr, DeclareReductionRef.get()); 9640 continue; 9641 } 9642 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 9643 // Not allowed reduction identifier is found. 9644 S.Diag(ReductionId.getLocStart(), 9645 diag::err_omp_unknown_reduction_identifier) 9646 << Type << ReductionIdRange; 9647 continue; 9648 } 9649 9650 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9651 // The type of a list item that appears in a reduction clause must be valid 9652 // for the reduction-identifier. For a max or min reduction in C, the type 9653 // of the list item must be an allowed arithmetic data type: char, int, 9654 // float, double, or _Bool, possibly modified with long, short, signed, or 9655 // unsigned. For a max or min reduction in C++, the type of the list item 9656 // must be an allowed arithmetic data type: char, wchar_t, int, float, 9657 // double, or bool, possibly modified with long, short, signed, or unsigned. 9658 if (DeclareReductionRef.isUnset()) { 9659 if ((BOK == BO_GT || BOK == BO_LT) && 9660 !(Type->isScalarType() || 9661 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 9662 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 9663 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 9664 if (!ASE && !OASE) { 9665 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9666 VarDecl::DeclarationOnly; 9667 S.Diag(D->getLocation(), 9668 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9669 << D; 9670 } 9671 continue; 9672 } 9673 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 9674 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 9675 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 9676 << getOpenMPClauseName(ClauseKind); 9677 if (!ASE && !OASE) { 9678 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9679 VarDecl::DeclarationOnly; 9680 S.Diag(D->getLocation(), 9681 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9682 << D; 9683 } 9684 continue; 9685 } 9686 } 9687 9688 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 9689 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 9690 D->hasAttrs() ? &D->getAttrs() : nullptr); 9691 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 9692 D->hasAttrs() ? &D->getAttrs() : nullptr); 9693 auto PrivateTy = Type; 9694 9695 // Try if we can determine constant lengths for all array sections and avoid 9696 // the VLA. 9697 bool ConstantLengthOASE = false; 9698 if (OASE) { 9699 bool SingleElement; 9700 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 9701 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction( 9702 Context, OASE, SingleElement, ArraySizes); 9703 9704 // If we don't have a single element, we must emit a constant array type. 9705 if (ConstantLengthOASE && !SingleElement) { 9706 for (auto &Size : ArraySizes) { 9707 PrivateTy = Context.getConstantArrayType( 9708 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0); 9709 } 9710 } 9711 } 9712 9713 if ((OASE && !ConstantLengthOASE) || 9714 (!OASE && !ASE && 9715 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 9716 // For arrays/array sections only: 9717 // Create pseudo array type for private copy. The size for this array will 9718 // be generated during codegen. 9719 // For array subscripts or single variables Private Ty is the same as Type 9720 // (type of the variable or single array element). 9721 PrivateTy = Context.getVariableArrayType( 9722 Type, 9723 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue), 9724 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 9725 } else if (!ASE && !OASE && 9726 Context.getAsArrayType(D->getType().getNonReferenceType())) 9727 PrivateTy = D->getType().getNonReferenceType(); 9728 // Private copy. 9729 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(), 9730 D->hasAttrs() ? &D->getAttrs() : nullptr); 9731 // Add initializer for private variable. 9732 Expr *Init = nullptr; 9733 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 9734 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 9735 if (DeclareReductionRef.isUsable()) { 9736 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 9737 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 9738 if (DRD->getInitializer()) { 9739 Init = DRDRef; 9740 RHSVD->setInit(DRDRef); 9741 RHSVD->setInitStyle(VarDecl::CallInit); 9742 } 9743 } else { 9744 switch (BOK) { 9745 case BO_Add: 9746 case BO_Xor: 9747 case BO_Or: 9748 case BO_LOr: 9749 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 9750 if (Type->isScalarType() || Type->isAnyComplexType()) 9751 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 9752 break; 9753 case BO_Mul: 9754 case BO_LAnd: 9755 if (Type->isScalarType() || Type->isAnyComplexType()) { 9756 // '*' and '&&' reduction ops - initializer is '1'. 9757 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 9758 } 9759 break; 9760 case BO_And: { 9761 // '&' reduction op - initializer is '~0'. 9762 QualType OrigType = Type; 9763 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 9764 Type = ComplexTy->getElementType(); 9765 if (Type->isRealFloatingType()) { 9766 llvm::APFloat InitValue = 9767 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 9768 /*isIEEE=*/true); 9769 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9770 Type, ELoc); 9771 } else if (Type->isScalarType()) { 9772 auto Size = Context.getTypeSize(Type); 9773 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 9774 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 9775 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9776 } 9777 if (Init && OrigType->isAnyComplexType()) { 9778 // Init = 0xFFFF + 0xFFFFi; 9779 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 9780 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 9781 } 9782 Type = OrigType; 9783 break; 9784 } 9785 case BO_LT: 9786 case BO_GT: { 9787 // 'min' reduction op - initializer is 'Largest representable number in 9788 // the reduction list item type'. 9789 // 'max' reduction op - initializer is 'Least representable number in 9790 // the reduction list item type'. 9791 if (Type->isIntegerType() || Type->isPointerType()) { 9792 bool IsSigned = Type->hasSignedIntegerRepresentation(); 9793 auto Size = Context.getTypeSize(Type); 9794 QualType IntTy = 9795 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 9796 llvm::APInt InitValue = 9797 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 9798 : llvm::APInt::getMinValue(Size) 9799 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 9800 : llvm::APInt::getMaxValue(Size); 9801 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9802 if (Type->isPointerType()) { 9803 // Cast to pointer type. 9804 auto CastExpr = S.BuildCStyleCastExpr( 9805 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 9806 if (CastExpr.isInvalid()) 9807 continue; 9808 Init = CastExpr.get(); 9809 } 9810 } else if (Type->isRealFloatingType()) { 9811 llvm::APFloat InitValue = llvm::APFloat::getLargest( 9812 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 9813 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9814 Type, ELoc); 9815 } 9816 break; 9817 } 9818 case BO_PtrMemD: 9819 case BO_PtrMemI: 9820 case BO_MulAssign: 9821 case BO_Div: 9822 case BO_Rem: 9823 case BO_Sub: 9824 case BO_Shl: 9825 case BO_Shr: 9826 case BO_LE: 9827 case BO_GE: 9828 case BO_EQ: 9829 case BO_NE: 9830 case BO_AndAssign: 9831 case BO_XorAssign: 9832 case BO_OrAssign: 9833 case BO_Assign: 9834 case BO_AddAssign: 9835 case BO_SubAssign: 9836 case BO_DivAssign: 9837 case BO_RemAssign: 9838 case BO_ShlAssign: 9839 case BO_ShrAssign: 9840 case BO_Comma: 9841 llvm_unreachable("Unexpected reduction operation"); 9842 } 9843 } 9844 if (Init && DeclareReductionRef.isUnset()) 9845 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 9846 else if (!Init) 9847 S.ActOnUninitializedDecl(RHSVD); 9848 if (RHSVD->isInvalidDecl()) 9849 continue; 9850 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 9851 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 9852 << Type << ReductionIdRange; 9853 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9854 VarDecl::DeclarationOnly; 9855 S.Diag(D->getLocation(), 9856 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9857 << D; 9858 continue; 9859 } 9860 // Store initializer for single element in private copy. Will be used during 9861 // codegen. 9862 PrivateVD->setInit(RHSVD->getInit()); 9863 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 9864 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 9865 ExprResult ReductionOp; 9866 if (DeclareReductionRef.isUsable()) { 9867 QualType RedTy = DeclareReductionRef.get()->getType(); 9868 QualType PtrRedTy = Context.getPointerType(RedTy); 9869 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 9870 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 9871 if (!BasePath.empty()) { 9872 LHS = S.DefaultLvalueConversion(LHS.get()); 9873 RHS = S.DefaultLvalueConversion(RHS.get()); 9874 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9875 CK_UncheckedDerivedToBase, LHS.get(), 9876 &BasePath, LHS.get()->getValueKind()); 9877 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9878 CK_UncheckedDerivedToBase, RHS.get(), 9879 &BasePath, RHS.get()->getValueKind()); 9880 } 9881 FunctionProtoType::ExtProtoInfo EPI; 9882 QualType Params[] = {PtrRedTy, PtrRedTy}; 9883 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 9884 auto *OVE = new (Context) OpaqueValueExpr( 9885 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 9886 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 9887 Expr *Args[] = {LHS.get(), RHS.get()}; 9888 ReductionOp = new (Context) 9889 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 9890 } else { 9891 ReductionOp = S.BuildBinOp( 9892 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 9893 if (ReductionOp.isUsable()) { 9894 if (BOK != BO_LT && BOK != BO_GT) { 9895 ReductionOp = 9896 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), 9897 BO_Assign, LHSDRE, ReductionOp.get()); 9898 } else { 9899 auto *ConditionalOp = new (Context) 9900 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE, 9901 Type, VK_LValue, OK_Ordinary); 9902 ReductionOp = 9903 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), 9904 BO_Assign, LHSDRE, ConditionalOp); 9905 } 9906 if (ReductionOp.isUsable()) 9907 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get()); 9908 } 9909 if (!ReductionOp.isUsable()) 9910 continue; 9911 } 9912 9913 // OpenMP [2.15.4.6, Restrictions, p.2] 9914 // A list item that appears in an in_reduction clause of a task construct 9915 // must appear in a task_reduction clause of a construct associated with a 9916 // taskgroup region that includes the participating task in its taskgroup 9917 // set. The construct associated with the innermost region that meets this 9918 // condition must specify the same reduction-identifier as the in_reduction 9919 // clause. 9920 if (ClauseKind == OMPC_in_reduction) { 9921 SourceRange ParentSR; 9922 BinaryOperatorKind ParentBOK; 9923 const Expr *ParentReductionOp; 9924 Expr *ParentBOKTD, *ParentReductionOpTD; 9925 DSAStackTy::DSAVarData ParentBOKDSA = 9926 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 9927 ParentBOKTD); 9928 DSAStackTy::DSAVarData ParentReductionOpDSA = 9929 Stack->getTopMostTaskgroupReductionData( 9930 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 9931 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 9932 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 9933 if (!IsParentBOK && !IsParentReductionOp) { 9934 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction); 9935 continue; 9936 } 9937 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 9938 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK || 9939 IsParentReductionOp) { 9940 bool EmitError = true; 9941 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 9942 llvm::FoldingSetNodeID RedId, ParentRedId; 9943 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 9944 DeclareReductionRef.get()->Profile(RedId, Context, 9945 /*Canonical=*/true); 9946 EmitError = RedId != ParentRedId; 9947 } 9948 if (EmitError) { 9949 S.Diag(ReductionId.getLocStart(), 9950 diag::err_omp_reduction_identifier_mismatch) 9951 << ReductionIdRange << RefExpr->getSourceRange(); 9952 S.Diag(ParentSR.getBegin(), 9953 diag::note_omp_previous_reduction_identifier) 9954 << ParentSR 9955 << (IsParentBOK ? ParentBOKDSA.RefExpr 9956 : ParentReductionOpDSA.RefExpr) 9957 ->getSourceRange(); 9958 continue; 9959 } 9960 } 9961 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 9962 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined."); 9963 } 9964 9965 DeclRefExpr *Ref = nullptr; 9966 Expr *VarsExpr = RefExpr->IgnoreParens(); 9967 if (!VD && !S.CurContext->isDependentContext()) { 9968 if (ASE || OASE) { 9969 TransformExprToCaptures RebuildToCapture(S, D); 9970 VarsExpr = 9971 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 9972 Ref = RebuildToCapture.getCapturedExpr(); 9973 } else { 9974 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 9975 } 9976 if (!S.IsOpenMPCapturedDecl(D)) { 9977 RD.ExprCaptures.emplace_back(Ref->getDecl()); 9978 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9979 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 9980 if (!RefRes.isUsable()) 9981 continue; 9982 ExprResult PostUpdateRes = 9983 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 9984 RefRes.get()); 9985 if (!PostUpdateRes.isUsable()) 9986 continue; 9987 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 9988 Stack->getCurrentDirective() == OMPD_taskgroup) { 9989 S.Diag(RefExpr->getExprLoc(), 9990 diag::err_omp_reduction_non_addressable_expression) 9991 << RefExpr->getSourceRange(); 9992 continue; 9993 } 9994 RD.ExprPostUpdates.emplace_back( 9995 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 9996 } 9997 } 9998 } 9999 // All reduction items are still marked as reduction (to do not increase 10000 // code base size). 10001 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 10002 if (CurrDir == OMPD_taskgroup) { 10003 if (DeclareReductionRef.isUsable()) 10004 Stack->addTaskgroupReductionData(D, ReductionIdRange, 10005 DeclareReductionRef.get()); 10006 else 10007 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 10008 } 10009 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 10010 TaskgroupDescriptor); 10011 } 10012 return RD.Vars.empty(); 10013 } 10014 10015 OMPClause *Sema::ActOnOpenMPReductionClause( 10016 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10017 SourceLocation ColonLoc, SourceLocation EndLoc, 10018 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10019 ArrayRef<Expr *> UnresolvedReductions) { 10020 ReductionData RD(VarList.size()); 10021 10022 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 10023 StartLoc, LParenLoc, ColonLoc, EndLoc, 10024 ReductionIdScopeSpec, ReductionId, 10025 UnresolvedReductions, RD)) 10026 return nullptr; 10027 10028 return OMPReductionClause::Create( 10029 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 10030 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 10031 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 10032 buildPreInits(Context, RD.ExprCaptures), 10033 buildPostUpdate(*this, RD.ExprPostUpdates)); 10034 } 10035 10036 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 10037 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10038 SourceLocation ColonLoc, SourceLocation EndLoc, 10039 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10040 ArrayRef<Expr *> UnresolvedReductions) { 10041 ReductionData RD(VarList.size()); 10042 10043 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, 10044 VarList, StartLoc, LParenLoc, ColonLoc, 10045 EndLoc, ReductionIdScopeSpec, ReductionId, 10046 UnresolvedReductions, RD)) 10047 return nullptr; 10048 10049 return OMPTaskReductionClause::Create( 10050 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 10051 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 10052 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 10053 buildPreInits(Context, RD.ExprCaptures), 10054 buildPostUpdate(*this, RD.ExprPostUpdates)); 10055 } 10056 10057 OMPClause *Sema::ActOnOpenMPInReductionClause( 10058 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10059 SourceLocation ColonLoc, SourceLocation EndLoc, 10060 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10061 ArrayRef<Expr *> UnresolvedReductions) { 10062 ReductionData RD(VarList.size()); 10063 10064 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 10065 StartLoc, LParenLoc, ColonLoc, EndLoc, 10066 ReductionIdScopeSpec, ReductionId, 10067 UnresolvedReductions, RD)) 10068 return nullptr; 10069 10070 return OMPInReductionClause::Create( 10071 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 10072 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 10073 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 10074 buildPreInits(Context, RD.ExprCaptures), 10075 buildPostUpdate(*this, RD.ExprPostUpdates)); 10076 } 10077 10078 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 10079 SourceLocation LinLoc) { 10080 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 10081 LinKind == OMPC_LINEAR_unknown) { 10082 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 10083 return true; 10084 } 10085 return false; 10086 } 10087 10088 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 10089 OpenMPLinearClauseKind LinKind, 10090 QualType Type) { 10091 auto *VD = dyn_cast_or_null<VarDecl>(D); 10092 // A variable must not have an incomplete type or a reference type. 10093 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 10094 return true; 10095 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 10096 !Type->isReferenceType()) { 10097 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 10098 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 10099 return true; 10100 } 10101 Type = Type.getNonReferenceType(); 10102 10103 // A list item must not be const-qualified. 10104 if (Type.isConstant(Context)) { 10105 Diag(ELoc, diag::err_omp_const_variable) 10106 << getOpenMPClauseName(OMPC_linear); 10107 if (D) { 10108 bool IsDecl = 10109 !VD || 10110 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10111 Diag(D->getLocation(), 10112 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10113 << D; 10114 } 10115 return true; 10116 } 10117 10118 // A list item must be of integral or pointer type. 10119 Type = Type.getUnqualifiedType().getCanonicalType(); 10120 const auto *Ty = Type.getTypePtrOrNull(); 10121 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 10122 !Ty->isPointerType())) { 10123 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 10124 if (D) { 10125 bool IsDecl = 10126 !VD || 10127 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10128 Diag(D->getLocation(), 10129 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10130 << D; 10131 } 10132 return true; 10133 } 10134 return false; 10135 } 10136 10137 OMPClause *Sema::ActOnOpenMPLinearClause( 10138 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 10139 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 10140 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 10141 SmallVector<Expr *, 8> Vars; 10142 SmallVector<Expr *, 8> Privates; 10143 SmallVector<Expr *, 8> Inits; 10144 SmallVector<Decl *, 4> ExprCaptures; 10145 SmallVector<Expr *, 4> ExprPostUpdates; 10146 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 10147 LinKind = OMPC_LINEAR_val; 10148 for (auto &RefExpr : VarList) { 10149 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10150 SourceLocation ELoc; 10151 SourceRange ERange; 10152 Expr *SimpleRefExpr = RefExpr; 10153 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10154 /*AllowArraySection=*/false); 10155 if (Res.second) { 10156 // It will be analyzed later. 10157 Vars.push_back(RefExpr); 10158 Privates.push_back(nullptr); 10159 Inits.push_back(nullptr); 10160 } 10161 ValueDecl *D = Res.first; 10162 if (!D) 10163 continue; 10164 10165 QualType Type = D->getType(); 10166 auto *VD = dyn_cast<VarDecl>(D); 10167 10168 // OpenMP [2.14.3.7, linear clause] 10169 // A list-item cannot appear in more than one linear clause. 10170 // A list-item that appears in a linear clause cannot appear in any 10171 // other data-sharing attribute clause. 10172 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 10173 if (DVar.RefExpr) { 10174 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 10175 << getOpenMPClauseName(OMPC_linear); 10176 ReportOriginalDSA(*this, DSAStack, D, DVar); 10177 continue; 10178 } 10179 10180 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 10181 continue; 10182 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 10183 10184 // Build private copy of original var. 10185 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 10186 D->hasAttrs() ? &D->getAttrs() : nullptr); 10187 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 10188 // Build var to save initial value. 10189 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 10190 Expr *InitExpr; 10191 DeclRefExpr *Ref = nullptr; 10192 if (!VD && !CurContext->isDependentContext()) { 10193 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 10194 if (!IsOpenMPCapturedDecl(D)) { 10195 ExprCaptures.push_back(Ref->getDecl()); 10196 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 10197 ExprResult RefRes = DefaultLvalueConversion(Ref); 10198 if (!RefRes.isUsable()) 10199 continue; 10200 ExprResult PostUpdateRes = 10201 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 10202 SimpleRefExpr, RefRes.get()); 10203 if (!PostUpdateRes.isUsable()) 10204 continue; 10205 ExprPostUpdates.push_back( 10206 IgnoredValueConversions(PostUpdateRes.get()).get()); 10207 } 10208 } 10209 } 10210 if (LinKind == OMPC_LINEAR_uval) 10211 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 10212 else 10213 InitExpr = VD ? SimpleRefExpr : Ref; 10214 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 10215 /*DirectInit=*/false); 10216 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 10217 10218 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 10219 Vars.push_back((VD || CurContext->isDependentContext()) 10220 ? RefExpr->IgnoreParens() 10221 : Ref); 10222 Privates.push_back(PrivateRef); 10223 Inits.push_back(InitRef); 10224 } 10225 10226 if (Vars.empty()) 10227 return nullptr; 10228 10229 Expr *StepExpr = Step; 10230 Expr *CalcStepExpr = nullptr; 10231 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 10232 !Step->isInstantiationDependent() && 10233 !Step->containsUnexpandedParameterPack()) { 10234 SourceLocation StepLoc = Step->getLocStart(); 10235 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 10236 if (Val.isInvalid()) 10237 return nullptr; 10238 StepExpr = Val.get(); 10239 10240 // Build var to save the step value. 10241 VarDecl *SaveVar = 10242 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 10243 ExprResult SaveRef = 10244 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 10245 ExprResult CalcStep = 10246 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 10247 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 10248 10249 // Warn about zero linear step (it would be probably better specified as 10250 // making corresponding variables 'const'). 10251 llvm::APSInt Result; 10252 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 10253 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 10254 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 10255 << (Vars.size() > 1); 10256 if (!IsConstant && CalcStep.isUsable()) { 10257 // Calculate the step beforehand instead of doing this on each iteration. 10258 // (This is not used if the number of iterations may be kfold-ed). 10259 CalcStepExpr = CalcStep.get(); 10260 } 10261 } 10262 10263 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 10264 ColonLoc, EndLoc, Vars, Privates, Inits, 10265 StepExpr, CalcStepExpr, 10266 buildPreInits(Context, ExprCaptures), 10267 buildPostUpdate(*this, ExprPostUpdates)); 10268 } 10269 10270 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 10271 Expr *NumIterations, Sema &SemaRef, 10272 Scope *S, DSAStackTy *Stack) { 10273 // Walk the vars and build update/final expressions for the CodeGen. 10274 SmallVector<Expr *, 8> Updates; 10275 SmallVector<Expr *, 8> Finals; 10276 Expr *Step = Clause.getStep(); 10277 Expr *CalcStep = Clause.getCalcStep(); 10278 // OpenMP [2.14.3.7, linear clause] 10279 // If linear-step is not specified it is assumed to be 1. 10280 if (Step == nullptr) 10281 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 10282 else if (CalcStep) { 10283 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 10284 } 10285 bool HasErrors = false; 10286 auto CurInit = Clause.inits().begin(); 10287 auto CurPrivate = Clause.privates().begin(); 10288 auto LinKind = Clause.getModifier(); 10289 for (auto &RefExpr : Clause.varlists()) { 10290 SourceLocation ELoc; 10291 SourceRange ERange; 10292 Expr *SimpleRefExpr = RefExpr; 10293 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 10294 /*AllowArraySection=*/false); 10295 ValueDecl *D = Res.first; 10296 if (Res.second || !D) { 10297 Updates.push_back(nullptr); 10298 Finals.push_back(nullptr); 10299 HasErrors = true; 10300 continue; 10301 } 10302 auto &&Info = Stack->isLoopControlVariable(D); 10303 Expr *InitExpr = *CurInit; 10304 10305 // Build privatized reference to the current linear var. 10306 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 10307 Expr *CapturedRef; 10308 if (LinKind == OMPC_LINEAR_uval) 10309 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 10310 else 10311 CapturedRef = 10312 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 10313 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 10314 /*RefersToCapture=*/true); 10315 10316 // Build update: Var = InitExpr + IV * Step 10317 ExprResult Update; 10318 if (!Info.first) { 10319 Update = 10320 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 10321 InitExpr, IV, Step, /* Subtract */ false); 10322 } else 10323 Update = *CurPrivate; 10324 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 10325 /*DiscardedValue=*/true); 10326 10327 // Build final: Var = InitExpr + NumIterations * Step 10328 ExprResult Final; 10329 if (!Info.first) { 10330 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 10331 InitExpr, NumIterations, Step, 10332 /* Subtract */ false); 10333 } else 10334 Final = *CurPrivate; 10335 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 10336 /*DiscardedValue=*/true); 10337 10338 if (!Update.isUsable() || !Final.isUsable()) { 10339 Updates.push_back(nullptr); 10340 Finals.push_back(nullptr); 10341 HasErrors = true; 10342 } else { 10343 Updates.push_back(Update.get()); 10344 Finals.push_back(Final.get()); 10345 } 10346 ++CurInit; 10347 ++CurPrivate; 10348 } 10349 Clause.setUpdates(Updates); 10350 Clause.setFinals(Finals); 10351 return HasErrors; 10352 } 10353 10354 OMPClause *Sema::ActOnOpenMPAlignedClause( 10355 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 10356 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 10357 10358 SmallVector<Expr *, 8> Vars; 10359 for (auto &RefExpr : VarList) { 10360 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10361 SourceLocation ELoc; 10362 SourceRange ERange; 10363 Expr *SimpleRefExpr = RefExpr; 10364 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10365 /*AllowArraySection=*/false); 10366 if (Res.second) { 10367 // It will be analyzed later. 10368 Vars.push_back(RefExpr); 10369 } 10370 ValueDecl *D = Res.first; 10371 if (!D) 10372 continue; 10373 10374 QualType QType = D->getType(); 10375 auto *VD = dyn_cast<VarDecl>(D); 10376 10377 // OpenMP [2.8.1, simd construct, Restrictions] 10378 // The type of list items appearing in the aligned clause must be 10379 // array, pointer, reference to array, or reference to pointer. 10380 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 10381 const Type *Ty = QType.getTypePtrOrNull(); 10382 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 10383 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 10384 << QType << getLangOpts().CPlusPlus << ERange; 10385 bool IsDecl = 10386 !VD || 10387 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10388 Diag(D->getLocation(), 10389 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10390 << D; 10391 continue; 10392 } 10393 10394 // OpenMP [2.8.1, simd construct, Restrictions] 10395 // A list-item cannot appear in more than one aligned clause. 10396 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 10397 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 10398 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 10399 << getOpenMPClauseName(OMPC_aligned); 10400 continue; 10401 } 10402 10403 DeclRefExpr *Ref = nullptr; 10404 if (!VD && IsOpenMPCapturedDecl(D)) 10405 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 10406 Vars.push_back(DefaultFunctionArrayConversion( 10407 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 10408 .get()); 10409 } 10410 10411 // OpenMP [2.8.1, simd construct, Description] 10412 // The parameter of the aligned clause, alignment, must be a constant 10413 // positive integer expression. 10414 // If no optional parameter is specified, implementation-defined default 10415 // alignments for SIMD instructions on the target platforms are assumed. 10416 if (Alignment != nullptr) { 10417 ExprResult AlignResult = 10418 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 10419 if (AlignResult.isInvalid()) 10420 return nullptr; 10421 Alignment = AlignResult.get(); 10422 } 10423 if (Vars.empty()) 10424 return nullptr; 10425 10426 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 10427 EndLoc, Vars, Alignment); 10428 } 10429 10430 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 10431 SourceLocation StartLoc, 10432 SourceLocation LParenLoc, 10433 SourceLocation EndLoc) { 10434 SmallVector<Expr *, 8> Vars; 10435 SmallVector<Expr *, 8> SrcExprs; 10436 SmallVector<Expr *, 8> DstExprs; 10437 SmallVector<Expr *, 8> AssignmentOps; 10438 for (auto &RefExpr : VarList) { 10439 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 10440 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 10441 // It will be analyzed later. 10442 Vars.push_back(RefExpr); 10443 SrcExprs.push_back(nullptr); 10444 DstExprs.push_back(nullptr); 10445 AssignmentOps.push_back(nullptr); 10446 continue; 10447 } 10448 10449 SourceLocation ELoc = RefExpr->getExprLoc(); 10450 // OpenMP [2.1, C/C++] 10451 // A list item is a variable name. 10452 // OpenMP [2.14.4.1, Restrictions, p.1] 10453 // A list item that appears in a copyin clause must be threadprivate. 10454 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 10455 if (!DE || !isa<VarDecl>(DE->getDecl())) { 10456 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 10457 << 0 << RefExpr->getSourceRange(); 10458 continue; 10459 } 10460 10461 Decl *D = DE->getDecl(); 10462 VarDecl *VD = cast<VarDecl>(D); 10463 10464 QualType Type = VD->getType(); 10465 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 10466 // It will be analyzed later. 10467 Vars.push_back(DE); 10468 SrcExprs.push_back(nullptr); 10469 DstExprs.push_back(nullptr); 10470 AssignmentOps.push_back(nullptr); 10471 continue; 10472 } 10473 10474 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 10475 // A list item that appears in a copyin clause must be threadprivate. 10476 if (!DSAStack->isThreadPrivate(VD)) { 10477 Diag(ELoc, diag::err_omp_required_access) 10478 << getOpenMPClauseName(OMPC_copyin) 10479 << getOpenMPDirectiveName(OMPD_threadprivate); 10480 continue; 10481 } 10482 10483 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 10484 // A variable of class type (or array thereof) that appears in a 10485 // copyin clause requires an accessible, unambiguous copy assignment 10486 // operator for the class type. 10487 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 10488 auto *SrcVD = 10489 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 10490 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 10491 auto *PseudoSrcExpr = buildDeclRefExpr( 10492 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 10493 auto *DstVD = 10494 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 10495 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 10496 auto *PseudoDstExpr = 10497 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 10498 // For arrays generate assignment operation for single element and replace 10499 // it by the original array element in CodeGen. 10500 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 10501 PseudoDstExpr, PseudoSrcExpr); 10502 if (AssignmentOp.isInvalid()) 10503 continue; 10504 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 10505 /*DiscardedValue=*/true); 10506 if (AssignmentOp.isInvalid()) 10507 continue; 10508 10509 DSAStack->addDSA(VD, DE, OMPC_copyin); 10510 Vars.push_back(DE); 10511 SrcExprs.push_back(PseudoSrcExpr); 10512 DstExprs.push_back(PseudoDstExpr); 10513 AssignmentOps.push_back(AssignmentOp.get()); 10514 } 10515 10516 if (Vars.empty()) 10517 return nullptr; 10518 10519 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 10520 SrcExprs, DstExprs, AssignmentOps); 10521 } 10522 10523 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 10524 SourceLocation StartLoc, 10525 SourceLocation LParenLoc, 10526 SourceLocation EndLoc) { 10527 SmallVector<Expr *, 8> Vars; 10528 SmallVector<Expr *, 8> SrcExprs; 10529 SmallVector<Expr *, 8> DstExprs; 10530 SmallVector<Expr *, 8> AssignmentOps; 10531 for (auto &RefExpr : VarList) { 10532 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10533 SourceLocation ELoc; 10534 SourceRange ERange; 10535 Expr *SimpleRefExpr = RefExpr; 10536 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10537 /*AllowArraySection=*/false); 10538 if (Res.second) { 10539 // It will be analyzed later. 10540 Vars.push_back(RefExpr); 10541 SrcExprs.push_back(nullptr); 10542 DstExprs.push_back(nullptr); 10543 AssignmentOps.push_back(nullptr); 10544 } 10545 ValueDecl *D = Res.first; 10546 if (!D) 10547 continue; 10548 10549 QualType Type = D->getType(); 10550 auto *VD = dyn_cast<VarDecl>(D); 10551 10552 // OpenMP [2.14.4.2, Restrictions, p.2] 10553 // A list item that appears in a copyprivate clause may not appear in a 10554 // private or firstprivate clause on the single construct. 10555 if (!VD || !DSAStack->isThreadPrivate(VD)) { 10556 auto DVar = DSAStack->getTopDSA(D, false); 10557 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 10558 DVar.RefExpr) { 10559 Diag(ELoc, diag::err_omp_wrong_dsa) 10560 << getOpenMPClauseName(DVar.CKind) 10561 << getOpenMPClauseName(OMPC_copyprivate); 10562 ReportOriginalDSA(*this, DSAStack, D, DVar); 10563 continue; 10564 } 10565 10566 // OpenMP [2.11.4.2, Restrictions, p.1] 10567 // All list items that appear in a copyprivate clause must be either 10568 // threadprivate or private in the enclosing context. 10569 if (DVar.CKind == OMPC_unknown) { 10570 DVar = DSAStack->getImplicitDSA(D, false); 10571 if (DVar.CKind == OMPC_shared) { 10572 Diag(ELoc, diag::err_omp_required_access) 10573 << getOpenMPClauseName(OMPC_copyprivate) 10574 << "threadprivate or private in the enclosing context"; 10575 ReportOriginalDSA(*this, DSAStack, D, DVar); 10576 continue; 10577 } 10578 } 10579 } 10580 10581 // Variably modified types are not supported. 10582 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 10583 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 10584 << getOpenMPClauseName(OMPC_copyprivate) << Type 10585 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 10586 bool IsDecl = 10587 !VD || 10588 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10589 Diag(D->getLocation(), 10590 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10591 << D; 10592 continue; 10593 } 10594 10595 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 10596 // A variable of class type (or array thereof) that appears in a 10597 // copyin clause requires an accessible, unambiguous copy assignment 10598 // operator for the class type. 10599 Type = Context.getBaseElementType(Type.getNonReferenceType()) 10600 .getUnqualifiedType(); 10601 auto *SrcVD = 10602 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 10603 D->hasAttrs() ? &D->getAttrs() : nullptr); 10604 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 10605 auto *DstVD = 10606 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 10607 D->hasAttrs() ? &D->getAttrs() : nullptr); 10608 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 10609 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 10610 PseudoDstExpr, PseudoSrcExpr); 10611 if (AssignmentOp.isInvalid()) 10612 continue; 10613 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 10614 /*DiscardedValue=*/true); 10615 if (AssignmentOp.isInvalid()) 10616 continue; 10617 10618 // No need to mark vars as copyprivate, they are already threadprivate or 10619 // implicitly private. 10620 assert(VD || IsOpenMPCapturedDecl(D)); 10621 Vars.push_back( 10622 VD ? RefExpr->IgnoreParens() 10623 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 10624 SrcExprs.push_back(PseudoSrcExpr); 10625 DstExprs.push_back(PseudoDstExpr); 10626 AssignmentOps.push_back(AssignmentOp.get()); 10627 } 10628 10629 if (Vars.empty()) 10630 return nullptr; 10631 10632 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10633 Vars, SrcExprs, DstExprs, AssignmentOps); 10634 } 10635 10636 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 10637 SourceLocation StartLoc, 10638 SourceLocation LParenLoc, 10639 SourceLocation EndLoc) { 10640 if (VarList.empty()) 10641 return nullptr; 10642 10643 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 10644 } 10645 10646 OMPClause * 10647 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 10648 SourceLocation DepLoc, SourceLocation ColonLoc, 10649 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10650 SourceLocation LParenLoc, SourceLocation EndLoc) { 10651 if (DSAStack->getCurrentDirective() == OMPD_ordered && 10652 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 10653 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 10654 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 10655 return nullptr; 10656 } 10657 if (DSAStack->getCurrentDirective() != OMPD_ordered && 10658 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 10659 DepKind == OMPC_DEPEND_sink)) { 10660 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 10661 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 10662 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 10663 /*Last=*/OMPC_DEPEND_unknown, Except) 10664 << getOpenMPClauseName(OMPC_depend); 10665 return nullptr; 10666 } 10667 SmallVector<Expr *, 8> Vars; 10668 DSAStackTy::OperatorOffsetTy OpsOffs; 10669 llvm::APSInt DepCounter(/*BitWidth=*/32); 10670 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 10671 if (DepKind == OMPC_DEPEND_sink) { 10672 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 10673 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 10674 TotalDepCount.setIsUnsigned(/*Val=*/true); 10675 } 10676 } 10677 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || 10678 DSAStack->getParentOrderedRegionParam()) { 10679 for (auto &RefExpr : VarList) { 10680 assert(RefExpr && "NULL expr in OpenMP shared clause."); 10681 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 10682 // It will be analyzed later. 10683 Vars.push_back(RefExpr); 10684 continue; 10685 } 10686 10687 SourceLocation ELoc = RefExpr->getExprLoc(); 10688 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 10689 if (DepKind == OMPC_DEPEND_sink) { 10690 if (DepCounter >= TotalDepCount) { 10691 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 10692 continue; 10693 } 10694 ++DepCounter; 10695 // OpenMP [2.13.9, Summary] 10696 // depend(dependence-type : vec), where dependence-type is: 10697 // 'sink' and where vec is the iteration vector, which has the form: 10698 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 10699 // where n is the value specified by the ordered clause in the loop 10700 // directive, xi denotes the loop iteration variable of the i-th nested 10701 // loop associated with the loop directive, and di is a constant 10702 // non-negative integer. 10703 if (CurContext->isDependentContext()) { 10704 // It will be analyzed later. 10705 Vars.push_back(RefExpr); 10706 continue; 10707 } 10708 SimpleExpr = SimpleExpr->IgnoreImplicit(); 10709 OverloadedOperatorKind OOK = OO_None; 10710 SourceLocation OOLoc; 10711 Expr *LHS = SimpleExpr; 10712 Expr *RHS = nullptr; 10713 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 10714 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 10715 OOLoc = BO->getOperatorLoc(); 10716 LHS = BO->getLHS()->IgnoreParenImpCasts(); 10717 RHS = BO->getRHS()->IgnoreParenImpCasts(); 10718 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 10719 OOK = OCE->getOperator(); 10720 OOLoc = OCE->getOperatorLoc(); 10721 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10722 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 10723 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 10724 OOK = MCE->getMethodDecl() 10725 ->getNameInfo() 10726 .getName() 10727 .getCXXOverloadedOperator(); 10728 OOLoc = MCE->getCallee()->getExprLoc(); 10729 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 10730 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10731 } 10732 SourceLocation ELoc; 10733 SourceRange ERange; 10734 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 10735 /*AllowArraySection=*/false); 10736 if (Res.second) { 10737 // It will be analyzed later. 10738 Vars.push_back(RefExpr); 10739 } 10740 ValueDecl *D = Res.first; 10741 if (!D) 10742 continue; 10743 10744 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 10745 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 10746 continue; 10747 } 10748 if (RHS) { 10749 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 10750 RHS, OMPC_depend, /*StrictlyPositive=*/false); 10751 if (RHSRes.isInvalid()) 10752 continue; 10753 } 10754 if (!CurContext->isDependentContext() && 10755 DSAStack->getParentOrderedRegionParam() && 10756 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 10757 ValueDecl* VD = DSAStack->getParentLoopControlVariable( 10758 DepCounter.getZExtValue()); 10759 if (VD) { 10760 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 10761 << 1 << VD; 10762 } else { 10763 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 10764 } 10765 continue; 10766 } 10767 OpsOffs.push_back({RHS, OOK}); 10768 } else { 10769 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 10770 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 10771 (ASE && 10772 !ASE->getBase() 10773 ->getType() 10774 .getNonReferenceType() 10775 ->isPointerType() && 10776 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 10777 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 10778 << RefExpr->getSourceRange(); 10779 continue; 10780 } 10781 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 10782 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 10783 ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, 10784 RefExpr->IgnoreParenImpCasts()); 10785 getDiagnostics().setSuppressAllDiagnostics(Suppress); 10786 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) { 10787 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 10788 << RefExpr->getSourceRange(); 10789 continue; 10790 } 10791 } 10792 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 10793 } 10794 10795 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 10796 TotalDepCount > VarList.size() && 10797 DSAStack->getParentOrderedRegionParam() && 10798 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 10799 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1 10800 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 10801 } 10802 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 10803 Vars.empty()) 10804 return nullptr; 10805 } 10806 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10807 DepKind, DepLoc, ColonLoc, Vars); 10808 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) 10809 DSAStack->addDoacrossDependClause(C, OpsOffs); 10810 return C; 10811 } 10812 10813 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 10814 SourceLocation LParenLoc, 10815 SourceLocation EndLoc) { 10816 Expr *ValExpr = Device; 10817 Stmt *HelperValStmt = nullptr; 10818 10819 // OpenMP [2.9.1, Restrictions] 10820 // The device expression must evaluate to a non-negative integer value. 10821 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 10822 /*StrictlyPositive=*/false)) 10823 return nullptr; 10824 10825 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 10826 if (isOpenMPTargetExecutionDirective(DKind) && 10827 !CurContext->isDependentContext()) { 10828 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 10829 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 10830 HelperValStmt = buildPreInits(Context, Captures); 10831 } 10832 10833 return new (Context) 10834 OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc); 10835 } 10836 10837 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 10838 DSAStackTy *Stack, QualType QTy) { 10839 NamedDecl *ND; 10840 if (QTy->isIncompleteType(&ND)) { 10841 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 10842 return false; 10843 } 10844 return true; 10845 } 10846 10847 /// \brief Return true if it can be proven that the provided array expression 10848 /// (array section or array subscript) does NOT specify the whole size of the 10849 /// array whose base type is \a BaseQTy. 10850 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 10851 const Expr *E, 10852 QualType BaseQTy) { 10853 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10854 10855 // If this is an array subscript, it refers to the whole size if the size of 10856 // the dimension is constant and equals 1. Also, an array section assumes the 10857 // format of an array subscript if no colon is used. 10858 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 10859 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10860 return ATy->getSize().getSExtValue() != 1; 10861 // Size can't be evaluated statically. 10862 return false; 10863 } 10864 10865 assert(OASE && "Expecting array section if not an array subscript."); 10866 auto *LowerBound = OASE->getLowerBound(); 10867 auto *Length = OASE->getLength(); 10868 10869 // If there is a lower bound that does not evaluates to zero, we are not 10870 // covering the whole dimension. 10871 if (LowerBound) { 10872 llvm::APSInt ConstLowerBound; 10873 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 10874 return false; // Can't get the integer value as a constant. 10875 if (ConstLowerBound.getSExtValue()) 10876 return true; 10877 } 10878 10879 // If we don't have a length we covering the whole dimension. 10880 if (!Length) 10881 return false; 10882 10883 // If the base is a pointer, we don't have a way to get the size of the 10884 // pointee. 10885 if (BaseQTy->isPointerType()) 10886 return false; 10887 10888 // We can only check if the length is the same as the size of the dimension 10889 // if we have a constant array. 10890 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 10891 if (!CATy) 10892 return false; 10893 10894 llvm::APSInt ConstLength; 10895 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10896 return false; // Can't get the integer value as a constant. 10897 10898 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 10899 } 10900 10901 // Return true if it can be proven that the provided array expression (array 10902 // section or array subscript) does NOT specify a single element of the array 10903 // whose base type is \a BaseQTy. 10904 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 10905 const Expr *E, 10906 QualType BaseQTy) { 10907 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10908 10909 // An array subscript always refer to a single element. Also, an array section 10910 // assumes the format of an array subscript if no colon is used. 10911 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 10912 return false; 10913 10914 assert(OASE && "Expecting array section if not an array subscript."); 10915 auto *Length = OASE->getLength(); 10916 10917 // If we don't have a length we have to check if the array has unitary size 10918 // for this dimension. Also, we should always expect a length if the base type 10919 // is pointer. 10920 if (!Length) { 10921 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10922 return ATy->getSize().getSExtValue() != 1; 10923 // We cannot assume anything. 10924 return false; 10925 } 10926 10927 // Check if the length evaluates to 1. 10928 llvm::APSInt ConstLength; 10929 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10930 return false; // Can't get the integer value as a constant. 10931 10932 return ConstLength.getSExtValue() != 1; 10933 } 10934 10935 // Return the expression of the base of the mappable expression or null if it 10936 // cannot be determined and do all the necessary checks to see if the expression 10937 // is valid as a standalone mappable expression. In the process, record all the 10938 // components of the expression. 10939 static Expr *CheckMapClauseExpressionBase( 10940 Sema &SemaRef, Expr *E, 10941 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 10942 OpenMPClauseKind CKind) { 10943 SourceLocation ELoc = E->getExprLoc(); 10944 SourceRange ERange = E->getSourceRange(); 10945 10946 // The base of elements of list in a map clause have to be either: 10947 // - a reference to variable or field. 10948 // - a member expression. 10949 // - an array expression. 10950 // 10951 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 10952 // reference to 'r'. 10953 // 10954 // If we have: 10955 // 10956 // struct SS { 10957 // Bla S; 10958 // foo() { 10959 // #pragma omp target map (S.Arr[:12]); 10960 // } 10961 // } 10962 // 10963 // We want to retrieve the member expression 'this->S'; 10964 10965 Expr *RelevantExpr = nullptr; 10966 10967 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 10968 // If a list item is an array section, it must specify contiguous storage. 10969 // 10970 // For this restriction it is sufficient that we make sure only references 10971 // to variables or fields and array expressions, and that no array sections 10972 // exist except in the rightmost expression (unless they cover the whole 10973 // dimension of the array). E.g. these would be invalid: 10974 // 10975 // r.ArrS[3:5].Arr[6:7] 10976 // 10977 // r.ArrS[3:5].x 10978 // 10979 // but these would be valid: 10980 // r.ArrS[3].Arr[6:7] 10981 // 10982 // r.ArrS[3].x 10983 10984 bool AllowUnitySizeArraySection = true; 10985 bool AllowWholeSizeArraySection = true; 10986 10987 while (!RelevantExpr) { 10988 E = E->IgnoreParenImpCasts(); 10989 10990 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 10991 if (!isa<VarDecl>(CurE->getDecl())) 10992 break; 10993 10994 RelevantExpr = CurE; 10995 10996 // If we got a reference to a declaration, we should not expect any array 10997 // section before that. 10998 AllowUnitySizeArraySection = false; 10999 AllowWholeSizeArraySection = false; 11000 11001 // Record the component. 11002 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent( 11003 CurE, CurE->getDecl())); 11004 continue; 11005 } 11006 11007 if (auto *CurE = dyn_cast<MemberExpr>(E)) { 11008 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 11009 11010 if (isa<CXXThisExpr>(BaseE)) 11011 // We found a base expression: this->Val. 11012 RelevantExpr = CurE; 11013 else 11014 E = BaseE; 11015 11016 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 11017 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 11018 << CurE->getSourceRange(); 11019 break; 11020 } 11021 11022 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 11023 11024 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 11025 // A bit-field cannot appear in a map clause. 11026 // 11027 if (FD->isBitField()) { 11028 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 11029 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 11030 break; 11031 } 11032 11033 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11034 // If the type of a list item is a reference to a type T then the type 11035 // will be considered to be T for all purposes of this clause. 11036 QualType CurType = BaseE->getType().getNonReferenceType(); 11037 11038 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 11039 // A list item cannot be a variable that is a member of a structure with 11040 // a union type. 11041 // 11042 if (auto *RT = CurType->getAs<RecordType>()) 11043 if (RT->isUnionType()) { 11044 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 11045 << CurE->getSourceRange(); 11046 break; 11047 } 11048 11049 // If we got a member expression, we should not expect any array section 11050 // before that: 11051 // 11052 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 11053 // If a list item is an element of a structure, only the rightmost symbol 11054 // of the variable reference can be an array section. 11055 // 11056 AllowUnitySizeArraySection = false; 11057 AllowWholeSizeArraySection = false; 11058 11059 // Record the component. 11060 CurComponents.push_back( 11061 OMPClauseMappableExprCommon::MappableComponent(CurE, FD)); 11062 continue; 11063 } 11064 11065 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 11066 E = CurE->getBase()->IgnoreParenImpCasts(); 11067 11068 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 11069 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 11070 << 0 << CurE->getSourceRange(); 11071 break; 11072 } 11073 11074 // If we got an array subscript that express the whole dimension we 11075 // can have any array expressions before. If it only expressing part of 11076 // the dimension, we can only have unitary-size array expressions. 11077 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 11078 E->getType())) 11079 AllowWholeSizeArraySection = false; 11080 11081 // Record the component - we don't have any declaration associated. 11082 CurComponents.push_back( 11083 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 11084 continue; 11085 } 11086 11087 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 11088 E = CurE->getBase()->IgnoreParenImpCasts(); 11089 11090 auto CurType = 11091 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 11092 11093 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11094 // If the type of a list item is a reference to a type T then the type 11095 // will be considered to be T for all purposes of this clause. 11096 if (CurType->isReferenceType()) 11097 CurType = CurType->getPointeeType(); 11098 11099 bool IsPointer = CurType->isAnyPointerType(); 11100 11101 if (!IsPointer && !CurType->isArrayType()) { 11102 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 11103 << 0 << CurE->getSourceRange(); 11104 break; 11105 } 11106 11107 bool NotWhole = 11108 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 11109 bool NotUnity = 11110 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 11111 11112 if (AllowWholeSizeArraySection) { 11113 // Any array section is currently allowed. Allowing a whole size array 11114 // section implies allowing a unity array section as well. 11115 // 11116 // If this array section refers to the whole dimension we can still 11117 // accept other array sections before this one, except if the base is a 11118 // pointer. Otherwise, only unitary sections are accepted. 11119 if (NotWhole || IsPointer) 11120 AllowWholeSizeArraySection = false; 11121 } else if (AllowUnitySizeArraySection && NotUnity) { 11122 // A unity or whole array section is not allowed and that is not 11123 // compatible with the properties of the current array section. 11124 SemaRef.Diag( 11125 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 11126 << CurE->getSourceRange(); 11127 break; 11128 } 11129 11130 // Record the component - we don't have any declaration associated. 11131 CurComponents.push_back( 11132 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 11133 continue; 11134 } 11135 11136 // If nothing else worked, this is not a valid map clause expression. 11137 SemaRef.Diag(ELoc, 11138 diag::err_omp_expected_named_var_member_or_array_expression) 11139 << ERange; 11140 break; 11141 } 11142 11143 return RelevantExpr; 11144 } 11145 11146 // Return true if expression E associated with value VD has conflicts with other 11147 // map information. 11148 static bool CheckMapConflicts( 11149 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 11150 bool CurrentRegionOnly, 11151 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 11152 OpenMPClauseKind CKind) { 11153 assert(VD && E); 11154 SourceLocation ELoc = E->getExprLoc(); 11155 SourceRange ERange = E->getSourceRange(); 11156 11157 // In order to easily check the conflicts we need to match each component of 11158 // the expression under test with the components of the expressions that are 11159 // already in the stack. 11160 11161 assert(!CurComponents.empty() && "Map clause expression with no components!"); 11162 assert(CurComponents.back().getAssociatedDeclaration() == VD && 11163 "Map clause expression with unexpected base!"); 11164 11165 // Variables to help detecting enclosing problems in data environment nests. 11166 bool IsEnclosedByDataEnvironmentExpr = false; 11167 const Expr *EnclosingExpr = nullptr; 11168 11169 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 11170 VD, CurrentRegionOnly, 11171 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 11172 StackComponents, 11173 OpenMPClauseKind) -> bool { 11174 11175 assert(!StackComponents.empty() && 11176 "Map clause expression with no components!"); 11177 assert(StackComponents.back().getAssociatedDeclaration() == VD && 11178 "Map clause expression with unexpected base!"); 11179 11180 // The whole expression in the stack. 11181 auto *RE = StackComponents.front().getAssociatedExpression(); 11182 11183 // Expressions must start from the same base. Here we detect at which 11184 // point both expressions diverge from each other and see if we can 11185 // detect if the memory referred to both expressions is contiguous and 11186 // do not overlap. 11187 auto CI = CurComponents.rbegin(); 11188 auto CE = CurComponents.rend(); 11189 auto SI = StackComponents.rbegin(); 11190 auto SE = StackComponents.rend(); 11191 for (; CI != CE && SI != SE; ++CI, ++SI) { 11192 11193 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 11194 // At most one list item can be an array item derived from a given 11195 // variable in map clauses of the same construct. 11196 if (CurrentRegionOnly && 11197 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 11198 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 11199 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 11200 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 11201 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 11202 diag::err_omp_multiple_array_items_in_map_clause) 11203 << CI->getAssociatedExpression()->getSourceRange(); 11204 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 11205 diag::note_used_here) 11206 << SI->getAssociatedExpression()->getSourceRange(); 11207 return true; 11208 } 11209 11210 // Do both expressions have the same kind? 11211 if (CI->getAssociatedExpression()->getStmtClass() != 11212 SI->getAssociatedExpression()->getStmtClass()) 11213 break; 11214 11215 // Are we dealing with different variables/fields? 11216 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 11217 break; 11218 } 11219 // Check if the extra components of the expressions in the enclosing 11220 // data environment are redundant for the current base declaration. 11221 // If they are, the maps completely overlap, which is legal. 11222 for (; SI != SE; ++SI) { 11223 QualType Type; 11224 if (auto *ASE = 11225 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 11226 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 11227 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>( 11228 SI->getAssociatedExpression())) { 11229 auto *E = OASE->getBase()->IgnoreParenImpCasts(); 11230 Type = 11231 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 11232 } 11233 if (Type.isNull() || Type->isAnyPointerType() || 11234 CheckArrayExpressionDoesNotReferToWholeSize( 11235 SemaRef, SI->getAssociatedExpression(), Type)) 11236 break; 11237 } 11238 11239 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 11240 // List items of map clauses in the same construct must not share 11241 // original storage. 11242 // 11243 // If the expressions are exactly the same or one is a subset of the 11244 // other, it means they are sharing storage. 11245 if (CI == CE && SI == SE) { 11246 if (CurrentRegionOnly) { 11247 if (CKind == OMPC_map) 11248 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 11249 else { 11250 assert(CKind == OMPC_to || CKind == OMPC_from); 11251 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 11252 << ERange; 11253 } 11254 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 11255 << RE->getSourceRange(); 11256 return true; 11257 } else { 11258 // If we find the same expression in the enclosing data environment, 11259 // that is legal. 11260 IsEnclosedByDataEnvironmentExpr = true; 11261 return false; 11262 } 11263 } 11264 11265 QualType DerivedType = 11266 std::prev(CI)->getAssociatedDeclaration()->getType(); 11267 SourceLocation DerivedLoc = 11268 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 11269 11270 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11271 // If the type of a list item is a reference to a type T then the type 11272 // will be considered to be T for all purposes of this clause. 11273 DerivedType = DerivedType.getNonReferenceType(); 11274 11275 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 11276 // A variable for which the type is pointer and an array section 11277 // derived from that variable must not appear as list items of map 11278 // clauses of the same construct. 11279 // 11280 // Also, cover one of the cases in: 11281 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 11282 // If any part of the original storage of a list item has corresponding 11283 // storage in the device data environment, all of the original storage 11284 // must have corresponding storage in the device data environment. 11285 // 11286 if (DerivedType->isAnyPointerType()) { 11287 if (CI == CE || SI == SE) { 11288 SemaRef.Diag( 11289 DerivedLoc, 11290 diag::err_omp_pointer_mapped_along_with_derived_section) 11291 << DerivedLoc; 11292 } else { 11293 assert(CI != CE && SI != SE); 11294 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) 11295 << DerivedLoc; 11296 } 11297 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 11298 << RE->getSourceRange(); 11299 return true; 11300 } 11301 11302 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 11303 // List items of map clauses in the same construct must not share 11304 // original storage. 11305 // 11306 // An expression is a subset of the other. 11307 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 11308 if (CKind == OMPC_map) 11309 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 11310 else { 11311 assert(CKind == OMPC_to || CKind == OMPC_from); 11312 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 11313 << ERange; 11314 } 11315 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 11316 << RE->getSourceRange(); 11317 return true; 11318 } 11319 11320 // The current expression uses the same base as other expression in the 11321 // data environment but does not contain it completely. 11322 if (!CurrentRegionOnly && SI != SE) 11323 EnclosingExpr = RE; 11324 11325 // The current expression is a subset of the expression in the data 11326 // environment. 11327 IsEnclosedByDataEnvironmentExpr |= 11328 (!CurrentRegionOnly && CI != CE && SI == SE); 11329 11330 return false; 11331 }); 11332 11333 if (CurrentRegionOnly) 11334 return FoundError; 11335 11336 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 11337 // If any part of the original storage of a list item has corresponding 11338 // storage in the device data environment, all of the original storage must 11339 // have corresponding storage in the device data environment. 11340 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 11341 // If a list item is an element of a structure, and a different element of 11342 // the structure has a corresponding list item in the device data environment 11343 // prior to a task encountering the construct associated with the map clause, 11344 // then the list item must also have a corresponding list item in the device 11345 // data environment prior to the task encountering the construct. 11346 // 11347 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 11348 SemaRef.Diag(ELoc, 11349 diag::err_omp_original_storage_is_shared_and_does_not_contain) 11350 << ERange; 11351 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 11352 << EnclosingExpr->getSourceRange(); 11353 return true; 11354 } 11355 11356 return FoundError; 11357 } 11358 11359 namespace { 11360 // Utility struct that gathers all the related lists associated with a mappable 11361 // expression. 11362 struct MappableVarListInfo final { 11363 // The list of expressions. 11364 ArrayRef<Expr *> VarList; 11365 // The list of processed expressions. 11366 SmallVector<Expr *, 16> ProcessedVarList; 11367 // The mappble components for each expression. 11368 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 11369 // The base declaration of the variable. 11370 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 11371 11372 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 11373 // We have a list of components and base declarations for each entry in the 11374 // variable list. 11375 VarComponents.reserve(VarList.size()); 11376 VarBaseDeclarations.reserve(VarList.size()); 11377 } 11378 }; 11379 } 11380 11381 // Check the validity of the provided variable list for the provided clause kind 11382 // \a CKind. In the check process the valid expressions, and mappable expression 11383 // components and variables are extracted and used to fill \a Vars, 11384 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 11385 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 11386 static void 11387 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 11388 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 11389 SourceLocation StartLoc, 11390 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 11391 bool IsMapTypeImplicit = false) { 11392 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 11393 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 11394 "Unexpected clause kind with mappable expressions!"); 11395 11396 // Keep track of the mappable components and base declarations in this clause. 11397 // Each entry in the list is going to have a list of components associated. We 11398 // record each set of the components so that we can build the clause later on. 11399 // In the end we should have the same amount of declarations and component 11400 // lists. 11401 11402 for (auto &RE : MVLI.VarList) { 11403 assert(RE && "Null expr in omp to/from/map clause"); 11404 SourceLocation ELoc = RE->getExprLoc(); 11405 11406 auto *VE = RE->IgnoreParenLValueCasts(); 11407 11408 if (VE->isValueDependent() || VE->isTypeDependent() || 11409 VE->isInstantiationDependent() || 11410 VE->containsUnexpandedParameterPack()) { 11411 // We can only analyze this information once the missing information is 11412 // resolved. 11413 MVLI.ProcessedVarList.push_back(RE); 11414 continue; 11415 } 11416 11417 auto *SimpleExpr = RE->IgnoreParenCasts(); 11418 11419 if (!RE->IgnoreParenImpCasts()->isLValue()) { 11420 SemaRef.Diag(ELoc, 11421 diag::err_omp_expected_named_var_member_or_array_expression) 11422 << RE->getSourceRange(); 11423 continue; 11424 } 11425 11426 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 11427 ValueDecl *CurDeclaration = nullptr; 11428 11429 // Obtain the array or member expression bases if required. Also, fill the 11430 // components array with all the components identified in the process. 11431 auto *BE = 11432 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind); 11433 if (!BE) 11434 continue; 11435 11436 assert(!CurComponents.empty() && 11437 "Invalid mappable expression information."); 11438 11439 // For the following checks, we rely on the base declaration which is 11440 // expected to be associated with the last component. The declaration is 11441 // expected to be a variable or a field (if 'this' is being mapped). 11442 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 11443 assert(CurDeclaration && "Null decl on map clause."); 11444 assert( 11445 CurDeclaration->isCanonicalDecl() && 11446 "Expecting components to have associated only canonical declarations."); 11447 11448 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 11449 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 11450 11451 assert((VD || FD) && "Only variables or fields are expected here!"); 11452 (void)FD; 11453 11454 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 11455 // threadprivate variables cannot appear in a map clause. 11456 // OpenMP 4.5 [2.10.5, target update Construct] 11457 // threadprivate variables cannot appear in a from clause. 11458 if (VD && DSAS->isThreadPrivate(VD)) { 11459 auto DVar = DSAS->getTopDSA(VD, false); 11460 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 11461 << getOpenMPClauseName(CKind); 11462 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 11463 continue; 11464 } 11465 11466 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 11467 // A list item cannot appear in both a map clause and a data-sharing 11468 // attribute clause on the same construct. 11469 11470 // Check conflicts with other map clause expressions. We check the conflicts 11471 // with the current construct separately from the enclosing data 11472 // environment, because the restrictions are different. We only have to 11473 // check conflicts across regions for the map clauses. 11474 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 11475 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 11476 break; 11477 if (CKind == OMPC_map && 11478 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 11479 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 11480 break; 11481 11482 // OpenMP 4.5 [2.10.5, target update Construct] 11483 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11484 // If the type of a list item is a reference to a type T then the type will 11485 // be considered to be T for all purposes of this clause. 11486 QualType Type = CurDeclaration->getType().getNonReferenceType(); 11487 11488 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 11489 // A list item in a to or from clause must have a mappable type. 11490 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 11491 // A list item must have a mappable type. 11492 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 11493 DSAS, Type)) 11494 continue; 11495 11496 if (CKind == OMPC_map) { 11497 // target enter data 11498 // OpenMP [2.10.2, Restrictions, p. 99] 11499 // A map-type must be specified in all map clauses and must be either 11500 // to or alloc. 11501 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 11502 if (DKind == OMPD_target_enter_data && 11503 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 11504 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 11505 << (IsMapTypeImplicit ? 1 : 0) 11506 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 11507 << getOpenMPDirectiveName(DKind); 11508 continue; 11509 } 11510 11511 // target exit_data 11512 // OpenMP [2.10.3, Restrictions, p. 102] 11513 // A map-type must be specified in all map clauses and must be either 11514 // from, release, or delete. 11515 if (DKind == OMPD_target_exit_data && 11516 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 11517 MapType == OMPC_MAP_delete)) { 11518 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 11519 << (IsMapTypeImplicit ? 1 : 0) 11520 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 11521 << getOpenMPDirectiveName(DKind); 11522 continue; 11523 } 11524 11525 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 11526 // A list item cannot appear in both a map clause and a data-sharing 11527 // attribute clause on the same construct 11528 if ((DKind == OMPD_target || DKind == OMPD_target_teams || 11529 DKind == OMPD_target_teams_distribute || 11530 DKind == OMPD_target_teams_distribute_parallel_for || 11531 DKind == OMPD_target_teams_distribute_parallel_for_simd || 11532 DKind == OMPD_target_teams_distribute_simd) && VD) { 11533 auto DVar = DSAS->getTopDSA(VD, false); 11534 if (isOpenMPPrivate(DVar.CKind)) { 11535 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 11536 << getOpenMPClauseName(DVar.CKind) 11537 << getOpenMPClauseName(OMPC_map) 11538 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 11539 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 11540 continue; 11541 } 11542 } 11543 } 11544 11545 // Save the current expression. 11546 MVLI.ProcessedVarList.push_back(RE); 11547 11548 // Store the components in the stack so that they can be used to check 11549 // against other clauses later on. 11550 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 11551 /*WhereFoundClauseKind=*/OMPC_map); 11552 11553 // Save the components and declaration to create the clause. For purposes of 11554 // the clause creation, any component list that has has base 'this' uses 11555 // null as base declaration. 11556 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11557 MVLI.VarComponents.back().append(CurComponents.begin(), 11558 CurComponents.end()); 11559 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 11560 : CurDeclaration); 11561 } 11562 } 11563 11564 OMPClause * 11565 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 11566 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 11567 SourceLocation MapLoc, SourceLocation ColonLoc, 11568 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 11569 SourceLocation LParenLoc, SourceLocation EndLoc) { 11570 MappableVarListInfo MVLI(VarList); 11571 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 11572 MapType, IsMapTypeImplicit); 11573 11574 // We need to produce a map clause even if we don't have variables so that 11575 // other diagnostics related with non-existing map clauses are accurate. 11576 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11577 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11578 MVLI.VarComponents, MapTypeModifier, MapType, 11579 IsMapTypeImplicit, MapLoc); 11580 } 11581 11582 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 11583 TypeResult ParsedType) { 11584 assert(ParsedType.isUsable()); 11585 11586 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 11587 if (ReductionType.isNull()) 11588 return QualType(); 11589 11590 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 11591 // A type name in a declare reduction directive cannot be a function type, an 11592 // array type, a reference type, or a type qualified with const, volatile or 11593 // restrict. 11594 if (ReductionType.hasQualifiers()) { 11595 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 11596 return QualType(); 11597 } 11598 11599 if (ReductionType->isFunctionType()) { 11600 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 11601 return QualType(); 11602 } 11603 if (ReductionType->isReferenceType()) { 11604 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 11605 return QualType(); 11606 } 11607 if (ReductionType->isArrayType()) { 11608 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 11609 return QualType(); 11610 } 11611 return ReductionType; 11612 } 11613 11614 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 11615 Scope *S, DeclContext *DC, DeclarationName Name, 11616 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 11617 AccessSpecifier AS, Decl *PrevDeclInScope) { 11618 SmallVector<Decl *, 8> Decls; 11619 Decls.reserve(ReductionTypes.size()); 11620 11621 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 11622 forRedeclarationInCurContext()); 11623 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 11624 // A reduction-identifier may not be re-declared in the current scope for the 11625 // same type or for a type that is compatible according to the base language 11626 // rules. 11627 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 11628 OMPDeclareReductionDecl *PrevDRD = nullptr; 11629 bool InCompoundScope = true; 11630 if (S != nullptr) { 11631 // Find previous declaration with the same name not referenced in other 11632 // declarations. 11633 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 11634 InCompoundScope = 11635 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 11636 LookupName(Lookup, S); 11637 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 11638 /*AllowInlineNamespace=*/false); 11639 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 11640 auto Filter = Lookup.makeFilter(); 11641 while (Filter.hasNext()) { 11642 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 11643 if (InCompoundScope) { 11644 auto I = UsedAsPrevious.find(PrevDecl); 11645 if (I == UsedAsPrevious.end()) 11646 UsedAsPrevious[PrevDecl] = false; 11647 if (auto *D = PrevDecl->getPrevDeclInScope()) 11648 UsedAsPrevious[D] = true; 11649 } 11650 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 11651 PrevDecl->getLocation(); 11652 } 11653 Filter.done(); 11654 if (InCompoundScope) { 11655 for (auto &PrevData : UsedAsPrevious) { 11656 if (!PrevData.second) { 11657 PrevDRD = PrevData.first; 11658 break; 11659 } 11660 } 11661 } 11662 } else if (PrevDeclInScope != nullptr) { 11663 auto *PrevDRDInScope = PrevDRD = 11664 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 11665 do { 11666 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 11667 PrevDRDInScope->getLocation(); 11668 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 11669 } while (PrevDRDInScope != nullptr); 11670 } 11671 for (auto &TyData : ReductionTypes) { 11672 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 11673 bool Invalid = false; 11674 if (I != PreviousRedeclTypes.end()) { 11675 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 11676 << TyData.first; 11677 Diag(I->second, diag::note_previous_definition); 11678 Invalid = true; 11679 } 11680 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 11681 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 11682 Name, TyData.first, PrevDRD); 11683 DC->addDecl(DRD); 11684 DRD->setAccess(AS); 11685 Decls.push_back(DRD); 11686 if (Invalid) 11687 DRD->setInvalidDecl(); 11688 else 11689 PrevDRD = DRD; 11690 } 11691 11692 return DeclGroupPtrTy::make( 11693 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 11694 } 11695 11696 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 11697 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11698 11699 // Enter new function scope. 11700 PushFunctionScope(); 11701 getCurFunction()->setHasBranchProtectedScope(); 11702 getCurFunction()->setHasOMPDeclareReductionCombiner(); 11703 11704 if (S != nullptr) 11705 PushDeclContext(S, DRD); 11706 else 11707 CurContext = DRD; 11708 11709 PushExpressionEvaluationContext( 11710 ExpressionEvaluationContext::PotentiallyEvaluated); 11711 11712 QualType ReductionType = DRD->getType(); 11713 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 11714 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 11715 // uses semantics of argument handles by value, but it should be passed by 11716 // reference. C lang does not support references, so pass all parameters as 11717 // pointers. 11718 // Create 'T omp_in;' variable. 11719 auto *OmpInParm = 11720 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 11721 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 11722 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 11723 // uses semantics of argument handles by value, but it should be passed by 11724 // reference. C lang does not support references, so pass all parameters as 11725 // pointers. 11726 // Create 'T omp_out;' variable. 11727 auto *OmpOutParm = 11728 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 11729 if (S != nullptr) { 11730 PushOnScopeChains(OmpInParm, S); 11731 PushOnScopeChains(OmpOutParm, S); 11732 } else { 11733 DRD->addDecl(OmpInParm); 11734 DRD->addDecl(OmpOutParm); 11735 } 11736 } 11737 11738 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 11739 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11740 DiscardCleanupsInEvaluationContext(); 11741 PopExpressionEvaluationContext(); 11742 11743 PopDeclContext(); 11744 PopFunctionScopeInfo(); 11745 11746 if (Combiner != nullptr) 11747 DRD->setCombiner(Combiner); 11748 else 11749 DRD->setInvalidDecl(); 11750 } 11751 11752 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 11753 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11754 11755 // Enter new function scope. 11756 PushFunctionScope(); 11757 getCurFunction()->setHasBranchProtectedScope(); 11758 11759 if (S != nullptr) 11760 PushDeclContext(S, DRD); 11761 else 11762 CurContext = DRD; 11763 11764 PushExpressionEvaluationContext( 11765 ExpressionEvaluationContext::PotentiallyEvaluated); 11766 11767 QualType ReductionType = DRD->getType(); 11768 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 11769 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 11770 // uses semantics of argument handles by value, but it should be passed by 11771 // reference. C lang does not support references, so pass all parameters as 11772 // pointers. 11773 // Create 'T omp_priv;' variable. 11774 auto *OmpPrivParm = 11775 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 11776 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 11777 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 11778 // uses semantics of argument handles by value, but it should be passed by 11779 // reference. C lang does not support references, so pass all parameters as 11780 // pointers. 11781 // Create 'T omp_orig;' variable. 11782 auto *OmpOrigParm = 11783 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 11784 if (S != nullptr) { 11785 PushOnScopeChains(OmpPrivParm, S); 11786 PushOnScopeChains(OmpOrigParm, S); 11787 } else { 11788 DRD->addDecl(OmpPrivParm); 11789 DRD->addDecl(OmpOrigParm); 11790 } 11791 return OmpPrivParm; 11792 } 11793 11794 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 11795 VarDecl *OmpPrivParm) { 11796 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11797 DiscardCleanupsInEvaluationContext(); 11798 PopExpressionEvaluationContext(); 11799 11800 PopDeclContext(); 11801 PopFunctionScopeInfo(); 11802 11803 if (Initializer != nullptr) { 11804 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 11805 } else if (OmpPrivParm->hasInit()) { 11806 DRD->setInitializer(OmpPrivParm->getInit(), 11807 OmpPrivParm->isDirectInit() 11808 ? OMPDeclareReductionDecl::DirectInit 11809 : OMPDeclareReductionDecl::CopyInit); 11810 } else { 11811 DRD->setInvalidDecl(); 11812 } 11813 } 11814 11815 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 11816 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 11817 for (auto *D : DeclReductions.get()) { 11818 if (IsValid) { 11819 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11820 if (S != nullptr) 11821 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 11822 } else 11823 D->setInvalidDecl(); 11824 } 11825 return DeclReductions; 11826 } 11827 11828 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 11829 SourceLocation StartLoc, 11830 SourceLocation LParenLoc, 11831 SourceLocation EndLoc) { 11832 Expr *ValExpr = NumTeams; 11833 Stmt *HelperValStmt = nullptr; 11834 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11835 11836 // OpenMP [teams Constrcut, Restrictions] 11837 // The num_teams expression must evaluate to a positive integer value. 11838 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 11839 /*StrictlyPositive=*/true)) 11840 return nullptr; 11841 11842 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11843 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 11844 if (CaptureRegion != OMPD_unknown) { 11845 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11846 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11847 HelperValStmt = buildPreInits(Context, Captures); 11848 } 11849 11850 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 11851 StartLoc, LParenLoc, EndLoc); 11852 } 11853 11854 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 11855 SourceLocation StartLoc, 11856 SourceLocation LParenLoc, 11857 SourceLocation EndLoc) { 11858 Expr *ValExpr = ThreadLimit; 11859 Stmt *HelperValStmt = nullptr; 11860 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11861 11862 // OpenMP [teams Constrcut, Restrictions] 11863 // The thread_limit expression must evaluate to a positive integer value. 11864 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 11865 /*StrictlyPositive=*/true)) 11866 return nullptr; 11867 11868 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11869 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 11870 if (CaptureRegion != OMPD_unknown) { 11871 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11872 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11873 HelperValStmt = buildPreInits(Context, Captures); 11874 } 11875 11876 return new (Context) OMPThreadLimitClause( 11877 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 11878 } 11879 11880 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 11881 SourceLocation StartLoc, 11882 SourceLocation LParenLoc, 11883 SourceLocation EndLoc) { 11884 Expr *ValExpr = Priority; 11885 11886 // OpenMP [2.9.1, task Constrcut] 11887 // The priority-value is a non-negative numerical scalar expression. 11888 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 11889 /*StrictlyPositive=*/false)) 11890 return nullptr; 11891 11892 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11893 } 11894 11895 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 11896 SourceLocation StartLoc, 11897 SourceLocation LParenLoc, 11898 SourceLocation EndLoc) { 11899 Expr *ValExpr = Grainsize; 11900 11901 // OpenMP [2.9.2, taskloop Constrcut] 11902 // The parameter of the grainsize clause must be a positive integer 11903 // expression. 11904 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 11905 /*StrictlyPositive=*/true)) 11906 return nullptr; 11907 11908 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11909 } 11910 11911 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 11912 SourceLocation StartLoc, 11913 SourceLocation LParenLoc, 11914 SourceLocation EndLoc) { 11915 Expr *ValExpr = NumTasks; 11916 11917 // OpenMP [2.9.2, taskloop Constrcut] 11918 // The parameter of the num_tasks clause must be a positive integer 11919 // expression. 11920 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 11921 /*StrictlyPositive=*/true)) 11922 return nullptr; 11923 11924 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11925 } 11926 11927 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 11928 SourceLocation LParenLoc, 11929 SourceLocation EndLoc) { 11930 // OpenMP [2.13.2, critical construct, Description] 11931 // ... where hint-expression is an integer constant expression that evaluates 11932 // to a valid lock hint. 11933 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 11934 if (HintExpr.isInvalid()) 11935 return nullptr; 11936 return new (Context) 11937 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 11938 } 11939 11940 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 11941 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 11942 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 11943 SourceLocation EndLoc) { 11944 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 11945 std::string Values; 11946 Values += "'"; 11947 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 11948 Values += "'"; 11949 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 11950 << Values << getOpenMPClauseName(OMPC_dist_schedule); 11951 return nullptr; 11952 } 11953 Expr *ValExpr = ChunkSize; 11954 Stmt *HelperValStmt = nullptr; 11955 if (ChunkSize) { 11956 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 11957 !ChunkSize->isInstantiationDependent() && 11958 !ChunkSize->containsUnexpandedParameterPack()) { 11959 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 11960 ExprResult Val = 11961 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 11962 if (Val.isInvalid()) 11963 return nullptr; 11964 11965 ValExpr = Val.get(); 11966 11967 // OpenMP [2.7.1, Restrictions] 11968 // chunk_size must be a loop invariant integer expression with a positive 11969 // value. 11970 llvm::APSInt Result; 11971 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 11972 if (Result.isSigned() && !Result.isStrictlyPositive()) { 11973 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 11974 << "dist_schedule" << ChunkSize->getSourceRange(); 11975 return nullptr; 11976 } 11977 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 11978 !CurContext->isDependentContext()) { 11979 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11980 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11981 HelperValStmt = buildPreInits(Context, Captures); 11982 } 11983 } 11984 } 11985 11986 return new (Context) 11987 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 11988 Kind, ValExpr, HelperValStmt); 11989 } 11990 11991 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 11992 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 11993 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 11994 SourceLocation KindLoc, SourceLocation EndLoc) { 11995 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 11996 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 11997 std::string Value; 11998 SourceLocation Loc; 11999 Value += "'"; 12000 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 12001 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 12002 OMPC_DEFAULTMAP_MODIFIER_tofrom); 12003 Loc = MLoc; 12004 } else { 12005 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 12006 OMPC_DEFAULTMAP_scalar); 12007 Loc = KindLoc; 12008 } 12009 Value += "'"; 12010 Diag(Loc, diag::err_omp_unexpected_clause_value) 12011 << Value << getOpenMPClauseName(OMPC_defaultmap); 12012 return nullptr; 12013 } 12014 DSAStack->setDefaultDMAToFromScalar(StartLoc); 12015 12016 return new (Context) 12017 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 12018 } 12019 12020 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 12021 DeclContext *CurLexicalContext = getCurLexicalContext(); 12022 if (!CurLexicalContext->isFileContext() && 12023 !CurLexicalContext->isExternCContext() && 12024 !CurLexicalContext->isExternCXXContext() && 12025 !isa<CXXRecordDecl>(CurLexicalContext) && 12026 !isa<ClassTemplateDecl>(CurLexicalContext) && 12027 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 12028 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 12029 Diag(Loc, diag::err_omp_region_not_file_context); 12030 return false; 12031 } 12032 if (IsInOpenMPDeclareTargetContext) { 12033 Diag(Loc, diag::err_omp_enclosed_declare_target); 12034 return false; 12035 } 12036 12037 IsInOpenMPDeclareTargetContext = true; 12038 return true; 12039 } 12040 12041 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 12042 assert(IsInOpenMPDeclareTargetContext && 12043 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 12044 12045 IsInOpenMPDeclareTargetContext = false; 12046 } 12047 12048 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 12049 CXXScopeSpec &ScopeSpec, 12050 const DeclarationNameInfo &Id, 12051 OMPDeclareTargetDeclAttr::MapTypeTy MT, 12052 NamedDeclSetType &SameDirectiveDecls) { 12053 LookupResult Lookup(*this, Id, LookupOrdinaryName); 12054 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 12055 12056 if (Lookup.isAmbiguous()) 12057 return; 12058 Lookup.suppressDiagnostics(); 12059 12060 if (!Lookup.isSingleResult()) { 12061 if (TypoCorrection Corrected = 12062 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 12063 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 12064 CTK_ErrorRecovery)) { 12065 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 12066 << Id.getName()); 12067 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 12068 return; 12069 } 12070 12071 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 12072 return; 12073 } 12074 12075 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 12076 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 12077 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 12078 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 12079 12080 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 12081 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 12082 ND->addAttr(A); 12083 if (ASTMutationListener *ML = Context.getASTMutationListener()) 12084 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 12085 checkDeclIsAllowedInOpenMPTarget(nullptr, ND); 12086 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 12087 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 12088 << Id.getName(); 12089 } 12090 } else 12091 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 12092 } 12093 12094 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 12095 Sema &SemaRef, Decl *D) { 12096 if (!D) 12097 return; 12098 Decl *LD = nullptr; 12099 if (isa<TagDecl>(D)) { 12100 LD = cast<TagDecl>(D)->getDefinition(); 12101 } else if (isa<VarDecl>(D)) { 12102 LD = cast<VarDecl>(D)->getDefinition(); 12103 12104 // If this is an implicit variable that is legal and we do not need to do 12105 // anything. 12106 if (cast<VarDecl>(D)->isImplicit()) { 12107 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12108 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 12109 D->addAttr(A); 12110 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 12111 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12112 return; 12113 } 12114 12115 } else if (isa<FunctionDecl>(D)) { 12116 const FunctionDecl *FD = nullptr; 12117 if (cast<FunctionDecl>(D)->hasBody(FD)) 12118 LD = const_cast<FunctionDecl *>(FD); 12119 12120 // If the definition is associated with the current declaration in the 12121 // target region (it can be e.g. a lambda) that is legal and we do not need 12122 // to do anything else. 12123 if (LD == D) { 12124 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12125 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 12126 D->addAttr(A); 12127 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 12128 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12129 return; 12130 } 12131 } 12132 if (!LD) 12133 LD = D; 12134 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 12135 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 12136 // Outlined declaration is not declared target. 12137 if (LD->isOutOfLine()) { 12138 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 12139 SemaRef.Diag(SL, diag::note_used_here) << SR; 12140 } else { 12141 DeclContext *DC = LD->getDeclContext(); 12142 while (DC) { 12143 if (isa<FunctionDecl>(DC) && 12144 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 12145 break; 12146 DC = DC->getParent(); 12147 } 12148 if (DC) 12149 return; 12150 12151 // Is not declared in target context. 12152 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 12153 SemaRef.Diag(SL, diag::note_used_here) << SR; 12154 } 12155 // Mark decl as declared target to prevent further diagnostic. 12156 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12157 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 12158 D->addAttr(A); 12159 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 12160 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12161 } 12162 } 12163 12164 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 12165 Sema &SemaRef, DSAStackTy *Stack, 12166 ValueDecl *VD) { 12167 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 12168 return true; 12169 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) 12170 return false; 12171 return true; 12172 } 12173 12174 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) { 12175 if (!D || D->isInvalidDecl()) 12176 return; 12177 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 12178 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 12179 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 12180 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12181 if (DSAStack->isThreadPrivate(VD)) { 12182 Diag(SL, diag::err_omp_threadprivate_in_target); 12183 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 12184 return; 12185 } 12186 } 12187 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 12188 // Problem if any with var declared with incomplete type will be reported 12189 // as normal, so no need to check it here. 12190 if ((E || !VD->getType()->isIncompleteType()) && 12191 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 12192 // Mark decl as declared target to prevent further diagnostic. 12193 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { 12194 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12195 Context, OMPDeclareTargetDeclAttr::MT_To); 12196 VD->addAttr(A); 12197 if (ASTMutationListener *ML = Context.getASTMutationListener()) 12198 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 12199 } 12200 return; 12201 } 12202 } 12203 if (!E) { 12204 // Checking declaration inside declare target region. 12205 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 12206 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { 12207 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12208 Context, OMPDeclareTargetDeclAttr::MT_To); 12209 D->addAttr(A); 12210 if (ASTMutationListener *ML = Context.getASTMutationListener()) 12211 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12212 } 12213 return; 12214 } 12215 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 12216 } 12217 12218 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 12219 SourceLocation StartLoc, 12220 SourceLocation LParenLoc, 12221 SourceLocation EndLoc) { 12222 MappableVarListInfo MVLI(VarList); 12223 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 12224 if (MVLI.ProcessedVarList.empty()) 12225 return nullptr; 12226 12227 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12228 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 12229 MVLI.VarComponents); 12230 } 12231 12232 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 12233 SourceLocation StartLoc, 12234 SourceLocation LParenLoc, 12235 SourceLocation EndLoc) { 12236 MappableVarListInfo MVLI(VarList); 12237 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 12238 if (MVLI.ProcessedVarList.empty()) 12239 return nullptr; 12240 12241 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12242 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 12243 MVLI.VarComponents); 12244 } 12245 12246 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 12247 SourceLocation StartLoc, 12248 SourceLocation LParenLoc, 12249 SourceLocation EndLoc) { 12250 MappableVarListInfo MVLI(VarList); 12251 SmallVector<Expr *, 8> PrivateCopies; 12252 SmallVector<Expr *, 8> Inits; 12253 12254 for (auto &RefExpr : VarList) { 12255 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 12256 SourceLocation ELoc; 12257 SourceRange ERange; 12258 Expr *SimpleRefExpr = RefExpr; 12259 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12260 if (Res.second) { 12261 // It will be analyzed later. 12262 MVLI.ProcessedVarList.push_back(RefExpr); 12263 PrivateCopies.push_back(nullptr); 12264 Inits.push_back(nullptr); 12265 } 12266 ValueDecl *D = Res.first; 12267 if (!D) 12268 continue; 12269 12270 QualType Type = D->getType(); 12271 Type = Type.getNonReferenceType().getUnqualifiedType(); 12272 12273 auto *VD = dyn_cast<VarDecl>(D); 12274 12275 // Item should be a pointer or reference to pointer. 12276 if (!Type->isPointerType()) { 12277 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 12278 << 0 << RefExpr->getSourceRange(); 12279 continue; 12280 } 12281 12282 // Build the private variable and the expression that refers to it. 12283 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 12284 D->hasAttrs() ? &D->getAttrs() : nullptr); 12285 if (VDPrivate->isInvalidDecl()) 12286 continue; 12287 12288 CurContext->addDecl(VDPrivate); 12289 auto VDPrivateRefExpr = buildDeclRefExpr( 12290 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 12291 12292 // Add temporary variable to initialize the private copy of the pointer. 12293 auto *VDInit = 12294 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 12295 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 12296 RefExpr->getExprLoc()); 12297 AddInitializerToDecl(VDPrivate, 12298 DefaultLvalueConversion(VDInitRefExpr).get(), 12299 /*DirectInit=*/false); 12300 12301 // If required, build a capture to implement the privatization initialized 12302 // with the current list item value. 12303 DeclRefExpr *Ref = nullptr; 12304 if (!VD) 12305 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 12306 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 12307 PrivateCopies.push_back(VDPrivateRefExpr); 12308 Inits.push_back(VDInitRefExpr); 12309 12310 // We need to add a data sharing attribute for this variable to make sure it 12311 // is correctly captured. A variable that shows up in a use_device_ptr has 12312 // similar properties of a first private variable. 12313 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 12314 12315 // Create a mappable component for the list item. List items in this clause 12316 // only need a component. 12317 MVLI.VarBaseDeclarations.push_back(D); 12318 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 12319 MVLI.VarComponents.back().push_back( 12320 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 12321 } 12322 12323 if (MVLI.ProcessedVarList.empty()) 12324 return nullptr; 12325 12326 return OMPUseDevicePtrClause::Create( 12327 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 12328 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 12329 } 12330 12331 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 12332 SourceLocation StartLoc, 12333 SourceLocation LParenLoc, 12334 SourceLocation EndLoc) { 12335 MappableVarListInfo MVLI(VarList); 12336 for (auto &RefExpr : VarList) { 12337 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 12338 SourceLocation ELoc; 12339 SourceRange ERange; 12340 Expr *SimpleRefExpr = RefExpr; 12341 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12342 if (Res.second) { 12343 // It will be analyzed later. 12344 MVLI.ProcessedVarList.push_back(RefExpr); 12345 } 12346 ValueDecl *D = Res.first; 12347 if (!D) 12348 continue; 12349 12350 QualType Type = D->getType(); 12351 // item should be a pointer or array or reference to pointer or array 12352 if (!Type.getNonReferenceType()->isPointerType() && 12353 !Type.getNonReferenceType()->isArrayType()) { 12354 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 12355 << 0 << RefExpr->getSourceRange(); 12356 continue; 12357 } 12358 12359 // Check if the declaration in the clause does not show up in any data 12360 // sharing attribute. 12361 auto DVar = DSAStack->getTopDSA(D, false); 12362 if (isOpenMPPrivate(DVar.CKind)) { 12363 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 12364 << getOpenMPClauseName(DVar.CKind) 12365 << getOpenMPClauseName(OMPC_is_device_ptr) 12366 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 12367 ReportOriginalDSA(*this, DSAStack, D, DVar); 12368 continue; 12369 } 12370 12371 Expr *ConflictExpr; 12372 if (DSAStack->checkMappableExprComponentListsForDecl( 12373 D, /*CurrentRegionOnly=*/true, 12374 [&ConflictExpr]( 12375 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 12376 OpenMPClauseKind) -> bool { 12377 ConflictExpr = R.front().getAssociatedExpression(); 12378 return true; 12379 })) { 12380 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 12381 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 12382 << ConflictExpr->getSourceRange(); 12383 continue; 12384 } 12385 12386 // Store the components in the stack so that they can be used to check 12387 // against other clauses later on. 12388 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 12389 DSAStack->addMappableExpressionComponents( 12390 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 12391 12392 // Record the expression we've just processed. 12393 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 12394 12395 // Create a mappable component for the list item. List items in this clause 12396 // only need a component. We use a null declaration to signal fields in 12397 // 'this'. 12398 assert((isa<DeclRefExpr>(SimpleRefExpr) || 12399 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 12400 "Unexpected device pointer expression!"); 12401 MVLI.VarBaseDeclarations.push_back( 12402 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 12403 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 12404 MVLI.VarComponents.back().push_back(MC); 12405 } 12406 12407 if (MVLI.ProcessedVarList.empty()) 12408 return nullptr; 12409 12410 return OMPIsDevicePtrClause::Create( 12411 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 12412 MVLI.VarBaseDeclarations, MVLI.VarComponents); 12413 } 12414