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 /// 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 const Expr *checkMapClauseExpressionBase( 39 Sema &SemaRef, Expr *E, 40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 41 OpenMPClauseKind CKind, bool NoDiagnose); 42 43 namespace { 44 /// Default data sharing attributes, which can be applied to directive. 45 enum DefaultDataSharingAttributes { 46 DSA_unspecified = 0, /// Data sharing attribute not specified. 47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'. 48 DSA_shared = 1 << 1, /// 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 /// Stack for tracking declarations used in OpenMP directives and 58 /// clauses and their data-sharing attributes. 59 class DSAStackTy { 60 public: 61 struct DSAVarData { 62 OpenMPDirectiveKind DKind = OMPD_unknown; 63 OpenMPClauseKind CKind = OMPC_unknown; 64 const Expr *RefExpr = nullptr; 65 DeclRefExpr *PrivateCopy = nullptr; 66 SourceLocation ImplicitDSALoc; 67 DSAVarData() = default; 68 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 69 const Expr *RefExpr, DeclRefExpr *PrivateCopy, 70 SourceLocation ImplicitDSALoc) 71 : DKind(DKind), CKind(CKind), RefExpr(RefExpr), 72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {} 73 }; 74 using OperatorOffsetTy = 75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>; 76 using DoacrossDependMapTy = 77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>; 78 79 private: 80 struct DSAInfo { 81 OpenMPClauseKind Attributes = OMPC_unknown; 82 /// Pointer to a reference expression and a flag which shows that the 83 /// variable is marked as lastprivate(true) or not (false). 84 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr; 85 DeclRefExpr *PrivateCopy = nullptr; 86 }; 87 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>; 88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>; 89 using LCDeclInfo = std::pair<unsigned, VarDecl *>; 90 using LoopControlVariablesMapTy = 91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>; 92 /// Struct that associates a component with the clause kind where they are 93 /// found. 94 struct MappedExprComponentTy { 95 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 96 OpenMPClauseKind Kind = OMPC_unknown; 97 }; 98 using MappedExprComponentsTy = 99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>; 100 using CriticalsWithHintsTy = 101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>; 102 struct ReductionData { 103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>; 104 SourceRange ReductionRange; 105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 106 ReductionData() = default; 107 void set(BinaryOperatorKind BO, SourceRange RR) { 108 ReductionRange = RR; 109 ReductionOp = BO; 110 } 111 void set(const Expr *RefExpr, SourceRange RR) { 112 ReductionRange = RR; 113 ReductionOp = RefExpr; 114 } 115 }; 116 using DeclReductionMapTy = 117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>; 118 119 struct SharingMapTy { 120 DeclSAMapTy SharingMap; 121 DeclReductionMapTy ReductionMap; 122 AlignedMapTy AlignedMap; 123 MappedExprComponentsTy MappedExprComponents; 124 LoopControlVariablesMapTy LCVMap; 125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 126 SourceLocation DefaultAttrLoc; 127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified; 128 SourceLocation DefaultMapAttrLoc; 129 OpenMPDirectiveKind Directive = OMPD_unknown; 130 DeclarationNameInfo DirectiveName; 131 Scope *CurScope = nullptr; 132 SourceLocation ConstructLoc; 133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 134 /// get the data (loop counters etc.) about enclosing loop-based construct. 135 /// This data is required during codegen. 136 DoacrossDependMapTy DoacrossDepends; 137 /// first argument (Expr *) contains optional argument of the 138 /// 'ordered' clause, the second one is true if the regions has 'ordered' 139 /// clause, false otherwise. 140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; 141 bool NowaitRegion = false; 142 bool CancelRegion = false; 143 unsigned AssociatedLoops = 1; 144 SourceLocation InnerTeamsRegionLoc; 145 /// Reference to the taskgroup task_reduction reference expression. 146 Expr *TaskgroupReductionRef = nullptr; 147 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 148 Scope *CurScope, SourceLocation Loc) 149 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 150 ConstructLoc(Loc) {} 151 SharingMapTy() = default; 152 }; 153 154 using StackTy = SmallVector<SharingMapTy, 4>; 155 156 /// Stack of used declaration and their data-sharing attributes. 157 DeclSAMapTy Threadprivates; 158 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 159 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 160 /// true, if check for DSA must be from parent directive, false, if 161 /// from current directive. 162 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 163 Sema &SemaRef; 164 bool ForceCapturing = false; 165 CriticalsWithHintsTy Criticals; 166 167 using iterator = StackTy::const_reverse_iterator; 168 169 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const; 170 171 /// Checks if the variable is a local for OpenMP region. 172 bool isOpenMPLocal(VarDecl *D, iterator Iter) const; 173 174 bool isStackEmpty() const { 175 return Stack.empty() || 176 Stack.back().second != CurrentNonCapturingFunctionScope || 177 Stack.back().first.empty(); 178 } 179 180 /// Vector of previously declared requires directives 181 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 182 183 public: 184 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 185 186 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 187 OpenMPClauseKind getClauseParsingMode() const { 188 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 189 return ClauseKindMode; 190 } 191 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 192 193 bool isForceVarCapturing() const { return ForceCapturing; } 194 void setForceVarCapturing(bool V) { ForceCapturing = V; } 195 196 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 197 Scope *CurScope, SourceLocation Loc) { 198 if (Stack.empty() || 199 Stack.back().second != CurrentNonCapturingFunctionScope) 200 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 201 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 202 Stack.back().first.back().DefaultAttrLoc = Loc; 203 } 204 205 void pop() { 206 assert(!Stack.back().first.empty() && 207 "Data-sharing attributes stack is empty!"); 208 Stack.back().first.pop_back(); 209 } 210 211 /// Start new OpenMP region stack in new non-capturing function. 212 void pushFunction() { 213 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 214 assert(!isa<CapturingScopeInfo>(CurFnScope)); 215 CurrentNonCapturingFunctionScope = CurFnScope; 216 } 217 /// Pop region stack for non-capturing function. 218 void popFunction(const FunctionScopeInfo *OldFSI) { 219 if (!Stack.empty() && Stack.back().second == OldFSI) { 220 assert(Stack.back().first.empty()); 221 Stack.pop_back(); 222 } 223 CurrentNonCapturingFunctionScope = nullptr; 224 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 225 if (!isa<CapturingScopeInfo>(FSI)) { 226 CurrentNonCapturingFunctionScope = FSI; 227 break; 228 } 229 } 230 } 231 232 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) { 233 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint); 234 } 235 const std::pair<const OMPCriticalDirective *, llvm::APSInt> 236 getCriticalWithHint(const DeclarationNameInfo &Name) const { 237 auto I = Criticals.find(Name.getAsString()); 238 if (I != Criticals.end()) 239 return I->second; 240 return std::make_pair(nullptr, llvm::APSInt()); 241 } 242 /// If 'aligned' declaration for given variable \a D was not seen yet, 243 /// add it and return NULL; otherwise return previous occurrence's expression 244 /// for diagnostics. 245 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE); 246 247 /// Register specified variable as loop control variable. 248 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture); 249 /// Check if the specified variable is a loop control variable for 250 /// current region. 251 /// \return The index of the loop control variable in the list of associated 252 /// for-loops (from outer to inner). 253 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const; 254 /// Check if the specified variable is a loop control variable for 255 /// parent region. 256 /// \return The index of the loop control variable in the list of associated 257 /// for-loops (from outer to inner). 258 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const; 259 /// Get the loop control variable for the I-th loop (or nullptr) in 260 /// parent directive. 261 const ValueDecl *getParentLoopControlVariable(unsigned I) const; 262 263 /// Adds explicit data sharing attribute to the specified declaration. 264 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 265 DeclRefExpr *PrivateCopy = nullptr); 266 267 /// Adds additional information for the reduction items with the reduction id 268 /// represented as an operator. 269 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 270 BinaryOperatorKind BOK); 271 /// Adds additional information for the reduction items with the reduction id 272 /// represented as reduction identifier. 273 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 274 const Expr *ReductionRef); 275 /// Returns the location and reduction operation from the innermost parent 276 /// region for the given \p D. 277 const DSAVarData 278 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 279 BinaryOperatorKind &BOK, 280 Expr *&TaskgroupDescriptor) const; 281 /// Returns the location and reduction operation from the innermost parent 282 /// region for the given \p D. 283 const DSAVarData 284 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 285 const Expr *&ReductionRef, 286 Expr *&TaskgroupDescriptor) const; 287 /// Return reduction reference expression for the current taskgroup. 288 Expr *getTaskgroupReductionRef() const { 289 assert(Stack.back().first.back().Directive == OMPD_taskgroup && 290 "taskgroup reference expression requested for non taskgroup " 291 "directive."); 292 return Stack.back().first.back().TaskgroupReductionRef; 293 } 294 /// Checks if the given \p VD declaration is actually a taskgroup reduction 295 /// descriptor variable at the \p Level of OpenMP regions. 296 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const { 297 return Stack.back().first[Level].TaskgroupReductionRef && 298 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef) 299 ->getDecl() == VD; 300 } 301 302 /// Returns data sharing attributes from top of the stack for the 303 /// specified declaration. 304 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 305 /// Returns data-sharing attributes for the specified declaration. 306 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const; 307 /// Checks if the specified variables has data-sharing attributes which 308 /// match specified \a CPred predicate in any directive which matches \a DPred 309 /// predicate. 310 const DSAVarData 311 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 312 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 313 bool FromParent) const; 314 /// Checks if the specified variables has data-sharing attributes which 315 /// match specified \a CPred predicate in any innermost directive which 316 /// matches \a DPred predicate. 317 const DSAVarData 318 hasInnermostDSA(ValueDecl *D, 319 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 320 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 321 bool FromParent) const; 322 /// Checks if the specified variables has explicit data-sharing 323 /// attributes which match specified \a CPred predicate at the specified 324 /// OpenMP region. 325 bool hasExplicitDSA(const ValueDecl *D, 326 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 327 unsigned Level, bool NotLastprivate = false) const; 328 329 /// Returns true if the directive at level \Level matches in the 330 /// specified \a DPred predicate. 331 bool hasExplicitDirective( 332 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 333 unsigned Level) const; 334 335 /// Finds a directive which matches specified \a DPred predicate. 336 bool hasDirective( 337 const llvm::function_ref<bool( 338 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> 339 DPred, 340 bool FromParent) const; 341 342 /// Returns currently analyzed directive. 343 OpenMPDirectiveKind getCurrentDirective() const { 344 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive; 345 } 346 /// Returns directive kind at specified level. 347 OpenMPDirectiveKind getDirective(unsigned Level) const { 348 assert(!isStackEmpty() && "No directive at specified level."); 349 return Stack.back().first[Level].Directive; 350 } 351 /// Returns parent directive. 352 OpenMPDirectiveKind getParentDirective() const { 353 if (isStackEmpty() || Stack.back().first.size() == 1) 354 return OMPD_unknown; 355 return std::next(Stack.back().first.rbegin())->Directive; 356 } 357 358 /// Add requires decl to internal vector 359 void addRequiresDecl(OMPRequiresDecl *RD) { 360 RequiresDecls.push_back(RD); 361 } 362 363 /// Checks for a duplicate clause amongst previously declared requires 364 /// directives 365 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 366 bool IsDuplicate = false; 367 for (OMPClause *CNew : ClauseList) { 368 for (const OMPRequiresDecl *D : RequiresDecls) { 369 for (const OMPClause *CPrev : D->clauselists()) { 370 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 371 SemaRef.Diag(CNew->getBeginLoc(), 372 diag::err_omp_requires_clause_redeclaration) 373 << getOpenMPClauseName(CNew->getClauseKind()); 374 SemaRef.Diag(CPrev->getBeginLoc(), 375 diag::note_omp_requires_previous_clause) 376 << getOpenMPClauseName(CPrev->getClauseKind()); 377 IsDuplicate = true; 378 } 379 } 380 } 381 } 382 return IsDuplicate; 383 } 384 385 /// Set default data sharing attribute to none. 386 void setDefaultDSANone(SourceLocation Loc) { 387 assert(!isStackEmpty()); 388 Stack.back().first.back().DefaultAttr = DSA_none; 389 Stack.back().first.back().DefaultAttrLoc = Loc; 390 } 391 /// Set default data sharing attribute to shared. 392 void setDefaultDSAShared(SourceLocation Loc) { 393 assert(!isStackEmpty()); 394 Stack.back().first.back().DefaultAttr = DSA_shared; 395 Stack.back().first.back().DefaultAttrLoc = Loc; 396 } 397 /// Set default data mapping attribute to 'tofrom:scalar'. 398 void setDefaultDMAToFromScalar(SourceLocation Loc) { 399 assert(!isStackEmpty()); 400 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar; 401 Stack.back().first.back().DefaultMapAttrLoc = Loc; 402 } 403 404 DefaultDataSharingAttributes getDefaultDSA() const { 405 return isStackEmpty() ? DSA_unspecified 406 : Stack.back().first.back().DefaultAttr; 407 } 408 SourceLocation getDefaultDSALocation() const { 409 return isStackEmpty() ? SourceLocation() 410 : Stack.back().first.back().DefaultAttrLoc; 411 } 412 DefaultMapAttributes getDefaultDMA() const { 413 return isStackEmpty() ? DMA_unspecified 414 : Stack.back().first.back().DefaultMapAttr; 415 } 416 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const { 417 return Stack.back().first[Level].DefaultMapAttr; 418 } 419 SourceLocation getDefaultDMALocation() const { 420 return isStackEmpty() ? SourceLocation() 421 : Stack.back().first.back().DefaultMapAttrLoc; 422 } 423 424 /// Checks if the specified variable is a threadprivate. 425 bool isThreadPrivate(VarDecl *D) { 426 const DSAVarData DVar = getTopDSA(D, false); 427 return isOpenMPThreadPrivate(DVar.CKind); 428 } 429 430 /// Marks current region as ordered (it has an 'ordered' clause). 431 void setOrderedRegion(bool IsOrdered, const Expr *Param, 432 OMPOrderedClause *Clause) { 433 assert(!isStackEmpty()); 434 if (IsOrdered) 435 Stack.back().first.back().OrderedRegion.emplace(Param, Clause); 436 else 437 Stack.back().first.back().OrderedRegion.reset(); 438 } 439 /// Returns true, if region is ordered (has associated 'ordered' clause), 440 /// false - otherwise. 441 bool isOrderedRegion() const { 442 if (isStackEmpty()) 443 return false; 444 return Stack.back().first.rbegin()->OrderedRegion.hasValue(); 445 } 446 /// Returns optional parameter for the ordered region. 447 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 448 if (isStackEmpty() || 449 !Stack.back().first.rbegin()->OrderedRegion.hasValue()) 450 return std::make_pair(nullptr, nullptr); 451 return Stack.back().first.rbegin()->OrderedRegion.getValue(); 452 } 453 /// Returns true, if parent region is ordered (has associated 454 /// 'ordered' clause), false - otherwise. 455 bool isParentOrderedRegion() const { 456 if (isStackEmpty() || Stack.back().first.size() == 1) 457 return false; 458 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue(); 459 } 460 /// Returns optional parameter for the ordered region. 461 std::pair<const Expr *, OMPOrderedClause *> 462 getParentOrderedRegionParam() const { 463 if (isStackEmpty() || Stack.back().first.size() == 1 || 464 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue()) 465 return std::make_pair(nullptr, nullptr); 466 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue(); 467 } 468 /// Marks current region as nowait (it has a 'nowait' clause). 469 void setNowaitRegion(bool IsNowait = true) { 470 assert(!isStackEmpty()); 471 Stack.back().first.back().NowaitRegion = IsNowait; 472 } 473 /// Returns true, if parent region is nowait (has associated 474 /// 'nowait' clause), false - otherwise. 475 bool isParentNowaitRegion() const { 476 if (isStackEmpty() || Stack.back().first.size() == 1) 477 return false; 478 return std::next(Stack.back().first.rbegin())->NowaitRegion; 479 } 480 /// Marks parent region as cancel region. 481 void setParentCancelRegion(bool Cancel = true) { 482 if (!isStackEmpty() && Stack.back().first.size() > 1) { 483 auto &StackElemRef = *std::next(Stack.back().first.rbegin()); 484 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel; 485 } 486 } 487 /// Return true if current region has inner cancel construct. 488 bool isCancelRegion() const { 489 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion; 490 } 491 492 /// Set collapse value for the region. 493 void setAssociatedLoops(unsigned Val) { 494 assert(!isStackEmpty()); 495 Stack.back().first.back().AssociatedLoops = Val; 496 } 497 /// Return collapse value for region. 498 unsigned getAssociatedLoops() const { 499 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops; 500 } 501 502 /// Marks current target region as one with closely nested teams 503 /// region. 504 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 505 if (!isStackEmpty() && Stack.back().first.size() > 1) { 506 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc = 507 TeamsRegionLoc; 508 } 509 } 510 /// Returns true, if current region has closely nested teams region. 511 bool hasInnerTeamsRegion() const { 512 return getInnerTeamsRegionLoc().isValid(); 513 } 514 /// Returns location of the nested teams region (if any). 515 SourceLocation getInnerTeamsRegionLoc() const { 516 return isStackEmpty() ? SourceLocation() 517 : Stack.back().first.back().InnerTeamsRegionLoc; 518 } 519 520 Scope *getCurScope() const { 521 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 522 } 523 SourceLocation getConstructLoc() const { 524 return isStackEmpty() ? SourceLocation() 525 : Stack.back().first.back().ConstructLoc; 526 } 527 528 /// Do the check specified in \a Check to all component lists and return true 529 /// if any issue is found. 530 bool checkMappableExprComponentListsForDecl( 531 const ValueDecl *VD, bool CurrentRegionOnly, 532 const llvm::function_ref< 533 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 534 OpenMPClauseKind)> 535 Check) const { 536 if (isStackEmpty()) 537 return false; 538 auto SI = Stack.back().first.rbegin(); 539 auto SE = Stack.back().first.rend(); 540 541 if (SI == SE) 542 return false; 543 544 if (CurrentRegionOnly) 545 SE = std::next(SI); 546 else 547 std::advance(SI, 1); 548 549 for (; SI != SE; ++SI) { 550 auto MI = SI->MappedExprComponents.find(VD); 551 if (MI != SI->MappedExprComponents.end()) 552 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 553 MI->second.Components) 554 if (Check(L, MI->second.Kind)) 555 return true; 556 } 557 return false; 558 } 559 560 /// Do the check specified in \a Check to all component lists at a given level 561 /// and return true if any issue is found. 562 bool checkMappableExprComponentListsForDeclAtLevel( 563 const ValueDecl *VD, unsigned Level, 564 const llvm::function_ref< 565 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 566 OpenMPClauseKind)> 567 Check) const { 568 if (isStackEmpty()) 569 return false; 570 571 auto StartI = Stack.back().first.begin(); 572 auto EndI = Stack.back().first.end(); 573 if (std::distance(StartI, EndI) <= (int)Level) 574 return false; 575 std::advance(StartI, Level); 576 577 auto MI = StartI->MappedExprComponents.find(VD); 578 if (MI != StartI->MappedExprComponents.end()) 579 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 580 MI->second.Components) 581 if (Check(L, MI->second.Kind)) 582 return true; 583 return false; 584 } 585 586 /// Create a new mappable expression component list associated with a given 587 /// declaration and initialize it with the provided list of components. 588 void addMappableExpressionComponents( 589 const ValueDecl *VD, 590 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 591 OpenMPClauseKind WhereFoundClauseKind) { 592 assert(!isStackEmpty() && 593 "Not expecting to retrieve components from a empty stack!"); 594 MappedExprComponentTy &MEC = 595 Stack.back().first.back().MappedExprComponents[VD]; 596 // Create new entry and append the new components there. 597 MEC.Components.resize(MEC.Components.size() + 1); 598 MEC.Components.back().append(Components.begin(), Components.end()); 599 MEC.Kind = WhereFoundClauseKind; 600 } 601 602 unsigned getNestingLevel() const { 603 assert(!isStackEmpty()); 604 return Stack.back().first.size() - 1; 605 } 606 void addDoacrossDependClause(OMPDependClause *C, 607 const OperatorOffsetTy &OpsOffs) { 608 assert(!isStackEmpty() && Stack.back().first.size() > 1); 609 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin()); 610 assert(isOpenMPWorksharingDirective(StackElem.Directive)); 611 StackElem.DoacrossDepends.try_emplace(C, OpsOffs); 612 } 613 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 614 getDoacrossDependClauses() const { 615 assert(!isStackEmpty()); 616 const SharingMapTy &StackElem = Stack.back().first.back(); 617 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 618 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 619 return llvm::make_range(Ref.begin(), Ref.end()); 620 } 621 return llvm::make_range(StackElem.DoacrossDepends.end(), 622 StackElem.DoacrossDepends.end()); 623 } 624 }; 625 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 626 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || 627 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 628 } 629 630 } // namespace 631 632 static const Expr *getExprAsWritten(const Expr *E) { 633 if (const auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 634 E = ExprTemp->getSubExpr(); 635 636 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 637 E = MTE->GetTemporaryExpr(); 638 639 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 640 E = Binder->getSubExpr(); 641 642 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 643 E = ICE->getSubExprAsWritten(); 644 return E->IgnoreParens(); 645 } 646 647 static Expr *getExprAsWritten(Expr *E) { 648 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 649 } 650 651 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 652 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 653 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 654 D = ME->getMemberDecl(); 655 const auto *VD = dyn_cast<VarDecl>(D); 656 const auto *FD = dyn_cast<FieldDecl>(D); 657 if (VD != nullptr) { 658 VD = VD->getCanonicalDecl(); 659 D = VD; 660 } else { 661 assert(FD); 662 FD = FD->getCanonicalDecl(); 663 D = FD; 664 } 665 return D; 666 } 667 668 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 669 return const_cast<ValueDecl *>( 670 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 671 } 672 673 DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter, 674 ValueDecl *D) const { 675 D = getCanonicalDecl(D); 676 auto *VD = dyn_cast<VarDecl>(D); 677 const auto *FD = dyn_cast<FieldDecl>(D); 678 DSAVarData DVar; 679 if (isStackEmpty() || Iter == Stack.back().first.rend()) { 680 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 681 // in a region but not in construct] 682 // File-scope or namespace-scope variables referenced in called routines 683 // in the region are shared unless they appear in a threadprivate 684 // directive. 685 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 686 DVar.CKind = OMPC_shared; 687 688 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 689 // in a region but not in construct] 690 // Variables with static storage duration that are declared in called 691 // routines in the region are shared. 692 if (VD && VD->hasGlobalStorage()) 693 DVar.CKind = OMPC_shared; 694 695 // Non-static data members are shared by default. 696 if (FD) 697 DVar.CKind = OMPC_shared; 698 699 return DVar; 700 } 701 702 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 703 // in a Construct, C/C++, predetermined, p.1] 704 // Variables with automatic storage duration that are declared in a scope 705 // inside the construct are private. 706 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 707 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 708 DVar.CKind = OMPC_private; 709 return DVar; 710 } 711 712 DVar.DKind = Iter->Directive; 713 // Explicitly specified attributes and local variables with predetermined 714 // attributes. 715 if (Iter->SharingMap.count(D)) { 716 const DSAInfo &Data = Iter->SharingMap.lookup(D); 717 DVar.RefExpr = Data.RefExpr.getPointer(); 718 DVar.PrivateCopy = Data.PrivateCopy; 719 DVar.CKind = Data.Attributes; 720 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 721 return DVar; 722 } 723 724 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 725 // in a Construct, C/C++, implicitly determined, p.1] 726 // In a parallel or task construct, the data-sharing attributes of these 727 // variables are determined by the default clause, if present. 728 switch (Iter->DefaultAttr) { 729 case DSA_shared: 730 DVar.CKind = OMPC_shared; 731 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 732 return DVar; 733 case DSA_none: 734 return DVar; 735 case DSA_unspecified: 736 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 737 // in a Construct, implicitly determined, p.2] 738 // In a parallel construct, if no default clause is present, these 739 // variables are shared. 740 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 741 if (isOpenMPParallelDirective(DVar.DKind) || 742 isOpenMPTeamsDirective(DVar.DKind)) { 743 DVar.CKind = OMPC_shared; 744 return DVar; 745 } 746 747 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 748 // in a Construct, implicitly determined, p.4] 749 // In a task construct, if no default clause is present, a variable that in 750 // the enclosing context is determined to be shared by all implicit tasks 751 // bound to the current team is shared. 752 if (isOpenMPTaskingDirective(DVar.DKind)) { 753 DSAVarData DVarTemp; 754 iterator I = Iter, E = Stack.back().first.rend(); 755 do { 756 ++I; 757 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 758 // Referenced in a Construct, implicitly determined, p.6] 759 // In a task construct, if no default clause is present, a variable 760 // whose data-sharing attribute is not determined by the rules above is 761 // firstprivate. 762 DVarTemp = getDSA(I, D); 763 if (DVarTemp.CKind != OMPC_shared) { 764 DVar.RefExpr = nullptr; 765 DVar.CKind = OMPC_firstprivate; 766 return DVar; 767 } 768 } while (I != E && !isParallelOrTaskRegion(I->Directive)); 769 DVar.CKind = 770 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 771 return DVar; 772 } 773 } 774 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 775 // in a Construct, implicitly determined, p.3] 776 // For constructs other than task, if no default clause is present, these 777 // variables inherit their data-sharing attributes from the enclosing 778 // context. 779 return getDSA(++Iter, D); 780 } 781 782 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 783 const Expr *NewDE) { 784 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 785 D = getCanonicalDecl(D); 786 SharingMapTy &StackElem = Stack.back().first.back(); 787 auto It = StackElem.AlignedMap.find(D); 788 if (It == StackElem.AlignedMap.end()) { 789 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 790 StackElem.AlignedMap[D] = NewDE; 791 return nullptr; 792 } 793 assert(It->second && "Unexpected nullptr expr in the aligned map"); 794 return It->second; 795 } 796 797 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 798 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 799 D = getCanonicalDecl(D); 800 SharingMapTy &StackElem = Stack.back().first.back(); 801 StackElem.LCVMap.try_emplace( 802 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 803 } 804 805 const DSAStackTy::LCDeclInfo 806 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 807 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 808 D = getCanonicalDecl(D); 809 const SharingMapTy &StackElem = Stack.back().first.back(); 810 auto It = StackElem.LCVMap.find(D); 811 if (It != StackElem.LCVMap.end()) 812 return It->second; 813 return {0, nullptr}; 814 } 815 816 const DSAStackTy::LCDeclInfo 817 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 818 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 819 "Data-sharing attributes stack is empty"); 820 D = getCanonicalDecl(D); 821 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin()); 822 auto It = StackElem.LCVMap.find(D); 823 if (It != StackElem.LCVMap.end()) 824 return It->second; 825 return {0, nullptr}; 826 } 827 828 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 829 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 830 "Data-sharing attributes stack is empty"); 831 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin()); 832 if (StackElem.LCVMap.size() < I) 833 return nullptr; 834 for (const auto &Pair : StackElem.LCVMap) 835 if (Pair.second.first == I) 836 return Pair.first; 837 return nullptr; 838 } 839 840 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 841 DeclRefExpr *PrivateCopy) { 842 D = getCanonicalDecl(D); 843 if (A == OMPC_threadprivate) { 844 DSAInfo &Data = Threadprivates[D]; 845 Data.Attributes = A; 846 Data.RefExpr.setPointer(E); 847 Data.PrivateCopy = nullptr; 848 } else { 849 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 850 DSAInfo &Data = Stack.back().first.back().SharingMap[D]; 851 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 852 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 853 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 854 (isLoopControlVariable(D).first && A == OMPC_private)); 855 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 856 Data.RefExpr.setInt(/*IntVal=*/true); 857 return; 858 } 859 const bool IsLastprivate = 860 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 861 Data.Attributes = A; 862 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 863 Data.PrivateCopy = PrivateCopy; 864 if (PrivateCopy) { 865 DSAInfo &Data = 866 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()]; 867 Data.Attributes = A; 868 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 869 Data.PrivateCopy = nullptr; 870 } 871 } 872 } 873 874 /// Build a variable declaration for OpenMP loop iteration variable. 875 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 876 StringRef Name, const AttrVec *Attrs = nullptr, 877 DeclRefExpr *OrigRef = nullptr) { 878 DeclContext *DC = SemaRef.CurContext; 879 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 880 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 881 auto *Decl = 882 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 883 if (Attrs) { 884 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 885 I != E; ++I) 886 Decl->addAttr(*I); 887 } 888 Decl->setImplicit(); 889 if (OrigRef) { 890 Decl->addAttr( 891 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 892 } 893 return Decl; 894 } 895 896 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 897 SourceLocation Loc, 898 bool RefersToCapture = false) { 899 D->setReferenced(); 900 D->markUsed(S.Context); 901 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 902 SourceLocation(), D, RefersToCapture, Loc, Ty, 903 VK_LValue); 904 } 905 906 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 907 BinaryOperatorKind BOK) { 908 D = getCanonicalDecl(D); 909 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 910 assert( 911 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 912 "Additional reduction info may be specified only for reduction items."); 913 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D]; 914 assert(ReductionData.ReductionRange.isInvalid() && 915 Stack.back().first.back().Directive == OMPD_taskgroup && 916 "Additional reduction info may be specified only once for reduction " 917 "items."); 918 ReductionData.set(BOK, SR); 919 Expr *&TaskgroupReductionRef = 920 Stack.back().first.back().TaskgroupReductionRef; 921 if (!TaskgroupReductionRef) { 922 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 923 SemaRef.Context.VoidPtrTy, ".task_red."); 924 TaskgroupReductionRef = 925 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 926 } 927 } 928 929 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 930 const Expr *ReductionRef) { 931 D = getCanonicalDecl(D); 932 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 933 assert( 934 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 935 "Additional reduction info may be specified only for reduction items."); 936 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D]; 937 assert(ReductionData.ReductionRange.isInvalid() && 938 Stack.back().first.back().Directive == OMPD_taskgroup && 939 "Additional reduction info may be specified only once for reduction " 940 "items."); 941 ReductionData.set(ReductionRef, SR); 942 Expr *&TaskgroupReductionRef = 943 Stack.back().first.back().TaskgroupReductionRef; 944 if (!TaskgroupReductionRef) { 945 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 946 SemaRef.Context.VoidPtrTy, ".task_red."); 947 TaskgroupReductionRef = 948 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 949 } 950 } 951 952 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 953 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 954 Expr *&TaskgroupDescriptor) const { 955 D = getCanonicalDecl(D); 956 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 957 if (Stack.back().first.empty()) 958 return DSAVarData(); 959 for (iterator I = std::next(Stack.back().first.rbegin(), 1), 960 E = Stack.back().first.rend(); 961 I != E; std::advance(I, 1)) { 962 const DSAInfo &Data = I->SharingMap.lookup(D); 963 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 964 continue; 965 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 966 if (!ReductionData.ReductionOp || 967 ReductionData.ReductionOp.is<const Expr *>()) 968 return DSAVarData(); 969 SR = ReductionData.ReductionRange; 970 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 971 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 972 "expression for the descriptor is not " 973 "set."); 974 TaskgroupDescriptor = I->TaskgroupReductionRef; 975 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 976 Data.PrivateCopy, I->DefaultAttrLoc); 977 } 978 return DSAVarData(); 979 } 980 981 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 982 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 983 Expr *&TaskgroupDescriptor) const { 984 D = getCanonicalDecl(D); 985 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 986 if (Stack.back().first.empty()) 987 return DSAVarData(); 988 for (iterator I = std::next(Stack.back().first.rbegin(), 1), 989 E = Stack.back().first.rend(); 990 I != E; std::advance(I, 1)) { 991 const DSAInfo &Data = I->SharingMap.lookup(D); 992 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 993 continue; 994 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 995 if (!ReductionData.ReductionOp || 996 !ReductionData.ReductionOp.is<const Expr *>()) 997 return DSAVarData(); 998 SR = ReductionData.ReductionRange; 999 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1000 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1001 "expression for the descriptor is not " 1002 "set."); 1003 TaskgroupDescriptor = I->TaskgroupReductionRef; 1004 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 1005 Data.PrivateCopy, I->DefaultAttrLoc); 1006 } 1007 return DSAVarData(); 1008 } 1009 1010 bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const { 1011 D = D->getCanonicalDecl(); 1012 if (!isStackEmpty()) { 1013 iterator I = Iter, E = Stack.back().first.rend(); 1014 Scope *TopScope = nullptr; 1015 while (I != E && !isParallelOrTaskRegion(I->Directive) && 1016 !isOpenMPTargetExecutionDirective(I->Directive)) 1017 ++I; 1018 if (I == E) 1019 return false; 1020 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 1021 Scope *CurScope = getCurScope(); 1022 while (CurScope != TopScope && !CurScope->isDeclScope(D)) 1023 CurScope = CurScope->getParent(); 1024 return CurScope != TopScope; 1025 } 1026 return false; 1027 } 1028 1029 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1030 bool FromParent) { 1031 D = getCanonicalDecl(D); 1032 DSAVarData DVar; 1033 1034 auto *VD = dyn_cast<VarDecl>(D); 1035 auto TI = Threadprivates.find(D); 1036 if (TI != Threadprivates.end()) { 1037 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1038 DVar.CKind = OMPC_threadprivate; 1039 return DVar; 1040 } 1041 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1042 DVar.RefExpr = buildDeclRefExpr( 1043 SemaRef, VD, D->getType().getNonReferenceType(), 1044 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1045 DVar.CKind = OMPC_threadprivate; 1046 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1047 return DVar; 1048 } 1049 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1050 // in a Construct, C/C++, predetermined, p.1] 1051 // Variables appearing in threadprivate directives are threadprivate. 1052 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1053 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1054 SemaRef.getLangOpts().OpenMPUseTLS && 1055 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1056 (VD && VD->getStorageClass() == SC_Register && 1057 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1058 DVar.RefExpr = buildDeclRefExpr( 1059 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1060 DVar.CKind = OMPC_threadprivate; 1061 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1062 return DVar; 1063 } 1064 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1065 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1066 !isLoopControlVariable(D).first) { 1067 iterator IterTarget = 1068 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(), 1069 [](const SharingMapTy &Data) { 1070 return isOpenMPTargetExecutionDirective(Data.Directive); 1071 }); 1072 if (IterTarget != Stack.back().first.rend()) { 1073 iterator ParentIterTarget = std::next(IterTarget, 1); 1074 for (iterator Iter = Stack.back().first.rbegin(); 1075 Iter != ParentIterTarget; std::advance(Iter, 1)) { 1076 if (isOpenMPLocal(VD, Iter)) { 1077 DVar.RefExpr = 1078 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1079 D->getLocation()); 1080 DVar.CKind = OMPC_threadprivate; 1081 return DVar; 1082 } 1083 } 1084 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) { 1085 auto DSAIter = IterTarget->SharingMap.find(D); 1086 if (DSAIter != IterTarget->SharingMap.end() && 1087 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1088 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1089 DVar.CKind = OMPC_threadprivate; 1090 return DVar; 1091 } 1092 iterator End = Stack.back().first.rend(); 1093 if (!SemaRef.isOpenMPCapturedByRef( 1094 D, std::distance(ParentIterTarget, End))) { 1095 DVar.RefExpr = 1096 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1097 IterTarget->ConstructLoc); 1098 DVar.CKind = OMPC_threadprivate; 1099 return DVar; 1100 } 1101 } 1102 } 1103 } 1104 1105 if (isStackEmpty()) 1106 // Not in OpenMP execution region and top scope was already checked. 1107 return DVar; 1108 1109 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1110 // in a Construct, C/C++, predetermined, p.4] 1111 // Static data members are shared. 1112 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1113 // in a Construct, C/C++, predetermined, p.7] 1114 // Variables with static storage duration that are declared in a scope 1115 // inside the construct are shared. 1116 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1117 if (VD && VD->isStaticDataMember()) { 1118 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 1119 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1120 return DVar; 1121 1122 DVar.CKind = OMPC_shared; 1123 return DVar; 1124 } 1125 1126 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 1127 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 1128 Type = SemaRef.getASTContext().getBaseElementType(Type); 1129 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1130 // in a Construct, C/C++, predetermined, p.6] 1131 // Variables with const qualified type having no mutable member are 1132 // shared. 1133 const CXXRecordDecl *RD = 1134 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 1135 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1136 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1137 RD = CTD->getTemplatedDecl(); 1138 if (IsConstant && 1139 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && 1140 RD->hasMutableFields())) { 1141 // Variables with const-qualified type having no mutable member may be 1142 // listed in a firstprivate clause, even if they are static data members. 1143 DSAVarData DVarTemp = 1144 hasDSA(D, [](OpenMPClauseKind C) { return C == OMPC_firstprivate; }, 1145 MatchesAlways, FromParent); 1146 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 1147 return DVarTemp; 1148 1149 DVar.CKind = OMPC_shared; 1150 return DVar; 1151 } 1152 1153 // Explicitly specified attributes and local variables with predetermined 1154 // attributes. 1155 iterator I = Stack.back().first.rbegin(); 1156 iterator EndI = Stack.back().first.rend(); 1157 if (FromParent && I != EndI) 1158 std::advance(I, 1); 1159 auto It = I->SharingMap.find(D); 1160 if (It != I->SharingMap.end()) { 1161 const DSAInfo &Data = It->getSecond(); 1162 DVar.RefExpr = Data.RefExpr.getPointer(); 1163 DVar.PrivateCopy = Data.PrivateCopy; 1164 DVar.CKind = Data.Attributes; 1165 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1166 DVar.DKind = I->Directive; 1167 } 1168 1169 return DVar; 1170 } 1171 1172 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1173 bool FromParent) const { 1174 if (isStackEmpty()) { 1175 iterator I; 1176 return getDSA(I, D); 1177 } 1178 D = getCanonicalDecl(D); 1179 iterator StartI = Stack.back().first.rbegin(); 1180 iterator EndI = Stack.back().first.rend(); 1181 if (FromParent && StartI != EndI) 1182 std::advance(StartI, 1); 1183 return getDSA(StartI, D); 1184 } 1185 1186 const DSAStackTy::DSAVarData 1187 DSAStackTy::hasDSA(ValueDecl *D, 1188 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1189 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1190 bool FromParent) const { 1191 if (isStackEmpty()) 1192 return {}; 1193 D = getCanonicalDecl(D); 1194 iterator I = Stack.back().first.rbegin(); 1195 iterator EndI = Stack.back().first.rend(); 1196 if (FromParent && I != EndI) 1197 std::advance(I, 1); 1198 for (; I != EndI; std::advance(I, 1)) { 1199 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 1200 continue; 1201 iterator NewI = I; 1202 DSAVarData DVar = getDSA(NewI, D); 1203 if (I == NewI && CPred(DVar.CKind)) 1204 return DVar; 1205 } 1206 return {}; 1207 } 1208 1209 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1210 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1211 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1212 bool FromParent) const { 1213 if (isStackEmpty()) 1214 return {}; 1215 D = getCanonicalDecl(D); 1216 iterator StartI = Stack.back().first.rbegin(); 1217 iterator EndI = Stack.back().first.rend(); 1218 if (FromParent && StartI != EndI) 1219 std::advance(StartI, 1); 1220 if (StartI == EndI || !DPred(StartI->Directive)) 1221 return {}; 1222 iterator NewI = StartI; 1223 DSAVarData DVar = getDSA(NewI, D); 1224 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); 1225 } 1226 1227 bool DSAStackTy::hasExplicitDSA( 1228 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1229 unsigned Level, bool NotLastprivate) const { 1230 if (isStackEmpty()) 1231 return false; 1232 D = getCanonicalDecl(D); 1233 auto StartI = Stack.back().first.begin(); 1234 auto EndI = Stack.back().first.end(); 1235 if (std::distance(StartI, EndI) <= (int)Level) 1236 return false; 1237 std::advance(StartI, Level); 1238 auto I = StartI->SharingMap.find(D); 1239 return (I != StartI->SharingMap.end()) && 1240 I->getSecond().RefExpr.getPointer() && 1241 CPred(I->getSecond().Attributes) && 1242 (!NotLastprivate || !I->getSecond().RefExpr.getInt()); 1243 } 1244 1245 bool DSAStackTy::hasExplicitDirective( 1246 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1247 unsigned Level) const { 1248 if (isStackEmpty()) 1249 return false; 1250 auto StartI = Stack.back().first.begin(); 1251 auto EndI = Stack.back().first.end(); 1252 if (std::distance(StartI, EndI) <= (int)Level) 1253 return false; 1254 std::advance(StartI, Level); 1255 return DPred(StartI->Directive); 1256 } 1257 1258 bool DSAStackTy::hasDirective( 1259 const llvm::function_ref<bool(OpenMPDirectiveKind, 1260 const DeclarationNameInfo &, SourceLocation)> 1261 DPred, 1262 bool FromParent) const { 1263 // We look only in the enclosing region. 1264 if (isStackEmpty()) 1265 return false; 1266 auto StartI = std::next(Stack.back().first.rbegin()); 1267 auto EndI = Stack.back().first.rend(); 1268 if (FromParent && StartI != EndI) 1269 StartI = std::next(StartI); 1270 for (auto I = StartI, EE = EndI; I != EE; ++I) { 1271 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1272 return true; 1273 } 1274 return false; 1275 } 1276 1277 void Sema::InitDataSharingAttributesStack() { 1278 VarDataSharingAttributesStack = new DSAStackTy(*this); 1279 } 1280 1281 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1282 1283 void Sema::pushOpenMPFunctionRegion() { 1284 DSAStack->pushFunction(); 1285 } 1286 1287 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1288 DSAStack->popFunction(OldFSI); 1289 } 1290 1291 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const { 1292 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1293 1294 ASTContext &Ctx = getASTContext(); 1295 bool IsByRef = true; 1296 1297 // Find the directive that is associated with the provided scope. 1298 D = cast<ValueDecl>(D->getCanonicalDecl()); 1299 QualType Ty = D->getType(); 1300 1301 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1302 // This table summarizes how a given variable should be passed to the device 1303 // given its type and the clauses where it appears. This table is based on 1304 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1305 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1306 // 1307 // ========================================================================= 1308 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1309 // | |(tofrom:scalar)| | pvt | | | | 1310 // ========================================================================= 1311 // | scl | | | | - | | bycopy| 1312 // | scl | | - | x | - | - | bycopy| 1313 // | scl | | x | - | - | - | null | 1314 // | scl | x | | | - | | byref | 1315 // | scl | x | - | x | - | - | bycopy| 1316 // | scl | x | x | - | - | - | null | 1317 // | scl | | - | - | - | x | byref | 1318 // | scl | x | - | - | - | x | byref | 1319 // 1320 // | agg | n.a. | | | - | | byref | 1321 // | agg | n.a. | - | x | - | - | byref | 1322 // | agg | n.a. | x | - | - | - | null | 1323 // | agg | n.a. | - | - | - | x | byref | 1324 // | agg | n.a. | - | - | - | x[] | byref | 1325 // 1326 // | ptr | n.a. | | | - | | bycopy| 1327 // | ptr | n.a. | - | x | - | - | bycopy| 1328 // | ptr | n.a. | x | - | - | - | null | 1329 // | ptr | n.a. | - | - | - | x | byref | 1330 // | ptr | n.a. | - | - | - | x[] | bycopy| 1331 // | ptr | n.a. | - | - | x | | bycopy| 1332 // | ptr | n.a. | - | - | x | x | bycopy| 1333 // | ptr | n.a. | - | - | x | x[] | bycopy| 1334 // ========================================================================= 1335 // Legend: 1336 // scl - scalar 1337 // ptr - pointer 1338 // agg - aggregate 1339 // x - applies 1340 // - - invalid in this combination 1341 // [] - mapped with an array section 1342 // byref - should be mapped by reference 1343 // byval - should be mapped by value 1344 // null - initialize a local variable to null on the device 1345 // 1346 // Observations: 1347 // - All scalar declarations that show up in a map clause have to be passed 1348 // by reference, because they may have been mapped in the enclosing data 1349 // environment. 1350 // - If the scalar value does not fit the size of uintptr, it has to be 1351 // passed by reference, regardless the result in the table above. 1352 // - For pointers mapped by value that have either an implicit map or an 1353 // array section, the runtime library may pass the NULL value to the 1354 // device instead of the value passed to it by the compiler. 1355 1356 if (Ty->isReferenceType()) 1357 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1358 1359 // Locate map clauses and see if the variable being captured is referred to 1360 // in any of those clauses. Here we only care about variables, not fields, 1361 // because fields are part of aggregates. 1362 bool IsVariableUsedInMapClause = false; 1363 bool IsVariableAssociatedWithSection = false; 1364 1365 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1366 D, Level, 1367 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D]( 1368 OMPClauseMappableExprCommon::MappableExprComponentListRef 1369 MapExprComponents, 1370 OpenMPClauseKind WhereFoundClauseKind) { 1371 // Only the map clause information influences how a variable is 1372 // captured. E.g. is_device_ptr does not require changing the default 1373 // behavior. 1374 if (WhereFoundClauseKind != OMPC_map) 1375 return false; 1376 1377 auto EI = MapExprComponents.rbegin(); 1378 auto EE = MapExprComponents.rend(); 1379 1380 assert(EI != EE && "Invalid map expression!"); 1381 1382 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1383 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1384 1385 ++EI; 1386 if (EI == EE) 1387 return false; 1388 1389 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1390 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1391 isa<MemberExpr>(EI->getAssociatedExpression())) { 1392 IsVariableAssociatedWithSection = true; 1393 // There is nothing more we need to know about this variable. 1394 return true; 1395 } 1396 1397 // Keep looking for more map info. 1398 return false; 1399 }); 1400 1401 if (IsVariableUsedInMapClause) { 1402 // If variable is identified in a map clause it is always captured by 1403 // reference except if it is a pointer that is dereferenced somehow. 1404 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1405 } else { 1406 // By default, all the data that has a scalar type is mapped by copy 1407 // (except for reduction variables). 1408 IsByRef = 1409 !Ty->isScalarType() || 1410 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar || 1411 DSAStack->hasExplicitDSA( 1412 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level); 1413 } 1414 } 1415 1416 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1417 IsByRef = 1418 !DSAStack->hasExplicitDSA( 1419 D, 1420 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1421 Level, /*NotLastprivate=*/true) && 1422 // If the variable is artificial and must be captured by value - try to 1423 // capture by value. 1424 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 1425 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()); 1426 } 1427 1428 // When passing data by copy, we need to make sure it fits the uintptr size 1429 // and alignment, because the runtime library only deals with uintptr types. 1430 // If it does not fit the uintptr size, we need to pass the data by reference 1431 // instead. 1432 if (!IsByRef && 1433 (Ctx.getTypeSizeInChars(Ty) > 1434 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1435 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1436 IsByRef = true; 1437 } 1438 1439 return IsByRef; 1440 } 1441 1442 unsigned Sema::getOpenMPNestingLevel() const { 1443 assert(getLangOpts().OpenMP); 1444 return DSAStack->getNestingLevel(); 1445 } 1446 1447 bool Sema::isInOpenMPTargetExecutionDirective() const { 1448 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 1449 !DSAStack->isClauseParsingMode()) || 1450 DSAStack->hasDirective( 1451 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1452 SourceLocation) -> bool { 1453 return isOpenMPTargetExecutionDirective(K); 1454 }, 1455 false); 1456 } 1457 1458 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) { 1459 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1460 D = getCanonicalDecl(D); 1461 1462 // If we are attempting to capture a global variable in a directive with 1463 // 'target' we return true so that this global is also mapped to the device. 1464 // 1465 auto *VD = dyn_cast<VarDecl>(D); 1466 if (VD && !VD->hasLocalStorage()) { 1467 if (isInOpenMPDeclareTargetContext() && 1468 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 1469 // Try to mark variable as declare target if it is used in capturing 1470 // regions. 1471 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 1472 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 1473 return nullptr; 1474 } else if (isInOpenMPTargetExecutionDirective()) { 1475 // If the declaration is enclosed in a 'declare target' directive, 1476 // then it should not be captured. 1477 // 1478 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 1479 return nullptr; 1480 return VD; 1481 } 1482 } 1483 1484 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1485 (!DSAStack->isClauseParsingMode() || 1486 DSAStack->getParentDirective() != OMPD_unknown)) { 1487 auto &&Info = DSAStack->isLoopControlVariable(D); 1488 if (Info.first || 1489 (VD && VD->hasLocalStorage() && 1490 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 1491 (VD && DSAStack->isForceVarCapturing())) 1492 return VD ? VD : Info.second; 1493 DSAStackTy::DSAVarData DVarPrivate = 1494 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1495 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1496 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1497 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate, 1498 [](OpenMPDirectiveKind) { return true; }, 1499 DSAStack->isClauseParsingMode()); 1500 if (DVarPrivate.CKind != OMPC_unknown) 1501 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1502 } 1503 return nullptr; 1504 } 1505 1506 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 1507 unsigned Level) const { 1508 SmallVector<OpenMPDirectiveKind, 4> Regions; 1509 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 1510 FunctionScopesIndex -= Regions.size(); 1511 } 1512 1513 bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const { 1514 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1515 return DSAStack->hasExplicitDSA( 1516 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) || 1517 (DSAStack->isClauseParsingMode() && 1518 DSAStack->getClauseParsingMode() == OMPC_private) || 1519 // Consider taskgroup reduction descriptor variable a private to avoid 1520 // possible capture in the region. 1521 (DSAStack->hasExplicitDirective( 1522 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; }, 1523 Level) && 1524 DSAStack->isTaskgroupReductionRef(D, Level)); 1525 } 1526 1527 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 1528 unsigned Level) { 1529 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1530 D = getCanonicalDecl(D); 1531 OpenMPClauseKind OMPC = OMPC_unknown; 1532 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 1533 const unsigned NewLevel = I - 1; 1534 if (DSAStack->hasExplicitDSA(D, 1535 [&OMPC](const OpenMPClauseKind K) { 1536 if (isOpenMPPrivate(K)) { 1537 OMPC = K; 1538 return true; 1539 } 1540 return false; 1541 }, 1542 NewLevel)) 1543 break; 1544 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1545 D, NewLevel, 1546 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 1547 OpenMPClauseKind) { return true; })) { 1548 OMPC = OMPC_map; 1549 break; 1550 } 1551 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1552 NewLevel)) { 1553 OMPC = OMPC_map; 1554 if (D->getType()->isScalarType() && 1555 DSAStack->getDefaultDMAAtLevel(NewLevel) != 1556 DefaultMapAttributes::DMA_tofrom_scalar) 1557 OMPC = OMPC_firstprivate; 1558 break; 1559 } 1560 } 1561 if (OMPC != OMPC_unknown) 1562 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC)); 1563 } 1564 1565 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, 1566 unsigned Level) const { 1567 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1568 // Return true if the current level is no longer enclosed in a target region. 1569 1570 const auto *VD = dyn_cast<VarDecl>(D); 1571 return VD && !VD->hasLocalStorage() && 1572 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1573 Level); 1574 } 1575 1576 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1577 1578 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1579 const DeclarationNameInfo &DirName, 1580 Scope *CurScope, SourceLocation Loc) { 1581 DSAStack->push(DKind, DirName, CurScope, Loc); 1582 PushExpressionEvaluationContext( 1583 ExpressionEvaluationContext::PotentiallyEvaluated); 1584 } 1585 1586 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1587 DSAStack->setClauseParsingMode(K); 1588 } 1589 1590 void Sema::EndOpenMPClause() { 1591 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1592 } 1593 1594 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1595 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1596 // A variable of class type (or array thereof) that appears in a lastprivate 1597 // clause requires an accessible, unambiguous default constructor for the 1598 // class type, unless the list item is also specified in a firstprivate 1599 // clause. 1600 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1601 for (OMPClause *C : D->clauses()) { 1602 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1603 SmallVector<Expr *, 8> PrivateCopies; 1604 for (Expr *DE : Clause->varlists()) { 1605 if (DE->isValueDependent() || DE->isTypeDependent()) { 1606 PrivateCopies.push_back(nullptr); 1607 continue; 1608 } 1609 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1610 auto *VD = cast<VarDecl>(DRE->getDecl()); 1611 QualType Type = VD->getType().getNonReferenceType(); 1612 const DSAStackTy::DSAVarData DVar = 1613 DSAStack->getTopDSA(VD, /*FromParent=*/false); 1614 if (DVar.CKind == OMPC_lastprivate) { 1615 // Generate helper private variable and initialize it with the 1616 // default value. The address of the original variable is replaced 1617 // by the address of the new private variable in CodeGen. This new 1618 // variable is not added to IdResolver, so the code in the OpenMP 1619 // region uses original variable for proper diagnostics. 1620 VarDecl *VDPrivate = buildVarDecl( 1621 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1622 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 1623 ActOnUninitializedDecl(VDPrivate); 1624 if (VDPrivate->isInvalidDecl()) 1625 continue; 1626 PrivateCopies.push_back(buildDeclRefExpr( 1627 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1628 } else { 1629 // The variable is also a firstprivate, so initialization sequence 1630 // for private copy is generated already. 1631 PrivateCopies.push_back(nullptr); 1632 } 1633 } 1634 // Set initializers to private copies if no errors were found. 1635 if (PrivateCopies.size() == Clause->varlist_size()) 1636 Clause->setPrivateCopies(PrivateCopies); 1637 } 1638 } 1639 } 1640 1641 DSAStack->pop(); 1642 DiscardCleanupsInEvaluationContext(); 1643 PopExpressionEvaluationContext(); 1644 } 1645 1646 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1647 Expr *NumIterations, Sema &SemaRef, 1648 Scope *S, DSAStackTy *Stack); 1649 1650 namespace { 1651 1652 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 1653 private: 1654 Sema &SemaRef; 1655 1656 public: 1657 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1658 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1659 NamedDecl *ND = Candidate.getCorrectionDecl(); 1660 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1661 return VD->hasGlobalStorage() && 1662 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1663 SemaRef.getCurScope()); 1664 } 1665 return false; 1666 } 1667 }; 1668 1669 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 1670 private: 1671 Sema &SemaRef; 1672 1673 public: 1674 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1675 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1676 NamedDecl *ND = Candidate.getCorrectionDecl(); 1677 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) { 1678 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1679 SemaRef.getCurScope()); 1680 } 1681 return false; 1682 } 1683 }; 1684 1685 } // namespace 1686 1687 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1688 CXXScopeSpec &ScopeSpec, 1689 const DeclarationNameInfo &Id) { 1690 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1691 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1692 1693 if (Lookup.isAmbiguous()) 1694 return ExprError(); 1695 1696 VarDecl *VD; 1697 if (!Lookup.isSingleResult()) { 1698 if (TypoCorrection Corrected = CorrectTypo( 1699 Id, LookupOrdinaryName, CurScope, nullptr, 1700 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1701 diagnoseTypo(Corrected, 1702 PDiag(Lookup.empty() 1703 ? diag::err_undeclared_var_use_suggest 1704 : diag::err_omp_expected_var_arg_suggest) 1705 << Id.getName()); 1706 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1707 } else { 1708 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1709 : diag::err_omp_expected_var_arg) 1710 << Id.getName(); 1711 return ExprError(); 1712 } 1713 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1714 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1715 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1716 return ExprError(); 1717 } 1718 Lookup.suppressDiagnostics(); 1719 1720 // OpenMP [2.9.2, Syntax, C/C++] 1721 // Variables must be file-scope, namespace-scope, or static block-scope. 1722 if (!VD->hasGlobalStorage()) { 1723 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1724 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1725 bool IsDecl = 1726 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1727 Diag(VD->getLocation(), 1728 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1729 << VD; 1730 return ExprError(); 1731 } 1732 1733 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1734 NamedDecl *ND = CanonicalVD; 1735 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1736 // A threadprivate directive for file-scope variables must appear outside 1737 // any definition or declaration. 1738 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1739 !getCurLexicalContext()->isTranslationUnit()) { 1740 Diag(Id.getLoc(), diag::err_omp_var_scope) 1741 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1742 bool IsDecl = 1743 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1744 Diag(VD->getLocation(), 1745 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1746 << VD; 1747 return ExprError(); 1748 } 1749 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1750 // A threadprivate directive for static class member variables must appear 1751 // in the class definition, in the same scope in which the member 1752 // variables are declared. 1753 if (CanonicalVD->isStaticDataMember() && 1754 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1755 Diag(Id.getLoc(), diag::err_omp_var_scope) 1756 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1757 bool IsDecl = 1758 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1759 Diag(VD->getLocation(), 1760 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1761 << VD; 1762 return ExprError(); 1763 } 1764 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1765 // A threadprivate directive for namespace-scope variables must appear 1766 // outside any definition or declaration other than the namespace 1767 // definition itself. 1768 if (CanonicalVD->getDeclContext()->isNamespace() && 1769 (!getCurLexicalContext()->isFileContext() || 1770 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1771 Diag(Id.getLoc(), diag::err_omp_var_scope) 1772 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1773 bool IsDecl = 1774 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1775 Diag(VD->getLocation(), 1776 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1777 << VD; 1778 return ExprError(); 1779 } 1780 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1781 // A threadprivate directive for static block-scope variables must appear 1782 // in the scope of the variable and not in a nested scope. 1783 if (CanonicalVD->isStaticLocal() && CurScope && 1784 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1785 Diag(Id.getLoc(), diag::err_omp_var_scope) 1786 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1787 bool IsDecl = 1788 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1789 Diag(VD->getLocation(), 1790 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1791 << VD; 1792 return ExprError(); 1793 } 1794 1795 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1796 // A threadprivate directive must lexically precede all references to any 1797 // of the variables in its list. 1798 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1799 Diag(Id.getLoc(), diag::err_omp_var_used) 1800 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1801 return ExprError(); 1802 } 1803 1804 QualType ExprType = VD->getType().getNonReferenceType(); 1805 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1806 SourceLocation(), VD, 1807 /*RefersToEnclosingVariableOrCapture=*/false, 1808 Id.getLoc(), ExprType, VK_LValue); 1809 } 1810 1811 Sema::DeclGroupPtrTy 1812 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1813 ArrayRef<Expr *> VarList) { 1814 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1815 CurContext->addDecl(D); 1816 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1817 } 1818 return nullptr; 1819 } 1820 1821 namespace { 1822 class LocalVarRefChecker final 1823 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1824 Sema &SemaRef; 1825 1826 public: 1827 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1828 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1829 if (VD->hasLocalStorage()) { 1830 SemaRef.Diag(E->getBeginLoc(), 1831 diag::err_omp_local_var_in_threadprivate_init) 1832 << E->getSourceRange(); 1833 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1834 << VD << VD->getSourceRange(); 1835 return true; 1836 } 1837 } 1838 return false; 1839 } 1840 bool VisitStmt(const Stmt *S) { 1841 for (const Stmt *Child : S->children()) { 1842 if (Child && Visit(Child)) 1843 return true; 1844 } 1845 return false; 1846 } 1847 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1848 }; 1849 } // namespace 1850 1851 OMPThreadPrivateDecl * 1852 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1853 SmallVector<Expr *, 8> Vars; 1854 for (Expr *RefExpr : VarList) { 1855 auto *DE = cast<DeclRefExpr>(RefExpr); 1856 auto *VD = cast<VarDecl>(DE->getDecl()); 1857 SourceLocation ILoc = DE->getExprLoc(); 1858 1859 // Mark variable as used. 1860 VD->setReferenced(); 1861 VD->markUsed(Context); 1862 1863 QualType QType = VD->getType(); 1864 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1865 // It will be analyzed later. 1866 Vars.push_back(DE); 1867 continue; 1868 } 1869 1870 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1871 // A threadprivate variable must not have an incomplete type. 1872 if (RequireCompleteType(ILoc, VD->getType(), 1873 diag::err_omp_threadprivate_incomplete_type)) { 1874 continue; 1875 } 1876 1877 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1878 // A threadprivate variable must not have a reference type. 1879 if (VD->getType()->isReferenceType()) { 1880 Diag(ILoc, diag::err_omp_ref_type_arg) 1881 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1882 bool IsDecl = 1883 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1884 Diag(VD->getLocation(), 1885 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1886 << VD; 1887 continue; 1888 } 1889 1890 // Check if this is a TLS variable. If TLS is not being supported, produce 1891 // the corresponding diagnostic. 1892 if ((VD->getTLSKind() != VarDecl::TLS_None && 1893 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1894 getLangOpts().OpenMPUseTLS && 1895 getASTContext().getTargetInfo().isTLSSupported())) || 1896 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1897 !VD->isLocalVarDecl())) { 1898 Diag(ILoc, diag::err_omp_var_thread_local) 1899 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1900 bool IsDecl = 1901 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1902 Diag(VD->getLocation(), 1903 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1904 << VD; 1905 continue; 1906 } 1907 1908 // Check if initial value of threadprivate variable reference variable with 1909 // local storage (it is not supported by runtime). 1910 if (const Expr *Init = VD->getAnyInitializer()) { 1911 LocalVarRefChecker Checker(*this); 1912 if (Checker.Visit(Init)) 1913 continue; 1914 } 1915 1916 Vars.push_back(RefExpr); 1917 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1918 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1919 Context, SourceRange(Loc, Loc))); 1920 if (ASTMutationListener *ML = Context.getASTMutationListener()) 1921 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1922 } 1923 OMPThreadPrivateDecl *D = nullptr; 1924 if (!Vars.empty()) { 1925 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1926 Vars); 1927 D->setAccess(AS_public); 1928 } 1929 return D; 1930 } 1931 1932 Sema::DeclGroupPtrTy 1933 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 1934 ArrayRef<OMPClause *> ClauseList) { 1935 OMPRequiresDecl *D = nullptr; 1936 if (!CurContext->isFileContext()) { 1937 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 1938 } else { 1939 D = CheckOMPRequiresDecl(Loc, ClauseList); 1940 if (D) { 1941 CurContext->addDecl(D); 1942 DSAStack->addRequiresDecl(D); 1943 } 1944 } 1945 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1946 } 1947 1948 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 1949 ArrayRef<OMPClause *> ClauseList) { 1950 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 1951 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 1952 ClauseList); 1953 return nullptr; 1954 } 1955 1956 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 1957 const ValueDecl *D, 1958 const DSAStackTy::DSAVarData &DVar, 1959 bool IsLoopIterVar = false) { 1960 if (DVar.RefExpr) { 1961 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1962 << getOpenMPClauseName(DVar.CKind); 1963 return; 1964 } 1965 enum { 1966 PDSA_StaticMemberShared, 1967 PDSA_StaticLocalVarShared, 1968 PDSA_LoopIterVarPrivate, 1969 PDSA_LoopIterVarLinear, 1970 PDSA_LoopIterVarLastprivate, 1971 PDSA_ConstVarShared, 1972 PDSA_GlobalVarShared, 1973 PDSA_TaskVarFirstprivate, 1974 PDSA_LocalVarPrivate, 1975 PDSA_Implicit 1976 } Reason = PDSA_Implicit; 1977 bool ReportHint = false; 1978 auto ReportLoc = D->getLocation(); 1979 auto *VD = dyn_cast<VarDecl>(D); 1980 if (IsLoopIterVar) { 1981 if (DVar.CKind == OMPC_private) 1982 Reason = PDSA_LoopIterVarPrivate; 1983 else if (DVar.CKind == OMPC_lastprivate) 1984 Reason = PDSA_LoopIterVarLastprivate; 1985 else 1986 Reason = PDSA_LoopIterVarLinear; 1987 } else if (isOpenMPTaskingDirective(DVar.DKind) && 1988 DVar.CKind == OMPC_firstprivate) { 1989 Reason = PDSA_TaskVarFirstprivate; 1990 ReportLoc = DVar.ImplicitDSALoc; 1991 } else if (VD && VD->isStaticLocal()) 1992 Reason = PDSA_StaticLocalVarShared; 1993 else if (VD && VD->isStaticDataMember()) 1994 Reason = PDSA_StaticMemberShared; 1995 else if (VD && VD->isFileVarDecl()) 1996 Reason = PDSA_GlobalVarShared; 1997 else if (D->getType().isConstant(SemaRef.getASTContext())) 1998 Reason = PDSA_ConstVarShared; 1999 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 2000 ReportHint = true; 2001 Reason = PDSA_LocalVarPrivate; 2002 } 2003 if (Reason != PDSA_Implicit) { 2004 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 2005 << Reason << ReportHint 2006 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 2007 } else if (DVar.ImplicitDSALoc.isValid()) { 2008 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 2009 << getOpenMPClauseName(DVar.CKind); 2010 } 2011 } 2012 2013 namespace { 2014 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 2015 DSAStackTy *Stack; 2016 Sema &SemaRef; 2017 bool ErrorFound = false; 2018 CapturedStmt *CS = nullptr; 2019 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 2020 llvm::SmallVector<Expr *, 4> ImplicitMap; 2021 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 2022 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 2023 2024 public: 2025 void VisitDeclRefExpr(DeclRefExpr *E) { 2026 if (E->isTypeDependent() || E->isValueDependent() || 2027 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 2028 return; 2029 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2030 VD = VD->getCanonicalDecl(); 2031 // Skip internally declared variables. 2032 if (VD->hasLocalStorage() && !CS->capturesVariable(VD)) 2033 return; 2034 2035 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 2036 // Check if the variable has explicit DSA set and stop analysis if it so. 2037 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 2038 return; 2039 2040 // Skip internally declared static variables. 2041 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2042 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 2043 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) && 2044 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)) 2045 return; 2046 2047 SourceLocation ELoc = E->getExprLoc(); 2048 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 2049 // The default(none) clause requires that each variable that is referenced 2050 // in the construct, and does not have a predetermined data-sharing 2051 // attribute, must have its data-sharing attribute explicitly determined 2052 // by being listed in a data-sharing attribute clause. 2053 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 2054 isParallelOrTaskRegion(DKind) && 2055 VarsWithInheritedDSA.count(VD) == 0) { 2056 VarsWithInheritedDSA[VD] = E; 2057 return; 2058 } 2059 2060 if (isOpenMPTargetExecutionDirective(DKind) && 2061 !Stack->isLoopControlVariable(VD).first) { 2062 if (!Stack->checkMappableExprComponentListsForDecl( 2063 VD, /*CurrentRegionOnly=*/true, 2064 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 2065 StackComponents, 2066 OpenMPClauseKind) { 2067 // Variable is used if it has been marked as an array, array 2068 // section or the variable iself. 2069 return StackComponents.size() == 1 || 2070 std::all_of( 2071 std::next(StackComponents.rbegin()), 2072 StackComponents.rend(), 2073 [](const OMPClauseMappableExprCommon:: 2074 MappableComponent &MC) { 2075 return MC.getAssociatedDeclaration() == 2076 nullptr && 2077 (isa<OMPArraySectionExpr>( 2078 MC.getAssociatedExpression()) || 2079 isa<ArraySubscriptExpr>( 2080 MC.getAssociatedExpression())); 2081 }); 2082 })) { 2083 bool IsFirstprivate = false; 2084 // By default lambdas are captured as firstprivates. 2085 if (const auto *RD = 2086 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 2087 IsFirstprivate = RD->isLambda(); 2088 IsFirstprivate = 2089 IsFirstprivate || 2090 (VD->getType().getNonReferenceType()->isScalarType() && 2091 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res); 2092 if (IsFirstprivate) 2093 ImplicitFirstprivate.emplace_back(E); 2094 else 2095 ImplicitMap.emplace_back(E); 2096 return; 2097 } 2098 } 2099 2100 // OpenMP [2.9.3.6, Restrictions, p.2] 2101 // A list item that appears in a reduction clause of the innermost 2102 // enclosing worksharing or parallel construct may not be accessed in an 2103 // explicit task. 2104 DVar = Stack->hasInnermostDSA( 2105 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 2106 [](OpenMPDirectiveKind K) { 2107 return isOpenMPParallelDirective(K) || 2108 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 2109 }, 2110 /*FromParent=*/true); 2111 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 2112 ErrorFound = true; 2113 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 2114 reportOriginalDsa(SemaRef, Stack, VD, DVar); 2115 return; 2116 } 2117 2118 // Define implicit data-sharing attributes for task. 2119 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 2120 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 2121 !Stack->isLoopControlVariable(VD).first) 2122 ImplicitFirstprivate.push_back(E); 2123 } 2124 } 2125 void VisitMemberExpr(MemberExpr *E) { 2126 if (E->isTypeDependent() || E->isValueDependent() || 2127 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 2128 return; 2129 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 2130 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 2131 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 2132 if (!FD) 2133 return; 2134 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 2135 // Check if the variable has explicit DSA set and stop analysis if it 2136 // so. 2137 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 2138 return; 2139 2140 if (isOpenMPTargetExecutionDirective(DKind) && 2141 !Stack->isLoopControlVariable(FD).first && 2142 !Stack->checkMappableExprComponentListsForDecl( 2143 FD, /*CurrentRegionOnly=*/true, 2144 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 2145 StackComponents, 2146 OpenMPClauseKind) { 2147 return isa<CXXThisExpr>( 2148 cast<MemberExpr>( 2149 StackComponents.back().getAssociatedExpression()) 2150 ->getBase() 2151 ->IgnoreParens()); 2152 })) { 2153 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 2154 // A bit-field cannot appear in a map clause. 2155 // 2156 if (FD->isBitField()) 2157 return; 2158 ImplicitMap.emplace_back(E); 2159 return; 2160 } 2161 2162 SourceLocation ELoc = E->getExprLoc(); 2163 // OpenMP [2.9.3.6, Restrictions, p.2] 2164 // A list item that appears in a reduction clause of the innermost 2165 // enclosing worksharing or parallel construct may not be accessed in 2166 // an explicit task. 2167 DVar = Stack->hasInnermostDSA( 2168 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 2169 [](OpenMPDirectiveKind K) { 2170 return isOpenMPParallelDirective(K) || 2171 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 2172 }, 2173 /*FromParent=*/true); 2174 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 2175 ErrorFound = true; 2176 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 2177 reportOriginalDsa(SemaRef, Stack, FD, DVar); 2178 return; 2179 } 2180 2181 // Define implicit data-sharing attributes for task. 2182 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 2183 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 2184 !Stack->isLoopControlVariable(FD).first) { 2185 // Check if there is a captured expression for the current field in the 2186 // region. Do not mark it as firstprivate unless there is no captured 2187 // expression. 2188 // TODO: try to make it firstprivate. 2189 if (DVar.CKind != OMPC_unknown) 2190 ImplicitFirstprivate.push_back(E); 2191 } 2192 return; 2193 } 2194 if (isOpenMPTargetExecutionDirective(DKind)) { 2195 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 2196 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 2197 /*NoDiagnose=*/true)) 2198 return; 2199 const auto *VD = cast<ValueDecl>( 2200 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 2201 if (!Stack->checkMappableExprComponentListsForDecl( 2202 VD, /*CurrentRegionOnly=*/true, 2203 [&CurComponents]( 2204 OMPClauseMappableExprCommon::MappableExprComponentListRef 2205 StackComponents, 2206 OpenMPClauseKind) { 2207 auto CCI = CurComponents.rbegin(); 2208 auto CCE = CurComponents.rend(); 2209 for (const auto &SC : llvm::reverse(StackComponents)) { 2210 // Do both expressions have the same kind? 2211 if (CCI->getAssociatedExpression()->getStmtClass() != 2212 SC.getAssociatedExpression()->getStmtClass()) 2213 if (!(isa<OMPArraySectionExpr>( 2214 SC.getAssociatedExpression()) && 2215 isa<ArraySubscriptExpr>( 2216 CCI->getAssociatedExpression()))) 2217 return false; 2218 2219 const Decl *CCD = CCI->getAssociatedDeclaration(); 2220 const Decl *SCD = SC.getAssociatedDeclaration(); 2221 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 2222 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 2223 if (SCD != CCD) 2224 return false; 2225 std::advance(CCI, 1); 2226 if (CCI == CCE) 2227 break; 2228 } 2229 return true; 2230 })) { 2231 Visit(E->getBase()); 2232 } 2233 } else { 2234 Visit(E->getBase()); 2235 } 2236 } 2237 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 2238 for (OMPClause *C : S->clauses()) { 2239 // Skip analysis of arguments of implicitly defined firstprivate clause 2240 // for task|target directives. 2241 // Skip analysis of arguments of implicitly defined map clause for target 2242 // directives. 2243 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 2244 C->isImplicit())) { 2245 for (Stmt *CC : C->children()) { 2246 if (CC) 2247 Visit(CC); 2248 } 2249 } 2250 } 2251 } 2252 void VisitStmt(Stmt *S) { 2253 for (Stmt *C : S->children()) { 2254 if (C && !isa<OMPExecutableDirective>(C)) 2255 Visit(C); 2256 } 2257 } 2258 2259 bool isErrorFound() const { return ErrorFound; } 2260 ArrayRef<Expr *> getImplicitFirstprivate() const { 2261 return ImplicitFirstprivate; 2262 } 2263 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; } 2264 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 2265 return VarsWithInheritedDSA; 2266 } 2267 2268 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 2269 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 2270 }; 2271 } // namespace 2272 2273 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 2274 switch (DKind) { 2275 case OMPD_parallel: 2276 case OMPD_parallel_for: 2277 case OMPD_parallel_for_simd: 2278 case OMPD_parallel_sections: 2279 case OMPD_teams: 2280 case OMPD_teams_distribute: 2281 case OMPD_teams_distribute_simd: { 2282 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2283 QualType KmpInt32PtrTy = 2284 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2285 Sema::CapturedParamNameType Params[] = { 2286 std::make_pair(".global_tid.", KmpInt32PtrTy), 2287 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2288 std::make_pair(StringRef(), QualType()) // __context with shared vars 2289 }; 2290 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2291 Params); 2292 break; 2293 } 2294 case OMPD_target_teams: 2295 case OMPD_target_parallel: 2296 case OMPD_target_parallel_for: 2297 case OMPD_target_parallel_for_simd: 2298 case OMPD_target_teams_distribute: 2299 case OMPD_target_teams_distribute_simd: { 2300 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2301 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2302 QualType KmpInt32PtrTy = 2303 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2304 QualType Args[] = {VoidPtrTy}; 2305 FunctionProtoType::ExtProtoInfo EPI; 2306 EPI.Variadic = true; 2307 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2308 Sema::CapturedParamNameType Params[] = { 2309 std::make_pair(".global_tid.", KmpInt32Ty), 2310 std::make_pair(".part_id.", KmpInt32PtrTy), 2311 std::make_pair(".privates.", VoidPtrTy), 2312 std::make_pair( 2313 ".copy_fn.", 2314 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2315 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2316 std::make_pair(StringRef(), QualType()) // __context with shared vars 2317 }; 2318 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2319 Params); 2320 // Mark this captured region as inlined, because we don't use outlined 2321 // function directly. 2322 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2323 AlwaysInlineAttr::CreateImplicit( 2324 Context, AlwaysInlineAttr::Keyword_forceinline)); 2325 Sema::CapturedParamNameType ParamsTarget[] = { 2326 std::make_pair(StringRef(), QualType()) // __context with shared vars 2327 }; 2328 // Start a captured region for 'target' with no implicit parameters. 2329 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2330 ParamsTarget); 2331 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 2332 std::make_pair(".global_tid.", KmpInt32PtrTy), 2333 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2334 std::make_pair(StringRef(), QualType()) // __context with shared vars 2335 }; 2336 // Start a captured region for 'teams' or 'parallel'. Both regions have 2337 // the same implicit parameters. 2338 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2339 ParamsTeamsOrParallel); 2340 break; 2341 } 2342 case OMPD_target: 2343 case OMPD_target_simd: { 2344 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2345 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2346 QualType KmpInt32PtrTy = 2347 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2348 QualType Args[] = {VoidPtrTy}; 2349 FunctionProtoType::ExtProtoInfo EPI; 2350 EPI.Variadic = true; 2351 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2352 Sema::CapturedParamNameType Params[] = { 2353 std::make_pair(".global_tid.", KmpInt32Ty), 2354 std::make_pair(".part_id.", KmpInt32PtrTy), 2355 std::make_pair(".privates.", VoidPtrTy), 2356 std::make_pair( 2357 ".copy_fn.", 2358 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2359 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2360 std::make_pair(StringRef(), QualType()) // __context with shared vars 2361 }; 2362 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2363 Params); 2364 // Mark this captured region as inlined, because we don't use outlined 2365 // function directly. 2366 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2367 AlwaysInlineAttr::CreateImplicit( 2368 Context, AlwaysInlineAttr::Keyword_forceinline)); 2369 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2370 std::make_pair(StringRef(), QualType())); 2371 break; 2372 } 2373 case OMPD_simd: 2374 case OMPD_for: 2375 case OMPD_for_simd: 2376 case OMPD_sections: 2377 case OMPD_section: 2378 case OMPD_single: 2379 case OMPD_master: 2380 case OMPD_critical: 2381 case OMPD_taskgroup: 2382 case OMPD_distribute: 2383 case OMPD_distribute_simd: 2384 case OMPD_ordered: 2385 case OMPD_atomic: 2386 case OMPD_target_data: { 2387 Sema::CapturedParamNameType Params[] = { 2388 std::make_pair(StringRef(), QualType()) // __context with shared vars 2389 }; 2390 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2391 Params); 2392 break; 2393 } 2394 case OMPD_task: { 2395 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2396 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2397 QualType KmpInt32PtrTy = 2398 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2399 QualType Args[] = {VoidPtrTy}; 2400 FunctionProtoType::ExtProtoInfo EPI; 2401 EPI.Variadic = true; 2402 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2403 Sema::CapturedParamNameType Params[] = { 2404 std::make_pair(".global_tid.", KmpInt32Ty), 2405 std::make_pair(".part_id.", KmpInt32PtrTy), 2406 std::make_pair(".privates.", VoidPtrTy), 2407 std::make_pair( 2408 ".copy_fn.", 2409 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2410 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2411 std::make_pair(StringRef(), QualType()) // __context with shared vars 2412 }; 2413 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2414 Params); 2415 // Mark this captured region as inlined, because we don't use outlined 2416 // function directly. 2417 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2418 AlwaysInlineAttr::CreateImplicit( 2419 Context, AlwaysInlineAttr::Keyword_forceinline)); 2420 break; 2421 } 2422 case OMPD_taskloop: 2423 case OMPD_taskloop_simd: { 2424 QualType KmpInt32Ty = 2425 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 2426 .withConst(); 2427 QualType KmpUInt64Ty = 2428 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 2429 .withConst(); 2430 QualType KmpInt64Ty = 2431 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 2432 .withConst(); 2433 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2434 QualType KmpInt32PtrTy = 2435 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2436 QualType Args[] = {VoidPtrTy}; 2437 FunctionProtoType::ExtProtoInfo EPI; 2438 EPI.Variadic = true; 2439 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2440 Sema::CapturedParamNameType Params[] = { 2441 std::make_pair(".global_tid.", KmpInt32Ty), 2442 std::make_pair(".part_id.", KmpInt32PtrTy), 2443 std::make_pair(".privates.", VoidPtrTy), 2444 std::make_pair( 2445 ".copy_fn.", 2446 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2447 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2448 std::make_pair(".lb.", KmpUInt64Ty), 2449 std::make_pair(".ub.", KmpUInt64Ty), 2450 std::make_pair(".st.", KmpInt64Ty), 2451 std::make_pair(".liter.", KmpInt32Ty), 2452 std::make_pair(".reductions.", VoidPtrTy), 2453 std::make_pair(StringRef(), QualType()) // __context with shared vars 2454 }; 2455 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2456 Params); 2457 // Mark this captured region as inlined, because we don't use outlined 2458 // function directly. 2459 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2460 AlwaysInlineAttr::CreateImplicit( 2461 Context, AlwaysInlineAttr::Keyword_forceinline)); 2462 break; 2463 } 2464 case OMPD_distribute_parallel_for_simd: 2465 case OMPD_distribute_parallel_for: { 2466 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2467 QualType KmpInt32PtrTy = 2468 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2469 Sema::CapturedParamNameType Params[] = { 2470 std::make_pair(".global_tid.", KmpInt32PtrTy), 2471 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2472 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 2473 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 2474 std::make_pair(StringRef(), QualType()) // __context with shared vars 2475 }; 2476 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2477 Params); 2478 break; 2479 } 2480 case OMPD_target_teams_distribute_parallel_for: 2481 case OMPD_target_teams_distribute_parallel_for_simd: { 2482 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2483 QualType KmpInt32PtrTy = 2484 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2485 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2486 2487 QualType Args[] = {VoidPtrTy}; 2488 FunctionProtoType::ExtProtoInfo EPI; 2489 EPI.Variadic = true; 2490 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2491 Sema::CapturedParamNameType Params[] = { 2492 std::make_pair(".global_tid.", KmpInt32Ty), 2493 std::make_pair(".part_id.", KmpInt32PtrTy), 2494 std::make_pair(".privates.", VoidPtrTy), 2495 std::make_pair( 2496 ".copy_fn.", 2497 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2498 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2499 std::make_pair(StringRef(), QualType()) // __context with shared vars 2500 }; 2501 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2502 Params); 2503 // Mark this captured region as inlined, because we don't use outlined 2504 // function directly. 2505 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2506 AlwaysInlineAttr::CreateImplicit( 2507 Context, AlwaysInlineAttr::Keyword_forceinline)); 2508 Sema::CapturedParamNameType ParamsTarget[] = { 2509 std::make_pair(StringRef(), QualType()) // __context with shared vars 2510 }; 2511 // Start a captured region for 'target' with no implicit parameters. 2512 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2513 ParamsTarget); 2514 2515 Sema::CapturedParamNameType ParamsTeams[] = { 2516 std::make_pair(".global_tid.", KmpInt32PtrTy), 2517 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2518 std::make_pair(StringRef(), QualType()) // __context with shared vars 2519 }; 2520 // Start a captured region for 'target' with no implicit parameters. 2521 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2522 ParamsTeams); 2523 2524 Sema::CapturedParamNameType ParamsParallel[] = { 2525 std::make_pair(".global_tid.", KmpInt32PtrTy), 2526 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2527 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 2528 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 2529 std::make_pair(StringRef(), QualType()) // __context with shared vars 2530 }; 2531 // Start a captured region for 'teams' or 'parallel'. Both regions have 2532 // the same implicit parameters. 2533 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2534 ParamsParallel); 2535 break; 2536 } 2537 2538 case OMPD_teams_distribute_parallel_for: 2539 case OMPD_teams_distribute_parallel_for_simd: { 2540 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2541 QualType KmpInt32PtrTy = 2542 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2543 2544 Sema::CapturedParamNameType ParamsTeams[] = { 2545 std::make_pair(".global_tid.", KmpInt32PtrTy), 2546 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2547 std::make_pair(StringRef(), QualType()) // __context with shared vars 2548 }; 2549 // Start a captured region for 'target' with no implicit parameters. 2550 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2551 ParamsTeams); 2552 2553 Sema::CapturedParamNameType ParamsParallel[] = { 2554 std::make_pair(".global_tid.", KmpInt32PtrTy), 2555 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2556 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 2557 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 2558 std::make_pair(StringRef(), QualType()) // __context with shared vars 2559 }; 2560 // Start a captured region for 'teams' or 'parallel'. Both regions have 2561 // the same implicit parameters. 2562 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2563 ParamsParallel); 2564 break; 2565 } 2566 case OMPD_target_update: 2567 case OMPD_target_enter_data: 2568 case OMPD_target_exit_data: { 2569 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2570 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2571 QualType KmpInt32PtrTy = 2572 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2573 QualType Args[] = {VoidPtrTy}; 2574 FunctionProtoType::ExtProtoInfo EPI; 2575 EPI.Variadic = true; 2576 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2577 Sema::CapturedParamNameType Params[] = { 2578 std::make_pair(".global_tid.", KmpInt32Ty), 2579 std::make_pair(".part_id.", KmpInt32PtrTy), 2580 std::make_pair(".privates.", VoidPtrTy), 2581 std::make_pair( 2582 ".copy_fn.", 2583 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2584 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2585 std::make_pair(StringRef(), QualType()) // __context with shared vars 2586 }; 2587 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2588 Params); 2589 // Mark this captured region as inlined, because we don't use outlined 2590 // function directly. 2591 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2592 AlwaysInlineAttr::CreateImplicit( 2593 Context, AlwaysInlineAttr::Keyword_forceinline)); 2594 break; 2595 } 2596 case OMPD_threadprivate: 2597 case OMPD_taskyield: 2598 case OMPD_barrier: 2599 case OMPD_taskwait: 2600 case OMPD_cancellation_point: 2601 case OMPD_cancel: 2602 case OMPD_flush: 2603 case OMPD_declare_reduction: 2604 case OMPD_declare_simd: 2605 case OMPD_declare_target: 2606 case OMPD_end_declare_target: 2607 case OMPD_requires: 2608 llvm_unreachable("OpenMP Directive is not allowed"); 2609 case OMPD_unknown: 2610 llvm_unreachable("Unknown OpenMP directive"); 2611 } 2612 } 2613 2614 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 2615 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2616 getOpenMPCaptureRegions(CaptureRegions, DKind); 2617 return CaptureRegions.size(); 2618 } 2619 2620 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 2621 Expr *CaptureExpr, bool WithInit, 2622 bool AsExpression) { 2623 assert(CaptureExpr); 2624 ASTContext &C = S.getASTContext(); 2625 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 2626 QualType Ty = Init->getType(); 2627 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 2628 if (S.getLangOpts().CPlusPlus) { 2629 Ty = C.getLValueReferenceType(Ty); 2630 } else { 2631 Ty = C.getPointerType(Ty); 2632 ExprResult Res = 2633 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 2634 if (!Res.isUsable()) 2635 return nullptr; 2636 Init = Res.get(); 2637 } 2638 WithInit = true; 2639 } 2640 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 2641 CaptureExpr->getBeginLoc()); 2642 if (!WithInit) 2643 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 2644 S.CurContext->addHiddenDecl(CED); 2645 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 2646 return CED; 2647 } 2648 2649 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2650 bool WithInit) { 2651 OMPCapturedExprDecl *CD; 2652 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 2653 CD = cast<OMPCapturedExprDecl>(VD); 2654 else 2655 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 2656 /*AsExpression=*/false); 2657 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2658 CaptureExpr->getExprLoc()); 2659 } 2660 2661 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 2662 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 2663 if (!Ref) { 2664 OMPCapturedExprDecl *CD = buildCaptureDecl( 2665 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 2666 /*WithInit=*/true, /*AsExpression=*/true); 2667 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2668 CaptureExpr->getExprLoc()); 2669 } 2670 ExprResult Res = Ref; 2671 if (!S.getLangOpts().CPlusPlus && 2672 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 2673 Ref->getType()->isPointerType()) { 2674 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 2675 if (!Res.isUsable()) 2676 return ExprError(); 2677 } 2678 return S.DefaultLvalueConversion(Res.get()); 2679 } 2680 2681 namespace { 2682 // OpenMP directives parsed in this section are represented as a 2683 // CapturedStatement with an associated statement. If a syntax error 2684 // is detected during the parsing of the associated statement, the 2685 // compiler must abort processing and close the CapturedStatement. 2686 // 2687 // Combined directives such as 'target parallel' have more than one 2688 // nested CapturedStatements. This RAII ensures that we unwind out 2689 // of all the nested CapturedStatements when an error is found. 2690 class CaptureRegionUnwinderRAII { 2691 private: 2692 Sema &S; 2693 bool &ErrorFound; 2694 OpenMPDirectiveKind DKind = OMPD_unknown; 2695 2696 public: 2697 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 2698 OpenMPDirectiveKind DKind) 2699 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 2700 ~CaptureRegionUnwinderRAII() { 2701 if (ErrorFound) { 2702 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 2703 while (--ThisCaptureLevel >= 0) 2704 S.ActOnCapturedRegionError(); 2705 } 2706 } 2707 }; 2708 } // namespace 2709 2710 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 2711 ArrayRef<OMPClause *> Clauses) { 2712 bool ErrorFound = false; 2713 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 2714 *this, ErrorFound, DSAStack->getCurrentDirective()); 2715 if (!S.isUsable()) { 2716 ErrorFound = true; 2717 return StmtError(); 2718 } 2719 2720 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2721 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 2722 OMPOrderedClause *OC = nullptr; 2723 OMPScheduleClause *SC = nullptr; 2724 SmallVector<const OMPLinearClause *, 4> LCs; 2725 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 2726 // This is required for proper codegen. 2727 for (OMPClause *Clause : Clauses) { 2728 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 2729 Clause->getClauseKind() == OMPC_in_reduction) { 2730 // Capture taskgroup task_reduction descriptors inside the tasking regions 2731 // with the corresponding in_reduction items. 2732 auto *IRC = cast<OMPInReductionClause>(Clause); 2733 for (Expr *E : IRC->taskgroup_descriptors()) 2734 if (E) 2735 MarkDeclarationsReferencedInExpr(E); 2736 } 2737 if (isOpenMPPrivate(Clause->getClauseKind()) || 2738 Clause->getClauseKind() == OMPC_copyprivate || 2739 (getLangOpts().OpenMPUseTLS && 2740 getASTContext().getTargetInfo().isTLSSupported() && 2741 Clause->getClauseKind() == OMPC_copyin)) { 2742 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 2743 // Mark all variables in private list clauses as used in inner region. 2744 for (Stmt *VarRef : Clause->children()) { 2745 if (auto *E = cast_or_null<Expr>(VarRef)) { 2746 MarkDeclarationsReferencedInExpr(E); 2747 } 2748 } 2749 DSAStack->setForceVarCapturing(/*V=*/false); 2750 } else if (CaptureRegions.size() > 1 || 2751 CaptureRegions.back() != OMPD_unknown) { 2752 if (auto *C = OMPClauseWithPreInit::get(Clause)) 2753 PICs.push_back(C); 2754 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 2755 if (Expr *E = C->getPostUpdateExpr()) 2756 MarkDeclarationsReferencedInExpr(E); 2757 } 2758 } 2759 if (Clause->getClauseKind() == OMPC_schedule) 2760 SC = cast<OMPScheduleClause>(Clause); 2761 else if (Clause->getClauseKind() == OMPC_ordered) 2762 OC = cast<OMPOrderedClause>(Clause); 2763 else if (Clause->getClauseKind() == OMPC_linear) 2764 LCs.push_back(cast<OMPLinearClause>(Clause)); 2765 } 2766 // OpenMP, 2.7.1 Loop Construct, Restrictions 2767 // The nonmonotonic modifier cannot be specified if an ordered clause is 2768 // specified. 2769 if (SC && 2770 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 2771 SC->getSecondScheduleModifier() == 2772 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 2773 OC) { 2774 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 2775 ? SC->getFirstScheduleModifierLoc() 2776 : SC->getSecondScheduleModifierLoc(), 2777 diag::err_omp_schedule_nonmonotonic_ordered) 2778 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 2779 ErrorFound = true; 2780 } 2781 if (!LCs.empty() && OC && OC->getNumForLoops()) { 2782 for (const OMPLinearClause *C : LCs) { 2783 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 2784 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 2785 } 2786 ErrorFound = true; 2787 } 2788 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 2789 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 2790 OC->getNumForLoops()) { 2791 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 2792 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 2793 ErrorFound = true; 2794 } 2795 if (ErrorFound) { 2796 return StmtError(); 2797 } 2798 StmtResult SR = S; 2799 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 2800 // Mark all variables in private list clauses as used in inner region. 2801 // Required for proper codegen of combined directives. 2802 // TODO: add processing for other clauses. 2803 if (ThisCaptureRegion != OMPD_unknown) { 2804 for (const clang::OMPClauseWithPreInit *C : PICs) { 2805 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 2806 // Find the particular capture region for the clause if the 2807 // directive is a combined one with multiple capture regions. 2808 // If the directive is not a combined one, the capture region 2809 // associated with the clause is OMPD_unknown and is generated 2810 // only once. 2811 if (CaptureRegion == ThisCaptureRegion || 2812 CaptureRegion == OMPD_unknown) { 2813 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 2814 for (Decl *D : DS->decls()) 2815 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 2816 } 2817 } 2818 } 2819 } 2820 SR = ActOnCapturedRegionEnd(SR.get()); 2821 } 2822 return SR; 2823 } 2824 2825 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 2826 OpenMPDirectiveKind CancelRegion, 2827 SourceLocation StartLoc) { 2828 // CancelRegion is only needed for cancel and cancellation_point. 2829 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 2830 return false; 2831 2832 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 2833 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 2834 return false; 2835 2836 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 2837 << getOpenMPDirectiveName(CancelRegion); 2838 return true; 2839 } 2840 2841 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 2842 OpenMPDirectiveKind CurrentRegion, 2843 const DeclarationNameInfo &CurrentName, 2844 OpenMPDirectiveKind CancelRegion, 2845 SourceLocation StartLoc) { 2846 if (Stack->getCurScope()) { 2847 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 2848 OpenMPDirectiveKind OffendingRegion = ParentRegion; 2849 bool NestingProhibited = false; 2850 bool CloseNesting = true; 2851 bool OrphanSeen = false; 2852 enum { 2853 NoRecommend, 2854 ShouldBeInParallelRegion, 2855 ShouldBeInOrderedRegion, 2856 ShouldBeInTargetRegion, 2857 ShouldBeInTeamsRegion 2858 } Recommend = NoRecommend; 2859 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 2860 // OpenMP [2.16, Nesting of Regions] 2861 // OpenMP constructs may not be nested inside a simd region. 2862 // OpenMP [2.8.1,simd Construct, Restrictions] 2863 // An ordered construct with the simd clause is the only OpenMP 2864 // construct that can appear in the simd region. 2865 // Allowing a SIMD construct nested in another SIMD construct is an 2866 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 2867 // message. 2868 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 2869 ? diag::err_omp_prohibited_region_simd 2870 : diag::warn_omp_nesting_simd); 2871 return CurrentRegion != OMPD_simd; 2872 } 2873 if (ParentRegion == OMPD_atomic) { 2874 // OpenMP [2.16, Nesting of Regions] 2875 // OpenMP constructs may not be nested inside an atomic region. 2876 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 2877 return true; 2878 } 2879 if (CurrentRegion == OMPD_section) { 2880 // OpenMP [2.7.2, sections Construct, Restrictions] 2881 // Orphaned section directives are prohibited. That is, the section 2882 // directives must appear within the sections construct and must not be 2883 // encountered elsewhere in the sections region. 2884 if (ParentRegion != OMPD_sections && 2885 ParentRegion != OMPD_parallel_sections) { 2886 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 2887 << (ParentRegion != OMPD_unknown) 2888 << getOpenMPDirectiveName(ParentRegion); 2889 return true; 2890 } 2891 return false; 2892 } 2893 // Allow some constructs (except teams) to be orphaned (they could be 2894 // used in functions, called from OpenMP regions with the required 2895 // preconditions). 2896 if (ParentRegion == OMPD_unknown && 2897 !isOpenMPNestingTeamsDirective(CurrentRegion)) 2898 return false; 2899 if (CurrentRegion == OMPD_cancellation_point || 2900 CurrentRegion == OMPD_cancel) { 2901 // OpenMP [2.16, Nesting of Regions] 2902 // A cancellation point construct for which construct-type-clause is 2903 // taskgroup must be nested inside a task construct. A cancellation 2904 // point construct for which construct-type-clause is not taskgroup must 2905 // be closely nested inside an OpenMP construct that matches the type 2906 // specified in construct-type-clause. 2907 // A cancel construct for which construct-type-clause is taskgroup must be 2908 // nested inside a task construct. A cancel construct for which 2909 // construct-type-clause is not taskgroup must be closely nested inside an 2910 // OpenMP construct that matches the type specified in 2911 // construct-type-clause. 2912 NestingProhibited = 2913 !((CancelRegion == OMPD_parallel && 2914 (ParentRegion == OMPD_parallel || 2915 ParentRegion == OMPD_target_parallel)) || 2916 (CancelRegion == OMPD_for && 2917 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 2918 ParentRegion == OMPD_target_parallel_for || 2919 ParentRegion == OMPD_distribute_parallel_for || 2920 ParentRegion == OMPD_teams_distribute_parallel_for || 2921 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 2922 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 2923 (CancelRegion == OMPD_sections && 2924 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 2925 ParentRegion == OMPD_parallel_sections))); 2926 } else if (CurrentRegion == OMPD_master) { 2927 // OpenMP [2.16, Nesting of Regions] 2928 // A master region may not be closely nested inside a worksharing, 2929 // atomic, or explicit task region. 2930 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2931 isOpenMPTaskingDirective(ParentRegion); 2932 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 2933 // OpenMP [2.16, Nesting of Regions] 2934 // A critical region may not be nested (closely or otherwise) inside a 2935 // critical region with the same name. Note that this restriction is not 2936 // sufficient to prevent deadlock. 2937 SourceLocation PreviousCriticalLoc; 2938 bool DeadLock = Stack->hasDirective( 2939 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 2940 const DeclarationNameInfo &DNI, 2941 SourceLocation Loc) { 2942 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 2943 PreviousCriticalLoc = Loc; 2944 return true; 2945 } 2946 return false; 2947 }, 2948 false /* skip top directive */); 2949 if (DeadLock) { 2950 SemaRef.Diag(StartLoc, 2951 diag::err_omp_prohibited_region_critical_same_name) 2952 << CurrentName.getName(); 2953 if (PreviousCriticalLoc.isValid()) 2954 SemaRef.Diag(PreviousCriticalLoc, 2955 diag::note_omp_previous_critical_region); 2956 return true; 2957 } 2958 } else if (CurrentRegion == OMPD_barrier) { 2959 // OpenMP [2.16, Nesting of Regions] 2960 // A barrier region may not be closely nested inside a worksharing, 2961 // explicit task, critical, ordered, atomic, or master region. 2962 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2963 isOpenMPTaskingDirective(ParentRegion) || 2964 ParentRegion == OMPD_master || 2965 ParentRegion == OMPD_critical || 2966 ParentRegion == OMPD_ordered; 2967 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2968 !isOpenMPParallelDirective(CurrentRegion) && 2969 !isOpenMPTeamsDirective(CurrentRegion)) { 2970 // OpenMP [2.16, Nesting of Regions] 2971 // A worksharing region may not be closely nested inside a worksharing, 2972 // explicit task, critical, ordered, atomic, or master region. 2973 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2974 isOpenMPTaskingDirective(ParentRegion) || 2975 ParentRegion == OMPD_master || 2976 ParentRegion == OMPD_critical || 2977 ParentRegion == OMPD_ordered; 2978 Recommend = ShouldBeInParallelRegion; 2979 } else if (CurrentRegion == OMPD_ordered) { 2980 // OpenMP [2.16, Nesting of Regions] 2981 // An ordered region may not be closely nested inside a critical, 2982 // atomic, or explicit task region. 2983 // An ordered region must be closely nested inside a loop region (or 2984 // parallel loop region) with an ordered clause. 2985 // OpenMP [2.8.1,simd Construct, Restrictions] 2986 // An ordered construct with the simd clause is the only OpenMP construct 2987 // that can appear in the simd region. 2988 NestingProhibited = ParentRegion == OMPD_critical || 2989 isOpenMPTaskingDirective(ParentRegion) || 2990 !(isOpenMPSimdDirective(ParentRegion) || 2991 Stack->isParentOrderedRegion()); 2992 Recommend = ShouldBeInOrderedRegion; 2993 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 2994 // OpenMP [2.16, Nesting of Regions] 2995 // If specified, a teams construct must be contained within a target 2996 // construct. 2997 NestingProhibited = ParentRegion != OMPD_target; 2998 OrphanSeen = ParentRegion == OMPD_unknown; 2999 Recommend = ShouldBeInTargetRegion; 3000 } 3001 if (!NestingProhibited && 3002 !isOpenMPTargetExecutionDirective(CurrentRegion) && 3003 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 3004 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 3005 // OpenMP [2.16, Nesting of Regions] 3006 // distribute, parallel, parallel sections, parallel workshare, and the 3007 // parallel loop and parallel loop SIMD constructs are the only OpenMP 3008 // constructs that can be closely nested in the teams region. 3009 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 3010 !isOpenMPDistributeDirective(CurrentRegion); 3011 Recommend = ShouldBeInParallelRegion; 3012 } 3013 if (!NestingProhibited && 3014 isOpenMPNestingDistributeDirective(CurrentRegion)) { 3015 // OpenMP 4.5 [2.17 Nesting of Regions] 3016 // The region associated with the distribute construct must be strictly 3017 // nested inside a teams region 3018 NestingProhibited = 3019 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 3020 Recommend = ShouldBeInTeamsRegion; 3021 } 3022 if (!NestingProhibited && 3023 (isOpenMPTargetExecutionDirective(CurrentRegion) || 3024 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 3025 // OpenMP 4.5 [2.17 Nesting of Regions] 3026 // If a target, target update, target data, target enter data, or 3027 // target exit data construct is encountered during execution of a 3028 // target region, the behavior is unspecified. 3029 NestingProhibited = Stack->hasDirective( 3030 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 3031 SourceLocation) { 3032 if (isOpenMPTargetExecutionDirective(K)) { 3033 OffendingRegion = K; 3034 return true; 3035 } 3036 return false; 3037 }, 3038 false /* don't skip top directive */); 3039 CloseNesting = false; 3040 } 3041 if (NestingProhibited) { 3042 if (OrphanSeen) { 3043 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 3044 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 3045 } else { 3046 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 3047 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 3048 << Recommend << getOpenMPDirectiveName(CurrentRegion); 3049 } 3050 return true; 3051 } 3052 } 3053 return false; 3054 } 3055 3056 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 3057 ArrayRef<OMPClause *> Clauses, 3058 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 3059 bool ErrorFound = false; 3060 unsigned NamedModifiersNumber = 0; 3061 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 3062 OMPD_unknown + 1); 3063 SmallVector<SourceLocation, 4> NameModifierLoc; 3064 for (const OMPClause *C : Clauses) { 3065 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 3066 // At most one if clause without a directive-name-modifier can appear on 3067 // the directive. 3068 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 3069 if (FoundNameModifiers[CurNM]) { 3070 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 3071 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 3072 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 3073 ErrorFound = true; 3074 } else if (CurNM != OMPD_unknown) { 3075 NameModifierLoc.push_back(IC->getNameModifierLoc()); 3076 ++NamedModifiersNumber; 3077 } 3078 FoundNameModifiers[CurNM] = IC; 3079 if (CurNM == OMPD_unknown) 3080 continue; 3081 // Check if the specified name modifier is allowed for the current 3082 // directive. 3083 // At most one if clause with the particular directive-name-modifier can 3084 // appear on the directive. 3085 bool MatchFound = false; 3086 for (auto NM : AllowedNameModifiers) { 3087 if (CurNM == NM) { 3088 MatchFound = true; 3089 break; 3090 } 3091 } 3092 if (!MatchFound) { 3093 S.Diag(IC->getNameModifierLoc(), 3094 diag::err_omp_wrong_if_directive_name_modifier) 3095 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 3096 ErrorFound = true; 3097 } 3098 } 3099 } 3100 // If any if clause on the directive includes a directive-name-modifier then 3101 // all if clauses on the directive must include a directive-name-modifier. 3102 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 3103 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 3104 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 3105 diag::err_omp_no_more_if_clause); 3106 } else { 3107 std::string Values; 3108 std::string Sep(", "); 3109 unsigned AllowedCnt = 0; 3110 unsigned TotalAllowedNum = 3111 AllowedNameModifiers.size() - NamedModifiersNumber; 3112 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 3113 ++Cnt) { 3114 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 3115 if (!FoundNameModifiers[NM]) { 3116 Values += "'"; 3117 Values += getOpenMPDirectiveName(NM); 3118 Values += "'"; 3119 if (AllowedCnt + 2 == TotalAllowedNum) 3120 Values += " or "; 3121 else if (AllowedCnt + 1 != TotalAllowedNum) 3122 Values += Sep; 3123 ++AllowedCnt; 3124 } 3125 } 3126 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 3127 diag::err_omp_unnamed_if_clause) 3128 << (TotalAllowedNum > 1) << Values; 3129 } 3130 for (SourceLocation Loc : NameModifierLoc) { 3131 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 3132 } 3133 ErrorFound = true; 3134 } 3135 return ErrorFound; 3136 } 3137 3138 StmtResult Sema::ActOnOpenMPExecutableDirective( 3139 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 3140 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 3141 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 3142 StmtResult Res = StmtError(); 3143 // First check CancelRegion which is then used in checkNestingOfRegions. 3144 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 3145 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 3146 StartLoc)) 3147 return StmtError(); 3148 3149 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 3150 VarsWithInheritedDSAType VarsWithInheritedDSA; 3151 bool ErrorFound = false; 3152 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 3153 if (AStmt && !CurContext->isDependentContext()) { 3154 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3155 3156 // Check default data sharing attributes for referenced variables. 3157 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 3158 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 3159 Stmt *S = AStmt; 3160 while (--ThisCaptureLevel >= 0) 3161 S = cast<CapturedStmt>(S)->getCapturedStmt(); 3162 DSAChecker.Visit(S); 3163 if (DSAChecker.isErrorFound()) 3164 return StmtError(); 3165 // Generate list of implicitly defined firstprivate variables. 3166 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 3167 3168 SmallVector<Expr *, 4> ImplicitFirstprivates( 3169 DSAChecker.getImplicitFirstprivate().begin(), 3170 DSAChecker.getImplicitFirstprivate().end()); 3171 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(), 3172 DSAChecker.getImplicitMap().end()); 3173 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 3174 for (OMPClause *C : Clauses) { 3175 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 3176 for (Expr *E : IRC->taskgroup_descriptors()) 3177 if (E) 3178 ImplicitFirstprivates.emplace_back(E); 3179 } 3180 } 3181 if (!ImplicitFirstprivates.empty()) { 3182 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 3183 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 3184 SourceLocation())) { 3185 ClausesWithImplicit.push_back(Implicit); 3186 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 3187 ImplicitFirstprivates.size(); 3188 } else { 3189 ErrorFound = true; 3190 } 3191 } 3192 if (!ImplicitMaps.empty()) { 3193 if (OMPClause *Implicit = ActOnOpenMPMapClause( 3194 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, 3195 SourceLocation(), SourceLocation(), ImplicitMaps, 3196 SourceLocation(), SourceLocation(), SourceLocation())) { 3197 ClausesWithImplicit.emplace_back(Implicit); 3198 ErrorFound |= 3199 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size(); 3200 } else { 3201 ErrorFound = true; 3202 } 3203 } 3204 } 3205 3206 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 3207 switch (Kind) { 3208 case OMPD_parallel: 3209 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 3210 EndLoc); 3211 AllowedNameModifiers.push_back(OMPD_parallel); 3212 break; 3213 case OMPD_simd: 3214 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3215 VarsWithInheritedDSA); 3216 break; 3217 case OMPD_for: 3218 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3219 VarsWithInheritedDSA); 3220 break; 3221 case OMPD_for_simd: 3222 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3223 EndLoc, VarsWithInheritedDSA); 3224 break; 3225 case OMPD_sections: 3226 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 3227 EndLoc); 3228 break; 3229 case OMPD_section: 3230 assert(ClausesWithImplicit.empty() && 3231 "No clauses are allowed for 'omp section' directive"); 3232 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 3233 break; 3234 case OMPD_single: 3235 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 3236 EndLoc); 3237 break; 3238 case OMPD_master: 3239 assert(ClausesWithImplicit.empty() && 3240 "No clauses are allowed for 'omp master' directive"); 3241 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 3242 break; 3243 case OMPD_critical: 3244 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 3245 StartLoc, EndLoc); 3246 break; 3247 case OMPD_parallel_for: 3248 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 3249 EndLoc, VarsWithInheritedDSA); 3250 AllowedNameModifiers.push_back(OMPD_parallel); 3251 break; 3252 case OMPD_parallel_for_simd: 3253 Res = ActOnOpenMPParallelForSimdDirective( 3254 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3255 AllowedNameModifiers.push_back(OMPD_parallel); 3256 break; 3257 case OMPD_parallel_sections: 3258 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 3259 StartLoc, EndLoc); 3260 AllowedNameModifiers.push_back(OMPD_parallel); 3261 break; 3262 case OMPD_task: 3263 Res = 3264 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3265 AllowedNameModifiers.push_back(OMPD_task); 3266 break; 3267 case OMPD_taskyield: 3268 assert(ClausesWithImplicit.empty() && 3269 "No clauses are allowed for 'omp taskyield' directive"); 3270 assert(AStmt == nullptr && 3271 "No associated statement allowed for 'omp taskyield' directive"); 3272 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 3273 break; 3274 case OMPD_barrier: 3275 assert(ClausesWithImplicit.empty() && 3276 "No clauses are allowed for 'omp barrier' directive"); 3277 assert(AStmt == nullptr && 3278 "No associated statement allowed for 'omp barrier' directive"); 3279 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 3280 break; 3281 case OMPD_taskwait: 3282 assert(ClausesWithImplicit.empty() && 3283 "No clauses are allowed for 'omp taskwait' directive"); 3284 assert(AStmt == nullptr && 3285 "No associated statement allowed for 'omp taskwait' directive"); 3286 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 3287 break; 3288 case OMPD_taskgroup: 3289 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 3290 EndLoc); 3291 break; 3292 case OMPD_flush: 3293 assert(AStmt == nullptr && 3294 "No associated statement allowed for 'omp flush' directive"); 3295 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 3296 break; 3297 case OMPD_ordered: 3298 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 3299 EndLoc); 3300 break; 3301 case OMPD_atomic: 3302 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 3303 EndLoc); 3304 break; 3305 case OMPD_teams: 3306 Res = 3307 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3308 break; 3309 case OMPD_target: 3310 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 3311 EndLoc); 3312 AllowedNameModifiers.push_back(OMPD_target); 3313 break; 3314 case OMPD_target_parallel: 3315 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 3316 StartLoc, EndLoc); 3317 AllowedNameModifiers.push_back(OMPD_target); 3318 AllowedNameModifiers.push_back(OMPD_parallel); 3319 break; 3320 case OMPD_target_parallel_for: 3321 Res = ActOnOpenMPTargetParallelForDirective( 3322 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3323 AllowedNameModifiers.push_back(OMPD_target); 3324 AllowedNameModifiers.push_back(OMPD_parallel); 3325 break; 3326 case OMPD_cancellation_point: 3327 assert(ClausesWithImplicit.empty() && 3328 "No clauses are allowed for 'omp cancellation point' directive"); 3329 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 3330 "cancellation point' directive"); 3331 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 3332 break; 3333 case OMPD_cancel: 3334 assert(AStmt == nullptr && 3335 "No associated statement allowed for 'omp cancel' directive"); 3336 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 3337 CancelRegion); 3338 AllowedNameModifiers.push_back(OMPD_cancel); 3339 break; 3340 case OMPD_target_data: 3341 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 3342 EndLoc); 3343 AllowedNameModifiers.push_back(OMPD_target_data); 3344 break; 3345 case OMPD_target_enter_data: 3346 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 3347 EndLoc, AStmt); 3348 AllowedNameModifiers.push_back(OMPD_target_enter_data); 3349 break; 3350 case OMPD_target_exit_data: 3351 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 3352 EndLoc, AStmt); 3353 AllowedNameModifiers.push_back(OMPD_target_exit_data); 3354 break; 3355 case OMPD_taskloop: 3356 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 3357 EndLoc, VarsWithInheritedDSA); 3358 AllowedNameModifiers.push_back(OMPD_taskloop); 3359 break; 3360 case OMPD_taskloop_simd: 3361 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3362 EndLoc, VarsWithInheritedDSA); 3363 AllowedNameModifiers.push_back(OMPD_taskloop); 3364 break; 3365 case OMPD_distribute: 3366 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 3367 EndLoc, VarsWithInheritedDSA); 3368 break; 3369 case OMPD_target_update: 3370 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 3371 EndLoc, AStmt); 3372 AllowedNameModifiers.push_back(OMPD_target_update); 3373 break; 3374 case OMPD_distribute_parallel_for: 3375 Res = ActOnOpenMPDistributeParallelForDirective( 3376 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3377 AllowedNameModifiers.push_back(OMPD_parallel); 3378 break; 3379 case OMPD_distribute_parallel_for_simd: 3380 Res = ActOnOpenMPDistributeParallelForSimdDirective( 3381 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3382 AllowedNameModifiers.push_back(OMPD_parallel); 3383 break; 3384 case OMPD_distribute_simd: 3385 Res = ActOnOpenMPDistributeSimdDirective( 3386 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3387 break; 3388 case OMPD_target_parallel_for_simd: 3389 Res = ActOnOpenMPTargetParallelForSimdDirective( 3390 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3391 AllowedNameModifiers.push_back(OMPD_target); 3392 AllowedNameModifiers.push_back(OMPD_parallel); 3393 break; 3394 case OMPD_target_simd: 3395 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3396 EndLoc, VarsWithInheritedDSA); 3397 AllowedNameModifiers.push_back(OMPD_target); 3398 break; 3399 case OMPD_teams_distribute: 3400 Res = ActOnOpenMPTeamsDistributeDirective( 3401 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3402 break; 3403 case OMPD_teams_distribute_simd: 3404 Res = ActOnOpenMPTeamsDistributeSimdDirective( 3405 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3406 break; 3407 case OMPD_teams_distribute_parallel_for_simd: 3408 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 3409 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3410 AllowedNameModifiers.push_back(OMPD_parallel); 3411 break; 3412 case OMPD_teams_distribute_parallel_for: 3413 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 3414 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3415 AllowedNameModifiers.push_back(OMPD_parallel); 3416 break; 3417 case OMPD_target_teams: 3418 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 3419 EndLoc); 3420 AllowedNameModifiers.push_back(OMPD_target); 3421 break; 3422 case OMPD_target_teams_distribute: 3423 Res = ActOnOpenMPTargetTeamsDistributeDirective( 3424 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3425 AllowedNameModifiers.push_back(OMPD_target); 3426 break; 3427 case OMPD_target_teams_distribute_parallel_for: 3428 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 3429 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3430 AllowedNameModifiers.push_back(OMPD_target); 3431 AllowedNameModifiers.push_back(OMPD_parallel); 3432 break; 3433 case OMPD_target_teams_distribute_parallel_for_simd: 3434 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 3435 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3436 AllowedNameModifiers.push_back(OMPD_target); 3437 AllowedNameModifiers.push_back(OMPD_parallel); 3438 break; 3439 case OMPD_target_teams_distribute_simd: 3440 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 3441 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3442 AllowedNameModifiers.push_back(OMPD_target); 3443 break; 3444 case OMPD_declare_target: 3445 case OMPD_end_declare_target: 3446 case OMPD_threadprivate: 3447 case OMPD_declare_reduction: 3448 case OMPD_declare_simd: 3449 case OMPD_requires: 3450 llvm_unreachable("OpenMP Directive is not allowed"); 3451 case OMPD_unknown: 3452 llvm_unreachable("Unknown OpenMP directive"); 3453 } 3454 3455 for (const auto &P : VarsWithInheritedDSA) { 3456 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 3457 << P.first << P.second->getSourceRange(); 3458 } 3459 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 3460 3461 if (!AllowedNameModifiers.empty()) 3462 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 3463 ErrorFound; 3464 3465 if (ErrorFound) 3466 return StmtError(); 3467 return Res; 3468 } 3469 3470 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 3471 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 3472 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 3473 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 3474 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 3475 assert(Aligneds.size() == Alignments.size()); 3476 assert(Linears.size() == LinModifiers.size()); 3477 assert(Linears.size() == Steps.size()); 3478 if (!DG || DG.get().isNull()) 3479 return DeclGroupPtrTy(); 3480 3481 if (!DG.get().isSingleDecl()) { 3482 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 3483 return DG; 3484 } 3485 Decl *ADecl = DG.get().getSingleDecl(); 3486 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 3487 ADecl = FTD->getTemplatedDecl(); 3488 3489 auto *FD = dyn_cast<FunctionDecl>(ADecl); 3490 if (!FD) { 3491 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 3492 return DeclGroupPtrTy(); 3493 } 3494 3495 // OpenMP [2.8.2, declare simd construct, Description] 3496 // The parameter of the simdlen clause must be a constant positive integer 3497 // expression. 3498 ExprResult SL; 3499 if (Simdlen) 3500 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 3501 // OpenMP [2.8.2, declare simd construct, Description] 3502 // The special this pointer can be used as if was one of the arguments to the 3503 // function in any of the linear, aligned, or uniform clauses. 3504 // The uniform clause declares one or more arguments to have an invariant 3505 // value for all concurrent invocations of the function in the execution of a 3506 // single SIMD loop. 3507 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 3508 const Expr *UniformedLinearThis = nullptr; 3509 for (const Expr *E : Uniforms) { 3510 E = E->IgnoreParenImpCasts(); 3511 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 3512 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 3513 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3514 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3515 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 3516 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 3517 continue; 3518 } 3519 if (isa<CXXThisExpr>(E)) { 3520 UniformedLinearThis = E; 3521 continue; 3522 } 3523 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3524 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3525 } 3526 // OpenMP [2.8.2, declare simd construct, Description] 3527 // The aligned clause declares that the object to which each list item points 3528 // is aligned to the number of bytes expressed in the optional parameter of 3529 // the aligned clause. 3530 // The special this pointer can be used as if was one of the arguments to the 3531 // function in any of the linear, aligned, or uniform clauses. 3532 // The type of list items appearing in the aligned clause must be array, 3533 // pointer, reference to array, or reference to pointer. 3534 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 3535 const Expr *AlignedThis = nullptr; 3536 for (const Expr *E : Aligneds) { 3537 E = E->IgnoreParenImpCasts(); 3538 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 3539 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3540 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 3541 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3542 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3543 ->getCanonicalDecl() == CanonPVD) { 3544 // OpenMP [2.8.1, simd construct, Restrictions] 3545 // A list-item cannot appear in more than one aligned clause. 3546 if (AlignedArgs.count(CanonPVD) > 0) { 3547 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3548 << 1 << E->getSourceRange(); 3549 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 3550 diag::note_omp_explicit_dsa) 3551 << getOpenMPClauseName(OMPC_aligned); 3552 continue; 3553 } 3554 AlignedArgs[CanonPVD] = E; 3555 QualType QTy = PVD->getType() 3556 .getNonReferenceType() 3557 .getUnqualifiedType() 3558 .getCanonicalType(); 3559 const Type *Ty = QTy.getTypePtrOrNull(); 3560 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 3561 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 3562 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 3563 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 3564 } 3565 continue; 3566 } 3567 } 3568 if (isa<CXXThisExpr>(E)) { 3569 if (AlignedThis) { 3570 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3571 << 2 << E->getSourceRange(); 3572 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 3573 << getOpenMPClauseName(OMPC_aligned); 3574 } 3575 AlignedThis = E; 3576 continue; 3577 } 3578 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3579 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3580 } 3581 // The optional parameter of the aligned clause, alignment, must be a constant 3582 // positive integer expression. If no optional parameter is specified, 3583 // implementation-defined default alignments for SIMD instructions on the 3584 // target platforms are assumed. 3585 SmallVector<const Expr *, 4> NewAligns; 3586 for (Expr *E : Alignments) { 3587 ExprResult Align; 3588 if (E) 3589 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 3590 NewAligns.push_back(Align.get()); 3591 } 3592 // OpenMP [2.8.2, declare simd construct, Description] 3593 // The linear clause declares one or more list items to be private to a SIMD 3594 // lane and to have a linear relationship with respect to the iteration space 3595 // of a loop. 3596 // The special this pointer can be used as if was one of the arguments to the 3597 // function in any of the linear, aligned, or uniform clauses. 3598 // When a linear-step expression is specified in a linear clause it must be 3599 // either a constant integer expression or an integer-typed parameter that is 3600 // specified in a uniform clause on the directive. 3601 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 3602 const bool IsUniformedThis = UniformedLinearThis != nullptr; 3603 auto MI = LinModifiers.begin(); 3604 for (const Expr *E : Linears) { 3605 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 3606 ++MI; 3607 E = E->IgnoreParenImpCasts(); 3608 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 3609 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3610 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 3611 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3612 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3613 ->getCanonicalDecl() == CanonPVD) { 3614 // OpenMP [2.15.3.7, linear Clause, Restrictions] 3615 // A list-item cannot appear in more than one linear clause. 3616 if (LinearArgs.count(CanonPVD) > 0) { 3617 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3618 << getOpenMPClauseName(OMPC_linear) 3619 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 3620 Diag(LinearArgs[CanonPVD]->getExprLoc(), 3621 diag::note_omp_explicit_dsa) 3622 << getOpenMPClauseName(OMPC_linear); 3623 continue; 3624 } 3625 // Each argument can appear in at most one uniform or linear clause. 3626 if (UniformedArgs.count(CanonPVD) > 0) { 3627 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3628 << getOpenMPClauseName(OMPC_linear) 3629 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 3630 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 3631 diag::note_omp_explicit_dsa) 3632 << getOpenMPClauseName(OMPC_uniform); 3633 continue; 3634 } 3635 LinearArgs[CanonPVD] = E; 3636 if (E->isValueDependent() || E->isTypeDependent() || 3637 E->isInstantiationDependent() || 3638 E->containsUnexpandedParameterPack()) 3639 continue; 3640 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 3641 PVD->getOriginalType()); 3642 continue; 3643 } 3644 } 3645 if (isa<CXXThisExpr>(E)) { 3646 if (UniformedLinearThis) { 3647 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3648 << getOpenMPClauseName(OMPC_linear) 3649 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 3650 << E->getSourceRange(); 3651 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 3652 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 3653 : OMPC_linear); 3654 continue; 3655 } 3656 UniformedLinearThis = E; 3657 if (E->isValueDependent() || E->isTypeDependent() || 3658 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3659 continue; 3660 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 3661 E->getType()); 3662 continue; 3663 } 3664 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3665 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3666 } 3667 Expr *Step = nullptr; 3668 Expr *NewStep = nullptr; 3669 SmallVector<Expr *, 4> NewSteps; 3670 for (Expr *E : Steps) { 3671 // Skip the same step expression, it was checked already. 3672 if (Step == E || !E) { 3673 NewSteps.push_back(E ? NewStep : nullptr); 3674 continue; 3675 } 3676 Step = E; 3677 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 3678 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3679 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 3680 if (UniformedArgs.count(CanonPVD) == 0) { 3681 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 3682 << Step->getSourceRange(); 3683 } else if (E->isValueDependent() || E->isTypeDependent() || 3684 E->isInstantiationDependent() || 3685 E->containsUnexpandedParameterPack() || 3686 CanonPVD->getType()->hasIntegerRepresentation()) { 3687 NewSteps.push_back(Step); 3688 } else { 3689 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 3690 << Step->getSourceRange(); 3691 } 3692 continue; 3693 } 3694 NewStep = Step; 3695 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 3696 !Step->isInstantiationDependent() && 3697 !Step->containsUnexpandedParameterPack()) { 3698 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 3699 .get(); 3700 if (NewStep) 3701 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 3702 } 3703 NewSteps.push_back(NewStep); 3704 } 3705 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 3706 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 3707 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 3708 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 3709 const_cast<Expr **>(Linears.data()), Linears.size(), 3710 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 3711 NewSteps.data(), NewSteps.size(), SR); 3712 ADecl->addAttr(NewAttr); 3713 return ConvertDeclToDeclGroup(ADecl); 3714 } 3715 3716 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 3717 Stmt *AStmt, 3718 SourceLocation StartLoc, 3719 SourceLocation EndLoc) { 3720 if (!AStmt) 3721 return StmtError(); 3722 3723 auto *CS = cast<CapturedStmt>(AStmt); 3724 // 1.2.2 OpenMP Language Terminology 3725 // Structured block - An executable statement with a single entry at the 3726 // top and a single exit at the bottom. 3727 // The point of exit cannot be a branch out of the structured block. 3728 // longjmp() and throw() must not violate the entry/exit criteria. 3729 CS->getCapturedDecl()->setNothrow(); 3730 3731 setFunctionHasBranchProtectedScope(); 3732 3733 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 3734 DSAStack->isCancelRegion()); 3735 } 3736 3737 namespace { 3738 /// Helper class for checking canonical form of the OpenMP loops and 3739 /// extracting iteration space of each loop in the loop nest, that will be used 3740 /// for IR generation. 3741 class OpenMPIterationSpaceChecker { 3742 /// Reference to Sema. 3743 Sema &SemaRef; 3744 /// A location for diagnostics (when there is no some better location). 3745 SourceLocation DefaultLoc; 3746 /// A location for diagnostics (when increment is not compatible). 3747 SourceLocation ConditionLoc; 3748 /// A source location for referring to loop init later. 3749 SourceRange InitSrcRange; 3750 /// A source location for referring to condition later. 3751 SourceRange ConditionSrcRange; 3752 /// A source location for referring to increment later. 3753 SourceRange IncrementSrcRange; 3754 /// Loop variable. 3755 ValueDecl *LCDecl = nullptr; 3756 /// Reference to loop variable. 3757 Expr *LCRef = nullptr; 3758 /// Lower bound (initializer for the var). 3759 Expr *LB = nullptr; 3760 /// Upper bound. 3761 Expr *UB = nullptr; 3762 /// Loop step (increment). 3763 Expr *Step = nullptr; 3764 /// This flag is true when condition is one of: 3765 /// Var < UB 3766 /// Var <= UB 3767 /// UB > Var 3768 /// UB >= Var 3769 bool TestIsLessOp = false; 3770 /// This flag is true when condition is strict ( < or > ). 3771 bool TestIsStrictOp = false; 3772 /// This flag is true when step is subtracted on each iteration. 3773 bool SubtractStep = false; 3774 3775 public: 3776 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 3777 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 3778 /// Check init-expr for canonical loop form and save loop counter 3779 /// variable - #Var and its initialization value - #LB. 3780 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 3781 /// Check test-expr for canonical form, save upper-bound (#UB), flags 3782 /// for less/greater and for strict/non-strict comparison. 3783 bool checkAndSetCond(Expr *S); 3784 /// Check incr-expr for canonical loop form and return true if it 3785 /// does not conform, otherwise save loop step (#Step). 3786 bool checkAndSetInc(Expr *S); 3787 /// Return the loop counter variable. 3788 ValueDecl *getLoopDecl() const { return LCDecl; } 3789 /// Return the reference expression to loop counter variable. 3790 Expr *getLoopDeclRefExpr() const { return LCRef; } 3791 /// Source range of the loop init. 3792 SourceRange getInitSrcRange() const { return InitSrcRange; } 3793 /// Source range of the loop condition. 3794 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 3795 /// Source range of the loop increment. 3796 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 3797 /// True if the step should be subtracted. 3798 bool shouldSubtractStep() const { return SubtractStep; } 3799 /// Build the expression to calculate the number of iterations. 3800 Expr *buildNumIterations( 3801 Scope *S, const bool LimitedType, 3802 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 3803 /// Build the precondition expression for the loops. 3804 Expr * 3805 buildPreCond(Scope *S, Expr *Cond, 3806 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 3807 /// Build reference expression to the counter be used for codegen. 3808 DeclRefExpr * 3809 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 3810 DSAStackTy &DSA) const; 3811 /// Build reference expression to the private counter be used for 3812 /// codegen. 3813 Expr *buildPrivateCounterVar() const; 3814 /// Build initialization of the counter be used for codegen. 3815 Expr *buildCounterInit() const; 3816 /// Build step of the counter be used for codegen. 3817 Expr *buildCounterStep() const; 3818 /// Build loop data with counter value for depend clauses in ordered 3819 /// directives. 3820 Expr * 3821 buildOrderedLoopData(Scope *S, Expr *Counter, 3822 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 3823 SourceLocation Loc, Expr *Inc = nullptr, 3824 OverloadedOperatorKind OOK = OO_Amp); 3825 /// Return true if any expression is dependent. 3826 bool dependent() const; 3827 3828 private: 3829 /// Check the right-hand side of an assignment in the increment 3830 /// expression. 3831 bool checkAndSetIncRHS(Expr *RHS); 3832 /// Helper to set loop counter variable and its initializer. 3833 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 3834 /// Helper to set upper bound. 3835 bool setUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 3836 SourceLocation SL); 3837 /// Helper to set loop increment. 3838 bool setStep(Expr *NewStep, bool Subtract); 3839 }; 3840 3841 bool OpenMPIterationSpaceChecker::dependent() const { 3842 if (!LCDecl) { 3843 assert(!LB && !UB && !Step); 3844 return false; 3845 } 3846 return LCDecl->getType()->isDependentType() || 3847 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 3848 (Step && Step->isValueDependent()); 3849 } 3850 3851 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 3852 Expr *NewLCRefExpr, 3853 Expr *NewLB) { 3854 // State consistency checking to ensure correct usage. 3855 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 3856 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3857 if (!NewLCDecl || !NewLB) 3858 return true; 3859 LCDecl = getCanonicalDecl(NewLCDecl); 3860 LCRef = NewLCRefExpr; 3861 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 3862 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3863 if ((Ctor->isCopyOrMoveConstructor() || 3864 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3865 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3866 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 3867 LB = NewLB; 3868 return false; 3869 } 3870 3871 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, bool LessOp, bool StrictOp, 3872 SourceRange SR, SourceLocation SL) { 3873 // State consistency checking to ensure correct usage. 3874 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 3875 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3876 if (!NewUB) 3877 return true; 3878 UB = NewUB; 3879 TestIsLessOp = LessOp; 3880 TestIsStrictOp = StrictOp; 3881 ConditionSrcRange = SR; 3882 ConditionLoc = SL; 3883 return false; 3884 } 3885 3886 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 3887 // State consistency checking to ensure correct usage. 3888 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 3889 if (!NewStep) 3890 return true; 3891 if (!NewStep->isValueDependent()) { 3892 // Check that the step is integer expression. 3893 SourceLocation StepLoc = NewStep->getBeginLoc(); 3894 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 3895 StepLoc, getExprAsWritten(NewStep)); 3896 if (Val.isInvalid()) 3897 return true; 3898 NewStep = Val.get(); 3899 3900 // OpenMP [2.6, Canonical Loop Form, Restrictions] 3901 // If test-expr is of form var relational-op b and relational-op is < or 3902 // <= then incr-expr must cause var to increase on each iteration of the 3903 // loop. If test-expr is of form var relational-op b and relational-op is 3904 // > or >= then incr-expr must cause var to decrease on each iteration of 3905 // the loop. 3906 // If test-expr is of form b relational-op var and relational-op is < or 3907 // <= then incr-expr must cause var to decrease on each iteration of the 3908 // loop. If test-expr is of form b relational-op var and relational-op is 3909 // > or >= then incr-expr must cause var to increase on each iteration of 3910 // the loop. 3911 llvm::APSInt Result; 3912 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 3913 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 3914 bool IsConstNeg = 3915 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 3916 bool IsConstPos = 3917 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 3918 bool IsConstZero = IsConstant && !Result.getBoolValue(); 3919 if (UB && (IsConstZero || 3920 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 3921 : (IsConstPos || (IsUnsigned && !Subtract))))) { 3922 SemaRef.Diag(NewStep->getExprLoc(), 3923 diag::err_omp_loop_incr_not_compatible) 3924 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 3925 SemaRef.Diag(ConditionLoc, 3926 diag::note_omp_loop_cond_requres_compatible_incr) 3927 << TestIsLessOp << ConditionSrcRange; 3928 return true; 3929 } 3930 if (TestIsLessOp == Subtract) { 3931 NewStep = 3932 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 3933 .get(); 3934 Subtract = !Subtract; 3935 } 3936 } 3937 3938 Step = NewStep; 3939 SubtractStep = Subtract; 3940 return false; 3941 } 3942 3943 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 3944 // Check init-expr for canonical loop form and save loop counter 3945 // variable - #Var and its initialization value - #LB. 3946 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 3947 // var = lb 3948 // integer-type var = lb 3949 // random-access-iterator-type var = lb 3950 // pointer-type var = lb 3951 // 3952 if (!S) { 3953 if (EmitDiags) { 3954 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 3955 } 3956 return true; 3957 } 3958 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3959 if (!ExprTemp->cleanupsHaveSideEffects()) 3960 S = ExprTemp->getSubExpr(); 3961 3962 InitSrcRange = S->getSourceRange(); 3963 if (Expr *E = dyn_cast<Expr>(S)) 3964 S = E->IgnoreParens(); 3965 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3966 if (BO->getOpcode() == BO_Assign) { 3967 Expr *LHS = BO->getLHS()->IgnoreParens(); 3968 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3969 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3970 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3971 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3972 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 3973 } 3974 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3975 if (ME->isArrow() && 3976 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3977 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3978 } 3979 } 3980 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 3981 if (DS->isSingleDecl()) { 3982 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 3983 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 3984 // Accept non-canonical init form here but emit ext. warning. 3985 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 3986 SemaRef.Diag(S->getBeginLoc(), 3987 diag::ext_omp_loop_not_canonical_init) 3988 << S->getSourceRange(); 3989 return setLCDeclAndLB( 3990 Var, 3991 buildDeclRefExpr(SemaRef, Var, 3992 Var->getType().getNonReferenceType(), 3993 DS->getBeginLoc()), 3994 Var->getInit()); 3995 } 3996 } 3997 } 3998 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3999 if (CE->getOperator() == OO_Equal) { 4000 Expr *LHS = CE->getArg(0); 4001 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 4002 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 4003 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4004 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4005 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 4006 } 4007 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 4008 if (ME->isArrow() && 4009 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4010 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4011 } 4012 } 4013 } 4014 4015 if (dependent() || SemaRef.CurContext->isDependentContext()) 4016 return false; 4017 if (EmitDiags) { 4018 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 4019 << S->getSourceRange(); 4020 } 4021 return true; 4022 } 4023 4024 /// Ignore parenthesizes, implicit casts, copy constructor and return the 4025 /// variable (which may be the loop variable) if possible. 4026 static const ValueDecl *getInitLCDecl(const Expr *E) { 4027 if (!E) 4028 return nullptr; 4029 E = getExprAsWritten(E); 4030 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 4031 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 4032 if ((Ctor->isCopyOrMoveConstructor() || 4033 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 4034 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 4035 E = CE->getArg(0)->IgnoreParenImpCasts(); 4036 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 4037 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 4038 return getCanonicalDecl(VD); 4039 } 4040 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 4041 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4042 return getCanonicalDecl(ME->getMemberDecl()); 4043 return nullptr; 4044 } 4045 4046 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 4047 // Check test-expr for canonical form, save upper-bound UB, flags for 4048 // less/greater and for strict/non-strict comparison. 4049 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 4050 // var relational-op b 4051 // b relational-op var 4052 // 4053 if (!S) { 4054 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 4055 return true; 4056 } 4057 S = getExprAsWritten(S); 4058 SourceLocation CondLoc = S->getBeginLoc(); 4059 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 4060 if (BO->isRelationalOp()) { 4061 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4062 return setUB(BO->getRHS(), 4063 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 4064 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 4065 BO->getSourceRange(), BO->getOperatorLoc()); 4066 if (getInitLCDecl(BO->getRHS()) == LCDecl) 4067 return setUB(BO->getLHS(), 4068 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 4069 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 4070 BO->getSourceRange(), BO->getOperatorLoc()); 4071 } 4072 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4073 if (CE->getNumArgs() == 2) { 4074 auto Op = CE->getOperator(); 4075 switch (Op) { 4076 case OO_Greater: 4077 case OO_GreaterEqual: 4078 case OO_Less: 4079 case OO_LessEqual: 4080 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4081 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 4082 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 4083 CE->getOperatorLoc()); 4084 if (getInitLCDecl(CE->getArg(1)) == LCDecl) 4085 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 4086 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 4087 CE->getOperatorLoc()); 4088 break; 4089 default: 4090 break; 4091 } 4092 } 4093 } 4094 if (dependent() || SemaRef.CurContext->isDependentContext()) 4095 return false; 4096 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 4097 << S->getSourceRange() << LCDecl; 4098 return true; 4099 } 4100 4101 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 4102 // RHS of canonical loop form increment can be: 4103 // var + incr 4104 // incr + var 4105 // var - incr 4106 // 4107 RHS = RHS->IgnoreParenImpCasts(); 4108 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 4109 if (BO->isAdditiveOp()) { 4110 bool IsAdd = BO->getOpcode() == BO_Add; 4111 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4112 return setStep(BO->getRHS(), !IsAdd); 4113 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 4114 return setStep(BO->getLHS(), /*Subtract=*/false); 4115 } 4116 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 4117 bool IsAdd = CE->getOperator() == OO_Plus; 4118 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 4119 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4120 return setStep(CE->getArg(1), !IsAdd); 4121 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 4122 return setStep(CE->getArg(0), /*Subtract=*/false); 4123 } 4124 } 4125 if (dependent() || SemaRef.CurContext->isDependentContext()) 4126 return false; 4127 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 4128 << RHS->getSourceRange() << LCDecl; 4129 return true; 4130 } 4131 4132 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 4133 // Check incr-expr for canonical loop form and return true if it 4134 // does not conform. 4135 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 4136 // ++var 4137 // var++ 4138 // --var 4139 // var-- 4140 // var += incr 4141 // var -= incr 4142 // var = var + incr 4143 // var = incr + var 4144 // var = var - incr 4145 // 4146 if (!S) { 4147 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 4148 return true; 4149 } 4150 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 4151 if (!ExprTemp->cleanupsHaveSideEffects()) 4152 S = ExprTemp->getSubExpr(); 4153 4154 IncrementSrcRange = S->getSourceRange(); 4155 S = S->IgnoreParens(); 4156 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 4157 if (UO->isIncrementDecrementOp() && 4158 getInitLCDecl(UO->getSubExpr()) == LCDecl) 4159 return setStep(SemaRef 4160 .ActOnIntegerConstant(UO->getBeginLoc(), 4161 (UO->isDecrementOp() ? -1 : 1)) 4162 .get(), 4163 /*Subtract=*/false); 4164 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 4165 switch (BO->getOpcode()) { 4166 case BO_AddAssign: 4167 case BO_SubAssign: 4168 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4169 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 4170 break; 4171 case BO_Assign: 4172 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4173 return checkAndSetIncRHS(BO->getRHS()); 4174 break; 4175 default: 4176 break; 4177 } 4178 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4179 switch (CE->getOperator()) { 4180 case OO_PlusPlus: 4181 case OO_MinusMinus: 4182 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4183 return setStep(SemaRef 4184 .ActOnIntegerConstant( 4185 CE->getBeginLoc(), 4186 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 4187 .get(), 4188 /*Subtract=*/false); 4189 break; 4190 case OO_PlusEqual: 4191 case OO_MinusEqual: 4192 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4193 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 4194 break; 4195 case OO_Equal: 4196 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4197 return checkAndSetIncRHS(CE->getArg(1)); 4198 break; 4199 default: 4200 break; 4201 } 4202 } 4203 if (dependent() || SemaRef.CurContext->isDependentContext()) 4204 return false; 4205 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 4206 << S->getSourceRange() << LCDecl; 4207 return true; 4208 } 4209 4210 static ExprResult 4211 tryBuildCapture(Sema &SemaRef, Expr *Capture, 4212 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 4213 if (SemaRef.CurContext->isDependentContext()) 4214 return ExprResult(Capture); 4215 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 4216 return SemaRef.PerformImplicitConversion( 4217 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 4218 /*AllowExplicit=*/true); 4219 auto I = Captures.find(Capture); 4220 if (I != Captures.end()) 4221 return buildCapture(SemaRef, Capture, I->second); 4222 DeclRefExpr *Ref = nullptr; 4223 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 4224 Captures[Capture] = Ref; 4225 return Res; 4226 } 4227 4228 /// Build the expression to calculate the number of iterations. 4229 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 4230 Scope *S, const bool LimitedType, 4231 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 4232 ExprResult Diff; 4233 QualType VarType = LCDecl->getType().getNonReferenceType(); 4234 if (VarType->isIntegerType() || VarType->isPointerType() || 4235 SemaRef.getLangOpts().CPlusPlus) { 4236 // Upper - Lower 4237 Expr *UBExpr = TestIsLessOp ? UB : LB; 4238 Expr *LBExpr = TestIsLessOp ? LB : UB; 4239 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 4240 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 4241 if (!Upper || !Lower) 4242 return nullptr; 4243 4244 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 4245 4246 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 4247 // BuildBinOp already emitted error, this one is to point user to upper 4248 // and lower bound, and to tell what is passed to 'operator-'. 4249 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 4250 << Upper->getSourceRange() << Lower->getSourceRange(); 4251 return nullptr; 4252 } 4253 } 4254 4255 if (!Diff.isUsable()) 4256 return nullptr; 4257 4258 // Upper - Lower [- 1] 4259 if (TestIsStrictOp) 4260 Diff = SemaRef.BuildBinOp( 4261 S, DefaultLoc, BO_Sub, Diff.get(), 4262 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4263 if (!Diff.isUsable()) 4264 return nullptr; 4265 4266 // Upper - Lower [- 1] + Step 4267 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 4268 if (!NewStep.isUsable()) 4269 return nullptr; 4270 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 4271 if (!Diff.isUsable()) 4272 return nullptr; 4273 4274 // Parentheses (for dumping/debugging purposes only). 4275 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 4276 if (!Diff.isUsable()) 4277 return nullptr; 4278 4279 // (Upper - Lower [- 1] + Step) / Step 4280 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 4281 if (!Diff.isUsable()) 4282 return nullptr; 4283 4284 // OpenMP runtime requires 32-bit or 64-bit loop variables. 4285 QualType Type = Diff.get()->getType(); 4286 ASTContext &C = SemaRef.Context; 4287 bool UseVarType = VarType->hasIntegerRepresentation() && 4288 C.getTypeSize(Type) > C.getTypeSize(VarType); 4289 if (!Type->isIntegerType() || UseVarType) { 4290 unsigned NewSize = 4291 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 4292 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 4293 : Type->hasSignedIntegerRepresentation(); 4294 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 4295 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 4296 Diff = SemaRef.PerformImplicitConversion( 4297 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 4298 if (!Diff.isUsable()) 4299 return nullptr; 4300 } 4301 } 4302 if (LimitedType) { 4303 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 4304 if (NewSize != C.getTypeSize(Type)) { 4305 if (NewSize < C.getTypeSize(Type)) { 4306 assert(NewSize == 64 && "incorrect loop var size"); 4307 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 4308 << InitSrcRange << ConditionSrcRange; 4309 } 4310 QualType NewType = C.getIntTypeForBitwidth( 4311 NewSize, Type->hasSignedIntegerRepresentation() || 4312 C.getTypeSize(Type) < NewSize); 4313 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 4314 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 4315 Sema::AA_Converting, true); 4316 if (!Diff.isUsable()) 4317 return nullptr; 4318 } 4319 } 4320 } 4321 4322 return Diff.get(); 4323 } 4324 4325 Expr *OpenMPIterationSpaceChecker::buildPreCond( 4326 Scope *S, Expr *Cond, 4327 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 4328 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 4329 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4330 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4331 4332 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 4333 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 4334 if (!NewLB.isUsable() || !NewUB.isUsable()) 4335 return nullptr; 4336 4337 ExprResult CondExpr = 4338 SemaRef.BuildBinOp(S, DefaultLoc, 4339 TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 4340 : (TestIsStrictOp ? BO_GT : BO_GE), 4341 NewLB.get(), NewUB.get()); 4342 if (CondExpr.isUsable()) { 4343 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 4344 SemaRef.Context.BoolTy)) 4345 CondExpr = SemaRef.PerformImplicitConversion( 4346 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 4347 /*AllowExplicit=*/true); 4348 } 4349 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4350 // Otherwise use original loop conditon and evaluate it in runtime. 4351 return CondExpr.isUsable() ? CondExpr.get() : Cond; 4352 } 4353 4354 /// Build reference expression to the counter be used for codegen. 4355 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 4356 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 4357 DSAStackTy &DSA) const { 4358 auto *VD = dyn_cast<VarDecl>(LCDecl); 4359 if (!VD) { 4360 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 4361 DeclRefExpr *Ref = buildDeclRefExpr( 4362 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 4363 const DSAStackTy::DSAVarData Data = 4364 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 4365 // If the loop control decl is explicitly marked as private, do not mark it 4366 // as captured again. 4367 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 4368 Captures.insert(std::make_pair(LCRef, Ref)); 4369 return Ref; 4370 } 4371 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 4372 DefaultLoc); 4373 } 4374 4375 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 4376 if (LCDecl && !LCDecl->isInvalidDecl()) { 4377 QualType Type = LCDecl->getType().getNonReferenceType(); 4378 VarDecl *PrivateVar = buildVarDecl( 4379 SemaRef, DefaultLoc, Type, LCDecl->getName(), 4380 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 4381 isa<VarDecl>(LCDecl) 4382 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 4383 : nullptr); 4384 if (PrivateVar->isInvalidDecl()) 4385 return nullptr; 4386 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 4387 } 4388 return nullptr; 4389 } 4390 4391 /// Build initialization of the counter to be used for codegen. 4392 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 4393 4394 /// Build step of the counter be used for codegen. 4395 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 4396 4397 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 4398 Scope *S, Expr *Counter, 4399 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 4400 Expr *Inc, OverloadedOperatorKind OOK) { 4401 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 4402 if (!Cnt) 4403 return nullptr; 4404 if (Inc) { 4405 assert((OOK == OO_Plus || OOK == OO_Minus) && 4406 "Expected only + or - operations for depend clauses."); 4407 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 4408 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 4409 if (!Cnt) 4410 return nullptr; 4411 } 4412 ExprResult Diff; 4413 QualType VarType = LCDecl->getType().getNonReferenceType(); 4414 if (VarType->isIntegerType() || VarType->isPointerType() || 4415 SemaRef.getLangOpts().CPlusPlus) { 4416 // Upper - Lower 4417 Expr *Upper = 4418 TestIsLessOp ? Cnt : tryBuildCapture(SemaRef, UB, Captures).get(); 4419 Expr *Lower = 4420 TestIsLessOp ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt; 4421 if (!Upper || !Lower) 4422 return nullptr; 4423 4424 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 4425 4426 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 4427 // BuildBinOp already emitted error, this one is to point user to upper 4428 // and lower bound, and to tell what is passed to 'operator-'. 4429 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 4430 << Upper->getSourceRange() << Lower->getSourceRange(); 4431 return nullptr; 4432 } 4433 } 4434 4435 if (!Diff.isUsable()) 4436 return nullptr; 4437 4438 // Parentheses (for dumping/debugging purposes only). 4439 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 4440 if (!Diff.isUsable()) 4441 return nullptr; 4442 4443 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 4444 if (!NewStep.isUsable()) 4445 return nullptr; 4446 // (Upper - Lower) / Step 4447 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 4448 if (!Diff.isUsable()) 4449 return nullptr; 4450 4451 return Diff.get(); 4452 } 4453 4454 /// Iteration space of a single for loop. 4455 struct LoopIterationSpace final { 4456 /// Condition of the loop. 4457 Expr *PreCond = nullptr; 4458 /// This expression calculates the number of iterations in the loop. 4459 /// It is always possible to calculate it before starting the loop. 4460 Expr *NumIterations = nullptr; 4461 /// The loop counter variable. 4462 Expr *CounterVar = nullptr; 4463 /// Private loop counter variable. 4464 Expr *PrivateCounterVar = nullptr; 4465 /// This is initializer for the initial value of #CounterVar. 4466 Expr *CounterInit = nullptr; 4467 /// This is step for the #CounterVar used to generate its update: 4468 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 4469 Expr *CounterStep = nullptr; 4470 /// Should step be subtracted? 4471 bool Subtract = false; 4472 /// Source range of the loop init. 4473 SourceRange InitSrcRange; 4474 /// Source range of the loop condition. 4475 SourceRange CondSrcRange; 4476 /// Source range of the loop increment. 4477 SourceRange IncSrcRange; 4478 }; 4479 4480 } // namespace 4481 4482 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 4483 assert(getLangOpts().OpenMP && "OpenMP is not active."); 4484 assert(Init && "Expected loop in canonical form."); 4485 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 4486 if (AssociatedLoops > 0 && 4487 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 4488 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 4489 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 4490 if (ValueDecl *D = ISC.getLoopDecl()) { 4491 auto *VD = dyn_cast<VarDecl>(D); 4492 if (!VD) { 4493 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 4494 VD = Private; 4495 } else { 4496 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 4497 /*WithInit=*/false); 4498 VD = cast<VarDecl>(Ref->getDecl()); 4499 } 4500 } 4501 DSAStack->addLoopControlVariable(D, VD); 4502 } 4503 } 4504 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 4505 } 4506 } 4507 4508 /// Called on a for stmt to check and extract its iteration space 4509 /// for further processing (such as collapsing). 4510 static bool checkOpenMPIterationSpace( 4511 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 4512 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 4513 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 4514 Expr *OrderedLoopCountExpr, 4515 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 4516 LoopIterationSpace &ResultIterSpace, 4517 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 4518 // OpenMP [2.6, Canonical Loop Form] 4519 // for (init-expr; test-expr; incr-expr) structured-block 4520 auto *For = dyn_cast_or_null<ForStmt>(S); 4521 if (!For) { 4522 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 4523 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 4524 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 4525 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 4526 if (TotalNestedLoopCount > 1) { 4527 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 4528 SemaRef.Diag(DSA.getConstructLoc(), 4529 diag::note_omp_collapse_ordered_expr) 4530 << 2 << CollapseLoopCountExpr->getSourceRange() 4531 << OrderedLoopCountExpr->getSourceRange(); 4532 else if (CollapseLoopCountExpr) 4533 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4534 diag::note_omp_collapse_ordered_expr) 4535 << 0 << CollapseLoopCountExpr->getSourceRange(); 4536 else 4537 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4538 diag::note_omp_collapse_ordered_expr) 4539 << 1 << OrderedLoopCountExpr->getSourceRange(); 4540 } 4541 return true; 4542 } 4543 assert(For->getBody()); 4544 4545 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 4546 4547 // Check init. 4548 Stmt *Init = For->getInit(); 4549 if (ISC.checkAndSetInit(Init)) 4550 return true; 4551 4552 bool HasErrors = false; 4553 4554 // Check loop variable's type. 4555 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 4556 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 4557 4558 // OpenMP [2.6, Canonical Loop Form] 4559 // Var is one of the following: 4560 // A variable of signed or unsigned integer type. 4561 // For C++, a variable of a random access iterator type. 4562 // For C, a variable of a pointer type. 4563 QualType VarType = LCDecl->getType().getNonReferenceType(); 4564 if (!VarType->isDependentType() && !VarType->isIntegerType() && 4565 !VarType->isPointerType() && 4566 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 4567 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 4568 << SemaRef.getLangOpts().CPlusPlus; 4569 HasErrors = true; 4570 } 4571 4572 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 4573 // a Construct 4574 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4575 // parallel for construct is (are) private. 4576 // The loop iteration variable in the associated for-loop of a simd 4577 // construct with just one associated for-loop is linear with a 4578 // constant-linear-step that is the increment of the associated for-loop. 4579 // Exclude loop var from the list of variables with implicitly defined data 4580 // sharing attributes. 4581 VarsWithImplicitDSA.erase(LCDecl); 4582 4583 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4584 // in a Construct, C/C++]. 4585 // The loop iteration variable in the associated for-loop of a simd 4586 // construct with just one associated for-loop may be listed in a linear 4587 // clause with a constant-linear-step that is the increment of the 4588 // associated for-loop. 4589 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4590 // parallel for construct may be listed in a private or lastprivate clause. 4591 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 4592 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 4593 // declared in the loop and it is predetermined as a private. 4594 OpenMPClauseKind PredeterminedCKind = 4595 isOpenMPSimdDirective(DKind) 4596 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 4597 : OMPC_private; 4598 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4599 DVar.CKind != PredeterminedCKind) || 4600 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 4601 isOpenMPDistributeDirective(DKind)) && 4602 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4603 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 4604 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 4605 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 4606 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 4607 << getOpenMPClauseName(PredeterminedCKind); 4608 if (DVar.RefExpr == nullptr) 4609 DVar.CKind = PredeterminedCKind; 4610 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 4611 HasErrors = true; 4612 } else if (LoopDeclRefExpr != nullptr) { 4613 // Make the loop iteration variable private (for worksharing constructs), 4614 // linear (for simd directives with the only one associated loop) or 4615 // lastprivate (for simd directives with several collapsed or ordered 4616 // loops). 4617 if (DVar.CKind == OMPC_unknown) 4618 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 4619 [](OpenMPDirectiveKind) -> bool { return true; }, 4620 /*FromParent=*/false); 4621 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 4622 } 4623 4624 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 4625 4626 // Check test-expr. 4627 HasErrors |= ISC.checkAndSetCond(For->getCond()); 4628 4629 // Check incr-expr. 4630 HasErrors |= ISC.checkAndSetInc(For->getInc()); 4631 } 4632 4633 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 4634 return HasErrors; 4635 4636 // Build the loop's iteration space representation. 4637 ResultIterSpace.PreCond = 4638 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures); 4639 ResultIterSpace.NumIterations = ISC.buildNumIterations( 4640 DSA.getCurScope(), 4641 (isOpenMPWorksharingDirective(DKind) || 4642 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 4643 Captures); 4644 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA); 4645 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar(); 4646 ResultIterSpace.CounterInit = ISC.buildCounterInit(); 4647 ResultIterSpace.CounterStep = ISC.buildCounterStep(); 4648 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange(); 4649 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange(); 4650 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange(); 4651 ResultIterSpace.Subtract = ISC.shouldSubtractStep(); 4652 4653 HasErrors |= (ResultIterSpace.PreCond == nullptr || 4654 ResultIterSpace.NumIterations == nullptr || 4655 ResultIterSpace.CounterVar == nullptr || 4656 ResultIterSpace.PrivateCounterVar == nullptr || 4657 ResultIterSpace.CounterInit == nullptr || 4658 ResultIterSpace.CounterStep == nullptr); 4659 if (!HasErrors && DSA.isOrderedRegion()) { 4660 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 4661 if (CurrentNestedLoopCount < 4662 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 4663 DSA.getOrderedRegionParam().second->setLoopNumIterations( 4664 CurrentNestedLoopCount, ResultIterSpace.NumIterations); 4665 DSA.getOrderedRegionParam().second->setLoopCounter( 4666 CurrentNestedLoopCount, ResultIterSpace.CounterVar); 4667 } 4668 } 4669 for (auto &Pair : DSA.getDoacrossDependClauses()) { 4670 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 4671 // Erroneous case - clause has some problems. 4672 continue; 4673 } 4674 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 4675 Pair.second.size() <= CurrentNestedLoopCount) { 4676 // Erroneous case - clause has some problems. 4677 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 4678 continue; 4679 } 4680 Expr *CntValue; 4681 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 4682 CntValue = ISC.buildOrderedLoopData( 4683 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures, 4684 Pair.first->getDependencyLoc()); 4685 else 4686 CntValue = ISC.buildOrderedLoopData( 4687 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures, 4688 Pair.first->getDependencyLoc(), 4689 Pair.second[CurrentNestedLoopCount].first, 4690 Pair.second[CurrentNestedLoopCount].second); 4691 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 4692 } 4693 } 4694 4695 return HasErrors; 4696 } 4697 4698 /// Build 'VarRef = Start. 4699 static ExprResult 4700 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 4701 ExprResult Start, 4702 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 4703 // Build 'VarRef = Start. 4704 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 4705 if (!NewStart.isUsable()) 4706 return ExprError(); 4707 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 4708 VarRef.get()->getType())) { 4709 NewStart = SemaRef.PerformImplicitConversion( 4710 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 4711 /*AllowExplicit=*/true); 4712 if (!NewStart.isUsable()) 4713 return ExprError(); 4714 } 4715 4716 ExprResult Init = 4717 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4718 return Init; 4719 } 4720 4721 /// Build 'VarRef = Start + Iter * Step'. 4722 static ExprResult buildCounterUpdate( 4723 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 4724 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 4725 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 4726 // Add parentheses (for debugging purposes only). 4727 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 4728 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 4729 !Step.isUsable()) 4730 return ExprError(); 4731 4732 ExprResult NewStep = Step; 4733 if (Captures) 4734 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 4735 if (NewStep.isInvalid()) 4736 return ExprError(); 4737 ExprResult Update = 4738 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 4739 if (!Update.isUsable()) 4740 return ExprError(); 4741 4742 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 4743 // 'VarRef = Start (+|-) Iter * Step'. 4744 ExprResult NewStart = Start; 4745 if (Captures) 4746 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 4747 if (NewStart.isInvalid()) 4748 return ExprError(); 4749 4750 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 4751 ExprResult SavedUpdate = Update; 4752 ExprResult UpdateVal; 4753 if (VarRef.get()->getType()->isOverloadableType() || 4754 NewStart.get()->getType()->isOverloadableType() || 4755 Update.get()->getType()->isOverloadableType()) { 4756 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4757 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4758 Update = 4759 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4760 if (Update.isUsable()) { 4761 UpdateVal = 4762 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 4763 VarRef.get(), SavedUpdate.get()); 4764 if (UpdateVal.isUsable()) { 4765 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 4766 UpdateVal.get()); 4767 } 4768 } 4769 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4770 } 4771 4772 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 4773 if (!Update.isUsable() || !UpdateVal.isUsable()) { 4774 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 4775 NewStart.get(), SavedUpdate.get()); 4776 if (!Update.isUsable()) 4777 return ExprError(); 4778 4779 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 4780 VarRef.get()->getType())) { 4781 Update = SemaRef.PerformImplicitConversion( 4782 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 4783 if (!Update.isUsable()) 4784 return ExprError(); 4785 } 4786 4787 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 4788 } 4789 return Update; 4790 } 4791 4792 /// Convert integer expression \a E to make it have at least \a Bits 4793 /// bits. 4794 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 4795 if (E == nullptr) 4796 return ExprError(); 4797 ASTContext &C = SemaRef.Context; 4798 QualType OldType = E->getType(); 4799 unsigned HasBits = C.getTypeSize(OldType); 4800 if (HasBits >= Bits) 4801 return ExprResult(E); 4802 // OK to convert to signed, because new type has more bits than old. 4803 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 4804 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 4805 true); 4806 } 4807 4808 /// Check if the given expression \a E is a constant integer that fits 4809 /// into \a Bits bits. 4810 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 4811 if (E == nullptr) 4812 return false; 4813 llvm::APSInt Result; 4814 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 4815 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 4816 return false; 4817 } 4818 4819 /// Build preinits statement for the given declarations. 4820 static Stmt *buildPreInits(ASTContext &Context, 4821 MutableArrayRef<Decl *> PreInits) { 4822 if (!PreInits.empty()) { 4823 return new (Context) DeclStmt( 4824 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 4825 SourceLocation(), SourceLocation()); 4826 } 4827 return nullptr; 4828 } 4829 4830 /// Build preinits statement for the given declarations. 4831 static Stmt * 4832 buildPreInits(ASTContext &Context, 4833 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 4834 if (!Captures.empty()) { 4835 SmallVector<Decl *, 16> PreInits; 4836 for (const auto &Pair : Captures) 4837 PreInits.push_back(Pair.second->getDecl()); 4838 return buildPreInits(Context, PreInits); 4839 } 4840 return nullptr; 4841 } 4842 4843 /// Build postupdate expression for the given list of postupdates expressions. 4844 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 4845 Expr *PostUpdate = nullptr; 4846 if (!PostUpdates.empty()) { 4847 for (Expr *E : PostUpdates) { 4848 Expr *ConvE = S.BuildCStyleCastExpr( 4849 E->getExprLoc(), 4850 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 4851 E->getExprLoc(), E) 4852 .get(); 4853 PostUpdate = PostUpdate 4854 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 4855 PostUpdate, ConvE) 4856 .get() 4857 : ConvE; 4858 } 4859 } 4860 return PostUpdate; 4861 } 4862 4863 /// Called on a for stmt to check itself and nested loops (if any). 4864 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 4865 /// number of collapsed loops otherwise. 4866 static unsigned 4867 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 4868 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 4869 DSAStackTy &DSA, 4870 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 4871 OMPLoopDirective::HelperExprs &Built) { 4872 unsigned NestedLoopCount = 1; 4873 if (CollapseLoopCountExpr) { 4874 // Found 'collapse' clause - calculate collapse number. 4875 llvm::APSInt Result; 4876 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 4877 NestedLoopCount = Result.getLimitedValue(); 4878 } 4879 unsigned OrderedLoopCount = 1; 4880 if (OrderedLoopCountExpr) { 4881 // Found 'ordered' clause - calculate collapse number. 4882 llvm::APSInt Result; 4883 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 4884 if (Result.getLimitedValue() < NestedLoopCount) { 4885 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4886 diag::err_omp_wrong_ordered_loop_count) 4887 << OrderedLoopCountExpr->getSourceRange(); 4888 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4889 diag::note_collapse_loop_count) 4890 << CollapseLoopCountExpr->getSourceRange(); 4891 } 4892 OrderedLoopCount = Result.getLimitedValue(); 4893 } 4894 } 4895 // This is helper routine for loop directives (e.g., 'for', 'simd', 4896 // 'for simd', etc.). 4897 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 4898 SmallVector<LoopIterationSpace, 4> IterSpaces; 4899 IterSpaces.resize(std::max(OrderedLoopCount, NestedLoopCount)); 4900 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 4901 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 4902 if (checkOpenMPIterationSpace( 4903 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 4904 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 4905 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt], 4906 Captures)) 4907 return 0; 4908 // Move on to the next nested for loop, or to the loop body. 4909 // OpenMP [2.8.1, simd construct, Restrictions] 4910 // All loops associated with the construct must be perfectly nested; that 4911 // is, there must be no intervening code nor any OpenMP directive between 4912 // any two loops. 4913 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 4914 } 4915 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) { 4916 if (checkOpenMPIterationSpace( 4917 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 4918 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 4919 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt], 4920 Captures)) 4921 return 0; 4922 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) { 4923 // Handle initialization of captured loop iterator variables. 4924 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 4925 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 4926 Captures[DRE] = DRE; 4927 } 4928 } 4929 // Move on to the next nested for loop, or to the loop body. 4930 // OpenMP [2.8.1, simd construct, Restrictions] 4931 // All loops associated with the construct must be perfectly nested; that 4932 // is, there must be no intervening code nor any OpenMP directive between 4933 // any two loops. 4934 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 4935 } 4936 4937 Built.clear(/* size */ NestedLoopCount); 4938 4939 if (SemaRef.CurContext->isDependentContext()) 4940 return NestedLoopCount; 4941 4942 // An example of what is generated for the following code: 4943 // 4944 // #pragma omp simd collapse(2) ordered(2) 4945 // for (i = 0; i < NI; ++i) 4946 // for (k = 0; k < NK; ++k) 4947 // for (j = J0; j < NJ; j+=2) { 4948 // <loop body> 4949 // } 4950 // 4951 // We generate the code below. 4952 // Note: the loop body may be outlined in CodeGen. 4953 // Note: some counters may be C++ classes, operator- is used to find number of 4954 // iterations and operator+= to calculate counter value. 4955 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 4956 // or i64 is currently supported). 4957 // 4958 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 4959 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 4960 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 4961 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 4962 // // similar updates for vars in clauses (e.g. 'linear') 4963 // <loop body (using local i and j)> 4964 // } 4965 // i = NI; // assign final values of counters 4966 // j = NJ; 4967 // 4968 4969 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 4970 // the iteration counts of the collapsed for loops. 4971 // Precondition tests if there is at least one iteration (all conditions are 4972 // true). 4973 auto PreCond = ExprResult(IterSpaces[0].PreCond); 4974 Expr *N0 = IterSpaces[0].NumIterations; 4975 ExprResult LastIteration32 = 4976 widenIterationCount(/*Bits=*/32, 4977 SemaRef 4978 .PerformImplicitConversion( 4979 N0->IgnoreImpCasts(), N0->getType(), 4980 Sema::AA_Converting, /*AllowExplicit=*/true) 4981 .get(), 4982 SemaRef); 4983 ExprResult LastIteration64 = widenIterationCount( 4984 /*Bits=*/64, 4985 SemaRef 4986 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 4987 Sema::AA_Converting, 4988 /*AllowExplicit=*/true) 4989 .get(), 4990 SemaRef); 4991 4992 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 4993 return NestedLoopCount; 4994 4995 ASTContext &C = SemaRef.Context; 4996 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 4997 4998 Scope *CurScope = DSA.getCurScope(); 4999 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 5000 if (PreCond.isUsable()) { 5001 PreCond = 5002 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 5003 PreCond.get(), IterSpaces[Cnt].PreCond); 5004 } 5005 Expr *N = IterSpaces[Cnt].NumIterations; 5006 SourceLocation Loc = N->getExprLoc(); 5007 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 5008 if (LastIteration32.isUsable()) 5009 LastIteration32 = SemaRef.BuildBinOp( 5010 CurScope, Loc, BO_Mul, LastIteration32.get(), 5011 SemaRef 5012 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 5013 Sema::AA_Converting, 5014 /*AllowExplicit=*/true) 5015 .get()); 5016 if (LastIteration64.isUsable()) 5017 LastIteration64 = SemaRef.BuildBinOp( 5018 CurScope, Loc, BO_Mul, LastIteration64.get(), 5019 SemaRef 5020 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 5021 Sema::AA_Converting, 5022 /*AllowExplicit=*/true) 5023 .get()); 5024 } 5025 5026 // Choose either the 32-bit or 64-bit version. 5027 ExprResult LastIteration = LastIteration64; 5028 if (LastIteration32.isUsable() && 5029 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 5030 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 5031 fitsInto( 5032 /*Bits=*/32, 5033 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 5034 LastIteration64.get(), SemaRef))) 5035 LastIteration = LastIteration32; 5036 QualType VType = LastIteration.get()->getType(); 5037 QualType RealVType = VType; 5038 QualType StrideVType = VType; 5039 if (isOpenMPTaskLoopDirective(DKind)) { 5040 VType = 5041 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 5042 StrideVType = 5043 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 5044 } 5045 5046 if (!LastIteration.isUsable()) 5047 return 0; 5048 5049 // Save the number of iterations. 5050 ExprResult NumIterations = LastIteration; 5051 { 5052 LastIteration = SemaRef.BuildBinOp( 5053 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 5054 LastIteration.get(), 5055 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5056 if (!LastIteration.isUsable()) 5057 return 0; 5058 } 5059 5060 // Calculate the last iteration number beforehand instead of doing this on 5061 // each iteration. Do not do this if the number of iterations may be kfold-ed. 5062 llvm::APSInt Result; 5063 bool IsConstant = 5064 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 5065 ExprResult CalcLastIteration; 5066 if (!IsConstant) { 5067 ExprResult SaveRef = 5068 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 5069 LastIteration = SaveRef; 5070 5071 // Prepare SaveRef + 1. 5072 NumIterations = SemaRef.BuildBinOp( 5073 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 5074 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5075 if (!NumIterations.isUsable()) 5076 return 0; 5077 } 5078 5079 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 5080 5081 // Build variables passed into runtime, necessary for worksharing directives. 5082 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 5083 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 5084 isOpenMPDistributeDirective(DKind)) { 5085 // Lower bound variable, initialized with zero. 5086 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 5087 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 5088 SemaRef.AddInitializerToDecl(LBDecl, 5089 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5090 /*DirectInit*/ false); 5091 5092 // Upper bound variable, initialized with last iteration number. 5093 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 5094 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 5095 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 5096 /*DirectInit*/ false); 5097 5098 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 5099 // This will be used to implement clause 'lastprivate'. 5100 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 5101 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 5102 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 5103 SemaRef.AddInitializerToDecl(ILDecl, 5104 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5105 /*DirectInit*/ false); 5106 5107 // Stride variable returned by runtime (we initialize it to 1 by default). 5108 VarDecl *STDecl = 5109 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 5110 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 5111 SemaRef.AddInitializerToDecl(STDecl, 5112 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 5113 /*DirectInit*/ false); 5114 5115 // Build expression: UB = min(UB, LastIteration) 5116 // It is necessary for CodeGen of directives with static scheduling. 5117 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 5118 UB.get(), LastIteration.get()); 5119 ExprResult CondOp = SemaRef.ActOnConditionalOp( 5120 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 5121 LastIteration.get(), UB.get()); 5122 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 5123 CondOp.get()); 5124 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 5125 5126 // If we have a combined directive that combines 'distribute', 'for' or 5127 // 'simd' we need to be able to access the bounds of the schedule of the 5128 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 5129 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 5130 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5131 // Lower bound variable, initialized with zero. 5132 VarDecl *CombLBDecl = 5133 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 5134 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 5135 SemaRef.AddInitializerToDecl( 5136 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5137 /*DirectInit*/ false); 5138 5139 // Upper bound variable, initialized with last iteration number. 5140 VarDecl *CombUBDecl = 5141 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 5142 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 5143 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 5144 /*DirectInit*/ false); 5145 5146 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 5147 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 5148 ExprResult CombCondOp = 5149 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 5150 LastIteration.get(), CombUB.get()); 5151 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 5152 CombCondOp.get()); 5153 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get()); 5154 5155 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 5156 // We expect to have at least 2 more parameters than the 'parallel' 5157 // directive does - the lower and upper bounds of the previous schedule. 5158 assert(CD->getNumParams() >= 4 && 5159 "Unexpected number of parameters in loop combined directive"); 5160 5161 // Set the proper type for the bounds given what we learned from the 5162 // enclosed loops. 5163 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 5164 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 5165 5166 // Previous lower and upper bounds are obtained from the region 5167 // parameters. 5168 PrevLB = 5169 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 5170 PrevUB = 5171 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 5172 } 5173 } 5174 5175 // Build the iteration variable and its initialization before loop. 5176 ExprResult IV; 5177 ExprResult Init, CombInit; 5178 { 5179 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 5180 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 5181 Expr *RHS = 5182 (isOpenMPWorksharingDirective(DKind) || 5183 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 5184 ? LB.get() 5185 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 5186 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 5187 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 5188 5189 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5190 Expr *CombRHS = 5191 (isOpenMPWorksharingDirective(DKind) || 5192 isOpenMPTaskLoopDirective(DKind) || 5193 isOpenMPDistributeDirective(DKind)) 5194 ? CombLB.get() 5195 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 5196 CombInit = 5197 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 5198 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get()); 5199 } 5200 } 5201 5202 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 5203 SourceLocation CondLoc = AStmt->getBeginLoc(); 5204 ExprResult Cond = 5205 (isOpenMPWorksharingDirective(DKind) || 5206 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 5207 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 5208 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 5209 NumIterations.get()); 5210 ExprResult CombCond; 5211 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5212 CombCond = 5213 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get()); 5214 } 5215 // Loop increment (IV = IV + 1) 5216 SourceLocation IncLoc = AStmt->getBeginLoc(); 5217 ExprResult Inc = 5218 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 5219 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 5220 if (!Inc.isUsable()) 5221 return 0; 5222 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 5223 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 5224 if (!Inc.isUsable()) 5225 return 0; 5226 5227 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 5228 // Used for directives with static scheduling. 5229 // In combined construct, add combined version that use CombLB and CombUB 5230 // base variables for the update 5231 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 5232 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 5233 isOpenMPDistributeDirective(DKind)) { 5234 // LB + ST 5235 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 5236 if (!NextLB.isUsable()) 5237 return 0; 5238 // LB = LB + ST 5239 NextLB = 5240 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 5241 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 5242 if (!NextLB.isUsable()) 5243 return 0; 5244 // UB + ST 5245 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 5246 if (!NextUB.isUsable()) 5247 return 0; 5248 // UB = UB + ST 5249 NextUB = 5250 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 5251 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 5252 if (!NextUB.isUsable()) 5253 return 0; 5254 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5255 CombNextLB = 5256 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 5257 if (!NextLB.isUsable()) 5258 return 0; 5259 // LB = LB + ST 5260 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 5261 CombNextLB.get()); 5262 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get()); 5263 if (!CombNextLB.isUsable()) 5264 return 0; 5265 // UB + ST 5266 CombNextUB = 5267 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 5268 if (!CombNextUB.isUsable()) 5269 return 0; 5270 // UB = UB + ST 5271 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 5272 CombNextUB.get()); 5273 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get()); 5274 if (!CombNextUB.isUsable()) 5275 return 0; 5276 } 5277 } 5278 5279 // Create increment expression for distribute loop when combined in a same 5280 // directive with for as IV = IV + ST; ensure upper bound expression based 5281 // on PrevUB instead of NumIterations - used to implement 'for' when found 5282 // in combination with 'distribute', like in 'distribute parallel for' 5283 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 5284 ExprResult DistCond, DistInc, PrevEUB; 5285 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5286 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()); 5287 assert(DistCond.isUsable() && "distribute cond expr was not built"); 5288 5289 DistInc = 5290 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 5291 assert(DistInc.isUsable() && "distribute inc expr was not built"); 5292 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 5293 DistInc.get()); 5294 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get()); 5295 assert(DistInc.isUsable() && "distribute inc expr was not built"); 5296 5297 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 5298 // construct 5299 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 5300 ExprResult IsUBGreater = 5301 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 5302 ExprResult CondOp = SemaRef.ActOnConditionalOp( 5303 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 5304 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 5305 CondOp.get()); 5306 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get()); 5307 } 5308 5309 // Build updates and final values of the loop counters. 5310 bool HasErrors = false; 5311 Built.Counters.resize(NestedLoopCount); 5312 Built.Inits.resize(NestedLoopCount); 5313 Built.Updates.resize(NestedLoopCount); 5314 Built.Finals.resize(NestedLoopCount); 5315 { 5316 ExprResult Div; 5317 // Go from inner nested loop to outer. 5318 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 5319 LoopIterationSpace &IS = IterSpaces[Cnt]; 5320 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 5321 // Build: Iter = (IV / Div) % IS.NumIters 5322 // where Div is product of previous iterations' IS.NumIters. 5323 ExprResult Iter; 5324 if (Div.isUsable()) { 5325 Iter = 5326 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 5327 } else { 5328 Iter = IV; 5329 assert((Cnt == (int)NestedLoopCount - 1) && 5330 "unusable div expected on first iteration only"); 5331 } 5332 5333 if (Cnt != 0 && Iter.isUsable()) 5334 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 5335 IS.NumIterations); 5336 if (!Iter.isUsable()) { 5337 HasErrors = true; 5338 break; 5339 } 5340 5341 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 5342 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 5343 DeclRefExpr *CounterVar = buildDeclRefExpr( 5344 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 5345 /*RefersToCapture=*/true); 5346 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 5347 IS.CounterInit, Captures); 5348 if (!Init.isUsable()) { 5349 HasErrors = true; 5350 break; 5351 } 5352 ExprResult Update = buildCounterUpdate( 5353 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 5354 IS.CounterStep, IS.Subtract, &Captures); 5355 if (!Update.isUsable()) { 5356 HasErrors = true; 5357 break; 5358 } 5359 5360 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 5361 ExprResult Final = buildCounterUpdate( 5362 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 5363 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 5364 if (!Final.isUsable()) { 5365 HasErrors = true; 5366 break; 5367 } 5368 5369 // Build Div for the next iteration: Div <- Div * IS.NumIters 5370 if (Cnt != 0) { 5371 if (Div.isUnset()) 5372 Div = IS.NumIterations; 5373 else 5374 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 5375 IS.NumIterations); 5376 5377 // Add parentheses (for debugging purposes only). 5378 if (Div.isUsable()) 5379 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 5380 if (!Div.isUsable()) { 5381 HasErrors = true; 5382 break; 5383 } 5384 } 5385 if (!Update.isUsable() || !Final.isUsable()) { 5386 HasErrors = true; 5387 break; 5388 } 5389 // Save results 5390 Built.Counters[Cnt] = IS.CounterVar; 5391 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 5392 Built.Inits[Cnt] = Init.get(); 5393 Built.Updates[Cnt] = Update.get(); 5394 Built.Finals[Cnt] = Final.get(); 5395 } 5396 } 5397 5398 if (HasErrors) 5399 return 0; 5400 5401 // Save results 5402 Built.IterationVarRef = IV.get(); 5403 Built.LastIteration = LastIteration.get(); 5404 Built.NumIterations = NumIterations.get(); 5405 Built.CalcLastIteration = 5406 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 5407 Built.PreCond = PreCond.get(); 5408 Built.PreInits = buildPreInits(C, Captures); 5409 Built.Cond = Cond.get(); 5410 Built.Init = Init.get(); 5411 Built.Inc = Inc.get(); 5412 Built.LB = LB.get(); 5413 Built.UB = UB.get(); 5414 Built.IL = IL.get(); 5415 Built.ST = ST.get(); 5416 Built.EUB = EUB.get(); 5417 Built.NLB = NextLB.get(); 5418 Built.NUB = NextUB.get(); 5419 Built.PrevLB = PrevLB.get(); 5420 Built.PrevUB = PrevUB.get(); 5421 Built.DistInc = DistInc.get(); 5422 Built.PrevEUB = PrevEUB.get(); 5423 Built.DistCombinedFields.LB = CombLB.get(); 5424 Built.DistCombinedFields.UB = CombUB.get(); 5425 Built.DistCombinedFields.EUB = CombEUB.get(); 5426 Built.DistCombinedFields.Init = CombInit.get(); 5427 Built.DistCombinedFields.Cond = CombCond.get(); 5428 Built.DistCombinedFields.NLB = CombNextLB.get(); 5429 Built.DistCombinedFields.NUB = CombNextUB.get(); 5430 5431 return NestedLoopCount; 5432 } 5433 5434 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 5435 auto CollapseClauses = 5436 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 5437 if (CollapseClauses.begin() != CollapseClauses.end()) 5438 return (*CollapseClauses.begin())->getNumForLoops(); 5439 return nullptr; 5440 } 5441 5442 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 5443 auto OrderedClauses = 5444 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 5445 if (OrderedClauses.begin() != OrderedClauses.end()) 5446 return (*OrderedClauses.begin())->getNumForLoops(); 5447 return nullptr; 5448 } 5449 5450 static bool checkSimdlenSafelenSpecified(Sema &S, 5451 const ArrayRef<OMPClause *> Clauses) { 5452 const OMPSafelenClause *Safelen = nullptr; 5453 const OMPSimdlenClause *Simdlen = nullptr; 5454 5455 for (const OMPClause *Clause : Clauses) { 5456 if (Clause->getClauseKind() == OMPC_safelen) 5457 Safelen = cast<OMPSafelenClause>(Clause); 5458 else if (Clause->getClauseKind() == OMPC_simdlen) 5459 Simdlen = cast<OMPSimdlenClause>(Clause); 5460 if (Safelen && Simdlen) 5461 break; 5462 } 5463 5464 if (Simdlen && Safelen) { 5465 llvm::APSInt SimdlenRes, SafelenRes; 5466 const Expr *SimdlenLength = Simdlen->getSimdlen(); 5467 const Expr *SafelenLength = Safelen->getSafelen(); 5468 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 5469 SimdlenLength->isInstantiationDependent() || 5470 SimdlenLength->containsUnexpandedParameterPack()) 5471 return false; 5472 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 5473 SafelenLength->isInstantiationDependent() || 5474 SafelenLength->containsUnexpandedParameterPack()) 5475 return false; 5476 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 5477 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 5478 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 5479 // If both simdlen and safelen clauses are specified, the value of the 5480 // simdlen parameter must be less than or equal to the value of the safelen 5481 // parameter. 5482 if (SimdlenRes > SafelenRes) { 5483 S.Diag(SimdlenLength->getExprLoc(), 5484 diag::err_omp_wrong_simdlen_safelen_values) 5485 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 5486 return true; 5487 } 5488 } 5489 return false; 5490 } 5491 5492 StmtResult 5493 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 5494 SourceLocation StartLoc, SourceLocation EndLoc, 5495 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5496 if (!AStmt) 5497 return StmtError(); 5498 5499 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5500 OMPLoopDirective::HelperExprs B; 5501 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5502 // define the nested loops number. 5503 unsigned NestedLoopCount = checkOpenMPLoop( 5504 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5505 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5506 if (NestedLoopCount == 0) 5507 return StmtError(); 5508 5509 assert((CurContext->isDependentContext() || B.builtAll()) && 5510 "omp simd loop exprs were not built"); 5511 5512 if (!CurContext->isDependentContext()) { 5513 // Finalize the clauses that need pre-built expressions for CodeGen. 5514 for (OMPClause *C : Clauses) { 5515 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5516 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5517 B.NumIterations, *this, CurScope, 5518 DSAStack)) 5519 return StmtError(); 5520 } 5521 } 5522 5523 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5524 return StmtError(); 5525 5526 setFunctionHasBranchProtectedScope(); 5527 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5528 Clauses, AStmt, B); 5529 } 5530 5531 StmtResult 5532 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 5533 SourceLocation StartLoc, SourceLocation EndLoc, 5534 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5535 if (!AStmt) 5536 return StmtError(); 5537 5538 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5539 OMPLoopDirective::HelperExprs B; 5540 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5541 // define the nested loops number. 5542 unsigned NestedLoopCount = checkOpenMPLoop( 5543 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5544 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5545 if (NestedLoopCount == 0) 5546 return StmtError(); 5547 5548 assert((CurContext->isDependentContext() || B.builtAll()) && 5549 "omp for loop exprs were not built"); 5550 5551 if (!CurContext->isDependentContext()) { 5552 // Finalize the clauses that need pre-built expressions for CodeGen. 5553 for (OMPClause *C : Clauses) { 5554 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5555 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5556 B.NumIterations, *this, CurScope, 5557 DSAStack)) 5558 return StmtError(); 5559 } 5560 } 5561 5562 setFunctionHasBranchProtectedScope(); 5563 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5564 Clauses, AStmt, B, DSAStack->isCancelRegion()); 5565 } 5566 5567 StmtResult Sema::ActOnOpenMPForSimdDirective( 5568 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5569 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5570 if (!AStmt) 5571 return StmtError(); 5572 5573 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5574 OMPLoopDirective::HelperExprs B; 5575 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5576 // define the nested loops number. 5577 unsigned NestedLoopCount = 5578 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 5579 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5580 VarsWithImplicitDSA, B); 5581 if (NestedLoopCount == 0) 5582 return StmtError(); 5583 5584 assert((CurContext->isDependentContext() || B.builtAll()) && 5585 "omp for simd loop exprs were not built"); 5586 5587 if (!CurContext->isDependentContext()) { 5588 // Finalize the clauses that need pre-built expressions for CodeGen. 5589 for (OMPClause *C : Clauses) { 5590 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5591 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5592 B.NumIterations, *this, CurScope, 5593 DSAStack)) 5594 return StmtError(); 5595 } 5596 } 5597 5598 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5599 return StmtError(); 5600 5601 setFunctionHasBranchProtectedScope(); 5602 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5603 Clauses, AStmt, B); 5604 } 5605 5606 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 5607 Stmt *AStmt, 5608 SourceLocation StartLoc, 5609 SourceLocation EndLoc) { 5610 if (!AStmt) 5611 return StmtError(); 5612 5613 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5614 auto BaseStmt = AStmt; 5615 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5616 BaseStmt = CS->getCapturedStmt(); 5617 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5618 auto S = C->children(); 5619 if (S.begin() == S.end()) 5620 return StmtError(); 5621 // All associated statements must be '#pragma omp section' except for 5622 // the first one. 5623 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5624 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5625 if (SectionStmt) 5626 Diag(SectionStmt->getBeginLoc(), 5627 diag::err_omp_sections_substmt_not_section); 5628 return StmtError(); 5629 } 5630 cast<OMPSectionDirective>(SectionStmt) 5631 ->setHasCancel(DSAStack->isCancelRegion()); 5632 } 5633 } else { 5634 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 5635 return StmtError(); 5636 } 5637 5638 setFunctionHasBranchProtectedScope(); 5639 5640 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5641 DSAStack->isCancelRegion()); 5642 } 5643 5644 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 5645 SourceLocation StartLoc, 5646 SourceLocation EndLoc) { 5647 if (!AStmt) 5648 return StmtError(); 5649 5650 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5651 5652 setFunctionHasBranchProtectedScope(); 5653 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 5654 5655 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 5656 DSAStack->isCancelRegion()); 5657 } 5658 5659 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 5660 Stmt *AStmt, 5661 SourceLocation StartLoc, 5662 SourceLocation EndLoc) { 5663 if (!AStmt) 5664 return StmtError(); 5665 5666 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5667 5668 setFunctionHasBranchProtectedScope(); 5669 5670 // OpenMP [2.7.3, single Construct, Restrictions] 5671 // The copyprivate clause must not be used with the nowait clause. 5672 const OMPClause *Nowait = nullptr; 5673 const OMPClause *Copyprivate = nullptr; 5674 for (const OMPClause *Clause : Clauses) { 5675 if (Clause->getClauseKind() == OMPC_nowait) 5676 Nowait = Clause; 5677 else if (Clause->getClauseKind() == OMPC_copyprivate) 5678 Copyprivate = Clause; 5679 if (Copyprivate && Nowait) { 5680 Diag(Copyprivate->getBeginLoc(), 5681 diag::err_omp_single_copyprivate_with_nowait); 5682 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 5683 return StmtError(); 5684 } 5685 } 5686 5687 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5688 } 5689 5690 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 5691 SourceLocation StartLoc, 5692 SourceLocation EndLoc) { 5693 if (!AStmt) 5694 return StmtError(); 5695 5696 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5697 5698 setFunctionHasBranchProtectedScope(); 5699 5700 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 5701 } 5702 5703 StmtResult Sema::ActOnOpenMPCriticalDirective( 5704 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 5705 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5706 if (!AStmt) 5707 return StmtError(); 5708 5709 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5710 5711 bool ErrorFound = false; 5712 llvm::APSInt Hint; 5713 SourceLocation HintLoc; 5714 bool DependentHint = false; 5715 for (const OMPClause *C : Clauses) { 5716 if (C->getClauseKind() == OMPC_hint) { 5717 if (!DirName.getName()) { 5718 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 5719 ErrorFound = true; 5720 } 5721 Expr *E = cast<OMPHintClause>(C)->getHint(); 5722 if (E->isTypeDependent() || E->isValueDependent() || 5723 E->isInstantiationDependent()) { 5724 DependentHint = true; 5725 } else { 5726 Hint = E->EvaluateKnownConstInt(Context); 5727 HintLoc = C->getBeginLoc(); 5728 } 5729 } 5730 } 5731 if (ErrorFound) 5732 return StmtError(); 5733 const auto Pair = DSAStack->getCriticalWithHint(DirName); 5734 if (Pair.first && DirName.getName() && !DependentHint) { 5735 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 5736 Diag(StartLoc, diag::err_omp_critical_with_hint); 5737 if (HintLoc.isValid()) 5738 Diag(HintLoc, diag::note_omp_critical_hint_here) 5739 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 5740 else 5741 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 5742 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 5743 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 5744 << 1 5745 << C->getHint()->EvaluateKnownConstInt(Context).toString( 5746 /*Radix=*/10, /*Signed=*/false); 5747 } else { 5748 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 5749 } 5750 } 5751 } 5752 5753 setFunctionHasBranchProtectedScope(); 5754 5755 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 5756 Clauses, AStmt); 5757 if (!Pair.first && DirName.getName() && !DependentHint) 5758 DSAStack->addCriticalWithHint(Dir, Hint); 5759 return Dir; 5760 } 5761 5762 StmtResult Sema::ActOnOpenMPParallelForDirective( 5763 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5764 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5765 if (!AStmt) 5766 return StmtError(); 5767 5768 auto *CS = cast<CapturedStmt>(AStmt); 5769 // 1.2.2 OpenMP Language Terminology 5770 // Structured block - An executable statement with a single entry at the 5771 // top and a single exit at the bottom. 5772 // The point of exit cannot be a branch out of the structured block. 5773 // longjmp() and throw() must not violate the entry/exit criteria. 5774 CS->getCapturedDecl()->setNothrow(); 5775 5776 OMPLoopDirective::HelperExprs B; 5777 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5778 // define the nested loops number. 5779 unsigned NestedLoopCount = 5780 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 5781 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5782 VarsWithImplicitDSA, B); 5783 if (NestedLoopCount == 0) 5784 return StmtError(); 5785 5786 assert((CurContext->isDependentContext() || B.builtAll()) && 5787 "omp parallel for loop exprs were not built"); 5788 5789 if (!CurContext->isDependentContext()) { 5790 // Finalize the clauses that need pre-built expressions for CodeGen. 5791 for (OMPClause *C : Clauses) { 5792 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5793 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5794 B.NumIterations, *this, CurScope, 5795 DSAStack)) 5796 return StmtError(); 5797 } 5798 } 5799 5800 setFunctionHasBranchProtectedScope(); 5801 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 5802 NestedLoopCount, Clauses, AStmt, B, 5803 DSAStack->isCancelRegion()); 5804 } 5805 5806 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 5807 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5808 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5809 if (!AStmt) 5810 return StmtError(); 5811 5812 auto *CS = cast<CapturedStmt>(AStmt); 5813 // 1.2.2 OpenMP Language Terminology 5814 // Structured block - An executable statement with a single entry at the 5815 // top and a single exit at the bottom. 5816 // The point of exit cannot be a branch out of the structured block. 5817 // longjmp() and throw() must not violate the entry/exit criteria. 5818 CS->getCapturedDecl()->setNothrow(); 5819 5820 OMPLoopDirective::HelperExprs B; 5821 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5822 // define the nested loops number. 5823 unsigned NestedLoopCount = 5824 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 5825 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5826 VarsWithImplicitDSA, B); 5827 if (NestedLoopCount == 0) 5828 return StmtError(); 5829 5830 if (!CurContext->isDependentContext()) { 5831 // Finalize the clauses that need pre-built expressions for CodeGen. 5832 for (OMPClause *C : Clauses) { 5833 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5834 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5835 B.NumIterations, *this, CurScope, 5836 DSAStack)) 5837 return StmtError(); 5838 } 5839 } 5840 5841 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5842 return StmtError(); 5843 5844 setFunctionHasBranchProtectedScope(); 5845 return OMPParallelForSimdDirective::Create( 5846 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 5847 } 5848 5849 StmtResult 5850 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 5851 Stmt *AStmt, SourceLocation StartLoc, 5852 SourceLocation EndLoc) { 5853 if (!AStmt) 5854 return StmtError(); 5855 5856 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5857 auto BaseStmt = AStmt; 5858 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5859 BaseStmt = CS->getCapturedStmt(); 5860 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5861 auto S = C->children(); 5862 if (S.begin() == S.end()) 5863 return StmtError(); 5864 // All associated statements must be '#pragma omp section' except for 5865 // the first one. 5866 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5867 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5868 if (SectionStmt) 5869 Diag(SectionStmt->getBeginLoc(), 5870 diag::err_omp_parallel_sections_substmt_not_section); 5871 return StmtError(); 5872 } 5873 cast<OMPSectionDirective>(SectionStmt) 5874 ->setHasCancel(DSAStack->isCancelRegion()); 5875 } 5876 } else { 5877 Diag(AStmt->getBeginLoc(), 5878 diag::err_omp_parallel_sections_not_compound_stmt); 5879 return StmtError(); 5880 } 5881 5882 setFunctionHasBranchProtectedScope(); 5883 5884 return OMPParallelSectionsDirective::Create( 5885 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 5886 } 5887 5888 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 5889 Stmt *AStmt, SourceLocation StartLoc, 5890 SourceLocation EndLoc) { 5891 if (!AStmt) 5892 return StmtError(); 5893 5894 auto *CS = cast<CapturedStmt>(AStmt); 5895 // 1.2.2 OpenMP Language Terminology 5896 // Structured block - An executable statement with a single entry at the 5897 // top and a single exit at the bottom. 5898 // The point of exit cannot be a branch out of the structured block. 5899 // longjmp() and throw() must not violate the entry/exit criteria. 5900 CS->getCapturedDecl()->setNothrow(); 5901 5902 setFunctionHasBranchProtectedScope(); 5903 5904 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5905 DSAStack->isCancelRegion()); 5906 } 5907 5908 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 5909 SourceLocation EndLoc) { 5910 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 5911 } 5912 5913 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 5914 SourceLocation EndLoc) { 5915 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 5916 } 5917 5918 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 5919 SourceLocation EndLoc) { 5920 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 5921 } 5922 5923 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 5924 Stmt *AStmt, 5925 SourceLocation StartLoc, 5926 SourceLocation EndLoc) { 5927 if (!AStmt) 5928 return StmtError(); 5929 5930 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5931 5932 setFunctionHasBranchProtectedScope(); 5933 5934 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 5935 AStmt, 5936 DSAStack->getTaskgroupReductionRef()); 5937 } 5938 5939 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 5940 SourceLocation StartLoc, 5941 SourceLocation EndLoc) { 5942 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 5943 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 5944 } 5945 5946 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 5947 Stmt *AStmt, 5948 SourceLocation StartLoc, 5949 SourceLocation EndLoc) { 5950 const OMPClause *DependFound = nullptr; 5951 const OMPClause *DependSourceClause = nullptr; 5952 const OMPClause *DependSinkClause = nullptr; 5953 bool ErrorFound = false; 5954 const OMPThreadsClause *TC = nullptr; 5955 const OMPSIMDClause *SC = nullptr; 5956 for (const OMPClause *C : Clauses) { 5957 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 5958 DependFound = C; 5959 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 5960 if (DependSourceClause) { 5961 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 5962 << getOpenMPDirectiveName(OMPD_ordered) 5963 << getOpenMPClauseName(OMPC_depend) << 2; 5964 ErrorFound = true; 5965 } else { 5966 DependSourceClause = C; 5967 } 5968 if (DependSinkClause) { 5969 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 5970 << 0; 5971 ErrorFound = true; 5972 } 5973 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 5974 if (DependSourceClause) { 5975 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 5976 << 1; 5977 ErrorFound = true; 5978 } 5979 DependSinkClause = C; 5980 } 5981 } else if (C->getClauseKind() == OMPC_threads) { 5982 TC = cast<OMPThreadsClause>(C); 5983 } else if (C->getClauseKind() == OMPC_simd) { 5984 SC = cast<OMPSIMDClause>(C); 5985 } 5986 } 5987 if (!ErrorFound && !SC && 5988 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 5989 // OpenMP [2.8.1,simd Construct, Restrictions] 5990 // An ordered construct with the simd clause is the only OpenMP construct 5991 // that can appear in the simd region. 5992 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 5993 ErrorFound = true; 5994 } else if (DependFound && (TC || SC)) { 5995 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 5996 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 5997 ErrorFound = true; 5998 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 5999 Diag(DependFound->getBeginLoc(), 6000 diag::err_omp_ordered_directive_without_param); 6001 ErrorFound = true; 6002 } else if (TC || Clauses.empty()) { 6003 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 6004 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 6005 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 6006 << (TC != nullptr); 6007 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param); 6008 ErrorFound = true; 6009 } 6010 } 6011 if ((!AStmt && !DependFound) || ErrorFound) 6012 return StmtError(); 6013 6014 if (AStmt) { 6015 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6016 6017 setFunctionHasBranchProtectedScope(); 6018 } 6019 6020 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6021 } 6022 6023 namespace { 6024 /// Helper class for checking expression in 'omp atomic [update]' 6025 /// construct. 6026 class OpenMPAtomicUpdateChecker { 6027 /// Error results for atomic update expressions. 6028 enum ExprAnalysisErrorCode { 6029 /// A statement is not an expression statement. 6030 NotAnExpression, 6031 /// Expression is not builtin binary or unary operation. 6032 NotABinaryOrUnaryExpression, 6033 /// Unary operation is not post-/pre- increment/decrement operation. 6034 NotAnUnaryIncDecExpression, 6035 /// An expression is not of scalar type. 6036 NotAScalarType, 6037 /// A binary operation is not an assignment operation. 6038 NotAnAssignmentOp, 6039 /// RHS part of the binary operation is not a binary expression. 6040 NotABinaryExpression, 6041 /// RHS part is not additive/multiplicative/shift/biwise binary 6042 /// expression. 6043 NotABinaryOperator, 6044 /// RHS binary operation does not have reference to the updated LHS 6045 /// part. 6046 NotAnUpdateExpression, 6047 /// No errors is found. 6048 NoError 6049 }; 6050 /// Reference to Sema. 6051 Sema &SemaRef; 6052 /// A location for note diagnostics (when error is found). 6053 SourceLocation NoteLoc; 6054 /// 'x' lvalue part of the source atomic expression. 6055 Expr *X; 6056 /// 'expr' rvalue part of the source atomic expression. 6057 Expr *E; 6058 /// Helper expression of the form 6059 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 6060 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 6061 Expr *UpdateExpr; 6062 /// Is 'x' a LHS in a RHS part of full update expression. It is 6063 /// important for non-associative operations. 6064 bool IsXLHSInRHSPart; 6065 BinaryOperatorKind Op; 6066 SourceLocation OpLoc; 6067 /// true if the source expression is a postfix unary operation, false 6068 /// if it is a prefix unary operation. 6069 bool IsPostfixUpdate; 6070 6071 public: 6072 OpenMPAtomicUpdateChecker(Sema &SemaRef) 6073 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 6074 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 6075 /// Check specified statement that it is suitable for 'atomic update' 6076 /// constructs and extract 'x', 'expr' and Operation from the original 6077 /// expression. If DiagId and NoteId == 0, then only check is performed 6078 /// without error notification. 6079 /// \param DiagId Diagnostic which should be emitted if error is found. 6080 /// \param NoteId Diagnostic note for the main error message. 6081 /// \return true if statement is not an update expression, false otherwise. 6082 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 6083 /// Return the 'x' lvalue part of the source atomic expression. 6084 Expr *getX() const { return X; } 6085 /// Return the 'expr' rvalue part of the source atomic expression. 6086 Expr *getExpr() const { return E; } 6087 /// Return the update expression used in calculation of the updated 6088 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 6089 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 6090 Expr *getUpdateExpr() const { return UpdateExpr; } 6091 /// Return true if 'x' is LHS in RHS part of full update expression, 6092 /// false otherwise. 6093 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 6094 6095 /// true if the source expression is a postfix unary operation, false 6096 /// if it is a prefix unary operation. 6097 bool isPostfixUpdate() const { return IsPostfixUpdate; } 6098 6099 private: 6100 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 6101 unsigned NoteId = 0); 6102 }; 6103 } // namespace 6104 6105 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 6106 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 6107 ExprAnalysisErrorCode ErrorFound = NoError; 6108 SourceLocation ErrorLoc, NoteLoc; 6109 SourceRange ErrorRange, NoteRange; 6110 // Allowed constructs are: 6111 // x = x binop expr; 6112 // x = expr binop x; 6113 if (AtomicBinOp->getOpcode() == BO_Assign) { 6114 X = AtomicBinOp->getLHS(); 6115 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 6116 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 6117 if (AtomicInnerBinOp->isMultiplicativeOp() || 6118 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 6119 AtomicInnerBinOp->isBitwiseOp()) { 6120 Op = AtomicInnerBinOp->getOpcode(); 6121 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 6122 Expr *LHS = AtomicInnerBinOp->getLHS(); 6123 Expr *RHS = AtomicInnerBinOp->getRHS(); 6124 llvm::FoldingSetNodeID XId, LHSId, RHSId; 6125 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 6126 /*Canonical=*/true); 6127 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 6128 /*Canonical=*/true); 6129 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 6130 /*Canonical=*/true); 6131 if (XId == LHSId) { 6132 E = RHS; 6133 IsXLHSInRHSPart = true; 6134 } else if (XId == RHSId) { 6135 E = LHS; 6136 IsXLHSInRHSPart = false; 6137 } else { 6138 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 6139 ErrorRange = AtomicInnerBinOp->getSourceRange(); 6140 NoteLoc = X->getExprLoc(); 6141 NoteRange = X->getSourceRange(); 6142 ErrorFound = NotAnUpdateExpression; 6143 } 6144 } else { 6145 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 6146 ErrorRange = AtomicInnerBinOp->getSourceRange(); 6147 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 6148 NoteRange = SourceRange(NoteLoc, NoteLoc); 6149 ErrorFound = NotABinaryOperator; 6150 } 6151 } else { 6152 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 6153 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 6154 ErrorFound = NotABinaryExpression; 6155 } 6156 } else { 6157 ErrorLoc = AtomicBinOp->getExprLoc(); 6158 ErrorRange = AtomicBinOp->getSourceRange(); 6159 NoteLoc = AtomicBinOp->getOperatorLoc(); 6160 NoteRange = SourceRange(NoteLoc, NoteLoc); 6161 ErrorFound = NotAnAssignmentOp; 6162 } 6163 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 6164 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 6165 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 6166 return true; 6167 } 6168 if (SemaRef.CurContext->isDependentContext()) 6169 E = X = UpdateExpr = nullptr; 6170 return ErrorFound != NoError; 6171 } 6172 6173 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 6174 unsigned NoteId) { 6175 ExprAnalysisErrorCode ErrorFound = NoError; 6176 SourceLocation ErrorLoc, NoteLoc; 6177 SourceRange ErrorRange, NoteRange; 6178 // Allowed constructs are: 6179 // x++; 6180 // x--; 6181 // ++x; 6182 // --x; 6183 // x binop= expr; 6184 // x = x binop expr; 6185 // x = expr binop x; 6186 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 6187 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 6188 if (AtomicBody->getType()->isScalarType() || 6189 AtomicBody->isInstantiationDependent()) { 6190 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 6191 AtomicBody->IgnoreParenImpCasts())) { 6192 // Check for Compound Assignment Operation 6193 Op = BinaryOperator::getOpForCompoundAssignment( 6194 AtomicCompAssignOp->getOpcode()); 6195 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 6196 E = AtomicCompAssignOp->getRHS(); 6197 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 6198 IsXLHSInRHSPart = true; 6199 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 6200 AtomicBody->IgnoreParenImpCasts())) { 6201 // Check for Binary Operation 6202 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 6203 return true; 6204 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 6205 AtomicBody->IgnoreParenImpCasts())) { 6206 // Check for Unary Operation 6207 if (AtomicUnaryOp->isIncrementDecrementOp()) { 6208 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 6209 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 6210 OpLoc = AtomicUnaryOp->getOperatorLoc(); 6211 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 6212 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 6213 IsXLHSInRHSPart = true; 6214 } else { 6215 ErrorFound = NotAnUnaryIncDecExpression; 6216 ErrorLoc = AtomicUnaryOp->getExprLoc(); 6217 ErrorRange = AtomicUnaryOp->getSourceRange(); 6218 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 6219 NoteRange = SourceRange(NoteLoc, NoteLoc); 6220 } 6221 } else if (!AtomicBody->isInstantiationDependent()) { 6222 ErrorFound = NotABinaryOrUnaryExpression; 6223 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 6224 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 6225 } 6226 } else { 6227 ErrorFound = NotAScalarType; 6228 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 6229 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6230 } 6231 } else { 6232 ErrorFound = NotAnExpression; 6233 NoteLoc = ErrorLoc = S->getBeginLoc(); 6234 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6235 } 6236 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 6237 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 6238 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 6239 return true; 6240 } 6241 if (SemaRef.CurContext->isDependentContext()) 6242 E = X = UpdateExpr = nullptr; 6243 if (ErrorFound == NoError && E && X) { 6244 // Build an update expression of form 'OpaqueValueExpr(x) binop 6245 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 6246 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 6247 auto *OVEX = new (SemaRef.getASTContext()) 6248 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 6249 auto *OVEExpr = new (SemaRef.getASTContext()) 6250 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 6251 ExprResult Update = 6252 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 6253 IsXLHSInRHSPart ? OVEExpr : OVEX); 6254 if (Update.isInvalid()) 6255 return true; 6256 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 6257 Sema::AA_Casting); 6258 if (Update.isInvalid()) 6259 return true; 6260 UpdateExpr = Update.get(); 6261 } 6262 return ErrorFound != NoError; 6263 } 6264 6265 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 6266 Stmt *AStmt, 6267 SourceLocation StartLoc, 6268 SourceLocation EndLoc) { 6269 if (!AStmt) 6270 return StmtError(); 6271 6272 auto *CS = cast<CapturedStmt>(AStmt); 6273 // 1.2.2 OpenMP Language Terminology 6274 // Structured block - An executable statement with a single entry at the 6275 // top and a single exit at the bottom. 6276 // The point of exit cannot be a branch out of the structured block. 6277 // longjmp() and throw() must not violate the entry/exit criteria. 6278 OpenMPClauseKind AtomicKind = OMPC_unknown; 6279 SourceLocation AtomicKindLoc; 6280 for (const OMPClause *C : Clauses) { 6281 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 6282 C->getClauseKind() == OMPC_update || 6283 C->getClauseKind() == OMPC_capture) { 6284 if (AtomicKind != OMPC_unknown) { 6285 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 6286 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 6287 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 6288 << getOpenMPClauseName(AtomicKind); 6289 } else { 6290 AtomicKind = C->getClauseKind(); 6291 AtomicKindLoc = C->getBeginLoc(); 6292 } 6293 } 6294 } 6295 6296 Stmt *Body = CS->getCapturedStmt(); 6297 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 6298 Body = EWC->getSubExpr(); 6299 6300 Expr *X = nullptr; 6301 Expr *V = nullptr; 6302 Expr *E = nullptr; 6303 Expr *UE = nullptr; 6304 bool IsXLHSInRHSPart = false; 6305 bool IsPostfixUpdate = false; 6306 // OpenMP [2.12.6, atomic Construct] 6307 // In the next expressions: 6308 // * x and v (as applicable) are both l-value expressions with scalar type. 6309 // * During the execution of an atomic region, multiple syntactic 6310 // occurrences of x must designate the same storage location. 6311 // * Neither of v and expr (as applicable) may access the storage location 6312 // designated by x. 6313 // * Neither of x and expr (as applicable) may access the storage location 6314 // designated by v. 6315 // * expr is an expression with scalar type. 6316 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 6317 // * binop, binop=, ++, and -- are not overloaded operators. 6318 // * The expression x binop expr must be numerically equivalent to x binop 6319 // (expr). This requirement is satisfied if the operators in expr have 6320 // precedence greater than binop, or by using parentheses around expr or 6321 // subexpressions of expr. 6322 // * The expression expr binop x must be numerically equivalent to (expr) 6323 // binop x. This requirement is satisfied if the operators in expr have 6324 // precedence equal to or greater than binop, or by using parentheses around 6325 // expr or subexpressions of expr. 6326 // * For forms that allow multiple occurrences of x, the number of times 6327 // that x is evaluated is unspecified. 6328 if (AtomicKind == OMPC_read) { 6329 enum { 6330 NotAnExpression, 6331 NotAnAssignmentOp, 6332 NotAScalarType, 6333 NotAnLValue, 6334 NoError 6335 } ErrorFound = NoError; 6336 SourceLocation ErrorLoc, NoteLoc; 6337 SourceRange ErrorRange, NoteRange; 6338 // If clause is read: 6339 // v = x; 6340 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 6341 const auto *AtomicBinOp = 6342 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6343 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6344 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6345 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 6346 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6347 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 6348 if (!X->isLValue() || !V->isLValue()) { 6349 const Expr *NotLValueExpr = X->isLValue() ? V : X; 6350 ErrorFound = NotAnLValue; 6351 ErrorLoc = AtomicBinOp->getExprLoc(); 6352 ErrorRange = AtomicBinOp->getSourceRange(); 6353 NoteLoc = NotLValueExpr->getExprLoc(); 6354 NoteRange = NotLValueExpr->getSourceRange(); 6355 } 6356 } else if (!X->isInstantiationDependent() || 6357 !V->isInstantiationDependent()) { 6358 const Expr *NotScalarExpr = 6359 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6360 ? V 6361 : X; 6362 ErrorFound = NotAScalarType; 6363 ErrorLoc = AtomicBinOp->getExprLoc(); 6364 ErrorRange = AtomicBinOp->getSourceRange(); 6365 NoteLoc = NotScalarExpr->getExprLoc(); 6366 NoteRange = NotScalarExpr->getSourceRange(); 6367 } 6368 } else if (!AtomicBody->isInstantiationDependent()) { 6369 ErrorFound = NotAnAssignmentOp; 6370 ErrorLoc = AtomicBody->getExprLoc(); 6371 ErrorRange = AtomicBody->getSourceRange(); 6372 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6373 : AtomicBody->getExprLoc(); 6374 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6375 : AtomicBody->getSourceRange(); 6376 } 6377 } else { 6378 ErrorFound = NotAnExpression; 6379 NoteLoc = ErrorLoc = Body->getBeginLoc(); 6380 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6381 } 6382 if (ErrorFound != NoError) { 6383 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 6384 << ErrorRange; 6385 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6386 << NoteRange; 6387 return StmtError(); 6388 } 6389 if (CurContext->isDependentContext()) 6390 V = X = nullptr; 6391 } else if (AtomicKind == OMPC_write) { 6392 enum { 6393 NotAnExpression, 6394 NotAnAssignmentOp, 6395 NotAScalarType, 6396 NotAnLValue, 6397 NoError 6398 } ErrorFound = NoError; 6399 SourceLocation ErrorLoc, NoteLoc; 6400 SourceRange ErrorRange, NoteRange; 6401 // If clause is write: 6402 // x = expr; 6403 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 6404 const auto *AtomicBinOp = 6405 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6406 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6407 X = AtomicBinOp->getLHS(); 6408 E = AtomicBinOp->getRHS(); 6409 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6410 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 6411 if (!X->isLValue()) { 6412 ErrorFound = NotAnLValue; 6413 ErrorLoc = AtomicBinOp->getExprLoc(); 6414 ErrorRange = AtomicBinOp->getSourceRange(); 6415 NoteLoc = X->getExprLoc(); 6416 NoteRange = X->getSourceRange(); 6417 } 6418 } else if (!X->isInstantiationDependent() || 6419 !E->isInstantiationDependent()) { 6420 const Expr *NotScalarExpr = 6421 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6422 ? E 6423 : X; 6424 ErrorFound = NotAScalarType; 6425 ErrorLoc = AtomicBinOp->getExprLoc(); 6426 ErrorRange = AtomicBinOp->getSourceRange(); 6427 NoteLoc = NotScalarExpr->getExprLoc(); 6428 NoteRange = NotScalarExpr->getSourceRange(); 6429 } 6430 } else if (!AtomicBody->isInstantiationDependent()) { 6431 ErrorFound = NotAnAssignmentOp; 6432 ErrorLoc = AtomicBody->getExprLoc(); 6433 ErrorRange = AtomicBody->getSourceRange(); 6434 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6435 : AtomicBody->getExprLoc(); 6436 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6437 : AtomicBody->getSourceRange(); 6438 } 6439 } else { 6440 ErrorFound = NotAnExpression; 6441 NoteLoc = ErrorLoc = Body->getBeginLoc(); 6442 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6443 } 6444 if (ErrorFound != NoError) { 6445 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 6446 << ErrorRange; 6447 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6448 << NoteRange; 6449 return StmtError(); 6450 } 6451 if (CurContext->isDependentContext()) 6452 E = X = nullptr; 6453 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 6454 // If clause is update: 6455 // x++; 6456 // x--; 6457 // ++x; 6458 // --x; 6459 // x binop= expr; 6460 // x = x binop expr; 6461 // x = expr binop x; 6462 OpenMPAtomicUpdateChecker Checker(*this); 6463 if (Checker.checkStatement( 6464 Body, (AtomicKind == OMPC_update) 6465 ? diag::err_omp_atomic_update_not_expression_statement 6466 : diag::err_omp_atomic_not_expression_statement, 6467 diag::note_omp_atomic_update)) 6468 return StmtError(); 6469 if (!CurContext->isDependentContext()) { 6470 E = Checker.getExpr(); 6471 X = Checker.getX(); 6472 UE = Checker.getUpdateExpr(); 6473 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6474 } 6475 } else if (AtomicKind == OMPC_capture) { 6476 enum { 6477 NotAnAssignmentOp, 6478 NotACompoundStatement, 6479 NotTwoSubstatements, 6480 NotASpecificExpression, 6481 NoError 6482 } ErrorFound = NoError; 6483 SourceLocation ErrorLoc, NoteLoc; 6484 SourceRange ErrorRange, NoteRange; 6485 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 6486 // If clause is a capture: 6487 // v = x++; 6488 // v = x--; 6489 // v = ++x; 6490 // v = --x; 6491 // v = x binop= expr; 6492 // v = x = x binop expr; 6493 // v = x = expr binop x; 6494 const auto *AtomicBinOp = 6495 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6496 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6497 V = AtomicBinOp->getLHS(); 6498 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6499 OpenMPAtomicUpdateChecker Checker(*this); 6500 if (Checker.checkStatement( 6501 Body, diag::err_omp_atomic_capture_not_expression_statement, 6502 diag::note_omp_atomic_update)) 6503 return StmtError(); 6504 E = Checker.getExpr(); 6505 X = Checker.getX(); 6506 UE = Checker.getUpdateExpr(); 6507 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6508 IsPostfixUpdate = Checker.isPostfixUpdate(); 6509 } else if (!AtomicBody->isInstantiationDependent()) { 6510 ErrorLoc = AtomicBody->getExprLoc(); 6511 ErrorRange = AtomicBody->getSourceRange(); 6512 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6513 : AtomicBody->getExprLoc(); 6514 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6515 : AtomicBody->getSourceRange(); 6516 ErrorFound = NotAnAssignmentOp; 6517 } 6518 if (ErrorFound != NoError) { 6519 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 6520 << ErrorRange; 6521 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6522 return StmtError(); 6523 } 6524 if (CurContext->isDependentContext()) 6525 UE = V = E = X = nullptr; 6526 } else { 6527 // If clause is a capture: 6528 // { v = x; x = expr; } 6529 // { v = x; x++; } 6530 // { v = x; x--; } 6531 // { v = x; ++x; } 6532 // { v = x; --x; } 6533 // { v = x; x binop= expr; } 6534 // { v = x; x = x binop expr; } 6535 // { v = x; x = expr binop x; } 6536 // { x++; v = x; } 6537 // { x--; v = x; } 6538 // { ++x; v = x; } 6539 // { --x; v = x; } 6540 // { x binop= expr; v = x; } 6541 // { x = x binop expr; v = x; } 6542 // { x = expr binop x; v = x; } 6543 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 6544 // Check that this is { expr1; expr2; } 6545 if (CS->size() == 2) { 6546 Stmt *First = CS->body_front(); 6547 Stmt *Second = CS->body_back(); 6548 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 6549 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 6550 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 6551 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 6552 // Need to find what subexpression is 'v' and what is 'x'. 6553 OpenMPAtomicUpdateChecker Checker(*this); 6554 bool IsUpdateExprFound = !Checker.checkStatement(Second); 6555 BinaryOperator *BinOp = nullptr; 6556 if (IsUpdateExprFound) { 6557 BinOp = dyn_cast<BinaryOperator>(First); 6558 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6559 } 6560 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6561 // { v = x; x++; } 6562 // { v = x; x--; } 6563 // { v = x; ++x; } 6564 // { v = x; --x; } 6565 // { v = x; x binop= expr; } 6566 // { v = x; x = x binop expr; } 6567 // { v = x; x = expr binop x; } 6568 // Check that the first expression has form v = x. 6569 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6570 llvm::FoldingSetNodeID XId, PossibleXId; 6571 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6572 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6573 IsUpdateExprFound = XId == PossibleXId; 6574 if (IsUpdateExprFound) { 6575 V = BinOp->getLHS(); 6576 X = Checker.getX(); 6577 E = Checker.getExpr(); 6578 UE = Checker.getUpdateExpr(); 6579 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6580 IsPostfixUpdate = true; 6581 } 6582 } 6583 if (!IsUpdateExprFound) { 6584 IsUpdateExprFound = !Checker.checkStatement(First); 6585 BinOp = nullptr; 6586 if (IsUpdateExprFound) { 6587 BinOp = dyn_cast<BinaryOperator>(Second); 6588 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6589 } 6590 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6591 // { x++; v = x; } 6592 // { x--; v = x; } 6593 // { ++x; v = x; } 6594 // { --x; v = x; } 6595 // { x binop= expr; v = x; } 6596 // { x = x binop expr; v = x; } 6597 // { x = expr binop x; v = x; } 6598 // Check that the second expression has form v = x. 6599 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6600 llvm::FoldingSetNodeID XId, PossibleXId; 6601 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6602 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6603 IsUpdateExprFound = XId == PossibleXId; 6604 if (IsUpdateExprFound) { 6605 V = BinOp->getLHS(); 6606 X = Checker.getX(); 6607 E = Checker.getExpr(); 6608 UE = Checker.getUpdateExpr(); 6609 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6610 IsPostfixUpdate = false; 6611 } 6612 } 6613 } 6614 if (!IsUpdateExprFound) { 6615 // { v = x; x = expr; } 6616 auto *FirstExpr = dyn_cast<Expr>(First); 6617 auto *SecondExpr = dyn_cast<Expr>(Second); 6618 if (!FirstExpr || !SecondExpr || 6619 !(FirstExpr->isInstantiationDependent() || 6620 SecondExpr->isInstantiationDependent())) { 6621 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 6622 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 6623 ErrorFound = NotAnAssignmentOp; 6624 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 6625 : First->getBeginLoc(); 6626 NoteRange = ErrorRange = FirstBinOp 6627 ? FirstBinOp->getSourceRange() 6628 : SourceRange(ErrorLoc, ErrorLoc); 6629 } else { 6630 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 6631 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 6632 ErrorFound = NotAnAssignmentOp; 6633 NoteLoc = ErrorLoc = SecondBinOp 6634 ? SecondBinOp->getOperatorLoc() 6635 : Second->getBeginLoc(); 6636 NoteRange = ErrorRange = 6637 SecondBinOp ? SecondBinOp->getSourceRange() 6638 : SourceRange(ErrorLoc, ErrorLoc); 6639 } else { 6640 Expr *PossibleXRHSInFirst = 6641 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 6642 Expr *PossibleXLHSInSecond = 6643 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 6644 llvm::FoldingSetNodeID X1Id, X2Id; 6645 PossibleXRHSInFirst->Profile(X1Id, Context, 6646 /*Canonical=*/true); 6647 PossibleXLHSInSecond->Profile(X2Id, Context, 6648 /*Canonical=*/true); 6649 IsUpdateExprFound = X1Id == X2Id; 6650 if (IsUpdateExprFound) { 6651 V = FirstBinOp->getLHS(); 6652 X = SecondBinOp->getLHS(); 6653 E = SecondBinOp->getRHS(); 6654 UE = nullptr; 6655 IsXLHSInRHSPart = false; 6656 IsPostfixUpdate = true; 6657 } else { 6658 ErrorFound = NotASpecificExpression; 6659 ErrorLoc = FirstBinOp->getExprLoc(); 6660 ErrorRange = FirstBinOp->getSourceRange(); 6661 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 6662 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 6663 } 6664 } 6665 } 6666 } 6667 } 6668 } else { 6669 NoteLoc = ErrorLoc = Body->getBeginLoc(); 6670 NoteRange = ErrorRange = 6671 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 6672 ErrorFound = NotTwoSubstatements; 6673 } 6674 } else { 6675 NoteLoc = ErrorLoc = Body->getBeginLoc(); 6676 NoteRange = ErrorRange = 6677 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 6678 ErrorFound = NotACompoundStatement; 6679 } 6680 if (ErrorFound != NoError) { 6681 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 6682 << ErrorRange; 6683 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6684 return StmtError(); 6685 } 6686 if (CurContext->isDependentContext()) 6687 UE = V = E = X = nullptr; 6688 } 6689 } 6690 6691 setFunctionHasBranchProtectedScope(); 6692 6693 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6694 X, V, E, UE, IsXLHSInRHSPart, 6695 IsPostfixUpdate); 6696 } 6697 6698 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 6699 Stmt *AStmt, 6700 SourceLocation StartLoc, 6701 SourceLocation EndLoc) { 6702 if (!AStmt) 6703 return StmtError(); 6704 6705 auto *CS = cast<CapturedStmt>(AStmt); 6706 // 1.2.2 OpenMP Language Terminology 6707 // Structured block - An executable statement with a single entry at the 6708 // top and a single exit at the bottom. 6709 // The point of exit cannot be a branch out of the structured block. 6710 // longjmp() and throw() must not violate the entry/exit criteria. 6711 CS->getCapturedDecl()->setNothrow(); 6712 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 6713 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6714 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6715 // 1.2.2 OpenMP Language Terminology 6716 // Structured block - An executable statement with a single entry at the 6717 // top and a single exit at the bottom. 6718 // The point of exit cannot be a branch out of the structured block. 6719 // longjmp() and throw() must not violate the entry/exit criteria. 6720 CS->getCapturedDecl()->setNothrow(); 6721 } 6722 6723 // OpenMP [2.16, Nesting of Regions] 6724 // If specified, a teams construct must be contained within a target 6725 // construct. That target construct must contain no statements or directives 6726 // outside of the teams construct. 6727 if (DSAStack->hasInnerTeamsRegion()) { 6728 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 6729 bool OMPTeamsFound = true; 6730 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 6731 auto I = CS->body_begin(); 6732 while (I != CS->body_end()) { 6733 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 6734 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 6735 OMPTeamsFound = false; 6736 break; 6737 } 6738 ++I; 6739 } 6740 assert(I != CS->body_end() && "Not found statement"); 6741 S = *I; 6742 } else { 6743 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 6744 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 6745 } 6746 if (!OMPTeamsFound) { 6747 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 6748 Diag(DSAStack->getInnerTeamsRegionLoc(), 6749 diag::note_omp_nested_teams_construct_here); 6750 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 6751 << isa<OMPExecutableDirective>(S); 6752 return StmtError(); 6753 } 6754 } 6755 6756 setFunctionHasBranchProtectedScope(); 6757 6758 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6759 } 6760 6761 StmtResult 6762 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 6763 Stmt *AStmt, SourceLocation StartLoc, 6764 SourceLocation EndLoc) { 6765 if (!AStmt) 6766 return StmtError(); 6767 6768 auto *CS = cast<CapturedStmt>(AStmt); 6769 // 1.2.2 OpenMP Language Terminology 6770 // Structured block - An executable statement with a single entry at the 6771 // top and a single exit at the bottom. 6772 // The point of exit cannot be a branch out of the structured block. 6773 // longjmp() and throw() must not violate the entry/exit criteria. 6774 CS->getCapturedDecl()->setNothrow(); 6775 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 6776 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6777 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6778 // 1.2.2 OpenMP Language Terminology 6779 // Structured block - An executable statement with a single entry at the 6780 // top and a single exit at the bottom. 6781 // The point of exit cannot be a branch out of the structured block. 6782 // longjmp() and throw() must not violate the entry/exit criteria. 6783 CS->getCapturedDecl()->setNothrow(); 6784 } 6785 6786 setFunctionHasBranchProtectedScope(); 6787 6788 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6789 AStmt); 6790 } 6791 6792 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 6793 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6794 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 6795 if (!AStmt) 6796 return StmtError(); 6797 6798 auto *CS = cast<CapturedStmt>(AStmt); 6799 // 1.2.2 OpenMP Language Terminology 6800 // Structured block - An executable statement with a single entry at the 6801 // top and a single exit at the bottom. 6802 // The point of exit cannot be a branch out of the structured block. 6803 // longjmp() and throw() must not violate the entry/exit criteria. 6804 CS->getCapturedDecl()->setNothrow(); 6805 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 6806 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6807 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6808 // 1.2.2 OpenMP Language Terminology 6809 // Structured block - An executable statement with a single entry at the 6810 // top and a single exit at the bottom. 6811 // The point of exit cannot be a branch out of the structured block. 6812 // longjmp() and throw() must not violate the entry/exit criteria. 6813 CS->getCapturedDecl()->setNothrow(); 6814 } 6815 6816 OMPLoopDirective::HelperExprs B; 6817 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6818 // define the nested loops number. 6819 unsigned NestedLoopCount = 6820 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 6821 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 6822 VarsWithImplicitDSA, B); 6823 if (NestedLoopCount == 0) 6824 return StmtError(); 6825 6826 assert((CurContext->isDependentContext() || B.builtAll()) && 6827 "omp target parallel for loop exprs were not built"); 6828 6829 if (!CurContext->isDependentContext()) { 6830 // Finalize the clauses that need pre-built expressions for CodeGen. 6831 for (OMPClause *C : Clauses) { 6832 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6833 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6834 B.NumIterations, *this, CurScope, 6835 DSAStack)) 6836 return StmtError(); 6837 } 6838 } 6839 6840 setFunctionHasBranchProtectedScope(); 6841 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 6842 NestedLoopCount, Clauses, AStmt, 6843 B, DSAStack->isCancelRegion()); 6844 } 6845 6846 /// Check for existence of a map clause in the list of clauses. 6847 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 6848 const OpenMPClauseKind K) { 6849 return llvm::any_of( 6850 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 6851 } 6852 6853 template <typename... Params> 6854 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 6855 const Params... ClauseTypes) { 6856 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 6857 } 6858 6859 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 6860 Stmt *AStmt, 6861 SourceLocation StartLoc, 6862 SourceLocation EndLoc) { 6863 if (!AStmt) 6864 return StmtError(); 6865 6866 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6867 6868 // OpenMP [2.10.1, Restrictions, p. 97] 6869 // At least one map clause must appear on the directive. 6870 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { 6871 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6872 << "'map' or 'use_device_ptr'" 6873 << getOpenMPDirectiveName(OMPD_target_data); 6874 return StmtError(); 6875 } 6876 6877 setFunctionHasBranchProtectedScope(); 6878 6879 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6880 AStmt); 6881 } 6882 6883 StmtResult 6884 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 6885 SourceLocation StartLoc, 6886 SourceLocation EndLoc, Stmt *AStmt) { 6887 if (!AStmt) 6888 return StmtError(); 6889 6890 auto *CS = cast<CapturedStmt>(AStmt); 6891 // 1.2.2 OpenMP Language Terminology 6892 // Structured block - An executable statement with a single entry at the 6893 // top and a single exit at the bottom. 6894 // The point of exit cannot be a branch out of the structured block. 6895 // longjmp() and throw() must not violate the entry/exit criteria. 6896 CS->getCapturedDecl()->setNothrow(); 6897 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 6898 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6899 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6900 // 1.2.2 OpenMP Language Terminology 6901 // Structured block - An executable statement with a single entry at the 6902 // top and a single exit at the bottom. 6903 // The point of exit cannot be a branch out of the structured block. 6904 // longjmp() and throw() must not violate the entry/exit criteria. 6905 CS->getCapturedDecl()->setNothrow(); 6906 } 6907 6908 // OpenMP [2.10.2, Restrictions, p. 99] 6909 // At least one map clause must appear on the directive. 6910 if (!hasClauses(Clauses, OMPC_map)) { 6911 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6912 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 6913 return StmtError(); 6914 } 6915 6916 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6917 AStmt); 6918 } 6919 6920 StmtResult 6921 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 6922 SourceLocation StartLoc, 6923 SourceLocation EndLoc, Stmt *AStmt) { 6924 if (!AStmt) 6925 return StmtError(); 6926 6927 auto *CS = cast<CapturedStmt>(AStmt); 6928 // 1.2.2 OpenMP Language Terminology 6929 // Structured block - An executable statement with a single entry at the 6930 // top and a single exit at the bottom. 6931 // The point of exit cannot be a branch out of the structured block. 6932 // longjmp() and throw() must not violate the entry/exit criteria. 6933 CS->getCapturedDecl()->setNothrow(); 6934 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 6935 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6936 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6937 // 1.2.2 OpenMP Language Terminology 6938 // Structured block - An executable statement with a single entry at the 6939 // top and a single exit at the bottom. 6940 // The point of exit cannot be a branch out of the structured block. 6941 // longjmp() and throw() must not violate the entry/exit criteria. 6942 CS->getCapturedDecl()->setNothrow(); 6943 } 6944 6945 // OpenMP [2.10.3, Restrictions, p. 102] 6946 // At least one map clause must appear on the directive. 6947 if (!hasClauses(Clauses, OMPC_map)) { 6948 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6949 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 6950 return StmtError(); 6951 } 6952 6953 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6954 AStmt); 6955 } 6956 6957 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 6958 SourceLocation StartLoc, 6959 SourceLocation EndLoc, 6960 Stmt *AStmt) { 6961 if (!AStmt) 6962 return StmtError(); 6963 6964 auto *CS = cast<CapturedStmt>(AStmt); 6965 // 1.2.2 OpenMP Language Terminology 6966 // Structured block - An executable statement with a single entry at the 6967 // top and a single exit at the bottom. 6968 // The point of exit cannot be a branch out of the structured block. 6969 // longjmp() and throw() must not violate the entry/exit criteria. 6970 CS->getCapturedDecl()->setNothrow(); 6971 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 6972 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6973 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6974 // 1.2.2 OpenMP Language Terminology 6975 // Structured block - An executable statement with a single entry at the 6976 // top and a single exit at the bottom. 6977 // The point of exit cannot be a branch out of the structured block. 6978 // longjmp() and throw() must not violate the entry/exit criteria. 6979 CS->getCapturedDecl()->setNothrow(); 6980 } 6981 6982 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 6983 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 6984 return StmtError(); 6985 } 6986 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 6987 AStmt); 6988 } 6989 6990 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 6991 Stmt *AStmt, SourceLocation StartLoc, 6992 SourceLocation EndLoc) { 6993 if (!AStmt) 6994 return StmtError(); 6995 6996 auto *CS = cast<CapturedStmt>(AStmt); 6997 // 1.2.2 OpenMP Language Terminology 6998 // Structured block - An executable statement with a single entry at the 6999 // top and a single exit at the bottom. 7000 // The point of exit cannot be a branch out of the structured block. 7001 // longjmp() and throw() must not violate the entry/exit criteria. 7002 CS->getCapturedDecl()->setNothrow(); 7003 7004 setFunctionHasBranchProtectedScope(); 7005 7006 DSAStack->setParentTeamsRegionLoc(StartLoc); 7007 7008 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 7009 } 7010 7011 StmtResult 7012 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 7013 SourceLocation EndLoc, 7014 OpenMPDirectiveKind CancelRegion) { 7015 if (DSAStack->isParentNowaitRegion()) { 7016 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 7017 return StmtError(); 7018 } 7019 if (DSAStack->isParentOrderedRegion()) { 7020 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 7021 return StmtError(); 7022 } 7023 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 7024 CancelRegion); 7025 } 7026 7027 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 7028 SourceLocation StartLoc, 7029 SourceLocation EndLoc, 7030 OpenMPDirectiveKind CancelRegion) { 7031 if (DSAStack->isParentNowaitRegion()) { 7032 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 7033 return StmtError(); 7034 } 7035 if (DSAStack->isParentOrderedRegion()) { 7036 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 7037 return StmtError(); 7038 } 7039 DSAStack->setParentCancelRegion(/*Cancel=*/true); 7040 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 7041 CancelRegion); 7042 } 7043 7044 static bool checkGrainsizeNumTasksClauses(Sema &S, 7045 ArrayRef<OMPClause *> Clauses) { 7046 const OMPClause *PrevClause = nullptr; 7047 bool ErrorFound = false; 7048 for (const OMPClause *C : Clauses) { 7049 if (C->getClauseKind() == OMPC_grainsize || 7050 C->getClauseKind() == OMPC_num_tasks) { 7051 if (!PrevClause) 7052 PrevClause = C; 7053 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 7054 S.Diag(C->getBeginLoc(), 7055 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 7056 << getOpenMPClauseName(C->getClauseKind()) 7057 << getOpenMPClauseName(PrevClause->getClauseKind()); 7058 S.Diag(PrevClause->getBeginLoc(), 7059 diag::note_omp_previous_grainsize_num_tasks) 7060 << getOpenMPClauseName(PrevClause->getClauseKind()); 7061 ErrorFound = true; 7062 } 7063 } 7064 } 7065 return ErrorFound; 7066 } 7067 7068 static bool checkReductionClauseWithNogroup(Sema &S, 7069 ArrayRef<OMPClause *> Clauses) { 7070 const OMPClause *ReductionClause = nullptr; 7071 const OMPClause *NogroupClause = nullptr; 7072 for (const OMPClause *C : Clauses) { 7073 if (C->getClauseKind() == OMPC_reduction) { 7074 ReductionClause = C; 7075 if (NogroupClause) 7076 break; 7077 continue; 7078 } 7079 if (C->getClauseKind() == OMPC_nogroup) { 7080 NogroupClause = C; 7081 if (ReductionClause) 7082 break; 7083 continue; 7084 } 7085 } 7086 if (ReductionClause && NogroupClause) { 7087 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 7088 << SourceRange(NogroupClause->getBeginLoc(), 7089 NogroupClause->getEndLoc()); 7090 return true; 7091 } 7092 return false; 7093 } 7094 7095 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 7096 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7097 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7098 if (!AStmt) 7099 return StmtError(); 7100 7101 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7102 OMPLoopDirective::HelperExprs B; 7103 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7104 // define the nested loops number. 7105 unsigned NestedLoopCount = 7106 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 7107 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 7108 VarsWithImplicitDSA, B); 7109 if (NestedLoopCount == 0) 7110 return StmtError(); 7111 7112 assert((CurContext->isDependentContext() || B.builtAll()) && 7113 "omp for loop exprs were not built"); 7114 7115 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7116 // The grainsize clause and num_tasks clause are mutually exclusive and may 7117 // not appear on the same taskloop directive. 7118 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 7119 return StmtError(); 7120 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7121 // If a reduction clause is present on the taskloop directive, the nogroup 7122 // clause must not be specified. 7123 if (checkReductionClauseWithNogroup(*this, Clauses)) 7124 return StmtError(); 7125 7126 setFunctionHasBranchProtectedScope(); 7127 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 7128 NestedLoopCount, Clauses, AStmt, B); 7129 } 7130 7131 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 7132 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7133 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7134 if (!AStmt) 7135 return StmtError(); 7136 7137 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7138 OMPLoopDirective::HelperExprs B; 7139 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7140 // define the nested loops number. 7141 unsigned NestedLoopCount = 7142 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 7143 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 7144 VarsWithImplicitDSA, B); 7145 if (NestedLoopCount == 0) 7146 return StmtError(); 7147 7148 assert((CurContext->isDependentContext() || B.builtAll()) && 7149 "omp for loop exprs were not built"); 7150 7151 if (!CurContext->isDependentContext()) { 7152 // Finalize the clauses that need pre-built expressions for CodeGen. 7153 for (OMPClause *C : Clauses) { 7154 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7155 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7156 B.NumIterations, *this, CurScope, 7157 DSAStack)) 7158 return StmtError(); 7159 } 7160 } 7161 7162 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7163 // The grainsize clause and num_tasks clause are mutually exclusive and may 7164 // not appear on the same taskloop directive. 7165 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 7166 return StmtError(); 7167 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7168 // If a reduction clause is present on the taskloop directive, the nogroup 7169 // clause must not be specified. 7170 if (checkReductionClauseWithNogroup(*this, Clauses)) 7171 return StmtError(); 7172 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7173 return StmtError(); 7174 7175 setFunctionHasBranchProtectedScope(); 7176 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 7177 NestedLoopCount, Clauses, AStmt, B); 7178 } 7179 7180 StmtResult Sema::ActOnOpenMPDistributeDirective( 7181 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7182 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7183 if (!AStmt) 7184 return StmtError(); 7185 7186 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7187 OMPLoopDirective::HelperExprs B; 7188 // In presence of clause 'collapse' with number of loops, it will 7189 // define the nested loops number. 7190 unsigned NestedLoopCount = 7191 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 7192 nullptr /*ordered not a clause on distribute*/, AStmt, 7193 *this, *DSAStack, VarsWithImplicitDSA, B); 7194 if (NestedLoopCount == 0) 7195 return StmtError(); 7196 7197 assert((CurContext->isDependentContext() || B.builtAll()) && 7198 "omp for loop exprs were not built"); 7199 7200 setFunctionHasBranchProtectedScope(); 7201 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 7202 NestedLoopCount, Clauses, AStmt, B); 7203 } 7204 7205 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 7206 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7207 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7208 if (!AStmt) 7209 return StmtError(); 7210 7211 auto *CS = cast<CapturedStmt>(AStmt); 7212 // 1.2.2 OpenMP Language Terminology 7213 // Structured block - An executable statement with a single entry at the 7214 // top and a single exit at the bottom. 7215 // The point of exit cannot be a branch out of the structured block. 7216 // longjmp() and throw() must not violate the entry/exit criteria. 7217 CS->getCapturedDecl()->setNothrow(); 7218 for (int ThisCaptureLevel = 7219 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 7220 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7221 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7222 // 1.2.2 OpenMP Language Terminology 7223 // Structured block - An executable statement with a single entry at the 7224 // top and a single exit at the bottom. 7225 // The point of exit cannot be a branch out of the structured block. 7226 // longjmp() and throw() must not violate the entry/exit criteria. 7227 CS->getCapturedDecl()->setNothrow(); 7228 } 7229 7230 OMPLoopDirective::HelperExprs B; 7231 // In presence of clause 'collapse' with number of loops, it will 7232 // define the nested loops number. 7233 unsigned NestedLoopCount = checkOpenMPLoop( 7234 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7235 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7236 VarsWithImplicitDSA, B); 7237 if (NestedLoopCount == 0) 7238 return StmtError(); 7239 7240 assert((CurContext->isDependentContext() || B.builtAll()) && 7241 "omp for loop exprs were not built"); 7242 7243 setFunctionHasBranchProtectedScope(); 7244 return OMPDistributeParallelForDirective::Create( 7245 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 7246 DSAStack->isCancelRegion()); 7247 } 7248 7249 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 7250 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7251 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7252 if (!AStmt) 7253 return StmtError(); 7254 7255 auto *CS = cast<CapturedStmt>(AStmt); 7256 // 1.2.2 OpenMP Language Terminology 7257 // Structured block - An executable statement with a single entry at the 7258 // top and a single exit at the bottom. 7259 // The point of exit cannot be a branch out of the structured block. 7260 // longjmp() and throw() must not violate the entry/exit criteria. 7261 CS->getCapturedDecl()->setNothrow(); 7262 for (int ThisCaptureLevel = 7263 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 7264 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7265 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7266 // 1.2.2 OpenMP Language Terminology 7267 // Structured block - An executable statement with a single entry at the 7268 // top and a single exit at the bottom. 7269 // The point of exit cannot be a branch out of the structured block. 7270 // longjmp() and throw() must not violate the entry/exit criteria. 7271 CS->getCapturedDecl()->setNothrow(); 7272 } 7273 7274 OMPLoopDirective::HelperExprs B; 7275 // In presence of clause 'collapse' with number of loops, it will 7276 // define the nested loops number. 7277 unsigned NestedLoopCount = checkOpenMPLoop( 7278 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 7279 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7280 VarsWithImplicitDSA, B); 7281 if (NestedLoopCount == 0) 7282 return StmtError(); 7283 7284 assert((CurContext->isDependentContext() || B.builtAll()) && 7285 "omp for loop exprs were not built"); 7286 7287 if (!CurContext->isDependentContext()) { 7288 // Finalize the clauses that need pre-built expressions for CodeGen. 7289 for (OMPClause *C : Clauses) { 7290 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7291 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7292 B.NumIterations, *this, CurScope, 7293 DSAStack)) 7294 return StmtError(); 7295 } 7296 } 7297 7298 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7299 return StmtError(); 7300 7301 setFunctionHasBranchProtectedScope(); 7302 return OMPDistributeParallelForSimdDirective::Create( 7303 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7304 } 7305 7306 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 7307 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7308 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7309 if (!AStmt) 7310 return StmtError(); 7311 7312 auto *CS = cast<CapturedStmt>(AStmt); 7313 // 1.2.2 OpenMP Language Terminology 7314 // Structured block - An executable statement with a single entry at the 7315 // top and a single exit at the bottom. 7316 // The point of exit cannot be a branch out of the structured block. 7317 // longjmp() and throw() must not violate the entry/exit criteria. 7318 CS->getCapturedDecl()->setNothrow(); 7319 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 7320 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7321 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7322 // 1.2.2 OpenMP Language Terminology 7323 // Structured block - An executable statement with a single entry at the 7324 // top and a single exit at the bottom. 7325 // The point of exit cannot be a branch out of the structured block. 7326 // longjmp() and throw() must not violate the entry/exit criteria. 7327 CS->getCapturedDecl()->setNothrow(); 7328 } 7329 7330 OMPLoopDirective::HelperExprs B; 7331 // In presence of clause 'collapse' with number of loops, it will 7332 // define the nested loops number. 7333 unsigned NestedLoopCount = 7334 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 7335 nullptr /*ordered not a clause on distribute*/, CS, *this, 7336 *DSAStack, VarsWithImplicitDSA, B); 7337 if (NestedLoopCount == 0) 7338 return StmtError(); 7339 7340 assert((CurContext->isDependentContext() || B.builtAll()) && 7341 "omp for loop exprs were not built"); 7342 7343 if (!CurContext->isDependentContext()) { 7344 // Finalize the clauses that need pre-built expressions for CodeGen. 7345 for (OMPClause *C : Clauses) { 7346 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7347 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7348 B.NumIterations, *this, CurScope, 7349 DSAStack)) 7350 return StmtError(); 7351 } 7352 } 7353 7354 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7355 return StmtError(); 7356 7357 setFunctionHasBranchProtectedScope(); 7358 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 7359 NestedLoopCount, Clauses, AStmt, B); 7360 } 7361 7362 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 7363 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7364 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7365 if (!AStmt) 7366 return StmtError(); 7367 7368 auto *CS = cast<CapturedStmt>(AStmt); 7369 // 1.2.2 OpenMP Language Terminology 7370 // Structured block - An executable statement with a single entry at the 7371 // top and a single exit at the bottom. 7372 // The point of exit cannot be a branch out of the structured block. 7373 // longjmp() and throw() must not violate the entry/exit criteria. 7374 CS->getCapturedDecl()->setNothrow(); 7375 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 7376 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7377 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7378 // 1.2.2 OpenMP Language Terminology 7379 // Structured block - An executable statement with a single entry at the 7380 // top and a single exit at the bottom. 7381 // The point of exit cannot be a branch out of the structured block. 7382 // longjmp() and throw() must not violate the entry/exit criteria. 7383 CS->getCapturedDecl()->setNothrow(); 7384 } 7385 7386 OMPLoopDirective::HelperExprs B; 7387 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7388 // define the nested loops number. 7389 unsigned NestedLoopCount = checkOpenMPLoop( 7390 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 7391 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7392 VarsWithImplicitDSA, B); 7393 if (NestedLoopCount == 0) 7394 return StmtError(); 7395 7396 assert((CurContext->isDependentContext() || B.builtAll()) && 7397 "omp target parallel for simd loop exprs were not built"); 7398 7399 if (!CurContext->isDependentContext()) { 7400 // Finalize the clauses that need pre-built expressions for CodeGen. 7401 for (OMPClause *C : Clauses) { 7402 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7403 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7404 B.NumIterations, *this, CurScope, 7405 DSAStack)) 7406 return StmtError(); 7407 } 7408 } 7409 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7410 return StmtError(); 7411 7412 setFunctionHasBranchProtectedScope(); 7413 return OMPTargetParallelForSimdDirective::Create( 7414 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7415 } 7416 7417 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 7418 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7419 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7420 if (!AStmt) 7421 return StmtError(); 7422 7423 auto *CS = cast<CapturedStmt>(AStmt); 7424 // 1.2.2 OpenMP Language Terminology 7425 // Structured block - An executable statement with a single entry at the 7426 // top and a single exit at the bottom. 7427 // The point of exit cannot be a branch out of the structured block. 7428 // longjmp() and throw() must not violate the entry/exit criteria. 7429 CS->getCapturedDecl()->setNothrow(); 7430 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 7431 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7432 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7433 // 1.2.2 OpenMP Language Terminology 7434 // Structured block - An executable statement with a single entry at the 7435 // top and a single exit at the bottom. 7436 // The point of exit cannot be a branch out of the structured block. 7437 // longjmp() and throw() must not violate the entry/exit criteria. 7438 CS->getCapturedDecl()->setNothrow(); 7439 } 7440 7441 OMPLoopDirective::HelperExprs B; 7442 // In presence of clause 'collapse' with number of loops, it will define the 7443 // nested loops number. 7444 unsigned NestedLoopCount = 7445 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 7446 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7447 VarsWithImplicitDSA, B); 7448 if (NestedLoopCount == 0) 7449 return StmtError(); 7450 7451 assert((CurContext->isDependentContext() || B.builtAll()) && 7452 "omp target simd loop exprs were not built"); 7453 7454 if (!CurContext->isDependentContext()) { 7455 // Finalize the clauses that need pre-built expressions for CodeGen. 7456 for (OMPClause *C : Clauses) { 7457 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7458 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7459 B.NumIterations, *this, CurScope, 7460 DSAStack)) 7461 return StmtError(); 7462 } 7463 } 7464 7465 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7466 return StmtError(); 7467 7468 setFunctionHasBranchProtectedScope(); 7469 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 7470 NestedLoopCount, Clauses, AStmt, B); 7471 } 7472 7473 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 7474 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7475 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7476 if (!AStmt) 7477 return StmtError(); 7478 7479 auto *CS = cast<CapturedStmt>(AStmt); 7480 // 1.2.2 OpenMP Language Terminology 7481 // Structured block - An executable statement with a single entry at the 7482 // top and a single exit at the bottom. 7483 // The point of exit cannot be a branch out of the structured block. 7484 // longjmp() and throw() must not violate the entry/exit criteria. 7485 CS->getCapturedDecl()->setNothrow(); 7486 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 7487 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7488 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7489 // 1.2.2 OpenMP Language Terminology 7490 // Structured block - An executable statement with a single entry at the 7491 // top and a single exit at the bottom. 7492 // The point of exit cannot be a branch out of the structured block. 7493 // longjmp() and throw() must not violate the entry/exit criteria. 7494 CS->getCapturedDecl()->setNothrow(); 7495 } 7496 7497 OMPLoopDirective::HelperExprs B; 7498 // In presence of clause 'collapse' with number of loops, it will 7499 // define the nested loops number. 7500 unsigned NestedLoopCount = 7501 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 7502 nullptr /*ordered not a clause on distribute*/, CS, *this, 7503 *DSAStack, VarsWithImplicitDSA, B); 7504 if (NestedLoopCount == 0) 7505 return StmtError(); 7506 7507 assert((CurContext->isDependentContext() || B.builtAll()) && 7508 "omp teams distribute loop exprs were not built"); 7509 7510 setFunctionHasBranchProtectedScope(); 7511 7512 DSAStack->setParentTeamsRegionLoc(StartLoc); 7513 7514 return OMPTeamsDistributeDirective::Create( 7515 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7516 } 7517 7518 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 7519 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7520 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7521 if (!AStmt) 7522 return StmtError(); 7523 7524 auto *CS = cast<CapturedStmt>(AStmt); 7525 // 1.2.2 OpenMP Language Terminology 7526 // Structured block - An executable statement with a single entry at the 7527 // top and a single exit at the bottom. 7528 // The point of exit cannot be a branch out of the structured block. 7529 // longjmp() and throw() must not violate the entry/exit criteria. 7530 CS->getCapturedDecl()->setNothrow(); 7531 for (int ThisCaptureLevel = 7532 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 7533 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7534 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7535 // 1.2.2 OpenMP Language Terminology 7536 // Structured block - An executable statement with a single entry at the 7537 // top and a single exit at the bottom. 7538 // The point of exit cannot be a branch out of the structured block. 7539 // longjmp() and throw() must not violate the entry/exit criteria. 7540 CS->getCapturedDecl()->setNothrow(); 7541 } 7542 7543 7544 OMPLoopDirective::HelperExprs B; 7545 // In presence of clause 'collapse' with number of loops, it will 7546 // define the nested loops number. 7547 unsigned NestedLoopCount = checkOpenMPLoop( 7548 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 7549 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7550 VarsWithImplicitDSA, B); 7551 7552 if (NestedLoopCount == 0) 7553 return StmtError(); 7554 7555 assert((CurContext->isDependentContext() || B.builtAll()) && 7556 "omp teams distribute simd loop exprs were not built"); 7557 7558 if (!CurContext->isDependentContext()) { 7559 // Finalize the clauses that need pre-built expressions for CodeGen. 7560 for (OMPClause *C : Clauses) { 7561 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7562 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7563 B.NumIterations, *this, CurScope, 7564 DSAStack)) 7565 return StmtError(); 7566 } 7567 } 7568 7569 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7570 return StmtError(); 7571 7572 setFunctionHasBranchProtectedScope(); 7573 7574 DSAStack->setParentTeamsRegionLoc(StartLoc); 7575 7576 return OMPTeamsDistributeSimdDirective::Create( 7577 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7578 } 7579 7580 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 7581 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7582 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7583 if (!AStmt) 7584 return StmtError(); 7585 7586 auto *CS = cast<CapturedStmt>(AStmt); 7587 // 1.2.2 OpenMP Language Terminology 7588 // Structured block - An executable statement with a single entry at the 7589 // top and a single exit at the bottom. 7590 // The point of exit cannot be a branch out of the structured block. 7591 // longjmp() and throw() must not violate the entry/exit criteria. 7592 CS->getCapturedDecl()->setNothrow(); 7593 7594 for (int ThisCaptureLevel = 7595 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 7596 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7597 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7598 // 1.2.2 OpenMP Language Terminology 7599 // Structured block - An executable statement with a single entry at the 7600 // top and a single exit at the bottom. 7601 // The point of exit cannot be a branch out of the structured block. 7602 // longjmp() and throw() must not violate the entry/exit criteria. 7603 CS->getCapturedDecl()->setNothrow(); 7604 } 7605 7606 OMPLoopDirective::HelperExprs B; 7607 // In presence of clause 'collapse' with number of loops, it will 7608 // define the nested loops number. 7609 unsigned NestedLoopCount = checkOpenMPLoop( 7610 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 7611 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7612 VarsWithImplicitDSA, B); 7613 7614 if (NestedLoopCount == 0) 7615 return StmtError(); 7616 7617 assert((CurContext->isDependentContext() || B.builtAll()) && 7618 "omp for loop exprs were not built"); 7619 7620 if (!CurContext->isDependentContext()) { 7621 // Finalize the clauses that need pre-built expressions for CodeGen. 7622 for (OMPClause *C : Clauses) { 7623 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7624 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7625 B.NumIterations, *this, CurScope, 7626 DSAStack)) 7627 return StmtError(); 7628 } 7629 } 7630 7631 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7632 return StmtError(); 7633 7634 setFunctionHasBranchProtectedScope(); 7635 7636 DSAStack->setParentTeamsRegionLoc(StartLoc); 7637 7638 return OMPTeamsDistributeParallelForSimdDirective::Create( 7639 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7640 } 7641 7642 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 7643 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7644 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7645 if (!AStmt) 7646 return StmtError(); 7647 7648 auto *CS = cast<CapturedStmt>(AStmt); 7649 // 1.2.2 OpenMP Language Terminology 7650 // Structured block - An executable statement with a single entry at the 7651 // top and a single exit at the bottom. 7652 // The point of exit cannot be a branch out of the structured block. 7653 // longjmp() and throw() must not violate the entry/exit criteria. 7654 CS->getCapturedDecl()->setNothrow(); 7655 7656 for (int ThisCaptureLevel = 7657 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 7658 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7659 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7660 // 1.2.2 OpenMP Language Terminology 7661 // Structured block - An executable statement with a single entry at the 7662 // top and a single exit at the bottom. 7663 // The point of exit cannot be a branch out of the structured block. 7664 // longjmp() and throw() must not violate the entry/exit criteria. 7665 CS->getCapturedDecl()->setNothrow(); 7666 } 7667 7668 OMPLoopDirective::HelperExprs B; 7669 // In presence of clause 'collapse' with number of loops, it will 7670 // define the nested loops number. 7671 unsigned NestedLoopCount = checkOpenMPLoop( 7672 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7673 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7674 VarsWithImplicitDSA, B); 7675 7676 if (NestedLoopCount == 0) 7677 return StmtError(); 7678 7679 assert((CurContext->isDependentContext() || B.builtAll()) && 7680 "omp for loop exprs were not built"); 7681 7682 setFunctionHasBranchProtectedScope(); 7683 7684 DSAStack->setParentTeamsRegionLoc(StartLoc); 7685 7686 return OMPTeamsDistributeParallelForDirective::Create( 7687 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 7688 DSAStack->isCancelRegion()); 7689 } 7690 7691 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 7692 Stmt *AStmt, 7693 SourceLocation StartLoc, 7694 SourceLocation EndLoc) { 7695 if (!AStmt) 7696 return StmtError(); 7697 7698 auto *CS = cast<CapturedStmt>(AStmt); 7699 // 1.2.2 OpenMP Language Terminology 7700 // Structured block - An executable statement with a single entry at the 7701 // top and a single exit at the bottom. 7702 // The point of exit cannot be a branch out of the structured block. 7703 // longjmp() and throw() must not violate the entry/exit criteria. 7704 CS->getCapturedDecl()->setNothrow(); 7705 7706 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 7707 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7708 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7709 // 1.2.2 OpenMP Language Terminology 7710 // Structured block - An executable statement with a single entry at the 7711 // top and a single exit at the bottom. 7712 // The point of exit cannot be a branch out of the structured block. 7713 // longjmp() and throw() must not violate the entry/exit criteria. 7714 CS->getCapturedDecl()->setNothrow(); 7715 } 7716 setFunctionHasBranchProtectedScope(); 7717 7718 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 7719 AStmt); 7720 } 7721 7722 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 7723 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7724 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7725 if (!AStmt) 7726 return StmtError(); 7727 7728 auto *CS = cast<CapturedStmt>(AStmt); 7729 // 1.2.2 OpenMP Language Terminology 7730 // Structured block - An executable statement with a single entry at the 7731 // top and a single exit at the bottom. 7732 // The point of exit cannot be a branch out of the structured block. 7733 // longjmp() and throw() must not violate the entry/exit criteria. 7734 CS->getCapturedDecl()->setNothrow(); 7735 for (int ThisCaptureLevel = 7736 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 7737 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7738 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7739 // 1.2.2 OpenMP Language Terminology 7740 // Structured block - An executable statement with a single entry at the 7741 // top and a single exit at the bottom. 7742 // The point of exit cannot be a branch out of the structured block. 7743 // longjmp() and throw() must not violate the entry/exit criteria. 7744 CS->getCapturedDecl()->setNothrow(); 7745 } 7746 7747 OMPLoopDirective::HelperExprs B; 7748 // In presence of clause 'collapse' with number of loops, it will 7749 // define the nested loops number. 7750 unsigned NestedLoopCount = checkOpenMPLoop( 7751 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 7752 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7753 VarsWithImplicitDSA, B); 7754 if (NestedLoopCount == 0) 7755 return StmtError(); 7756 7757 assert((CurContext->isDependentContext() || B.builtAll()) && 7758 "omp target teams distribute loop exprs were not built"); 7759 7760 setFunctionHasBranchProtectedScope(); 7761 return OMPTargetTeamsDistributeDirective::Create( 7762 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7763 } 7764 7765 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 7766 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7767 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7768 if (!AStmt) 7769 return StmtError(); 7770 7771 auto *CS = cast<CapturedStmt>(AStmt); 7772 // 1.2.2 OpenMP Language Terminology 7773 // Structured block - An executable statement with a single entry at the 7774 // top and a single exit at the bottom. 7775 // The point of exit cannot be a branch out of the structured block. 7776 // longjmp() and throw() must not violate the entry/exit criteria. 7777 CS->getCapturedDecl()->setNothrow(); 7778 for (int ThisCaptureLevel = 7779 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 7780 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7781 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7782 // 1.2.2 OpenMP Language Terminology 7783 // Structured block - An executable statement with a single entry at the 7784 // top and a single exit at the bottom. 7785 // The point of exit cannot be a branch out of the structured block. 7786 // longjmp() and throw() must not violate the entry/exit criteria. 7787 CS->getCapturedDecl()->setNothrow(); 7788 } 7789 7790 OMPLoopDirective::HelperExprs B; 7791 // In presence of clause 'collapse' with number of loops, it will 7792 // define the nested loops number. 7793 unsigned NestedLoopCount = checkOpenMPLoop( 7794 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7795 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7796 VarsWithImplicitDSA, B); 7797 if (NestedLoopCount == 0) 7798 return StmtError(); 7799 7800 assert((CurContext->isDependentContext() || B.builtAll()) && 7801 "omp target teams distribute parallel for loop exprs were not built"); 7802 7803 if (!CurContext->isDependentContext()) { 7804 // Finalize the clauses that need pre-built expressions for CodeGen. 7805 for (OMPClause *C : Clauses) { 7806 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7807 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7808 B.NumIterations, *this, CurScope, 7809 DSAStack)) 7810 return StmtError(); 7811 } 7812 } 7813 7814 setFunctionHasBranchProtectedScope(); 7815 return OMPTargetTeamsDistributeParallelForDirective::Create( 7816 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 7817 DSAStack->isCancelRegion()); 7818 } 7819 7820 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 7821 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7822 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7823 if (!AStmt) 7824 return StmtError(); 7825 7826 auto *CS = cast<CapturedStmt>(AStmt); 7827 // 1.2.2 OpenMP Language Terminology 7828 // Structured block - An executable statement with a single entry at the 7829 // top and a single exit at the bottom. 7830 // The point of exit cannot be a branch out of the structured block. 7831 // longjmp() and throw() must not violate the entry/exit criteria. 7832 CS->getCapturedDecl()->setNothrow(); 7833 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 7834 OMPD_target_teams_distribute_parallel_for_simd); 7835 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7836 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7837 // 1.2.2 OpenMP Language Terminology 7838 // Structured block - An executable statement with a single entry at the 7839 // top and a single exit at the bottom. 7840 // The point of exit cannot be a branch out of the structured block. 7841 // longjmp() and throw() must not violate the entry/exit criteria. 7842 CS->getCapturedDecl()->setNothrow(); 7843 } 7844 7845 OMPLoopDirective::HelperExprs B; 7846 // In presence of clause 'collapse' with number of loops, it will 7847 // define the nested loops number. 7848 unsigned NestedLoopCount = 7849 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 7850 getCollapseNumberExpr(Clauses), 7851 nullptr /*ordered not a clause on distribute*/, CS, *this, 7852 *DSAStack, VarsWithImplicitDSA, B); 7853 if (NestedLoopCount == 0) 7854 return StmtError(); 7855 7856 assert((CurContext->isDependentContext() || B.builtAll()) && 7857 "omp target teams distribute parallel for simd loop exprs were not " 7858 "built"); 7859 7860 if (!CurContext->isDependentContext()) { 7861 // Finalize the clauses that need pre-built expressions for CodeGen. 7862 for (OMPClause *C : Clauses) { 7863 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7864 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7865 B.NumIterations, *this, CurScope, 7866 DSAStack)) 7867 return StmtError(); 7868 } 7869 } 7870 7871 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7872 return StmtError(); 7873 7874 setFunctionHasBranchProtectedScope(); 7875 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 7876 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7877 } 7878 7879 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 7880 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7881 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7882 if (!AStmt) 7883 return StmtError(); 7884 7885 auto *CS = cast<CapturedStmt>(AStmt); 7886 // 1.2.2 OpenMP Language Terminology 7887 // Structured block - An executable statement with a single entry at the 7888 // top and a single exit at the bottom. 7889 // The point of exit cannot be a branch out of the structured block. 7890 // longjmp() and throw() must not violate the entry/exit criteria. 7891 CS->getCapturedDecl()->setNothrow(); 7892 for (int ThisCaptureLevel = 7893 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 7894 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7895 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7896 // 1.2.2 OpenMP Language Terminology 7897 // Structured block - An executable statement with a single entry at the 7898 // top and a single exit at the bottom. 7899 // The point of exit cannot be a branch out of the structured block. 7900 // longjmp() and throw() must not violate the entry/exit criteria. 7901 CS->getCapturedDecl()->setNothrow(); 7902 } 7903 7904 OMPLoopDirective::HelperExprs B; 7905 // In presence of clause 'collapse' with number of loops, it will 7906 // define the nested loops number. 7907 unsigned NestedLoopCount = checkOpenMPLoop( 7908 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 7909 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7910 VarsWithImplicitDSA, B); 7911 if (NestedLoopCount == 0) 7912 return StmtError(); 7913 7914 assert((CurContext->isDependentContext() || B.builtAll()) && 7915 "omp target teams distribute simd loop exprs were not built"); 7916 7917 if (!CurContext->isDependentContext()) { 7918 // Finalize the clauses that need pre-built expressions for CodeGen. 7919 for (OMPClause *C : Clauses) { 7920 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7921 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7922 B.NumIterations, *this, CurScope, 7923 DSAStack)) 7924 return StmtError(); 7925 } 7926 } 7927 7928 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7929 return StmtError(); 7930 7931 setFunctionHasBranchProtectedScope(); 7932 return OMPTargetTeamsDistributeSimdDirective::Create( 7933 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7934 } 7935 7936 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 7937 SourceLocation StartLoc, 7938 SourceLocation LParenLoc, 7939 SourceLocation EndLoc) { 7940 OMPClause *Res = nullptr; 7941 switch (Kind) { 7942 case OMPC_final: 7943 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 7944 break; 7945 case OMPC_num_threads: 7946 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 7947 break; 7948 case OMPC_safelen: 7949 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 7950 break; 7951 case OMPC_simdlen: 7952 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 7953 break; 7954 case OMPC_collapse: 7955 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 7956 break; 7957 case OMPC_ordered: 7958 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 7959 break; 7960 case OMPC_device: 7961 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 7962 break; 7963 case OMPC_num_teams: 7964 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 7965 break; 7966 case OMPC_thread_limit: 7967 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 7968 break; 7969 case OMPC_priority: 7970 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 7971 break; 7972 case OMPC_grainsize: 7973 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 7974 break; 7975 case OMPC_num_tasks: 7976 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 7977 break; 7978 case OMPC_hint: 7979 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 7980 break; 7981 case OMPC_if: 7982 case OMPC_default: 7983 case OMPC_proc_bind: 7984 case OMPC_schedule: 7985 case OMPC_private: 7986 case OMPC_firstprivate: 7987 case OMPC_lastprivate: 7988 case OMPC_shared: 7989 case OMPC_reduction: 7990 case OMPC_task_reduction: 7991 case OMPC_in_reduction: 7992 case OMPC_linear: 7993 case OMPC_aligned: 7994 case OMPC_copyin: 7995 case OMPC_copyprivate: 7996 case OMPC_nowait: 7997 case OMPC_untied: 7998 case OMPC_mergeable: 7999 case OMPC_threadprivate: 8000 case OMPC_flush: 8001 case OMPC_read: 8002 case OMPC_write: 8003 case OMPC_update: 8004 case OMPC_capture: 8005 case OMPC_seq_cst: 8006 case OMPC_depend: 8007 case OMPC_threads: 8008 case OMPC_simd: 8009 case OMPC_map: 8010 case OMPC_nogroup: 8011 case OMPC_dist_schedule: 8012 case OMPC_defaultmap: 8013 case OMPC_unknown: 8014 case OMPC_uniform: 8015 case OMPC_to: 8016 case OMPC_from: 8017 case OMPC_use_device_ptr: 8018 case OMPC_is_device_ptr: 8019 case OMPC_unified_address: 8020 case OMPC_unified_shared_memory: 8021 case OMPC_reverse_offload: 8022 case OMPC_dynamic_allocators: 8023 llvm_unreachable("Clause is not allowed."); 8024 } 8025 return Res; 8026 } 8027 8028 // An OpenMP directive such as 'target parallel' has two captured regions: 8029 // for the 'target' and 'parallel' respectively. This function returns 8030 // the region in which to capture expressions associated with a clause. 8031 // A return value of OMPD_unknown signifies that the expression should not 8032 // be captured. 8033 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 8034 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 8035 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 8036 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 8037 switch (CKind) { 8038 case OMPC_if: 8039 switch (DKind) { 8040 case OMPD_target_parallel: 8041 case OMPD_target_parallel_for: 8042 case OMPD_target_parallel_for_simd: 8043 // If this clause applies to the nested 'parallel' region, capture within 8044 // the 'target' region, otherwise do not capture. 8045 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 8046 CaptureRegion = OMPD_target; 8047 break; 8048 case OMPD_target_teams_distribute_parallel_for: 8049 case OMPD_target_teams_distribute_parallel_for_simd: 8050 // If this clause applies to the nested 'parallel' region, capture within 8051 // the 'teams' region, otherwise do not capture. 8052 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 8053 CaptureRegion = OMPD_teams; 8054 break; 8055 case OMPD_teams_distribute_parallel_for: 8056 case OMPD_teams_distribute_parallel_for_simd: 8057 CaptureRegion = OMPD_teams; 8058 break; 8059 case OMPD_target_update: 8060 case OMPD_target_enter_data: 8061 case OMPD_target_exit_data: 8062 CaptureRegion = OMPD_task; 8063 break; 8064 case OMPD_cancel: 8065 case OMPD_parallel: 8066 case OMPD_parallel_sections: 8067 case OMPD_parallel_for: 8068 case OMPD_parallel_for_simd: 8069 case OMPD_target: 8070 case OMPD_target_simd: 8071 case OMPD_target_teams: 8072 case OMPD_target_teams_distribute: 8073 case OMPD_target_teams_distribute_simd: 8074 case OMPD_distribute_parallel_for: 8075 case OMPD_distribute_parallel_for_simd: 8076 case OMPD_task: 8077 case OMPD_taskloop: 8078 case OMPD_taskloop_simd: 8079 case OMPD_target_data: 8080 // Do not capture if-clause expressions. 8081 break; 8082 case OMPD_threadprivate: 8083 case OMPD_taskyield: 8084 case OMPD_barrier: 8085 case OMPD_taskwait: 8086 case OMPD_cancellation_point: 8087 case OMPD_flush: 8088 case OMPD_declare_reduction: 8089 case OMPD_declare_simd: 8090 case OMPD_declare_target: 8091 case OMPD_end_declare_target: 8092 case OMPD_teams: 8093 case OMPD_simd: 8094 case OMPD_for: 8095 case OMPD_for_simd: 8096 case OMPD_sections: 8097 case OMPD_section: 8098 case OMPD_single: 8099 case OMPD_master: 8100 case OMPD_critical: 8101 case OMPD_taskgroup: 8102 case OMPD_distribute: 8103 case OMPD_ordered: 8104 case OMPD_atomic: 8105 case OMPD_distribute_simd: 8106 case OMPD_teams_distribute: 8107 case OMPD_teams_distribute_simd: 8108 case OMPD_requires: 8109 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 8110 case OMPD_unknown: 8111 llvm_unreachable("Unknown OpenMP directive"); 8112 } 8113 break; 8114 case OMPC_num_threads: 8115 switch (DKind) { 8116 case OMPD_target_parallel: 8117 case OMPD_target_parallel_for: 8118 case OMPD_target_parallel_for_simd: 8119 CaptureRegion = OMPD_target; 8120 break; 8121 case OMPD_teams_distribute_parallel_for: 8122 case OMPD_teams_distribute_parallel_for_simd: 8123 case OMPD_target_teams_distribute_parallel_for: 8124 case OMPD_target_teams_distribute_parallel_for_simd: 8125 CaptureRegion = OMPD_teams; 8126 break; 8127 case OMPD_parallel: 8128 case OMPD_parallel_sections: 8129 case OMPD_parallel_for: 8130 case OMPD_parallel_for_simd: 8131 case OMPD_distribute_parallel_for: 8132 case OMPD_distribute_parallel_for_simd: 8133 // Do not capture num_threads-clause expressions. 8134 break; 8135 case OMPD_target_data: 8136 case OMPD_target_enter_data: 8137 case OMPD_target_exit_data: 8138 case OMPD_target_update: 8139 case OMPD_target: 8140 case OMPD_target_simd: 8141 case OMPD_target_teams: 8142 case OMPD_target_teams_distribute: 8143 case OMPD_target_teams_distribute_simd: 8144 case OMPD_cancel: 8145 case OMPD_task: 8146 case OMPD_taskloop: 8147 case OMPD_taskloop_simd: 8148 case OMPD_threadprivate: 8149 case OMPD_taskyield: 8150 case OMPD_barrier: 8151 case OMPD_taskwait: 8152 case OMPD_cancellation_point: 8153 case OMPD_flush: 8154 case OMPD_declare_reduction: 8155 case OMPD_declare_simd: 8156 case OMPD_declare_target: 8157 case OMPD_end_declare_target: 8158 case OMPD_teams: 8159 case OMPD_simd: 8160 case OMPD_for: 8161 case OMPD_for_simd: 8162 case OMPD_sections: 8163 case OMPD_section: 8164 case OMPD_single: 8165 case OMPD_master: 8166 case OMPD_critical: 8167 case OMPD_taskgroup: 8168 case OMPD_distribute: 8169 case OMPD_ordered: 8170 case OMPD_atomic: 8171 case OMPD_distribute_simd: 8172 case OMPD_teams_distribute: 8173 case OMPD_teams_distribute_simd: 8174 case OMPD_requires: 8175 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 8176 case OMPD_unknown: 8177 llvm_unreachable("Unknown OpenMP directive"); 8178 } 8179 break; 8180 case OMPC_num_teams: 8181 switch (DKind) { 8182 case OMPD_target_teams: 8183 case OMPD_target_teams_distribute: 8184 case OMPD_target_teams_distribute_simd: 8185 case OMPD_target_teams_distribute_parallel_for: 8186 case OMPD_target_teams_distribute_parallel_for_simd: 8187 CaptureRegion = OMPD_target; 8188 break; 8189 case OMPD_teams_distribute_parallel_for: 8190 case OMPD_teams_distribute_parallel_for_simd: 8191 case OMPD_teams: 8192 case OMPD_teams_distribute: 8193 case OMPD_teams_distribute_simd: 8194 // Do not capture num_teams-clause expressions. 8195 break; 8196 case OMPD_distribute_parallel_for: 8197 case OMPD_distribute_parallel_for_simd: 8198 case OMPD_task: 8199 case OMPD_taskloop: 8200 case OMPD_taskloop_simd: 8201 case OMPD_target_data: 8202 case OMPD_target_enter_data: 8203 case OMPD_target_exit_data: 8204 case OMPD_target_update: 8205 case OMPD_cancel: 8206 case OMPD_parallel: 8207 case OMPD_parallel_sections: 8208 case OMPD_parallel_for: 8209 case OMPD_parallel_for_simd: 8210 case OMPD_target: 8211 case OMPD_target_simd: 8212 case OMPD_target_parallel: 8213 case OMPD_target_parallel_for: 8214 case OMPD_target_parallel_for_simd: 8215 case OMPD_threadprivate: 8216 case OMPD_taskyield: 8217 case OMPD_barrier: 8218 case OMPD_taskwait: 8219 case OMPD_cancellation_point: 8220 case OMPD_flush: 8221 case OMPD_declare_reduction: 8222 case OMPD_declare_simd: 8223 case OMPD_declare_target: 8224 case OMPD_end_declare_target: 8225 case OMPD_simd: 8226 case OMPD_for: 8227 case OMPD_for_simd: 8228 case OMPD_sections: 8229 case OMPD_section: 8230 case OMPD_single: 8231 case OMPD_master: 8232 case OMPD_critical: 8233 case OMPD_taskgroup: 8234 case OMPD_distribute: 8235 case OMPD_ordered: 8236 case OMPD_atomic: 8237 case OMPD_distribute_simd: 8238 case OMPD_requires: 8239 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 8240 case OMPD_unknown: 8241 llvm_unreachable("Unknown OpenMP directive"); 8242 } 8243 break; 8244 case OMPC_thread_limit: 8245 switch (DKind) { 8246 case OMPD_target_teams: 8247 case OMPD_target_teams_distribute: 8248 case OMPD_target_teams_distribute_simd: 8249 case OMPD_target_teams_distribute_parallel_for: 8250 case OMPD_target_teams_distribute_parallel_for_simd: 8251 CaptureRegion = OMPD_target; 8252 break; 8253 case OMPD_teams_distribute_parallel_for: 8254 case OMPD_teams_distribute_parallel_for_simd: 8255 case OMPD_teams: 8256 case OMPD_teams_distribute: 8257 case OMPD_teams_distribute_simd: 8258 // Do not capture thread_limit-clause expressions. 8259 break; 8260 case OMPD_distribute_parallel_for: 8261 case OMPD_distribute_parallel_for_simd: 8262 case OMPD_task: 8263 case OMPD_taskloop: 8264 case OMPD_taskloop_simd: 8265 case OMPD_target_data: 8266 case OMPD_target_enter_data: 8267 case OMPD_target_exit_data: 8268 case OMPD_target_update: 8269 case OMPD_cancel: 8270 case OMPD_parallel: 8271 case OMPD_parallel_sections: 8272 case OMPD_parallel_for: 8273 case OMPD_parallel_for_simd: 8274 case OMPD_target: 8275 case OMPD_target_simd: 8276 case OMPD_target_parallel: 8277 case OMPD_target_parallel_for: 8278 case OMPD_target_parallel_for_simd: 8279 case OMPD_threadprivate: 8280 case OMPD_taskyield: 8281 case OMPD_barrier: 8282 case OMPD_taskwait: 8283 case OMPD_cancellation_point: 8284 case OMPD_flush: 8285 case OMPD_declare_reduction: 8286 case OMPD_declare_simd: 8287 case OMPD_declare_target: 8288 case OMPD_end_declare_target: 8289 case OMPD_simd: 8290 case OMPD_for: 8291 case OMPD_for_simd: 8292 case OMPD_sections: 8293 case OMPD_section: 8294 case OMPD_single: 8295 case OMPD_master: 8296 case OMPD_critical: 8297 case OMPD_taskgroup: 8298 case OMPD_distribute: 8299 case OMPD_ordered: 8300 case OMPD_atomic: 8301 case OMPD_distribute_simd: 8302 case OMPD_requires: 8303 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 8304 case OMPD_unknown: 8305 llvm_unreachable("Unknown OpenMP directive"); 8306 } 8307 break; 8308 case OMPC_schedule: 8309 switch (DKind) { 8310 case OMPD_parallel_for: 8311 case OMPD_parallel_for_simd: 8312 case OMPD_distribute_parallel_for: 8313 case OMPD_distribute_parallel_for_simd: 8314 case OMPD_teams_distribute_parallel_for: 8315 case OMPD_teams_distribute_parallel_for_simd: 8316 case OMPD_target_parallel_for: 8317 case OMPD_target_parallel_for_simd: 8318 case OMPD_target_teams_distribute_parallel_for: 8319 case OMPD_target_teams_distribute_parallel_for_simd: 8320 CaptureRegion = OMPD_parallel; 8321 break; 8322 case OMPD_for: 8323 case OMPD_for_simd: 8324 // Do not capture schedule-clause expressions. 8325 break; 8326 case OMPD_task: 8327 case OMPD_taskloop: 8328 case OMPD_taskloop_simd: 8329 case OMPD_target_data: 8330 case OMPD_target_enter_data: 8331 case OMPD_target_exit_data: 8332 case OMPD_target_update: 8333 case OMPD_teams: 8334 case OMPD_teams_distribute: 8335 case OMPD_teams_distribute_simd: 8336 case OMPD_target_teams_distribute: 8337 case OMPD_target_teams_distribute_simd: 8338 case OMPD_target: 8339 case OMPD_target_simd: 8340 case OMPD_target_parallel: 8341 case OMPD_cancel: 8342 case OMPD_parallel: 8343 case OMPD_parallel_sections: 8344 case OMPD_threadprivate: 8345 case OMPD_taskyield: 8346 case OMPD_barrier: 8347 case OMPD_taskwait: 8348 case OMPD_cancellation_point: 8349 case OMPD_flush: 8350 case OMPD_declare_reduction: 8351 case OMPD_declare_simd: 8352 case OMPD_declare_target: 8353 case OMPD_end_declare_target: 8354 case OMPD_simd: 8355 case OMPD_sections: 8356 case OMPD_section: 8357 case OMPD_single: 8358 case OMPD_master: 8359 case OMPD_critical: 8360 case OMPD_taskgroup: 8361 case OMPD_distribute: 8362 case OMPD_ordered: 8363 case OMPD_atomic: 8364 case OMPD_distribute_simd: 8365 case OMPD_target_teams: 8366 case OMPD_requires: 8367 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 8368 case OMPD_unknown: 8369 llvm_unreachable("Unknown OpenMP directive"); 8370 } 8371 break; 8372 case OMPC_dist_schedule: 8373 switch (DKind) { 8374 case OMPD_teams_distribute_parallel_for: 8375 case OMPD_teams_distribute_parallel_for_simd: 8376 case OMPD_teams_distribute: 8377 case OMPD_teams_distribute_simd: 8378 case OMPD_target_teams_distribute_parallel_for: 8379 case OMPD_target_teams_distribute_parallel_for_simd: 8380 case OMPD_target_teams_distribute: 8381 case OMPD_target_teams_distribute_simd: 8382 CaptureRegion = OMPD_teams; 8383 break; 8384 case OMPD_distribute_parallel_for: 8385 case OMPD_distribute_parallel_for_simd: 8386 case OMPD_distribute: 8387 case OMPD_distribute_simd: 8388 // Do not capture thread_limit-clause expressions. 8389 break; 8390 case OMPD_parallel_for: 8391 case OMPD_parallel_for_simd: 8392 case OMPD_target_parallel_for_simd: 8393 case OMPD_target_parallel_for: 8394 case OMPD_task: 8395 case OMPD_taskloop: 8396 case OMPD_taskloop_simd: 8397 case OMPD_target_data: 8398 case OMPD_target_enter_data: 8399 case OMPD_target_exit_data: 8400 case OMPD_target_update: 8401 case OMPD_teams: 8402 case OMPD_target: 8403 case OMPD_target_simd: 8404 case OMPD_target_parallel: 8405 case OMPD_cancel: 8406 case OMPD_parallel: 8407 case OMPD_parallel_sections: 8408 case OMPD_threadprivate: 8409 case OMPD_taskyield: 8410 case OMPD_barrier: 8411 case OMPD_taskwait: 8412 case OMPD_cancellation_point: 8413 case OMPD_flush: 8414 case OMPD_declare_reduction: 8415 case OMPD_declare_simd: 8416 case OMPD_declare_target: 8417 case OMPD_end_declare_target: 8418 case OMPD_simd: 8419 case OMPD_for: 8420 case OMPD_for_simd: 8421 case OMPD_sections: 8422 case OMPD_section: 8423 case OMPD_single: 8424 case OMPD_master: 8425 case OMPD_critical: 8426 case OMPD_taskgroup: 8427 case OMPD_ordered: 8428 case OMPD_atomic: 8429 case OMPD_target_teams: 8430 case OMPD_requires: 8431 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 8432 case OMPD_unknown: 8433 llvm_unreachable("Unknown OpenMP directive"); 8434 } 8435 break; 8436 case OMPC_device: 8437 switch (DKind) { 8438 case OMPD_target_update: 8439 case OMPD_target_enter_data: 8440 case OMPD_target_exit_data: 8441 case OMPD_target: 8442 case OMPD_target_simd: 8443 case OMPD_target_teams: 8444 case OMPD_target_parallel: 8445 case OMPD_target_teams_distribute: 8446 case OMPD_target_teams_distribute_simd: 8447 case OMPD_target_parallel_for: 8448 case OMPD_target_parallel_for_simd: 8449 case OMPD_target_teams_distribute_parallel_for: 8450 case OMPD_target_teams_distribute_parallel_for_simd: 8451 CaptureRegion = OMPD_task; 8452 break; 8453 case OMPD_target_data: 8454 // Do not capture device-clause expressions. 8455 break; 8456 case OMPD_teams_distribute_parallel_for: 8457 case OMPD_teams_distribute_parallel_for_simd: 8458 case OMPD_teams: 8459 case OMPD_teams_distribute: 8460 case OMPD_teams_distribute_simd: 8461 case OMPD_distribute_parallel_for: 8462 case OMPD_distribute_parallel_for_simd: 8463 case OMPD_task: 8464 case OMPD_taskloop: 8465 case OMPD_taskloop_simd: 8466 case OMPD_cancel: 8467 case OMPD_parallel: 8468 case OMPD_parallel_sections: 8469 case OMPD_parallel_for: 8470 case OMPD_parallel_for_simd: 8471 case OMPD_threadprivate: 8472 case OMPD_taskyield: 8473 case OMPD_barrier: 8474 case OMPD_taskwait: 8475 case OMPD_cancellation_point: 8476 case OMPD_flush: 8477 case OMPD_declare_reduction: 8478 case OMPD_declare_simd: 8479 case OMPD_declare_target: 8480 case OMPD_end_declare_target: 8481 case OMPD_simd: 8482 case OMPD_for: 8483 case OMPD_for_simd: 8484 case OMPD_sections: 8485 case OMPD_section: 8486 case OMPD_single: 8487 case OMPD_master: 8488 case OMPD_critical: 8489 case OMPD_taskgroup: 8490 case OMPD_distribute: 8491 case OMPD_ordered: 8492 case OMPD_atomic: 8493 case OMPD_distribute_simd: 8494 case OMPD_requires: 8495 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 8496 case OMPD_unknown: 8497 llvm_unreachable("Unknown OpenMP directive"); 8498 } 8499 break; 8500 case OMPC_firstprivate: 8501 case OMPC_lastprivate: 8502 case OMPC_reduction: 8503 case OMPC_task_reduction: 8504 case OMPC_in_reduction: 8505 case OMPC_linear: 8506 case OMPC_default: 8507 case OMPC_proc_bind: 8508 case OMPC_final: 8509 case OMPC_safelen: 8510 case OMPC_simdlen: 8511 case OMPC_collapse: 8512 case OMPC_private: 8513 case OMPC_shared: 8514 case OMPC_aligned: 8515 case OMPC_copyin: 8516 case OMPC_copyprivate: 8517 case OMPC_ordered: 8518 case OMPC_nowait: 8519 case OMPC_untied: 8520 case OMPC_mergeable: 8521 case OMPC_threadprivate: 8522 case OMPC_flush: 8523 case OMPC_read: 8524 case OMPC_write: 8525 case OMPC_update: 8526 case OMPC_capture: 8527 case OMPC_seq_cst: 8528 case OMPC_depend: 8529 case OMPC_threads: 8530 case OMPC_simd: 8531 case OMPC_map: 8532 case OMPC_priority: 8533 case OMPC_grainsize: 8534 case OMPC_nogroup: 8535 case OMPC_num_tasks: 8536 case OMPC_hint: 8537 case OMPC_defaultmap: 8538 case OMPC_unknown: 8539 case OMPC_uniform: 8540 case OMPC_to: 8541 case OMPC_from: 8542 case OMPC_use_device_ptr: 8543 case OMPC_is_device_ptr: 8544 case OMPC_unified_address: 8545 case OMPC_unified_shared_memory: 8546 case OMPC_reverse_offload: 8547 case OMPC_dynamic_allocators: 8548 llvm_unreachable("Unexpected OpenMP clause."); 8549 } 8550 return CaptureRegion; 8551 } 8552 8553 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 8554 Expr *Condition, SourceLocation StartLoc, 8555 SourceLocation LParenLoc, 8556 SourceLocation NameModifierLoc, 8557 SourceLocation ColonLoc, 8558 SourceLocation EndLoc) { 8559 Expr *ValExpr = Condition; 8560 Stmt *HelperValStmt = nullptr; 8561 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 8562 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 8563 !Condition->isInstantiationDependent() && 8564 !Condition->containsUnexpandedParameterPack()) { 8565 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 8566 if (Val.isInvalid()) 8567 return nullptr; 8568 8569 ValExpr = Val.get(); 8570 8571 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8572 CaptureRegion = 8573 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 8574 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 8575 ValExpr = MakeFullExpr(ValExpr).get(); 8576 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 8577 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 8578 HelperValStmt = buildPreInits(Context, Captures); 8579 } 8580 } 8581 8582 return new (Context) 8583 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 8584 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 8585 } 8586 8587 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 8588 SourceLocation StartLoc, 8589 SourceLocation LParenLoc, 8590 SourceLocation EndLoc) { 8591 Expr *ValExpr = Condition; 8592 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 8593 !Condition->isInstantiationDependent() && 8594 !Condition->containsUnexpandedParameterPack()) { 8595 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 8596 if (Val.isInvalid()) 8597 return nullptr; 8598 8599 ValExpr = MakeFullExpr(Val.get()).get(); 8600 } 8601 8602 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 8603 } 8604 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 8605 Expr *Op) { 8606 if (!Op) 8607 return ExprError(); 8608 8609 class IntConvertDiagnoser : public ICEConvertDiagnoser { 8610 public: 8611 IntConvertDiagnoser() 8612 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 8613 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 8614 QualType T) override { 8615 return S.Diag(Loc, diag::err_omp_not_integral) << T; 8616 } 8617 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 8618 QualType T) override { 8619 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 8620 } 8621 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 8622 QualType T, 8623 QualType ConvTy) override { 8624 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 8625 } 8626 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 8627 QualType ConvTy) override { 8628 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 8629 << ConvTy->isEnumeralType() << ConvTy; 8630 } 8631 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 8632 QualType T) override { 8633 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 8634 } 8635 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 8636 QualType ConvTy) override { 8637 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 8638 << ConvTy->isEnumeralType() << ConvTy; 8639 } 8640 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 8641 QualType) override { 8642 llvm_unreachable("conversion functions are permitted"); 8643 } 8644 } ConvertDiagnoser; 8645 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 8646 } 8647 8648 static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 8649 OpenMPClauseKind CKind, 8650 bool StrictlyPositive) { 8651 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 8652 !ValExpr->isInstantiationDependent()) { 8653 SourceLocation Loc = ValExpr->getExprLoc(); 8654 ExprResult Value = 8655 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 8656 if (Value.isInvalid()) 8657 return false; 8658 8659 ValExpr = Value.get(); 8660 // The expression must evaluate to a non-negative integer value. 8661 llvm::APSInt Result; 8662 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 8663 Result.isSigned() && 8664 !((!StrictlyPositive && Result.isNonNegative()) || 8665 (StrictlyPositive && Result.isStrictlyPositive()))) { 8666 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 8667 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 8668 << ValExpr->getSourceRange(); 8669 return false; 8670 } 8671 } 8672 return true; 8673 } 8674 8675 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 8676 SourceLocation StartLoc, 8677 SourceLocation LParenLoc, 8678 SourceLocation EndLoc) { 8679 Expr *ValExpr = NumThreads; 8680 Stmt *HelperValStmt = nullptr; 8681 8682 // OpenMP [2.5, Restrictions] 8683 // The num_threads expression must evaluate to a positive integer value. 8684 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 8685 /*StrictlyPositive=*/true)) 8686 return nullptr; 8687 8688 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8689 OpenMPDirectiveKind CaptureRegion = 8690 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 8691 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 8692 ValExpr = MakeFullExpr(ValExpr).get(); 8693 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 8694 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 8695 HelperValStmt = buildPreInits(Context, Captures); 8696 } 8697 8698 return new (Context) OMPNumThreadsClause( 8699 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 8700 } 8701 8702 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 8703 OpenMPClauseKind CKind, 8704 bool StrictlyPositive) { 8705 if (!E) 8706 return ExprError(); 8707 if (E->isValueDependent() || E->isTypeDependent() || 8708 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 8709 return E; 8710 llvm::APSInt Result; 8711 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 8712 if (ICE.isInvalid()) 8713 return ExprError(); 8714 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 8715 (!StrictlyPositive && !Result.isNonNegative())) { 8716 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 8717 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 8718 << E->getSourceRange(); 8719 return ExprError(); 8720 } 8721 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 8722 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 8723 << E->getSourceRange(); 8724 return ExprError(); 8725 } 8726 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 8727 DSAStack->setAssociatedLoops(Result.getExtValue()); 8728 else if (CKind == OMPC_ordered) 8729 DSAStack->setAssociatedLoops(Result.getExtValue()); 8730 return ICE; 8731 } 8732 8733 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 8734 SourceLocation LParenLoc, 8735 SourceLocation EndLoc) { 8736 // OpenMP [2.8.1, simd construct, Description] 8737 // The parameter of the safelen clause must be a constant 8738 // positive integer expression. 8739 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 8740 if (Safelen.isInvalid()) 8741 return nullptr; 8742 return new (Context) 8743 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 8744 } 8745 8746 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 8747 SourceLocation LParenLoc, 8748 SourceLocation EndLoc) { 8749 // OpenMP [2.8.1, simd construct, Description] 8750 // The parameter of the simdlen clause must be a constant 8751 // positive integer expression. 8752 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 8753 if (Simdlen.isInvalid()) 8754 return nullptr; 8755 return new (Context) 8756 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 8757 } 8758 8759 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 8760 SourceLocation StartLoc, 8761 SourceLocation LParenLoc, 8762 SourceLocation EndLoc) { 8763 // OpenMP [2.7.1, loop construct, Description] 8764 // OpenMP [2.8.1, simd construct, Description] 8765 // OpenMP [2.9.6, distribute construct, Description] 8766 // The parameter of the collapse clause must be a constant 8767 // positive integer expression. 8768 ExprResult NumForLoopsResult = 8769 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 8770 if (NumForLoopsResult.isInvalid()) 8771 return nullptr; 8772 return new (Context) 8773 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 8774 } 8775 8776 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 8777 SourceLocation EndLoc, 8778 SourceLocation LParenLoc, 8779 Expr *NumForLoops) { 8780 // OpenMP [2.7.1, loop construct, Description] 8781 // OpenMP [2.8.1, simd construct, Description] 8782 // OpenMP [2.9.6, distribute construct, Description] 8783 // The parameter of the ordered clause must be a constant 8784 // positive integer expression if any. 8785 if (NumForLoops && LParenLoc.isValid()) { 8786 ExprResult NumForLoopsResult = 8787 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 8788 if (NumForLoopsResult.isInvalid()) 8789 return nullptr; 8790 NumForLoops = NumForLoopsResult.get(); 8791 } else { 8792 NumForLoops = nullptr; 8793 } 8794 auto *Clause = OMPOrderedClause::Create( 8795 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 8796 StartLoc, LParenLoc, EndLoc); 8797 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 8798 return Clause; 8799 } 8800 8801 OMPClause *Sema::ActOnOpenMPSimpleClause( 8802 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 8803 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 8804 OMPClause *Res = nullptr; 8805 switch (Kind) { 8806 case OMPC_default: 8807 Res = 8808 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 8809 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 8810 break; 8811 case OMPC_proc_bind: 8812 Res = ActOnOpenMPProcBindClause( 8813 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 8814 LParenLoc, EndLoc); 8815 break; 8816 case OMPC_if: 8817 case OMPC_final: 8818 case OMPC_num_threads: 8819 case OMPC_safelen: 8820 case OMPC_simdlen: 8821 case OMPC_collapse: 8822 case OMPC_schedule: 8823 case OMPC_private: 8824 case OMPC_firstprivate: 8825 case OMPC_lastprivate: 8826 case OMPC_shared: 8827 case OMPC_reduction: 8828 case OMPC_task_reduction: 8829 case OMPC_in_reduction: 8830 case OMPC_linear: 8831 case OMPC_aligned: 8832 case OMPC_copyin: 8833 case OMPC_copyprivate: 8834 case OMPC_ordered: 8835 case OMPC_nowait: 8836 case OMPC_untied: 8837 case OMPC_mergeable: 8838 case OMPC_threadprivate: 8839 case OMPC_flush: 8840 case OMPC_read: 8841 case OMPC_write: 8842 case OMPC_update: 8843 case OMPC_capture: 8844 case OMPC_seq_cst: 8845 case OMPC_depend: 8846 case OMPC_device: 8847 case OMPC_threads: 8848 case OMPC_simd: 8849 case OMPC_map: 8850 case OMPC_num_teams: 8851 case OMPC_thread_limit: 8852 case OMPC_priority: 8853 case OMPC_grainsize: 8854 case OMPC_nogroup: 8855 case OMPC_num_tasks: 8856 case OMPC_hint: 8857 case OMPC_dist_schedule: 8858 case OMPC_defaultmap: 8859 case OMPC_unknown: 8860 case OMPC_uniform: 8861 case OMPC_to: 8862 case OMPC_from: 8863 case OMPC_use_device_ptr: 8864 case OMPC_is_device_ptr: 8865 case OMPC_unified_address: 8866 case OMPC_unified_shared_memory: 8867 case OMPC_reverse_offload: 8868 case OMPC_dynamic_allocators: 8869 llvm_unreachable("Clause is not allowed."); 8870 } 8871 return Res; 8872 } 8873 8874 static std::string 8875 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 8876 ArrayRef<unsigned> Exclude = llvm::None) { 8877 SmallString<256> Buffer; 8878 llvm::raw_svector_ostream Out(Buffer); 8879 unsigned Bound = Last >= 2 ? Last - 2 : 0; 8880 unsigned Skipped = Exclude.size(); 8881 auto S = Exclude.begin(), E = Exclude.end(); 8882 for (unsigned I = First; I < Last; ++I) { 8883 if (std::find(S, E, I) != E) { 8884 --Skipped; 8885 continue; 8886 } 8887 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 8888 if (I == Bound - Skipped) 8889 Out << " or "; 8890 else if (I != Bound + 1 - Skipped) 8891 Out << ", "; 8892 } 8893 return Out.str(); 8894 } 8895 8896 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 8897 SourceLocation KindKwLoc, 8898 SourceLocation StartLoc, 8899 SourceLocation LParenLoc, 8900 SourceLocation EndLoc) { 8901 if (Kind == OMPC_DEFAULT_unknown) { 8902 static_assert(OMPC_DEFAULT_unknown > 0, 8903 "OMPC_DEFAULT_unknown not greater than 0"); 8904 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 8905 << getListOfPossibleValues(OMPC_default, /*First=*/0, 8906 /*Last=*/OMPC_DEFAULT_unknown) 8907 << getOpenMPClauseName(OMPC_default); 8908 return nullptr; 8909 } 8910 switch (Kind) { 8911 case OMPC_DEFAULT_none: 8912 DSAStack->setDefaultDSANone(KindKwLoc); 8913 break; 8914 case OMPC_DEFAULT_shared: 8915 DSAStack->setDefaultDSAShared(KindKwLoc); 8916 break; 8917 case OMPC_DEFAULT_unknown: 8918 llvm_unreachable("Clause kind is not allowed."); 8919 break; 8920 } 8921 return new (Context) 8922 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 8923 } 8924 8925 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 8926 SourceLocation KindKwLoc, 8927 SourceLocation StartLoc, 8928 SourceLocation LParenLoc, 8929 SourceLocation EndLoc) { 8930 if (Kind == OMPC_PROC_BIND_unknown) { 8931 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 8932 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 8933 /*Last=*/OMPC_PROC_BIND_unknown) 8934 << getOpenMPClauseName(OMPC_proc_bind); 8935 return nullptr; 8936 } 8937 return new (Context) 8938 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 8939 } 8940 8941 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 8942 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 8943 SourceLocation StartLoc, SourceLocation LParenLoc, 8944 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 8945 SourceLocation EndLoc) { 8946 OMPClause *Res = nullptr; 8947 switch (Kind) { 8948 case OMPC_schedule: 8949 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 8950 assert(Argument.size() == NumberOfElements && 8951 ArgumentLoc.size() == NumberOfElements); 8952 Res = ActOnOpenMPScheduleClause( 8953 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 8954 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 8955 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 8956 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 8957 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 8958 break; 8959 case OMPC_if: 8960 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 8961 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 8962 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 8963 DelimLoc, EndLoc); 8964 break; 8965 case OMPC_dist_schedule: 8966 Res = ActOnOpenMPDistScheduleClause( 8967 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 8968 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 8969 break; 8970 case OMPC_defaultmap: 8971 enum { Modifier, DefaultmapKind }; 8972 Res = ActOnOpenMPDefaultmapClause( 8973 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 8974 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 8975 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 8976 EndLoc); 8977 break; 8978 case OMPC_final: 8979 case OMPC_num_threads: 8980 case OMPC_safelen: 8981 case OMPC_simdlen: 8982 case OMPC_collapse: 8983 case OMPC_default: 8984 case OMPC_proc_bind: 8985 case OMPC_private: 8986 case OMPC_firstprivate: 8987 case OMPC_lastprivate: 8988 case OMPC_shared: 8989 case OMPC_reduction: 8990 case OMPC_task_reduction: 8991 case OMPC_in_reduction: 8992 case OMPC_linear: 8993 case OMPC_aligned: 8994 case OMPC_copyin: 8995 case OMPC_copyprivate: 8996 case OMPC_ordered: 8997 case OMPC_nowait: 8998 case OMPC_untied: 8999 case OMPC_mergeable: 9000 case OMPC_threadprivate: 9001 case OMPC_flush: 9002 case OMPC_read: 9003 case OMPC_write: 9004 case OMPC_update: 9005 case OMPC_capture: 9006 case OMPC_seq_cst: 9007 case OMPC_depend: 9008 case OMPC_device: 9009 case OMPC_threads: 9010 case OMPC_simd: 9011 case OMPC_map: 9012 case OMPC_num_teams: 9013 case OMPC_thread_limit: 9014 case OMPC_priority: 9015 case OMPC_grainsize: 9016 case OMPC_nogroup: 9017 case OMPC_num_tasks: 9018 case OMPC_hint: 9019 case OMPC_unknown: 9020 case OMPC_uniform: 9021 case OMPC_to: 9022 case OMPC_from: 9023 case OMPC_use_device_ptr: 9024 case OMPC_is_device_ptr: 9025 case OMPC_unified_address: 9026 case OMPC_unified_shared_memory: 9027 case OMPC_reverse_offload: 9028 case OMPC_dynamic_allocators: 9029 llvm_unreachable("Clause is not allowed."); 9030 } 9031 return Res; 9032 } 9033 9034 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 9035 OpenMPScheduleClauseModifier M2, 9036 SourceLocation M1Loc, SourceLocation M2Loc) { 9037 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 9038 SmallVector<unsigned, 2> Excluded; 9039 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 9040 Excluded.push_back(M2); 9041 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 9042 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 9043 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 9044 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 9045 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 9046 << getListOfPossibleValues(OMPC_schedule, 9047 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 9048 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 9049 Excluded) 9050 << getOpenMPClauseName(OMPC_schedule); 9051 return true; 9052 } 9053 return false; 9054 } 9055 9056 OMPClause *Sema::ActOnOpenMPScheduleClause( 9057 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 9058 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 9059 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 9060 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 9061 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 9062 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 9063 return nullptr; 9064 // OpenMP, 2.7.1, Loop Construct, Restrictions 9065 // Either the monotonic modifier or the nonmonotonic modifier can be specified 9066 // but not both. 9067 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 9068 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 9069 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 9070 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 9071 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 9072 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 9073 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 9074 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 9075 return nullptr; 9076 } 9077 if (Kind == OMPC_SCHEDULE_unknown) { 9078 std::string Values; 9079 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 9080 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 9081 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 9082 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 9083 Exclude); 9084 } else { 9085 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 9086 /*Last=*/OMPC_SCHEDULE_unknown); 9087 } 9088 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 9089 << Values << getOpenMPClauseName(OMPC_schedule); 9090 return nullptr; 9091 } 9092 // OpenMP, 2.7.1, Loop Construct, Restrictions 9093 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 9094 // schedule(guided). 9095 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 9096 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 9097 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 9098 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 9099 diag::err_omp_schedule_nonmonotonic_static); 9100 return nullptr; 9101 } 9102 Expr *ValExpr = ChunkSize; 9103 Stmt *HelperValStmt = nullptr; 9104 if (ChunkSize) { 9105 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 9106 !ChunkSize->isInstantiationDependent() && 9107 !ChunkSize->containsUnexpandedParameterPack()) { 9108 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 9109 ExprResult Val = 9110 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 9111 if (Val.isInvalid()) 9112 return nullptr; 9113 9114 ValExpr = Val.get(); 9115 9116 // OpenMP [2.7.1, Restrictions] 9117 // chunk_size must be a loop invariant integer expression with a positive 9118 // value. 9119 llvm::APSInt Result; 9120 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 9121 if (Result.isSigned() && !Result.isStrictlyPositive()) { 9122 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 9123 << "schedule" << 1 << ChunkSize->getSourceRange(); 9124 return nullptr; 9125 } 9126 } else if (getOpenMPCaptureRegionForClause( 9127 DSAStack->getCurrentDirective(), OMPC_schedule) != 9128 OMPD_unknown && 9129 !CurContext->isDependentContext()) { 9130 ValExpr = MakeFullExpr(ValExpr).get(); 9131 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9132 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 9133 HelperValStmt = buildPreInits(Context, Captures); 9134 } 9135 } 9136 } 9137 9138 return new (Context) 9139 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 9140 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 9141 } 9142 9143 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 9144 SourceLocation StartLoc, 9145 SourceLocation EndLoc) { 9146 OMPClause *Res = nullptr; 9147 switch (Kind) { 9148 case OMPC_ordered: 9149 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 9150 break; 9151 case OMPC_nowait: 9152 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 9153 break; 9154 case OMPC_untied: 9155 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 9156 break; 9157 case OMPC_mergeable: 9158 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 9159 break; 9160 case OMPC_read: 9161 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 9162 break; 9163 case OMPC_write: 9164 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 9165 break; 9166 case OMPC_update: 9167 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 9168 break; 9169 case OMPC_capture: 9170 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 9171 break; 9172 case OMPC_seq_cst: 9173 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 9174 break; 9175 case OMPC_threads: 9176 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 9177 break; 9178 case OMPC_simd: 9179 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 9180 break; 9181 case OMPC_nogroup: 9182 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 9183 break; 9184 case OMPC_unified_address: 9185 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 9186 break; 9187 case OMPC_unified_shared_memory: 9188 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 9189 break; 9190 case OMPC_reverse_offload: 9191 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 9192 break; 9193 case OMPC_dynamic_allocators: 9194 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 9195 break; 9196 case OMPC_if: 9197 case OMPC_final: 9198 case OMPC_num_threads: 9199 case OMPC_safelen: 9200 case OMPC_simdlen: 9201 case OMPC_collapse: 9202 case OMPC_schedule: 9203 case OMPC_private: 9204 case OMPC_firstprivate: 9205 case OMPC_lastprivate: 9206 case OMPC_shared: 9207 case OMPC_reduction: 9208 case OMPC_task_reduction: 9209 case OMPC_in_reduction: 9210 case OMPC_linear: 9211 case OMPC_aligned: 9212 case OMPC_copyin: 9213 case OMPC_copyprivate: 9214 case OMPC_default: 9215 case OMPC_proc_bind: 9216 case OMPC_threadprivate: 9217 case OMPC_flush: 9218 case OMPC_depend: 9219 case OMPC_device: 9220 case OMPC_map: 9221 case OMPC_num_teams: 9222 case OMPC_thread_limit: 9223 case OMPC_priority: 9224 case OMPC_grainsize: 9225 case OMPC_num_tasks: 9226 case OMPC_hint: 9227 case OMPC_dist_schedule: 9228 case OMPC_defaultmap: 9229 case OMPC_unknown: 9230 case OMPC_uniform: 9231 case OMPC_to: 9232 case OMPC_from: 9233 case OMPC_use_device_ptr: 9234 case OMPC_is_device_ptr: 9235 llvm_unreachable("Clause is not allowed."); 9236 } 9237 return Res; 9238 } 9239 9240 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 9241 SourceLocation EndLoc) { 9242 DSAStack->setNowaitRegion(); 9243 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 9244 } 9245 9246 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 9247 SourceLocation EndLoc) { 9248 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 9249 } 9250 9251 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 9252 SourceLocation EndLoc) { 9253 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 9254 } 9255 9256 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 9257 SourceLocation EndLoc) { 9258 return new (Context) OMPReadClause(StartLoc, EndLoc); 9259 } 9260 9261 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 9262 SourceLocation EndLoc) { 9263 return new (Context) OMPWriteClause(StartLoc, EndLoc); 9264 } 9265 9266 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 9267 SourceLocation EndLoc) { 9268 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 9269 } 9270 9271 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 9272 SourceLocation EndLoc) { 9273 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 9274 } 9275 9276 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 9277 SourceLocation EndLoc) { 9278 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 9279 } 9280 9281 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 9282 SourceLocation EndLoc) { 9283 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 9284 } 9285 9286 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 9287 SourceLocation EndLoc) { 9288 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 9289 } 9290 9291 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 9292 SourceLocation EndLoc) { 9293 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 9294 } 9295 9296 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 9297 SourceLocation EndLoc) { 9298 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 9299 } 9300 9301 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 9302 SourceLocation EndLoc) { 9303 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 9304 } 9305 9306 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 9307 SourceLocation EndLoc) { 9308 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 9309 } 9310 9311 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 9312 SourceLocation EndLoc) { 9313 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 9314 } 9315 9316 OMPClause *Sema::ActOnOpenMPVarListClause( 9317 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 9318 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 9319 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 9320 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 9321 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 9322 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 9323 SourceLocation DepLinMapLoc) { 9324 OMPClause *Res = nullptr; 9325 switch (Kind) { 9326 case OMPC_private: 9327 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9328 break; 9329 case OMPC_firstprivate: 9330 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9331 break; 9332 case OMPC_lastprivate: 9333 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9334 break; 9335 case OMPC_shared: 9336 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 9337 break; 9338 case OMPC_reduction: 9339 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9340 EndLoc, ReductionIdScopeSpec, ReductionId); 9341 break; 9342 case OMPC_task_reduction: 9343 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9344 EndLoc, ReductionIdScopeSpec, 9345 ReductionId); 9346 break; 9347 case OMPC_in_reduction: 9348 Res = 9349 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9350 EndLoc, ReductionIdScopeSpec, ReductionId); 9351 break; 9352 case OMPC_linear: 9353 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 9354 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 9355 break; 9356 case OMPC_aligned: 9357 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 9358 ColonLoc, EndLoc); 9359 break; 9360 case OMPC_copyin: 9361 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 9362 break; 9363 case OMPC_copyprivate: 9364 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9365 break; 9366 case OMPC_flush: 9367 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 9368 break; 9369 case OMPC_depend: 9370 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 9371 StartLoc, LParenLoc, EndLoc); 9372 break; 9373 case OMPC_map: 9374 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 9375 DepLinMapLoc, ColonLoc, VarList, StartLoc, 9376 LParenLoc, EndLoc); 9377 break; 9378 case OMPC_to: 9379 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 9380 break; 9381 case OMPC_from: 9382 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 9383 break; 9384 case OMPC_use_device_ptr: 9385 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 9386 break; 9387 case OMPC_is_device_ptr: 9388 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 9389 break; 9390 case OMPC_if: 9391 case OMPC_final: 9392 case OMPC_num_threads: 9393 case OMPC_safelen: 9394 case OMPC_simdlen: 9395 case OMPC_collapse: 9396 case OMPC_default: 9397 case OMPC_proc_bind: 9398 case OMPC_schedule: 9399 case OMPC_ordered: 9400 case OMPC_nowait: 9401 case OMPC_untied: 9402 case OMPC_mergeable: 9403 case OMPC_threadprivate: 9404 case OMPC_read: 9405 case OMPC_write: 9406 case OMPC_update: 9407 case OMPC_capture: 9408 case OMPC_seq_cst: 9409 case OMPC_device: 9410 case OMPC_threads: 9411 case OMPC_simd: 9412 case OMPC_num_teams: 9413 case OMPC_thread_limit: 9414 case OMPC_priority: 9415 case OMPC_grainsize: 9416 case OMPC_nogroup: 9417 case OMPC_num_tasks: 9418 case OMPC_hint: 9419 case OMPC_dist_schedule: 9420 case OMPC_defaultmap: 9421 case OMPC_unknown: 9422 case OMPC_uniform: 9423 case OMPC_unified_address: 9424 case OMPC_unified_shared_memory: 9425 case OMPC_reverse_offload: 9426 case OMPC_dynamic_allocators: 9427 llvm_unreachable("Clause is not allowed."); 9428 } 9429 return Res; 9430 } 9431 9432 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 9433 ExprObjectKind OK, SourceLocation Loc) { 9434 ExprResult Res = BuildDeclRefExpr( 9435 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 9436 if (!Res.isUsable()) 9437 return ExprError(); 9438 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 9439 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 9440 if (!Res.isUsable()) 9441 return ExprError(); 9442 } 9443 if (VK != VK_LValue && Res.get()->isGLValue()) { 9444 Res = DefaultLvalueConversion(Res.get()); 9445 if (!Res.isUsable()) 9446 return ExprError(); 9447 } 9448 return Res; 9449 } 9450 9451 static std::pair<ValueDecl *, bool> 9452 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 9453 SourceRange &ERange, bool AllowArraySection = false) { 9454 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 9455 RefExpr->containsUnexpandedParameterPack()) 9456 return std::make_pair(nullptr, true); 9457 9458 // OpenMP [3.1, C/C++] 9459 // A list item is a variable name. 9460 // OpenMP [2.9.3.3, Restrictions, p.1] 9461 // A variable that is part of another variable (as an array or 9462 // structure element) cannot appear in a private clause. 9463 RefExpr = RefExpr->IgnoreParens(); 9464 enum { 9465 NoArrayExpr = -1, 9466 ArraySubscript = 0, 9467 OMPArraySection = 1 9468 } IsArrayExpr = NoArrayExpr; 9469 if (AllowArraySection) { 9470 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 9471 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 9472 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 9473 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9474 RefExpr = Base; 9475 IsArrayExpr = ArraySubscript; 9476 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 9477 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 9478 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 9479 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 9480 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 9481 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9482 RefExpr = Base; 9483 IsArrayExpr = OMPArraySection; 9484 } 9485 } 9486 ELoc = RefExpr->getExprLoc(); 9487 ERange = RefExpr->getSourceRange(); 9488 RefExpr = RefExpr->IgnoreParenImpCasts(); 9489 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 9490 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 9491 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 9492 (S.getCurrentThisType().isNull() || !ME || 9493 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 9494 !isa<FieldDecl>(ME->getMemberDecl()))) { 9495 if (IsArrayExpr != NoArrayExpr) { 9496 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 9497 << ERange; 9498 } else { 9499 S.Diag(ELoc, 9500 AllowArraySection 9501 ? diag::err_omp_expected_var_name_member_expr_or_array_item 9502 : diag::err_omp_expected_var_name_member_expr) 9503 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 9504 } 9505 return std::make_pair(nullptr, false); 9506 } 9507 return std::make_pair( 9508 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 9509 } 9510 9511 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 9512 SourceLocation StartLoc, 9513 SourceLocation LParenLoc, 9514 SourceLocation EndLoc) { 9515 SmallVector<Expr *, 8> Vars; 9516 SmallVector<Expr *, 8> PrivateCopies; 9517 for (Expr *RefExpr : VarList) { 9518 assert(RefExpr && "NULL expr in OpenMP private clause."); 9519 SourceLocation ELoc; 9520 SourceRange ERange; 9521 Expr *SimpleRefExpr = RefExpr; 9522 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9523 if (Res.second) { 9524 // It will be analyzed later. 9525 Vars.push_back(RefExpr); 9526 PrivateCopies.push_back(nullptr); 9527 } 9528 ValueDecl *D = Res.first; 9529 if (!D) 9530 continue; 9531 9532 QualType Type = D->getType(); 9533 auto *VD = dyn_cast<VarDecl>(D); 9534 9535 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9536 // A variable that appears in a private clause must not have an incomplete 9537 // type or a reference type. 9538 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 9539 continue; 9540 Type = Type.getNonReferenceType(); 9541 9542 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9543 // in a Construct] 9544 // Variables with the predetermined data-sharing attributes may not be 9545 // listed in data-sharing attributes clauses, except for the cases 9546 // listed below. For these exceptions only, listing a predetermined 9547 // variable in a data-sharing attribute clause is allowed and overrides 9548 // the variable's predetermined data-sharing attributes. 9549 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 9550 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 9551 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9552 << getOpenMPClauseName(OMPC_private); 9553 reportOriginalDsa(*this, DSAStack, D, DVar); 9554 continue; 9555 } 9556 9557 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9558 // Variably modified types are not supported for tasks. 9559 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 9560 isOpenMPTaskingDirective(CurrDir)) { 9561 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9562 << getOpenMPClauseName(OMPC_private) << Type 9563 << getOpenMPDirectiveName(CurrDir); 9564 bool IsDecl = 9565 !VD || 9566 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9567 Diag(D->getLocation(), 9568 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9569 << D; 9570 continue; 9571 } 9572 9573 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 9574 // A list item cannot appear in both a map clause and a data-sharing 9575 // attribute clause on the same construct 9576 if (isOpenMPTargetExecutionDirective(CurrDir)) { 9577 OpenMPClauseKind ConflictKind; 9578 if (DSAStack->checkMappableExprComponentListsForDecl( 9579 VD, /*CurrentRegionOnly=*/true, 9580 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 9581 OpenMPClauseKind WhereFoundClauseKind) -> bool { 9582 ConflictKind = WhereFoundClauseKind; 9583 return true; 9584 })) { 9585 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 9586 << getOpenMPClauseName(OMPC_private) 9587 << getOpenMPClauseName(ConflictKind) 9588 << getOpenMPDirectiveName(CurrDir); 9589 reportOriginalDsa(*this, DSAStack, D, DVar); 9590 continue; 9591 } 9592 } 9593 9594 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 9595 // A variable of class type (or array thereof) that appears in a private 9596 // clause requires an accessible, unambiguous default constructor for the 9597 // class type. 9598 // Generate helper private variable and initialize it with the default 9599 // value. The address of the original variable is replaced by the address of 9600 // the new private variable in CodeGen. This new variable is not added to 9601 // IdResolver, so the code in the OpenMP region uses original variable for 9602 // proper diagnostics. 9603 Type = Type.getUnqualifiedType(); 9604 VarDecl *VDPrivate = 9605 buildVarDecl(*this, ELoc, Type, D->getName(), 9606 D->hasAttrs() ? &D->getAttrs() : nullptr, 9607 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 9608 ActOnUninitializedDecl(VDPrivate); 9609 if (VDPrivate->isInvalidDecl()) 9610 continue; 9611 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 9612 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 9613 9614 DeclRefExpr *Ref = nullptr; 9615 if (!VD && !CurContext->isDependentContext()) 9616 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9617 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 9618 Vars.push_back((VD || CurContext->isDependentContext()) 9619 ? RefExpr->IgnoreParens() 9620 : Ref); 9621 PrivateCopies.push_back(VDPrivateRefExpr); 9622 } 9623 9624 if (Vars.empty()) 9625 return nullptr; 9626 9627 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 9628 PrivateCopies); 9629 } 9630 9631 namespace { 9632 class DiagsUninitializedSeveretyRAII { 9633 private: 9634 DiagnosticsEngine &Diags; 9635 SourceLocation SavedLoc; 9636 bool IsIgnored = false; 9637 9638 public: 9639 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 9640 bool IsIgnored) 9641 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 9642 if (!IsIgnored) { 9643 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 9644 /*Map*/ diag::Severity::Ignored, Loc); 9645 } 9646 } 9647 ~DiagsUninitializedSeveretyRAII() { 9648 if (!IsIgnored) 9649 Diags.popMappings(SavedLoc); 9650 } 9651 }; 9652 } 9653 9654 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 9655 SourceLocation StartLoc, 9656 SourceLocation LParenLoc, 9657 SourceLocation EndLoc) { 9658 SmallVector<Expr *, 8> Vars; 9659 SmallVector<Expr *, 8> PrivateCopies; 9660 SmallVector<Expr *, 8> Inits; 9661 SmallVector<Decl *, 4> ExprCaptures; 9662 bool IsImplicitClause = 9663 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 9664 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 9665 9666 for (Expr *RefExpr : VarList) { 9667 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 9668 SourceLocation ELoc; 9669 SourceRange ERange; 9670 Expr *SimpleRefExpr = RefExpr; 9671 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9672 if (Res.second) { 9673 // It will be analyzed later. 9674 Vars.push_back(RefExpr); 9675 PrivateCopies.push_back(nullptr); 9676 Inits.push_back(nullptr); 9677 } 9678 ValueDecl *D = Res.first; 9679 if (!D) 9680 continue; 9681 9682 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 9683 QualType Type = D->getType(); 9684 auto *VD = dyn_cast<VarDecl>(D); 9685 9686 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9687 // A variable that appears in a private clause must not have an incomplete 9688 // type or a reference type. 9689 if (RequireCompleteType(ELoc, Type, 9690 diag::err_omp_firstprivate_incomplete_type)) 9691 continue; 9692 Type = Type.getNonReferenceType(); 9693 9694 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 9695 // A variable of class type (or array thereof) that appears in a private 9696 // clause requires an accessible, unambiguous copy constructor for the 9697 // class type. 9698 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 9699 9700 // If an implicit firstprivate variable found it was checked already. 9701 DSAStackTy::DSAVarData TopDVar; 9702 if (!IsImplicitClause) { 9703 DSAStackTy::DSAVarData DVar = 9704 DSAStack->getTopDSA(D, /*FromParent=*/false); 9705 TopDVar = DVar; 9706 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9707 bool IsConstant = ElemType.isConstant(Context); 9708 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 9709 // A list item that specifies a given variable may not appear in more 9710 // than one clause on the same directive, except that a variable may be 9711 // specified in both firstprivate and lastprivate clauses. 9712 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 9713 // A list item may appear in a firstprivate or lastprivate clause but not 9714 // both. 9715 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 9716 (isOpenMPDistributeDirective(CurrDir) || 9717 DVar.CKind != OMPC_lastprivate) && 9718 DVar.RefExpr) { 9719 Diag(ELoc, diag::err_omp_wrong_dsa) 9720 << getOpenMPClauseName(DVar.CKind) 9721 << getOpenMPClauseName(OMPC_firstprivate); 9722 reportOriginalDsa(*this, DSAStack, D, DVar); 9723 continue; 9724 } 9725 9726 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9727 // in a Construct] 9728 // Variables with the predetermined data-sharing attributes may not be 9729 // listed in data-sharing attributes clauses, except for the cases 9730 // listed below. For these exceptions only, listing a predetermined 9731 // variable in a data-sharing attribute clause is allowed and overrides 9732 // the variable's predetermined data-sharing attributes. 9733 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9734 // in a Construct, C/C++, p.2] 9735 // Variables with const-qualified type having no mutable member may be 9736 // listed in a firstprivate clause, even if they are static data members. 9737 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 9738 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 9739 Diag(ELoc, diag::err_omp_wrong_dsa) 9740 << getOpenMPClauseName(DVar.CKind) 9741 << getOpenMPClauseName(OMPC_firstprivate); 9742 reportOriginalDsa(*this, DSAStack, D, DVar); 9743 continue; 9744 } 9745 9746 // OpenMP [2.9.3.4, Restrictions, p.2] 9747 // A list item that is private within a parallel region must not appear 9748 // in a firstprivate clause on a worksharing construct if any of the 9749 // worksharing regions arising from the worksharing construct ever bind 9750 // to any of the parallel regions arising from the parallel construct. 9751 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 9752 // A list item that is private within a teams region must not appear in a 9753 // firstprivate clause on a distribute construct if any of the distribute 9754 // regions arising from the distribute construct ever bind to any of the 9755 // teams regions arising from the teams construct. 9756 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 9757 // A list item that appears in a reduction clause of a teams construct 9758 // must not appear in a firstprivate clause on a distribute construct if 9759 // any of the distribute regions arising from the distribute construct 9760 // ever bind to any of the teams regions arising from the teams construct. 9761 if ((isOpenMPWorksharingDirective(CurrDir) || 9762 isOpenMPDistributeDirective(CurrDir)) && 9763 !isOpenMPParallelDirective(CurrDir) && 9764 !isOpenMPTeamsDirective(CurrDir)) { 9765 DVar = DSAStack->getImplicitDSA(D, true); 9766 if (DVar.CKind != OMPC_shared && 9767 (isOpenMPParallelDirective(DVar.DKind) || 9768 isOpenMPTeamsDirective(DVar.DKind) || 9769 DVar.DKind == OMPD_unknown)) { 9770 Diag(ELoc, diag::err_omp_required_access) 9771 << getOpenMPClauseName(OMPC_firstprivate) 9772 << getOpenMPClauseName(OMPC_shared); 9773 reportOriginalDsa(*this, DSAStack, D, DVar); 9774 continue; 9775 } 9776 } 9777 // OpenMP [2.9.3.4, Restrictions, p.3] 9778 // A list item that appears in a reduction clause of a parallel construct 9779 // must not appear in a firstprivate clause on a worksharing or task 9780 // construct if any of the worksharing or task regions arising from the 9781 // worksharing or task construct ever bind to any of the parallel regions 9782 // arising from the parallel construct. 9783 // OpenMP [2.9.3.4, Restrictions, p.4] 9784 // A list item that appears in a reduction clause in worksharing 9785 // construct must not appear in a firstprivate clause in a task construct 9786 // encountered during execution of any of the worksharing regions arising 9787 // from the worksharing construct. 9788 if (isOpenMPTaskingDirective(CurrDir)) { 9789 DVar = DSAStack->hasInnermostDSA( 9790 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 9791 [](OpenMPDirectiveKind K) { 9792 return isOpenMPParallelDirective(K) || 9793 isOpenMPWorksharingDirective(K) || 9794 isOpenMPTeamsDirective(K); 9795 }, 9796 /*FromParent=*/true); 9797 if (DVar.CKind == OMPC_reduction && 9798 (isOpenMPParallelDirective(DVar.DKind) || 9799 isOpenMPWorksharingDirective(DVar.DKind) || 9800 isOpenMPTeamsDirective(DVar.DKind))) { 9801 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 9802 << getOpenMPDirectiveName(DVar.DKind); 9803 reportOriginalDsa(*this, DSAStack, D, DVar); 9804 continue; 9805 } 9806 } 9807 9808 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 9809 // A list item cannot appear in both a map clause and a data-sharing 9810 // attribute clause on the same construct 9811 if (isOpenMPTargetExecutionDirective(CurrDir)) { 9812 OpenMPClauseKind ConflictKind; 9813 if (DSAStack->checkMappableExprComponentListsForDecl( 9814 VD, /*CurrentRegionOnly=*/true, 9815 [&ConflictKind]( 9816 OMPClauseMappableExprCommon::MappableExprComponentListRef, 9817 OpenMPClauseKind WhereFoundClauseKind) { 9818 ConflictKind = WhereFoundClauseKind; 9819 return true; 9820 })) { 9821 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 9822 << getOpenMPClauseName(OMPC_firstprivate) 9823 << getOpenMPClauseName(ConflictKind) 9824 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 9825 reportOriginalDsa(*this, DSAStack, D, DVar); 9826 continue; 9827 } 9828 } 9829 } 9830 9831 // Variably modified types are not supported for tasks. 9832 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 9833 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 9834 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9835 << getOpenMPClauseName(OMPC_firstprivate) << Type 9836 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 9837 bool IsDecl = 9838 !VD || 9839 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9840 Diag(D->getLocation(), 9841 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9842 << D; 9843 continue; 9844 } 9845 9846 Type = Type.getUnqualifiedType(); 9847 VarDecl *VDPrivate = 9848 buildVarDecl(*this, ELoc, Type, D->getName(), 9849 D->hasAttrs() ? &D->getAttrs() : nullptr, 9850 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 9851 // Generate helper private variable and initialize it with the value of the 9852 // original variable. The address of the original variable is replaced by 9853 // the address of the new private variable in the CodeGen. This new variable 9854 // is not added to IdResolver, so the code in the OpenMP region uses 9855 // original variable for proper diagnostics and variable capturing. 9856 Expr *VDInitRefExpr = nullptr; 9857 // For arrays generate initializer for single element and replace it by the 9858 // original array element in CodeGen. 9859 if (Type->isArrayType()) { 9860 VarDecl *VDInit = 9861 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 9862 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 9863 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 9864 ElemType = ElemType.getUnqualifiedType(); 9865 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 9866 ".firstprivate.temp"); 9867 InitializedEntity Entity = 9868 InitializedEntity::InitializeVariable(VDInitTemp); 9869 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 9870 9871 InitializationSequence InitSeq(*this, Entity, Kind, Init); 9872 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 9873 if (Result.isInvalid()) 9874 VDPrivate->setInvalidDecl(); 9875 else 9876 VDPrivate->setInit(Result.getAs<Expr>()); 9877 // Remove temp variable declaration. 9878 Context.Deallocate(VDInitTemp); 9879 } else { 9880 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 9881 ".firstprivate.temp"); 9882 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 9883 RefExpr->getExprLoc()); 9884 AddInitializerToDecl(VDPrivate, 9885 DefaultLvalueConversion(VDInitRefExpr).get(), 9886 /*DirectInit=*/false); 9887 } 9888 if (VDPrivate->isInvalidDecl()) { 9889 if (IsImplicitClause) { 9890 Diag(RefExpr->getExprLoc(), 9891 diag::note_omp_task_predetermined_firstprivate_here); 9892 } 9893 continue; 9894 } 9895 CurContext->addDecl(VDPrivate); 9896 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 9897 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 9898 RefExpr->getExprLoc()); 9899 DeclRefExpr *Ref = nullptr; 9900 if (!VD && !CurContext->isDependentContext()) { 9901 if (TopDVar.CKind == OMPC_lastprivate) { 9902 Ref = TopDVar.PrivateCopy; 9903 } else { 9904 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9905 if (!isOpenMPCapturedDecl(D)) 9906 ExprCaptures.push_back(Ref->getDecl()); 9907 } 9908 } 9909 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 9910 Vars.push_back((VD || CurContext->isDependentContext()) 9911 ? RefExpr->IgnoreParens() 9912 : Ref); 9913 PrivateCopies.push_back(VDPrivateRefExpr); 9914 Inits.push_back(VDInitRefExpr); 9915 } 9916 9917 if (Vars.empty()) 9918 return nullptr; 9919 9920 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9921 Vars, PrivateCopies, Inits, 9922 buildPreInits(Context, ExprCaptures)); 9923 } 9924 9925 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 9926 SourceLocation StartLoc, 9927 SourceLocation LParenLoc, 9928 SourceLocation EndLoc) { 9929 SmallVector<Expr *, 8> Vars; 9930 SmallVector<Expr *, 8> SrcExprs; 9931 SmallVector<Expr *, 8> DstExprs; 9932 SmallVector<Expr *, 8> AssignmentOps; 9933 SmallVector<Decl *, 4> ExprCaptures; 9934 SmallVector<Expr *, 4> ExprPostUpdates; 9935 for (Expr *RefExpr : VarList) { 9936 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 9937 SourceLocation ELoc; 9938 SourceRange ERange; 9939 Expr *SimpleRefExpr = RefExpr; 9940 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9941 if (Res.second) { 9942 // It will be analyzed later. 9943 Vars.push_back(RefExpr); 9944 SrcExprs.push_back(nullptr); 9945 DstExprs.push_back(nullptr); 9946 AssignmentOps.push_back(nullptr); 9947 } 9948 ValueDecl *D = Res.first; 9949 if (!D) 9950 continue; 9951 9952 QualType Type = D->getType(); 9953 auto *VD = dyn_cast<VarDecl>(D); 9954 9955 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 9956 // A variable that appears in a lastprivate clause must not have an 9957 // incomplete type or a reference type. 9958 if (RequireCompleteType(ELoc, Type, 9959 diag::err_omp_lastprivate_incomplete_type)) 9960 continue; 9961 Type = Type.getNonReferenceType(); 9962 9963 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9964 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 9965 // in a Construct] 9966 // Variables with the predetermined data-sharing attributes may not be 9967 // listed in data-sharing attributes clauses, except for the cases 9968 // listed below. 9969 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 9970 // A list item may appear in a firstprivate or lastprivate clause but not 9971 // both. 9972 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 9973 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 9974 (isOpenMPDistributeDirective(CurrDir) || 9975 DVar.CKind != OMPC_firstprivate) && 9976 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 9977 Diag(ELoc, diag::err_omp_wrong_dsa) 9978 << getOpenMPClauseName(DVar.CKind) 9979 << getOpenMPClauseName(OMPC_lastprivate); 9980 reportOriginalDsa(*this, DSAStack, D, DVar); 9981 continue; 9982 } 9983 9984 // OpenMP [2.14.3.5, Restrictions, p.2] 9985 // A list item that is private within a parallel region, or that appears in 9986 // the reduction clause of a parallel construct, must not appear in a 9987 // lastprivate clause on a worksharing construct if any of the corresponding 9988 // worksharing regions ever binds to any of the corresponding parallel 9989 // regions. 9990 DSAStackTy::DSAVarData TopDVar = DVar; 9991 if (isOpenMPWorksharingDirective(CurrDir) && 9992 !isOpenMPParallelDirective(CurrDir) && 9993 !isOpenMPTeamsDirective(CurrDir)) { 9994 DVar = DSAStack->getImplicitDSA(D, true); 9995 if (DVar.CKind != OMPC_shared) { 9996 Diag(ELoc, diag::err_omp_required_access) 9997 << getOpenMPClauseName(OMPC_lastprivate) 9998 << getOpenMPClauseName(OMPC_shared); 9999 reportOriginalDsa(*this, DSAStack, D, DVar); 10000 continue; 10001 } 10002 } 10003 10004 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 10005 // A variable of class type (or array thereof) that appears in a 10006 // lastprivate clause requires an accessible, unambiguous default 10007 // constructor for the class type, unless the list item is also specified 10008 // in a firstprivate clause. 10009 // A variable of class type (or array thereof) that appears in a 10010 // lastprivate clause requires an accessible, unambiguous copy assignment 10011 // operator for the class type. 10012 Type = Context.getBaseElementType(Type).getNonReferenceType(); 10013 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 10014 Type.getUnqualifiedType(), ".lastprivate.src", 10015 D->hasAttrs() ? &D->getAttrs() : nullptr); 10016 DeclRefExpr *PseudoSrcExpr = 10017 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 10018 VarDecl *DstVD = 10019 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 10020 D->hasAttrs() ? &D->getAttrs() : nullptr); 10021 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 10022 // For arrays generate assignment operation for single element and replace 10023 // it by the original array element in CodeGen. 10024 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 10025 PseudoDstExpr, PseudoSrcExpr); 10026 if (AssignmentOp.isInvalid()) 10027 continue; 10028 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 10029 /*DiscardedValue=*/true); 10030 if (AssignmentOp.isInvalid()) 10031 continue; 10032 10033 DeclRefExpr *Ref = nullptr; 10034 if (!VD && !CurContext->isDependentContext()) { 10035 if (TopDVar.CKind == OMPC_firstprivate) { 10036 Ref = TopDVar.PrivateCopy; 10037 } else { 10038 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 10039 if (!isOpenMPCapturedDecl(D)) 10040 ExprCaptures.push_back(Ref->getDecl()); 10041 } 10042 if (TopDVar.CKind == OMPC_firstprivate || 10043 (!isOpenMPCapturedDecl(D) && 10044 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 10045 ExprResult RefRes = DefaultLvalueConversion(Ref); 10046 if (!RefRes.isUsable()) 10047 continue; 10048 ExprResult PostUpdateRes = 10049 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 10050 RefRes.get()); 10051 if (!PostUpdateRes.isUsable()) 10052 continue; 10053 ExprPostUpdates.push_back( 10054 IgnoredValueConversions(PostUpdateRes.get()).get()); 10055 } 10056 } 10057 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 10058 Vars.push_back((VD || CurContext->isDependentContext()) 10059 ? RefExpr->IgnoreParens() 10060 : Ref); 10061 SrcExprs.push_back(PseudoSrcExpr); 10062 DstExprs.push_back(PseudoDstExpr); 10063 AssignmentOps.push_back(AssignmentOp.get()); 10064 } 10065 10066 if (Vars.empty()) 10067 return nullptr; 10068 10069 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10070 Vars, SrcExprs, DstExprs, AssignmentOps, 10071 buildPreInits(Context, ExprCaptures), 10072 buildPostUpdate(*this, ExprPostUpdates)); 10073 } 10074 10075 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 10076 SourceLocation StartLoc, 10077 SourceLocation LParenLoc, 10078 SourceLocation EndLoc) { 10079 SmallVector<Expr *, 8> Vars; 10080 for (Expr *RefExpr : VarList) { 10081 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 10082 SourceLocation ELoc; 10083 SourceRange ERange; 10084 Expr *SimpleRefExpr = RefExpr; 10085 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10086 if (Res.second) { 10087 // It will be analyzed later. 10088 Vars.push_back(RefExpr); 10089 } 10090 ValueDecl *D = Res.first; 10091 if (!D) 10092 continue; 10093 10094 auto *VD = dyn_cast<VarDecl>(D); 10095 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 10096 // in a Construct] 10097 // Variables with the predetermined data-sharing attributes may not be 10098 // listed in data-sharing attributes clauses, except for the cases 10099 // listed below. For these exceptions only, listing a predetermined 10100 // variable in a data-sharing attribute clause is allowed and overrides 10101 // the variable's predetermined data-sharing attributes. 10102 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 10103 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 10104 DVar.RefExpr) { 10105 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 10106 << getOpenMPClauseName(OMPC_shared); 10107 reportOriginalDsa(*this, DSAStack, D, DVar); 10108 continue; 10109 } 10110 10111 DeclRefExpr *Ref = nullptr; 10112 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 10113 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 10114 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 10115 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 10116 ? RefExpr->IgnoreParens() 10117 : Ref); 10118 } 10119 10120 if (Vars.empty()) 10121 return nullptr; 10122 10123 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 10124 } 10125 10126 namespace { 10127 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 10128 DSAStackTy *Stack; 10129 10130 public: 10131 bool VisitDeclRefExpr(DeclRefExpr *E) { 10132 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 10133 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 10134 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 10135 return false; 10136 if (DVar.CKind != OMPC_unknown) 10137 return true; 10138 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 10139 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; }, 10140 /*FromParent=*/true); 10141 return DVarPrivate.CKind != OMPC_unknown; 10142 } 10143 return false; 10144 } 10145 bool VisitStmt(Stmt *S) { 10146 for (Stmt *Child : S->children()) { 10147 if (Child && Visit(Child)) 10148 return true; 10149 } 10150 return false; 10151 } 10152 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 10153 }; 10154 } // namespace 10155 10156 namespace { 10157 // Transform MemberExpression for specified FieldDecl of current class to 10158 // DeclRefExpr to specified OMPCapturedExprDecl. 10159 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 10160 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 10161 ValueDecl *Field = nullptr; 10162 DeclRefExpr *CapturedExpr = nullptr; 10163 10164 public: 10165 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 10166 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 10167 10168 ExprResult TransformMemberExpr(MemberExpr *E) { 10169 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 10170 E->getMemberDecl() == Field) { 10171 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 10172 return CapturedExpr; 10173 } 10174 return BaseTransform::TransformMemberExpr(E); 10175 } 10176 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 10177 }; 10178 } // namespace 10179 10180 template <typename T, typename U> 10181 static T filterLookupForUDR(SmallVectorImpl<U> &Lookups, 10182 const llvm::function_ref<T(ValueDecl *)> Gen) { 10183 for (U &Set : Lookups) { 10184 for (auto *D : Set) { 10185 if (T Res = Gen(cast<ValueDecl>(D))) 10186 return Res; 10187 } 10188 } 10189 return T(); 10190 } 10191 10192 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 10193 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 10194 10195 for (auto RD : D->redecls()) { 10196 // Don't bother with extra checks if we already know this one isn't visible. 10197 if (RD == D) 10198 continue; 10199 10200 auto ND = cast<NamedDecl>(RD); 10201 if (LookupResult::isVisible(SemaRef, ND)) 10202 return ND; 10203 } 10204 10205 return nullptr; 10206 } 10207 10208 static void 10209 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &ReductionId, 10210 SourceLocation Loc, QualType Ty, 10211 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 10212 // Find all of the associated namespaces and classes based on the 10213 // arguments we have. 10214 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10215 Sema::AssociatedClassSet AssociatedClasses; 10216 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 10217 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 10218 AssociatedClasses); 10219 10220 // C++ [basic.lookup.argdep]p3: 10221 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10222 // and let Y be the lookup set produced by argument dependent 10223 // lookup (defined as follows). If X contains [...] then Y is 10224 // empty. Otherwise Y is the set of declarations found in the 10225 // namespaces associated with the argument types as described 10226 // below. The set of declarations found by the lookup of the name 10227 // is the union of X and Y. 10228 // 10229 // Here, we compute Y and add its members to the overloaded 10230 // candidate set. 10231 for (auto *NS : AssociatedNamespaces) { 10232 // When considering an associated namespace, the lookup is the 10233 // same as the lookup performed when the associated namespace is 10234 // used as a qualifier (3.4.3.2) except that: 10235 // 10236 // -- Any using-directives in the associated namespace are 10237 // ignored. 10238 // 10239 // -- Any namespace-scope friend functions declared in 10240 // associated classes are visible within their respective 10241 // namespaces even if they are not visible during an ordinary 10242 // lookup (11.4). 10243 DeclContext::lookup_result R = NS->lookup(ReductionId.getName()); 10244 for (auto *D : R) { 10245 auto *Underlying = D; 10246 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 10247 Underlying = USD->getTargetDecl(); 10248 10249 if (!isa<OMPDeclareReductionDecl>(Underlying)) 10250 continue; 10251 10252 if (!SemaRef.isVisible(D)) { 10253 D = findAcceptableDecl(SemaRef, D); 10254 if (!D) 10255 continue; 10256 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 10257 Underlying = USD->getTargetDecl(); 10258 } 10259 Lookups.emplace_back(); 10260 Lookups.back().addDecl(Underlying); 10261 } 10262 } 10263 } 10264 10265 static ExprResult 10266 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 10267 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 10268 const DeclarationNameInfo &ReductionId, QualType Ty, 10269 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 10270 if (ReductionIdScopeSpec.isInvalid()) 10271 return ExprError(); 10272 SmallVector<UnresolvedSet<8>, 4> Lookups; 10273 if (S) { 10274 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 10275 Lookup.suppressDiagnostics(); 10276 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 10277 NamedDecl *D = Lookup.getRepresentativeDecl(); 10278 do { 10279 S = S->getParent(); 10280 } while (S && !S->isDeclScope(D)); 10281 if (S) 10282 S = S->getParent(); 10283 Lookups.emplace_back(); 10284 Lookups.back().append(Lookup.begin(), Lookup.end()); 10285 Lookup.clear(); 10286 } 10287 } else if (auto *ULE = 10288 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 10289 Lookups.push_back(UnresolvedSet<8>()); 10290 Decl *PrevD = nullptr; 10291 for (NamedDecl *D : ULE->decls()) { 10292 if (D == PrevD) 10293 Lookups.push_back(UnresolvedSet<8>()); 10294 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 10295 Lookups.back().addDecl(DRD); 10296 PrevD = D; 10297 } 10298 } 10299 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 10300 Ty->isInstantiationDependentType() || 10301 Ty->containsUnexpandedParameterPack() || 10302 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) { 10303 return !D->isInvalidDecl() && 10304 (D->getType()->isDependentType() || 10305 D->getType()->isInstantiationDependentType() || 10306 D->getType()->containsUnexpandedParameterPack()); 10307 })) { 10308 UnresolvedSet<8> ResSet; 10309 for (const UnresolvedSet<8> &Set : Lookups) { 10310 if (Set.empty()) 10311 continue; 10312 ResSet.append(Set.begin(), Set.end()); 10313 // The last item marks the end of all declarations at the specified scope. 10314 ResSet.addDecl(Set[Set.size() - 1]); 10315 } 10316 return UnresolvedLookupExpr::Create( 10317 SemaRef.Context, /*NamingClass=*/nullptr, 10318 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 10319 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 10320 } 10321 // Lookup inside the classes. 10322 // C++ [over.match.oper]p3: 10323 // For a unary operator @ with an operand of a type whose 10324 // cv-unqualified version is T1, and for a binary operator @ with 10325 // a left operand of a type whose cv-unqualified version is T1 and 10326 // a right operand of a type whose cv-unqualified version is T2, 10327 // three sets of candidate functions, designated member 10328 // candidates, non-member candidates and built-in candidates, are 10329 // constructed as follows: 10330 // -- If T1 is a complete class type or a class currently being 10331 // defined, the set of member candidates is the result of the 10332 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 10333 // the set of member candidates is empty. 10334 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 10335 Lookup.suppressDiagnostics(); 10336 if (const auto *TyRec = Ty->getAs<RecordType>()) { 10337 // Complete the type if it can be completed. 10338 // If the type is neither complete nor being defined, bail out now. 10339 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 10340 TyRec->getDecl()->getDefinition()) { 10341 Lookup.clear(); 10342 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 10343 if (Lookup.empty()) { 10344 Lookups.emplace_back(); 10345 Lookups.back().append(Lookup.begin(), Lookup.end()); 10346 } 10347 } 10348 } 10349 // Perform ADL. 10350 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 10351 if (auto *VD = filterLookupForUDR<ValueDecl *>( 10352 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 10353 if (!D->isInvalidDecl() && 10354 SemaRef.Context.hasSameType(D->getType(), Ty)) 10355 return D; 10356 return nullptr; 10357 })) 10358 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 10359 if (auto *VD = filterLookupForUDR<ValueDecl *>( 10360 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 10361 if (!D->isInvalidDecl() && 10362 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 10363 !Ty.isMoreQualifiedThan(D->getType())) 10364 return D; 10365 return nullptr; 10366 })) { 10367 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 10368 /*DetectVirtual=*/false); 10369 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 10370 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 10371 VD->getType().getUnqualifiedType()))) { 10372 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 10373 /*DiagID=*/0) != 10374 Sema::AR_inaccessible) { 10375 SemaRef.BuildBasePathArray(Paths, BasePath); 10376 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 10377 } 10378 } 10379 } 10380 } 10381 if (ReductionIdScopeSpec.isSet()) { 10382 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 10383 return ExprError(); 10384 } 10385 return ExprEmpty(); 10386 } 10387 10388 namespace { 10389 /// Data for the reduction-based clauses. 10390 struct ReductionData { 10391 /// List of original reduction items. 10392 SmallVector<Expr *, 8> Vars; 10393 /// List of private copies of the reduction items. 10394 SmallVector<Expr *, 8> Privates; 10395 /// LHS expressions for the reduction_op expressions. 10396 SmallVector<Expr *, 8> LHSs; 10397 /// RHS expressions for the reduction_op expressions. 10398 SmallVector<Expr *, 8> RHSs; 10399 /// Reduction operation expression. 10400 SmallVector<Expr *, 8> ReductionOps; 10401 /// Taskgroup descriptors for the corresponding reduction items in 10402 /// in_reduction clauses. 10403 SmallVector<Expr *, 8> TaskgroupDescriptors; 10404 /// List of captures for clause. 10405 SmallVector<Decl *, 4> ExprCaptures; 10406 /// List of postupdate expressions. 10407 SmallVector<Expr *, 4> ExprPostUpdates; 10408 ReductionData() = delete; 10409 /// Reserves required memory for the reduction data. 10410 ReductionData(unsigned Size) { 10411 Vars.reserve(Size); 10412 Privates.reserve(Size); 10413 LHSs.reserve(Size); 10414 RHSs.reserve(Size); 10415 ReductionOps.reserve(Size); 10416 TaskgroupDescriptors.reserve(Size); 10417 ExprCaptures.reserve(Size); 10418 ExprPostUpdates.reserve(Size); 10419 } 10420 /// Stores reduction item and reduction operation only (required for dependent 10421 /// reduction item). 10422 void push(Expr *Item, Expr *ReductionOp) { 10423 Vars.emplace_back(Item); 10424 Privates.emplace_back(nullptr); 10425 LHSs.emplace_back(nullptr); 10426 RHSs.emplace_back(nullptr); 10427 ReductionOps.emplace_back(ReductionOp); 10428 TaskgroupDescriptors.emplace_back(nullptr); 10429 } 10430 /// Stores reduction data. 10431 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 10432 Expr *TaskgroupDescriptor) { 10433 Vars.emplace_back(Item); 10434 Privates.emplace_back(Private); 10435 LHSs.emplace_back(LHS); 10436 RHSs.emplace_back(RHS); 10437 ReductionOps.emplace_back(ReductionOp); 10438 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 10439 } 10440 }; 10441 } // namespace 10442 10443 static bool checkOMPArraySectionConstantForReduction( 10444 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 10445 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 10446 const Expr *Length = OASE->getLength(); 10447 if (Length == nullptr) { 10448 // For array sections of the form [1:] or [:], we would need to analyze 10449 // the lower bound... 10450 if (OASE->getColonLoc().isValid()) 10451 return false; 10452 10453 // This is an array subscript which has implicit length 1! 10454 SingleElement = true; 10455 ArraySizes.push_back(llvm::APSInt::get(1)); 10456 } else { 10457 llvm::APSInt ConstantLengthValue; 10458 if (!Length->EvaluateAsInt(ConstantLengthValue, Context)) 10459 return false; 10460 10461 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 10462 ArraySizes.push_back(ConstantLengthValue); 10463 } 10464 10465 // Get the base of this array section and walk up from there. 10466 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 10467 10468 // We require length = 1 for all array sections except the right-most to 10469 // guarantee that the memory region is contiguous and has no holes in it. 10470 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 10471 Length = TempOASE->getLength(); 10472 if (Length == nullptr) { 10473 // For array sections of the form [1:] or [:], we would need to analyze 10474 // the lower bound... 10475 if (OASE->getColonLoc().isValid()) 10476 return false; 10477 10478 // This is an array subscript which has implicit length 1! 10479 ArraySizes.push_back(llvm::APSInt::get(1)); 10480 } else { 10481 llvm::APSInt ConstantLengthValue; 10482 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) || 10483 ConstantLengthValue.getSExtValue() != 1) 10484 return false; 10485 10486 ArraySizes.push_back(ConstantLengthValue); 10487 } 10488 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 10489 } 10490 10491 // If we have a single element, we don't need to add the implicit lengths. 10492 if (!SingleElement) { 10493 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 10494 // Has implicit length 1! 10495 ArraySizes.push_back(llvm::APSInt::get(1)); 10496 Base = TempASE->getBase()->IgnoreParenImpCasts(); 10497 } 10498 } 10499 10500 // This array section can be privatized as a single value or as a constant 10501 // sized array. 10502 return true; 10503 } 10504 10505 static bool actOnOMPReductionKindClause( 10506 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 10507 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10508 SourceLocation ColonLoc, SourceLocation EndLoc, 10509 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10510 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 10511 DeclarationName DN = ReductionId.getName(); 10512 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 10513 BinaryOperatorKind BOK = BO_Comma; 10514 10515 ASTContext &Context = S.Context; 10516 // OpenMP [2.14.3.6, reduction clause] 10517 // C 10518 // reduction-identifier is either an identifier or one of the following 10519 // operators: +, -, *, &, |, ^, && and || 10520 // C++ 10521 // reduction-identifier is either an id-expression or one of the following 10522 // operators: +, -, *, &, |, ^, && and || 10523 switch (OOK) { 10524 case OO_Plus: 10525 case OO_Minus: 10526 BOK = BO_Add; 10527 break; 10528 case OO_Star: 10529 BOK = BO_Mul; 10530 break; 10531 case OO_Amp: 10532 BOK = BO_And; 10533 break; 10534 case OO_Pipe: 10535 BOK = BO_Or; 10536 break; 10537 case OO_Caret: 10538 BOK = BO_Xor; 10539 break; 10540 case OO_AmpAmp: 10541 BOK = BO_LAnd; 10542 break; 10543 case OO_PipePipe: 10544 BOK = BO_LOr; 10545 break; 10546 case OO_New: 10547 case OO_Delete: 10548 case OO_Array_New: 10549 case OO_Array_Delete: 10550 case OO_Slash: 10551 case OO_Percent: 10552 case OO_Tilde: 10553 case OO_Exclaim: 10554 case OO_Equal: 10555 case OO_Less: 10556 case OO_Greater: 10557 case OO_LessEqual: 10558 case OO_GreaterEqual: 10559 case OO_PlusEqual: 10560 case OO_MinusEqual: 10561 case OO_StarEqual: 10562 case OO_SlashEqual: 10563 case OO_PercentEqual: 10564 case OO_CaretEqual: 10565 case OO_AmpEqual: 10566 case OO_PipeEqual: 10567 case OO_LessLess: 10568 case OO_GreaterGreater: 10569 case OO_LessLessEqual: 10570 case OO_GreaterGreaterEqual: 10571 case OO_EqualEqual: 10572 case OO_ExclaimEqual: 10573 case OO_Spaceship: 10574 case OO_PlusPlus: 10575 case OO_MinusMinus: 10576 case OO_Comma: 10577 case OO_ArrowStar: 10578 case OO_Arrow: 10579 case OO_Call: 10580 case OO_Subscript: 10581 case OO_Conditional: 10582 case OO_Coawait: 10583 case NUM_OVERLOADED_OPERATORS: 10584 llvm_unreachable("Unexpected reduction identifier"); 10585 case OO_None: 10586 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 10587 if (II->isStr("max")) 10588 BOK = BO_GT; 10589 else if (II->isStr("min")) 10590 BOK = BO_LT; 10591 } 10592 break; 10593 } 10594 SourceRange ReductionIdRange; 10595 if (ReductionIdScopeSpec.isValid()) 10596 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 10597 else 10598 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 10599 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 10600 10601 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 10602 bool FirstIter = true; 10603 for (Expr *RefExpr : VarList) { 10604 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 10605 // OpenMP [2.1, C/C++] 10606 // A list item is a variable or array section, subject to the restrictions 10607 // specified in Section 2.4 on page 42 and in each of the sections 10608 // describing clauses and directives for which a list appears. 10609 // OpenMP [2.14.3.3, Restrictions, p.1] 10610 // A variable that is part of another variable (as an array or 10611 // structure element) cannot appear in a private clause. 10612 if (!FirstIter && IR != ER) 10613 ++IR; 10614 FirstIter = false; 10615 SourceLocation ELoc; 10616 SourceRange ERange; 10617 Expr *SimpleRefExpr = RefExpr; 10618 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 10619 /*AllowArraySection=*/true); 10620 if (Res.second) { 10621 // Try to find 'declare reduction' corresponding construct before using 10622 // builtin/overloaded operators. 10623 QualType Type = Context.DependentTy; 10624 CXXCastPath BasePath; 10625 ExprResult DeclareReductionRef = buildDeclareReductionRef( 10626 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 10627 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 10628 Expr *ReductionOp = nullptr; 10629 if (S.CurContext->isDependentContext() && 10630 (DeclareReductionRef.isUnset() || 10631 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 10632 ReductionOp = DeclareReductionRef.get(); 10633 // It will be analyzed later. 10634 RD.push(RefExpr, ReductionOp); 10635 } 10636 ValueDecl *D = Res.first; 10637 if (!D) 10638 continue; 10639 10640 Expr *TaskgroupDescriptor = nullptr; 10641 QualType Type; 10642 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 10643 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 10644 if (ASE) { 10645 Type = ASE->getType().getNonReferenceType(); 10646 } else if (OASE) { 10647 QualType BaseType = 10648 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 10649 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 10650 Type = ATy->getElementType(); 10651 else 10652 Type = BaseType->getPointeeType(); 10653 Type = Type.getNonReferenceType(); 10654 } else { 10655 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 10656 } 10657 auto *VD = dyn_cast<VarDecl>(D); 10658 10659 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 10660 // A variable that appears in a private clause must not have an incomplete 10661 // type or a reference type. 10662 if (S.RequireCompleteType(ELoc, D->getType(), 10663 diag::err_omp_reduction_incomplete_type)) 10664 continue; 10665 // OpenMP [2.14.3.6, reduction clause, Restrictions] 10666 // A list item that appears in a reduction clause must not be 10667 // const-qualified. 10668 if (Type.getNonReferenceType().isConstant(Context)) { 10669 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange; 10670 if (!ASE && !OASE) { 10671 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 10672 VarDecl::DeclarationOnly; 10673 S.Diag(D->getLocation(), 10674 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10675 << D; 10676 } 10677 continue; 10678 } 10679 10680 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 10681 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 10682 // If a list-item is a reference type then it must bind to the same object 10683 // for all threads of the team. 10684 if (!ASE && !OASE) { 10685 if (VD) { 10686 VarDecl *VDDef = VD->getDefinition(); 10687 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 10688 DSARefChecker Check(Stack); 10689 if (Check.Visit(VDDef->getInit())) { 10690 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 10691 << getOpenMPClauseName(ClauseKind) << ERange; 10692 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 10693 continue; 10694 } 10695 } 10696 } 10697 10698 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 10699 // in a Construct] 10700 // Variables with the predetermined data-sharing attributes may not be 10701 // listed in data-sharing attributes clauses, except for the cases 10702 // listed below. For these exceptions only, listing a predetermined 10703 // variable in a data-sharing attribute clause is allowed and overrides 10704 // the variable's predetermined data-sharing attributes. 10705 // OpenMP [2.14.3.6, Restrictions, p.3] 10706 // Any number of reduction clauses can be specified on the directive, 10707 // but a list item can appear only once in the reduction clauses for that 10708 // directive. 10709 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 10710 if (DVar.CKind == OMPC_reduction) { 10711 S.Diag(ELoc, diag::err_omp_once_referenced) 10712 << getOpenMPClauseName(ClauseKind); 10713 if (DVar.RefExpr) 10714 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 10715 continue; 10716 } 10717 if (DVar.CKind != OMPC_unknown) { 10718 S.Diag(ELoc, diag::err_omp_wrong_dsa) 10719 << getOpenMPClauseName(DVar.CKind) 10720 << getOpenMPClauseName(OMPC_reduction); 10721 reportOriginalDsa(S, Stack, D, DVar); 10722 continue; 10723 } 10724 10725 // OpenMP [2.14.3.6, Restrictions, p.1] 10726 // A list item that appears in a reduction clause of a worksharing 10727 // construct must be shared in the parallel regions to which any of the 10728 // worksharing regions arising from the worksharing construct bind. 10729 if (isOpenMPWorksharingDirective(CurrDir) && 10730 !isOpenMPParallelDirective(CurrDir) && 10731 !isOpenMPTeamsDirective(CurrDir)) { 10732 DVar = Stack->getImplicitDSA(D, true); 10733 if (DVar.CKind != OMPC_shared) { 10734 S.Diag(ELoc, diag::err_omp_required_access) 10735 << getOpenMPClauseName(OMPC_reduction) 10736 << getOpenMPClauseName(OMPC_shared); 10737 reportOriginalDsa(S, Stack, D, DVar); 10738 continue; 10739 } 10740 } 10741 } 10742 10743 // Try to find 'declare reduction' corresponding construct before using 10744 // builtin/overloaded operators. 10745 CXXCastPath BasePath; 10746 ExprResult DeclareReductionRef = buildDeclareReductionRef( 10747 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 10748 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 10749 if (DeclareReductionRef.isInvalid()) 10750 continue; 10751 if (S.CurContext->isDependentContext() && 10752 (DeclareReductionRef.isUnset() || 10753 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 10754 RD.push(RefExpr, DeclareReductionRef.get()); 10755 continue; 10756 } 10757 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 10758 // Not allowed reduction identifier is found. 10759 S.Diag(ReductionId.getBeginLoc(), 10760 diag::err_omp_unknown_reduction_identifier) 10761 << Type << ReductionIdRange; 10762 continue; 10763 } 10764 10765 // OpenMP [2.14.3.6, reduction clause, Restrictions] 10766 // The type of a list item that appears in a reduction clause must be valid 10767 // for the reduction-identifier. For a max or min reduction in C, the type 10768 // of the list item must be an allowed arithmetic data type: char, int, 10769 // float, double, or _Bool, possibly modified with long, short, signed, or 10770 // unsigned. For a max or min reduction in C++, the type of the list item 10771 // must be an allowed arithmetic data type: char, wchar_t, int, float, 10772 // double, or bool, possibly modified with long, short, signed, or unsigned. 10773 if (DeclareReductionRef.isUnset()) { 10774 if ((BOK == BO_GT || BOK == BO_LT) && 10775 !(Type->isScalarType() || 10776 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 10777 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 10778 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 10779 if (!ASE && !OASE) { 10780 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 10781 VarDecl::DeclarationOnly; 10782 S.Diag(D->getLocation(), 10783 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10784 << D; 10785 } 10786 continue; 10787 } 10788 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 10789 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 10790 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 10791 << getOpenMPClauseName(ClauseKind); 10792 if (!ASE && !OASE) { 10793 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 10794 VarDecl::DeclarationOnly; 10795 S.Diag(D->getLocation(), 10796 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10797 << D; 10798 } 10799 continue; 10800 } 10801 } 10802 10803 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 10804 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 10805 D->hasAttrs() ? &D->getAttrs() : nullptr); 10806 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 10807 D->hasAttrs() ? &D->getAttrs() : nullptr); 10808 QualType PrivateTy = Type; 10809 10810 // Try if we can determine constant lengths for all array sections and avoid 10811 // the VLA. 10812 bool ConstantLengthOASE = false; 10813 if (OASE) { 10814 bool SingleElement; 10815 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 10816 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 10817 Context, OASE, SingleElement, ArraySizes); 10818 10819 // If we don't have a single element, we must emit a constant array type. 10820 if (ConstantLengthOASE && !SingleElement) { 10821 for (llvm::APSInt &Size : ArraySizes) 10822 PrivateTy = Context.getConstantArrayType( 10823 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0); 10824 } 10825 } 10826 10827 if ((OASE && !ConstantLengthOASE) || 10828 (!OASE && !ASE && 10829 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 10830 if (!Context.getTargetInfo().isVLASupported() && 10831 S.shouldDiagnoseTargetSupportFromOpenMP()) { 10832 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 10833 S.Diag(ELoc, diag::note_vla_unsupported); 10834 continue; 10835 } 10836 // For arrays/array sections only: 10837 // Create pseudo array type for private copy. The size for this array will 10838 // be generated during codegen. 10839 // For array subscripts or single variables Private Ty is the same as Type 10840 // (type of the variable or single array element). 10841 PrivateTy = Context.getVariableArrayType( 10842 Type, 10843 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue), 10844 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 10845 } else if (!ASE && !OASE && 10846 Context.getAsArrayType(D->getType().getNonReferenceType())) { 10847 PrivateTy = D->getType().getNonReferenceType(); 10848 } 10849 // Private copy. 10850 VarDecl *PrivateVD = 10851 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 10852 D->hasAttrs() ? &D->getAttrs() : nullptr, 10853 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 10854 // Add initializer for private variable. 10855 Expr *Init = nullptr; 10856 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 10857 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 10858 if (DeclareReductionRef.isUsable()) { 10859 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 10860 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 10861 if (DRD->getInitializer()) { 10862 Init = DRDRef; 10863 RHSVD->setInit(DRDRef); 10864 RHSVD->setInitStyle(VarDecl::CallInit); 10865 } 10866 } else { 10867 switch (BOK) { 10868 case BO_Add: 10869 case BO_Xor: 10870 case BO_Or: 10871 case BO_LOr: 10872 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 10873 if (Type->isScalarType() || Type->isAnyComplexType()) 10874 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 10875 break; 10876 case BO_Mul: 10877 case BO_LAnd: 10878 if (Type->isScalarType() || Type->isAnyComplexType()) { 10879 // '*' and '&&' reduction ops - initializer is '1'. 10880 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 10881 } 10882 break; 10883 case BO_And: { 10884 // '&' reduction op - initializer is '~0'. 10885 QualType OrigType = Type; 10886 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 10887 Type = ComplexTy->getElementType(); 10888 if (Type->isRealFloatingType()) { 10889 llvm::APFloat InitValue = 10890 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 10891 /*isIEEE=*/true); 10892 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 10893 Type, ELoc); 10894 } else if (Type->isScalarType()) { 10895 uint64_t Size = Context.getTypeSize(Type); 10896 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 10897 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 10898 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 10899 } 10900 if (Init && OrigType->isAnyComplexType()) { 10901 // Init = 0xFFFF + 0xFFFFi; 10902 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 10903 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 10904 } 10905 Type = OrigType; 10906 break; 10907 } 10908 case BO_LT: 10909 case BO_GT: { 10910 // 'min' reduction op - initializer is 'Largest representable number in 10911 // the reduction list item type'. 10912 // 'max' reduction op - initializer is 'Least representable number in 10913 // the reduction list item type'. 10914 if (Type->isIntegerType() || Type->isPointerType()) { 10915 bool IsSigned = Type->hasSignedIntegerRepresentation(); 10916 uint64_t Size = Context.getTypeSize(Type); 10917 QualType IntTy = 10918 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 10919 llvm::APInt InitValue = 10920 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 10921 : llvm::APInt::getMinValue(Size) 10922 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 10923 : llvm::APInt::getMaxValue(Size); 10924 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 10925 if (Type->isPointerType()) { 10926 // Cast to pointer type. 10927 ExprResult CastExpr = S.BuildCStyleCastExpr( 10928 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 10929 if (CastExpr.isInvalid()) 10930 continue; 10931 Init = CastExpr.get(); 10932 } 10933 } else if (Type->isRealFloatingType()) { 10934 llvm::APFloat InitValue = llvm::APFloat::getLargest( 10935 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 10936 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 10937 Type, ELoc); 10938 } 10939 break; 10940 } 10941 case BO_PtrMemD: 10942 case BO_PtrMemI: 10943 case BO_MulAssign: 10944 case BO_Div: 10945 case BO_Rem: 10946 case BO_Sub: 10947 case BO_Shl: 10948 case BO_Shr: 10949 case BO_LE: 10950 case BO_GE: 10951 case BO_EQ: 10952 case BO_NE: 10953 case BO_Cmp: 10954 case BO_AndAssign: 10955 case BO_XorAssign: 10956 case BO_OrAssign: 10957 case BO_Assign: 10958 case BO_AddAssign: 10959 case BO_SubAssign: 10960 case BO_DivAssign: 10961 case BO_RemAssign: 10962 case BO_ShlAssign: 10963 case BO_ShrAssign: 10964 case BO_Comma: 10965 llvm_unreachable("Unexpected reduction operation"); 10966 } 10967 } 10968 if (Init && DeclareReductionRef.isUnset()) 10969 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 10970 else if (!Init) 10971 S.ActOnUninitializedDecl(RHSVD); 10972 if (RHSVD->isInvalidDecl()) 10973 continue; 10974 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 10975 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 10976 << Type << ReductionIdRange; 10977 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 10978 VarDecl::DeclarationOnly; 10979 S.Diag(D->getLocation(), 10980 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10981 << D; 10982 continue; 10983 } 10984 // Store initializer for single element in private copy. Will be used during 10985 // codegen. 10986 PrivateVD->setInit(RHSVD->getInit()); 10987 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 10988 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 10989 ExprResult ReductionOp; 10990 if (DeclareReductionRef.isUsable()) { 10991 QualType RedTy = DeclareReductionRef.get()->getType(); 10992 QualType PtrRedTy = Context.getPointerType(RedTy); 10993 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 10994 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 10995 if (!BasePath.empty()) { 10996 LHS = S.DefaultLvalueConversion(LHS.get()); 10997 RHS = S.DefaultLvalueConversion(RHS.get()); 10998 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 10999 CK_UncheckedDerivedToBase, LHS.get(), 11000 &BasePath, LHS.get()->getValueKind()); 11001 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 11002 CK_UncheckedDerivedToBase, RHS.get(), 11003 &BasePath, RHS.get()->getValueKind()); 11004 } 11005 FunctionProtoType::ExtProtoInfo EPI; 11006 QualType Params[] = {PtrRedTy, PtrRedTy}; 11007 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 11008 auto *OVE = new (Context) OpaqueValueExpr( 11009 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 11010 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 11011 Expr *Args[] = {LHS.get(), RHS.get()}; 11012 ReductionOp = new (Context) 11013 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 11014 } else { 11015 ReductionOp = S.BuildBinOp( 11016 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE); 11017 if (ReductionOp.isUsable()) { 11018 if (BOK != BO_LT && BOK != BO_GT) { 11019 ReductionOp = 11020 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 11021 BO_Assign, LHSDRE, ReductionOp.get()); 11022 } else { 11023 auto *ConditionalOp = new (Context) 11024 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE, 11025 Type, VK_LValue, OK_Ordinary); 11026 ReductionOp = 11027 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 11028 BO_Assign, LHSDRE, ConditionalOp); 11029 } 11030 if (ReductionOp.isUsable()) 11031 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get()); 11032 } 11033 if (!ReductionOp.isUsable()) 11034 continue; 11035 } 11036 11037 // OpenMP [2.15.4.6, Restrictions, p.2] 11038 // A list item that appears in an in_reduction clause of a task construct 11039 // must appear in a task_reduction clause of a construct associated with a 11040 // taskgroup region that includes the participating task in its taskgroup 11041 // set. The construct associated with the innermost region that meets this 11042 // condition must specify the same reduction-identifier as the in_reduction 11043 // clause. 11044 if (ClauseKind == OMPC_in_reduction) { 11045 SourceRange ParentSR; 11046 BinaryOperatorKind ParentBOK; 11047 const Expr *ParentReductionOp; 11048 Expr *ParentBOKTD, *ParentReductionOpTD; 11049 DSAStackTy::DSAVarData ParentBOKDSA = 11050 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 11051 ParentBOKTD); 11052 DSAStackTy::DSAVarData ParentReductionOpDSA = 11053 Stack->getTopMostTaskgroupReductionData( 11054 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 11055 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 11056 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 11057 if (!IsParentBOK && !IsParentReductionOp) { 11058 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction); 11059 continue; 11060 } 11061 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 11062 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK || 11063 IsParentReductionOp) { 11064 bool EmitError = true; 11065 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 11066 llvm::FoldingSetNodeID RedId, ParentRedId; 11067 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 11068 DeclareReductionRef.get()->Profile(RedId, Context, 11069 /*Canonical=*/true); 11070 EmitError = RedId != ParentRedId; 11071 } 11072 if (EmitError) { 11073 S.Diag(ReductionId.getBeginLoc(), 11074 diag::err_omp_reduction_identifier_mismatch) 11075 << ReductionIdRange << RefExpr->getSourceRange(); 11076 S.Diag(ParentSR.getBegin(), 11077 diag::note_omp_previous_reduction_identifier) 11078 << ParentSR 11079 << (IsParentBOK ? ParentBOKDSA.RefExpr 11080 : ParentReductionOpDSA.RefExpr) 11081 ->getSourceRange(); 11082 continue; 11083 } 11084 } 11085 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 11086 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined."); 11087 } 11088 11089 DeclRefExpr *Ref = nullptr; 11090 Expr *VarsExpr = RefExpr->IgnoreParens(); 11091 if (!VD && !S.CurContext->isDependentContext()) { 11092 if (ASE || OASE) { 11093 TransformExprToCaptures RebuildToCapture(S, D); 11094 VarsExpr = 11095 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 11096 Ref = RebuildToCapture.getCapturedExpr(); 11097 } else { 11098 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 11099 } 11100 if (!S.isOpenMPCapturedDecl(D)) { 11101 RD.ExprCaptures.emplace_back(Ref->getDecl()); 11102 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 11103 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 11104 if (!RefRes.isUsable()) 11105 continue; 11106 ExprResult PostUpdateRes = 11107 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 11108 RefRes.get()); 11109 if (!PostUpdateRes.isUsable()) 11110 continue; 11111 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 11112 Stack->getCurrentDirective() == OMPD_taskgroup) { 11113 S.Diag(RefExpr->getExprLoc(), 11114 diag::err_omp_reduction_non_addressable_expression) 11115 << RefExpr->getSourceRange(); 11116 continue; 11117 } 11118 RD.ExprPostUpdates.emplace_back( 11119 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 11120 } 11121 } 11122 } 11123 // All reduction items are still marked as reduction (to do not increase 11124 // code base size). 11125 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 11126 if (CurrDir == OMPD_taskgroup) { 11127 if (DeclareReductionRef.isUsable()) 11128 Stack->addTaskgroupReductionData(D, ReductionIdRange, 11129 DeclareReductionRef.get()); 11130 else 11131 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 11132 } 11133 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 11134 TaskgroupDescriptor); 11135 } 11136 return RD.Vars.empty(); 11137 } 11138 11139 OMPClause *Sema::ActOnOpenMPReductionClause( 11140 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11141 SourceLocation ColonLoc, SourceLocation EndLoc, 11142 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11143 ArrayRef<Expr *> UnresolvedReductions) { 11144 ReductionData RD(VarList.size()); 11145 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 11146 StartLoc, LParenLoc, ColonLoc, EndLoc, 11147 ReductionIdScopeSpec, ReductionId, 11148 UnresolvedReductions, RD)) 11149 return nullptr; 11150 11151 return OMPReductionClause::Create( 11152 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 11153 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 11154 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 11155 buildPreInits(Context, RD.ExprCaptures), 11156 buildPostUpdate(*this, RD.ExprPostUpdates)); 11157 } 11158 11159 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 11160 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11161 SourceLocation ColonLoc, SourceLocation EndLoc, 11162 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11163 ArrayRef<Expr *> UnresolvedReductions) { 11164 ReductionData RD(VarList.size()); 11165 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 11166 StartLoc, LParenLoc, ColonLoc, EndLoc, 11167 ReductionIdScopeSpec, ReductionId, 11168 UnresolvedReductions, RD)) 11169 return nullptr; 11170 11171 return OMPTaskReductionClause::Create( 11172 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 11173 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 11174 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 11175 buildPreInits(Context, RD.ExprCaptures), 11176 buildPostUpdate(*this, RD.ExprPostUpdates)); 11177 } 11178 11179 OMPClause *Sema::ActOnOpenMPInReductionClause( 11180 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11181 SourceLocation ColonLoc, SourceLocation EndLoc, 11182 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11183 ArrayRef<Expr *> UnresolvedReductions) { 11184 ReductionData RD(VarList.size()); 11185 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 11186 StartLoc, LParenLoc, ColonLoc, EndLoc, 11187 ReductionIdScopeSpec, ReductionId, 11188 UnresolvedReductions, RD)) 11189 return nullptr; 11190 11191 return OMPInReductionClause::Create( 11192 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 11193 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 11194 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 11195 buildPreInits(Context, RD.ExprCaptures), 11196 buildPostUpdate(*this, RD.ExprPostUpdates)); 11197 } 11198 11199 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 11200 SourceLocation LinLoc) { 11201 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 11202 LinKind == OMPC_LINEAR_unknown) { 11203 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 11204 return true; 11205 } 11206 return false; 11207 } 11208 11209 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 11210 OpenMPLinearClauseKind LinKind, 11211 QualType Type) { 11212 const auto *VD = dyn_cast_or_null<VarDecl>(D); 11213 // A variable must not have an incomplete type or a reference type. 11214 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 11215 return true; 11216 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 11217 !Type->isReferenceType()) { 11218 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 11219 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 11220 return true; 11221 } 11222 Type = Type.getNonReferenceType(); 11223 11224 // A list item must not be const-qualified. 11225 if (Type.isConstant(Context)) { 11226 Diag(ELoc, diag::err_omp_const_variable) 11227 << getOpenMPClauseName(OMPC_linear); 11228 if (D) { 11229 bool IsDecl = 11230 !VD || 11231 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11232 Diag(D->getLocation(), 11233 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11234 << D; 11235 } 11236 return true; 11237 } 11238 11239 // A list item must be of integral or pointer type. 11240 Type = Type.getUnqualifiedType().getCanonicalType(); 11241 const auto *Ty = Type.getTypePtrOrNull(); 11242 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 11243 !Ty->isPointerType())) { 11244 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 11245 if (D) { 11246 bool IsDecl = 11247 !VD || 11248 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11249 Diag(D->getLocation(), 11250 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11251 << D; 11252 } 11253 return true; 11254 } 11255 return false; 11256 } 11257 11258 OMPClause *Sema::ActOnOpenMPLinearClause( 11259 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 11260 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 11261 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 11262 SmallVector<Expr *, 8> Vars; 11263 SmallVector<Expr *, 8> Privates; 11264 SmallVector<Expr *, 8> Inits; 11265 SmallVector<Decl *, 4> ExprCaptures; 11266 SmallVector<Expr *, 4> ExprPostUpdates; 11267 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 11268 LinKind = OMPC_LINEAR_val; 11269 for (Expr *RefExpr : VarList) { 11270 assert(RefExpr && "NULL expr in OpenMP linear clause."); 11271 SourceLocation ELoc; 11272 SourceRange ERange; 11273 Expr *SimpleRefExpr = RefExpr; 11274 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11275 if (Res.second) { 11276 // It will be analyzed later. 11277 Vars.push_back(RefExpr); 11278 Privates.push_back(nullptr); 11279 Inits.push_back(nullptr); 11280 } 11281 ValueDecl *D = Res.first; 11282 if (!D) 11283 continue; 11284 11285 QualType Type = D->getType(); 11286 auto *VD = dyn_cast<VarDecl>(D); 11287 11288 // OpenMP [2.14.3.7, linear clause] 11289 // A list-item cannot appear in more than one linear clause. 11290 // A list-item that appears in a linear clause cannot appear in any 11291 // other data-sharing attribute clause. 11292 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 11293 if (DVar.RefExpr) { 11294 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 11295 << getOpenMPClauseName(OMPC_linear); 11296 reportOriginalDsa(*this, DSAStack, D, DVar); 11297 continue; 11298 } 11299 11300 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 11301 continue; 11302 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 11303 11304 // Build private copy of original var. 11305 VarDecl *Private = 11306 buildVarDecl(*this, ELoc, Type, D->getName(), 11307 D->hasAttrs() ? &D->getAttrs() : nullptr, 11308 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 11309 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 11310 // Build var to save initial value. 11311 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 11312 Expr *InitExpr; 11313 DeclRefExpr *Ref = nullptr; 11314 if (!VD && !CurContext->isDependentContext()) { 11315 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 11316 if (!isOpenMPCapturedDecl(D)) { 11317 ExprCaptures.push_back(Ref->getDecl()); 11318 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 11319 ExprResult RefRes = DefaultLvalueConversion(Ref); 11320 if (!RefRes.isUsable()) 11321 continue; 11322 ExprResult PostUpdateRes = 11323 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 11324 SimpleRefExpr, RefRes.get()); 11325 if (!PostUpdateRes.isUsable()) 11326 continue; 11327 ExprPostUpdates.push_back( 11328 IgnoredValueConversions(PostUpdateRes.get()).get()); 11329 } 11330 } 11331 } 11332 if (LinKind == OMPC_LINEAR_uval) 11333 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 11334 else 11335 InitExpr = VD ? SimpleRefExpr : Ref; 11336 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 11337 /*DirectInit=*/false); 11338 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 11339 11340 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 11341 Vars.push_back((VD || CurContext->isDependentContext()) 11342 ? RefExpr->IgnoreParens() 11343 : Ref); 11344 Privates.push_back(PrivateRef); 11345 Inits.push_back(InitRef); 11346 } 11347 11348 if (Vars.empty()) 11349 return nullptr; 11350 11351 Expr *StepExpr = Step; 11352 Expr *CalcStepExpr = nullptr; 11353 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 11354 !Step->isInstantiationDependent() && 11355 !Step->containsUnexpandedParameterPack()) { 11356 SourceLocation StepLoc = Step->getBeginLoc(); 11357 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 11358 if (Val.isInvalid()) 11359 return nullptr; 11360 StepExpr = Val.get(); 11361 11362 // Build var to save the step value. 11363 VarDecl *SaveVar = 11364 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 11365 ExprResult SaveRef = 11366 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 11367 ExprResult CalcStep = 11368 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 11369 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 11370 11371 // Warn about zero linear step (it would be probably better specified as 11372 // making corresponding variables 'const'). 11373 llvm::APSInt Result; 11374 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 11375 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 11376 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 11377 << (Vars.size() > 1); 11378 if (!IsConstant && CalcStep.isUsable()) { 11379 // Calculate the step beforehand instead of doing this on each iteration. 11380 // (This is not used if the number of iterations may be kfold-ed). 11381 CalcStepExpr = CalcStep.get(); 11382 } 11383 } 11384 11385 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 11386 ColonLoc, EndLoc, Vars, Privates, Inits, 11387 StepExpr, CalcStepExpr, 11388 buildPreInits(Context, ExprCaptures), 11389 buildPostUpdate(*this, ExprPostUpdates)); 11390 } 11391 11392 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 11393 Expr *NumIterations, Sema &SemaRef, 11394 Scope *S, DSAStackTy *Stack) { 11395 // Walk the vars and build update/final expressions for the CodeGen. 11396 SmallVector<Expr *, 8> Updates; 11397 SmallVector<Expr *, 8> Finals; 11398 Expr *Step = Clause.getStep(); 11399 Expr *CalcStep = Clause.getCalcStep(); 11400 // OpenMP [2.14.3.7, linear clause] 11401 // If linear-step is not specified it is assumed to be 1. 11402 if (!Step) 11403 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 11404 else if (CalcStep) 11405 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 11406 bool HasErrors = false; 11407 auto CurInit = Clause.inits().begin(); 11408 auto CurPrivate = Clause.privates().begin(); 11409 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 11410 for (Expr *RefExpr : Clause.varlists()) { 11411 SourceLocation ELoc; 11412 SourceRange ERange; 11413 Expr *SimpleRefExpr = RefExpr; 11414 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 11415 ValueDecl *D = Res.first; 11416 if (Res.second || !D) { 11417 Updates.push_back(nullptr); 11418 Finals.push_back(nullptr); 11419 HasErrors = true; 11420 continue; 11421 } 11422 auto &&Info = Stack->isLoopControlVariable(D); 11423 // OpenMP [2.15.11, distribute simd Construct] 11424 // A list item may not appear in a linear clause, unless it is the loop 11425 // iteration variable. 11426 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 11427 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 11428 SemaRef.Diag(ELoc, 11429 diag::err_omp_linear_distribute_var_non_loop_iteration); 11430 Updates.push_back(nullptr); 11431 Finals.push_back(nullptr); 11432 HasErrors = true; 11433 continue; 11434 } 11435 Expr *InitExpr = *CurInit; 11436 11437 // Build privatized reference to the current linear var. 11438 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 11439 Expr *CapturedRef; 11440 if (LinKind == OMPC_LINEAR_uval) 11441 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 11442 else 11443 CapturedRef = 11444 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 11445 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 11446 /*RefersToCapture=*/true); 11447 11448 // Build update: Var = InitExpr + IV * Step 11449 ExprResult Update; 11450 if (!Info.first) 11451 Update = 11452 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 11453 InitExpr, IV, Step, /* Subtract */ false); 11454 else 11455 Update = *CurPrivate; 11456 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 11457 /*DiscardedValue=*/true); 11458 11459 // Build final: Var = InitExpr + NumIterations * Step 11460 ExprResult Final; 11461 if (!Info.first) 11462 Final = 11463 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 11464 InitExpr, NumIterations, Step, /*Subtract=*/false); 11465 else 11466 Final = *CurPrivate; 11467 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 11468 /*DiscardedValue=*/true); 11469 11470 if (!Update.isUsable() || !Final.isUsable()) { 11471 Updates.push_back(nullptr); 11472 Finals.push_back(nullptr); 11473 HasErrors = true; 11474 } else { 11475 Updates.push_back(Update.get()); 11476 Finals.push_back(Final.get()); 11477 } 11478 ++CurInit; 11479 ++CurPrivate; 11480 } 11481 Clause.setUpdates(Updates); 11482 Clause.setFinals(Finals); 11483 return HasErrors; 11484 } 11485 11486 OMPClause *Sema::ActOnOpenMPAlignedClause( 11487 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 11488 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 11489 SmallVector<Expr *, 8> Vars; 11490 for (Expr *RefExpr : VarList) { 11491 assert(RefExpr && "NULL expr in OpenMP linear clause."); 11492 SourceLocation ELoc; 11493 SourceRange ERange; 11494 Expr *SimpleRefExpr = RefExpr; 11495 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11496 if (Res.second) { 11497 // It will be analyzed later. 11498 Vars.push_back(RefExpr); 11499 } 11500 ValueDecl *D = Res.first; 11501 if (!D) 11502 continue; 11503 11504 QualType QType = D->getType(); 11505 auto *VD = dyn_cast<VarDecl>(D); 11506 11507 // OpenMP [2.8.1, simd construct, Restrictions] 11508 // The type of list items appearing in the aligned clause must be 11509 // array, pointer, reference to array, or reference to pointer. 11510 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 11511 const Type *Ty = QType.getTypePtrOrNull(); 11512 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 11513 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 11514 << QType << getLangOpts().CPlusPlus << ERange; 11515 bool IsDecl = 11516 !VD || 11517 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11518 Diag(D->getLocation(), 11519 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11520 << D; 11521 continue; 11522 } 11523 11524 // OpenMP [2.8.1, simd construct, Restrictions] 11525 // A list-item cannot appear in more than one aligned clause. 11526 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 11527 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 11528 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 11529 << getOpenMPClauseName(OMPC_aligned); 11530 continue; 11531 } 11532 11533 DeclRefExpr *Ref = nullptr; 11534 if (!VD && isOpenMPCapturedDecl(D)) 11535 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 11536 Vars.push_back(DefaultFunctionArrayConversion( 11537 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 11538 .get()); 11539 } 11540 11541 // OpenMP [2.8.1, simd construct, Description] 11542 // The parameter of the aligned clause, alignment, must be a constant 11543 // positive integer expression. 11544 // If no optional parameter is specified, implementation-defined default 11545 // alignments for SIMD instructions on the target platforms are assumed. 11546 if (Alignment != nullptr) { 11547 ExprResult AlignResult = 11548 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 11549 if (AlignResult.isInvalid()) 11550 return nullptr; 11551 Alignment = AlignResult.get(); 11552 } 11553 if (Vars.empty()) 11554 return nullptr; 11555 11556 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 11557 EndLoc, Vars, Alignment); 11558 } 11559 11560 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 11561 SourceLocation StartLoc, 11562 SourceLocation LParenLoc, 11563 SourceLocation EndLoc) { 11564 SmallVector<Expr *, 8> Vars; 11565 SmallVector<Expr *, 8> SrcExprs; 11566 SmallVector<Expr *, 8> DstExprs; 11567 SmallVector<Expr *, 8> AssignmentOps; 11568 for (Expr *RefExpr : VarList) { 11569 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 11570 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 11571 // It will be analyzed later. 11572 Vars.push_back(RefExpr); 11573 SrcExprs.push_back(nullptr); 11574 DstExprs.push_back(nullptr); 11575 AssignmentOps.push_back(nullptr); 11576 continue; 11577 } 11578 11579 SourceLocation ELoc = RefExpr->getExprLoc(); 11580 // OpenMP [2.1, C/C++] 11581 // A list item is a variable name. 11582 // OpenMP [2.14.4.1, Restrictions, p.1] 11583 // A list item that appears in a copyin clause must be threadprivate. 11584 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 11585 if (!DE || !isa<VarDecl>(DE->getDecl())) { 11586 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 11587 << 0 << RefExpr->getSourceRange(); 11588 continue; 11589 } 11590 11591 Decl *D = DE->getDecl(); 11592 auto *VD = cast<VarDecl>(D); 11593 11594 QualType Type = VD->getType(); 11595 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 11596 // It will be analyzed later. 11597 Vars.push_back(DE); 11598 SrcExprs.push_back(nullptr); 11599 DstExprs.push_back(nullptr); 11600 AssignmentOps.push_back(nullptr); 11601 continue; 11602 } 11603 11604 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 11605 // A list item that appears in a copyin clause must be threadprivate. 11606 if (!DSAStack->isThreadPrivate(VD)) { 11607 Diag(ELoc, diag::err_omp_required_access) 11608 << getOpenMPClauseName(OMPC_copyin) 11609 << getOpenMPDirectiveName(OMPD_threadprivate); 11610 continue; 11611 } 11612 11613 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 11614 // A variable of class type (or array thereof) that appears in a 11615 // copyin clause requires an accessible, unambiguous copy assignment 11616 // operator for the class type. 11617 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 11618 VarDecl *SrcVD = 11619 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 11620 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 11621 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 11622 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 11623 VarDecl *DstVD = 11624 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 11625 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 11626 DeclRefExpr *PseudoDstExpr = 11627 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 11628 // For arrays generate assignment operation for single element and replace 11629 // it by the original array element in CodeGen. 11630 ExprResult AssignmentOp = 11631 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 11632 PseudoSrcExpr); 11633 if (AssignmentOp.isInvalid()) 11634 continue; 11635 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 11636 /*DiscardedValue=*/true); 11637 if (AssignmentOp.isInvalid()) 11638 continue; 11639 11640 DSAStack->addDSA(VD, DE, OMPC_copyin); 11641 Vars.push_back(DE); 11642 SrcExprs.push_back(PseudoSrcExpr); 11643 DstExprs.push_back(PseudoDstExpr); 11644 AssignmentOps.push_back(AssignmentOp.get()); 11645 } 11646 11647 if (Vars.empty()) 11648 return nullptr; 11649 11650 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 11651 SrcExprs, DstExprs, AssignmentOps); 11652 } 11653 11654 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 11655 SourceLocation StartLoc, 11656 SourceLocation LParenLoc, 11657 SourceLocation EndLoc) { 11658 SmallVector<Expr *, 8> Vars; 11659 SmallVector<Expr *, 8> SrcExprs; 11660 SmallVector<Expr *, 8> DstExprs; 11661 SmallVector<Expr *, 8> AssignmentOps; 11662 for (Expr *RefExpr : VarList) { 11663 assert(RefExpr && "NULL expr in OpenMP linear clause."); 11664 SourceLocation ELoc; 11665 SourceRange ERange; 11666 Expr *SimpleRefExpr = RefExpr; 11667 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11668 if (Res.second) { 11669 // It will be analyzed later. 11670 Vars.push_back(RefExpr); 11671 SrcExprs.push_back(nullptr); 11672 DstExprs.push_back(nullptr); 11673 AssignmentOps.push_back(nullptr); 11674 } 11675 ValueDecl *D = Res.first; 11676 if (!D) 11677 continue; 11678 11679 QualType Type = D->getType(); 11680 auto *VD = dyn_cast<VarDecl>(D); 11681 11682 // OpenMP [2.14.4.2, Restrictions, p.2] 11683 // A list item that appears in a copyprivate clause may not appear in a 11684 // private or firstprivate clause on the single construct. 11685 if (!VD || !DSAStack->isThreadPrivate(VD)) { 11686 DSAStackTy::DSAVarData DVar = 11687 DSAStack->getTopDSA(D, /*FromParent=*/false); 11688 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 11689 DVar.RefExpr) { 11690 Diag(ELoc, diag::err_omp_wrong_dsa) 11691 << getOpenMPClauseName(DVar.CKind) 11692 << getOpenMPClauseName(OMPC_copyprivate); 11693 reportOriginalDsa(*this, DSAStack, D, DVar); 11694 continue; 11695 } 11696 11697 // OpenMP [2.11.4.2, Restrictions, p.1] 11698 // All list items that appear in a copyprivate clause must be either 11699 // threadprivate or private in the enclosing context. 11700 if (DVar.CKind == OMPC_unknown) { 11701 DVar = DSAStack->getImplicitDSA(D, false); 11702 if (DVar.CKind == OMPC_shared) { 11703 Diag(ELoc, diag::err_omp_required_access) 11704 << getOpenMPClauseName(OMPC_copyprivate) 11705 << "threadprivate or private in the enclosing context"; 11706 reportOriginalDsa(*this, DSAStack, D, DVar); 11707 continue; 11708 } 11709 } 11710 } 11711 11712 // Variably modified types are not supported. 11713 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 11714 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 11715 << getOpenMPClauseName(OMPC_copyprivate) << Type 11716 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 11717 bool IsDecl = 11718 !VD || 11719 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11720 Diag(D->getLocation(), 11721 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11722 << D; 11723 continue; 11724 } 11725 11726 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 11727 // A variable of class type (or array thereof) that appears in a 11728 // copyin clause requires an accessible, unambiguous copy assignment 11729 // operator for the class type. 11730 Type = Context.getBaseElementType(Type.getNonReferenceType()) 11731 .getUnqualifiedType(); 11732 VarDecl *SrcVD = 11733 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 11734 D->hasAttrs() ? &D->getAttrs() : nullptr); 11735 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 11736 VarDecl *DstVD = 11737 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 11738 D->hasAttrs() ? &D->getAttrs() : nullptr); 11739 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 11740 ExprResult AssignmentOp = BuildBinOp( 11741 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 11742 if (AssignmentOp.isInvalid()) 11743 continue; 11744 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 11745 /*DiscardedValue=*/true); 11746 if (AssignmentOp.isInvalid()) 11747 continue; 11748 11749 // No need to mark vars as copyprivate, they are already threadprivate or 11750 // implicitly private. 11751 assert(VD || isOpenMPCapturedDecl(D)); 11752 Vars.push_back( 11753 VD ? RefExpr->IgnoreParens() 11754 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 11755 SrcExprs.push_back(PseudoSrcExpr); 11756 DstExprs.push_back(PseudoDstExpr); 11757 AssignmentOps.push_back(AssignmentOp.get()); 11758 } 11759 11760 if (Vars.empty()) 11761 return nullptr; 11762 11763 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11764 Vars, SrcExprs, DstExprs, AssignmentOps); 11765 } 11766 11767 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 11768 SourceLocation StartLoc, 11769 SourceLocation LParenLoc, 11770 SourceLocation EndLoc) { 11771 if (VarList.empty()) 11772 return nullptr; 11773 11774 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 11775 } 11776 11777 OMPClause * 11778 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 11779 SourceLocation DepLoc, SourceLocation ColonLoc, 11780 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 11781 SourceLocation LParenLoc, SourceLocation EndLoc) { 11782 if (DSAStack->getCurrentDirective() == OMPD_ordered && 11783 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 11784 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 11785 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 11786 return nullptr; 11787 } 11788 if (DSAStack->getCurrentDirective() != OMPD_ordered && 11789 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 11790 DepKind == OMPC_DEPEND_sink)) { 11791 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 11792 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 11793 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 11794 /*Last=*/OMPC_DEPEND_unknown, Except) 11795 << getOpenMPClauseName(OMPC_depend); 11796 return nullptr; 11797 } 11798 SmallVector<Expr *, 8> Vars; 11799 DSAStackTy::OperatorOffsetTy OpsOffs; 11800 llvm::APSInt DepCounter(/*BitWidth=*/32); 11801 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 11802 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 11803 if (const Expr *OrderedCountExpr = 11804 DSAStack->getParentOrderedRegionParam().first) { 11805 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 11806 TotalDepCount.setIsUnsigned(/*Val=*/true); 11807 } 11808 } 11809 for (Expr *RefExpr : VarList) { 11810 assert(RefExpr && "NULL expr in OpenMP shared clause."); 11811 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 11812 // It will be analyzed later. 11813 Vars.push_back(RefExpr); 11814 continue; 11815 } 11816 11817 SourceLocation ELoc = RefExpr->getExprLoc(); 11818 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 11819 if (DepKind == OMPC_DEPEND_sink) { 11820 if (DSAStack->getParentOrderedRegionParam().first && 11821 DepCounter >= TotalDepCount) { 11822 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 11823 continue; 11824 } 11825 ++DepCounter; 11826 // OpenMP [2.13.9, Summary] 11827 // depend(dependence-type : vec), where dependence-type is: 11828 // 'sink' and where vec is the iteration vector, which has the form: 11829 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 11830 // where n is the value specified by the ordered clause in the loop 11831 // directive, xi denotes the loop iteration variable of the i-th nested 11832 // loop associated with the loop directive, and di is a constant 11833 // non-negative integer. 11834 if (CurContext->isDependentContext()) { 11835 // It will be analyzed later. 11836 Vars.push_back(RefExpr); 11837 continue; 11838 } 11839 SimpleExpr = SimpleExpr->IgnoreImplicit(); 11840 OverloadedOperatorKind OOK = OO_None; 11841 SourceLocation OOLoc; 11842 Expr *LHS = SimpleExpr; 11843 Expr *RHS = nullptr; 11844 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 11845 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 11846 OOLoc = BO->getOperatorLoc(); 11847 LHS = BO->getLHS()->IgnoreParenImpCasts(); 11848 RHS = BO->getRHS()->IgnoreParenImpCasts(); 11849 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 11850 OOK = OCE->getOperator(); 11851 OOLoc = OCE->getOperatorLoc(); 11852 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 11853 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 11854 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 11855 OOK = MCE->getMethodDecl() 11856 ->getNameInfo() 11857 .getName() 11858 .getCXXOverloadedOperator(); 11859 OOLoc = MCE->getCallee()->getExprLoc(); 11860 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 11861 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 11862 } 11863 SourceLocation ELoc; 11864 SourceRange ERange; 11865 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 11866 if (Res.second) { 11867 // It will be analyzed later. 11868 Vars.push_back(RefExpr); 11869 } 11870 ValueDecl *D = Res.first; 11871 if (!D) 11872 continue; 11873 11874 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 11875 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 11876 continue; 11877 } 11878 if (RHS) { 11879 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 11880 RHS, OMPC_depend, /*StrictlyPositive=*/false); 11881 if (RHSRes.isInvalid()) 11882 continue; 11883 } 11884 if (!CurContext->isDependentContext() && 11885 DSAStack->getParentOrderedRegionParam().first && 11886 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 11887 const ValueDecl *VD = 11888 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 11889 if (VD) 11890 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 11891 << 1 << VD; 11892 else 11893 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 11894 continue; 11895 } 11896 OpsOffs.emplace_back(RHS, OOK); 11897 } else { 11898 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 11899 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 11900 (ASE && 11901 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() && 11902 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 11903 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 11904 << RefExpr->getSourceRange(); 11905 continue; 11906 } 11907 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 11908 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 11909 ExprResult Res = 11910 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts()); 11911 getDiagnostics().setSuppressAllDiagnostics(Suppress); 11912 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) { 11913 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 11914 << RefExpr->getSourceRange(); 11915 continue; 11916 } 11917 } 11918 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 11919 } 11920 11921 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 11922 TotalDepCount > VarList.size() && 11923 DSAStack->getParentOrderedRegionParam().first && 11924 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 11925 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 11926 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 11927 } 11928 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 11929 Vars.empty()) 11930 return nullptr; 11931 11932 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11933 DepKind, DepLoc, ColonLoc, Vars, 11934 TotalDepCount.getZExtValue()); 11935 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 11936 DSAStack->isParentOrderedRegion()) 11937 DSAStack->addDoacrossDependClause(C, OpsOffs); 11938 return C; 11939 } 11940 11941 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 11942 SourceLocation LParenLoc, 11943 SourceLocation EndLoc) { 11944 Expr *ValExpr = Device; 11945 Stmt *HelperValStmt = nullptr; 11946 11947 // OpenMP [2.9.1, Restrictions] 11948 // The device expression must evaluate to a non-negative integer value. 11949 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 11950 /*StrictlyPositive=*/false)) 11951 return nullptr; 11952 11953 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11954 OpenMPDirectiveKind CaptureRegion = 11955 getOpenMPCaptureRegionForClause(DKind, OMPC_device); 11956 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 11957 ValExpr = MakeFullExpr(ValExpr).get(); 11958 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 11959 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11960 HelperValStmt = buildPreInits(Context, Captures); 11961 } 11962 11963 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion, 11964 StartLoc, LParenLoc, EndLoc); 11965 } 11966 11967 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 11968 DSAStackTy *Stack, QualType QTy, 11969 bool FullCheck = true) { 11970 NamedDecl *ND; 11971 if (QTy->isIncompleteType(&ND)) { 11972 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 11973 return false; 11974 } 11975 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 11976 !QTy.isTrivialType(SemaRef.Context)) 11977 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 11978 return true; 11979 } 11980 11981 /// Return true if it can be proven that the provided array expression 11982 /// (array section or array subscript) does NOT specify the whole size of the 11983 /// array whose base type is \a BaseQTy. 11984 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 11985 const Expr *E, 11986 QualType BaseQTy) { 11987 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 11988 11989 // If this is an array subscript, it refers to the whole size if the size of 11990 // the dimension is constant and equals 1. Also, an array section assumes the 11991 // format of an array subscript if no colon is used. 11992 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 11993 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 11994 return ATy->getSize().getSExtValue() != 1; 11995 // Size can't be evaluated statically. 11996 return false; 11997 } 11998 11999 assert(OASE && "Expecting array section if not an array subscript."); 12000 const Expr *LowerBound = OASE->getLowerBound(); 12001 const Expr *Length = OASE->getLength(); 12002 12003 // If there is a lower bound that does not evaluates to zero, we are not 12004 // covering the whole dimension. 12005 if (LowerBound) { 12006 llvm::APSInt ConstLowerBound; 12007 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 12008 return false; // Can't get the integer value as a constant. 12009 if (ConstLowerBound.getSExtValue()) 12010 return true; 12011 } 12012 12013 // If we don't have a length we covering the whole dimension. 12014 if (!Length) 12015 return false; 12016 12017 // If the base is a pointer, we don't have a way to get the size of the 12018 // pointee. 12019 if (BaseQTy->isPointerType()) 12020 return false; 12021 12022 // We can only check if the length is the same as the size of the dimension 12023 // if we have a constant array. 12024 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 12025 if (!CATy) 12026 return false; 12027 12028 llvm::APSInt ConstLength; 12029 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 12030 return false; // Can't get the integer value as a constant. 12031 12032 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 12033 } 12034 12035 // Return true if it can be proven that the provided array expression (array 12036 // section or array subscript) does NOT specify a single element of the array 12037 // whose base type is \a BaseQTy. 12038 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 12039 const Expr *E, 12040 QualType BaseQTy) { 12041 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 12042 12043 // An array subscript always refer to a single element. Also, an array section 12044 // assumes the format of an array subscript if no colon is used. 12045 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 12046 return false; 12047 12048 assert(OASE && "Expecting array section if not an array subscript."); 12049 const Expr *Length = OASE->getLength(); 12050 12051 // If we don't have a length we have to check if the array has unitary size 12052 // for this dimension. Also, we should always expect a length if the base type 12053 // is pointer. 12054 if (!Length) { 12055 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 12056 return ATy->getSize().getSExtValue() != 1; 12057 // We cannot assume anything. 12058 return false; 12059 } 12060 12061 // Check if the length evaluates to 1. 12062 llvm::APSInt ConstLength; 12063 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 12064 return false; // Can't get the integer value as a constant. 12065 12066 return ConstLength.getSExtValue() != 1; 12067 } 12068 12069 // Return the expression of the base of the mappable expression or null if it 12070 // cannot be determined and do all the necessary checks to see if the expression 12071 // is valid as a standalone mappable expression. In the process, record all the 12072 // components of the expression. 12073 static const Expr *checkMapClauseExpressionBase( 12074 Sema &SemaRef, Expr *E, 12075 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 12076 OpenMPClauseKind CKind, bool NoDiagnose) { 12077 SourceLocation ELoc = E->getExprLoc(); 12078 SourceRange ERange = E->getSourceRange(); 12079 12080 // The base of elements of list in a map clause have to be either: 12081 // - a reference to variable or field. 12082 // - a member expression. 12083 // - an array expression. 12084 // 12085 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 12086 // reference to 'r'. 12087 // 12088 // If we have: 12089 // 12090 // struct SS { 12091 // Bla S; 12092 // foo() { 12093 // #pragma omp target map (S.Arr[:12]); 12094 // } 12095 // } 12096 // 12097 // We want to retrieve the member expression 'this->S'; 12098 12099 const Expr *RelevantExpr = nullptr; 12100 12101 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 12102 // If a list item is an array section, it must specify contiguous storage. 12103 // 12104 // For this restriction it is sufficient that we make sure only references 12105 // to variables or fields and array expressions, and that no array sections 12106 // exist except in the rightmost expression (unless they cover the whole 12107 // dimension of the array). E.g. these would be invalid: 12108 // 12109 // r.ArrS[3:5].Arr[6:7] 12110 // 12111 // r.ArrS[3:5].x 12112 // 12113 // but these would be valid: 12114 // r.ArrS[3].Arr[6:7] 12115 // 12116 // r.ArrS[3].x 12117 12118 bool AllowUnitySizeArraySection = true; 12119 bool AllowWholeSizeArraySection = true; 12120 12121 while (!RelevantExpr) { 12122 E = E->IgnoreParenImpCasts(); 12123 12124 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 12125 if (!isa<VarDecl>(CurE->getDecl())) 12126 return nullptr; 12127 12128 RelevantExpr = CurE; 12129 12130 // If we got a reference to a declaration, we should not expect any array 12131 // section before that. 12132 AllowUnitySizeArraySection = false; 12133 AllowWholeSizeArraySection = false; 12134 12135 // Record the component. 12136 CurComponents.emplace_back(CurE, CurE->getDecl()); 12137 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) { 12138 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 12139 12140 if (isa<CXXThisExpr>(BaseE)) 12141 // We found a base expression: this->Val. 12142 RelevantExpr = CurE; 12143 else 12144 E = BaseE; 12145 12146 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 12147 if (!NoDiagnose) { 12148 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 12149 << CurE->getSourceRange(); 12150 return nullptr; 12151 } 12152 if (RelevantExpr) 12153 return nullptr; 12154 continue; 12155 } 12156 12157 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 12158 12159 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 12160 // A bit-field cannot appear in a map clause. 12161 // 12162 if (FD->isBitField()) { 12163 if (!NoDiagnose) { 12164 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 12165 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 12166 return nullptr; 12167 } 12168 if (RelevantExpr) 12169 return nullptr; 12170 continue; 12171 } 12172 12173 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12174 // If the type of a list item is a reference to a type T then the type 12175 // will be considered to be T for all purposes of this clause. 12176 QualType CurType = BaseE->getType().getNonReferenceType(); 12177 12178 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 12179 // A list item cannot be a variable that is a member of a structure with 12180 // a union type. 12181 // 12182 if (CurType->isUnionType()) { 12183 if (!NoDiagnose) { 12184 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 12185 << CurE->getSourceRange(); 12186 return nullptr; 12187 } 12188 continue; 12189 } 12190 12191 // If we got a member expression, we should not expect any array section 12192 // before that: 12193 // 12194 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 12195 // If a list item is an element of a structure, only the rightmost symbol 12196 // of the variable reference can be an array section. 12197 // 12198 AllowUnitySizeArraySection = false; 12199 AllowWholeSizeArraySection = false; 12200 12201 // Record the component. 12202 CurComponents.emplace_back(CurE, FD); 12203 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 12204 E = CurE->getBase()->IgnoreParenImpCasts(); 12205 12206 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 12207 if (!NoDiagnose) { 12208 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 12209 << 0 << CurE->getSourceRange(); 12210 return nullptr; 12211 } 12212 continue; 12213 } 12214 12215 // If we got an array subscript that express the whole dimension we 12216 // can have any array expressions before. If it only expressing part of 12217 // the dimension, we can only have unitary-size array expressions. 12218 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 12219 E->getType())) 12220 AllowWholeSizeArraySection = false; 12221 12222 // Record the component - we don't have any declaration associated. 12223 CurComponents.emplace_back(CurE, nullptr); 12224 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 12225 assert(!NoDiagnose && "Array sections cannot be implicitly mapped."); 12226 E = CurE->getBase()->IgnoreParenImpCasts(); 12227 12228 QualType CurType = 12229 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 12230 12231 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12232 // If the type of a list item is a reference to a type T then the type 12233 // will be considered to be T for all purposes of this clause. 12234 if (CurType->isReferenceType()) 12235 CurType = CurType->getPointeeType(); 12236 12237 bool IsPointer = CurType->isAnyPointerType(); 12238 12239 if (!IsPointer && !CurType->isArrayType()) { 12240 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 12241 << 0 << CurE->getSourceRange(); 12242 return nullptr; 12243 } 12244 12245 bool NotWhole = 12246 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 12247 bool NotUnity = 12248 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 12249 12250 if (AllowWholeSizeArraySection) { 12251 // Any array section is currently allowed. Allowing a whole size array 12252 // section implies allowing a unity array section as well. 12253 // 12254 // If this array section refers to the whole dimension we can still 12255 // accept other array sections before this one, except if the base is a 12256 // pointer. Otherwise, only unitary sections are accepted. 12257 if (NotWhole || IsPointer) 12258 AllowWholeSizeArraySection = false; 12259 } else if (AllowUnitySizeArraySection && NotUnity) { 12260 // A unity or whole array section is not allowed and that is not 12261 // compatible with the properties of the current array section. 12262 SemaRef.Diag( 12263 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 12264 << CurE->getSourceRange(); 12265 return nullptr; 12266 } 12267 12268 // Record the component - we don't have any declaration associated. 12269 CurComponents.emplace_back(CurE, nullptr); 12270 } else { 12271 if (!NoDiagnose) { 12272 // If nothing else worked, this is not a valid map clause expression. 12273 SemaRef.Diag( 12274 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 12275 << ERange; 12276 } 12277 return nullptr; 12278 } 12279 } 12280 12281 return RelevantExpr; 12282 } 12283 12284 // Return true if expression E associated with value VD has conflicts with other 12285 // map information. 12286 static bool checkMapConflicts( 12287 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 12288 bool CurrentRegionOnly, 12289 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 12290 OpenMPClauseKind CKind) { 12291 assert(VD && E); 12292 SourceLocation ELoc = E->getExprLoc(); 12293 SourceRange ERange = E->getSourceRange(); 12294 12295 // In order to easily check the conflicts we need to match each component of 12296 // the expression under test with the components of the expressions that are 12297 // already in the stack. 12298 12299 assert(!CurComponents.empty() && "Map clause expression with no components!"); 12300 assert(CurComponents.back().getAssociatedDeclaration() == VD && 12301 "Map clause expression with unexpected base!"); 12302 12303 // Variables to help detecting enclosing problems in data environment nests. 12304 bool IsEnclosedByDataEnvironmentExpr = false; 12305 const Expr *EnclosingExpr = nullptr; 12306 12307 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 12308 VD, CurrentRegionOnly, 12309 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 12310 ERange, CKind, &EnclosingExpr, 12311 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 12312 StackComponents, 12313 OpenMPClauseKind) { 12314 assert(!StackComponents.empty() && 12315 "Map clause expression with no components!"); 12316 assert(StackComponents.back().getAssociatedDeclaration() == VD && 12317 "Map clause expression with unexpected base!"); 12318 (void)VD; 12319 12320 // The whole expression in the stack. 12321 const Expr *RE = StackComponents.front().getAssociatedExpression(); 12322 12323 // Expressions must start from the same base. Here we detect at which 12324 // point both expressions diverge from each other and see if we can 12325 // detect if the memory referred to both expressions is contiguous and 12326 // do not overlap. 12327 auto CI = CurComponents.rbegin(); 12328 auto CE = CurComponents.rend(); 12329 auto SI = StackComponents.rbegin(); 12330 auto SE = StackComponents.rend(); 12331 for (; CI != CE && SI != SE; ++CI, ++SI) { 12332 12333 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 12334 // At most one list item can be an array item derived from a given 12335 // variable in map clauses of the same construct. 12336 if (CurrentRegionOnly && 12337 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 12338 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 12339 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 12340 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 12341 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 12342 diag::err_omp_multiple_array_items_in_map_clause) 12343 << CI->getAssociatedExpression()->getSourceRange(); 12344 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 12345 diag::note_used_here) 12346 << SI->getAssociatedExpression()->getSourceRange(); 12347 return true; 12348 } 12349 12350 // Do both expressions have the same kind? 12351 if (CI->getAssociatedExpression()->getStmtClass() != 12352 SI->getAssociatedExpression()->getStmtClass()) 12353 break; 12354 12355 // Are we dealing with different variables/fields? 12356 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 12357 break; 12358 } 12359 // Check if the extra components of the expressions in the enclosing 12360 // data environment are redundant for the current base declaration. 12361 // If they are, the maps completely overlap, which is legal. 12362 for (; SI != SE; ++SI) { 12363 QualType Type; 12364 if (const auto *ASE = 12365 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 12366 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 12367 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 12368 SI->getAssociatedExpression())) { 12369 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 12370 Type = 12371 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 12372 } 12373 if (Type.isNull() || Type->isAnyPointerType() || 12374 checkArrayExpressionDoesNotReferToWholeSize( 12375 SemaRef, SI->getAssociatedExpression(), Type)) 12376 break; 12377 } 12378 12379 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 12380 // List items of map clauses in the same construct must not share 12381 // original storage. 12382 // 12383 // If the expressions are exactly the same or one is a subset of the 12384 // other, it means they are sharing storage. 12385 if (CI == CE && SI == SE) { 12386 if (CurrentRegionOnly) { 12387 if (CKind == OMPC_map) { 12388 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 12389 } else { 12390 assert(CKind == OMPC_to || CKind == OMPC_from); 12391 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 12392 << ERange; 12393 } 12394 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12395 << RE->getSourceRange(); 12396 return true; 12397 } 12398 // If we find the same expression in the enclosing data environment, 12399 // that is legal. 12400 IsEnclosedByDataEnvironmentExpr = true; 12401 return false; 12402 } 12403 12404 QualType DerivedType = 12405 std::prev(CI)->getAssociatedDeclaration()->getType(); 12406 SourceLocation DerivedLoc = 12407 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 12408 12409 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12410 // If the type of a list item is a reference to a type T then the type 12411 // will be considered to be T for all purposes of this clause. 12412 DerivedType = DerivedType.getNonReferenceType(); 12413 12414 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 12415 // A variable for which the type is pointer and an array section 12416 // derived from that variable must not appear as list items of map 12417 // clauses of the same construct. 12418 // 12419 // Also, cover one of the cases in: 12420 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 12421 // If any part of the original storage of a list item has corresponding 12422 // storage in the device data environment, all of the original storage 12423 // must have corresponding storage in the device data environment. 12424 // 12425 if (DerivedType->isAnyPointerType()) { 12426 if (CI == CE || SI == SE) { 12427 SemaRef.Diag( 12428 DerivedLoc, 12429 diag::err_omp_pointer_mapped_along_with_derived_section) 12430 << DerivedLoc; 12431 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12432 << RE->getSourceRange(); 12433 return true; 12434 } 12435 if (CI->getAssociatedExpression()->getStmtClass() != 12436 SI->getAssociatedExpression()->getStmtClass() || 12437 CI->getAssociatedDeclaration()->getCanonicalDecl() == 12438 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 12439 assert(CI != CE && SI != SE); 12440 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 12441 << DerivedLoc; 12442 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12443 << RE->getSourceRange(); 12444 return true; 12445 } 12446 } 12447 12448 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 12449 // List items of map clauses in the same construct must not share 12450 // original storage. 12451 // 12452 // An expression is a subset of the other. 12453 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 12454 if (CKind == OMPC_map) { 12455 if (CI != CE || SI != SE) { 12456 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 12457 // a pointer. 12458 auto Begin = 12459 CI != CE ? CurComponents.begin() : StackComponents.begin(); 12460 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 12461 auto It = Begin; 12462 while (It != End && !It->getAssociatedDeclaration()) 12463 std::advance(It, 1); 12464 assert(It != End && 12465 "Expected at least one component with the declaration."); 12466 if (It != Begin && It->getAssociatedDeclaration() 12467 ->getType() 12468 .getCanonicalType() 12469 ->isAnyPointerType()) { 12470 IsEnclosedByDataEnvironmentExpr = false; 12471 EnclosingExpr = nullptr; 12472 return false; 12473 } 12474 } 12475 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 12476 } else { 12477 assert(CKind == OMPC_to || CKind == OMPC_from); 12478 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 12479 << ERange; 12480 } 12481 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12482 << RE->getSourceRange(); 12483 return true; 12484 } 12485 12486 // The current expression uses the same base as other expression in the 12487 // data environment but does not contain it completely. 12488 if (!CurrentRegionOnly && SI != SE) 12489 EnclosingExpr = RE; 12490 12491 // The current expression is a subset of the expression in the data 12492 // environment. 12493 IsEnclosedByDataEnvironmentExpr |= 12494 (!CurrentRegionOnly && CI != CE && SI == SE); 12495 12496 return false; 12497 }); 12498 12499 if (CurrentRegionOnly) 12500 return FoundError; 12501 12502 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 12503 // If any part of the original storage of a list item has corresponding 12504 // storage in the device data environment, all of the original storage must 12505 // have corresponding storage in the device data environment. 12506 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 12507 // If a list item is an element of a structure, and a different element of 12508 // the structure has a corresponding list item in the device data environment 12509 // prior to a task encountering the construct associated with the map clause, 12510 // then the list item must also have a corresponding list item in the device 12511 // data environment prior to the task encountering the construct. 12512 // 12513 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 12514 SemaRef.Diag(ELoc, 12515 diag::err_omp_original_storage_is_shared_and_does_not_contain) 12516 << ERange; 12517 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 12518 << EnclosingExpr->getSourceRange(); 12519 return true; 12520 } 12521 12522 return FoundError; 12523 } 12524 12525 namespace { 12526 // Utility struct that gathers all the related lists associated with a mappable 12527 // expression. 12528 struct MappableVarListInfo { 12529 // The list of expressions. 12530 ArrayRef<Expr *> VarList; 12531 // The list of processed expressions. 12532 SmallVector<Expr *, 16> ProcessedVarList; 12533 // The mappble components for each expression. 12534 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 12535 // The base declaration of the variable. 12536 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 12537 12538 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 12539 // We have a list of components and base declarations for each entry in the 12540 // variable list. 12541 VarComponents.reserve(VarList.size()); 12542 VarBaseDeclarations.reserve(VarList.size()); 12543 } 12544 }; 12545 } 12546 12547 // Check the validity of the provided variable list for the provided clause kind 12548 // \a CKind. In the check process the valid expressions, and mappable expression 12549 // components and variables are extracted and used to fill \a Vars, 12550 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 12551 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 12552 static void 12553 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 12554 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 12555 SourceLocation StartLoc, 12556 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 12557 bool IsMapTypeImplicit = false) { 12558 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 12559 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 12560 "Unexpected clause kind with mappable expressions!"); 12561 12562 // Keep track of the mappable components and base declarations in this clause. 12563 // Each entry in the list is going to have a list of components associated. We 12564 // record each set of the components so that we can build the clause later on. 12565 // In the end we should have the same amount of declarations and component 12566 // lists. 12567 12568 for (Expr *RE : MVLI.VarList) { 12569 assert(RE && "Null expr in omp to/from/map clause"); 12570 SourceLocation ELoc = RE->getExprLoc(); 12571 12572 const Expr *VE = RE->IgnoreParenLValueCasts(); 12573 12574 if (VE->isValueDependent() || VE->isTypeDependent() || 12575 VE->isInstantiationDependent() || 12576 VE->containsUnexpandedParameterPack()) { 12577 // We can only analyze this information once the missing information is 12578 // resolved. 12579 MVLI.ProcessedVarList.push_back(RE); 12580 continue; 12581 } 12582 12583 Expr *SimpleExpr = RE->IgnoreParenCasts(); 12584 12585 if (!RE->IgnoreParenImpCasts()->isLValue()) { 12586 SemaRef.Diag(ELoc, 12587 diag::err_omp_expected_named_var_member_or_array_expression) 12588 << RE->getSourceRange(); 12589 continue; 12590 } 12591 12592 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 12593 ValueDecl *CurDeclaration = nullptr; 12594 12595 // Obtain the array or member expression bases if required. Also, fill the 12596 // components array with all the components identified in the process. 12597 const Expr *BE = checkMapClauseExpressionBase( 12598 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false); 12599 if (!BE) 12600 continue; 12601 12602 assert(!CurComponents.empty() && 12603 "Invalid mappable expression information."); 12604 12605 // For the following checks, we rely on the base declaration which is 12606 // expected to be associated with the last component. The declaration is 12607 // expected to be a variable or a field (if 'this' is being mapped). 12608 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 12609 assert(CurDeclaration && "Null decl on map clause."); 12610 assert( 12611 CurDeclaration->isCanonicalDecl() && 12612 "Expecting components to have associated only canonical declarations."); 12613 12614 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 12615 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 12616 12617 assert((VD || FD) && "Only variables or fields are expected here!"); 12618 (void)FD; 12619 12620 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 12621 // threadprivate variables cannot appear in a map clause. 12622 // OpenMP 4.5 [2.10.5, target update Construct] 12623 // threadprivate variables cannot appear in a from clause. 12624 if (VD && DSAS->isThreadPrivate(VD)) { 12625 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 12626 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 12627 << getOpenMPClauseName(CKind); 12628 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 12629 continue; 12630 } 12631 12632 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 12633 // A list item cannot appear in both a map clause and a data-sharing 12634 // attribute clause on the same construct. 12635 12636 // Check conflicts with other map clause expressions. We check the conflicts 12637 // with the current construct separately from the enclosing data 12638 // environment, because the restrictions are different. We only have to 12639 // check conflicts across regions for the map clauses. 12640 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 12641 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 12642 break; 12643 if (CKind == OMPC_map && 12644 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 12645 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 12646 break; 12647 12648 // OpenMP 4.5 [2.10.5, target update Construct] 12649 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12650 // If the type of a list item is a reference to a type T then the type will 12651 // be considered to be T for all purposes of this clause. 12652 auto I = llvm::find_if( 12653 CurComponents, 12654 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 12655 return MC.getAssociatedDeclaration(); 12656 }); 12657 assert(I != CurComponents.end() && "Null decl on map clause."); 12658 QualType Type = 12659 I->getAssociatedDeclaration()->getType().getNonReferenceType(); 12660 12661 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 12662 // A list item in a to or from clause must have a mappable type. 12663 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 12664 // A list item must have a mappable type. 12665 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 12666 DSAS, Type)) 12667 continue; 12668 12669 if (CKind == OMPC_map) { 12670 // target enter data 12671 // OpenMP [2.10.2, Restrictions, p. 99] 12672 // A map-type must be specified in all map clauses and must be either 12673 // to or alloc. 12674 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 12675 if (DKind == OMPD_target_enter_data && 12676 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 12677 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 12678 << (IsMapTypeImplicit ? 1 : 0) 12679 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 12680 << getOpenMPDirectiveName(DKind); 12681 continue; 12682 } 12683 12684 // target exit_data 12685 // OpenMP [2.10.3, Restrictions, p. 102] 12686 // A map-type must be specified in all map clauses and must be either 12687 // from, release, or delete. 12688 if (DKind == OMPD_target_exit_data && 12689 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 12690 MapType == OMPC_MAP_delete)) { 12691 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 12692 << (IsMapTypeImplicit ? 1 : 0) 12693 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 12694 << getOpenMPDirectiveName(DKind); 12695 continue; 12696 } 12697 12698 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 12699 // A list item cannot appear in both a map clause and a data-sharing 12700 // attribute clause on the same construct 12701 if (VD && isOpenMPTargetExecutionDirective(DKind)) { 12702 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 12703 if (isOpenMPPrivate(DVar.CKind)) { 12704 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 12705 << getOpenMPClauseName(DVar.CKind) 12706 << getOpenMPClauseName(OMPC_map) 12707 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 12708 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 12709 continue; 12710 } 12711 } 12712 } 12713 12714 // Save the current expression. 12715 MVLI.ProcessedVarList.push_back(RE); 12716 12717 // Store the components in the stack so that they can be used to check 12718 // against other clauses later on. 12719 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 12720 /*WhereFoundClauseKind=*/OMPC_map); 12721 12722 // Save the components and declaration to create the clause. For purposes of 12723 // the clause creation, any component list that has has base 'this' uses 12724 // null as base declaration. 12725 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 12726 MVLI.VarComponents.back().append(CurComponents.begin(), 12727 CurComponents.end()); 12728 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 12729 : CurDeclaration); 12730 } 12731 } 12732 12733 OMPClause * 12734 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 12735 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 12736 SourceLocation MapLoc, SourceLocation ColonLoc, 12737 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 12738 SourceLocation LParenLoc, SourceLocation EndLoc) { 12739 MappableVarListInfo MVLI(VarList); 12740 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 12741 MapType, IsMapTypeImplicit); 12742 12743 // We need to produce a map clause even if we don't have variables so that 12744 // other diagnostics related with non-existing map clauses are accurate. 12745 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12746 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 12747 MVLI.VarComponents, MapTypeModifier, MapType, 12748 IsMapTypeImplicit, MapLoc); 12749 } 12750 12751 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 12752 TypeResult ParsedType) { 12753 assert(ParsedType.isUsable()); 12754 12755 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 12756 if (ReductionType.isNull()) 12757 return QualType(); 12758 12759 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 12760 // A type name in a declare reduction directive cannot be a function type, an 12761 // array type, a reference type, or a type qualified with const, volatile or 12762 // restrict. 12763 if (ReductionType.hasQualifiers()) { 12764 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 12765 return QualType(); 12766 } 12767 12768 if (ReductionType->isFunctionType()) { 12769 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 12770 return QualType(); 12771 } 12772 if (ReductionType->isReferenceType()) { 12773 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 12774 return QualType(); 12775 } 12776 if (ReductionType->isArrayType()) { 12777 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 12778 return QualType(); 12779 } 12780 return ReductionType; 12781 } 12782 12783 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 12784 Scope *S, DeclContext *DC, DeclarationName Name, 12785 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 12786 AccessSpecifier AS, Decl *PrevDeclInScope) { 12787 SmallVector<Decl *, 8> Decls; 12788 Decls.reserve(ReductionTypes.size()); 12789 12790 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 12791 forRedeclarationInCurContext()); 12792 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 12793 // A reduction-identifier may not be re-declared in the current scope for the 12794 // same type or for a type that is compatible according to the base language 12795 // rules. 12796 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 12797 OMPDeclareReductionDecl *PrevDRD = nullptr; 12798 bool InCompoundScope = true; 12799 if (S != nullptr) { 12800 // Find previous declaration with the same name not referenced in other 12801 // declarations. 12802 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 12803 InCompoundScope = 12804 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 12805 LookupName(Lookup, S); 12806 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 12807 /*AllowInlineNamespace=*/false); 12808 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 12809 LookupResult::Filter Filter = Lookup.makeFilter(); 12810 while (Filter.hasNext()) { 12811 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 12812 if (InCompoundScope) { 12813 auto I = UsedAsPrevious.find(PrevDecl); 12814 if (I == UsedAsPrevious.end()) 12815 UsedAsPrevious[PrevDecl] = false; 12816 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 12817 UsedAsPrevious[D] = true; 12818 } 12819 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 12820 PrevDecl->getLocation(); 12821 } 12822 Filter.done(); 12823 if (InCompoundScope) { 12824 for (const auto &PrevData : UsedAsPrevious) { 12825 if (!PrevData.second) { 12826 PrevDRD = PrevData.first; 12827 break; 12828 } 12829 } 12830 } 12831 } else if (PrevDeclInScope != nullptr) { 12832 auto *PrevDRDInScope = PrevDRD = 12833 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 12834 do { 12835 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 12836 PrevDRDInScope->getLocation(); 12837 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 12838 } while (PrevDRDInScope != nullptr); 12839 } 12840 for (const auto &TyData : ReductionTypes) { 12841 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 12842 bool Invalid = false; 12843 if (I != PreviousRedeclTypes.end()) { 12844 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 12845 << TyData.first; 12846 Diag(I->second, diag::note_previous_definition); 12847 Invalid = true; 12848 } 12849 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 12850 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 12851 Name, TyData.first, PrevDRD); 12852 DC->addDecl(DRD); 12853 DRD->setAccess(AS); 12854 Decls.push_back(DRD); 12855 if (Invalid) 12856 DRD->setInvalidDecl(); 12857 else 12858 PrevDRD = DRD; 12859 } 12860 12861 return DeclGroupPtrTy::make( 12862 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 12863 } 12864 12865 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 12866 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12867 12868 // Enter new function scope. 12869 PushFunctionScope(); 12870 setFunctionHasBranchProtectedScope(); 12871 getCurFunction()->setHasOMPDeclareReductionCombiner(); 12872 12873 if (S != nullptr) 12874 PushDeclContext(S, DRD); 12875 else 12876 CurContext = DRD; 12877 12878 PushExpressionEvaluationContext( 12879 ExpressionEvaluationContext::PotentiallyEvaluated); 12880 12881 QualType ReductionType = DRD->getType(); 12882 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 12883 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 12884 // uses semantics of argument handles by value, but it should be passed by 12885 // reference. C lang does not support references, so pass all parameters as 12886 // pointers. 12887 // Create 'T omp_in;' variable. 12888 VarDecl *OmpInParm = 12889 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 12890 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 12891 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 12892 // uses semantics of argument handles by value, but it should be passed by 12893 // reference. C lang does not support references, so pass all parameters as 12894 // pointers. 12895 // Create 'T omp_out;' variable. 12896 VarDecl *OmpOutParm = 12897 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 12898 if (S != nullptr) { 12899 PushOnScopeChains(OmpInParm, S); 12900 PushOnScopeChains(OmpOutParm, S); 12901 } else { 12902 DRD->addDecl(OmpInParm); 12903 DRD->addDecl(OmpOutParm); 12904 } 12905 Expr *InE = 12906 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 12907 Expr *OutE = 12908 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 12909 DRD->setCombinerData(InE, OutE); 12910 } 12911 12912 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 12913 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12914 DiscardCleanupsInEvaluationContext(); 12915 PopExpressionEvaluationContext(); 12916 12917 PopDeclContext(); 12918 PopFunctionScopeInfo(); 12919 12920 if (Combiner != nullptr) 12921 DRD->setCombiner(Combiner); 12922 else 12923 DRD->setInvalidDecl(); 12924 } 12925 12926 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 12927 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12928 12929 // Enter new function scope. 12930 PushFunctionScope(); 12931 setFunctionHasBranchProtectedScope(); 12932 12933 if (S != nullptr) 12934 PushDeclContext(S, DRD); 12935 else 12936 CurContext = DRD; 12937 12938 PushExpressionEvaluationContext( 12939 ExpressionEvaluationContext::PotentiallyEvaluated); 12940 12941 QualType ReductionType = DRD->getType(); 12942 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 12943 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 12944 // uses semantics of argument handles by value, but it should be passed by 12945 // reference. C lang does not support references, so pass all parameters as 12946 // pointers. 12947 // Create 'T omp_priv;' variable. 12948 VarDecl *OmpPrivParm = 12949 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 12950 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 12951 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 12952 // uses semantics of argument handles by value, but it should be passed by 12953 // reference. C lang does not support references, so pass all parameters as 12954 // pointers. 12955 // Create 'T omp_orig;' variable. 12956 VarDecl *OmpOrigParm = 12957 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 12958 if (S != nullptr) { 12959 PushOnScopeChains(OmpPrivParm, S); 12960 PushOnScopeChains(OmpOrigParm, S); 12961 } else { 12962 DRD->addDecl(OmpPrivParm); 12963 DRD->addDecl(OmpOrigParm); 12964 } 12965 Expr *OrigE = 12966 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 12967 Expr *PrivE = 12968 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 12969 DRD->setInitializerData(OrigE, PrivE); 12970 return OmpPrivParm; 12971 } 12972 12973 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 12974 VarDecl *OmpPrivParm) { 12975 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12976 DiscardCleanupsInEvaluationContext(); 12977 PopExpressionEvaluationContext(); 12978 12979 PopDeclContext(); 12980 PopFunctionScopeInfo(); 12981 12982 if (Initializer != nullptr) { 12983 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 12984 } else if (OmpPrivParm->hasInit()) { 12985 DRD->setInitializer(OmpPrivParm->getInit(), 12986 OmpPrivParm->isDirectInit() 12987 ? OMPDeclareReductionDecl::DirectInit 12988 : OMPDeclareReductionDecl::CopyInit); 12989 } else { 12990 DRD->setInvalidDecl(); 12991 } 12992 } 12993 12994 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 12995 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 12996 for (Decl *D : DeclReductions.get()) { 12997 if (IsValid) { 12998 if (S) 12999 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 13000 /*AddToContext=*/false); 13001 } else { 13002 D->setInvalidDecl(); 13003 } 13004 } 13005 return DeclReductions; 13006 } 13007 13008 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 13009 SourceLocation StartLoc, 13010 SourceLocation LParenLoc, 13011 SourceLocation EndLoc) { 13012 Expr *ValExpr = NumTeams; 13013 Stmt *HelperValStmt = nullptr; 13014 13015 // OpenMP [teams Constrcut, Restrictions] 13016 // The num_teams expression must evaluate to a positive integer value. 13017 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 13018 /*StrictlyPositive=*/true)) 13019 return nullptr; 13020 13021 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 13022 OpenMPDirectiveKind CaptureRegion = 13023 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 13024 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 13025 ValExpr = MakeFullExpr(ValExpr).get(); 13026 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13027 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13028 HelperValStmt = buildPreInits(Context, Captures); 13029 } 13030 13031 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 13032 StartLoc, LParenLoc, EndLoc); 13033 } 13034 13035 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 13036 SourceLocation StartLoc, 13037 SourceLocation LParenLoc, 13038 SourceLocation EndLoc) { 13039 Expr *ValExpr = ThreadLimit; 13040 Stmt *HelperValStmt = nullptr; 13041 13042 // OpenMP [teams Constrcut, Restrictions] 13043 // The thread_limit expression must evaluate to a positive integer value. 13044 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 13045 /*StrictlyPositive=*/true)) 13046 return nullptr; 13047 13048 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 13049 OpenMPDirectiveKind CaptureRegion = 13050 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 13051 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 13052 ValExpr = MakeFullExpr(ValExpr).get(); 13053 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13054 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13055 HelperValStmt = buildPreInits(Context, Captures); 13056 } 13057 13058 return new (Context) OMPThreadLimitClause( 13059 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 13060 } 13061 13062 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 13063 SourceLocation StartLoc, 13064 SourceLocation LParenLoc, 13065 SourceLocation EndLoc) { 13066 Expr *ValExpr = Priority; 13067 13068 // OpenMP [2.9.1, task Constrcut] 13069 // The priority-value is a non-negative numerical scalar expression. 13070 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 13071 /*StrictlyPositive=*/false)) 13072 return nullptr; 13073 13074 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 13075 } 13076 13077 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 13078 SourceLocation StartLoc, 13079 SourceLocation LParenLoc, 13080 SourceLocation EndLoc) { 13081 Expr *ValExpr = Grainsize; 13082 13083 // OpenMP [2.9.2, taskloop Constrcut] 13084 // The parameter of the grainsize clause must be a positive integer 13085 // expression. 13086 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 13087 /*StrictlyPositive=*/true)) 13088 return nullptr; 13089 13090 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 13091 } 13092 13093 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 13094 SourceLocation StartLoc, 13095 SourceLocation LParenLoc, 13096 SourceLocation EndLoc) { 13097 Expr *ValExpr = NumTasks; 13098 13099 // OpenMP [2.9.2, taskloop Constrcut] 13100 // The parameter of the num_tasks clause must be a positive integer 13101 // expression. 13102 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 13103 /*StrictlyPositive=*/true)) 13104 return nullptr; 13105 13106 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 13107 } 13108 13109 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 13110 SourceLocation LParenLoc, 13111 SourceLocation EndLoc) { 13112 // OpenMP [2.13.2, critical construct, Description] 13113 // ... where hint-expression is an integer constant expression that evaluates 13114 // to a valid lock hint. 13115 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 13116 if (HintExpr.isInvalid()) 13117 return nullptr; 13118 return new (Context) 13119 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 13120 } 13121 13122 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 13123 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 13124 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 13125 SourceLocation EndLoc) { 13126 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 13127 std::string Values; 13128 Values += "'"; 13129 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 13130 Values += "'"; 13131 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 13132 << Values << getOpenMPClauseName(OMPC_dist_schedule); 13133 return nullptr; 13134 } 13135 Expr *ValExpr = ChunkSize; 13136 Stmt *HelperValStmt = nullptr; 13137 if (ChunkSize) { 13138 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 13139 !ChunkSize->isInstantiationDependent() && 13140 !ChunkSize->containsUnexpandedParameterPack()) { 13141 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 13142 ExprResult Val = 13143 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 13144 if (Val.isInvalid()) 13145 return nullptr; 13146 13147 ValExpr = Val.get(); 13148 13149 // OpenMP [2.7.1, Restrictions] 13150 // chunk_size must be a loop invariant integer expression with a positive 13151 // value. 13152 llvm::APSInt Result; 13153 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 13154 if (Result.isSigned() && !Result.isStrictlyPositive()) { 13155 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 13156 << "dist_schedule" << ChunkSize->getSourceRange(); 13157 return nullptr; 13158 } 13159 } else if (getOpenMPCaptureRegionForClause( 13160 DSAStack->getCurrentDirective(), OMPC_dist_schedule) != 13161 OMPD_unknown && 13162 !CurContext->isDependentContext()) { 13163 ValExpr = MakeFullExpr(ValExpr).get(); 13164 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13165 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13166 HelperValStmt = buildPreInits(Context, Captures); 13167 } 13168 } 13169 } 13170 13171 return new (Context) 13172 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 13173 Kind, ValExpr, HelperValStmt); 13174 } 13175 13176 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 13177 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 13178 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 13179 SourceLocation KindLoc, SourceLocation EndLoc) { 13180 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 13181 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 13182 std::string Value; 13183 SourceLocation Loc; 13184 Value += "'"; 13185 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 13186 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 13187 OMPC_DEFAULTMAP_MODIFIER_tofrom); 13188 Loc = MLoc; 13189 } else { 13190 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 13191 OMPC_DEFAULTMAP_scalar); 13192 Loc = KindLoc; 13193 } 13194 Value += "'"; 13195 Diag(Loc, diag::err_omp_unexpected_clause_value) 13196 << Value << getOpenMPClauseName(OMPC_defaultmap); 13197 return nullptr; 13198 } 13199 DSAStack->setDefaultDMAToFromScalar(StartLoc); 13200 13201 return new (Context) 13202 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 13203 } 13204 13205 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 13206 DeclContext *CurLexicalContext = getCurLexicalContext(); 13207 if (!CurLexicalContext->isFileContext() && 13208 !CurLexicalContext->isExternCContext() && 13209 !CurLexicalContext->isExternCXXContext() && 13210 !isa<CXXRecordDecl>(CurLexicalContext) && 13211 !isa<ClassTemplateDecl>(CurLexicalContext) && 13212 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 13213 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 13214 Diag(Loc, diag::err_omp_region_not_file_context); 13215 return false; 13216 } 13217 ++DeclareTargetNestingLevel; 13218 return true; 13219 } 13220 13221 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 13222 assert(DeclareTargetNestingLevel > 0 && 13223 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 13224 --DeclareTargetNestingLevel; 13225 } 13226 13227 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 13228 CXXScopeSpec &ScopeSpec, 13229 const DeclarationNameInfo &Id, 13230 OMPDeclareTargetDeclAttr::MapTypeTy MT, 13231 NamedDeclSetType &SameDirectiveDecls) { 13232 LookupResult Lookup(*this, Id, LookupOrdinaryName); 13233 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 13234 13235 if (Lookup.isAmbiguous()) 13236 return; 13237 Lookup.suppressDiagnostics(); 13238 13239 if (!Lookup.isSingleResult()) { 13240 if (TypoCorrection Corrected = 13241 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 13242 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 13243 CTK_ErrorRecovery)) { 13244 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 13245 << Id.getName()); 13246 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 13247 return; 13248 } 13249 13250 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 13251 return; 13252 } 13253 13254 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 13255 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 13256 isa<FunctionTemplateDecl>(ND)) { 13257 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 13258 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 13259 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 13260 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 13261 cast<ValueDecl>(ND)); 13262 if (!Res) { 13263 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 13264 ND->addAttr(A); 13265 if (ASTMutationListener *ML = Context.getASTMutationListener()) 13266 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 13267 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc()); 13268 } else if (*Res != MT) { 13269 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 13270 << Id.getName(); 13271 } 13272 } else { 13273 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 13274 } 13275 } 13276 13277 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 13278 Sema &SemaRef, Decl *D) { 13279 if (!D || !isa<VarDecl>(D)) 13280 return; 13281 auto *VD = cast<VarDecl>(D); 13282 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 13283 return; 13284 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 13285 SemaRef.Diag(SL, diag::note_used_here) << SR; 13286 } 13287 13288 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 13289 Sema &SemaRef, DSAStackTy *Stack, 13290 ValueDecl *VD) { 13291 return VD->hasAttr<OMPDeclareTargetDeclAttr>() || 13292 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 13293 /*FullCheck=*/false); 13294 } 13295 13296 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 13297 SourceLocation IdLoc) { 13298 if (!D || D->isInvalidDecl()) 13299 return; 13300 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 13301 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 13302 if (auto *VD = dyn_cast<VarDecl>(D)) { 13303 // Only global variables can be marked as declare target. 13304 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 13305 !VD->isStaticDataMember()) 13306 return; 13307 // 2.10.6: threadprivate variable cannot appear in a declare target 13308 // directive. 13309 if (DSAStack->isThreadPrivate(VD)) { 13310 Diag(SL, diag::err_omp_threadprivate_in_target); 13311 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 13312 return; 13313 } 13314 } 13315 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 13316 D = FTD->getTemplatedDecl(); 13317 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 13318 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 13319 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 13320 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 13321 assert(IdLoc.isValid() && "Source location is expected"); 13322 Diag(IdLoc, diag::err_omp_function_in_link_clause); 13323 Diag(FD->getLocation(), diag::note_defined_here) << FD; 13324 return; 13325 } 13326 } 13327 if (auto *VD = dyn_cast<ValueDecl>(D)) { 13328 // Problem if any with var declared with incomplete type will be reported 13329 // as normal, so no need to check it here. 13330 if ((E || !VD->getType()->isIncompleteType()) && 13331 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 13332 return; 13333 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 13334 // Checking declaration inside declare target region. 13335 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 13336 isa<FunctionTemplateDecl>(D)) { 13337 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 13338 Context, OMPDeclareTargetDeclAttr::MT_To); 13339 D->addAttr(A); 13340 if (ASTMutationListener *ML = Context.getASTMutationListener()) 13341 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 13342 } 13343 return; 13344 } 13345 } 13346 if (!E) 13347 return; 13348 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 13349 } 13350 13351 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 13352 SourceLocation StartLoc, 13353 SourceLocation LParenLoc, 13354 SourceLocation EndLoc) { 13355 MappableVarListInfo MVLI(VarList); 13356 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 13357 if (MVLI.ProcessedVarList.empty()) 13358 return nullptr; 13359 13360 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 13361 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 13362 MVLI.VarComponents); 13363 } 13364 13365 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 13366 SourceLocation StartLoc, 13367 SourceLocation LParenLoc, 13368 SourceLocation EndLoc) { 13369 MappableVarListInfo MVLI(VarList); 13370 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 13371 if (MVLI.ProcessedVarList.empty()) 13372 return nullptr; 13373 13374 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 13375 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 13376 MVLI.VarComponents); 13377 } 13378 13379 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 13380 SourceLocation StartLoc, 13381 SourceLocation LParenLoc, 13382 SourceLocation EndLoc) { 13383 MappableVarListInfo MVLI(VarList); 13384 SmallVector<Expr *, 8> PrivateCopies; 13385 SmallVector<Expr *, 8> Inits; 13386 13387 for (Expr *RefExpr : VarList) { 13388 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 13389 SourceLocation ELoc; 13390 SourceRange ERange; 13391 Expr *SimpleRefExpr = RefExpr; 13392 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 13393 if (Res.second) { 13394 // It will be analyzed later. 13395 MVLI.ProcessedVarList.push_back(RefExpr); 13396 PrivateCopies.push_back(nullptr); 13397 Inits.push_back(nullptr); 13398 } 13399 ValueDecl *D = Res.first; 13400 if (!D) 13401 continue; 13402 13403 QualType Type = D->getType(); 13404 Type = Type.getNonReferenceType().getUnqualifiedType(); 13405 13406 auto *VD = dyn_cast<VarDecl>(D); 13407 13408 // Item should be a pointer or reference to pointer. 13409 if (!Type->isPointerType()) { 13410 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 13411 << 0 << RefExpr->getSourceRange(); 13412 continue; 13413 } 13414 13415 // Build the private variable and the expression that refers to it. 13416 auto VDPrivate = 13417 buildVarDecl(*this, ELoc, Type, D->getName(), 13418 D->hasAttrs() ? &D->getAttrs() : nullptr, 13419 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 13420 if (VDPrivate->isInvalidDecl()) 13421 continue; 13422 13423 CurContext->addDecl(VDPrivate); 13424 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 13425 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 13426 13427 // Add temporary variable to initialize the private copy of the pointer. 13428 VarDecl *VDInit = 13429 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 13430 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 13431 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 13432 AddInitializerToDecl(VDPrivate, 13433 DefaultLvalueConversion(VDInitRefExpr).get(), 13434 /*DirectInit=*/false); 13435 13436 // If required, build a capture to implement the privatization initialized 13437 // with the current list item value. 13438 DeclRefExpr *Ref = nullptr; 13439 if (!VD) 13440 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 13441 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 13442 PrivateCopies.push_back(VDPrivateRefExpr); 13443 Inits.push_back(VDInitRefExpr); 13444 13445 // We need to add a data sharing attribute for this variable to make sure it 13446 // is correctly captured. A variable that shows up in a use_device_ptr has 13447 // similar properties of a first private variable. 13448 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 13449 13450 // Create a mappable component for the list item. List items in this clause 13451 // only need a component. 13452 MVLI.VarBaseDeclarations.push_back(D); 13453 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 13454 MVLI.VarComponents.back().push_back( 13455 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 13456 } 13457 13458 if (MVLI.ProcessedVarList.empty()) 13459 return nullptr; 13460 13461 return OMPUseDevicePtrClause::Create( 13462 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 13463 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 13464 } 13465 13466 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 13467 SourceLocation StartLoc, 13468 SourceLocation LParenLoc, 13469 SourceLocation EndLoc) { 13470 MappableVarListInfo MVLI(VarList); 13471 for (Expr *RefExpr : VarList) { 13472 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 13473 SourceLocation ELoc; 13474 SourceRange ERange; 13475 Expr *SimpleRefExpr = RefExpr; 13476 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 13477 if (Res.second) { 13478 // It will be analyzed later. 13479 MVLI.ProcessedVarList.push_back(RefExpr); 13480 } 13481 ValueDecl *D = Res.first; 13482 if (!D) 13483 continue; 13484 13485 QualType Type = D->getType(); 13486 // item should be a pointer or array or reference to pointer or array 13487 if (!Type.getNonReferenceType()->isPointerType() && 13488 !Type.getNonReferenceType()->isArrayType()) { 13489 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 13490 << 0 << RefExpr->getSourceRange(); 13491 continue; 13492 } 13493 13494 // Check if the declaration in the clause does not show up in any data 13495 // sharing attribute. 13496 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 13497 if (isOpenMPPrivate(DVar.CKind)) { 13498 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 13499 << getOpenMPClauseName(DVar.CKind) 13500 << getOpenMPClauseName(OMPC_is_device_ptr) 13501 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 13502 reportOriginalDsa(*this, DSAStack, D, DVar); 13503 continue; 13504 } 13505 13506 const Expr *ConflictExpr; 13507 if (DSAStack->checkMappableExprComponentListsForDecl( 13508 D, /*CurrentRegionOnly=*/true, 13509 [&ConflictExpr]( 13510 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 13511 OpenMPClauseKind) -> bool { 13512 ConflictExpr = R.front().getAssociatedExpression(); 13513 return true; 13514 })) { 13515 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 13516 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 13517 << ConflictExpr->getSourceRange(); 13518 continue; 13519 } 13520 13521 // Store the components in the stack so that they can be used to check 13522 // against other clauses later on. 13523 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 13524 DSAStack->addMappableExpressionComponents( 13525 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 13526 13527 // Record the expression we've just processed. 13528 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 13529 13530 // Create a mappable component for the list item. List items in this clause 13531 // only need a component. We use a null declaration to signal fields in 13532 // 'this'. 13533 assert((isa<DeclRefExpr>(SimpleRefExpr) || 13534 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 13535 "Unexpected device pointer expression!"); 13536 MVLI.VarBaseDeclarations.push_back( 13537 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 13538 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 13539 MVLI.VarComponents.back().push_back(MC); 13540 } 13541 13542 if (MVLI.ProcessedVarList.empty()) 13543 return nullptr; 13544 13545 return OMPIsDevicePtrClause::Create( 13546 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 13547 MVLI.VarBaseDeclarations, MVLI.VarComponents); 13548 } 13549