1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// \file 10 /// \brief This file implements semantic analysis for OpenMP directives and 11 /// clauses. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "TreeTransform.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclOpenMP.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/Basic/OpenMPKinds.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Scope.h" 29 #include "clang/Sema/ScopeInfo.h" 30 #include "clang/Sema/SemaInternal.h" 31 #include "llvm/ADT/PointerEmbeddedInt.h" 32 using namespace clang; 33 34 //===----------------------------------------------------------------------===// 35 // Stack of data-sharing attributes for variables 36 //===----------------------------------------------------------------------===// 37 38 static Expr *CheckMapClauseExpressionBase( 39 Sema &SemaRef, Expr *E, 40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 41 OpenMPClauseKind CKind, bool NoDiagnose); 42 43 namespace { 44 /// \brief Default data sharing attributes, which can be applied to directive. 45 enum DefaultDataSharingAttributes { 46 DSA_unspecified = 0, /// \brief Data sharing attribute not specified. 47 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'. 48 DSA_shared = 1 << 1, /// \brief Default data sharing attribute 'shared'. 49 }; 50 51 /// Attributes of the defaultmap clause. 52 enum DefaultMapAttributes { 53 DMA_unspecified, /// Default mapping is not specified. 54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'. 55 }; 56 57 /// \brief Stack for tracking declarations used in OpenMP directives and 58 /// clauses and their data-sharing attributes. 59 class DSAStackTy final { 60 public: 61 struct DSAVarData final { 62 OpenMPDirectiveKind DKind = OMPD_unknown; 63 OpenMPClauseKind CKind = OMPC_unknown; 64 Expr *RefExpr = nullptr; 65 DeclRefExpr *PrivateCopy = nullptr; 66 SourceLocation ImplicitDSALoc; 67 DSAVarData() = default; 68 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr, 69 DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc) 70 : DKind(DKind), CKind(CKind), RefExpr(RefExpr), 71 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {} 72 }; 73 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4> 74 OperatorOffsetTy; 75 76 private: 77 struct DSAInfo final { 78 OpenMPClauseKind Attributes = OMPC_unknown; 79 /// Pointer to a reference expression and a flag which shows that the 80 /// variable is marked as lastprivate(true) or not (false). 81 llvm::PointerIntPair<Expr *, 1, bool> RefExpr; 82 DeclRefExpr *PrivateCopy = nullptr; 83 }; 84 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy; 85 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy; 86 typedef std::pair<unsigned, VarDecl *> LCDeclInfo; 87 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy; 88 /// Struct that associates a component with the clause kind where they are 89 /// found. 90 struct MappedExprComponentTy { 91 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 92 OpenMPClauseKind Kind = OMPC_unknown; 93 }; 94 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy> 95 MappedExprComponentsTy; 96 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>> 97 CriticalsWithHintsTy; 98 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy> 99 DoacrossDependMapTy; 100 struct ReductionData { 101 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType; 102 SourceRange ReductionRange; 103 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 104 ReductionData() = default; 105 void set(BinaryOperatorKind BO, SourceRange RR) { 106 ReductionRange = RR; 107 ReductionOp = BO; 108 } 109 void set(const Expr *RefExpr, SourceRange RR) { 110 ReductionRange = RR; 111 ReductionOp = RefExpr; 112 } 113 }; 114 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy; 115 116 struct SharingMapTy final { 117 DeclSAMapTy SharingMap; 118 DeclReductionMapTy ReductionMap; 119 AlignedMapTy AlignedMap; 120 MappedExprComponentsTy MappedExprComponents; 121 LoopControlVariablesMapTy LCVMap; 122 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 123 SourceLocation DefaultAttrLoc; 124 DefaultMapAttributes DefaultMapAttr = DMA_unspecified; 125 SourceLocation DefaultMapAttrLoc; 126 OpenMPDirectiveKind Directive = OMPD_unknown; 127 DeclarationNameInfo DirectiveName; 128 Scope *CurScope = nullptr; 129 SourceLocation ConstructLoc; 130 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 131 /// get the data (loop counters etc.) about enclosing loop-based construct. 132 /// This data is required during codegen. 133 DoacrossDependMapTy DoacrossDepends; 134 /// \brief first argument (Expr *) contains optional argument of the 135 /// 'ordered' clause, the second one is true if the regions has 'ordered' 136 /// clause, false otherwise. 137 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion; 138 bool NowaitRegion = false; 139 bool CancelRegion = false; 140 unsigned AssociatedLoops = 1; 141 SourceLocation InnerTeamsRegionLoc; 142 /// Reference to the taskgroup task_reduction reference expression. 143 Expr *TaskgroupReductionRef = nullptr; 144 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 145 Scope *CurScope, SourceLocation Loc) 146 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 147 ConstructLoc(Loc) {} 148 SharingMapTy() = default; 149 }; 150 151 typedef SmallVector<SharingMapTy, 4> StackTy; 152 153 /// \brief Stack of used declaration and their data-sharing attributes. 154 DeclSAMapTy Threadprivates; 155 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 156 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 157 /// \brief true, if check for DSA must be from parent directive, false, if 158 /// from current directive. 159 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 160 Sema &SemaRef; 161 bool ForceCapturing = false; 162 CriticalsWithHintsTy Criticals; 163 164 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; 165 166 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D); 167 168 /// \brief Checks if the variable is a local for OpenMP region. 169 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); 170 171 bool isStackEmpty() const { 172 return Stack.empty() || 173 Stack.back().second != CurrentNonCapturingFunctionScope || 174 Stack.back().first.empty(); 175 } 176 177 public: 178 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 179 180 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 181 OpenMPClauseKind getClauseParsingMode() const { 182 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 183 return ClauseKindMode; 184 } 185 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 186 187 bool isForceVarCapturing() const { return ForceCapturing; } 188 void setForceVarCapturing(bool V) { ForceCapturing = V; } 189 190 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 191 Scope *CurScope, SourceLocation Loc) { 192 if (Stack.empty() || 193 Stack.back().second != CurrentNonCapturingFunctionScope) 194 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 195 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 196 Stack.back().first.back().DefaultAttrLoc = Loc; 197 } 198 199 void pop() { 200 assert(!Stack.back().first.empty() && 201 "Data-sharing attributes stack is empty!"); 202 Stack.back().first.pop_back(); 203 } 204 205 /// Start new OpenMP region stack in new non-capturing function. 206 void pushFunction() { 207 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 208 assert(!isa<CapturingScopeInfo>(CurFnScope)); 209 CurrentNonCapturingFunctionScope = CurFnScope; 210 } 211 /// Pop region stack for non-capturing function. 212 void popFunction(const FunctionScopeInfo *OldFSI) { 213 if (!Stack.empty() && Stack.back().second == OldFSI) { 214 assert(Stack.back().first.empty()); 215 Stack.pop_back(); 216 } 217 CurrentNonCapturingFunctionScope = nullptr; 218 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 219 if (!isa<CapturingScopeInfo>(FSI)) { 220 CurrentNonCapturingFunctionScope = FSI; 221 break; 222 } 223 } 224 } 225 226 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) { 227 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint); 228 } 229 const std::pair<OMPCriticalDirective *, llvm::APSInt> 230 getCriticalWithHint(const DeclarationNameInfo &Name) const { 231 auto I = Criticals.find(Name.getAsString()); 232 if (I != Criticals.end()) 233 return I->second; 234 return std::make_pair(nullptr, llvm::APSInt()); 235 } 236 /// \brief If 'aligned' declaration for given variable \a D was not seen yet, 237 /// add it and return NULL; otherwise return previous occurrence's expression 238 /// for diagnostics. 239 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE); 240 241 /// \brief Register specified variable as loop control variable. 242 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture); 243 /// \brief Check if the specified variable is a loop control variable for 244 /// current region. 245 /// \return The index of the loop control variable in the list of associated 246 /// for-loops (from outer to inner). 247 LCDeclInfo isLoopControlVariable(ValueDecl *D); 248 /// \brief Check if the specified variable is a loop control variable for 249 /// parent region. 250 /// \return The index of the loop control variable in the list of associated 251 /// for-loops (from outer to inner). 252 LCDeclInfo isParentLoopControlVariable(ValueDecl *D); 253 /// \brief Get the loop control variable for the I-th loop (or nullptr) in 254 /// parent directive. 255 ValueDecl *getParentLoopControlVariable(unsigned I); 256 257 /// \brief Adds explicit data sharing attribute to the specified declaration. 258 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 259 DeclRefExpr *PrivateCopy = nullptr); 260 261 /// Adds additional information for the reduction items with the reduction id 262 /// represented as an operator. 263 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 264 BinaryOperatorKind BOK); 265 /// Adds additional information for the reduction items with the reduction id 266 /// represented as reduction identifier. 267 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 268 const Expr *ReductionRef); 269 /// Returns the location and reduction operation from the innermost parent 270 /// region for the given \p D. 271 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 272 BinaryOperatorKind &BOK, 273 Expr *&TaskgroupDescriptor); 274 /// Returns the location and reduction operation from the innermost parent 275 /// region for the given \p D. 276 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 277 const Expr *&ReductionRef, 278 Expr *&TaskgroupDescriptor); 279 /// Return reduction reference expression for the current taskgroup. 280 Expr *getTaskgroupReductionRef() const { 281 assert(Stack.back().first.back().Directive == OMPD_taskgroup && 282 "taskgroup reference expression requested for non taskgroup " 283 "directive."); 284 return Stack.back().first.back().TaskgroupReductionRef; 285 } 286 /// Checks if the given \p VD declaration is actually a taskgroup reduction 287 /// descriptor variable at the \p Level of OpenMP regions. 288 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const { 289 return Stack.back().first[Level].TaskgroupReductionRef && 290 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef) 291 ->getDecl() == VD; 292 } 293 294 /// \brief Returns data sharing attributes from top of the stack for the 295 /// specified declaration. 296 DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 297 /// \brief Returns data-sharing attributes for the specified declaration. 298 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent); 299 /// \brief Checks if the specified variables has data-sharing attributes which 300 /// match specified \a CPred predicate in any directive which matches \a DPred 301 /// predicate. 302 DSAVarData hasDSA(ValueDecl *D, 303 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 304 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 305 bool FromParent); 306 /// \brief Checks if the specified variables has data-sharing attributes which 307 /// match specified \a CPred predicate in any innermost directive which 308 /// matches \a DPred predicate. 309 DSAVarData 310 hasInnermostDSA(ValueDecl *D, 311 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 312 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 313 bool FromParent); 314 /// \brief Checks if the specified variables has explicit data-sharing 315 /// attributes which match specified \a CPred predicate at the specified 316 /// OpenMP region. 317 bool hasExplicitDSA(ValueDecl *D, 318 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 319 unsigned Level, bool NotLastprivate = false); 320 321 /// \brief Returns true if the directive at level \Level matches in the 322 /// specified \a DPred predicate. 323 bool hasExplicitDirective( 324 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 325 unsigned Level); 326 327 /// \brief Finds a directive which matches specified \a DPred predicate. 328 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind, 329 const DeclarationNameInfo &, 330 SourceLocation)> &DPred, 331 bool FromParent); 332 333 /// \brief Returns currently analyzed directive. 334 OpenMPDirectiveKind getCurrentDirective() const { 335 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive; 336 } 337 /// \brief Returns directive kind at specified level. 338 OpenMPDirectiveKind getDirective(unsigned Level) const { 339 assert(!isStackEmpty() && "No directive at specified level."); 340 return Stack.back().first[Level].Directive; 341 } 342 /// \brief Returns parent directive. 343 OpenMPDirectiveKind getParentDirective() const { 344 if (isStackEmpty() || Stack.back().first.size() == 1) 345 return OMPD_unknown; 346 return std::next(Stack.back().first.rbegin())->Directive; 347 } 348 349 /// \brief Set default data sharing attribute to none. 350 void setDefaultDSANone(SourceLocation Loc) { 351 assert(!isStackEmpty()); 352 Stack.back().first.back().DefaultAttr = DSA_none; 353 Stack.back().first.back().DefaultAttrLoc = Loc; 354 } 355 /// \brief Set default data sharing attribute to shared. 356 void setDefaultDSAShared(SourceLocation Loc) { 357 assert(!isStackEmpty()); 358 Stack.back().first.back().DefaultAttr = DSA_shared; 359 Stack.back().first.back().DefaultAttrLoc = Loc; 360 } 361 /// Set default data mapping attribute to 'tofrom:scalar'. 362 void setDefaultDMAToFromScalar(SourceLocation Loc) { 363 assert(!isStackEmpty()); 364 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar; 365 Stack.back().first.back().DefaultMapAttrLoc = Loc; 366 } 367 368 DefaultDataSharingAttributes getDefaultDSA() const { 369 return isStackEmpty() ? DSA_unspecified 370 : Stack.back().first.back().DefaultAttr; 371 } 372 SourceLocation getDefaultDSALocation() const { 373 return isStackEmpty() ? SourceLocation() 374 : Stack.back().first.back().DefaultAttrLoc; 375 } 376 DefaultMapAttributes getDefaultDMA() const { 377 return isStackEmpty() ? DMA_unspecified 378 : Stack.back().first.back().DefaultMapAttr; 379 } 380 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const { 381 return Stack.back().first[Level].DefaultMapAttr; 382 } 383 SourceLocation getDefaultDMALocation() const { 384 return isStackEmpty() ? SourceLocation() 385 : Stack.back().first.back().DefaultMapAttrLoc; 386 } 387 388 /// \brief Checks if the specified variable is a threadprivate. 389 bool isThreadPrivate(VarDecl *D) { 390 DSAVarData DVar = getTopDSA(D, false); 391 return isOpenMPThreadPrivate(DVar.CKind); 392 } 393 394 /// \brief Marks current region as ordered (it has an 'ordered' clause). 395 void setOrderedRegion(bool IsOrdered, Expr *Param) { 396 assert(!isStackEmpty()); 397 Stack.back().first.back().OrderedRegion.setInt(IsOrdered); 398 Stack.back().first.back().OrderedRegion.setPointer(Param); 399 } 400 /// \brief Returns true, if parent region is ordered (has associated 401 /// 'ordered' clause), false - otherwise. 402 bool isParentOrderedRegion() const { 403 if (isStackEmpty() || Stack.back().first.size() == 1) 404 return false; 405 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt(); 406 } 407 /// \brief Returns optional parameter for the ordered region. 408 Expr *getParentOrderedRegionParam() const { 409 if (isStackEmpty() || Stack.back().first.size() == 1) 410 return nullptr; 411 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer(); 412 } 413 /// \brief Marks current region as nowait (it has a 'nowait' clause). 414 void setNowaitRegion(bool IsNowait = true) { 415 assert(!isStackEmpty()); 416 Stack.back().first.back().NowaitRegion = IsNowait; 417 } 418 /// \brief Returns true, if parent region is nowait (has associated 419 /// 'nowait' clause), false - otherwise. 420 bool isParentNowaitRegion() const { 421 if (isStackEmpty() || Stack.back().first.size() == 1) 422 return false; 423 return std::next(Stack.back().first.rbegin())->NowaitRegion; 424 } 425 /// \brief Marks parent region as cancel region. 426 void setParentCancelRegion(bool Cancel = true) { 427 if (!isStackEmpty() && Stack.back().first.size() > 1) { 428 auto &StackElemRef = *std::next(Stack.back().first.rbegin()); 429 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel; 430 } 431 } 432 /// \brief Return true if current region has inner cancel construct. 433 bool isCancelRegion() const { 434 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion; 435 } 436 437 /// \brief Set collapse value for the region. 438 void setAssociatedLoops(unsigned Val) { 439 assert(!isStackEmpty()); 440 Stack.back().first.back().AssociatedLoops = Val; 441 } 442 /// \brief Return collapse value for region. 443 unsigned getAssociatedLoops() const { 444 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops; 445 } 446 447 /// \brief Marks current target region as one with closely nested teams 448 /// region. 449 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 450 if (!isStackEmpty() && Stack.back().first.size() > 1) { 451 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc = 452 TeamsRegionLoc; 453 } 454 } 455 /// \brief Returns true, if current region has closely nested teams region. 456 bool hasInnerTeamsRegion() const { 457 return getInnerTeamsRegionLoc().isValid(); 458 } 459 /// \brief Returns location of the nested teams region (if any). 460 SourceLocation getInnerTeamsRegionLoc() const { 461 return isStackEmpty() ? SourceLocation() 462 : Stack.back().first.back().InnerTeamsRegionLoc; 463 } 464 465 Scope *getCurScope() const { 466 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 467 } 468 Scope *getCurScope() { 469 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 470 } 471 SourceLocation getConstructLoc() { 472 return isStackEmpty() ? SourceLocation() 473 : Stack.back().first.back().ConstructLoc; 474 } 475 476 /// Do the check specified in \a Check to all component lists and return true 477 /// if any issue is found. 478 bool checkMappableExprComponentListsForDecl( 479 ValueDecl *VD, bool CurrentRegionOnly, 480 const llvm::function_ref< 481 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 482 OpenMPClauseKind)> &Check) { 483 if (isStackEmpty()) 484 return false; 485 auto SI = Stack.back().first.rbegin(); 486 auto SE = Stack.back().first.rend(); 487 488 if (SI == SE) 489 return false; 490 491 if (CurrentRegionOnly) { 492 SE = std::next(SI); 493 } else { 494 ++SI; 495 } 496 497 for (; SI != SE; ++SI) { 498 auto MI = SI->MappedExprComponents.find(VD); 499 if (MI != SI->MappedExprComponents.end()) 500 for (auto &L : MI->second.Components) 501 if (Check(L, MI->second.Kind)) 502 return true; 503 } 504 return false; 505 } 506 507 /// Do the check specified in \a Check to all component lists at a given level 508 /// and return true if any issue is found. 509 bool checkMappableExprComponentListsForDeclAtLevel( 510 ValueDecl *VD, unsigned Level, 511 const llvm::function_ref< 512 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 513 OpenMPClauseKind)> &Check) { 514 if (isStackEmpty()) 515 return false; 516 517 auto StartI = Stack.back().first.begin(); 518 auto EndI = Stack.back().first.end(); 519 if (std::distance(StartI, EndI) <= (int)Level) 520 return false; 521 std::advance(StartI, Level); 522 523 auto MI = StartI->MappedExprComponents.find(VD); 524 if (MI != StartI->MappedExprComponents.end()) 525 for (auto &L : MI->second.Components) 526 if (Check(L, MI->second.Kind)) 527 return true; 528 return false; 529 } 530 531 /// Create a new mappable expression component list associated with a given 532 /// declaration and initialize it with the provided list of components. 533 void addMappableExpressionComponents( 534 ValueDecl *VD, 535 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 536 OpenMPClauseKind WhereFoundClauseKind) { 537 assert(!isStackEmpty() && 538 "Not expecting to retrieve components from a empty stack!"); 539 auto &MEC = Stack.back().first.back().MappedExprComponents[VD]; 540 // Create new entry and append the new components there. 541 MEC.Components.resize(MEC.Components.size() + 1); 542 MEC.Components.back().append(Components.begin(), Components.end()); 543 MEC.Kind = WhereFoundClauseKind; 544 } 545 546 unsigned getNestingLevel() const { 547 assert(!isStackEmpty()); 548 return Stack.back().first.size() - 1; 549 } 550 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) { 551 assert(!isStackEmpty() && Stack.back().first.size() > 1); 552 auto &StackElem = *std::next(Stack.back().first.rbegin()); 553 assert(isOpenMPWorksharingDirective(StackElem.Directive)); 554 StackElem.DoacrossDepends.insert({C, OpsOffs}); 555 } 556 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 557 getDoacrossDependClauses() const { 558 assert(!isStackEmpty()); 559 auto &StackElem = Stack.back().first.back(); 560 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 561 auto &Ref = StackElem.DoacrossDepends; 562 return llvm::make_range(Ref.begin(), Ref.end()); 563 } 564 return llvm::make_range(StackElem.DoacrossDepends.end(), 565 StackElem.DoacrossDepends.end()); 566 } 567 }; 568 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 569 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || 570 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 571 } 572 } // namespace 573 574 static Expr *getExprAsWritten(Expr *E) { 575 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 576 E = ExprTemp->getSubExpr(); 577 578 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 579 E = MTE->GetTemporaryExpr(); 580 581 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 582 E = Binder->getSubExpr(); 583 584 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 585 E = ICE->getSubExprAsWritten(); 586 return E->IgnoreParens(); 587 } 588 589 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 590 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 591 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 592 D = ME->getMemberDecl(); 593 auto *VD = dyn_cast<VarDecl>(D); 594 auto *FD = dyn_cast<FieldDecl>(D); 595 if (VD != nullptr) { 596 VD = VD->getCanonicalDecl(); 597 D = VD; 598 } else { 599 assert(FD); 600 FD = FD->getCanonicalDecl(); 601 D = FD; 602 } 603 return D; 604 } 605 606 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter, 607 ValueDecl *D) { 608 D = getCanonicalDecl(D); 609 auto *VD = dyn_cast<VarDecl>(D); 610 auto *FD = dyn_cast<FieldDecl>(D); 611 DSAVarData DVar; 612 if (isStackEmpty() || Iter == Stack.back().first.rend()) { 613 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 614 // in a region but not in construct] 615 // File-scope or namespace-scope variables referenced in called routines 616 // in the region are shared unless they appear in a threadprivate 617 // directive. 618 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 619 DVar.CKind = OMPC_shared; 620 621 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 622 // in a region but not in construct] 623 // Variables with static storage duration that are declared in called 624 // routines in the region are shared. 625 if (VD && VD->hasGlobalStorage()) 626 DVar.CKind = OMPC_shared; 627 628 // Non-static data members are shared by default. 629 if (FD) 630 DVar.CKind = OMPC_shared; 631 632 return DVar; 633 } 634 635 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 636 // in a Construct, C/C++, predetermined, p.1] 637 // Variables with automatic storage duration that are declared in a scope 638 // inside the construct are private. 639 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 640 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 641 DVar.CKind = OMPC_private; 642 return DVar; 643 } 644 645 DVar.DKind = Iter->Directive; 646 // Explicitly specified attributes and local variables with predetermined 647 // attributes. 648 if (Iter->SharingMap.count(D)) { 649 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer(); 650 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy; 651 DVar.CKind = Iter->SharingMap[D].Attributes; 652 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 653 return DVar; 654 } 655 656 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 657 // in a Construct, C/C++, implicitly determined, p.1] 658 // In a parallel or task construct, the data-sharing attributes of these 659 // variables are determined by the default clause, if present. 660 switch (Iter->DefaultAttr) { 661 case DSA_shared: 662 DVar.CKind = OMPC_shared; 663 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 664 return DVar; 665 case DSA_none: 666 return DVar; 667 case DSA_unspecified: 668 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 669 // in a Construct, implicitly determined, p.2] 670 // In a parallel construct, if no default clause is present, these 671 // variables are shared. 672 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 673 if (isOpenMPParallelDirective(DVar.DKind) || 674 isOpenMPTeamsDirective(DVar.DKind)) { 675 DVar.CKind = OMPC_shared; 676 return DVar; 677 } 678 679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 680 // in a Construct, implicitly determined, p.4] 681 // In a task construct, if no default clause is present, a variable that in 682 // the enclosing context is determined to be shared by all implicit tasks 683 // bound to the current team is shared. 684 if (isOpenMPTaskingDirective(DVar.DKind)) { 685 DSAVarData DVarTemp; 686 auto I = Iter, E = Stack.back().first.rend(); 687 do { 688 ++I; 689 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 690 // Referenced in a Construct, implicitly determined, p.6] 691 // In a task construct, if no default clause is present, a variable 692 // whose data-sharing attribute is not determined by the rules above is 693 // firstprivate. 694 DVarTemp = getDSA(I, D); 695 if (DVarTemp.CKind != OMPC_shared) { 696 DVar.RefExpr = nullptr; 697 DVar.CKind = OMPC_firstprivate; 698 return DVar; 699 } 700 } while (I != E && !isParallelOrTaskRegion(I->Directive)); 701 DVar.CKind = 702 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 703 return DVar; 704 } 705 } 706 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 707 // in a Construct, implicitly determined, p.3] 708 // For constructs other than task, if no default clause is present, these 709 // variables inherit their data-sharing attributes from the enclosing 710 // context. 711 return getDSA(++Iter, D); 712 } 713 714 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) { 715 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 716 D = getCanonicalDecl(D); 717 auto &StackElem = Stack.back().first.back(); 718 auto It = StackElem.AlignedMap.find(D); 719 if (It == StackElem.AlignedMap.end()) { 720 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 721 StackElem.AlignedMap[D] = NewDE; 722 return nullptr; 723 } else { 724 assert(It->second && "Unexpected nullptr expr in the aligned map"); 725 return It->second; 726 } 727 return nullptr; 728 } 729 730 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) { 731 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 732 D = getCanonicalDecl(D); 733 auto &StackElem = Stack.back().first.back(); 734 StackElem.LCVMap.insert( 735 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)}); 736 } 737 738 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) { 739 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 740 D = getCanonicalDecl(D); 741 auto &StackElem = Stack.back().first.back(); 742 auto It = StackElem.LCVMap.find(D); 743 if (It != StackElem.LCVMap.end()) 744 return It->second; 745 return {0, nullptr}; 746 } 747 748 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) { 749 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 750 "Data-sharing attributes stack is empty"); 751 D = getCanonicalDecl(D); 752 auto &StackElem = *std::next(Stack.back().first.rbegin()); 753 auto It = StackElem.LCVMap.find(D); 754 if (It != StackElem.LCVMap.end()) 755 return It->second; 756 return {0, nullptr}; 757 } 758 759 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) { 760 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 761 "Data-sharing attributes stack is empty"); 762 auto &StackElem = *std::next(Stack.back().first.rbegin()); 763 if (StackElem.LCVMap.size() < I) 764 return nullptr; 765 for (auto &Pair : StackElem.LCVMap) 766 if (Pair.second.first == I) 767 return Pair.first; 768 return nullptr; 769 } 770 771 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 772 DeclRefExpr *PrivateCopy) { 773 D = getCanonicalDecl(D); 774 if (A == OMPC_threadprivate) { 775 auto &Data = Threadprivates[D]; 776 Data.Attributes = A; 777 Data.RefExpr.setPointer(E); 778 Data.PrivateCopy = nullptr; 779 } else { 780 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 781 auto &Data = Stack.back().first.back().SharingMap[D]; 782 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 783 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 784 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 785 (isLoopControlVariable(D).first && A == OMPC_private)); 786 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 787 Data.RefExpr.setInt(/*IntVal=*/true); 788 return; 789 } 790 const bool IsLastprivate = 791 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 792 Data.Attributes = A; 793 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 794 Data.PrivateCopy = PrivateCopy; 795 if (PrivateCopy) { 796 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()]; 797 Data.Attributes = A; 798 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 799 Data.PrivateCopy = nullptr; 800 } 801 } 802 } 803 804 /// \brief Build a variable declaration for OpenMP loop iteration variable. 805 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 806 StringRef Name, const AttrVec *Attrs = nullptr) { 807 DeclContext *DC = SemaRef.CurContext; 808 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 809 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 810 VarDecl *Decl = 811 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 812 if (Attrs) { 813 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 814 I != E; ++I) 815 Decl->addAttr(*I); 816 } 817 Decl->setImplicit(); 818 return Decl; 819 } 820 821 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 822 SourceLocation Loc, 823 bool RefersToCapture = false) { 824 D->setReferenced(); 825 D->markUsed(S.Context); 826 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 827 SourceLocation(), D, RefersToCapture, Loc, Ty, 828 VK_LValue); 829 } 830 831 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 832 BinaryOperatorKind BOK) { 833 D = getCanonicalDecl(D); 834 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 835 assert( 836 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 837 "Additional reduction info may be specified only for reduction items."); 838 auto &ReductionData = Stack.back().first.back().ReductionMap[D]; 839 assert(ReductionData.ReductionRange.isInvalid() && 840 Stack.back().first.back().Directive == OMPD_taskgroup && 841 "Additional reduction info may be specified only once for reduction " 842 "items."); 843 ReductionData.set(BOK, SR); 844 Expr *&TaskgroupReductionRef = 845 Stack.back().first.back().TaskgroupReductionRef; 846 if (!TaskgroupReductionRef) { 847 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), 848 SemaRef.Context.VoidPtrTy, ".task_red."); 849 TaskgroupReductionRef = 850 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 851 } 852 } 853 854 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 855 const Expr *ReductionRef) { 856 D = getCanonicalDecl(D); 857 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 858 assert( 859 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 860 "Additional reduction info may be specified only for reduction items."); 861 auto &ReductionData = Stack.back().first.back().ReductionMap[D]; 862 assert(ReductionData.ReductionRange.isInvalid() && 863 Stack.back().first.back().Directive == OMPD_taskgroup && 864 "Additional reduction info may be specified only once for reduction " 865 "items."); 866 ReductionData.set(ReductionRef, SR); 867 Expr *&TaskgroupReductionRef = 868 Stack.back().first.back().TaskgroupReductionRef; 869 if (!TaskgroupReductionRef) { 870 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy, 871 ".task_red."); 872 TaskgroupReductionRef = 873 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 874 } 875 } 876 877 DSAStackTy::DSAVarData 878 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 879 BinaryOperatorKind &BOK, 880 Expr *&TaskgroupDescriptor) { 881 D = getCanonicalDecl(D); 882 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 883 if (Stack.back().first.empty()) 884 return DSAVarData(); 885 for (auto I = std::next(Stack.back().first.rbegin(), 1), 886 E = Stack.back().first.rend(); 887 I != E; std::advance(I, 1)) { 888 auto &Data = I->SharingMap[D]; 889 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 890 continue; 891 auto &ReductionData = I->ReductionMap[D]; 892 if (!ReductionData.ReductionOp || 893 ReductionData.ReductionOp.is<const Expr *>()) 894 return DSAVarData(); 895 SR = ReductionData.ReductionRange; 896 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 897 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 898 "expression for the descriptor is not " 899 "set."); 900 TaskgroupDescriptor = I->TaskgroupReductionRef; 901 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 902 Data.PrivateCopy, I->DefaultAttrLoc); 903 } 904 return DSAVarData(); 905 } 906 907 DSAStackTy::DSAVarData 908 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 909 const Expr *&ReductionRef, 910 Expr *&TaskgroupDescriptor) { 911 D = getCanonicalDecl(D); 912 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 913 if (Stack.back().first.empty()) 914 return DSAVarData(); 915 for (auto I = std::next(Stack.back().first.rbegin(), 1), 916 E = Stack.back().first.rend(); 917 I != E; std::advance(I, 1)) { 918 auto &Data = I->SharingMap[D]; 919 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 920 continue; 921 auto &ReductionData = I->ReductionMap[D]; 922 if (!ReductionData.ReductionOp || 923 !ReductionData.ReductionOp.is<const Expr *>()) 924 return DSAVarData(); 925 SR = ReductionData.ReductionRange; 926 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 927 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 928 "expression for the descriptor is not " 929 "set."); 930 TaskgroupDescriptor = I->TaskgroupReductionRef; 931 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 932 Data.PrivateCopy, I->DefaultAttrLoc); 933 } 934 return DSAVarData(); 935 } 936 937 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 938 D = D->getCanonicalDecl(); 939 if (!isStackEmpty() && Stack.back().first.size() > 1) { 940 reverse_iterator I = Iter, E = Stack.back().first.rend(); 941 Scope *TopScope = nullptr; 942 while (I != E && !isParallelOrTaskRegion(I->Directive)) 943 ++I; 944 if (I == E) 945 return false; 946 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 947 Scope *CurScope = getCurScope(); 948 while (CurScope != TopScope && !CurScope->isDeclScope(D)) 949 CurScope = CurScope->getParent(); 950 return CurScope != TopScope; 951 } 952 return false; 953 } 954 955 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) { 956 D = getCanonicalDecl(D); 957 DSAVarData DVar; 958 959 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 960 // in a Construct, C/C++, predetermined, p.1] 961 // Variables appearing in threadprivate directives are threadprivate. 962 auto *VD = dyn_cast<VarDecl>(D); 963 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 964 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 965 SemaRef.getLangOpts().OpenMPUseTLS && 966 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 967 (VD && VD->getStorageClass() == SC_Register && 968 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 969 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 970 D->getLocation()), 971 OMPC_threadprivate); 972 } 973 auto TI = Threadprivates.find(D); 974 if (TI != Threadprivates.end()) { 975 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 976 DVar.CKind = OMPC_threadprivate; 977 return DVar; 978 } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 979 DVar.RefExpr = buildDeclRefExpr( 980 SemaRef, VD, D->getType().getNonReferenceType(), 981 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 982 DVar.CKind = OMPC_threadprivate; 983 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 984 } 985 986 if (isStackEmpty()) 987 // Not in OpenMP execution region and top scope was already checked. 988 return DVar; 989 990 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 991 // in a Construct, C/C++, predetermined, p.4] 992 // Static data members are shared. 993 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 994 // in a Construct, C/C++, predetermined, p.7] 995 // Variables with static storage duration that are declared in a scope 996 // inside the construct are shared. 997 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; 998 if (VD && VD->isStaticDataMember()) { 999 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 1000 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1001 return DVar; 1002 1003 DVar.CKind = OMPC_shared; 1004 return DVar; 1005 } 1006 1007 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 1008 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 1009 Type = SemaRef.getASTContext().getBaseElementType(Type); 1010 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1011 // in a Construct, C/C++, predetermined, p.6] 1012 // Variables with const qualified type having no mutable member are 1013 // shared. 1014 CXXRecordDecl *RD = 1015 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 1016 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1017 if (auto *CTD = CTSD->getSpecializedTemplate()) 1018 RD = CTD->getTemplatedDecl(); 1019 if (IsConstant && 1020 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && 1021 RD->hasMutableFields())) { 1022 // Variables with const-qualified type having no mutable member may be 1023 // listed in a firstprivate clause, even if they are static data members. 1024 DSAVarData DVarTemp = hasDSA( 1025 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, 1026 MatchesAlways, FromParent); 1027 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 1028 return DVar; 1029 1030 DVar.CKind = OMPC_shared; 1031 return DVar; 1032 } 1033 1034 // Explicitly specified attributes and local variables with predetermined 1035 // attributes. 1036 auto I = Stack.back().first.rbegin(); 1037 auto EndI = Stack.back().first.rend(); 1038 if (FromParent && I != EndI) 1039 std::advance(I, 1); 1040 if (I->SharingMap.count(D)) { 1041 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); 1042 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; 1043 DVar.CKind = I->SharingMap[D].Attributes; 1044 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1045 DVar.DKind = I->Directive; 1046 } 1047 1048 return DVar; 1049 } 1050 1051 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1052 bool FromParent) { 1053 if (isStackEmpty()) { 1054 StackTy::reverse_iterator I; 1055 return getDSA(I, D); 1056 } 1057 D = getCanonicalDecl(D); 1058 auto StartI = Stack.back().first.rbegin(); 1059 auto EndI = Stack.back().first.rend(); 1060 if (FromParent && StartI != EndI) 1061 std::advance(StartI, 1); 1062 return getDSA(StartI, D); 1063 } 1064 1065 DSAStackTy::DSAVarData 1066 DSAStackTy::hasDSA(ValueDecl *D, 1067 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1068 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1069 bool FromParent) { 1070 if (isStackEmpty()) 1071 return {}; 1072 D = getCanonicalDecl(D); 1073 auto I = Stack.back().first.rbegin(); 1074 auto EndI = Stack.back().first.rend(); 1075 if (FromParent && I != EndI) 1076 std::advance(I, 1); 1077 for (; I != EndI; std::advance(I, 1)) { 1078 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 1079 continue; 1080 auto NewI = I; 1081 DSAVarData DVar = getDSA(NewI, D); 1082 if (I == NewI && CPred(DVar.CKind)) 1083 return DVar; 1084 } 1085 return {}; 1086 } 1087 1088 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1089 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1090 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1091 bool FromParent) { 1092 if (isStackEmpty()) 1093 return {}; 1094 D = getCanonicalDecl(D); 1095 auto StartI = Stack.back().first.rbegin(); 1096 auto EndI = Stack.back().first.rend(); 1097 if (FromParent && StartI != EndI) 1098 std::advance(StartI, 1); 1099 if (StartI == EndI || !DPred(StartI->Directive)) 1100 return {}; 1101 auto NewI = StartI; 1102 DSAVarData DVar = getDSA(NewI, D); 1103 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); 1104 } 1105 1106 bool DSAStackTy::hasExplicitDSA( 1107 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1108 unsigned Level, bool NotLastprivate) { 1109 if (isStackEmpty()) 1110 return false; 1111 D = getCanonicalDecl(D); 1112 auto StartI = Stack.back().first.begin(); 1113 auto EndI = Stack.back().first.end(); 1114 if (std::distance(StartI, EndI) <= (int)Level) 1115 return false; 1116 std::advance(StartI, Level); 1117 return (StartI->SharingMap.count(D) > 0) && 1118 StartI->SharingMap[D].RefExpr.getPointer() && 1119 CPred(StartI->SharingMap[D].Attributes) && 1120 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt()); 1121 } 1122 1123 bool DSAStackTy::hasExplicitDirective( 1124 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1125 unsigned Level) { 1126 if (isStackEmpty()) 1127 return false; 1128 auto StartI = Stack.back().first.begin(); 1129 auto EndI = Stack.back().first.end(); 1130 if (std::distance(StartI, EndI) <= (int)Level) 1131 return false; 1132 std::advance(StartI, Level); 1133 return DPred(StartI->Directive); 1134 } 1135 1136 bool DSAStackTy::hasDirective( 1137 const llvm::function_ref<bool(OpenMPDirectiveKind, 1138 const DeclarationNameInfo &, SourceLocation)> 1139 &DPred, 1140 bool FromParent) { 1141 // We look only in the enclosing region. 1142 if (isStackEmpty()) 1143 return false; 1144 auto StartI = std::next(Stack.back().first.rbegin()); 1145 auto EndI = Stack.back().first.rend(); 1146 if (FromParent && StartI != EndI) 1147 StartI = std::next(StartI); 1148 for (auto I = StartI, EE = EndI; I != EE; ++I) { 1149 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1150 return true; 1151 } 1152 return false; 1153 } 1154 1155 void Sema::InitDataSharingAttributesStack() { 1156 VarDataSharingAttributesStack = new DSAStackTy(*this); 1157 } 1158 1159 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1160 1161 void Sema::pushOpenMPFunctionRegion() { 1162 DSAStack->pushFunction(); 1163 } 1164 1165 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1166 DSAStack->popFunction(OldFSI); 1167 } 1168 1169 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { 1170 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1171 1172 auto &Ctx = getASTContext(); 1173 bool IsByRef = true; 1174 1175 // Find the directive that is associated with the provided scope. 1176 D = cast<ValueDecl>(D->getCanonicalDecl()); 1177 auto Ty = D->getType(); 1178 1179 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1180 // This table summarizes how a given variable should be passed to the device 1181 // given its type and the clauses where it appears. This table is based on 1182 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1183 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1184 // 1185 // ========================================================================= 1186 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1187 // | |(tofrom:scalar)| | pvt | | | | 1188 // ========================================================================= 1189 // | scl | | | | - | | bycopy| 1190 // | scl | | - | x | - | - | bycopy| 1191 // | scl | | x | - | - | - | null | 1192 // | scl | x | | | - | | byref | 1193 // | scl | x | - | x | - | - | bycopy| 1194 // | scl | x | x | - | - | - | null | 1195 // | scl | | - | - | - | x | byref | 1196 // | scl | x | - | - | - | x | byref | 1197 // 1198 // | agg | n.a. | | | - | | byref | 1199 // | agg | n.a. | - | x | - | - | byref | 1200 // | agg | n.a. | x | - | - | - | null | 1201 // | agg | n.a. | - | - | - | x | byref | 1202 // | agg | n.a. | - | - | - | x[] | byref | 1203 // 1204 // | ptr | n.a. | | | - | | bycopy| 1205 // | ptr | n.a. | - | x | - | - | bycopy| 1206 // | ptr | n.a. | x | - | - | - | null | 1207 // | ptr | n.a. | - | - | - | x | byref | 1208 // | ptr | n.a. | - | - | - | x[] | bycopy| 1209 // | ptr | n.a. | - | - | x | | bycopy| 1210 // | ptr | n.a. | - | - | x | x | bycopy| 1211 // | ptr | n.a. | - | - | x | x[] | bycopy| 1212 // ========================================================================= 1213 // Legend: 1214 // scl - scalar 1215 // ptr - pointer 1216 // agg - aggregate 1217 // x - applies 1218 // - - invalid in this combination 1219 // [] - mapped with an array section 1220 // byref - should be mapped by reference 1221 // byval - should be mapped by value 1222 // null - initialize a local variable to null on the device 1223 // 1224 // Observations: 1225 // - All scalar declarations that show up in a map clause have to be passed 1226 // by reference, because they may have been mapped in the enclosing data 1227 // environment. 1228 // - If the scalar value does not fit the size of uintptr, it has to be 1229 // passed by reference, regardless the result in the table above. 1230 // - For pointers mapped by value that have either an implicit map or an 1231 // array section, the runtime library may pass the NULL value to the 1232 // device instead of the value passed to it by the compiler. 1233 1234 if (Ty->isReferenceType()) 1235 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1236 1237 // Locate map clauses and see if the variable being captured is referred to 1238 // in any of those clauses. Here we only care about variables, not fields, 1239 // because fields are part of aggregates. 1240 bool IsVariableUsedInMapClause = false; 1241 bool IsVariableAssociatedWithSection = false; 1242 1243 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1244 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 1245 MapExprComponents, 1246 OpenMPClauseKind WhereFoundClauseKind) { 1247 // Only the map clause information influences how a variable is 1248 // captured. E.g. is_device_ptr does not require changing the default 1249 // behavior. 1250 if (WhereFoundClauseKind != OMPC_map) 1251 return false; 1252 1253 auto EI = MapExprComponents.rbegin(); 1254 auto EE = MapExprComponents.rend(); 1255 1256 assert(EI != EE && "Invalid map expression!"); 1257 1258 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1259 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1260 1261 ++EI; 1262 if (EI == EE) 1263 return false; 1264 1265 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1266 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1267 isa<MemberExpr>(EI->getAssociatedExpression())) { 1268 IsVariableAssociatedWithSection = true; 1269 // There is nothing more we need to know about this variable. 1270 return true; 1271 } 1272 1273 // Keep looking for more map info. 1274 return false; 1275 }); 1276 1277 if (IsVariableUsedInMapClause) { 1278 // If variable is identified in a map clause it is always captured by 1279 // reference except if it is a pointer that is dereferenced somehow. 1280 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1281 } else { 1282 // By default, all the data that has a scalar type is mapped by copy 1283 // (except for reduction variables). 1284 IsByRef = 1285 !Ty->isScalarType() || 1286 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar || 1287 DSAStack->hasExplicitDSA( 1288 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level); 1289 } 1290 } 1291 1292 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1293 IsByRef = 1294 !DSAStack->hasExplicitDSA( 1295 D, 1296 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1297 Level, /*NotLastprivate=*/true) && 1298 // If the variable is artificial and must be captured by value - try to 1299 // capture by value. 1300 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 1301 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()); 1302 } 1303 1304 // When passing data by copy, we need to make sure it fits the uintptr size 1305 // and alignment, because the runtime library only deals with uintptr types. 1306 // If it does not fit the uintptr size, we need to pass the data by reference 1307 // instead. 1308 if (!IsByRef && 1309 (Ctx.getTypeSizeInChars(Ty) > 1310 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1311 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1312 IsByRef = true; 1313 } 1314 1315 return IsByRef; 1316 } 1317 1318 unsigned Sema::getOpenMPNestingLevel() const { 1319 assert(getLangOpts().OpenMP); 1320 return DSAStack->getNestingLevel(); 1321 } 1322 1323 bool Sema::isInOpenMPTargetExecutionDirective() const { 1324 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 1325 !DSAStack->isClauseParsingMode()) || 1326 DSAStack->hasDirective( 1327 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1328 SourceLocation) -> bool { 1329 return isOpenMPTargetExecutionDirective(K); 1330 }, 1331 false); 1332 } 1333 1334 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { 1335 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1336 D = getCanonicalDecl(D); 1337 1338 // If we are attempting to capture a global variable in a directive with 1339 // 'target' we return true so that this global is also mapped to the device. 1340 // 1341 // FIXME: If the declaration is enclosed in a 'declare target' directive, 1342 // then it should not be captured. Therefore, an extra check has to be 1343 // inserted here once support for 'declare target' is added. 1344 // 1345 auto *VD = dyn_cast<VarDecl>(D); 1346 if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective()) 1347 return VD; 1348 1349 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1350 (!DSAStack->isClauseParsingMode() || 1351 DSAStack->getParentDirective() != OMPD_unknown)) { 1352 auto &&Info = DSAStack->isLoopControlVariable(D); 1353 if (Info.first || 1354 (VD && VD->hasLocalStorage() && 1355 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 1356 (VD && DSAStack->isForceVarCapturing())) 1357 return VD ? VD : Info.second; 1358 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1359 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1360 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1361 DVarPrivate = DSAStack->hasDSA( 1362 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 1363 DSAStack->isClauseParsingMode()); 1364 if (DVarPrivate.CKind != OMPC_unknown) 1365 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1366 } 1367 return nullptr; 1368 } 1369 1370 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 1371 unsigned Level) const { 1372 SmallVector<OpenMPDirectiveKind, 4> Regions; 1373 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 1374 FunctionScopesIndex -= Regions.size(); 1375 } 1376 1377 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { 1378 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1379 return DSAStack->hasExplicitDSA( 1380 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, 1381 Level) || 1382 (DSAStack->isClauseParsingMode() && 1383 DSAStack->getClauseParsingMode() == OMPC_private) || 1384 // Consider taskgroup reduction descriptor variable a private to avoid 1385 // possible capture in the region. 1386 (DSAStack->hasExplicitDirective( 1387 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; }, 1388 Level) && 1389 DSAStack->isTaskgroupReductionRef(D, Level)); 1390 } 1391 1392 void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) { 1393 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1394 D = getCanonicalDecl(D); 1395 OpenMPClauseKind OMPC = OMPC_unknown; 1396 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 1397 const unsigned NewLevel = I - 1; 1398 if (DSAStack->hasExplicitDSA(D, 1399 [&OMPC](const OpenMPClauseKind K) { 1400 if (isOpenMPPrivate(K)) { 1401 OMPC = K; 1402 return true; 1403 } 1404 return false; 1405 }, 1406 NewLevel)) 1407 break; 1408 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1409 D, NewLevel, 1410 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 1411 OpenMPClauseKind) { return true; })) { 1412 OMPC = OMPC_map; 1413 break; 1414 } 1415 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1416 NewLevel)) { 1417 OMPC = OMPC_firstprivate; 1418 break; 1419 } 1420 } 1421 if (OMPC != OMPC_unknown) 1422 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC)); 1423 } 1424 1425 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { 1426 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1427 // Return true if the current level is no longer enclosed in a target region. 1428 1429 auto *VD = dyn_cast<VarDecl>(D); 1430 return VD && !VD->hasLocalStorage() && 1431 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1432 Level); 1433 } 1434 1435 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1436 1437 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1438 const DeclarationNameInfo &DirName, 1439 Scope *CurScope, SourceLocation Loc) { 1440 DSAStack->push(DKind, DirName, CurScope, Loc); 1441 PushExpressionEvaluationContext( 1442 ExpressionEvaluationContext::PotentiallyEvaluated); 1443 } 1444 1445 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1446 DSAStack->setClauseParsingMode(K); 1447 } 1448 1449 void Sema::EndOpenMPClause() { 1450 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1451 } 1452 1453 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1454 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1455 // A variable of class type (or array thereof) that appears in a lastprivate 1456 // clause requires an accessible, unambiguous default constructor for the 1457 // class type, unless the list item is also specified in a firstprivate 1458 // clause. 1459 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1460 for (auto *C : D->clauses()) { 1461 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1462 SmallVector<Expr *, 8> PrivateCopies; 1463 for (auto *DE : Clause->varlists()) { 1464 if (DE->isValueDependent() || DE->isTypeDependent()) { 1465 PrivateCopies.push_back(nullptr); 1466 continue; 1467 } 1468 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1469 VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1470 QualType Type = VD->getType().getNonReferenceType(); 1471 auto DVar = DSAStack->getTopDSA(VD, false); 1472 if (DVar.CKind == OMPC_lastprivate) { 1473 // Generate helper private variable and initialize it with the 1474 // default value. The address of the original variable is replaced 1475 // by the address of the new private variable in CodeGen. This new 1476 // variable is not added to IdResolver, so the code in the OpenMP 1477 // region uses original variable for proper diagnostics. 1478 auto *VDPrivate = buildVarDecl( 1479 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1480 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); 1481 ActOnUninitializedDecl(VDPrivate); 1482 if (VDPrivate->isInvalidDecl()) 1483 continue; 1484 PrivateCopies.push_back(buildDeclRefExpr( 1485 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1486 } else { 1487 // The variable is also a firstprivate, so initialization sequence 1488 // for private copy is generated already. 1489 PrivateCopies.push_back(nullptr); 1490 } 1491 } 1492 // Set initializers to private copies if no errors were found. 1493 if (PrivateCopies.size() == Clause->varlist_size()) 1494 Clause->setPrivateCopies(PrivateCopies); 1495 } 1496 } 1497 } 1498 1499 DSAStack->pop(); 1500 DiscardCleanupsInEvaluationContext(); 1501 PopExpressionEvaluationContext(); 1502 } 1503 1504 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1505 Expr *NumIterations, Sema &SemaRef, 1506 Scope *S, DSAStackTy *Stack); 1507 1508 namespace { 1509 1510 class VarDeclFilterCCC : public CorrectionCandidateCallback { 1511 private: 1512 Sema &SemaRef; 1513 1514 public: 1515 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1516 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1517 NamedDecl *ND = Candidate.getCorrectionDecl(); 1518 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1519 return VD->hasGlobalStorage() && 1520 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1521 SemaRef.getCurScope()); 1522 } 1523 return false; 1524 } 1525 }; 1526 1527 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { 1528 private: 1529 Sema &SemaRef; 1530 1531 public: 1532 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1533 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1534 NamedDecl *ND = Candidate.getCorrectionDecl(); 1535 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) { 1536 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1537 SemaRef.getCurScope()); 1538 } 1539 return false; 1540 } 1541 }; 1542 1543 } // namespace 1544 1545 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1546 CXXScopeSpec &ScopeSpec, 1547 const DeclarationNameInfo &Id) { 1548 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1549 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1550 1551 if (Lookup.isAmbiguous()) 1552 return ExprError(); 1553 1554 VarDecl *VD; 1555 if (!Lookup.isSingleResult()) { 1556 if (TypoCorrection Corrected = CorrectTypo( 1557 Id, LookupOrdinaryName, CurScope, nullptr, 1558 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1559 diagnoseTypo(Corrected, 1560 PDiag(Lookup.empty() 1561 ? diag::err_undeclared_var_use_suggest 1562 : diag::err_omp_expected_var_arg_suggest) 1563 << Id.getName()); 1564 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1565 } else { 1566 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1567 : diag::err_omp_expected_var_arg) 1568 << Id.getName(); 1569 return ExprError(); 1570 } 1571 } else { 1572 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1573 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1574 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1575 return ExprError(); 1576 } 1577 } 1578 Lookup.suppressDiagnostics(); 1579 1580 // OpenMP [2.9.2, Syntax, C/C++] 1581 // Variables must be file-scope, namespace-scope, or static block-scope. 1582 if (!VD->hasGlobalStorage()) { 1583 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1584 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1585 bool IsDecl = 1586 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1587 Diag(VD->getLocation(), 1588 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1589 << VD; 1590 return ExprError(); 1591 } 1592 1593 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1594 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 1595 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1596 // A threadprivate directive for file-scope variables must appear outside 1597 // any definition or declaration. 1598 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1599 !getCurLexicalContext()->isTranslationUnit()) { 1600 Diag(Id.getLoc(), diag::err_omp_var_scope) 1601 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1602 bool IsDecl = 1603 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1604 Diag(VD->getLocation(), 1605 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1606 << VD; 1607 return ExprError(); 1608 } 1609 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1610 // A threadprivate directive for static class member variables must appear 1611 // in the class definition, in the same scope in which the member 1612 // variables are declared. 1613 if (CanonicalVD->isStaticDataMember() && 1614 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1615 Diag(Id.getLoc(), diag::err_omp_var_scope) 1616 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1617 bool IsDecl = 1618 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1619 Diag(VD->getLocation(), 1620 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1621 << VD; 1622 return ExprError(); 1623 } 1624 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1625 // A threadprivate directive for namespace-scope variables must appear 1626 // outside any definition or declaration other than the namespace 1627 // definition itself. 1628 if (CanonicalVD->getDeclContext()->isNamespace() && 1629 (!getCurLexicalContext()->isFileContext() || 1630 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1631 Diag(Id.getLoc(), diag::err_omp_var_scope) 1632 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1633 bool IsDecl = 1634 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1635 Diag(VD->getLocation(), 1636 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1637 << VD; 1638 return ExprError(); 1639 } 1640 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1641 // A threadprivate directive for static block-scope variables must appear 1642 // in the scope of the variable and not in a nested scope. 1643 if (CanonicalVD->isStaticLocal() && CurScope && 1644 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1645 Diag(Id.getLoc(), diag::err_omp_var_scope) 1646 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1647 bool IsDecl = 1648 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1649 Diag(VD->getLocation(), 1650 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1651 << VD; 1652 return ExprError(); 1653 } 1654 1655 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1656 // A threadprivate directive must lexically precede all references to any 1657 // of the variables in its list. 1658 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1659 Diag(Id.getLoc(), diag::err_omp_var_used) 1660 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1661 return ExprError(); 1662 } 1663 1664 QualType ExprType = VD->getType().getNonReferenceType(); 1665 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1666 SourceLocation(), VD, 1667 /*RefersToEnclosingVariableOrCapture=*/false, 1668 Id.getLoc(), ExprType, VK_LValue); 1669 } 1670 1671 Sema::DeclGroupPtrTy 1672 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1673 ArrayRef<Expr *> VarList) { 1674 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1675 CurContext->addDecl(D); 1676 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1677 } 1678 return nullptr; 1679 } 1680 1681 namespace { 1682 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1683 Sema &SemaRef; 1684 1685 public: 1686 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1687 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1688 if (VD->hasLocalStorage()) { 1689 SemaRef.Diag(E->getLocStart(), 1690 diag::err_omp_local_var_in_threadprivate_init) 1691 << E->getSourceRange(); 1692 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1693 << VD << VD->getSourceRange(); 1694 return true; 1695 } 1696 } 1697 return false; 1698 } 1699 bool VisitStmt(const Stmt *S) { 1700 for (auto Child : S->children()) { 1701 if (Child && Visit(Child)) 1702 return true; 1703 } 1704 return false; 1705 } 1706 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1707 }; 1708 } // namespace 1709 1710 OMPThreadPrivateDecl * 1711 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1712 SmallVector<Expr *, 8> Vars; 1713 for (auto &RefExpr : VarList) { 1714 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 1715 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 1716 SourceLocation ILoc = DE->getExprLoc(); 1717 1718 // Mark variable as used. 1719 VD->setReferenced(); 1720 VD->markUsed(Context); 1721 1722 QualType QType = VD->getType(); 1723 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1724 // It will be analyzed later. 1725 Vars.push_back(DE); 1726 continue; 1727 } 1728 1729 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1730 // A threadprivate variable must not have an incomplete type. 1731 if (RequireCompleteType(ILoc, VD->getType(), 1732 diag::err_omp_threadprivate_incomplete_type)) { 1733 continue; 1734 } 1735 1736 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1737 // A threadprivate variable must not have a reference type. 1738 if (VD->getType()->isReferenceType()) { 1739 Diag(ILoc, diag::err_omp_ref_type_arg) 1740 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1741 bool IsDecl = 1742 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1743 Diag(VD->getLocation(), 1744 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1745 << VD; 1746 continue; 1747 } 1748 1749 // Check if this is a TLS variable. If TLS is not being supported, produce 1750 // the corresponding diagnostic. 1751 if ((VD->getTLSKind() != VarDecl::TLS_None && 1752 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1753 getLangOpts().OpenMPUseTLS && 1754 getASTContext().getTargetInfo().isTLSSupported())) || 1755 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1756 !VD->isLocalVarDecl())) { 1757 Diag(ILoc, diag::err_omp_var_thread_local) 1758 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1759 bool IsDecl = 1760 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1761 Diag(VD->getLocation(), 1762 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1763 << VD; 1764 continue; 1765 } 1766 1767 // Check if initial value of threadprivate variable reference variable with 1768 // local storage (it is not supported by runtime). 1769 if (auto Init = VD->getAnyInitializer()) { 1770 LocalVarRefChecker Checker(*this); 1771 if (Checker.Visit(Init)) 1772 continue; 1773 } 1774 1775 Vars.push_back(RefExpr); 1776 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1777 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1778 Context, SourceRange(Loc, Loc))); 1779 if (auto *ML = Context.getASTMutationListener()) 1780 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1781 } 1782 OMPThreadPrivateDecl *D = nullptr; 1783 if (!Vars.empty()) { 1784 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1785 Vars); 1786 D->setAccess(AS_public); 1787 } 1788 return D; 1789 } 1790 1791 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 1792 const ValueDecl *D, DSAStackTy::DSAVarData DVar, 1793 bool IsLoopIterVar = false) { 1794 if (DVar.RefExpr) { 1795 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1796 << getOpenMPClauseName(DVar.CKind); 1797 return; 1798 } 1799 enum { 1800 PDSA_StaticMemberShared, 1801 PDSA_StaticLocalVarShared, 1802 PDSA_LoopIterVarPrivate, 1803 PDSA_LoopIterVarLinear, 1804 PDSA_LoopIterVarLastprivate, 1805 PDSA_ConstVarShared, 1806 PDSA_GlobalVarShared, 1807 PDSA_TaskVarFirstprivate, 1808 PDSA_LocalVarPrivate, 1809 PDSA_Implicit 1810 } Reason = PDSA_Implicit; 1811 bool ReportHint = false; 1812 auto ReportLoc = D->getLocation(); 1813 auto *VD = dyn_cast<VarDecl>(D); 1814 if (IsLoopIterVar) { 1815 if (DVar.CKind == OMPC_private) 1816 Reason = PDSA_LoopIterVarPrivate; 1817 else if (DVar.CKind == OMPC_lastprivate) 1818 Reason = PDSA_LoopIterVarLastprivate; 1819 else 1820 Reason = PDSA_LoopIterVarLinear; 1821 } else if (isOpenMPTaskingDirective(DVar.DKind) && 1822 DVar.CKind == OMPC_firstprivate) { 1823 Reason = PDSA_TaskVarFirstprivate; 1824 ReportLoc = DVar.ImplicitDSALoc; 1825 } else if (VD && VD->isStaticLocal()) 1826 Reason = PDSA_StaticLocalVarShared; 1827 else if (VD && VD->isStaticDataMember()) 1828 Reason = PDSA_StaticMemberShared; 1829 else if (VD && VD->isFileVarDecl()) 1830 Reason = PDSA_GlobalVarShared; 1831 else if (D->getType().isConstant(SemaRef.getASTContext())) 1832 Reason = PDSA_ConstVarShared; 1833 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 1834 ReportHint = true; 1835 Reason = PDSA_LocalVarPrivate; 1836 } 1837 if (Reason != PDSA_Implicit) { 1838 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 1839 << Reason << ReportHint 1840 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 1841 } else if (DVar.ImplicitDSALoc.isValid()) { 1842 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 1843 << getOpenMPClauseName(DVar.CKind); 1844 } 1845 } 1846 1847 namespace { 1848 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 1849 DSAStackTy *Stack; 1850 Sema &SemaRef; 1851 bool ErrorFound; 1852 CapturedStmt *CS; 1853 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 1854 llvm::SmallVector<Expr *, 8> ImplicitMap; 1855 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 1856 llvm::DenseSet<ValueDecl *> ImplicitDeclarations; 1857 1858 public: 1859 void VisitDeclRefExpr(DeclRefExpr *E) { 1860 if (E->isTypeDependent() || E->isValueDependent() || 1861 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1862 return; 1863 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1864 VD = VD->getCanonicalDecl(); 1865 // Skip internally declared variables. 1866 if (VD->hasLocalStorage() && !CS->capturesVariable(VD)) 1867 return; 1868 1869 auto DVar = Stack->getTopDSA(VD, false); 1870 // Check if the variable has explicit DSA set and stop analysis if it so. 1871 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 1872 return; 1873 1874 // Skip internally declared static variables. 1875 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD)) 1876 return; 1877 1878 auto ELoc = E->getExprLoc(); 1879 auto DKind = Stack->getCurrentDirective(); 1880 // The default(none) clause requires that each variable that is referenced 1881 // in the construct, and does not have a predetermined data-sharing 1882 // attribute, must have its data-sharing attribute explicitly determined 1883 // by being listed in a data-sharing attribute clause. 1884 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 1885 isParallelOrTaskRegion(DKind) && 1886 VarsWithInheritedDSA.count(VD) == 0) { 1887 VarsWithInheritedDSA[VD] = E; 1888 return; 1889 } 1890 1891 if (isOpenMPTargetExecutionDirective(DKind) && 1892 !Stack->isLoopControlVariable(VD).first) { 1893 if (!Stack->checkMappableExprComponentListsForDecl( 1894 VD, /*CurrentRegionOnly=*/true, 1895 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 1896 StackComponents, 1897 OpenMPClauseKind) { 1898 // Variable is used if it has been marked as an array, array 1899 // section or the variable iself. 1900 return StackComponents.size() == 1 || 1901 std::all_of( 1902 std::next(StackComponents.rbegin()), 1903 StackComponents.rend(), 1904 [](const OMPClauseMappableExprCommon:: 1905 MappableComponent &MC) { 1906 return MC.getAssociatedDeclaration() == 1907 nullptr && 1908 (isa<OMPArraySectionExpr>( 1909 MC.getAssociatedExpression()) || 1910 isa<ArraySubscriptExpr>( 1911 MC.getAssociatedExpression())); 1912 }); 1913 })) { 1914 bool IsFirstprivate = false; 1915 // By default lambdas are captured as firstprivates. 1916 if (const auto *RD = 1917 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 1918 IsFirstprivate = RD->isLambda(); 1919 IsFirstprivate = 1920 IsFirstprivate || 1921 (VD->getType().getNonReferenceType()->isScalarType() && 1922 Stack->getDefaultDMA() != DMA_tofrom_scalar); 1923 if (IsFirstprivate) 1924 ImplicitFirstprivate.emplace_back(E); 1925 else 1926 ImplicitMap.emplace_back(E); 1927 return; 1928 } 1929 } 1930 1931 // OpenMP [2.9.3.6, Restrictions, p.2] 1932 // A list item that appears in a reduction clause of the innermost 1933 // enclosing worksharing or parallel construct may not be accessed in an 1934 // explicit task. 1935 DVar = Stack->hasInnermostDSA( 1936 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1937 [](OpenMPDirectiveKind K) -> bool { 1938 return isOpenMPParallelDirective(K) || 1939 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1940 }, 1941 /*FromParent=*/true); 1942 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1943 ErrorFound = true; 1944 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1945 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 1946 return; 1947 } 1948 1949 // Define implicit data-sharing attributes for task. 1950 DVar = Stack->getImplicitDSA(VD, false); 1951 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1952 !Stack->isLoopControlVariable(VD).first) 1953 ImplicitFirstprivate.push_back(E); 1954 } 1955 } 1956 void VisitMemberExpr(MemberExpr *E) { 1957 if (E->isTypeDependent() || E->isValueDependent() || 1958 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1959 return; 1960 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 1961 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 1962 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 1963 if (!FD) 1964 return; 1965 auto DVar = Stack->getTopDSA(FD, false); 1966 // Check if the variable has explicit DSA set and stop analysis if it 1967 // so. 1968 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 1969 return; 1970 1971 if (isOpenMPTargetExecutionDirective(DKind) && 1972 !Stack->isLoopControlVariable(FD).first && 1973 !Stack->checkMappableExprComponentListsForDecl( 1974 FD, /*CurrentRegionOnly=*/true, 1975 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 1976 StackComponents, 1977 OpenMPClauseKind) { 1978 return isa<CXXThisExpr>( 1979 cast<MemberExpr>( 1980 StackComponents.back().getAssociatedExpression()) 1981 ->getBase() 1982 ->IgnoreParens()); 1983 })) { 1984 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 1985 // A bit-field cannot appear in a map clause. 1986 // 1987 if (FD->isBitField()) 1988 return; 1989 ImplicitMap.emplace_back(E); 1990 return; 1991 } 1992 1993 auto ELoc = E->getExprLoc(); 1994 // OpenMP [2.9.3.6, Restrictions, p.2] 1995 // A list item that appears in a reduction clause of the innermost 1996 // enclosing worksharing or parallel construct may not be accessed in 1997 // an explicit task. 1998 DVar = Stack->hasInnermostDSA( 1999 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 2000 [](OpenMPDirectiveKind K) -> bool { 2001 return isOpenMPParallelDirective(K) || 2002 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 2003 }, 2004 /*FromParent=*/true); 2005 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 2006 ErrorFound = true; 2007 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 2008 ReportOriginalDSA(SemaRef, Stack, FD, DVar); 2009 return; 2010 } 2011 2012 // Define implicit data-sharing attributes for task. 2013 DVar = Stack->getImplicitDSA(FD, false); 2014 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 2015 !Stack->isLoopControlVariable(FD).first) 2016 ImplicitFirstprivate.push_back(E); 2017 return; 2018 } 2019 if (isOpenMPTargetExecutionDirective(DKind)) { 2020 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 2021 if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 2022 /*NoDiagnose=*/true)) 2023 return; 2024 auto *VD = cast<ValueDecl>( 2025 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 2026 if (!Stack->checkMappableExprComponentListsForDecl( 2027 VD, /*CurrentRegionOnly=*/true, 2028 [&CurComponents]( 2029 OMPClauseMappableExprCommon::MappableExprComponentListRef 2030 StackComponents, 2031 OpenMPClauseKind) { 2032 auto CCI = CurComponents.rbegin(); 2033 auto CCE = CurComponents.rend(); 2034 for (const auto &SC : llvm::reverse(StackComponents)) { 2035 // Do both expressions have the same kind? 2036 if (CCI->getAssociatedExpression()->getStmtClass() != 2037 SC.getAssociatedExpression()->getStmtClass()) 2038 if (!(isa<OMPArraySectionExpr>( 2039 SC.getAssociatedExpression()) && 2040 isa<ArraySubscriptExpr>( 2041 CCI->getAssociatedExpression()))) 2042 return false; 2043 2044 Decl *CCD = CCI->getAssociatedDeclaration(); 2045 Decl *SCD = SC.getAssociatedDeclaration(); 2046 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 2047 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 2048 if (SCD != CCD) 2049 return false; 2050 std::advance(CCI, 1); 2051 if (CCI == CCE) 2052 break; 2053 } 2054 return true; 2055 })) { 2056 Visit(E->getBase()); 2057 } 2058 } else 2059 Visit(E->getBase()); 2060 } 2061 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 2062 for (auto *C : S->clauses()) { 2063 // Skip analysis of arguments of implicitly defined firstprivate clause 2064 // for task|target directives. 2065 // Skip analysis of arguments of implicitly defined map clause for target 2066 // directives. 2067 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 2068 C->isImplicit())) { 2069 for (auto *CC : C->children()) { 2070 if (CC) 2071 Visit(CC); 2072 } 2073 } 2074 } 2075 } 2076 void VisitStmt(Stmt *S) { 2077 for (auto *C : S->children()) { 2078 if (C && !isa<OMPExecutableDirective>(C)) 2079 Visit(C); 2080 } 2081 } 2082 2083 bool isErrorFound() { return ErrorFound; } 2084 ArrayRef<Expr *> getImplicitFirstprivate() const { 2085 return ImplicitFirstprivate; 2086 } 2087 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; } 2088 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() { 2089 return VarsWithInheritedDSA; 2090 } 2091 2092 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 2093 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 2094 }; 2095 } // namespace 2096 2097 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 2098 switch (DKind) { 2099 case OMPD_parallel: 2100 case OMPD_parallel_for: 2101 case OMPD_parallel_for_simd: 2102 case OMPD_parallel_sections: 2103 case OMPD_teams: 2104 case OMPD_teams_distribute: 2105 case OMPD_teams_distribute_simd: { 2106 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2107 QualType KmpInt32PtrTy = 2108 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2109 Sema::CapturedParamNameType Params[] = { 2110 std::make_pair(".global_tid.", KmpInt32PtrTy), 2111 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2112 std::make_pair(StringRef(), QualType()) // __context with shared vars 2113 }; 2114 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2115 Params); 2116 break; 2117 } 2118 case OMPD_target_teams: 2119 case OMPD_target_parallel: 2120 case OMPD_target_parallel_for: 2121 case OMPD_target_parallel_for_simd: 2122 case OMPD_target_teams_distribute: 2123 case OMPD_target_teams_distribute_simd: { 2124 Sema::CapturedParamNameType ParamsTarget[] = { 2125 std::make_pair(StringRef(), QualType()) // __context with shared vars 2126 }; 2127 // Start a captured region for 'target' with no implicit parameters. 2128 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2129 ParamsTarget); 2130 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2131 QualType KmpInt32PtrTy = 2132 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2133 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 2134 std::make_pair(".global_tid.", KmpInt32PtrTy), 2135 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2136 std::make_pair(StringRef(), QualType()) // __context with shared vars 2137 }; 2138 // Start a captured region for 'teams' or 'parallel'. Both regions have 2139 // the same implicit parameters. 2140 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2141 ParamsTeamsOrParallel); 2142 break; 2143 } 2144 case OMPD_simd: 2145 case OMPD_for: 2146 case OMPD_for_simd: 2147 case OMPD_sections: 2148 case OMPD_section: 2149 case OMPD_single: 2150 case OMPD_master: 2151 case OMPD_critical: 2152 case OMPD_taskgroup: 2153 case OMPD_distribute: 2154 case OMPD_distribute_simd: 2155 case OMPD_ordered: 2156 case OMPD_atomic: 2157 case OMPD_target_data: 2158 case OMPD_target: 2159 case OMPD_target_simd: { 2160 Sema::CapturedParamNameType Params[] = { 2161 std::make_pair(StringRef(), QualType()) // __context with shared vars 2162 }; 2163 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2164 Params); 2165 break; 2166 } 2167 case OMPD_task: { 2168 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2169 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2170 FunctionProtoType::ExtProtoInfo EPI; 2171 EPI.Variadic = true; 2172 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2173 Sema::CapturedParamNameType Params[] = { 2174 std::make_pair(".global_tid.", KmpInt32Ty), 2175 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2176 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 2177 std::make_pair(".copy_fn.", 2178 Context.getPointerType(CopyFnType).withConst()), 2179 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2180 std::make_pair(StringRef(), QualType()) // __context with shared vars 2181 }; 2182 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2183 Params); 2184 // Mark this captured region as inlined, because we don't use outlined 2185 // function directly. 2186 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2187 AlwaysInlineAttr::CreateImplicit( 2188 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2189 break; 2190 } 2191 case OMPD_taskloop: 2192 case OMPD_taskloop_simd: { 2193 QualType KmpInt32Ty = 2194 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 2195 QualType KmpUInt64Ty = 2196 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 2197 QualType KmpInt64Ty = 2198 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 2199 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2200 FunctionProtoType::ExtProtoInfo EPI; 2201 EPI.Variadic = true; 2202 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2203 Sema::CapturedParamNameType Params[] = { 2204 std::make_pair(".global_tid.", KmpInt32Ty), 2205 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2206 std::make_pair(".privates.", 2207 Context.VoidPtrTy.withConst().withRestrict()), 2208 std::make_pair( 2209 ".copy_fn.", 2210 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2211 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2212 std::make_pair(".lb.", KmpUInt64Ty), 2213 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 2214 std::make_pair(".liter.", KmpInt32Ty), 2215 std::make_pair(".reductions.", 2216 Context.VoidPtrTy.withConst().withRestrict()), 2217 std::make_pair(StringRef(), QualType()) // __context with shared vars 2218 }; 2219 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2220 Params); 2221 // Mark this captured region as inlined, because we don't use outlined 2222 // function directly. 2223 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2224 AlwaysInlineAttr::CreateImplicit( 2225 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2226 break; 2227 } 2228 case OMPD_distribute_parallel_for_simd: 2229 case OMPD_distribute_parallel_for: 2230 case OMPD_target_teams_distribute_parallel_for_simd: { 2231 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2232 QualType KmpInt32PtrTy = 2233 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2234 Sema::CapturedParamNameType Params[] = { 2235 std::make_pair(".global_tid.", KmpInt32PtrTy), 2236 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2237 std::make_pair(".previous.lb.", Context.getSizeType()), 2238 std::make_pair(".previous.ub.", Context.getSizeType()), 2239 std::make_pair(StringRef(), QualType()) // __context with shared vars 2240 }; 2241 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2242 Params); 2243 break; 2244 } 2245 case OMPD_target_teams_distribute_parallel_for: { 2246 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2247 QualType KmpInt32PtrTy = 2248 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2249 2250 Sema::CapturedParamNameType ParamsTarget[] = { 2251 std::make_pair(StringRef(), QualType()) // __context with shared vars 2252 }; 2253 // Start a captured region for 'target' with no implicit parameters. 2254 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2255 ParamsTarget); 2256 2257 Sema::CapturedParamNameType ParamsTeams[] = { 2258 std::make_pair(".global_tid.", KmpInt32PtrTy), 2259 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2260 std::make_pair(StringRef(), QualType()) // __context with shared vars 2261 }; 2262 // Start a captured region for 'target' with no implicit parameters. 2263 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2264 ParamsTeams); 2265 2266 Sema::CapturedParamNameType ParamsParallel[] = { 2267 std::make_pair(".global_tid.", KmpInt32PtrTy), 2268 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2269 std::make_pair(".previous.lb.", Context.getSizeType()), 2270 std::make_pair(".previous.ub.", Context.getSizeType()), 2271 std::make_pair(StringRef(), QualType()) // __context with shared vars 2272 }; 2273 // Start a captured region for 'teams' or 'parallel'. Both regions have 2274 // the same implicit parameters. 2275 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2276 ParamsParallel); 2277 break; 2278 } 2279 2280 case OMPD_teams_distribute_parallel_for: 2281 case OMPD_teams_distribute_parallel_for_simd: { 2282 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2283 QualType KmpInt32PtrTy = 2284 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2285 2286 Sema::CapturedParamNameType ParamsTeams[] = { 2287 std::make_pair(".global_tid.", KmpInt32PtrTy), 2288 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2289 std::make_pair(StringRef(), QualType()) // __context with shared vars 2290 }; 2291 // Start a captured region for 'target' with no implicit parameters. 2292 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2293 ParamsTeams); 2294 2295 Sema::CapturedParamNameType ParamsParallel[] = { 2296 std::make_pair(".global_tid.", KmpInt32PtrTy), 2297 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2298 std::make_pair(".previous.lb.", Context.getSizeType()), 2299 std::make_pair(".previous.ub.", Context.getSizeType()), 2300 std::make_pair(StringRef(), QualType()) // __context with shared vars 2301 }; 2302 // Start a captured region for 'teams' or 'parallel'. Both regions have 2303 // the same implicit parameters. 2304 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2305 ParamsParallel); 2306 break; 2307 } 2308 case OMPD_target_update: 2309 case OMPD_target_enter_data: 2310 case OMPD_target_exit_data: { 2311 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2312 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2313 FunctionProtoType::ExtProtoInfo EPI; 2314 EPI.Variadic = true; 2315 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2316 Sema::CapturedParamNameType Params[] = { 2317 std::make_pair(".global_tid.", KmpInt32Ty), 2318 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2319 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 2320 std::make_pair(".copy_fn.", 2321 Context.getPointerType(CopyFnType).withConst()), 2322 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2323 std::make_pair(StringRef(), QualType()) // __context with shared vars 2324 }; 2325 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2326 Params); 2327 // Mark this captured region as inlined, because we don't use outlined 2328 // function directly. 2329 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2330 AlwaysInlineAttr::CreateImplicit( 2331 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2332 break; 2333 } 2334 case OMPD_threadprivate: 2335 case OMPD_taskyield: 2336 case OMPD_barrier: 2337 case OMPD_taskwait: 2338 case OMPD_cancellation_point: 2339 case OMPD_cancel: 2340 case OMPD_flush: 2341 case OMPD_declare_reduction: 2342 case OMPD_declare_simd: 2343 case OMPD_declare_target: 2344 case OMPD_end_declare_target: 2345 llvm_unreachable("OpenMP Directive is not allowed"); 2346 case OMPD_unknown: 2347 llvm_unreachable("Unknown OpenMP directive"); 2348 } 2349 } 2350 2351 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 2352 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2353 getOpenMPCaptureRegions(CaptureRegions, DKind); 2354 return CaptureRegions.size(); 2355 } 2356 2357 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 2358 Expr *CaptureExpr, bool WithInit, 2359 bool AsExpression) { 2360 assert(CaptureExpr); 2361 ASTContext &C = S.getASTContext(); 2362 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 2363 QualType Ty = Init->getType(); 2364 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 2365 if (S.getLangOpts().CPlusPlus) { 2366 Ty = C.getLValueReferenceType(Ty); 2367 } else { 2368 Ty = C.getPointerType(Ty); 2369 ExprResult Res = 2370 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 2371 if (!Res.isUsable()) 2372 return nullptr; 2373 Init = Res.get(); 2374 } 2375 WithInit = true; 2376 } 2377 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 2378 CaptureExpr->getLocStart()); 2379 if (!WithInit) 2380 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 2381 S.CurContext->addHiddenDecl(CED); 2382 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 2383 return CED; 2384 } 2385 2386 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2387 bool WithInit) { 2388 OMPCapturedExprDecl *CD; 2389 if (auto *VD = S.IsOpenMPCapturedDecl(D)) { 2390 CD = cast<OMPCapturedExprDecl>(VD); 2391 } else { 2392 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 2393 /*AsExpression=*/false); 2394 } 2395 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2396 CaptureExpr->getExprLoc()); 2397 } 2398 2399 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 2400 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 2401 if (!Ref) { 2402 OMPCapturedExprDecl *CD = buildCaptureDecl( 2403 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 2404 /*WithInit=*/true, /*AsExpression=*/true); 2405 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2406 CaptureExpr->getExprLoc()); 2407 } 2408 ExprResult Res = Ref; 2409 if (!S.getLangOpts().CPlusPlus && 2410 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 2411 Ref->getType()->isPointerType()) { 2412 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 2413 if (!Res.isUsable()) 2414 return ExprError(); 2415 } 2416 return S.DefaultLvalueConversion(Res.get()); 2417 } 2418 2419 namespace { 2420 // OpenMP directives parsed in this section are represented as a 2421 // CapturedStatement with an associated statement. If a syntax error 2422 // is detected during the parsing of the associated statement, the 2423 // compiler must abort processing and close the CapturedStatement. 2424 // 2425 // Combined directives such as 'target parallel' have more than one 2426 // nested CapturedStatements. This RAII ensures that we unwind out 2427 // of all the nested CapturedStatements when an error is found. 2428 class CaptureRegionUnwinderRAII { 2429 private: 2430 Sema &S; 2431 bool &ErrorFound; 2432 OpenMPDirectiveKind DKind; 2433 2434 public: 2435 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 2436 OpenMPDirectiveKind DKind) 2437 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 2438 ~CaptureRegionUnwinderRAII() { 2439 if (ErrorFound) { 2440 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 2441 while (--ThisCaptureLevel >= 0) 2442 S.ActOnCapturedRegionError(); 2443 } 2444 } 2445 }; 2446 } // namespace 2447 2448 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 2449 ArrayRef<OMPClause *> Clauses) { 2450 bool ErrorFound = false; 2451 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 2452 *this, ErrorFound, DSAStack->getCurrentDirective()); 2453 if (!S.isUsable()) { 2454 ErrorFound = true; 2455 return StmtError(); 2456 } 2457 2458 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2459 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 2460 OMPOrderedClause *OC = nullptr; 2461 OMPScheduleClause *SC = nullptr; 2462 SmallVector<OMPLinearClause *, 4> LCs; 2463 SmallVector<OMPClauseWithPreInit *, 8> PICs; 2464 // This is required for proper codegen. 2465 for (auto *Clause : Clauses) { 2466 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 2467 Clause->getClauseKind() == OMPC_in_reduction) { 2468 // Capture taskgroup task_reduction descriptors inside the tasking regions 2469 // with the corresponding in_reduction items. 2470 auto *IRC = cast<OMPInReductionClause>(Clause); 2471 for (auto *E : IRC->taskgroup_descriptors()) 2472 if (E) 2473 MarkDeclarationsReferencedInExpr(E); 2474 } 2475 if (isOpenMPPrivate(Clause->getClauseKind()) || 2476 Clause->getClauseKind() == OMPC_copyprivate || 2477 (getLangOpts().OpenMPUseTLS && 2478 getASTContext().getTargetInfo().isTLSSupported() && 2479 Clause->getClauseKind() == OMPC_copyin)) { 2480 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 2481 // Mark all variables in private list clauses as used in inner region. 2482 for (auto *VarRef : Clause->children()) { 2483 if (auto *E = cast_or_null<Expr>(VarRef)) { 2484 MarkDeclarationsReferencedInExpr(E); 2485 } 2486 } 2487 DSAStack->setForceVarCapturing(/*V=*/false); 2488 } else if (CaptureRegions.size() > 1 || 2489 CaptureRegions.back() != OMPD_unknown) { 2490 if (auto *C = OMPClauseWithPreInit::get(Clause)) 2491 PICs.push_back(C); 2492 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 2493 if (auto *E = C->getPostUpdateExpr()) 2494 MarkDeclarationsReferencedInExpr(E); 2495 } 2496 } 2497 if (Clause->getClauseKind() == OMPC_schedule) 2498 SC = cast<OMPScheduleClause>(Clause); 2499 else if (Clause->getClauseKind() == OMPC_ordered) 2500 OC = cast<OMPOrderedClause>(Clause); 2501 else if (Clause->getClauseKind() == OMPC_linear) 2502 LCs.push_back(cast<OMPLinearClause>(Clause)); 2503 } 2504 // OpenMP, 2.7.1 Loop Construct, Restrictions 2505 // The nonmonotonic modifier cannot be specified if an ordered clause is 2506 // specified. 2507 if (SC && 2508 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 2509 SC->getSecondScheduleModifier() == 2510 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 2511 OC) { 2512 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 2513 ? SC->getFirstScheduleModifierLoc() 2514 : SC->getSecondScheduleModifierLoc(), 2515 diag::err_omp_schedule_nonmonotonic_ordered) 2516 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2517 ErrorFound = true; 2518 } 2519 if (!LCs.empty() && OC && OC->getNumForLoops()) { 2520 for (auto *C : LCs) { 2521 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 2522 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2523 } 2524 ErrorFound = true; 2525 } 2526 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 2527 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 2528 OC->getNumForLoops()) { 2529 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 2530 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 2531 ErrorFound = true; 2532 } 2533 if (ErrorFound) { 2534 return StmtError(); 2535 } 2536 StmtResult SR = S; 2537 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 2538 // Mark all variables in private list clauses as used in inner region. 2539 // Required for proper codegen of combined directives. 2540 // TODO: add processing for other clauses. 2541 if (ThisCaptureRegion != OMPD_unknown) { 2542 for (auto *C : PICs) { 2543 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 2544 // Find the particular capture region for the clause if the 2545 // directive is a combined one with multiple capture regions. 2546 // If the directive is not a combined one, the capture region 2547 // associated with the clause is OMPD_unknown and is generated 2548 // only once. 2549 if (CaptureRegion == ThisCaptureRegion || 2550 CaptureRegion == OMPD_unknown) { 2551 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 2552 for (auto *D : DS->decls()) 2553 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 2554 } 2555 } 2556 } 2557 } 2558 SR = ActOnCapturedRegionEnd(SR.get()); 2559 } 2560 return SR; 2561 } 2562 2563 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 2564 OpenMPDirectiveKind CancelRegion, 2565 SourceLocation StartLoc) { 2566 // CancelRegion is only needed for cancel and cancellation_point. 2567 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 2568 return false; 2569 2570 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 2571 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 2572 return false; 2573 2574 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 2575 << getOpenMPDirectiveName(CancelRegion); 2576 return true; 2577 } 2578 2579 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 2580 OpenMPDirectiveKind CurrentRegion, 2581 const DeclarationNameInfo &CurrentName, 2582 OpenMPDirectiveKind CancelRegion, 2583 SourceLocation StartLoc) { 2584 if (Stack->getCurScope()) { 2585 auto ParentRegion = Stack->getParentDirective(); 2586 auto OffendingRegion = ParentRegion; 2587 bool NestingProhibited = false; 2588 bool CloseNesting = true; 2589 bool OrphanSeen = false; 2590 enum { 2591 NoRecommend, 2592 ShouldBeInParallelRegion, 2593 ShouldBeInOrderedRegion, 2594 ShouldBeInTargetRegion, 2595 ShouldBeInTeamsRegion 2596 } Recommend = NoRecommend; 2597 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 2598 // OpenMP [2.16, Nesting of Regions] 2599 // OpenMP constructs may not be nested inside a simd region. 2600 // OpenMP [2.8.1,simd Construct, Restrictions] 2601 // An ordered construct with the simd clause is the only OpenMP 2602 // construct that can appear in the simd region. 2603 // Allowing a SIMD construct nested in another SIMD construct is an 2604 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 2605 // message. 2606 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 2607 ? diag::err_omp_prohibited_region_simd 2608 : diag::warn_omp_nesting_simd); 2609 return CurrentRegion != OMPD_simd; 2610 } 2611 if (ParentRegion == OMPD_atomic) { 2612 // OpenMP [2.16, Nesting of Regions] 2613 // OpenMP constructs may not be nested inside an atomic region. 2614 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 2615 return true; 2616 } 2617 if (CurrentRegion == OMPD_section) { 2618 // OpenMP [2.7.2, sections Construct, Restrictions] 2619 // Orphaned section directives are prohibited. That is, the section 2620 // directives must appear within the sections construct and must not be 2621 // encountered elsewhere in the sections region. 2622 if (ParentRegion != OMPD_sections && 2623 ParentRegion != OMPD_parallel_sections) { 2624 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 2625 << (ParentRegion != OMPD_unknown) 2626 << getOpenMPDirectiveName(ParentRegion); 2627 return true; 2628 } 2629 return false; 2630 } 2631 // Allow some constructs (except teams) to be orphaned (they could be 2632 // used in functions, called from OpenMP regions with the required 2633 // preconditions). 2634 if (ParentRegion == OMPD_unknown && 2635 !isOpenMPNestingTeamsDirective(CurrentRegion)) 2636 return false; 2637 if (CurrentRegion == OMPD_cancellation_point || 2638 CurrentRegion == OMPD_cancel) { 2639 // OpenMP [2.16, Nesting of Regions] 2640 // A cancellation point construct for which construct-type-clause is 2641 // taskgroup must be nested inside a task construct. A cancellation 2642 // point construct for which construct-type-clause is not taskgroup must 2643 // be closely nested inside an OpenMP construct that matches the type 2644 // specified in construct-type-clause. 2645 // A cancel construct for which construct-type-clause is taskgroup must be 2646 // nested inside a task construct. A cancel construct for which 2647 // construct-type-clause is not taskgroup must be closely nested inside an 2648 // OpenMP construct that matches the type specified in 2649 // construct-type-clause. 2650 NestingProhibited = 2651 !((CancelRegion == OMPD_parallel && 2652 (ParentRegion == OMPD_parallel || 2653 ParentRegion == OMPD_target_parallel)) || 2654 (CancelRegion == OMPD_for && 2655 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 2656 ParentRegion == OMPD_target_parallel_for || 2657 ParentRegion == OMPD_distribute_parallel_for || 2658 ParentRegion == OMPD_teams_distribute_parallel_for || 2659 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 2660 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 2661 (CancelRegion == OMPD_sections && 2662 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 2663 ParentRegion == OMPD_parallel_sections))); 2664 } else if (CurrentRegion == OMPD_master) { 2665 // OpenMP [2.16, Nesting of Regions] 2666 // A master region may not be closely nested inside a worksharing, 2667 // atomic, or explicit task region. 2668 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2669 isOpenMPTaskingDirective(ParentRegion); 2670 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 2671 // OpenMP [2.16, Nesting of Regions] 2672 // A critical region may not be nested (closely or otherwise) inside a 2673 // critical region with the same name. Note that this restriction is not 2674 // sufficient to prevent deadlock. 2675 SourceLocation PreviousCriticalLoc; 2676 bool DeadLock = Stack->hasDirective( 2677 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 2678 const DeclarationNameInfo &DNI, 2679 SourceLocation Loc) -> bool { 2680 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 2681 PreviousCriticalLoc = Loc; 2682 return true; 2683 } else 2684 return false; 2685 }, 2686 false /* skip top directive */); 2687 if (DeadLock) { 2688 SemaRef.Diag(StartLoc, 2689 diag::err_omp_prohibited_region_critical_same_name) 2690 << CurrentName.getName(); 2691 if (PreviousCriticalLoc.isValid()) 2692 SemaRef.Diag(PreviousCriticalLoc, 2693 diag::note_omp_previous_critical_region); 2694 return true; 2695 } 2696 } else if (CurrentRegion == OMPD_barrier) { 2697 // OpenMP [2.16, Nesting of Regions] 2698 // A barrier region may not be closely nested inside a worksharing, 2699 // explicit task, critical, ordered, atomic, or master region. 2700 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2701 isOpenMPTaskingDirective(ParentRegion) || 2702 ParentRegion == OMPD_master || 2703 ParentRegion == OMPD_critical || 2704 ParentRegion == OMPD_ordered; 2705 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2706 !isOpenMPParallelDirective(CurrentRegion) && 2707 !isOpenMPTeamsDirective(CurrentRegion)) { 2708 // OpenMP [2.16, Nesting of Regions] 2709 // A worksharing region may not be closely nested inside a worksharing, 2710 // explicit task, critical, ordered, atomic, or master region. 2711 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2712 isOpenMPTaskingDirective(ParentRegion) || 2713 ParentRegion == OMPD_master || 2714 ParentRegion == OMPD_critical || 2715 ParentRegion == OMPD_ordered; 2716 Recommend = ShouldBeInParallelRegion; 2717 } else if (CurrentRegion == OMPD_ordered) { 2718 // OpenMP [2.16, Nesting of Regions] 2719 // An ordered region may not be closely nested inside a critical, 2720 // atomic, or explicit task region. 2721 // An ordered region must be closely nested inside a loop region (or 2722 // parallel loop region) with an ordered clause. 2723 // OpenMP [2.8.1,simd Construct, Restrictions] 2724 // An ordered construct with the simd clause is the only OpenMP construct 2725 // that can appear in the simd region. 2726 NestingProhibited = ParentRegion == OMPD_critical || 2727 isOpenMPTaskingDirective(ParentRegion) || 2728 !(isOpenMPSimdDirective(ParentRegion) || 2729 Stack->isParentOrderedRegion()); 2730 Recommend = ShouldBeInOrderedRegion; 2731 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 2732 // OpenMP [2.16, Nesting of Regions] 2733 // If specified, a teams construct must be contained within a target 2734 // construct. 2735 NestingProhibited = ParentRegion != OMPD_target; 2736 OrphanSeen = ParentRegion == OMPD_unknown; 2737 Recommend = ShouldBeInTargetRegion; 2738 } 2739 if (!NestingProhibited && 2740 !isOpenMPTargetExecutionDirective(CurrentRegion) && 2741 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 2742 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 2743 // OpenMP [2.16, Nesting of Regions] 2744 // distribute, parallel, parallel sections, parallel workshare, and the 2745 // parallel loop and parallel loop SIMD constructs are the only OpenMP 2746 // constructs that can be closely nested in the teams region. 2747 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 2748 !isOpenMPDistributeDirective(CurrentRegion); 2749 Recommend = ShouldBeInParallelRegion; 2750 } 2751 if (!NestingProhibited && 2752 isOpenMPNestingDistributeDirective(CurrentRegion)) { 2753 // OpenMP 4.5 [2.17 Nesting of Regions] 2754 // The region associated with the distribute construct must be strictly 2755 // nested inside a teams region 2756 NestingProhibited = 2757 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 2758 Recommend = ShouldBeInTeamsRegion; 2759 } 2760 if (!NestingProhibited && 2761 (isOpenMPTargetExecutionDirective(CurrentRegion) || 2762 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 2763 // OpenMP 4.5 [2.17 Nesting of Regions] 2764 // If a target, target update, target data, target enter data, or 2765 // target exit data construct is encountered during execution of a 2766 // target region, the behavior is unspecified. 2767 NestingProhibited = Stack->hasDirective( 2768 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2769 SourceLocation) -> bool { 2770 if (isOpenMPTargetExecutionDirective(K)) { 2771 OffendingRegion = K; 2772 return true; 2773 } else 2774 return false; 2775 }, 2776 false /* don't skip top directive */); 2777 CloseNesting = false; 2778 } 2779 if (NestingProhibited) { 2780 if (OrphanSeen) { 2781 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 2782 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 2783 } else { 2784 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 2785 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 2786 << Recommend << getOpenMPDirectiveName(CurrentRegion); 2787 } 2788 return true; 2789 } 2790 } 2791 return false; 2792 } 2793 2794 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 2795 ArrayRef<OMPClause *> Clauses, 2796 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 2797 bool ErrorFound = false; 2798 unsigned NamedModifiersNumber = 0; 2799 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 2800 OMPD_unknown + 1); 2801 SmallVector<SourceLocation, 4> NameModifierLoc; 2802 for (const auto *C : Clauses) { 2803 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 2804 // At most one if clause without a directive-name-modifier can appear on 2805 // the directive. 2806 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 2807 if (FoundNameModifiers[CurNM]) { 2808 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 2809 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 2810 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 2811 ErrorFound = true; 2812 } else if (CurNM != OMPD_unknown) { 2813 NameModifierLoc.push_back(IC->getNameModifierLoc()); 2814 ++NamedModifiersNumber; 2815 } 2816 FoundNameModifiers[CurNM] = IC; 2817 if (CurNM == OMPD_unknown) 2818 continue; 2819 // Check if the specified name modifier is allowed for the current 2820 // directive. 2821 // At most one if clause with the particular directive-name-modifier can 2822 // appear on the directive. 2823 bool MatchFound = false; 2824 for (auto NM : AllowedNameModifiers) { 2825 if (CurNM == NM) { 2826 MatchFound = true; 2827 break; 2828 } 2829 } 2830 if (!MatchFound) { 2831 S.Diag(IC->getNameModifierLoc(), 2832 diag::err_omp_wrong_if_directive_name_modifier) 2833 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 2834 ErrorFound = true; 2835 } 2836 } 2837 } 2838 // If any if clause on the directive includes a directive-name-modifier then 2839 // all if clauses on the directive must include a directive-name-modifier. 2840 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 2841 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 2842 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 2843 diag::err_omp_no_more_if_clause); 2844 } else { 2845 std::string Values; 2846 std::string Sep(", "); 2847 unsigned AllowedCnt = 0; 2848 unsigned TotalAllowedNum = 2849 AllowedNameModifiers.size() - NamedModifiersNumber; 2850 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 2851 ++Cnt) { 2852 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 2853 if (!FoundNameModifiers[NM]) { 2854 Values += "'"; 2855 Values += getOpenMPDirectiveName(NM); 2856 Values += "'"; 2857 if (AllowedCnt + 2 == TotalAllowedNum) 2858 Values += " or "; 2859 else if (AllowedCnt + 1 != TotalAllowedNum) 2860 Values += Sep; 2861 ++AllowedCnt; 2862 } 2863 } 2864 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 2865 diag::err_omp_unnamed_if_clause) 2866 << (TotalAllowedNum > 1) << Values; 2867 } 2868 for (auto Loc : NameModifierLoc) { 2869 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 2870 } 2871 ErrorFound = true; 2872 } 2873 return ErrorFound; 2874 } 2875 2876 StmtResult Sema::ActOnOpenMPExecutableDirective( 2877 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 2878 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 2879 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 2880 StmtResult Res = StmtError(); 2881 // First check CancelRegion which is then used in checkNestingOfRegions. 2882 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 2883 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 2884 StartLoc)) 2885 return StmtError(); 2886 2887 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 2888 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 2889 bool ErrorFound = false; 2890 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 2891 if (AStmt && !CurContext->isDependentContext()) { 2892 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2893 2894 // Check default data sharing attributes for referenced variables. 2895 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 2896 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 2897 Stmt *S = AStmt; 2898 while (--ThisCaptureLevel >= 0) 2899 S = cast<CapturedStmt>(S)->getCapturedStmt(); 2900 DSAChecker.Visit(S); 2901 if (DSAChecker.isErrorFound()) 2902 return StmtError(); 2903 // Generate list of implicitly defined firstprivate variables. 2904 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 2905 2906 SmallVector<Expr *, 4> ImplicitFirstprivates( 2907 DSAChecker.getImplicitFirstprivate().begin(), 2908 DSAChecker.getImplicitFirstprivate().end()); 2909 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(), 2910 DSAChecker.getImplicitMap().end()); 2911 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 2912 for (auto *C : Clauses) { 2913 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 2914 for (auto *E : IRC->taskgroup_descriptors()) 2915 if (E) 2916 ImplicitFirstprivates.emplace_back(E); 2917 } 2918 } 2919 if (!ImplicitFirstprivates.empty()) { 2920 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 2921 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 2922 SourceLocation())) { 2923 ClausesWithImplicit.push_back(Implicit); 2924 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 2925 ImplicitFirstprivates.size(); 2926 } else 2927 ErrorFound = true; 2928 } 2929 if (!ImplicitMaps.empty()) { 2930 if (OMPClause *Implicit = ActOnOpenMPMapClause( 2931 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, 2932 SourceLocation(), SourceLocation(), ImplicitMaps, 2933 SourceLocation(), SourceLocation(), SourceLocation())) { 2934 ClausesWithImplicit.emplace_back(Implicit); 2935 ErrorFound |= 2936 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size(); 2937 } else 2938 ErrorFound = true; 2939 } 2940 } 2941 2942 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 2943 switch (Kind) { 2944 case OMPD_parallel: 2945 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 2946 EndLoc); 2947 AllowedNameModifiers.push_back(OMPD_parallel); 2948 break; 2949 case OMPD_simd: 2950 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2951 VarsWithInheritedDSA); 2952 break; 2953 case OMPD_for: 2954 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2955 VarsWithInheritedDSA); 2956 break; 2957 case OMPD_for_simd: 2958 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2959 EndLoc, VarsWithInheritedDSA); 2960 break; 2961 case OMPD_sections: 2962 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 2963 EndLoc); 2964 break; 2965 case OMPD_section: 2966 assert(ClausesWithImplicit.empty() && 2967 "No clauses are allowed for 'omp section' directive"); 2968 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 2969 break; 2970 case OMPD_single: 2971 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 2972 EndLoc); 2973 break; 2974 case OMPD_master: 2975 assert(ClausesWithImplicit.empty() && 2976 "No clauses are allowed for 'omp master' directive"); 2977 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 2978 break; 2979 case OMPD_critical: 2980 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 2981 StartLoc, EndLoc); 2982 break; 2983 case OMPD_parallel_for: 2984 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 2985 EndLoc, VarsWithInheritedDSA); 2986 AllowedNameModifiers.push_back(OMPD_parallel); 2987 break; 2988 case OMPD_parallel_for_simd: 2989 Res = ActOnOpenMPParallelForSimdDirective( 2990 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2991 AllowedNameModifiers.push_back(OMPD_parallel); 2992 break; 2993 case OMPD_parallel_sections: 2994 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 2995 StartLoc, EndLoc); 2996 AllowedNameModifiers.push_back(OMPD_parallel); 2997 break; 2998 case OMPD_task: 2999 Res = 3000 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3001 AllowedNameModifiers.push_back(OMPD_task); 3002 break; 3003 case OMPD_taskyield: 3004 assert(ClausesWithImplicit.empty() && 3005 "No clauses are allowed for 'omp taskyield' directive"); 3006 assert(AStmt == nullptr && 3007 "No associated statement allowed for 'omp taskyield' directive"); 3008 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 3009 break; 3010 case OMPD_barrier: 3011 assert(ClausesWithImplicit.empty() && 3012 "No clauses are allowed for 'omp barrier' directive"); 3013 assert(AStmt == nullptr && 3014 "No associated statement allowed for 'omp barrier' directive"); 3015 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 3016 break; 3017 case OMPD_taskwait: 3018 assert(ClausesWithImplicit.empty() && 3019 "No clauses are allowed for 'omp taskwait' directive"); 3020 assert(AStmt == nullptr && 3021 "No associated statement allowed for 'omp taskwait' directive"); 3022 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 3023 break; 3024 case OMPD_taskgroup: 3025 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 3026 EndLoc); 3027 break; 3028 case OMPD_flush: 3029 assert(AStmt == nullptr && 3030 "No associated statement allowed for 'omp flush' directive"); 3031 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 3032 break; 3033 case OMPD_ordered: 3034 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 3035 EndLoc); 3036 break; 3037 case OMPD_atomic: 3038 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 3039 EndLoc); 3040 break; 3041 case OMPD_teams: 3042 Res = 3043 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3044 break; 3045 case OMPD_target: 3046 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 3047 EndLoc); 3048 AllowedNameModifiers.push_back(OMPD_target); 3049 break; 3050 case OMPD_target_parallel: 3051 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 3052 StartLoc, EndLoc); 3053 AllowedNameModifiers.push_back(OMPD_target); 3054 AllowedNameModifiers.push_back(OMPD_parallel); 3055 break; 3056 case OMPD_target_parallel_for: 3057 Res = ActOnOpenMPTargetParallelForDirective( 3058 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3059 AllowedNameModifiers.push_back(OMPD_target); 3060 AllowedNameModifiers.push_back(OMPD_parallel); 3061 break; 3062 case OMPD_cancellation_point: 3063 assert(ClausesWithImplicit.empty() && 3064 "No clauses are allowed for 'omp cancellation point' directive"); 3065 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 3066 "cancellation point' directive"); 3067 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 3068 break; 3069 case OMPD_cancel: 3070 assert(AStmt == nullptr && 3071 "No associated statement allowed for 'omp cancel' directive"); 3072 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 3073 CancelRegion); 3074 AllowedNameModifiers.push_back(OMPD_cancel); 3075 break; 3076 case OMPD_target_data: 3077 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 3078 EndLoc); 3079 AllowedNameModifiers.push_back(OMPD_target_data); 3080 break; 3081 case OMPD_target_enter_data: 3082 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 3083 EndLoc, AStmt); 3084 AllowedNameModifiers.push_back(OMPD_target_enter_data); 3085 break; 3086 case OMPD_target_exit_data: 3087 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 3088 EndLoc, AStmt); 3089 AllowedNameModifiers.push_back(OMPD_target_exit_data); 3090 break; 3091 case OMPD_taskloop: 3092 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 3093 EndLoc, VarsWithInheritedDSA); 3094 AllowedNameModifiers.push_back(OMPD_taskloop); 3095 break; 3096 case OMPD_taskloop_simd: 3097 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3098 EndLoc, VarsWithInheritedDSA); 3099 AllowedNameModifiers.push_back(OMPD_taskloop); 3100 break; 3101 case OMPD_distribute: 3102 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 3103 EndLoc, VarsWithInheritedDSA); 3104 break; 3105 case OMPD_target_update: 3106 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 3107 EndLoc, AStmt); 3108 AllowedNameModifiers.push_back(OMPD_target_update); 3109 break; 3110 case OMPD_distribute_parallel_for: 3111 Res = ActOnOpenMPDistributeParallelForDirective( 3112 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3113 AllowedNameModifiers.push_back(OMPD_parallel); 3114 break; 3115 case OMPD_distribute_parallel_for_simd: 3116 Res = ActOnOpenMPDistributeParallelForSimdDirective( 3117 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3118 AllowedNameModifiers.push_back(OMPD_parallel); 3119 break; 3120 case OMPD_distribute_simd: 3121 Res = ActOnOpenMPDistributeSimdDirective( 3122 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3123 break; 3124 case OMPD_target_parallel_for_simd: 3125 Res = ActOnOpenMPTargetParallelForSimdDirective( 3126 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3127 AllowedNameModifiers.push_back(OMPD_target); 3128 AllowedNameModifiers.push_back(OMPD_parallel); 3129 break; 3130 case OMPD_target_simd: 3131 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3132 EndLoc, VarsWithInheritedDSA); 3133 AllowedNameModifiers.push_back(OMPD_target); 3134 break; 3135 case OMPD_teams_distribute: 3136 Res = ActOnOpenMPTeamsDistributeDirective( 3137 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3138 break; 3139 case OMPD_teams_distribute_simd: 3140 Res = ActOnOpenMPTeamsDistributeSimdDirective( 3141 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3142 break; 3143 case OMPD_teams_distribute_parallel_for_simd: 3144 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 3145 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3146 AllowedNameModifiers.push_back(OMPD_parallel); 3147 break; 3148 case OMPD_teams_distribute_parallel_for: 3149 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 3150 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3151 AllowedNameModifiers.push_back(OMPD_parallel); 3152 break; 3153 case OMPD_target_teams: 3154 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 3155 EndLoc); 3156 AllowedNameModifiers.push_back(OMPD_target); 3157 break; 3158 case OMPD_target_teams_distribute: 3159 Res = ActOnOpenMPTargetTeamsDistributeDirective( 3160 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3161 AllowedNameModifiers.push_back(OMPD_target); 3162 break; 3163 case OMPD_target_teams_distribute_parallel_for: 3164 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 3165 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3166 AllowedNameModifiers.push_back(OMPD_target); 3167 AllowedNameModifiers.push_back(OMPD_parallel); 3168 break; 3169 case OMPD_target_teams_distribute_parallel_for_simd: 3170 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 3171 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3172 AllowedNameModifiers.push_back(OMPD_target); 3173 AllowedNameModifiers.push_back(OMPD_parallel); 3174 break; 3175 case OMPD_target_teams_distribute_simd: 3176 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 3177 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3178 AllowedNameModifiers.push_back(OMPD_target); 3179 break; 3180 case OMPD_declare_target: 3181 case OMPD_end_declare_target: 3182 case OMPD_threadprivate: 3183 case OMPD_declare_reduction: 3184 case OMPD_declare_simd: 3185 llvm_unreachable("OpenMP Directive is not allowed"); 3186 case OMPD_unknown: 3187 llvm_unreachable("Unknown OpenMP directive"); 3188 } 3189 3190 for (auto P : VarsWithInheritedDSA) { 3191 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 3192 << P.first << P.second->getSourceRange(); 3193 } 3194 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 3195 3196 if (!AllowedNameModifiers.empty()) 3197 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 3198 ErrorFound; 3199 3200 if (ErrorFound) 3201 return StmtError(); 3202 return Res; 3203 } 3204 3205 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 3206 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 3207 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 3208 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 3209 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 3210 assert(Aligneds.size() == Alignments.size()); 3211 assert(Linears.size() == LinModifiers.size()); 3212 assert(Linears.size() == Steps.size()); 3213 if (!DG || DG.get().isNull()) 3214 return DeclGroupPtrTy(); 3215 3216 if (!DG.get().isSingleDecl()) { 3217 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 3218 return DG; 3219 } 3220 auto *ADecl = DG.get().getSingleDecl(); 3221 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 3222 ADecl = FTD->getTemplatedDecl(); 3223 3224 auto *FD = dyn_cast<FunctionDecl>(ADecl); 3225 if (!FD) { 3226 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 3227 return DeclGroupPtrTy(); 3228 } 3229 3230 // OpenMP [2.8.2, declare simd construct, Description] 3231 // The parameter of the simdlen clause must be a constant positive integer 3232 // expression. 3233 ExprResult SL; 3234 if (Simdlen) 3235 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 3236 // OpenMP [2.8.2, declare simd construct, Description] 3237 // The special this pointer can be used as if was one of the arguments to the 3238 // function in any of the linear, aligned, or uniform clauses. 3239 // The uniform clause declares one or more arguments to have an invariant 3240 // value for all concurrent invocations of the function in the execution of a 3241 // single SIMD loop. 3242 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 3243 Expr *UniformedLinearThis = nullptr; 3244 for (auto *E : Uniforms) { 3245 E = E->IgnoreParenImpCasts(); 3246 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3247 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 3248 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3249 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3250 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 3251 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 3252 continue; 3253 } 3254 if (isa<CXXThisExpr>(E)) { 3255 UniformedLinearThis = E; 3256 continue; 3257 } 3258 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3259 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3260 } 3261 // OpenMP [2.8.2, declare simd construct, Description] 3262 // The aligned clause declares that the object to which each list item points 3263 // is aligned to the number of bytes expressed in the optional parameter of 3264 // the aligned clause. 3265 // The special this pointer can be used as if was one of the arguments to the 3266 // function in any of the linear, aligned, or uniform clauses. 3267 // The type of list items appearing in the aligned clause must be array, 3268 // pointer, reference to array, or reference to pointer. 3269 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 3270 Expr *AlignedThis = nullptr; 3271 for (auto *E : Aligneds) { 3272 E = E->IgnoreParenImpCasts(); 3273 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3274 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3275 auto *CanonPVD = PVD->getCanonicalDecl(); 3276 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3277 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3278 ->getCanonicalDecl() == CanonPVD) { 3279 // OpenMP [2.8.1, simd construct, Restrictions] 3280 // A list-item cannot appear in more than one aligned clause. 3281 if (AlignedArgs.count(CanonPVD) > 0) { 3282 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3283 << 1 << E->getSourceRange(); 3284 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 3285 diag::note_omp_explicit_dsa) 3286 << getOpenMPClauseName(OMPC_aligned); 3287 continue; 3288 } 3289 AlignedArgs[CanonPVD] = E; 3290 QualType QTy = PVD->getType() 3291 .getNonReferenceType() 3292 .getUnqualifiedType() 3293 .getCanonicalType(); 3294 const Type *Ty = QTy.getTypePtrOrNull(); 3295 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 3296 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 3297 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 3298 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 3299 } 3300 continue; 3301 } 3302 } 3303 if (isa<CXXThisExpr>(E)) { 3304 if (AlignedThis) { 3305 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3306 << 2 << E->getSourceRange(); 3307 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 3308 << getOpenMPClauseName(OMPC_aligned); 3309 } 3310 AlignedThis = E; 3311 continue; 3312 } 3313 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3314 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3315 } 3316 // The optional parameter of the aligned clause, alignment, must be a constant 3317 // positive integer expression. If no optional parameter is specified, 3318 // implementation-defined default alignments for SIMD instructions on the 3319 // target platforms are assumed. 3320 SmallVector<Expr *, 4> NewAligns; 3321 for (auto *E : Alignments) { 3322 ExprResult Align; 3323 if (E) 3324 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 3325 NewAligns.push_back(Align.get()); 3326 } 3327 // OpenMP [2.8.2, declare simd construct, Description] 3328 // The linear clause declares one or more list items to be private to a SIMD 3329 // lane and to have a linear relationship with respect to the iteration space 3330 // of a loop. 3331 // The special this pointer can be used as if was one of the arguments to the 3332 // function in any of the linear, aligned, or uniform clauses. 3333 // When a linear-step expression is specified in a linear clause it must be 3334 // either a constant integer expression or an integer-typed parameter that is 3335 // specified in a uniform clause on the directive. 3336 llvm::DenseMap<Decl *, Expr *> LinearArgs; 3337 const bool IsUniformedThis = UniformedLinearThis != nullptr; 3338 auto MI = LinModifiers.begin(); 3339 for (auto *E : Linears) { 3340 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 3341 ++MI; 3342 E = E->IgnoreParenImpCasts(); 3343 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3344 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3345 auto *CanonPVD = PVD->getCanonicalDecl(); 3346 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3347 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3348 ->getCanonicalDecl() == CanonPVD) { 3349 // OpenMP [2.15.3.7, linear Clause, Restrictions] 3350 // A list-item cannot appear in more than one linear clause. 3351 if (LinearArgs.count(CanonPVD) > 0) { 3352 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3353 << getOpenMPClauseName(OMPC_linear) 3354 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 3355 Diag(LinearArgs[CanonPVD]->getExprLoc(), 3356 diag::note_omp_explicit_dsa) 3357 << getOpenMPClauseName(OMPC_linear); 3358 continue; 3359 } 3360 // Each argument can appear in at most one uniform or linear clause. 3361 if (UniformedArgs.count(CanonPVD) > 0) { 3362 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3363 << getOpenMPClauseName(OMPC_linear) 3364 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 3365 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 3366 diag::note_omp_explicit_dsa) 3367 << getOpenMPClauseName(OMPC_uniform); 3368 continue; 3369 } 3370 LinearArgs[CanonPVD] = E; 3371 if (E->isValueDependent() || E->isTypeDependent() || 3372 E->isInstantiationDependent() || 3373 E->containsUnexpandedParameterPack()) 3374 continue; 3375 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 3376 PVD->getOriginalType()); 3377 continue; 3378 } 3379 } 3380 if (isa<CXXThisExpr>(E)) { 3381 if (UniformedLinearThis) { 3382 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3383 << getOpenMPClauseName(OMPC_linear) 3384 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 3385 << E->getSourceRange(); 3386 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 3387 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 3388 : OMPC_linear); 3389 continue; 3390 } 3391 UniformedLinearThis = E; 3392 if (E->isValueDependent() || E->isTypeDependent() || 3393 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3394 continue; 3395 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 3396 E->getType()); 3397 continue; 3398 } 3399 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3400 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3401 } 3402 Expr *Step = nullptr; 3403 Expr *NewStep = nullptr; 3404 SmallVector<Expr *, 4> NewSteps; 3405 for (auto *E : Steps) { 3406 // Skip the same step expression, it was checked already. 3407 if (Step == E || !E) { 3408 NewSteps.push_back(E ? NewStep : nullptr); 3409 continue; 3410 } 3411 Step = E; 3412 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 3413 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3414 auto *CanonPVD = PVD->getCanonicalDecl(); 3415 if (UniformedArgs.count(CanonPVD) == 0) { 3416 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 3417 << Step->getSourceRange(); 3418 } else if (E->isValueDependent() || E->isTypeDependent() || 3419 E->isInstantiationDependent() || 3420 E->containsUnexpandedParameterPack() || 3421 CanonPVD->getType()->hasIntegerRepresentation()) 3422 NewSteps.push_back(Step); 3423 else { 3424 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 3425 << Step->getSourceRange(); 3426 } 3427 continue; 3428 } 3429 NewStep = Step; 3430 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 3431 !Step->isInstantiationDependent() && 3432 !Step->containsUnexpandedParameterPack()) { 3433 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 3434 .get(); 3435 if (NewStep) 3436 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 3437 } 3438 NewSteps.push_back(NewStep); 3439 } 3440 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 3441 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 3442 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 3443 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 3444 const_cast<Expr **>(Linears.data()), Linears.size(), 3445 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 3446 NewSteps.data(), NewSteps.size(), SR); 3447 ADecl->addAttr(NewAttr); 3448 return ConvertDeclToDeclGroup(ADecl); 3449 } 3450 3451 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 3452 Stmt *AStmt, 3453 SourceLocation StartLoc, 3454 SourceLocation EndLoc) { 3455 if (!AStmt) 3456 return StmtError(); 3457 3458 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3459 // 1.2.2 OpenMP Language Terminology 3460 // Structured block - An executable statement with a single entry at the 3461 // top and a single exit at the bottom. 3462 // The point of exit cannot be a branch out of the structured block. 3463 // longjmp() and throw() must not violate the entry/exit criteria. 3464 CS->getCapturedDecl()->setNothrow(); 3465 3466 getCurFunction()->setHasBranchProtectedScope(); 3467 3468 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 3469 DSAStack->isCancelRegion()); 3470 } 3471 3472 namespace { 3473 /// \brief Helper class for checking canonical form of the OpenMP loops and 3474 /// extracting iteration space of each loop in the loop nest, that will be used 3475 /// for IR generation. 3476 class OpenMPIterationSpaceChecker { 3477 /// \brief Reference to Sema. 3478 Sema &SemaRef; 3479 /// \brief A location for diagnostics (when there is no some better location). 3480 SourceLocation DefaultLoc; 3481 /// \brief A location for diagnostics (when increment is not compatible). 3482 SourceLocation ConditionLoc; 3483 /// \brief A source location for referring to loop init later. 3484 SourceRange InitSrcRange; 3485 /// \brief A source location for referring to condition later. 3486 SourceRange ConditionSrcRange; 3487 /// \brief A source location for referring to increment later. 3488 SourceRange IncrementSrcRange; 3489 /// \brief Loop variable. 3490 ValueDecl *LCDecl = nullptr; 3491 /// \brief Reference to loop variable. 3492 Expr *LCRef = nullptr; 3493 /// \brief Lower bound (initializer for the var). 3494 Expr *LB = nullptr; 3495 /// \brief Upper bound. 3496 Expr *UB = nullptr; 3497 /// \brief Loop step (increment). 3498 Expr *Step = nullptr; 3499 /// \brief This flag is true when condition is one of: 3500 /// Var < UB 3501 /// Var <= UB 3502 /// UB > Var 3503 /// UB >= Var 3504 bool TestIsLessOp = false; 3505 /// \brief This flag is true when condition is strict ( < or > ). 3506 bool TestIsStrictOp = false; 3507 /// \brief This flag is true when step is subtracted on each iteration. 3508 bool SubtractStep = false; 3509 3510 public: 3511 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 3512 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 3513 /// \brief Check init-expr for canonical loop form and save loop counter 3514 /// variable - #Var and its initialization value - #LB. 3515 bool CheckInit(Stmt *S, bool EmitDiags = true); 3516 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 3517 /// for less/greater and for strict/non-strict comparison. 3518 bool CheckCond(Expr *S); 3519 /// \brief Check incr-expr for canonical loop form and return true if it 3520 /// does not conform, otherwise save loop step (#Step). 3521 bool CheckInc(Expr *S); 3522 /// \brief Return the loop counter variable. 3523 ValueDecl *GetLoopDecl() const { return LCDecl; } 3524 /// \brief Return the reference expression to loop counter variable. 3525 Expr *GetLoopDeclRefExpr() const { return LCRef; } 3526 /// \brief Source range of the loop init. 3527 SourceRange GetInitSrcRange() const { return InitSrcRange; } 3528 /// \brief Source range of the loop condition. 3529 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 3530 /// \brief Source range of the loop increment. 3531 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 3532 /// \brief True if the step should be subtracted. 3533 bool ShouldSubtractStep() const { return SubtractStep; } 3534 /// \brief Build the expression to calculate the number of iterations. 3535 Expr * 3536 BuildNumIterations(Scope *S, const bool LimitedType, 3537 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3538 /// \brief Build the precondition expression for the loops. 3539 Expr *BuildPreCond(Scope *S, Expr *Cond, 3540 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3541 /// \brief Build reference expression to the counter be used for codegen. 3542 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 3543 DSAStackTy &DSA) const; 3544 /// \brief Build reference expression to the private counter be used for 3545 /// codegen. 3546 Expr *BuildPrivateCounterVar() const; 3547 /// \brief Build initialization of the counter be used for codegen. 3548 Expr *BuildCounterInit() const; 3549 /// \brief Build step of the counter be used for codegen. 3550 Expr *BuildCounterStep() const; 3551 /// \brief Return true if any expression is dependent. 3552 bool Dependent() const; 3553 3554 private: 3555 /// \brief Check the right-hand side of an assignment in the increment 3556 /// expression. 3557 bool CheckIncRHS(Expr *RHS); 3558 /// \brief Helper to set loop counter variable and its initializer. 3559 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 3560 /// \brief Helper to set upper bound. 3561 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 3562 SourceLocation SL); 3563 /// \brief Helper to set loop increment. 3564 bool SetStep(Expr *NewStep, bool Subtract); 3565 }; 3566 3567 bool OpenMPIterationSpaceChecker::Dependent() const { 3568 if (!LCDecl) { 3569 assert(!LB && !UB && !Step); 3570 return false; 3571 } 3572 return LCDecl->getType()->isDependentType() || 3573 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 3574 (Step && Step->isValueDependent()); 3575 } 3576 3577 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 3578 Expr *NewLCRefExpr, 3579 Expr *NewLB) { 3580 // State consistency checking to ensure correct usage. 3581 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 3582 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3583 if (!NewLCDecl || !NewLB) 3584 return true; 3585 LCDecl = getCanonicalDecl(NewLCDecl); 3586 LCRef = NewLCRefExpr; 3587 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 3588 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3589 if ((Ctor->isCopyOrMoveConstructor() || 3590 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3591 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3592 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 3593 LB = NewLB; 3594 return false; 3595 } 3596 3597 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 3598 SourceRange SR, SourceLocation SL) { 3599 // State consistency checking to ensure correct usage. 3600 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 3601 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3602 if (!NewUB) 3603 return true; 3604 UB = NewUB; 3605 TestIsLessOp = LessOp; 3606 TestIsStrictOp = StrictOp; 3607 ConditionSrcRange = SR; 3608 ConditionLoc = SL; 3609 return false; 3610 } 3611 3612 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 3613 // State consistency checking to ensure correct usage. 3614 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 3615 if (!NewStep) 3616 return true; 3617 if (!NewStep->isValueDependent()) { 3618 // Check that the step is integer expression. 3619 SourceLocation StepLoc = NewStep->getLocStart(); 3620 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 3621 StepLoc, getExprAsWritten(NewStep)); 3622 if (Val.isInvalid()) 3623 return true; 3624 NewStep = Val.get(); 3625 3626 // OpenMP [2.6, Canonical Loop Form, Restrictions] 3627 // If test-expr is of form var relational-op b and relational-op is < or 3628 // <= then incr-expr must cause var to increase on each iteration of the 3629 // loop. If test-expr is of form var relational-op b and relational-op is 3630 // > or >= then incr-expr must cause var to decrease on each iteration of 3631 // the loop. 3632 // If test-expr is of form b relational-op var and relational-op is < or 3633 // <= then incr-expr must cause var to decrease on each iteration of the 3634 // loop. If test-expr is of form b relational-op var and relational-op is 3635 // > or >= then incr-expr must cause var to increase on each iteration of 3636 // the loop. 3637 llvm::APSInt Result; 3638 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 3639 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 3640 bool IsConstNeg = 3641 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 3642 bool IsConstPos = 3643 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 3644 bool IsConstZero = IsConstant && !Result.getBoolValue(); 3645 if (UB && (IsConstZero || 3646 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 3647 : (IsConstPos || (IsUnsigned && !Subtract))))) { 3648 SemaRef.Diag(NewStep->getExprLoc(), 3649 diag::err_omp_loop_incr_not_compatible) 3650 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 3651 SemaRef.Diag(ConditionLoc, 3652 diag::note_omp_loop_cond_requres_compatible_incr) 3653 << TestIsLessOp << ConditionSrcRange; 3654 return true; 3655 } 3656 if (TestIsLessOp == Subtract) { 3657 NewStep = 3658 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 3659 .get(); 3660 Subtract = !Subtract; 3661 } 3662 } 3663 3664 Step = NewStep; 3665 SubtractStep = Subtract; 3666 return false; 3667 } 3668 3669 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 3670 // Check init-expr for canonical loop form and save loop counter 3671 // variable - #Var and its initialization value - #LB. 3672 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 3673 // var = lb 3674 // integer-type var = lb 3675 // random-access-iterator-type var = lb 3676 // pointer-type var = lb 3677 // 3678 if (!S) { 3679 if (EmitDiags) { 3680 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 3681 } 3682 return true; 3683 } 3684 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3685 if (!ExprTemp->cleanupsHaveSideEffects()) 3686 S = ExprTemp->getSubExpr(); 3687 3688 InitSrcRange = S->getSourceRange(); 3689 if (Expr *E = dyn_cast<Expr>(S)) 3690 S = E->IgnoreParens(); 3691 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3692 if (BO->getOpcode() == BO_Assign) { 3693 auto *LHS = BO->getLHS()->IgnoreParens(); 3694 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3695 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3696 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3697 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3698 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 3699 } 3700 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3701 if (ME->isArrow() && 3702 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3703 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3704 } 3705 } 3706 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 3707 if (DS->isSingleDecl()) { 3708 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 3709 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 3710 // Accept non-canonical init form here but emit ext. warning. 3711 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 3712 SemaRef.Diag(S->getLocStart(), 3713 diag::ext_omp_loop_not_canonical_init) 3714 << S->getSourceRange(); 3715 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 3716 } 3717 } 3718 } 3719 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3720 if (CE->getOperator() == OO_Equal) { 3721 auto *LHS = CE->getArg(0); 3722 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3723 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3724 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3725 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3726 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 3727 } 3728 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3729 if (ME->isArrow() && 3730 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3731 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3732 } 3733 } 3734 } 3735 3736 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3737 return false; 3738 if (EmitDiags) { 3739 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 3740 << S->getSourceRange(); 3741 } 3742 return true; 3743 } 3744 3745 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 3746 /// variable (which may be the loop variable) if possible. 3747 static const ValueDecl *GetInitLCDecl(Expr *E) { 3748 if (!E) 3749 return nullptr; 3750 E = getExprAsWritten(E); 3751 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 3752 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3753 if ((Ctor->isCopyOrMoveConstructor() || 3754 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3755 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3756 E = CE->getArg(0)->IgnoreParenImpCasts(); 3757 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 3758 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 3759 return getCanonicalDecl(VD); 3760 } 3761 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 3762 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3763 return getCanonicalDecl(ME->getMemberDecl()); 3764 return nullptr; 3765 } 3766 3767 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 3768 // Check test-expr for canonical form, save upper-bound UB, flags for 3769 // less/greater and for strict/non-strict comparison. 3770 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3771 // var relational-op b 3772 // b relational-op var 3773 // 3774 if (!S) { 3775 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 3776 return true; 3777 } 3778 S = getExprAsWritten(S); 3779 SourceLocation CondLoc = S->getLocStart(); 3780 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3781 if (BO->isRelationalOp()) { 3782 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3783 return SetUB(BO->getRHS(), 3784 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 3785 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3786 BO->getSourceRange(), BO->getOperatorLoc()); 3787 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 3788 return SetUB(BO->getLHS(), 3789 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 3790 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3791 BO->getSourceRange(), BO->getOperatorLoc()); 3792 } 3793 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3794 if (CE->getNumArgs() == 2) { 3795 auto Op = CE->getOperator(); 3796 switch (Op) { 3797 case OO_Greater: 3798 case OO_GreaterEqual: 3799 case OO_Less: 3800 case OO_LessEqual: 3801 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3802 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 3803 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3804 CE->getOperatorLoc()); 3805 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 3806 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 3807 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3808 CE->getOperatorLoc()); 3809 break; 3810 default: 3811 break; 3812 } 3813 } 3814 } 3815 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3816 return false; 3817 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 3818 << S->getSourceRange() << LCDecl; 3819 return true; 3820 } 3821 3822 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 3823 // RHS of canonical loop form increment can be: 3824 // var + incr 3825 // incr + var 3826 // var - incr 3827 // 3828 RHS = RHS->IgnoreParenImpCasts(); 3829 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 3830 if (BO->isAdditiveOp()) { 3831 bool IsAdd = BO->getOpcode() == BO_Add; 3832 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3833 return SetStep(BO->getRHS(), !IsAdd); 3834 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 3835 return SetStep(BO->getLHS(), false); 3836 } 3837 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 3838 bool IsAdd = CE->getOperator() == OO_Plus; 3839 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 3840 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3841 return SetStep(CE->getArg(1), !IsAdd); 3842 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 3843 return SetStep(CE->getArg(0), false); 3844 } 3845 } 3846 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3847 return false; 3848 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3849 << RHS->getSourceRange() << LCDecl; 3850 return true; 3851 } 3852 3853 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 3854 // Check incr-expr for canonical loop form and return true if it 3855 // does not conform. 3856 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3857 // ++var 3858 // var++ 3859 // --var 3860 // var-- 3861 // var += incr 3862 // var -= incr 3863 // var = var + incr 3864 // var = incr + var 3865 // var = var - incr 3866 // 3867 if (!S) { 3868 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 3869 return true; 3870 } 3871 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3872 if (!ExprTemp->cleanupsHaveSideEffects()) 3873 S = ExprTemp->getSubExpr(); 3874 3875 IncrementSrcRange = S->getSourceRange(); 3876 S = S->IgnoreParens(); 3877 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 3878 if (UO->isIncrementDecrementOp() && 3879 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 3880 return SetStep(SemaRef 3881 .ActOnIntegerConstant(UO->getLocStart(), 3882 (UO->isDecrementOp() ? -1 : 1)) 3883 .get(), 3884 false); 3885 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3886 switch (BO->getOpcode()) { 3887 case BO_AddAssign: 3888 case BO_SubAssign: 3889 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3890 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 3891 break; 3892 case BO_Assign: 3893 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3894 return CheckIncRHS(BO->getRHS()); 3895 break; 3896 default: 3897 break; 3898 } 3899 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3900 switch (CE->getOperator()) { 3901 case OO_PlusPlus: 3902 case OO_MinusMinus: 3903 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3904 return SetStep(SemaRef 3905 .ActOnIntegerConstant( 3906 CE->getLocStart(), 3907 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 3908 .get(), 3909 false); 3910 break; 3911 case OO_PlusEqual: 3912 case OO_MinusEqual: 3913 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3914 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 3915 break; 3916 case OO_Equal: 3917 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3918 return CheckIncRHS(CE->getArg(1)); 3919 break; 3920 default: 3921 break; 3922 } 3923 } 3924 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3925 return false; 3926 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3927 << S->getSourceRange() << LCDecl; 3928 return true; 3929 } 3930 3931 static ExprResult 3932 tryBuildCapture(Sema &SemaRef, Expr *Capture, 3933 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3934 if (SemaRef.CurContext->isDependentContext()) 3935 return ExprResult(Capture); 3936 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 3937 return SemaRef.PerformImplicitConversion( 3938 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 3939 /*AllowExplicit=*/true); 3940 auto I = Captures.find(Capture); 3941 if (I != Captures.end()) 3942 return buildCapture(SemaRef, Capture, I->second); 3943 DeclRefExpr *Ref = nullptr; 3944 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 3945 Captures[Capture] = Ref; 3946 return Res; 3947 } 3948 3949 /// \brief Build the expression to calculate the number of iterations. 3950 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 3951 Scope *S, const bool LimitedType, 3952 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3953 ExprResult Diff; 3954 auto VarType = LCDecl->getType().getNonReferenceType(); 3955 if (VarType->isIntegerType() || VarType->isPointerType() || 3956 SemaRef.getLangOpts().CPlusPlus) { 3957 // Upper - Lower 3958 auto *UBExpr = TestIsLessOp ? UB : LB; 3959 auto *LBExpr = TestIsLessOp ? LB : UB; 3960 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 3961 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 3962 if (!Upper || !Lower) 3963 return nullptr; 3964 3965 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 3966 3967 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 3968 // BuildBinOp already emitted error, this one is to point user to upper 3969 // and lower bound, and to tell what is passed to 'operator-'. 3970 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 3971 << Upper->getSourceRange() << Lower->getSourceRange(); 3972 return nullptr; 3973 } 3974 } 3975 3976 if (!Diff.isUsable()) 3977 return nullptr; 3978 3979 // Upper - Lower [- 1] 3980 if (TestIsStrictOp) 3981 Diff = SemaRef.BuildBinOp( 3982 S, DefaultLoc, BO_Sub, Diff.get(), 3983 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3984 if (!Diff.isUsable()) 3985 return nullptr; 3986 3987 // Upper - Lower [- 1] + Step 3988 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 3989 if (!NewStep.isUsable()) 3990 return nullptr; 3991 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 3992 if (!Diff.isUsable()) 3993 return nullptr; 3994 3995 // Parentheses (for dumping/debugging purposes only). 3996 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 3997 if (!Diff.isUsable()) 3998 return nullptr; 3999 4000 // (Upper - Lower [- 1] + Step) / Step 4001 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 4002 if (!Diff.isUsable()) 4003 return nullptr; 4004 4005 // OpenMP runtime requires 32-bit or 64-bit loop variables. 4006 QualType Type = Diff.get()->getType(); 4007 auto &C = SemaRef.Context; 4008 bool UseVarType = VarType->hasIntegerRepresentation() && 4009 C.getTypeSize(Type) > C.getTypeSize(VarType); 4010 if (!Type->isIntegerType() || UseVarType) { 4011 unsigned NewSize = 4012 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 4013 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 4014 : Type->hasSignedIntegerRepresentation(); 4015 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 4016 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 4017 Diff = SemaRef.PerformImplicitConversion( 4018 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 4019 if (!Diff.isUsable()) 4020 return nullptr; 4021 } 4022 } 4023 if (LimitedType) { 4024 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 4025 if (NewSize != C.getTypeSize(Type)) { 4026 if (NewSize < C.getTypeSize(Type)) { 4027 assert(NewSize == 64 && "incorrect loop var size"); 4028 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 4029 << InitSrcRange << ConditionSrcRange; 4030 } 4031 QualType NewType = C.getIntTypeForBitwidth( 4032 NewSize, Type->hasSignedIntegerRepresentation() || 4033 C.getTypeSize(Type) < NewSize); 4034 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 4035 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 4036 Sema::AA_Converting, true); 4037 if (!Diff.isUsable()) 4038 return nullptr; 4039 } 4040 } 4041 } 4042 4043 return Diff.get(); 4044 } 4045 4046 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 4047 Scope *S, Expr *Cond, 4048 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 4049 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 4050 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4051 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4052 4053 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 4054 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 4055 if (!NewLB.isUsable() || !NewUB.isUsable()) 4056 return nullptr; 4057 4058 auto CondExpr = SemaRef.BuildBinOp( 4059 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 4060 : (TestIsStrictOp ? BO_GT : BO_GE), 4061 NewLB.get(), NewUB.get()); 4062 if (CondExpr.isUsable()) { 4063 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 4064 SemaRef.Context.BoolTy)) 4065 CondExpr = SemaRef.PerformImplicitConversion( 4066 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 4067 /*AllowExplicit=*/true); 4068 } 4069 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4070 // Otherwise use original loop conditon and evaluate it in runtime. 4071 return CondExpr.isUsable() ? CondExpr.get() : Cond; 4072 } 4073 4074 /// \brief Build reference expression to the counter be used for codegen. 4075 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 4076 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 4077 auto *VD = dyn_cast<VarDecl>(LCDecl); 4078 if (!VD) { 4079 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 4080 auto *Ref = buildDeclRefExpr( 4081 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 4082 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 4083 // If the loop control decl is explicitly marked as private, do not mark it 4084 // as captured again. 4085 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 4086 Captures.insert(std::make_pair(LCRef, Ref)); 4087 return Ref; 4088 } 4089 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 4090 DefaultLoc); 4091 } 4092 4093 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 4094 if (LCDecl && !LCDecl->isInvalidDecl()) { 4095 auto Type = LCDecl->getType().getNonReferenceType(); 4096 auto *PrivateVar = 4097 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 4098 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 4099 if (PrivateVar->isInvalidDecl()) 4100 return nullptr; 4101 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 4102 } 4103 return nullptr; 4104 } 4105 4106 /// \brief Build initialization of the counter to be used for codegen. 4107 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 4108 4109 /// \brief Build step of the counter be used for codegen. 4110 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 4111 4112 /// \brief Iteration space of a single for loop. 4113 struct LoopIterationSpace final { 4114 /// \brief Condition of the loop. 4115 Expr *PreCond = nullptr; 4116 /// \brief This expression calculates the number of iterations in the loop. 4117 /// It is always possible to calculate it before starting the loop. 4118 Expr *NumIterations = nullptr; 4119 /// \brief The loop counter variable. 4120 Expr *CounterVar = nullptr; 4121 /// \brief Private loop counter variable. 4122 Expr *PrivateCounterVar = nullptr; 4123 /// \brief This is initializer for the initial value of #CounterVar. 4124 Expr *CounterInit = nullptr; 4125 /// \brief This is step for the #CounterVar used to generate its update: 4126 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 4127 Expr *CounterStep = nullptr; 4128 /// \brief Should step be subtracted? 4129 bool Subtract = false; 4130 /// \brief Source range of the loop init. 4131 SourceRange InitSrcRange; 4132 /// \brief Source range of the loop condition. 4133 SourceRange CondSrcRange; 4134 /// \brief Source range of the loop increment. 4135 SourceRange IncSrcRange; 4136 }; 4137 4138 } // namespace 4139 4140 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 4141 assert(getLangOpts().OpenMP && "OpenMP is not active."); 4142 assert(Init && "Expected loop in canonical form."); 4143 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 4144 if (AssociatedLoops > 0 && 4145 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 4146 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 4147 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 4148 if (auto *D = ISC.GetLoopDecl()) { 4149 auto *VD = dyn_cast<VarDecl>(D); 4150 if (!VD) { 4151 if (auto *Private = IsOpenMPCapturedDecl(D)) 4152 VD = Private; 4153 else { 4154 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 4155 /*WithInit=*/false); 4156 VD = cast<VarDecl>(Ref->getDecl()); 4157 } 4158 } 4159 DSAStack->addLoopControlVariable(D, VD); 4160 } 4161 } 4162 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 4163 } 4164 } 4165 4166 /// \brief Called on a for stmt to check and extract its iteration space 4167 /// for further processing (such as collapsing). 4168 static bool CheckOpenMPIterationSpace( 4169 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 4170 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 4171 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 4172 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 4173 LoopIterationSpace &ResultIterSpace, 4174 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4175 // OpenMP [2.6, Canonical Loop Form] 4176 // for (init-expr; test-expr; incr-expr) structured-block 4177 auto *For = dyn_cast_or_null<ForStmt>(S); 4178 if (!For) { 4179 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 4180 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 4181 << getOpenMPDirectiveName(DKind) << NestedLoopCount 4182 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 4183 if (NestedLoopCount > 1) { 4184 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 4185 SemaRef.Diag(DSA.getConstructLoc(), 4186 diag::note_omp_collapse_ordered_expr) 4187 << 2 << CollapseLoopCountExpr->getSourceRange() 4188 << OrderedLoopCountExpr->getSourceRange(); 4189 else if (CollapseLoopCountExpr) 4190 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4191 diag::note_omp_collapse_ordered_expr) 4192 << 0 << CollapseLoopCountExpr->getSourceRange(); 4193 else 4194 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4195 diag::note_omp_collapse_ordered_expr) 4196 << 1 << OrderedLoopCountExpr->getSourceRange(); 4197 } 4198 return true; 4199 } 4200 assert(For->getBody()); 4201 4202 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 4203 4204 // Check init. 4205 auto Init = For->getInit(); 4206 if (ISC.CheckInit(Init)) 4207 return true; 4208 4209 bool HasErrors = false; 4210 4211 // Check loop variable's type. 4212 if (auto *LCDecl = ISC.GetLoopDecl()) { 4213 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 4214 4215 // OpenMP [2.6, Canonical Loop Form] 4216 // Var is one of the following: 4217 // A variable of signed or unsigned integer type. 4218 // For C++, a variable of a random access iterator type. 4219 // For C, a variable of a pointer type. 4220 auto VarType = LCDecl->getType().getNonReferenceType(); 4221 if (!VarType->isDependentType() && !VarType->isIntegerType() && 4222 !VarType->isPointerType() && 4223 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 4224 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 4225 << SemaRef.getLangOpts().CPlusPlus; 4226 HasErrors = true; 4227 } 4228 4229 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 4230 // a Construct 4231 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4232 // parallel for construct is (are) private. 4233 // The loop iteration variable in the associated for-loop of a simd 4234 // construct with just one associated for-loop is linear with a 4235 // constant-linear-step that is the increment of the associated for-loop. 4236 // Exclude loop var from the list of variables with implicitly defined data 4237 // sharing attributes. 4238 VarsWithImplicitDSA.erase(LCDecl); 4239 4240 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4241 // in a Construct, C/C++]. 4242 // The loop iteration variable in the associated for-loop of a simd 4243 // construct with just one associated for-loop may be listed in a linear 4244 // clause with a constant-linear-step that is the increment of the 4245 // associated for-loop. 4246 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4247 // parallel for construct may be listed in a private or lastprivate clause. 4248 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 4249 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 4250 // declared in the loop and it is predetermined as a private. 4251 auto PredeterminedCKind = 4252 isOpenMPSimdDirective(DKind) 4253 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 4254 : OMPC_private; 4255 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4256 DVar.CKind != PredeterminedCKind) || 4257 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 4258 isOpenMPDistributeDirective(DKind)) && 4259 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4260 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 4261 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 4262 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 4263 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 4264 << getOpenMPClauseName(PredeterminedCKind); 4265 if (DVar.RefExpr == nullptr) 4266 DVar.CKind = PredeterminedCKind; 4267 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 4268 HasErrors = true; 4269 } else if (LoopDeclRefExpr != nullptr) { 4270 // Make the loop iteration variable private (for worksharing constructs), 4271 // linear (for simd directives with the only one associated loop) or 4272 // lastprivate (for simd directives with several collapsed or ordered 4273 // loops). 4274 if (DVar.CKind == OMPC_unknown) 4275 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 4276 [](OpenMPDirectiveKind) -> bool { return true; }, 4277 /*FromParent=*/false); 4278 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 4279 } 4280 4281 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 4282 4283 // Check test-expr. 4284 HasErrors |= ISC.CheckCond(For->getCond()); 4285 4286 // Check incr-expr. 4287 HasErrors |= ISC.CheckInc(For->getInc()); 4288 } 4289 4290 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 4291 return HasErrors; 4292 4293 // Build the loop's iteration space representation. 4294 ResultIterSpace.PreCond = 4295 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 4296 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 4297 DSA.getCurScope(), 4298 (isOpenMPWorksharingDirective(DKind) || 4299 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 4300 Captures); 4301 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 4302 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 4303 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 4304 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 4305 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 4306 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 4307 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 4308 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 4309 4310 HasErrors |= (ResultIterSpace.PreCond == nullptr || 4311 ResultIterSpace.NumIterations == nullptr || 4312 ResultIterSpace.CounterVar == nullptr || 4313 ResultIterSpace.PrivateCounterVar == nullptr || 4314 ResultIterSpace.CounterInit == nullptr || 4315 ResultIterSpace.CounterStep == nullptr); 4316 4317 return HasErrors; 4318 } 4319 4320 /// \brief Build 'VarRef = Start. 4321 static ExprResult 4322 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 4323 ExprResult Start, 4324 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4325 // Build 'VarRef = Start. 4326 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 4327 if (!NewStart.isUsable()) 4328 return ExprError(); 4329 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 4330 VarRef.get()->getType())) { 4331 NewStart = SemaRef.PerformImplicitConversion( 4332 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 4333 /*AllowExplicit=*/true); 4334 if (!NewStart.isUsable()) 4335 return ExprError(); 4336 } 4337 4338 auto Init = 4339 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4340 return Init; 4341 } 4342 4343 /// \brief Build 'VarRef = Start + Iter * Step'. 4344 static ExprResult 4345 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 4346 ExprResult VarRef, ExprResult Start, ExprResult Iter, 4347 ExprResult Step, bool Subtract, 4348 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 4349 // Add parentheses (for debugging purposes only). 4350 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 4351 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 4352 !Step.isUsable()) 4353 return ExprError(); 4354 4355 ExprResult NewStep = Step; 4356 if (Captures) 4357 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 4358 if (NewStep.isInvalid()) 4359 return ExprError(); 4360 ExprResult Update = 4361 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 4362 if (!Update.isUsable()) 4363 return ExprError(); 4364 4365 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 4366 // 'VarRef = Start (+|-) Iter * Step'. 4367 ExprResult NewStart = Start; 4368 if (Captures) 4369 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 4370 if (NewStart.isInvalid()) 4371 return ExprError(); 4372 4373 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 4374 ExprResult SavedUpdate = Update; 4375 ExprResult UpdateVal; 4376 if (VarRef.get()->getType()->isOverloadableType() || 4377 NewStart.get()->getType()->isOverloadableType() || 4378 Update.get()->getType()->isOverloadableType()) { 4379 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4380 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4381 Update = 4382 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4383 if (Update.isUsable()) { 4384 UpdateVal = 4385 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 4386 VarRef.get(), SavedUpdate.get()); 4387 if (UpdateVal.isUsable()) { 4388 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 4389 UpdateVal.get()); 4390 } 4391 } 4392 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4393 } 4394 4395 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 4396 if (!Update.isUsable() || !UpdateVal.isUsable()) { 4397 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 4398 NewStart.get(), SavedUpdate.get()); 4399 if (!Update.isUsable()) 4400 return ExprError(); 4401 4402 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 4403 VarRef.get()->getType())) { 4404 Update = SemaRef.PerformImplicitConversion( 4405 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 4406 if (!Update.isUsable()) 4407 return ExprError(); 4408 } 4409 4410 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 4411 } 4412 return Update; 4413 } 4414 4415 /// \brief Convert integer expression \a E to make it have at least \a Bits 4416 /// bits. 4417 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 4418 if (E == nullptr) 4419 return ExprError(); 4420 auto &C = SemaRef.Context; 4421 QualType OldType = E->getType(); 4422 unsigned HasBits = C.getTypeSize(OldType); 4423 if (HasBits >= Bits) 4424 return ExprResult(E); 4425 // OK to convert to signed, because new type has more bits than old. 4426 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 4427 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 4428 true); 4429 } 4430 4431 /// \brief Check if the given expression \a E is a constant integer that fits 4432 /// into \a Bits bits. 4433 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 4434 if (E == nullptr) 4435 return false; 4436 llvm::APSInt Result; 4437 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 4438 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 4439 return false; 4440 } 4441 4442 /// Build preinits statement for the given declarations. 4443 static Stmt *buildPreInits(ASTContext &Context, 4444 MutableArrayRef<Decl *> PreInits) { 4445 if (!PreInits.empty()) { 4446 return new (Context) DeclStmt( 4447 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 4448 SourceLocation(), SourceLocation()); 4449 } 4450 return nullptr; 4451 } 4452 4453 /// Build preinits statement for the given declarations. 4454 static Stmt * 4455 buildPreInits(ASTContext &Context, 4456 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4457 if (!Captures.empty()) { 4458 SmallVector<Decl *, 16> PreInits; 4459 for (auto &Pair : Captures) 4460 PreInits.push_back(Pair.second->getDecl()); 4461 return buildPreInits(Context, PreInits); 4462 } 4463 return nullptr; 4464 } 4465 4466 /// Build postupdate expression for the given list of postupdates expressions. 4467 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 4468 Expr *PostUpdate = nullptr; 4469 if (!PostUpdates.empty()) { 4470 for (auto *E : PostUpdates) { 4471 Expr *ConvE = S.BuildCStyleCastExpr( 4472 E->getExprLoc(), 4473 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 4474 E->getExprLoc(), E) 4475 .get(); 4476 PostUpdate = PostUpdate 4477 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 4478 PostUpdate, ConvE) 4479 .get() 4480 : ConvE; 4481 } 4482 } 4483 return PostUpdate; 4484 } 4485 4486 /// \brief Called on a for stmt to check itself and nested loops (if any). 4487 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 4488 /// number of collapsed loops otherwise. 4489 static unsigned 4490 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 4491 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 4492 DSAStackTy &DSA, 4493 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 4494 OMPLoopDirective::HelperExprs &Built) { 4495 unsigned NestedLoopCount = 1; 4496 if (CollapseLoopCountExpr) { 4497 // Found 'collapse' clause - calculate collapse number. 4498 llvm::APSInt Result; 4499 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 4500 NestedLoopCount = Result.getLimitedValue(); 4501 } 4502 if (OrderedLoopCountExpr) { 4503 // Found 'ordered' clause - calculate collapse number. 4504 llvm::APSInt Result; 4505 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 4506 if (Result.getLimitedValue() < NestedLoopCount) { 4507 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4508 diag::err_omp_wrong_ordered_loop_count) 4509 << OrderedLoopCountExpr->getSourceRange(); 4510 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4511 diag::note_collapse_loop_count) 4512 << CollapseLoopCountExpr->getSourceRange(); 4513 } 4514 NestedLoopCount = Result.getLimitedValue(); 4515 } 4516 } 4517 // This is helper routine for loop directives (e.g., 'for', 'simd', 4518 // 'for simd', etc.). 4519 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 4520 SmallVector<LoopIterationSpace, 4> IterSpaces; 4521 IterSpaces.resize(NestedLoopCount); 4522 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 4523 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 4524 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 4525 NestedLoopCount, CollapseLoopCountExpr, 4526 OrderedLoopCountExpr, VarsWithImplicitDSA, 4527 IterSpaces[Cnt], Captures)) 4528 return 0; 4529 // Move on to the next nested for loop, or to the loop body. 4530 // OpenMP [2.8.1, simd construct, Restrictions] 4531 // All loops associated with the construct must be perfectly nested; that 4532 // is, there must be no intervening code nor any OpenMP directive between 4533 // any two loops. 4534 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 4535 } 4536 4537 Built.clear(/* size */ NestedLoopCount); 4538 4539 if (SemaRef.CurContext->isDependentContext()) 4540 return NestedLoopCount; 4541 4542 // An example of what is generated for the following code: 4543 // 4544 // #pragma omp simd collapse(2) ordered(2) 4545 // for (i = 0; i < NI; ++i) 4546 // for (k = 0; k < NK; ++k) 4547 // for (j = J0; j < NJ; j+=2) { 4548 // <loop body> 4549 // } 4550 // 4551 // We generate the code below. 4552 // Note: the loop body may be outlined in CodeGen. 4553 // Note: some counters may be C++ classes, operator- is used to find number of 4554 // iterations and operator+= to calculate counter value. 4555 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 4556 // or i64 is currently supported). 4557 // 4558 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 4559 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 4560 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 4561 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 4562 // // similar updates for vars in clauses (e.g. 'linear') 4563 // <loop body (using local i and j)> 4564 // } 4565 // i = NI; // assign final values of counters 4566 // j = NJ; 4567 // 4568 4569 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 4570 // the iteration counts of the collapsed for loops. 4571 // Precondition tests if there is at least one iteration (all conditions are 4572 // true). 4573 auto PreCond = ExprResult(IterSpaces[0].PreCond); 4574 auto N0 = IterSpaces[0].NumIterations; 4575 ExprResult LastIteration32 = WidenIterationCount( 4576 32 /* Bits */, SemaRef 4577 .PerformImplicitConversion( 4578 N0->IgnoreImpCasts(), N0->getType(), 4579 Sema::AA_Converting, /*AllowExplicit=*/true) 4580 .get(), 4581 SemaRef); 4582 ExprResult LastIteration64 = WidenIterationCount( 4583 64 /* Bits */, SemaRef 4584 .PerformImplicitConversion( 4585 N0->IgnoreImpCasts(), N0->getType(), 4586 Sema::AA_Converting, /*AllowExplicit=*/true) 4587 .get(), 4588 SemaRef); 4589 4590 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 4591 return NestedLoopCount; 4592 4593 auto &C = SemaRef.Context; 4594 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 4595 4596 Scope *CurScope = DSA.getCurScope(); 4597 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 4598 if (PreCond.isUsable()) { 4599 PreCond = 4600 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 4601 PreCond.get(), IterSpaces[Cnt].PreCond); 4602 } 4603 auto N = IterSpaces[Cnt].NumIterations; 4604 SourceLocation Loc = N->getExprLoc(); 4605 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 4606 if (LastIteration32.isUsable()) 4607 LastIteration32 = SemaRef.BuildBinOp( 4608 CurScope, Loc, BO_Mul, LastIteration32.get(), 4609 SemaRef 4610 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4611 Sema::AA_Converting, 4612 /*AllowExplicit=*/true) 4613 .get()); 4614 if (LastIteration64.isUsable()) 4615 LastIteration64 = SemaRef.BuildBinOp( 4616 CurScope, Loc, BO_Mul, LastIteration64.get(), 4617 SemaRef 4618 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4619 Sema::AA_Converting, 4620 /*AllowExplicit=*/true) 4621 .get()); 4622 } 4623 4624 // Choose either the 32-bit or 64-bit version. 4625 ExprResult LastIteration = LastIteration64; 4626 if (LastIteration32.isUsable() && 4627 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 4628 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 4629 FitsInto( 4630 32 /* Bits */, 4631 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 4632 LastIteration64.get(), SemaRef))) 4633 LastIteration = LastIteration32; 4634 QualType VType = LastIteration.get()->getType(); 4635 QualType RealVType = VType; 4636 QualType StrideVType = VType; 4637 if (isOpenMPTaskLoopDirective(DKind)) { 4638 VType = 4639 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 4640 StrideVType = 4641 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 4642 } 4643 4644 if (!LastIteration.isUsable()) 4645 return 0; 4646 4647 // Save the number of iterations. 4648 ExprResult NumIterations = LastIteration; 4649 { 4650 LastIteration = SemaRef.BuildBinOp( 4651 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 4652 LastIteration.get(), 4653 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4654 if (!LastIteration.isUsable()) 4655 return 0; 4656 } 4657 4658 // Calculate the last iteration number beforehand instead of doing this on 4659 // each iteration. Do not do this if the number of iterations may be kfold-ed. 4660 llvm::APSInt Result; 4661 bool IsConstant = 4662 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 4663 ExprResult CalcLastIteration; 4664 if (!IsConstant) { 4665 ExprResult SaveRef = 4666 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 4667 LastIteration = SaveRef; 4668 4669 // Prepare SaveRef + 1. 4670 NumIterations = SemaRef.BuildBinOp( 4671 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 4672 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4673 if (!NumIterations.isUsable()) 4674 return 0; 4675 } 4676 4677 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 4678 4679 // Build variables passed into runtime, necessary for worksharing directives. 4680 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 4681 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4682 isOpenMPDistributeDirective(DKind)) { 4683 // Lower bound variable, initialized with zero. 4684 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 4685 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 4686 SemaRef.AddInitializerToDecl(LBDecl, 4687 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4688 /*DirectInit*/ false); 4689 4690 // Upper bound variable, initialized with last iteration number. 4691 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 4692 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 4693 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 4694 /*DirectInit*/ false); 4695 4696 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 4697 // This will be used to implement clause 'lastprivate'. 4698 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 4699 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 4700 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 4701 SemaRef.AddInitializerToDecl(ILDecl, 4702 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4703 /*DirectInit*/ false); 4704 4705 // Stride variable returned by runtime (we initialize it to 1 by default). 4706 VarDecl *STDecl = 4707 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 4708 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 4709 SemaRef.AddInitializerToDecl(STDecl, 4710 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 4711 /*DirectInit*/ false); 4712 4713 // Build expression: UB = min(UB, LastIteration) 4714 // It is necessary for CodeGen of directives with static scheduling. 4715 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 4716 UB.get(), LastIteration.get()); 4717 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4718 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 4719 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 4720 CondOp.get()); 4721 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 4722 4723 // If we have a combined directive that combines 'distribute', 'for' or 4724 // 'simd' we need to be able to access the bounds of the schedule of the 4725 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 4726 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 4727 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4728 4729 // Lower bound variable, initialized with zero. 4730 VarDecl *CombLBDecl = 4731 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 4732 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 4733 SemaRef.AddInitializerToDecl( 4734 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4735 /*DirectInit*/ false); 4736 4737 // Upper bound variable, initialized with last iteration number. 4738 VarDecl *CombUBDecl = 4739 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 4740 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 4741 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 4742 /*DirectInit*/ false); 4743 4744 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 4745 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 4746 ExprResult CombCondOp = 4747 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 4748 LastIteration.get(), CombUB.get()); 4749 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 4750 CombCondOp.get()); 4751 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get()); 4752 4753 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 4754 // We expect to have at least 2 more parameters than the 'parallel' 4755 // directive does - the lower and upper bounds of the previous schedule. 4756 assert(CD->getNumParams() >= 4 && 4757 "Unexpected number of parameters in loop combined directive"); 4758 4759 // Set the proper type for the bounds given what we learned from the 4760 // enclosed loops. 4761 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 4762 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 4763 4764 // Previous lower and upper bounds are obtained from the region 4765 // parameters. 4766 PrevLB = 4767 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 4768 PrevUB = 4769 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 4770 } 4771 } 4772 4773 // Build the iteration variable and its initialization before loop. 4774 ExprResult IV; 4775 ExprResult Init, CombInit; 4776 { 4777 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 4778 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 4779 Expr *RHS = 4780 (isOpenMPWorksharingDirective(DKind) || 4781 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4782 ? LB.get() 4783 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4784 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 4785 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 4786 4787 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4788 Expr *CombRHS = 4789 (isOpenMPWorksharingDirective(DKind) || 4790 isOpenMPTaskLoopDirective(DKind) || 4791 isOpenMPDistributeDirective(DKind)) 4792 ? CombLB.get() 4793 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4794 CombInit = 4795 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 4796 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get()); 4797 } 4798 } 4799 4800 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 4801 SourceLocation CondLoc; 4802 ExprResult Cond = 4803 (isOpenMPWorksharingDirective(DKind) || 4804 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4805 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 4806 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 4807 NumIterations.get()); 4808 ExprResult CombCond; 4809 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4810 CombCond = 4811 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get()); 4812 } 4813 // Loop increment (IV = IV + 1) 4814 SourceLocation IncLoc; 4815 ExprResult Inc = 4816 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 4817 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 4818 if (!Inc.isUsable()) 4819 return 0; 4820 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 4821 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 4822 if (!Inc.isUsable()) 4823 return 0; 4824 4825 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 4826 // Used for directives with static scheduling. 4827 // In combined construct, add combined version that use CombLB and CombUB 4828 // base variables for the update 4829 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 4830 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4831 isOpenMPDistributeDirective(DKind)) { 4832 // LB + ST 4833 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 4834 if (!NextLB.isUsable()) 4835 return 0; 4836 // LB = LB + ST 4837 NextLB = 4838 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 4839 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 4840 if (!NextLB.isUsable()) 4841 return 0; 4842 // UB + ST 4843 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 4844 if (!NextUB.isUsable()) 4845 return 0; 4846 // UB = UB + ST 4847 NextUB = 4848 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 4849 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 4850 if (!NextUB.isUsable()) 4851 return 0; 4852 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4853 CombNextLB = 4854 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 4855 if (!NextLB.isUsable()) 4856 return 0; 4857 // LB = LB + ST 4858 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 4859 CombNextLB.get()); 4860 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get()); 4861 if (!CombNextLB.isUsable()) 4862 return 0; 4863 // UB + ST 4864 CombNextUB = 4865 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 4866 if (!CombNextUB.isUsable()) 4867 return 0; 4868 // UB = UB + ST 4869 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 4870 CombNextUB.get()); 4871 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get()); 4872 if (!CombNextUB.isUsable()) 4873 return 0; 4874 } 4875 } 4876 4877 // Create increment expression for distribute loop when combined in a same 4878 // directive with for as IV = IV + ST; ensure upper bound expression based 4879 // on PrevUB instead of NumIterations - used to implement 'for' when found 4880 // in combination with 'distribute', like in 'distribute parallel for' 4881 SourceLocation DistIncLoc; 4882 ExprResult DistCond, DistInc, PrevEUB; 4883 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4884 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()); 4885 assert(DistCond.isUsable() && "distribute cond expr was not built"); 4886 4887 DistInc = 4888 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 4889 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4890 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 4891 DistInc.get()); 4892 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get()); 4893 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4894 4895 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 4896 // construct 4897 SourceLocation DistEUBLoc; 4898 ExprResult IsUBGreater = 4899 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 4900 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4901 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 4902 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 4903 CondOp.get()); 4904 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get()); 4905 } 4906 4907 // Build updates and final values of the loop counters. 4908 bool HasErrors = false; 4909 Built.Counters.resize(NestedLoopCount); 4910 Built.Inits.resize(NestedLoopCount); 4911 Built.Updates.resize(NestedLoopCount); 4912 Built.Finals.resize(NestedLoopCount); 4913 SmallVector<Expr *, 4> LoopMultipliers; 4914 { 4915 ExprResult Div; 4916 // Go from inner nested loop to outer. 4917 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4918 LoopIterationSpace &IS = IterSpaces[Cnt]; 4919 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 4920 // Build: Iter = (IV / Div) % IS.NumIters 4921 // where Div is product of previous iterations' IS.NumIters. 4922 ExprResult Iter; 4923 if (Div.isUsable()) { 4924 Iter = 4925 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 4926 } else { 4927 Iter = IV; 4928 assert((Cnt == (int)NestedLoopCount - 1) && 4929 "unusable div expected on first iteration only"); 4930 } 4931 4932 if (Cnt != 0 && Iter.isUsable()) 4933 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 4934 IS.NumIterations); 4935 if (!Iter.isUsable()) { 4936 HasErrors = true; 4937 break; 4938 } 4939 4940 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 4941 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 4942 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 4943 IS.CounterVar->getExprLoc(), 4944 /*RefersToCapture=*/true); 4945 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 4946 IS.CounterInit, Captures); 4947 if (!Init.isUsable()) { 4948 HasErrors = true; 4949 break; 4950 } 4951 ExprResult Update = BuildCounterUpdate( 4952 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 4953 IS.CounterStep, IS.Subtract, &Captures); 4954 if (!Update.isUsable()) { 4955 HasErrors = true; 4956 break; 4957 } 4958 4959 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 4960 ExprResult Final = BuildCounterUpdate( 4961 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 4962 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 4963 if (!Final.isUsable()) { 4964 HasErrors = true; 4965 break; 4966 } 4967 4968 // Build Div for the next iteration: Div <- Div * IS.NumIters 4969 if (Cnt != 0) { 4970 if (Div.isUnset()) 4971 Div = IS.NumIterations; 4972 else 4973 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 4974 IS.NumIterations); 4975 4976 // Add parentheses (for debugging purposes only). 4977 if (Div.isUsable()) 4978 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 4979 if (!Div.isUsable()) { 4980 HasErrors = true; 4981 break; 4982 } 4983 LoopMultipliers.push_back(Div.get()); 4984 } 4985 if (!Update.isUsable() || !Final.isUsable()) { 4986 HasErrors = true; 4987 break; 4988 } 4989 // Save results 4990 Built.Counters[Cnt] = IS.CounterVar; 4991 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 4992 Built.Inits[Cnt] = Init.get(); 4993 Built.Updates[Cnt] = Update.get(); 4994 Built.Finals[Cnt] = Final.get(); 4995 } 4996 } 4997 4998 if (HasErrors) 4999 return 0; 5000 5001 // Save results 5002 Built.IterationVarRef = IV.get(); 5003 Built.LastIteration = LastIteration.get(); 5004 Built.NumIterations = NumIterations.get(); 5005 Built.CalcLastIteration = 5006 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 5007 Built.PreCond = PreCond.get(); 5008 Built.PreInits = buildPreInits(C, Captures); 5009 Built.Cond = Cond.get(); 5010 Built.Init = Init.get(); 5011 Built.Inc = Inc.get(); 5012 Built.LB = LB.get(); 5013 Built.UB = UB.get(); 5014 Built.IL = IL.get(); 5015 Built.ST = ST.get(); 5016 Built.EUB = EUB.get(); 5017 Built.NLB = NextLB.get(); 5018 Built.NUB = NextUB.get(); 5019 Built.PrevLB = PrevLB.get(); 5020 Built.PrevUB = PrevUB.get(); 5021 Built.DistInc = DistInc.get(); 5022 Built.PrevEUB = PrevEUB.get(); 5023 Built.DistCombinedFields.LB = CombLB.get(); 5024 Built.DistCombinedFields.UB = CombUB.get(); 5025 Built.DistCombinedFields.EUB = CombEUB.get(); 5026 Built.DistCombinedFields.Init = CombInit.get(); 5027 Built.DistCombinedFields.Cond = CombCond.get(); 5028 Built.DistCombinedFields.NLB = CombNextLB.get(); 5029 Built.DistCombinedFields.NUB = CombNextUB.get(); 5030 5031 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 5032 // Fill data for doacross depend clauses. 5033 for (auto Pair : DSA.getDoacrossDependClauses()) { 5034 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 5035 Pair.first->setCounterValue(CounterVal); 5036 else { 5037 if (NestedLoopCount != Pair.second.size() || 5038 NestedLoopCount != LoopMultipliers.size() + 1) { 5039 // Erroneous case - clause has some problems. 5040 Pair.first->setCounterValue(CounterVal); 5041 continue; 5042 } 5043 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 5044 auto I = Pair.second.rbegin(); 5045 auto IS = IterSpaces.rbegin(); 5046 auto ILM = LoopMultipliers.rbegin(); 5047 Expr *UpCounterVal = CounterVal; 5048 Expr *Multiplier = nullptr; 5049 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 5050 if (I->first) { 5051 assert(IS->CounterStep); 5052 Expr *NormalizedOffset = 5053 SemaRef 5054 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 5055 I->first, IS->CounterStep) 5056 .get(); 5057 if (Multiplier) { 5058 NormalizedOffset = 5059 SemaRef 5060 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 5061 NormalizedOffset, Multiplier) 5062 .get(); 5063 } 5064 assert(I->second == OO_Plus || I->second == OO_Minus); 5065 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 5066 UpCounterVal = SemaRef 5067 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 5068 UpCounterVal, NormalizedOffset) 5069 .get(); 5070 } 5071 Multiplier = *ILM; 5072 ++I; 5073 ++IS; 5074 ++ILM; 5075 } 5076 Pair.first->setCounterValue(UpCounterVal); 5077 } 5078 } 5079 5080 return NestedLoopCount; 5081 } 5082 5083 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 5084 auto CollapseClauses = 5085 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 5086 if (CollapseClauses.begin() != CollapseClauses.end()) 5087 return (*CollapseClauses.begin())->getNumForLoops(); 5088 return nullptr; 5089 } 5090 5091 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 5092 auto OrderedClauses = 5093 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 5094 if (OrderedClauses.begin() != OrderedClauses.end()) 5095 return (*OrderedClauses.begin())->getNumForLoops(); 5096 return nullptr; 5097 } 5098 5099 static bool checkSimdlenSafelenSpecified(Sema &S, 5100 const ArrayRef<OMPClause *> Clauses) { 5101 OMPSafelenClause *Safelen = nullptr; 5102 OMPSimdlenClause *Simdlen = nullptr; 5103 5104 for (auto *Clause : Clauses) { 5105 if (Clause->getClauseKind() == OMPC_safelen) 5106 Safelen = cast<OMPSafelenClause>(Clause); 5107 else if (Clause->getClauseKind() == OMPC_simdlen) 5108 Simdlen = cast<OMPSimdlenClause>(Clause); 5109 if (Safelen && Simdlen) 5110 break; 5111 } 5112 5113 if (Simdlen && Safelen) { 5114 llvm::APSInt SimdlenRes, SafelenRes; 5115 auto SimdlenLength = Simdlen->getSimdlen(); 5116 auto SafelenLength = Safelen->getSafelen(); 5117 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 5118 SimdlenLength->isInstantiationDependent() || 5119 SimdlenLength->containsUnexpandedParameterPack()) 5120 return false; 5121 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 5122 SafelenLength->isInstantiationDependent() || 5123 SafelenLength->containsUnexpandedParameterPack()) 5124 return false; 5125 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 5126 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 5127 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 5128 // If both simdlen and safelen clauses are specified, the value of the 5129 // simdlen parameter must be less than or equal to the value of the safelen 5130 // parameter. 5131 if (SimdlenRes > SafelenRes) { 5132 S.Diag(SimdlenLength->getExprLoc(), 5133 diag::err_omp_wrong_simdlen_safelen_values) 5134 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 5135 return true; 5136 } 5137 } 5138 return false; 5139 } 5140 5141 StmtResult Sema::ActOnOpenMPSimdDirective( 5142 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5143 SourceLocation EndLoc, 5144 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5145 if (!AStmt) 5146 return StmtError(); 5147 5148 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5149 OMPLoopDirective::HelperExprs B; 5150 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5151 // define the nested loops number. 5152 unsigned NestedLoopCount = CheckOpenMPLoop( 5153 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5154 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5155 if (NestedLoopCount == 0) 5156 return StmtError(); 5157 5158 assert((CurContext->isDependentContext() || B.builtAll()) && 5159 "omp simd loop exprs were not built"); 5160 5161 if (!CurContext->isDependentContext()) { 5162 // Finalize the clauses that need pre-built expressions for CodeGen. 5163 for (auto C : Clauses) { 5164 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5165 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5166 B.NumIterations, *this, CurScope, 5167 DSAStack)) 5168 return StmtError(); 5169 } 5170 } 5171 5172 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5173 return StmtError(); 5174 5175 getCurFunction()->setHasBranchProtectedScope(); 5176 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5177 Clauses, AStmt, B); 5178 } 5179 5180 StmtResult Sema::ActOnOpenMPForDirective( 5181 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5182 SourceLocation EndLoc, 5183 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5184 if (!AStmt) 5185 return StmtError(); 5186 5187 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5188 OMPLoopDirective::HelperExprs B; 5189 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5190 // define the nested loops number. 5191 unsigned NestedLoopCount = CheckOpenMPLoop( 5192 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5193 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5194 if (NestedLoopCount == 0) 5195 return StmtError(); 5196 5197 assert((CurContext->isDependentContext() || B.builtAll()) && 5198 "omp for loop exprs were not built"); 5199 5200 if (!CurContext->isDependentContext()) { 5201 // Finalize the clauses that need pre-built expressions for CodeGen. 5202 for (auto C : Clauses) { 5203 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5204 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5205 B.NumIterations, *this, CurScope, 5206 DSAStack)) 5207 return StmtError(); 5208 } 5209 } 5210 5211 getCurFunction()->setHasBranchProtectedScope(); 5212 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5213 Clauses, AStmt, B, DSAStack->isCancelRegion()); 5214 } 5215 5216 StmtResult Sema::ActOnOpenMPForSimdDirective( 5217 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5218 SourceLocation EndLoc, 5219 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5220 if (!AStmt) 5221 return StmtError(); 5222 5223 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5224 OMPLoopDirective::HelperExprs B; 5225 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5226 // define the nested loops number. 5227 unsigned NestedLoopCount = 5228 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 5229 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5230 VarsWithImplicitDSA, B); 5231 if (NestedLoopCount == 0) 5232 return StmtError(); 5233 5234 assert((CurContext->isDependentContext() || B.builtAll()) && 5235 "omp for simd loop exprs were not built"); 5236 5237 if (!CurContext->isDependentContext()) { 5238 // Finalize the clauses that need pre-built expressions for CodeGen. 5239 for (auto C : Clauses) { 5240 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5241 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5242 B.NumIterations, *this, CurScope, 5243 DSAStack)) 5244 return StmtError(); 5245 } 5246 } 5247 5248 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5249 return StmtError(); 5250 5251 getCurFunction()->setHasBranchProtectedScope(); 5252 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5253 Clauses, AStmt, B); 5254 } 5255 5256 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 5257 Stmt *AStmt, 5258 SourceLocation StartLoc, 5259 SourceLocation EndLoc) { 5260 if (!AStmt) 5261 return StmtError(); 5262 5263 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5264 auto BaseStmt = AStmt; 5265 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5266 BaseStmt = CS->getCapturedStmt(); 5267 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5268 auto S = C->children(); 5269 if (S.begin() == S.end()) 5270 return StmtError(); 5271 // All associated statements must be '#pragma omp section' except for 5272 // the first one. 5273 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5274 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5275 if (SectionStmt) 5276 Diag(SectionStmt->getLocStart(), 5277 diag::err_omp_sections_substmt_not_section); 5278 return StmtError(); 5279 } 5280 cast<OMPSectionDirective>(SectionStmt) 5281 ->setHasCancel(DSAStack->isCancelRegion()); 5282 } 5283 } else { 5284 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 5285 return StmtError(); 5286 } 5287 5288 getCurFunction()->setHasBranchProtectedScope(); 5289 5290 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5291 DSAStack->isCancelRegion()); 5292 } 5293 5294 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 5295 SourceLocation StartLoc, 5296 SourceLocation EndLoc) { 5297 if (!AStmt) 5298 return StmtError(); 5299 5300 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5301 5302 getCurFunction()->setHasBranchProtectedScope(); 5303 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 5304 5305 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 5306 DSAStack->isCancelRegion()); 5307 } 5308 5309 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 5310 Stmt *AStmt, 5311 SourceLocation StartLoc, 5312 SourceLocation EndLoc) { 5313 if (!AStmt) 5314 return StmtError(); 5315 5316 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5317 5318 getCurFunction()->setHasBranchProtectedScope(); 5319 5320 // OpenMP [2.7.3, single Construct, Restrictions] 5321 // The copyprivate clause must not be used with the nowait clause. 5322 OMPClause *Nowait = nullptr; 5323 OMPClause *Copyprivate = nullptr; 5324 for (auto *Clause : Clauses) { 5325 if (Clause->getClauseKind() == OMPC_nowait) 5326 Nowait = Clause; 5327 else if (Clause->getClauseKind() == OMPC_copyprivate) 5328 Copyprivate = Clause; 5329 if (Copyprivate && Nowait) { 5330 Diag(Copyprivate->getLocStart(), 5331 diag::err_omp_single_copyprivate_with_nowait); 5332 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 5333 return StmtError(); 5334 } 5335 } 5336 5337 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5338 } 5339 5340 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 5341 SourceLocation StartLoc, 5342 SourceLocation EndLoc) { 5343 if (!AStmt) 5344 return StmtError(); 5345 5346 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5347 5348 getCurFunction()->setHasBranchProtectedScope(); 5349 5350 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 5351 } 5352 5353 StmtResult Sema::ActOnOpenMPCriticalDirective( 5354 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 5355 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5356 if (!AStmt) 5357 return StmtError(); 5358 5359 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5360 5361 bool ErrorFound = false; 5362 llvm::APSInt Hint; 5363 SourceLocation HintLoc; 5364 bool DependentHint = false; 5365 for (auto *C : Clauses) { 5366 if (C->getClauseKind() == OMPC_hint) { 5367 if (!DirName.getName()) { 5368 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 5369 ErrorFound = true; 5370 } 5371 Expr *E = cast<OMPHintClause>(C)->getHint(); 5372 if (E->isTypeDependent() || E->isValueDependent() || 5373 E->isInstantiationDependent()) 5374 DependentHint = true; 5375 else { 5376 Hint = E->EvaluateKnownConstInt(Context); 5377 HintLoc = C->getLocStart(); 5378 } 5379 } 5380 } 5381 if (ErrorFound) 5382 return StmtError(); 5383 auto Pair = DSAStack->getCriticalWithHint(DirName); 5384 if (Pair.first && DirName.getName() && !DependentHint) { 5385 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 5386 Diag(StartLoc, diag::err_omp_critical_with_hint); 5387 if (HintLoc.isValid()) { 5388 Diag(HintLoc, diag::note_omp_critical_hint_here) 5389 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 5390 } else 5391 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 5392 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 5393 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 5394 << 1 5395 << C->getHint()->EvaluateKnownConstInt(Context).toString( 5396 /*Radix=*/10, /*Signed=*/false); 5397 } else 5398 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 5399 } 5400 } 5401 5402 getCurFunction()->setHasBranchProtectedScope(); 5403 5404 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 5405 Clauses, AStmt); 5406 if (!Pair.first && DirName.getName() && !DependentHint) 5407 DSAStack->addCriticalWithHint(Dir, Hint); 5408 return Dir; 5409 } 5410 5411 StmtResult Sema::ActOnOpenMPParallelForDirective( 5412 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5413 SourceLocation EndLoc, 5414 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5415 if (!AStmt) 5416 return StmtError(); 5417 5418 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5419 // 1.2.2 OpenMP Language Terminology 5420 // Structured block - An executable statement with a single entry at the 5421 // top and a single exit at the bottom. 5422 // The point of exit cannot be a branch out of the structured block. 5423 // longjmp() and throw() must not violate the entry/exit criteria. 5424 CS->getCapturedDecl()->setNothrow(); 5425 5426 OMPLoopDirective::HelperExprs B; 5427 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5428 // define the nested loops number. 5429 unsigned NestedLoopCount = 5430 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 5431 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5432 VarsWithImplicitDSA, B); 5433 if (NestedLoopCount == 0) 5434 return StmtError(); 5435 5436 assert((CurContext->isDependentContext() || B.builtAll()) && 5437 "omp parallel for loop exprs were not built"); 5438 5439 if (!CurContext->isDependentContext()) { 5440 // Finalize the clauses that need pre-built expressions for CodeGen. 5441 for (auto C : Clauses) { 5442 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5443 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5444 B.NumIterations, *this, CurScope, 5445 DSAStack)) 5446 return StmtError(); 5447 } 5448 } 5449 5450 getCurFunction()->setHasBranchProtectedScope(); 5451 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 5452 NestedLoopCount, Clauses, AStmt, B, 5453 DSAStack->isCancelRegion()); 5454 } 5455 5456 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 5457 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5458 SourceLocation EndLoc, 5459 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5460 if (!AStmt) 5461 return StmtError(); 5462 5463 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5464 // 1.2.2 OpenMP Language Terminology 5465 // Structured block - An executable statement with a single entry at the 5466 // top and a single exit at the bottom. 5467 // The point of exit cannot be a branch out of the structured block. 5468 // longjmp() and throw() must not violate the entry/exit criteria. 5469 CS->getCapturedDecl()->setNothrow(); 5470 5471 OMPLoopDirective::HelperExprs B; 5472 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5473 // define the nested loops number. 5474 unsigned NestedLoopCount = 5475 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 5476 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5477 VarsWithImplicitDSA, B); 5478 if (NestedLoopCount == 0) 5479 return StmtError(); 5480 5481 if (!CurContext->isDependentContext()) { 5482 // Finalize the clauses that need pre-built expressions for CodeGen. 5483 for (auto C : Clauses) { 5484 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5485 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5486 B.NumIterations, *this, CurScope, 5487 DSAStack)) 5488 return StmtError(); 5489 } 5490 } 5491 5492 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5493 return StmtError(); 5494 5495 getCurFunction()->setHasBranchProtectedScope(); 5496 return OMPParallelForSimdDirective::Create( 5497 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 5498 } 5499 5500 StmtResult 5501 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 5502 Stmt *AStmt, SourceLocation StartLoc, 5503 SourceLocation EndLoc) { 5504 if (!AStmt) 5505 return StmtError(); 5506 5507 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5508 auto BaseStmt = AStmt; 5509 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5510 BaseStmt = CS->getCapturedStmt(); 5511 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5512 auto S = C->children(); 5513 if (S.begin() == S.end()) 5514 return StmtError(); 5515 // All associated statements must be '#pragma omp section' except for 5516 // the first one. 5517 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5518 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5519 if (SectionStmt) 5520 Diag(SectionStmt->getLocStart(), 5521 diag::err_omp_parallel_sections_substmt_not_section); 5522 return StmtError(); 5523 } 5524 cast<OMPSectionDirective>(SectionStmt) 5525 ->setHasCancel(DSAStack->isCancelRegion()); 5526 } 5527 } else { 5528 Diag(AStmt->getLocStart(), 5529 diag::err_omp_parallel_sections_not_compound_stmt); 5530 return StmtError(); 5531 } 5532 5533 getCurFunction()->setHasBranchProtectedScope(); 5534 5535 return OMPParallelSectionsDirective::Create( 5536 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 5537 } 5538 5539 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 5540 Stmt *AStmt, SourceLocation StartLoc, 5541 SourceLocation EndLoc) { 5542 if (!AStmt) 5543 return StmtError(); 5544 5545 auto *CS = cast<CapturedStmt>(AStmt); 5546 // 1.2.2 OpenMP Language Terminology 5547 // Structured block - An executable statement with a single entry at the 5548 // top and a single exit at the bottom. 5549 // The point of exit cannot be a branch out of the structured block. 5550 // longjmp() and throw() must not violate the entry/exit criteria. 5551 CS->getCapturedDecl()->setNothrow(); 5552 5553 getCurFunction()->setHasBranchProtectedScope(); 5554 5555 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5556 DSAStack->isCancelRegion()); 5557 } 5558 5559 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 5560 SourceLocation EndLoc) { 5561 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 5562 } 5563 5564 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 5565 SourceLocation EndLoc) { 5566 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 5567 } 5568 5569 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 5570 SourceLocation EndLoc) { 5571 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 5572 } 5573 5574 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 5575 Stmt *AStmt, 5576 SourceLocation StartLoc, 5577 SourceLocation EndLoc) { 5578 if (!AStmt) 5579 return StmtError(); 5580 5581 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5582 5583 getCurFunction()->setHasBranchProtectedScope(); 5584 5585 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 5586 AStmt, 5587 DSAStack->getTaskgroupReductionRef()); 5588 } 5589 5590 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 5591 SourceLocation StartLoc, 5592 SourceLocation EndLoc) { 5593 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 5594 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 5595 } 5596 5597 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 5598 Stmt *AStmt, 5599 SourceLocation StartLoc, 5600 SourceLocation EndLoc) { 5601 OMPClause *DependFound = nullptr; 5602 OMPClause *DependSourceClause = nullptr; 5603 OMPClause *DependSinkClause = nullptr; 5604 bool ErrorFound = false; 5605 OMPThreadsClause *TC = nullptr; 5606 OMPSIMDClause *SC = nullptr; 5607 for (auto *C : Clauses) { 5608 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 5609 DependFound = C; 5610 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 5611 if (DependSourceClause) { 5612 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 5613 << getOpenMPDirectiveName(OMPD_ordered) 5614 << getOpenMPClauseName(OMPC_depend) << 2; 5615 ErrorFound = true; 5616 } else 5617 DependSourceClause = C; 5618 if (DependSinkClause) { 5619 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5620 << 0; 5621 ErrorFound = true; 5622 } 5623 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 5624 if (DependSourceClause) { 5625 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5626 << 1; 5627 ErrorFound = true; 5628 } 5629 DependSinkClause = C; 5630 } 5631 } else if (C->getClauseKind() == OMPC_threads) 5632 TC = cast<OMPThreadsClause>(C); 5633 else if (C->getClauseKind() == OMPC_simd) 5634 SC = cast<OMPSIMDClause>(C); 5635 } 5636 if (!ErrorFound && !SC && 5637 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 5638 // OpenMP [2.8.1,simd Construct, Restrictions] 5639 // An ordered construct with the simd clause is the only OpenMP construct 5640 // that can appear in the simd region. 5641 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 5642 ErrorFound = true; 5643 } else if (DependFound && (TC || SC)) { 5644 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 5645 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 5646 ErrorFound = true; 5647 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 5648 Diag(DependFound->getLocStart(), 5649 diag::err_omp_ordered_directive_without_param); 5650 ErrorFound = true; 5651 } else if (TC || Clauses.empty()) { 5652 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 5653 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 5654 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 5655 << (TC != nullptr); 5656 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 5657 ErrorFound = true; 5658 } 5659 } 5660 if ((!AStmt && !DependFound) || ErrorFound) 5661 return StmtError(); 5662 5663 if (AStmt) { 5664 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5665 5666 getCurFunction()->setHasBranchProtectedScope(); 5667 } 5668 5669 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5670 } 5671 5672 namespace { 5673 /// \brief Helper class for checking expression in 'omp atomic [update]' 5674 /// construct. 5675 class OpenMPAtomicUpdateChecker { 5676 /// \brief Error results for atomic update expressions. 5677 enum ExprAnalysisErrorCode { 5678 /// \brief A statement is not an expression statement. 5679 NotAnExpression, 5680 /// \brief Expression is not builtin binary or unary operation. 5681 NotABinaryOrUnaryExpression, 5682 /// \brief Unary operation is not post-/pre- increment/decrement operation. 5683 NotAnUnaryIncDecExpression, 5684 /// \brief An expression is not of scalar type. 5685 NotAScalarType, 5686 /// \brief A binary operation is not an assignment operation. 5687 NotAnAssignmentOp, 5688 /// \brief RHS part of the binary operation is not a binary expression. 5689 NotABinaryExpression, 5690 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 5691 /// expression. 5692 NotABinaryOperator, 5693 /// \brief RHS binary operation does not have reference to the updated LHS 5694 /// part. 5695 NotAnUpdateExpression, 5696 /// \brief No errors is found. 5697 NoError 5698 }; 5699 /// \brief Reference to Sema. 5700 Sema &SemaRef; 5701 /// \brief A location for note diagnostics (when error is found). 5702 SourceLocation NoteLoc; 5703 /// \brief 'x' lvalue part of the source atomic expression. 5704 Expr *X; 5705 /// \brief 'expr' rvalue part of the source atomic expression. 5706 Expr *E; 5707 /// \brief Helper expression of the form 5708 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5709 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5710 Expr *UpdateExpr; 5711 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 5712 /// important for non-associative operations. 5713 bool IsXLHSInRHSPart; 5714 BinaryOperatorKind Op; 5715 SourceLocation OpLoc; 5716 /// \brief true if the source expression is a postfix unary operation, false 5717 /// if it is a prefix unary operation. 5718 bool IsPostfixUpdate; 5719 5720 public: 5721 OpenMPAtomicUpdateChecker(Sema &SemaRef) 5722 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 5723 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 5724 /// \brief Check specified statement that it is suitable for 'atomic update' 5725 /// constructs and extract 'x', 'expr' and Operation from the original 5726 /// expression. If DiagId and NoteId == 0, then only check is performed 5727 /// without error notification. 5728 /// \param DiagId Diagnostic which should be emitted if error is found. 5729 /// \param NoteId Diagnostic note for the main error message. 5730 /// \return true if statement is not an update expression, false otherwise. 5731 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 5732 /// \brief Return the 'x' lvalue part of the source atomic expression. 5733 Expr *getX() const { return X; } 5734 /// \brief Return the 'expr' rvalue part of the source atomic expression. 5735 Expr *getExpr() const { return E; } 5736 /// \brief Return the update expression used in calculation of the updated 5737 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5738 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5739 Expr *getUpdateExpr() const { return UpdateExpr; } 5740 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 5741 /// false otherwise. 5742 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 5743 5744 /// \brief true if the source expression is a postfix unary operation, false 5745 /// if it is a prefix unary operation. 5746 bool isPostfixUpdate() const { return IsPostfixUpdate; } 5747 5748 private: 5749 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 5750 unsigned NoteId = 0); 5751 }; 5752 } // namespace 5753 5754 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 5755 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 5756 ExprAnalysisErrorCode ErrorFound = NoError; 5757 SourceLocation ErrorLoc, NoteLoc; 5758 SourceRange ErrorRange, NoteRange; 5759 // Allowed constructs are: 5760 // x = x binop expr; 5761 // x = expr binop x; 5762 if (AtomicBinOp->getOpcode() == BO_Assign) { 5763 X = AtomicBinOp->getLHS(); 5764 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 5765 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 5766 if (AtomicInnerBinOp->isMultiplicativeOp() || 5767 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 5768 AtomicInnerBinOp->isBitwiseOp()) { 5769 Op = AtomicInnerBinOp->getOpcode(); 5770 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 5771 auto *LHS = AtomicInnerBinOp->getLHS(); 5772 auto *RHS = AtomicInnerBinOp->getRHS(); 5773 llvm::FoldingSetNodeID XId, LHSId, RHSId; 5774 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 5775 /*Canonical=*/true); 5776 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 5777 /*Canonical=*/true); 5778 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 5779 /*Canonical=*/true); 5780 if (XId == LHSId) { 5781 E = RHS; 5782 IsXLHSInRHSPart = true; 5783 } else if (XId == RHSId) { 5784 E = LHS; 5785 IsXLHSInRHSPart = false; 5786 } else { 5787 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5788 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5789 NoteLoc = X->getExprLoc(); 5790 NoteRange = X->getSourceRange(); 5791 ErrorFound = NotAnUpdateExpression; 5792 } 5793 } else { 5794 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5795 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5796 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 5797 NoteRange = SourceRange(NoteLoc, NoteLoc); 5798 ErrorFound = NotABinaryOperator; 5799 } 5800 } else { 5801 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 5802 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 5803 ErrorFound = NotABinaryExpression; 5804 } 5805 } else { 5806 ErrorLoc = AtomicBinOp->getExprLoc(); 5807 ErrorRange = AtomicBinOp->getSourceRange(); 5808 NoteLoc = AtomicBinOp->getOperatorLoc(); 5809 NoteRange = SourceRange(NoteLoc, NoteLoc); 5810 ErrorFound = NotAnAssignmentOp; 5811 } 5812 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5813 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5814 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5815 return true; 5816 } else if (SemaRef.CurContext->isDependentContext()) 5817 E = X = UpdateExpr = nullptr; 5818 return ErrorFound != NoError; 5819 } 5820 5821 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 5822 unsigned NoteId) { 5823 ExprAnalysisErrorCode ErrorFound = NoError; 5824 SourceLocation ErrorLoc, NoteLoc; 5825 SourceRange ErrorRange, NoteRange; 5826 // Allowed constructs are: 5827 // x++; 5828 // x--; 5829 // ++x; 5830 // --x; 5831 // x binop= expr; 5832 // x = x binop expr; 5833 // x = expr binop x; 5834 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 5835 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 5836 if (AtomicBody->getType()->isScalarType() || 5837 AtomicBody->isInstantiationDependent()) { 5838 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 5839 AtomicBody->IgnoreParenImpCasts())) { 5840 // Check for Compound Assignment Operation 5841 Op = BinaryOperator::getOpForCompoundAssignment( 5842 AtomicCompAssignOp->getOpcode()); 5843 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 5844 E = AtomicCompAssignOp->getRHS(); 5845 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 5846 IsXLHSInRHSPart = true; 5847 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 5848 AtomicBody->IgnoreParenImpCasts())) { 5849 // Check for Binary Operation 5850 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 5851 return true; 5852 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 5853 AtomicBody->IgnoreParenImpCasts())) { 5854 // Check for Unary Operation 5855 if (AtomicUnaryOp->isIncrementDecrementOp()) { 5856 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 5857 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 5858 OpLoc = AtomicUnaryOp->getOperatorLoc(); 5859 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 5860 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 5861 IsXLHSInRHSPart = true; 5862 } else { 5863 ErrorFound = NotAnUnaryIncDecExpression; 5864 ErrorLoc = AtomicUnaryOp->getExprLoc(); 5865 ErrorRange = AtomicUnaryOp->getSourceRange(); 5866 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 5867 NoteRange = SourceRange(NoteLoc, NoteLoc); 5868 } 5869 } else if (!AtomicBody->isInstantiationDependent()) { 5870 ErrorFound = NotABinaryOrUnaryExpression; 5871 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 5872 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 5873 } 5874 } else { 5875 ErrorFound = NotAScalarType; 5876 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 5877 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5878 } 5879 } else { 5880 ErrorFound = NotAnExpression; 5881 NoteLoc = ErrorLoc = S->getLocStart(); 5882 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5883 } 5884 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5885 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5886 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5887 return true; 5888 } else if (SemaRef.CurContext->isDependentContext()) 5889 E = X = UpdateExpr = nullptr; 5890 if (ErrorFound == NoError && E && X) { 5891 // Build an update expression of form 'OpaqueValueExpr(x) binop 5892 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 5893 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 5894 auto *OVEX = new (SemaRef.getASTContext()) 5895 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 5896 auto *OVEExpr = new (SemaRef.getASTContext()) 5897 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 5898 auto Update = 5899 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 5900 IsXLHSInRHSPart ? OVEExpr : OVEX); 5901 if (Update.isInvalid()) 5902 return true; 5903 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 5904 Sema::AA_Casting); 5905 if (Update.isInvalid()) 5906 return true; 5907 UpdateExpr = Update.get(); 5908 } 5909 return ErrorFound != NoError; 5910 } 5911 5912 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 5913 Stmt *AStmt, 5914 SourceLocation StartLoc, 5915 SourceLocation EndLoc) { 5916 if (!AStmt) 5917 return StmtError(); 5918 5919 auto *CS = cast<CapturedStmt>(AStmt); 5920 // 1.2.2 OpenMP Language Terminology 5921 // Structured block - An executable statement with a single entry at the 5922 // top and a single exit at the bottom. 5923 // The point of exit cannot be a branch out of the structured block. 5924 // longjmp() and throw() must not violate the entry/exit criteria. 5925 OpenMPClauseKind AtomicKind = OMPC_unknown; 5926 SourceLocation AtomicKindLoc; 5927 for (auto *C : Clauses) { 5928 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 5929 C->getClauseKind() == OMPC_update || 5930 C->getClauseKind() == OMPC_capture) { 5931 if (AtomicKind != OMPC_unknown) { 5932 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 5933 << SourceRange(C->getLocStart(), C->getLocEnd()); 5934 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 5935 << getOpenMPClauseName(AtomicKind); 5936 } else { 5937 AtomicKind = C->getClauseKind(); 5938 AtomicKindLoc = C->getLocStart(); 5939 } 5940 } 5941 } 5942 5943 auto Body = CS->getCapturedStmt(); 5944 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 5945 Body = EWC->getSubExpr(); 5946 5947 Expr *X = nullptr; 5948 Expr *V = nullptr; 5949 Expr *E = nullptr; 5950 Expr *UE = nullptr; 5951 bool IsXLHSInRHSPart = false; 5952 bool IsPostfixUpdate = false; 5953 // OpenMP [2.12.6, atomic Construct] 5954 // In the next expressions: 5955 // * x and v (as applicable) are both l-value expressions with scalar type. 5956 // * During the execution of an atomic region, multiple syntactic 5957 // occurrences of x must designate the same storage location. 5958 // * Neither of v and expr (as applicable) may access the storage location 5959 // designated by x. 5960 // * Neither of x and expr (as applicable) may access the storage location 5961 // designated by v. 5962 // * expr is an expression with scalar type. 5963 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 5964 // * binop, binop=, ++, and -- are not overloaded operators. 5965 // * The expression x binop expr must be numerically equivalent to x binop 5966 // (expr). This requirement is satisfied if the operators in expr have 5967 // precedence greater than binop, or by using parentheses around expr or 5968 // subexpressions of expr. 5969 // * The expression expr binop x must be numerically equivalent to (expr) 5970 // binop x. This requirement is satisfied if the operators in expr have 5971 // precedence equal to or greater than binop, or by using parentheses around 5972 // expr or subexpressions of expr. 5973 // * For forms that allow multiple occurrences of x, the number of times 5974 // that x is evaluated is unspecified. 5975 if (AtomicKind == OMPC_read) { 5976 enum { 5977 NotAnExpression, 5978 NotAnAssignmentOp, 5979 NotAScalarType, 5980 NotAnLValue, 5981 NoError 5982 } ErrorFound = NoError; 5983 SourceLocation ErrorLoc, NoteLoc; 5984 SourceRange ErrorRange, NoteRange; 5985 // If clause is read: 5986 // v = x; 5987 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5988 auto *AtomicBinOp = 5989 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5990 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5991 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5992 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 5993 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5994 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 5995 if (!X->isLValue() || !V->isLValue()) { 5996 auto NotLValueExpr = X->isLValue() ? V : X; 5997 ErrorFound = NotAnLValue; 5998 ErrorLoc = AtomicBinOp->getExprLoc(); 5999 ErrorRange = AtomicBinOp->getSourceRange(); 6000 NoteLoc = NotLValueExpr->getExprLoc(); 6001 NoteRange = NotLValueExpr->getSourceRange(); 6002 } 6003 } else if (!X->isInstantiationDependent() || 6004 !V->isInstantiationDependent()) { 6005 auto NotScalarExpr = 6006 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6007 ? V 6008 : X; 6009 ErrorFound = NotAScalarType; 6010 ErrorLoc = AtomicBinOp->getExprLoc(); 6011 ErrorRange = AtomicBinOp->getSourceRange(); 6012 NoteLoc = NotScalarExpr->getExprLoc(); 6013 NoteRange = NotScalarExpr->getSourceRange(); 6014 } 6015 } else if (!AtomicBody->isInstantiationDependent()) { 6016 ErrorFound = NotAnAssignmentOp; 6017 ErrorLoc = AtomicBody->getExprLoc(); 6018 ErrorRange = AtomicBody->getSourceRange(); 6019 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6020 : AtomicBody->getExprLoc(); 6021 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6022 : AtomicBody->getSourceRange(); 6023 } 6024 } else { 6025 ErrorFound = NotAnExpression; 6026 NoteLoc = ErrorLoc = Body->getLocStart(); 6027 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6028 } 6029 if (ErrorFound != NoError) { 6030 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 6031 << ErrorRange; 6032 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6033 << NoteRange; 6034 return StmtError(); 6035 } else if (CurContext->isDependentContext()) 6036 V = X = nullptr; 6037 } else if (AtomicKind == OMPC_write) { 6038 enum { 6039 NotAnExpression, 6040 NotAnAssignmentOp, 6041 NotAScalarType, 6042 NotAnLValue, 6043 NoError 6044 } ErrorFound = NoError; 6045 SourceLocation ErrorLoc, NoteLoc; 6046 SourceRange ErrorRange, NoteRange; 6047 // If clause is write: 6048 // x = expr; 6049 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 6050 auto *AtomicBinOp = 6051 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6052 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6053 X = AtomicBinOp->getLHS(); 6054 E = AtomicBinOp->getRHS(); 6055 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6056 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 6057 if (!X->isLValue()) { 6058 ErrorFound = NotAnLValue; 6059 ErrorLoc = AtomicBinOp->getExprLoc(); 6060 ErrorRange = AtomicBinOp->getSourceRange(); 6061 NoteLoc = X->getExprLoc(); 6062 NoteRange = X->getSourceRange(); 6063 } 6064 } else if (!X->isInstantiationDependent() || 6065 !E->isInstantiationDependent()) { 6066 auto NotScalarExpr = 6067 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6068 ? E 6069 : X; 6070 ErrorFound = NotAScalarType; 6071 ErrorLoc = AtomicBinOp->getExprLoc(); 6072 ErrorRange = AtomicBinOp->getSourceRange(); 6073 NoteLoc = NotScalarExpr->getExprLoc(); 6074 NoteRange = NotScalarExpr->getSourceRange(); 6075 } 6076 } else if (!AtomicBody->isInstantiationDependent()) { 6077 ErrorFound = NotAnAssignmentOp; 6078 ErrorLoc = AtomicBody->getExprLoc(); 6079 ErrorRange = AtomicBody->getSourceRange(); 6080 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6081 : AtomicBody->getExprLoc(); 6082 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6083 : AtomicBody->getSourceRange(); 6084 } 6085 } else { 6086 ErrorFound = NotAnExpression; 6087 NoteLoc = ErrorLoc = Body->getLocStart(); 6088 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6089 } 6090 if (ErrorFound != NoError) { 6091 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 6092 << ErrorRange; 6093 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6094 << NoteRange; 6095 return StmtError(); 6096 } else if (CurContext->isDependentContext()) 6097 E = X = nullptr; 6098 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 6099 // If clause is update: 6100 // x++; 6101 // x--; 6102 // ++x; 6103 // --x; 6104 // x binop= expr; 6105 // x = x binop expr; 6106 // x = expr binop x; 6107 OpenMPAtomicUpdateChecker Checker(*this); 6108 if (Checker.checkStatement( 6109 Body, (AtomicKind == OMPC_update) 6110 ? diag::err_omp_atomic_update_not_expression_statement 6111 : diag::err_omp_atomic_not_expression_statement, 6112 diag::note_omp_atomic_update)) 6113 return StmtError(); 6114 if (!CurContext->isDependentContext()) { 6115 E = Checker.getExpr(); 6116 X = Checker.getX(); 6117 UE = Checker.getUpdateExpr(); 6118 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6119 } 6120 } else if (AtomicKind == OMPC_capture) { 6121 enum { 6122 NotAnAssignmentOp, 6123 NotACompoundStatement, 6124 NotTwoSubstatements, 6125 NotASpecificExpression, 6126 NoError 6127 } ErrorFound = NoError; 6128 SourceLocation ErrorLoc, NoteLoc; 6129 SourceRange ErrorRange, NoteRange; 6130 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 6131 // If clause is a capture: 6132 // v = x++; 6133 // v = x--; 6134 // v = ++x; 6135 // v = --x; 6136 // v = x binop= expr; 6137 // v = x = x binop expr; 6138 // v = x = expr binop x; 6139 auto *AtomicBinOp = 6140 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6141 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6142 V = AtomicBinOp->getLHS(); 6143 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6144 OpenMPAtomicUpdateChecker Checker(*this); 6145 if (Checker.checkStatement( 6146 Body, diag::err_omp_atomic_capture_not_expression_statement, 6147 diag::note_omp_atomic_update)) 6148 return StmtError(); 6149 E = Checker.getExpr(); 6150 X = Checker.getX(); 6151 UE = Checker.getUpdateExpr(); 6152 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6153 IsPostfixUpdate = Checker.isPostfixUpdate(); 6154 } else if (!AtomicBody->isInstantiationDependent()) { 6155 ErrorLoc = AtomicBody->getExprLoc(); 6156 ErrorRange = AtomicBody->getSourceRange(); 6157 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6158 : AtomicBody->getExprLoc(); 6159 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6160 : AtomicBody->getSourceRange(); 6161 ErrorFound = NotAnAssignmentOp; 6162 } 6163 if (ErrorFound != NoError) { 6164 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 6165 << ErrorRange; 6166 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6167 return StmtError(); 6168 } else if (CurContext->isDependentContext()) { 6169 UE = V = E = X = nullptr; 6170 } 6171 } else { 6172 // If clause is a capture: 6173 // { v = x; x = expr; } 6174 // { v = x; x++; } 6175 // { v = x; x--; } 6176 // { v = x; ++x; } 6177 // { v = x; --x; } 6178 // { v = x; x binop= expr; } 6179 // { v = x; x = x binop expr; } 6180 // { v = x; x = expr binop x; } 6181 // { x++; v = x; } 6182 // { x--; v = x; } 6183 // { ++x; v = x; } 6184 // { --x; v = x; } 6185 // { x binop= expr; v = x; } 6186 // { x = x binop expr; v = x; } 6187 // { x = expr binop x; v = x; } 6188 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 6189 // Check that this is { expr1; expr2; } 6190 if (CS->size() == 2) { 6191 auto *First = CS->body_front(); 6192 auto *Second = CS->body_back(); 6193 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 6194 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 6195 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 6196 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 6197 // Need to find what subexpression is 'v' and what is 'x'. 6198 OpenMPAtomicUpdateChecker Checker(*this); 6199 bool IsUpdateExprFound = !Checker.checkStatement(Second); 6200 BinaryOperator *BinOp = nullptr; 6201 if (IsUpdateExprFound) { 6202 BinOp = dyn_cast<BinaryOperator>(First); 6203 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6204 } 6205 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6206 // { v = x; x++; } 6207 // { v = x; x--; } 6208 // { v = x; ++x; } 6209 // { v = x; --x; } 6210 // { v = x; x binop= expr; } 6211 // { v = x; x = x binop expr; } 6212 // { v = x; x = expr binop x; } 6213 // Check that the first expression has form v = x. 6214 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6215 llvm::FoldingSetNodeID XId, PossibleXId; 6216 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6217 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6218 IsUpdateExprFound = XId == PossibleXId; 6219 if (IsUpdateExprFound) { 6220 V = BinOp->getLHS(); 6221 X = Checker.getX(); 6222 E = Checker.getExpr(); 6223 UE = Checker.getUpdateExpr(); 6224 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6225 IsPostfixUpdate = true; 6226 } 6227 } 6228 if (!IsUpdateExprFound) { 6229 IsUpdateExprFound = !Checker.checkStatement(First); 6230 BinOp = nullptr; 6231 if (IsUpdateExprFound) { 6232 BinOp = dyn_cast<BinaryOperator>(Second); 6233 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6234 } 6235 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6236 // { x++; v = x; } 6237 // { x--; v = x; } 6238 // { ++x; v = x; } 6239 // { --x; v = x; } 6240 // { x binop= expr; v = x; } 6241 // { x = x binop expr; v = x; } 6242 // { x = expr binop x; v = x; } 6243 // Check that the second expression has form v = x. 6244 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6245 llvm::FoldingSetNodeID XId, PossibleXId; 6246 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6247 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6248 IsUpdateExprFound = XId == PossibleXId; 6249 if (IsUpdateExprFound) { 6250 V = BinOp->getLHS(); 6251 X = Checker.getX(); 6252 E = Checker.getExpr(); 6253 UE = Checker.getUpdateExpr(); 6254 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6255 IsPostfixUpdate = false; 6256 } 6257 } 6258 } 6259 if (!IsUpdateExprFound) { 6260 // { v = x; x = expr; } 6261 auto *FirstExpr = dyn_cast<Expr>(First); 6262 auto *SecondExpr = dyn_cast<Expr>(Second); 6263 if (!FirstExpr || !SecondExpr || 6264 !(FirstExpr->isInstantiationDependent() || 6265 SecondExpr->isInstantiationDependent())) { 6266 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 6267 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 6268 ErrorFound = NotAnAssignmentOp; 6269 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 6270 : First->getLocStart(); 6271 NoteRange = ErrorRange = FirstBinOp 6272 ? FirstBinOp->getSourceRange() 6273 : SourceRange(ErrorLoc, ErrorLoc); 6274 } else { 6275 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 6276 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 6277 ErrorFound = NotAnAssignmentOp; 6278 NoteLoc = ErrorLoc = SecondBinOp 6279 ? SecondBinOp->getOperatorLoc() 6280 : Second->getLocStart(); 6281 NoteRange = ErrorRange = 6282 SecondBinOp ? SecondBinOp->getSourceRange() 6283 : SourceRange(ErrorLoc, ErrorLoc); 6284 } else { 6285 auto *PossibleXRHSInFirst = 6286 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 6287 auto *PossibleXLHSInSecond = 6288 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 6289 llvm::FoldingSetNodeID X1Id, X2Id; 6290 PossibleXRHSInFirst->Profile(X1Id, Context, 6291 /*Canonical=*/true); 6292 PossibleXLHSInSecond->Profile(X2Id, Context, 6293 /*Canonical=*/true); 6294 IsUpdateExprFound = X1Id == X2Id; 6295 if (IsUpdateExprFound) { 6296 V = FirstBinOp->getLHS(); 6297 X = SecondBinOp->getLHS(); 6298 E = SecondBinOp->getRHS(); 6299 UE = nullptr; 6300 IsXLHSInRHSPart = false; 6301 IsPostfixUpdate = true; 6302 } else { 6303 ErrorFound = NotASpecificExpression; 6304 ErrorLoc = FirstBinOp->getExprLoc(); 6305 ErrorRange = FirstBinOp->getSourceRange(); 6306 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 6307 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 6308 } 6309 } 6310 } 6311 } 6312 } 6313 } else { 6314 NoteLoc = ErrorLoc = Body->getLocStart(); 6315 NoteRange = ErrorRange = 6316 SourceRange(Body->getLocStart(), Body->getLocStart()); 6317 ErrorFound = NotTwoSubstatements; 6318 } 6319 } else { 6320 NoteLoc = ErrorLoc = Body->getLocStart(); 6321 NoteRange = ErrorRange = 6322 SourceRange(Body->getLocStart(), Body->getLocStart()); 6323 ErrorFound = NotACompoundStatement; 6324 } 6325 if (ErrorFound != NoError) { 6326 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 6327 << ErrorRange; 6328 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6329 return StmtError(); 6330 } else if (CurContext->isDependentContext()) { 6331 UE = V = E = X = nullptr; 6332 } 6333 } 6334 } 6335 6336 getCurFunction()->setHasBranchProtectedScope(); 6337 6338 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6339 X, V, E, UE, IsXLHSInRHSPart, 6340 IsPostfixUpdate); 6341 } 6342 6343 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 6344 Stmt *AStmt, 6345 SourceLocation StartLoc, 6346 SourceLocation EndLoc) { 6347 if (!AStmt) 6348 return StmtError(); 6349 6350 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6351 // 1.2.2 OpenMP Language Terminology 6352 // Structured block - An executable statement with a single entry at the 6353 // top and a single exit at the bottom. 6354 // The point of exit cannot be a branch out of the structured block. 6355 // longjmp() and throw() must not violate the entry/exit criteria. 6356 CS->getCapturedDecl()->setNothrow(); 6357 6358 // OpenMP [2.16, Nesting of Regions] 6359 // If specified, a teams construct must be contained within a target 6360 // construct. That target construct must contain no statements or directives 6361 // outside of the teams construct. 6362 if (DSAStack->hasInnerTeamsRegion()) { 6363 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 6364 bool OMPTeamsFound = true; 6365 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 6366 auto I = CS->body_begin(); 6367 while (I != CS->body_end()) { 6368 auto *OED = dyn_cast<OMPExecutableDirective>(*I); 6369 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 6370 OMPTeamsFound = false; 6371 break; 6372 } 6373 ++I; 6374 } 6375 assert(I != CS->body_end() && "Not found statement"); 6376 S = *I; 6377 } else { 6378 auto *OED = dyn_cast<OMPExecutableDirective>(S); 6379 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 6380 } 6381 if (!OMPTeamsFound) { 6382 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 6383 Diag(DSAStack->getInnerTeamsRegionLoc(), 6384 diag::note_omp_nested_teams_construct_here); 6385 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 6386 << isa<OMPExecutableDirective>(S); 6387 return StmtError(); 6388 } 6389 } 6390 6391 getCurFunction()->setHasBranchProtectedScope(); 6392 6393 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6394 } 6395 6396 StmtResult 6397 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 6398 Stmt *AStmt, SourceLocation StartLoc, 6399 SourceLocation EndLoc) { 6400 if (!AStmt) 6401 return StmtError(); 6402 6403 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6404 // 1.2.2 OpenMP Language Terminology 6405 // Structured block - An executable statement with a single entry at the 6406 // top and a single exit at the bottom. 6407 // The point of exit cannot be a branch out of the structured block. 6408 // longjmp() and throw() must not violate the entry/exit criteria. 6409 CS->getCapturedDecl()->setNothrow(); 6410 6411 getCurFunction()->setHasBranchProtectedScope(); 6412 6413 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6414 AStmt); 6415 } 6416 6417 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 6418 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6419 SourceLocation EndLoc, 6420 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6421 if (!AStmt) 6422 return StmtError(); 6423 6424 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6425 // 1.2.2 OpenMP Language Terminology 6426 // Structured block - An executable statement with a single entry at the 6427 // top and a single exit at the bottom. 6428 // The point of exit cannot be a branch out of the structured block. 6429 // longjmp() and throw() must not violate the entry/exit criteria. 6430 CS->getCapturedDecl()->setNothrow(); 6431 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 6432 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6433 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6434 // 1.2.2 OpenMP Language Terminology 6435 // Structured block - An executable statement with a single entry at the 6436 // top and a single exit at the bottom. 6437 // The point of exit cannot be a branch out of the structured block. 6438 // longjmp() and throw() must not violate the entry/exit criteria. 6439 CS->getCapturedDecl()->setNothrow(); 6440 } 6441 6442 OMPLoopDirective::HelperExprs B; 6443 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6444 // define the nested loops number. 6445 unsigned NestedLoopCount = 6446 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 6447 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 6448 VarsWithImplicitDSA, B); 6449 if (NestedLoopCount == 0) 6450 return StmtError(); 6451 6452 assert((CurContext->isDependentContext() || B.builtAll()) && 6453 "omp target parallel for loop exprs were not built"); 6454 6455 if (!CurContext->isDependentContext()) { 6456 // Finalize the clauses that need pre-built expressions for CodeGen. 6457 for (auto C : Clauses) { 6458 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6459 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6460 B.NumIterations, *this, CurScope, 6461 DSAStack)) 6462 return StmtError(); 6463 } 6464 } 6465 6466 getCurFunction()->setHasBranchProtectedScope(); 6467 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 6468 NestedLoopCount, Clauses, AStmt, 6469 B, DSAStack->isCancelRegion()); 6470 } 6471 6472 /// Check for existence of a map clause in the list of clauses. 6473 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 6474 const OpenMPClauseKind K) { 6475 return llvm::any_of( 6476 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 6477 } 6478 6479 template <typename... Params> 6480 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 6481 const Params... ClauseTypes) { 6482 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 6483 } 6484 6485 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 6486 Stmt *AStmt, 6487 SourceLocation StartLoc, 6488 SourceLocation EndLoc) { 6489 if (!AStmt) 6490 return StmtError(); 6491 6492 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6493 6494 // OpenMP [2.10.1, Restrictions, p. 97] 6495 // At least one map clause must appear on the directive. 6496 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { 6497 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6498 << "'map' or 'use_device_ptr'" 6499 << getOpenMPDirectiveName(OMPD_target_data); 6500 return StmtError(); 6501 } 6502 6503 getCurFunction()->setHasBranchProtectedScope(); 6504 6505 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6506 AStmt); 6507 } 6508 6509 StmtResult 6510 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 6511 SourceLocation StartLoc, 6512 SourceLocation EndLoc, Stmt *AStmt) { 6513 if (!AStmt) 6514 return StmtError(); 6515 6516 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6517 // 1.2.2 OpenMP Language Terminology 6518 // Structured block - An executable statement with a single entry at the 6519 // top and a single exit at the bottom. 6520 // The point of exit cannot be a branch out of the structured block. 6521 // longjmp() and throw() must not violate the entry/exit criteria. 6522 CS->getCapturedDecl()->setNothrow(); 6523 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 6524 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6525 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6526 // 1.2.2 OpenMP Language Terminology 6527 // Structured block - An executable statement with a single entry at the 6528 // top and a single exit at the bottom. 6529 // The point of exit cannot be a branch out of the structured block. 6530 // longjmp() and throw() must not violate the entry/exit criteria. 6531 CS->getCapturedDecl()->setNothrow(); 6532 } 6533 6534 // OpenMP [2.10.2, Restrictions, p. 99] 6535 // At least one map clause must appear on the directive. 6536 if (!hasClauses(Clauses, OMPC_map)) { 6537 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6538 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 6539 return StmtError(); 6540 } 6541 6542 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6543 AStmt); 6544 } 6545 6546 StmtResult 6547 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 6548 SourceLocation StartLoc, 6549 SourceLocation EndLoc, Stmt *AStmt) { 6550 if (!AStmt) 6551 return StmtError(); 6552 6553 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6554 // 1.2.2 OpenMP Language Terminology 6555 // Structured block - An executable statement with a single entry at the 6556 // top and a single exit at the bottom. 6557 // The point of exit cannot be a branch out of the structured block. 6558 // longjmp() and throw() must not violate the entry/exit criteria. 6559 CS->getCapturedDecl()->setNothrow(); 6560 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 6561 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6562 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6563 // 1.2.2 OpenMP Language Terminology 6564 // Structured block - An executable statement with a single entry at the 6565 // top and a single exit at the bottom. 6566 // The point of exit cannot be a branch out of the structured block. 6567 // longjmp() and throw() must not violate the entry/exit criteria. 6568 CS->getCapturedDecl()->setNothrow(); 6569 } 6570 6571 // OpenMP [2.10.3, Restrictions, p. 102] 6572 // At least one map clause must appear on the directive. 6573 if (!hasClauses(Clauses, OMPC_map)) { 6574 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6575 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 6576 return StmtError(); 6577 } 6578 6579 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6580 AStmt); 6581 } 6582 6583 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 6584 SourceLocation StartLoc, 6585 SourceLocation EndLoc, 6586 Stmt *AStmt) { 6587 if (!AStmt) 6588 return StmtError(); 6589 6590 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6591 // 1.2.2 OpenMP Language Terminology 6592 // Structured block - An executable statement with a single entry at the 6593 // top and a single exit at the bottom. 6594 // The point of exit cannot be a branch out of the structured block. 6595 // longjmp() and throw() must not violate the entry/exit criteria. 6596 CS->getCapturedDecl()->setNothrow(); 6597 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 6598 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6599 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6600 // 1.2.2 OpenMP Language Terminology 6601 // Structured block - An executable statement with a single entry at the 6602 // top and a single exit at the bottom. 6603 // The point of exit cannot be a branch out of the structured block. 6604 // longjmp() and throw() must not violate the entry/exit criteria. 6605 CS->getCapturedDecl()->setNothrow(); 6606 } 6607 6608 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 6609 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 6610 return StmtError(); 6611 } 6612 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 6613 AStmt); 6614 } 6615 6616 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 6617 Stmt *AStmt, SourceLocation StartLoc, 6618 SourceLocation EndLoc) { 6619 if (!AStmt) 6620 return StmtError(); 6621 6622 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6623 // 1.2.2 OpenMP Language Terminology 6624 // Structured block - An executable statement with a single entry at the 6625 // top and a single exit at the bottom. 6626 // The point of exit cannot be a branch out of the structured block. 6627 // longjmp() and throw() must not violate the entry/exit criteria. 6628 CS->getCapturedDecl()->setNothrow(); 6629 6630 getCurFunction()->setHasBranchProtectedScope(); 6631 6632 DSAStack->setParentTeamsRegionLoc(StartLoc); 6633 6634 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6635 } 6636 6637 StmtResult 6638 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 6639 SourceLocation EndLoc, 6640 OpenMPDirectiveKind CancelRegion) { 6641 if (DSAStack->isParentNowaitRegion()) { 6642 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 6643 return StmtError(); 6644 } 6645 if (DSAStack->isParentOrderedRegion()) { 6646 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 6647 return StmtError(); 6648 } 6649 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 6650 CancelRegion); 6651 } 6652 6653 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 6654 SourceLocation StartLoc, 6655 SourceLocation EndLoc, 6656 OpenMPDirectiveKind CancelRegion) { 6657 if (DSAStack->isParentNowaitRegion()) { 6658 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 6659 return StmtError(); 6660 } 6661 if (DSAStack->isParentOrderedRegion()) { 6662 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 6663 return StmtError(); 6664 } 6665 DSAStack->setParentCancelRegion(/*Cancel=*/true); 6666 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6667 CancelRegion); 6668 } 6669 6670 static bool checkGrainsizeNumTasksClauses(Sema &S, 6671 ArrayRef<OMPClause *> Clauses) { 6672 OMPClause *PrevClause = nullptr; 6673 bool ErrorFound = false; 6674 for (auto *C : Clauses) { 6675 if (C->getClauseKind() == OMPC_grainsize || 6676 C->getClauseKind() == OMPC_num_tasks) { 6677 if (!PrevClause) 6678 PrevClause = C; 6679 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 6680 S.Diag(C->getLocStart(), 6681 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 6682 << getOpenMPClauseName(C->getClauseKind()) 6683 << getOpenMPClauseName(PrevClause->getClauseKind()); 6684 S.Diag(PrevClause->getLocStart(), 6685 diag::note_omp_previous_grainsize_num_tasks) 6686 << getOpenMPClauseName(PrevClause->getClauseKind()); 6687 ErrorFound = true; 6688 } 6689 } 6690 } 6691 return ErrorFound; 6692 } 6693 6694 static bool checkReductionClauseWithNogroup(Sema &S, 6695 ArrayRef<OMPClause *> Clauses) { 6696 OMPClause *ReductionClause = nullptr; 6697 OMPClause *NogroupClause = nullptr; 6698 for (auto *C : Clauses) { 6699 if (C->getClauseKind() == OMPC_reduction) { 6700 ReductionClause = C; 6701 if (NogroupClause) 6702 break; 6703 continue; 6704 } 6705 if (C->getClauseKind() == OMPC_nogroup) { 6706 NogroupClause = C; 6707 if (ReductionClause) 6708 break; 6709 continue; 6710 } 6711 } 6712 if (ReductionClause && NogroupClause) { 6713 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup) 6714 << SourceRange(NogroupClause->getLocStart(), 6715 NogroupClause->getLocEnd()); 6716 return true; 6717 } 6718 return false; 6719 } 6720 6721 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 6722 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6723 SourceLocation EndLoc, 6724 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6725 if (!AStmt) 6726 return StmtError(); 6727 6728 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6729 OMPLoopDirective::HelperExprs B; 6730 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6731 // define the nested loops number. 6732 unsigned NestedLoopCount = 6733 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 6734 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6735 VarsWithImplicitDSA, B); 6736 if (NestedLoopCount == 0) 6737 return StmtError(); 6738 6739 assert((CurContext->isDependentContext() || B.builtAll()) && 6740 "omp for loop exprs were not built"); 6741 6742 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6743 // The grainsize clause and num_tasks clause are mutually exclusive and may 6744 // not appear on the same taskloop directive. 6745 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6746 return StmtError(); 6747 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6748 // If a reduction clause is present on the taskloop directive, the nogroup 6749 // clause must not be specified. 6750 if (checkReductionClauseWithNogroup(*this, Clauses)) 6751 return StmtError(); 6752 6753 getCurFunction()->setHasBranchProtectedScope(); 6754 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 6755 NestedLoopCount, Clauses, AStmt, B); 6756 } 6757 6758 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 6759 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6760 SourceLocation EndLoc, 6761 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6762 if (!AStmt) 6763 return StmtError(); 6764 6765 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6766 OMPLoopDirective::HelperExprs B; 6767 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6768 // define the nested loops number. 6769 unsigned NestedLoopCount = 6770 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 6771 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6772 VarsWithImplicitDSA, B); 6773 if (NestedLoopCount == 0) 6774 return StmtError(); 6775 6776 assert((CurContext->isDependentContext() || B.builtAll()) && 6777 "omp for loop exprs were not built"); 6778 6779 if (!CurContext->isDependentContext()) { 6780 // Finalize the clauses that need pre-built expressions for CodeGen. 6781 for (auto C : Clauses) { 6782 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6783 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6784 B.NumIterations, *this, CurScope, 6785 DSAStack)) 6786 return StmtError(); 6787 } 6788 } 6789 6790 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6791 // The grainsize clause and num_tasks clause are mutually exclusive and may 6792 // not appear on the same taskloop directive. 6793 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6794 return StmtError(); 6795 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6796 // If a reduction clause is present on the taskloop directive, the nogroup 6797 // clause must not be specified. 6798 if (checkReductionClauseWithNogroup(*this, Clauses)) 6799 return StmtError(); 6800 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6801 return StmtError(); 6802 6803 getCurFunction()->setHasBranchProtectedScope(); 6804 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 6805 NestedLoopCount, Clauses, AStmt, B); 6806 } 6807 6808 StmtResult Sema::ActOnOpenMPDistributeDirective( 6809 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6810 SourceLocation EndLoc, 6811 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6812 if (!AStmt) 6813 return StmtError(); 6814 6815 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6816 OMPLoopDirective::HelperExprs B; 6817 // In presence of clause 'collapse' with number of loops, it will 6818 // define the nested loops number. 6819 unsigned NestedLoopCount = 6820 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 6821 nullptr /*ordered not a clause on distribute*/, AStmt, 6822 *this, *DSAStack, VarsWithImplicitDSA, B); 6823 if (NestedLoopCount == 0) 6824 return StmtError(); 6825 6826 assert((CurContext->isDependentContext() || B.builtAll()) && 6827 "omp for loop exprs were not built"); 6828 6829 getCurFunction()->setHasBranchProtectedScope(); 6830 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 6831 NestedLoopCount, Clauses, AStmt, B); 6832 } 6833 6834 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 6835 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6836 SourceLocation EndLoc, 6837 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6838 if (!AStmt) 6839 return StmtError(); 6840 6841 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6842 // 1.2.2 OpenMP Language Terminology 6843 // Structured block - An executable statement with a single entry at the 6844 // top and a single exit at the bottom. 6845 // The point of exit cannot be a branch out of the structured block. 6846 // longjmp() and throw() must not violate the entry/exit criteria. 6847 CS->getCapturedDecl()->setNothrow(); 6848 for (int ThisCaptureLevel = 6849 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 6850 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6851 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6852 // 1.2.2 OpenMP Language Terminology 6853 // Structured block - An executable statement with a single entry at the 6854 // top and a single exit at the bottom. 6855 // The point of exit cannot be a branch out of the structured block. 6856 // longjmp() and throw() must not violate the entry/exit criteria. 6857 CS->getCapturedDecl()->setNothrow(); 6858 } 6859 6860 OMPLoopDirective::HelperExprs B; 6861 // In presence of clause 'collapse' with number of loops, it will 6862 // define the nested loops number. 6863 unsigned NestedLoopCount = CheckOpenMPLoop( 6864 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6865 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 6866 VarsWithImplicitDSA, B); 6867 if (NestedLoopCount == 0) 6868 return StmtError(); 6869 6870 assert((CurContext->isDependentContext() || B.builtAll()) && 6871 "omp for loop exprs were not built"); 6872 6873 getCurFunction()->setHasBranchProtectedScope(); 6874 return OMPDistributeParallelForDirective::Create( 6875 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 6876 DSAStack->isCancelRegion()); 6877 } 6878 6879 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 6880 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6881 SourceLocation EndLoc, 6882 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6883 if (!AStmt) 6884 return StmtError(); 6885 6886 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6887 // 1.2.2 OpenMP Language Terminology 6888 // Structured block - An executable statement with a single entry at the 6889 // top and a single exit at the bottom. 6890 // The point of exit cannot be a branch out of the structured block. 6891 // longjmp() and throw() must not violate the entry/exit criteria. 6892 CS->getCapturedDecl()->setNothrow(); 6893 for (int ThisCaptureLevel = 6894 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 6895 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6896 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6897 // 1.2.2 OpenMP Language Terminology 6898 // Structured block - An executable statement with a single entry at the 6899 // top and a single exit at the bottom. 6900 // The point of exit cannot be a branch out of the structured block. 6901 // longjmp() and throw() must not violate the entry/exit criteria. 6902 CS->getCapturedDecl()->setNothrow(); 6903 } 6904 6905 OMPLoopDirective::HelperExprs B; 6906 // In presence of clause 'collapse' with number of loops, it will 6907 // define the nested loops number. 6908 unsigned NestedLoopCount = CheckOpenMPLoop( 6909 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6910 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 6911 VarsWithImplicitDSA, B); 6912 if (NestedLoopCount == 0) 6913 return StmtError(); 6914 6915 assert((CurContext->isDependentContext() || B.builtAll()) && 6916 "omp for loop exprs were not built"); 6917 6918 if (!CurContext->isDependentContext()) { 6919 // Finalize the clauses that need pre-built expressions for CodeGen. 6920 for (auto C : Clauses) { 6921 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6922 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6923 B.NumIterations, *this, CurScope, 6924 DSAStack)) 6925 return StmtError(); 6926 } 6927 } 6928 6929 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6930 return StmtError(); 6931 6932 getCurFunction()->setHasBranchProtectedScope(); 6933 return OMPDistributeParallelForSimdDirective::Create( 6934 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6935 } 6936 6937 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 6938 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6939 SourceLocation EndLoc, 6940 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6941 if (!AStmt) 6942 return StmtError(); 6943 6944 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6945 // 1.2.2 OpenMP Language Terminology 6946 // Structured block - An executable statement with a single entry at the 6947 // top and a single exit at the bottom. 6948 // The point of exit cannot be a branch out of the structured block. 6949 // longjmp() and throw() must not violate the entry/exit criteria. 6950 CS->getCapturedDecl()->setNothrow(); 6951 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 6952 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6953 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6954 // 1.2.2 OpenMP Language Terminology 6955 // Structured block - An executable statement with a single entry at the 6956 // top and a single exit at the bottom. 6957 // The point of exit cannot be a branch out of the structured block. 6958 // longjmp() and throw() must not violate the entry/exit criteria. 6959 CS->getCapturedDecl()->setNothrow(); 6960 } 6961 6962 OMPLoopDirective::HelperExprs B; 6963 // In presence of clause 'collapse' with number of loops, it will 6964 // define the nested loops number. 6965 unsigned NestedLoopCount = 6966 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 6967 nullptr /*ordered not a clause on distribute*/, CS, *this, 6968 *DSAStack, VarsWithImplicitDSA, B); 6969 if (NestedLoopCount == 0) 6970 return StmtError(); 6971 6972 assert((CurContext->isDependentContext() || B.builtAll()) && 6973 "omp for loop exprs were not built"); 6974 6975 if (!CurContext->isDependentContext()) { 6976 // Finalize the clauses that need pre-built expressions for CodeGen. 6977 for (auto C : Clauses) { 6978 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6979 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6980 B.NumIterations, *this, CurScope, 6981 DSAStack)) 6982 return StmtError(); 6983 } 6984 } 6985 6986 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6987 return StmtError(); 6988 6989 getCurFunction()->setHasBranchProtectedScope(); 6990 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 6991 NestedLoopCount, Clauses, AStmt, B); 6992 } 6993 6994 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 6995 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6996 SourceLocation EndLoc, 6997 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6998 if (!AStmt) 6999 return StmtError(); 7000 7001 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7002 // 1.2.2 OpenMP Language Terminology 7003 // Structured block - An executable statement with a single entry at the 7004 // top and a single exit at the bottom. 7005 // The point of exit cannot be a branch out of the structured block. 7006 // longjmp() and throw() must not violate the entry/exit criteria. 7007 CS->getCapturedDecl()->setNothrow(); 7008 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 7009 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7010 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7011 // 1.2.2 OpenMP Language Terminology 7012 // Structured block - An executable statement with a single entry at the 7013 // top and a single exit at the bottom. 7014 // The point of exit cannot be a branch out of the structured block. 7015 // longjmp() and throw() must not violate the entry/exit criteria. 7016 CS->getCapturedDecl()->setNothrow(); 7017 } 7018 7019 OMPLoopDirective::HelperExprs B; 7020 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7021 // define the nested loops number. 7022 unsigned NestedLoopCount = CheckOpenMPLoop( 7023 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 7024 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7025 VarsWithImplicitDSA, B); 7026 if (NestedLoopCount == 0) 7027 return StmtError(); 7028 7029 assert((CurContext->isDependentContext() || B.builtAll()) && 7030 "omp target parallel for simd loop exprs were not built"); 7031 7032 if (!CurContext->isDependentContext()) { 7033 // Finalize the clauses that need pre-built expressions for CodeGen. 7034 for (auto C : Clauses) { 7035 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7036 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7037 B.NumIterations, *this, CurScope, 7038 DSAStack)) 7039 return StmtError(); 7040 } 7041 } 7042 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7043 return StmtError(); 7044 7045 getCurFunction()->setHasBranchProtectedScope(); 7046 return OMPTargetParallelForSimdDirective::Create( 7047 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7048 } 7049 7050 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 7051 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7052 SourceLocation EndLoc, 7053 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7054 if (!AStmt) 7055 return StmtError(); 7056 7057 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7058 // 1.2.2 OpenMP Language Terminology 7059 // Structured block - An executable statement with a single entry at the 7060 // top and a single exit at the bottom. 7061 // The point of exit cannot be a branch out of the structured block. 7062 // longjmp() and throw() must not violate the entry/exit criteria. 7063 CS->getCapturedDecl()->setNothrow(); 7064 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 7065 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7066 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7067 // 1.2.2 OpenMP Language Terminology 7068 // Structured block - An executable statement with a single entry at the 7069 // top and a single exit at the bottom. 7070 // The point of exit cannot be a branch out of the structured block. 7071 // longjmp() and throw() must not violate the entry/exit criteria. 7072 CS->getCapturedDecl()->setNothrow(); 7073 } 7074 7075 OMPLoopDirective::HelperExprs B; 7076 // In presence of clause 'collapse' with number of loops, it will define the 7077 // nested loops number. 7078 unsigned NestedLoopCount = 7079 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 7080 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7081 VarsWithImplicitDSA, B); 7082 if (NestedLoopCount == 0) 7083 return StmtError(); 7084 7085 assert((CurContext->isDependentContext() || B.builtAll()) && 7086 "omp target simd loop exprs were not built"); 7087 7088 if (!CurContext->isDependentContext()) { 7089 // Finalize the clauses that need pre-built expressions for CodeGen. 7090 for (auto C : Clauses) { 7091 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7092 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7093 B.NumIterations, *this, CurScope, 7094 DSAStack)) 7095 return StmtError(); 7096 } 7097 } 7098 7099 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7100 return StmtError(); 7101 7102 getCurFunction()->setHasBranchProtectedScope(); 7103 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 7104 NestedLoopCount, Clauses, AStmt, B); 7105 } 7106 7107 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 7108 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7109 SourceLocation EndLoc, 7110 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7111 if (!AStmt) 7112 return StmtError(); 7113 7114 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7115 // 1.2.2 OpenMP Language Terminology 7116 // Structured block - An executable statement with a single entry at the 7117 // top and a single exit at the bottom. 7118 // The point of exit cannot be a branch out of the structured block. 7119 // longjmp() and throw() must not violate the entry/exit criteria. 7120 CS->getCapturedDecl()->setNothrow(); 7121 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 7122 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7123 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7124 // 1.2.2 OpenMP Language Terminology 7125 // Structured block - An executable statement with a single entry at the 7126 // top and a single exit at the bottom. 7127 // The point of exit cannot be a branch out of the structured block. 7128 // longjmp() and throw() must not violate the entry/exit criteria. 7129 CS->getCapturedDecl()->setNothrow(); 7130 } 7131 7132 OMPLoopDirective::HelperExprs B; 7133 // In presence of clause 'collapse' with number of loops, it will 7134 // define the nested loops number. 7135 unsigned NestedLoopCount = 7136 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 7137 nullptr /*ordered not a clause on distribute*/, CS, *this, 7138 *DSAStack, VarsWithImplicitDSA, B); 7139 if (NestedLoopCount == 0) 7140 return StmtError(); 7141 7142 assert((CurContext->isDependentContext() || B.builtAll()) && 7143 "omp teams distribute loop exprs were not built"); 7144 7145 getCurFunction()->setHasBranchProtectedScope(); 7146 7147 DSAStack->setParentTeamsRegionLoc(StartLoc); 7148 7149 return OMPTeamsDistributeDirective::Create( 7150 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7151 } 7152 7153 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 7154 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7155 SourceLocation EndLoc, 7156 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7157 if (!AStmt) 7158 return StmtError(); 7159 7160 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7161 // 1.2.2 OpenMP Language Terminology 7162 // Structured block - An executable statement with a single entry at the 7163 // top and a single exit at the bottom. 7164 // The point of exit cannot be a branch out of the structured block. 7165 // longjmp() and throw() must not violate the entry/exit criteria. 7166 CS->getCapturedDecl()->setNothrow(); 7167 for (int ThisCaptureLevel = 7168 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 7169 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7170 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7171 // 1.2.2 OpenMP Language Terminology 7172 // Structured block - An executable statement with a single entry at the 7173 // top and a single exit at the bottom. 7174 // The point of exit cannot be a branch out of the structured block. 7175 // longjmp() and throw() must not violate the entry/exit criteria. 7176 CS->getCapturedDecl()->setNothrow(); 7177 } 7178 7179 7180 OMPLoopDirective::HelperExprs B; 7181 // In presence of clause 'collapse' with number of loops, it will 7182 // define the nested loops number. 7183 unsigned NestedLoopCount = CheckOpenMPLoop( 7184 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 7185 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7186 VarsWithImplicitDSA, B); 7187 7188 if (NestedLoopCount == 0) 7189 return StmtError(); 7190 7191 assert((CurContext->isDependentContext() || B.builtAll()) && 7192 "omp teams distribute simd loop exprs were not built"); 7193 7194 if (!CurContext->isDependentContext()) { 7195 // Finalize the clauses that need pre-built expressions for CodeGen. 7196 for (auto C : Clauses) { 7197 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7198 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7199 B.NumIterations, *this, CurScope, 7200 DSAStack)) 7201 return StmtError(); 7202 } 7203 } 7204 7205 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7206 return StmtError(); 7207 7208 getCurFunction()->setHasBranchProtectedScope(); 7209 7210 DSAStack->setParentTeamsRegionLoc(StartLoc); 7211 7212 return OMPTeamsDistributeSimdDirective::Create( 7213 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7214 } 7215 7216 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 7217 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7218 SourceLocation EndLoc, 7219 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7220 if (!AStmt) 7221 return StmtError(); 7222 7223 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7224 // 1.2.2 OpenMP Language Terminology 7225 // Structured block - An executable statement with a single entry at the 7226 // top and a single exit at the bottom. 7227 // The point of exit cannot be a branch out of the structured block. 7228 // longjmp() and throw() must not violate the entry/exit criteria. 7229 CS->getCapturedDecl()->setNothrow(); 7230 7231 for (int ThisCaptureLevel = 7232 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 7233 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7234 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7235 // 1.2.2 OpenMP Language Terminology 7236 // Structured block - An executable statement with a single entry at the 7237 // top and a single exit at the bottom. 7238 // The point of exit cannot be a branch out of the structured block. 7239 // longjmp() and throw() must not violate the entry/exit criteria. 7240 CS->getCapturedDecl()->setNothrow(); 7241 } 7242 7243 OMPLoopDirective::HelperExprs B; 7244 // In presence of clause 'collapse' with number of loops, it will 7245 // define the nested loops number. 7246 auto NestedLoopCount = CheckOpenMPLoop( 7247 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 7248 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7249 VarsWithImplicitDSA, B); 7250 7251 if (NestedLoopCount == 0) 7252 return StmtError(); 7253 7254 assert((CurContext->isDependentContext() || B.builtAll()) && 7255 "omp for loop exprs were not built"); 7256 7257 if (!CurContext->isDependentContext()) { 7258 // Finalize the clauses that need pre-built expressions for CodeGen. 7259 for (auto C : Clauses) { 7260 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7261 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7262 B.NumIterations, *this, CurScope, 7263 DSAStack)) 7264 return StmtError(); 7265 } 7266 } 7267 7268 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7269 return StmtError(); 7270 7271 getCurFunction()->setHasBranchProtectedScope(); 7272 7273 DSAStack->setParentTeamsRegionLoc(StartLoc); 7274 7275 return OMPTeamsDistributeParallelForSimdDirective::Create( 7276 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7277 } 7278 7279 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 7280 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7281 SourceLocation EndLoc, 7282 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7283 if (!AStmt) 7284 return StmtError(); 7285 7286 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7287 // 1.2.2 OpenMP Language Terminology 7288 // Structured block - An executable statement with a single entry at the 7289 // top and a single exit at the bottom. 7290 // The point of exit cannot be a branch out of the structured block. 7291 // longjmp() and throw() must not violate the entry/exit criteria. 7292 CS->getCapturedDecl()->setNothrow(); 7293 7294 for (int ThisCaptureLevel = 7295 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 7296 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7297 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7298 // 1.2.2 OpenMP Language Terminology 7299 // Structured block - An executable statement with a single entry at the 7300 // top and a single exit at the bottom. 7301 // The point of exit cannot be a branch out of the structured block. 7302 // longjmp() and throw() must not violate the entry/exit criteria. 7303 CS->getCapturedDecl()->setNothrow(); 7304 } 7305 7306 OMPLoopDirective::HelperExprs B; 7307 // In presence of clause 'collapse' with number of loops, it will 7308 // define the nested loops number. 7309 unsigned NestedLoopCount = CheckOpenMPLoop( 7310 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7311 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7312 VarsWithImplicitDSA, B); 7313 7314 if (NestedLoopCount == 0) 7315 return StmtError(); 7316 7317 assert((CurContext->isDependentContext() || B.builtAll()) && 7318 "omp for loop exprs were not built"); 7319 7320 getCurFunction()->setHasBranchProtectedScope(); 7321 7322 DSAStack->setParentTeamsRegionLoc(StartLoc); 7323 7324 return OMPTeamsDistributeParallelForDirective::Create( 7325 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 7326 DSAStack->isCancelRegion()); 7327 } 7328 7329 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 7330 Stmt *AStmt, 7331 SourceLocation StartLoc, 7332 SourceLocation EndLoc) { 7333 if (!AStmt) 7334 return StmtError(); 7335 7336 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7337 // 1.2.2 OpenMP Language Terminology 7338 // Structured block - An executable statement with a single entry at the 7339 // top and a single exit at the bottom. 7340 // The point of exit cannot be a branch out of the structured block. 7341 // longjmp() and throw() must not violate the entry/exit criteria. 7342 CS->getCapturedDecl()->setNothrow(); 7343 7344 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 7345 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7346 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7347 // 1.2.2 OpenMP Language Terminology 7348 // Structured block - An executable statement with a single entry at the 7349 // top and a single exit at the bottom. 7350 // The point of exit cannot be a branch out of the structured block. 7351 // longjmp() and throw() must not violate the entry/exit criteria. 7352 CS->getCapturedDecl()->setNothrow(); 7353 } 7354 getCurFunction()->setHasBranchProtectedScope(); 7355 7356 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 7357 AStmt); 7358 } 7359 7360 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 7361 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7362 SourceLocation EndLoc, 7363 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7364 if (!AStmt) 7365 return StmtError(); 7366 7367 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7368 // 1.2.2 OpenMP Language Terminology 7369 // Structured block - An executable statement with a single entry at the 7370 // top and a single exit at the bottom. 7371 // The point of exit cannot be a branch out of the structured block. 7372 // longjmp() and throw() must not violate the entry/exit criteria. 7373 CS->getCapturedDecl()->setNothrow(); 7374 for (int ThisCaptureLevel = 7375 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 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' with number of loops, it will 7388 // define the nested loops number. 7389 auto NestedLoopCount = CheckOpenMPLoop( 7390 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 7391 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7392 VarsWithImplicitDSA, B); 7393 if (NestedLoopCount == 0) 7394 return StmtError(); 7395 7396 assert((CurContext->isDependentContext() || B.builtAll()) && 7397 "omp target teams distribute loop exprs were not built"); 7398 7399 getCurFunction()->setHasBranchProtectedScope(); 7400 return OMPTargetTeamsDistributeDirective::Create( 7401 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7402 } 7403 7404 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 7405 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7406 SourceLocation EndLoc, 7407 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7408 if (!AStmt) 7409 return StmtError(); 7410 7411 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7412 // 1.2.2 OpenMP Language Terminology 7413 // Structured block - An executable statement with a single entry at the 7414 // top and a single exit at the bottom. 7415 // The point of exit cannot be a branch out of the structured block. 7416 // longjmp() and throw() must not violate the entry/exit criteria. 7417 CS->getCapturedDecl()->setNothrow(); 7418 7419 for (int ThisCaptureLevel = 7420 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 7421 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7422 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7423 // 1.2.2 OpenMP Language Terminology 7424 // Structured block - An executable statement with a single entry at the 7425 // top and a single exit at the bottom. 7426 // The point of exit cannot be a branch out of the structured block. 7427 // longjmp() and throw() must not violate the entry/exit criteria. 7428 CS->getCapturedDecl()->setNothrow(); 7429 } 7430 7431 OMPLoopDirective::HelperExprs B; 7432 // In presence of clause 'collapse' with number of loops, it will 7433 // define the nested loops number. 7434 auto NestedLoopCount = CheckOpenMPLoop( 7435 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7436 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7437 VarsWithImplicitDSA, B); 7438 if (NestedLoopCount == 0) 7439 return StmtError(); 7440 7441 assert((CurContext->isDependentContext() || B.builtAll()) && 7442 "omp target teams distribute parallel for loop exprs were not built"); 7443 7444 getCurFunction()->setHasBranchProtectedScope(); 7445 return OMPTargetTeamsDistributeParallelForDirective::Create( 7446 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 7447 DSAStack->isCancelRegion()); 7448 } 7449 7450 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 7451 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7452 SourceLocation EndLoc, 7453 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7454 if (!AStmt) 7455 return StmtError(); 7456 7457 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7458 // 1.2.2 OpenMP Language Terminology 7459 // Structured block - An executable statement with a single entry at the 7460 // top and a single exit at the bottom. 7461 // The point of exit cannot be a branch out of the structured block. 7462 // longjmp() and throw() must not violate the entry/exit criteria. 7463 CS->getCapturedDecl()->setNothrow(); 7464 7465 OMPLoopDirective::HelperExprs B; 7466 // In presence of clause 'collapse' with number of loops, it will 7467 // define the nested loops number. 7468 auto NestedLoopCount = CheckOpenMPLoop( 7469 OMPD_target_teams_distribute_parallel_for_simd, 7470 getCollapseNumberExpr(Clauses), 7471 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7472 VarsWithImplicitDSA, B); 7473 if (NestedLoopCount == 0) 7474 return StmtError(); 7475 7476 assert((CurContext->isDependentContext() || B.builtAll()) && 7477 "omp target teams distribute parallel for simd loop exprs were not " 7478 "built"); 7479 7480 if (!CurContext->isDependentContext()) { 7481 // Finalize the clauses that need pre-built expressions for CodeGen. 7482 for (auto C : Clauses) { 7483 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7484 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7485 B.NumIterations, *this, CurScope, 7486 DSAStack)) 7487 return StmtError(); 7488 } 7489 } 7490 7491 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7492 return StmtError(); 7493 7494 getCurFunction()->setHasBranchProtectedScope(); 7495 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 7496 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7497 } 7498 7499 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 7500 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7501 SourceLocation EndLoc, 7502 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7503 if (!AStmt) 7504 return StmtError(); 7505 7506 auto *CS = cast<CapturedStmt>(AStmt); 7507 // 1.2.2 OpenMP Language Terminology 7508 // Structured block - An executable statement with a single entry at the 7509 // top and a single exit at the bottom. 7510 // The point of exit cannot be a branch out of the structured block. 7511 // longjmp() and throw() must not violate the entry/exit criteria. 7512 CS->getCapturedDecl()->setNothrow(); 7513 for (int ThisCaptureLevel = 7514 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 7515 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7516 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7517 // 1.2.2 OpenMP Language Terminology 7518 // Structured block - An executable statement with a single entry at the 7519 // top and a single exit at the bottom. 7520 // The point of exit cannot be a branch out of the structured block. 7521 // longjmp() and throw() must not violate the entry/exit criteria. 7522 CS->getCapturedDecl()->setNothrow(); 7523 } 7524 7525 OMPLoopDirective::HelperExprs B; 7526 // In presence of clause 'collapse' with number of loops, it will 7527 // define the nested loops number. 7528 auto NestedLoopCount = CheckOpenMPLoop( 7529 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 7530 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7531 VarsWithImplicitDSA, B); 7532 if (NestedLoopCount == 0) 7533 return StmtError(); 7534 7535 assert((CurContext->isDependentContext() || B.builtAll()) && 7536 "omp target teams distribute simd loop exprs were not built"); 7537 7538 if (!CurContext->isDependentContext()) { 7539 // Finalize the clauses that need pre-built expressions for CodeGen. 7540 for (auto C : Clauses) { 7541 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7542 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7543 B.NumIterations, *this, CurScope, 7544 DSAStack)) 7545 return StmtError(); 7546 } 7547 } 7548 7549 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7550 return StmtError(); 7551 7552 getCurFunction()->setHasBranchProtectedScope(); 7553 return OMPTargetTeamsDistributeSimdDirective::Create( 7554 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7555 } 7556 7557 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 7558 SourceLocation StartLoc, 7559 SourceLocation LParenLoc, 7560 SourceLocation EndLoc) { 7561 OMPClause *Res = nullptr; 7562 switch (Kind) { 7563 case OMPC_final: 7564 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 7565 break; 7566 case OMPC_num_threads: 7567 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 7568 break; 7569 case OMPC_safelen: 7570 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 7571 break; 7572 case OMPC_simdlen: 7573 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 7574 break; 7575 case OMPC_collapse: 7576 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 7577 break; 7578 case OMPC_ordered: 7579 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 7580 break; 7581 case OMPC_device: 7582 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 7583 break; 7584 case OMPC_num_teams: 7585 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 7586 break; 7587 case OMPC_thread_limit: 7588 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 7589 break; 7590 case OMPC_priority: 7591 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 7592 break; 7593 case OMPC_grainsize: 7594 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 7595 break; 7596 case OMPC_num_tasks: 7597 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 7598 break; 7599 case OMPC_hint: 7600 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 7601 break; 7602 case OMPC_if: 7603 case OMPC_default: 7604 case OMPC_proc_bind: 7605 case OMPC_schedule: 7606 case OMPC_private: 7607 case OMPC_firstprivate: 7608 case OMPC_lastprivate: 7609 case OMPC_shared: 7610 case OMPC_reduction: 7611 case OMPC_task_reduction: 7612 case OMPC_in_reduction: 7613 case OMPC_linear: 7614 case OMPC_aligned: 7615 case OMPC_copyin: 7616 case OMPC_copyprivate: 7617 case OMPC_nowait: 7618 case OMPC_untied: 7619 case OMPC_mergeable: 7620 case OMPC_threadprivate: 7621 case OMPC_flush: 7622 case OMPC_read: 7623 case OMPC_write: 7624 case OMPC_update: 7625 case OMPC_capture: 7626 case OMPC_seq_cst: 7627 case OMPC_depend: 7628 case OMPC_threads: 7629 case OMPC_simd: 7630 case OMPC_map: 7631 case OMPC_nogroup: 7632 case OMPC_dist_schedule: 7633 case OMPC_defaultmap: 7634 case OMPC_unknown: 7635 case OMPC_uniform: 7636 case OMPC_to: 7637 case OMPC_from: 7638 case OMPC_use_device_ptr: 7639 case OMPC_is_device_ptr: 7640 llvm_unreachable("Clause is not allowed."); 7641 } 7642 return Res; 7643 } 7644 7645 // An OpenMP directive such as 'target parallel' has two captured regions: 7646 // for the 'target' and 'parallel' respectively. This function returns 7647 // the region in which to capture expressions associated with a clause. 7648 // A return value of OMPD_unknown signifies that the expression should not 7649 // be captured. 7650 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 7651 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 7652 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 7653 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7654 switch (CKind) { 7655 case OMPC_if: 7656 switch (DKind) { 7657 case OMPD_target_parallel: 7658 case OMPD_target_parallel_for: 7659 case OMPD_target_parallel_for_simd: 7660 // If this clause applies to the nested 'parallel' region, capture within 7661 // the 'target' region, otherwise do not capture. 7662 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 7663 CaptureRegion = OMPD_target; 7664 break; 7665 case OMPD_target_teams_distribute_parallel_for: 7666 case OMPD_target_teams_distribute_parallel_for_simd: 7667 // If this clause applies to the nested 'parallel' region, capture within 7668 // the 'teams' region, otherwise do not capture. 7669 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 7670 CaptureRegion = OMPD_teams; 7671 break; 7672 case OMPD_teams_distribute_parallel_for: 7673 case OMPD_teams_distribute_parallel_for_simd: 7674 CaptureRegion = OMPD_teams; 7675 break; 7676 case OMPD_target_update: 7677 case OMPD_target_enter_data: 7678 case OMPD_target_exit_data: 7679 CaptureRegion = OMPD_task; 7680 break; 7681 case OMPD_cancel: 7682 case OMPD_parallel: 7683 case OMPD_parallel_sections: 7684 case OMPD_parallel_for: 7685 case OMPD_parallel_for_simd: 7686 case OMPD_target: 7687 case OMPD_target_simd: 7688 case OMPD_target_teams: 7689 case OMPD_target_teams_distribute: 7690 case OMPD_target_teams_distribute_simd: 7691 case OMPD_distribute_parallel_for: 7692 case OMPD_distribute_parallel_for_simd: 7693 case OMPD_task: 7694 case OMPD_taskloop: 7695 case OMPD_taskloop_simd: 7696 case OMPD_target_data: 7697 // Do not capture if-clause expressions. 7698 break; 7699 case OMPD_threadprivate: 7700 case OMPD_taskyield: 7701 case OMPD_barrier: 7702 case OMPD_taskwait: 7703 case OMPD_cancellation_point: 7704 case OMPD_flush: 7705 case OMPD_declare_reduction: 7706 case OMPD_declare_simd: 7707 case OMPD_declare_target: 7708 case OMPD_end_declare_target: 7709 case OMPD_teams: 7710 case OMPD_simd: 7711 case OMPD_for: 7712 case OMPD_for_simd: 7713 case OMPD_sections: 7714 case OMPD_section: 7715 case OMPD_single: 7716 case OMPD_master: 7717 case OMPD_critical: 7718 case OMPD_taskgroup: 7719 case OMPD_distribute: 7720 case OMPD_ordered: 7721 case OMPD_atomic: 7722 case OMPD_distribute_simd: 7723 case OMPD_teams_distribute: 7724 case OMPD_teams_distribute_simd: 7725 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 7726 case OMPD_unknown: 7727 llvm_unreachable("Unknown OpenMP directive"); 7728 } 7729 break; 7730 case OMPC_num_threads: 7731 switch (DKind) { 7732 case OMPD_target_parallel: 7733 case OMPD_target_parallel_for: 7734 case OMPD_target_parallel_for_simd: 7735 CaptureRegion = OMPD_target; 7736 break; 7737 case OMPD_teams_distribute_parallel_for: 7738 case OMPD_teams_distribute_parallel_for_simd: 7739 case OMPD_target_teams_distribute_parallel_for: 7740 case OMPD_target_teams_distribute_parallel_for_simd: 7741 CaptureRegion = OMPD_teams; 7742 break; 7743 case OMPD_parallel: 7744 case OMPD_parallel_sections: 7745 case OMPD_parallel_for: 7746 case OMPD_parallel_for_simd: 7747 case OMPD_distribute_parallel_for: 7748 case OMPD_distribute_parallel_for_simd: 7749 // Do not capture num_threads-clause expressions. 7750 break; 7751 case OMPD_target_data: 7752 case OMPD_target_enter_data: 7753 case OMPD_target_exit_data: 7754 case OMPD_target_update: 7755 case OMPD_target: 7756 case OMPD_target_simd: 7757 case OMPD_target_teams: 7758 case OMPD_target_teams_distribute: 7759 case OMPD_target_teams_distribute_simd: 7760 case OMPD_cancel: 7761 case OMPD_task: 7762 case OMPD_taskloop: 7763 case OMPD_taskloop_simd: 7764 case OMPD_threadprivate: 7765 case OMPD_taskyield: 7766 case OMPD_barrier: 7767 case OMPD_taskwait: 7768 case OMPD_cancellation_point: 7769 case OMPD_flush: 7770 case OMPD_declare_reduction: 7771 case OMPD_declare_simd: 7772 case OMPD_declare_target: 7773 case OMPD_end_declare_target: 7774 case OMPD_teams: 7775 case OMPD_simd: 7776 case OMPD_for: 7777 case OMPD_for_simd: 7778 case OMPD_sections: 7779 case OMPD_section: 7780 case OMPD_single: 7781 case OMPD_master: 7782 case OMPD_critical: 7783 case OMPD_taskgroup: 7784 case OMPD_distribute: 7785 case OMPD_ordered: 7786 case OMPD_atomic: 7787 case OMPD_distribute_simd: 7788 case OMPD_teams_distribute: 7789 case OMPD_teams_distribute_simd: 7790 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 7791 case OMPD_unknown: 7792 llvm_unreachable("Unknown OpenMP directive"); 7793 } 7794 break; 7795 case OMPC_num_teams: 7796 switch (DKind) { 7797 case OMPD_target_teams: 7798 case OMPD_target_teams_distribute: 7799 case OMPD_target_teams_distribute_simd: 7800 case OMPD_target_teams_distribute_parallel_for: 7801 case OMPD_target_teams_distribute_parallel_for_simd: 7802 CaptureRegion = OMPD_target; 7803 break; 7804 case OMPD_teams_distribute_parallel_for: 7805 case OMPD_teams_distribute_parallel_for_simd: 7806 case OMPD_teams: 7807 case OMPD_teams_distribute: 7808 case OMPD_teams_distribute_simd: 7809 // Do not capture num_teams-clause expressions. 7810 break; 7811 case OMPD_distribute_parallel_for: 7812 case OMPD_distribute_parallel_for_simd: 7813 case OMPD_task: 7814 case OMPD_taskloop: 7815 case OMPD_taskloop_simd: 7816 case OMPD_target_data: 7817 case OMPD_target_enter_data: 7818 case OMPD_target_exit_data: 7819 case OMPD_target_update: 7820 case OMPD_cancel: 7821 case OMPD_parallel: 7822 case OMPD_parallel_sections: 7823 case OMPD_parallel_for: 7824 case OMPD_parallel_for_simd: 7825 case OMPD_target: 7826 case OMPD_target_simd: 7827 case OMPD_target_parallel: 7828 case OMPD_target_parallel_for: 7829 case OMPD_target_parallel_for_simd: 7830 case OMPD_threadprivate: 7831 case OMPD_taskyield: 7832 case OMPD_barrier: 7833 case OMPD_taskwait: 7834 case OMPD_cancellation_point: 7835 case OMPD_flush: 7836 case OMPD_declare_reduction: 7837 case OMPD_declare_simd: 7838 case OMPD_declare_target: 7839 case OMPD_end_declare_target: 7840 case OMPD_simd: 7841 case OMPD_for: 7842 case OMPD_for_simd: 7843 case OMPD_sections: 7844 case OMPD_section: 7845 case OMPD_single: 7846 case OMPD_master: 7847 case OMPD_critical: 7848 case OMPD_taskgroup: 7849 case OMPD_distribute: 7850 case OMPD_ordered: 7851 case OMPD_atomic: 7852 case OMPD_distribute_simd: 7853 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 7854 case OMPD_unknown: 7855 llvm_unreachable("Unknown OpenMP directive"); 7856 } 7857 break; 7858 case OMPC_thread_limit: 7859 switch (DKind) { 7860 case OMPD_target_teams: 7861 case OMPD_target_teams_distribute: 7862 case OMPD_target_teams_distribute_simd: 7863 case OMPD_target_teams_distribute_parallel_for: 7864 case OMPD_target_teams_distribute_parallel_for_simd: 7865 CaptureRegion = OMPD_target; 7866 break; 7867 case OMPD_teams_distribute_parallel_for: 7868 case OMPD_teams_distribute_parallel_for_simd: 7869 case OMPD_teams: 7870 case OMPD_teams_distribute: 7871 case OMPD_teams_distribute_simd: 7872 // Do not capture thread_limit-clause expressions. 7873 break; 7874 case OMPD_distribute_parallel_for: 7875 case OMPD_distribute_parallel_for_simd: 7876 case OMPD_task: 7877 case OMPD_taskloop: 7878 case OMPD_taskloop_simd: 7879 case OMPD_target_data: 7880 case OMPD_target_enter_data: 7881 case OMPD_target_exit_data: 7882 case OMPD_target_update: 7883 case OMPD_cancel: 7884 case OMPD_parallel: 7885 case OMPD_parallel_sections: 7886 case OMPD_parallel_for: 7887 case OMPD_parallel_for_simd: 7888 case OMPD_target: 7889 case OMPD_target_simd: 7890 case OMPD_target_parallel: 7891 case OMPD_target_parallel_for: 7892 case OMPD_target_parallel_for_simd: 7893 case OMPD_threadprivate: 7894 case OMPD_taskyield: 7895 case OMPD_barrier: 7896 case OMPD_taskwait: 7897 case OMPD_cancellation_point: 7898 case OMPD_flush: 7899 case OMPD_declare_reduction: 7900 case OMPD_declare_simd: 7901 case OMPD_declare_target: 7902 case OMPD_end_declare_target: 7903 case OMPD_simd: 7904 case OMPD_for: 7905 case OMPD_for_simd: 7906 case OMPD_sections: 7907 case OMPD_section: 7908 case OMPD_single: 7909 case OMPD_master: 7910 case OMPD_critical: 7911 case OMPD_taskgroup: 7912 case OMPD_distribute: 7913 case OMPD_ordered: 7914 case OMPD_atomic: 7915 case OMPD_distribute_simd: 7916 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 7917 case OMPD_unknown: 7918 llvm_unreachable("Unknown OpenMP directive"); 7919 } 7920 break; 7921 case OMPC_schedule: 7922 switch (DKind) { 7923 case OMPD_parallel_for: 7924 case OMPD_parallel_for_simd: 7925 case OMPD_distribute_parallel_for: 7926 case OMPD_distribute_parallel_for_simd: 7927 case OMPD_teams_distribute_parallel_for: 7928 case OMPD_teams_distribute_parallel_for_simd: 7929 case OMPD_target_parallel_for: 7930 case OMPD_target_parallel_for_simd: 7931 case OMPD_target_teams_distribute_parallel_for: 7932 case OMPD_target_teams_distribute_parallel_for_simd: 7933 CaptureRegion = OMPD_parallel; 7934 break; 7935 case OMPD_for: 7936 case OMPD_for_simd: 7937 // Do not capture schedule-clause expressions. 7938 break; 7939 case OMPD_task: 7940 case OMPD_taskloop: 7941 case OMPD_taskloop_simd: 7942 case OMPD_target_data: 7943 case OMPD_target_enter_data: 7944 case OMPD_target_exit_data: 7945 case OMPD_target_update: 7946 case OMPD_teams: 7947 case OMPD_teams_distribute: 7948 case OMPD_teams_distribute_simd: 7949 case OMPD_target_teams_distribute: 7950 case OMPD_target_teams_distribute_simd: 7951 case OMPD_target: 7952 case OMPD_target_simd: 7953 case OMPD_target_parallel: 7954 case OMPD_cancel: 7955 case OMPD_parallel: 7956 case OMPD_parallel_sections: 7957 case OMPD_threadprivate: 7958 case OMPD_taskyield: 7959 case OMPD_barrier: 7960 case OMPD_taskwait: 7961 case OMPD_cancellation_point: 7962 case OMPD_flush: 7963 case OMPD_declare_reduction: 7964 case OMPD_declare_simd: 7965 case OMPD_declare_target: 7966 case OMPD_end_declare_target: 7967 case OMPD_simd: 7968 case OMPD_sections: 7969 case OMPD_section: 7970 case OMPD_single: 7971 case OMPD_master: 7972 case OMPD_critical: 7973 case OMPD_taskgroup: 7974 case OMPD_distribute: 7975 case OMPD_ordered: 7976 case OMPD_atomic: 7977 case OMPD_distribute_simd: 7978 case OMPD_target_teams: 7979 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 7980 case OMPD_unknown: 7981 llvm_unreachable("Unknown OpenMP directive"); 7982 } 7983 break; 7984 case OMPC_dist_schedule: 7985 switch (DKind) { 7986 case OMPD_teams_distribute_parallel_for: 7987 case OMPD_teams_distribute_parallel_for_simd: 7988 case OMPD_teams_distribute: 7989 case OMPD_teams_distribute_simd: 7990 case OMPD_target_teams_distribute_parallel_for: 7991 case OMPD_target_teams_distribute_parallel_for_simd: 7992 case OMPD_target_teams_distribute: 7993 case OMPD_target_teams_distribute_simd: 7994 CaptureRegion = OMPD_teams; 7995 break; 7996 case OMPD_distribute_parallel_for: 7997 case OMPD_distribute_parallel_for_simd: 7998 case OMPD_distribute: 7999 case OMPD_distribute_simd: 8000 // Do not capture thread_limit-clause expressions. 8001 break; 8002 case OMPD_parallel_for: 8003 case OMPD_parallel_for_simd: 8004 case OMPD_target_parallel_for_simd: 8005 case OMPD_target_parallel_for: 8006 case OMPD_task: 8007 case OMPD_taskloop: 8008 case OMPD_taskloop_simd: 8009 case OMPD_target_data: 8010 case OMPD_target_enter_data: 8011 case OMPD_target_exit_data: 8012 case OMPD_target_update: 8013 case OMPD_teams: 8014 case OMPD_target: 8015 case OMPD_target_simd: 8016 case OMPD_target_parallel: 8017 case OMPD_cancel: 8018 case OMPD_parallel: 8019 case OMPD_parallel_sections: 8020 case OMPD_threadprivate: 8021 case OMPD_taskyield: 8022 case OMPD_barrier: 8023 case OMPD_taskwait: 8024 case OMPD_cancellation_point: 8025 case OMPD_flush: 8026 case OMPD_declare_reduction: 8027 case OMPD_declare_simd: 8028 case OMPD_declare_target: 8029 case OMPD_end_declare_target: 8030 case OMPD_simd: 8031 case OMPD_for: 8032 case OMPD_for_simd: 8033 case OMPD_sections: 8034 case OMPD_section: 8035 case OMPD_single: 8036 case OMPD_master: 8037 case OMPD_critical: 8038 case OMPD_taskgroup: 8039 case OMPD_ordered: 8040 case OMPD_atomic: 8041 case OMPD_target_teams: 8042 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 8043 case OMPD_unknown: 8044 llvm_unreachable("Unknown OpenMP directive"); 8045 } 8046 break; 8047 case OMPC_device: 8048 switch (DKind) { 8049 case OMPD_target_update: 8050 case OMPD_target_enter_data: 8051 case OMPD_target_exit_data: 8052 CaptureRegion = OMPD_task; 8053 break; 8054 case OMPD_target_teams: 8055 case OMPD_target_teams_distribute: 8056 case OMPD_target_teams_distribute_simd: 8057 case OMPD_target_teams_distribute_parallel_for: 8058 case OMPD_target_teams_distribute_parallel_for_simd: 8059 case OMPD_target_data: 8060 case OMPD_target: 8061 case OMPD_target_simd: 8062 case OMPD_target_parallel: 8063 case OMPD_target_parallel_for: 8064 case OMPD_target_parallel_for_simd: 8065 // Do not capture device-clause expressions. 8066 break; 8067 case OMPD_teams_distribute_parallel_for: 8068 case OMPD_teams_distribute_parallel_for_simd: 8069 case OMPD_teams: 8070 case OMPD_teams_distribute: 8071 case OMPD_teams_distribute_simd: 8072 case OMPD_distribute_parallel_for: 8073 case OMPD_distribute_parallel_for_simd: 8074 case OMPD_task: 8075 case OMPD_taskloop: 8076 case OMPD_taskloop_simd: 8077 case OMPD_cancel: 8078 case OMPD_parallel: 8079 case OMPD_parallel_sections: 8080 case OMPD_parallel_for: 8081 case OMPD_parallel_for_simd: 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_simd: 8093 case OMPD_for: 8094 case OMPD_for_simd: 8095 case OMPD_sections: 8096 case OMPD_section: 8097 case OMPD_single: 8098 case OMPD_master: 8099 case OMPD_critical: 8100 case OMPD_taskgroup: 8101 case OMPD_distribute: 8102 case OMPD_ordered: 8103 case OMPD_atomic: 8104 case OMPD_distribute_simd: 8105 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 8106 case OMPD_unknown: 8107 llvm_unreachable("Unknown OpenMP directive"); 8108 } 8109 break; 8110 case OMPC_firstprivate: 8111 case OMPC_lastprivate: 8112 case OMPC_reduction: 8113 case OMPC_task_reduction: 8114 case OMPC_in_reduction: 8115 case OMPC_linear: 8116 case OMPC_default: 8117 case OMPC_proc_bind: 8118 case OMPC_final: 8119 case OMPC_safelen: 8120 case OMPC_simdlen: 8121 case OMPC_collapse: 8122 case OMPC_private: 8123 case OMPC_shared: 8124 case OMPC_aligned: 8125 case OMPC_copyin: 8126 case OMPC_copyprivate: 8127 case OMPC_ordered: 8128 case OMPC_nowait: 8129 case OMPC_untied: 8130 case OMPC_mergeable: 8131 case OMPC_threadprivate: 8132 case OMPC_flush: 8133 case OMPC_read: 8134 case OMPC_write: 8135 case OMPC_update: 8136 case OMPC_capture: 8137 case OMPC_seq_cst: 8138 case OMPC_depend: 8139 case OMPC_threads: 8140 case OMPC_simd: 8141 case OMPC_map: 8142 case OMPC_priority: 8143 case OMPC_grainsize: 8144 case OMPC_nogroup: 8145 case OMPC_num_tasks: 8146 case OMPC_hint: 8147 case OMPC_defaultmap: 8148 case OMPC_unknown: 8149 case OMPC_uniform: 8150 case OMPC_to: 8151 case OMPC_from: 8152 case OMPC_use_device_ptr: 8153 case OMPC_is_device_ptr: 8154 llvm_unreachable("Unexpected OpenMP clause."); 8155 } 8156 return CaptureRegion; 8157 } 8158 8159 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 8160 Expr *Condition, SourceLocation StartLoc, 8161 SourceLocation LParenLoc, 8162 SourceLocation NameModifierLoc, 8163 SourceLocation ColonLoc, 8164 SourceLocation EndLoc) { 8165 Expr *ValExpr = Condition; 8166 Stmt *HelperValStmt = nullptr; 8167 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 8168 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 8169 !Condition->isInstantiationDependent() && 8170 !Condition->containsUnexpandedParameterPack()) { 8171 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 8172 if (Val.isInvalid()) 8173 return nullptr; 8174 8175 ValExpr = Val.get(); 8176 8177 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8178 CaptureRegion = 8179 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 8180 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 8181 ValExpr = MakeFullExpr(ValExpr).get(); 8182 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 8183 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 8184 HelperValStmt = buildPreInits(Context, Captures); 8185 } 8186 } 8187 8188 return new (Context) 8189 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 8190 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 8191 } 8192 8193 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 8194 SourceLocation StartLoc, 8195 SourceLocation LParenLoc, 8196 SourceLocation EndLoc) { 8197 Expr *ValExpr = Condition; 8198 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 8199 !Condition->isInstantiationDependent() && 8200 !Condition->containsUnexpandedParameterPack()) { 8201 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 8202 if (Val.isInvalid()) 8203 return nullptr; 8204 8205 ValExpr = MakeFullExpr(Val.get()).get(); 8206 } 8207 8208 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 8209 } 8210 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 8211 Expr *Op) { 8212 if (!Op) 8213 return ExprError(); 8214 8215 class IntConvertDiagnoser : public ICEConvertDiagnoser { 8216 public: 8217 IntConvertDiagnoser() 8218 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 8219 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 8220 QualType T) override { 8221 return S.Diag(Loc, diag::err_omp_not_integral) << T; 8222 } 8223 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 8224 QualType T) override { 8225 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 8226 } 8227 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 8228 QualType T, 8229 QualType ConvTy) override { 8230 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 8231 } 8232 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 8233 QualType ConvTy) override { 8234 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 8235 << ConvTy->isEnumeralType() << ConvTy; 8236 } 8237 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 8238 QualType T) override { 8239 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 8240 } 8241 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 8242 QualType ConvTy) override { 8243 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 8244 << ConvTy->isEnumeralType() << ConvTy; 8245 } 8246 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 8247 QualType) override { 8248 llvm_unreachable("conversion functions are permitted"); 8249 } 8250 } ConvertDiagnoser; 8251 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 8252 } 8253 8254 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 8255 OpenMPClauseKind CKind, 8256 bool StrictlyPositive) { 8257 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 8258 !ValExpr->isInstantiationDependent()) { 8259 SourceLocation Loc = ValExpr->getExprLoc(); 8260 ExprResult Value = 8261 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 8262 if (Value.isInvalid()) 8263 return false; 8264 8265 ValExpr = Value.get(); 8266 // The expression must evaluate to a non-negative integer value. 8267 llvm::APSInt Result; 8268 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 8269 Result.isSigned() && 8270 !((!StrictlyPositive && Result.isNonNegative()) || 8271 (StrictlyPositive && Result.isStrictlyPositive()))) { 8272 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 8273 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 8274 << ValExpr->getSourceRange(); 8275 return false; 8276 } 8277 } 8278 return true; 8279 } 8280 8281 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 8282 SourceLocation StartLoc, 8283 SourceLocation LParenLoc, 8284 SourceLocation EndLoc) { 8285 Expr *ValExpr = NumThreads; 8286 Stmt *HelperValStmt = nullptr; 8287 8288 // OpenMP [2.5, Restrictions] 8289 // The num_threads expression must evaluate to a positive integer value. 8290 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 8291 /*StrictlyPositive=*/true)) 8292 return nullptr; 8293 8294 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8295 OpenMPDirectiveKind CaptureRegion = 8296 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 8297 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 8298 ValExpr = MakeFullExpr(ValExpr).get(); 8299 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 8300 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 8301 HelperValStmt = buildPreInits(Context, Captures); 8302 } 8303 8304 return new (Context) OMPNumThreadsClause( 8305 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 8306 } 8307 8308 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 8309 OpenMPClauseKind CKind, 8310 bool StrictlyPositive) { 8311 if (!E) 8312 return ExprError(); 8313 if (E->isValueDependent() || E->isTypeDependent() || 8314 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 8315 return E; 8316 llvm::APSInt Result; 8317 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 8318 if (ICE.isInvalid()) 8319 return ExprError(); 8320 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 8321 (!StrictlyPositive && !Result.isNonNegative())) { 8322 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 8323 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 8324 << E->getSourceRange(); 8325 return ExprError(); 8326 } 8327 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 8328 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 8329 << E->getSourceRange(); 8330 return ExprError(); 8331 } 8332 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 8333 DSAStack->setAssociatedLoops(Result.getExtValue()); 8334 else if (CKind == OMPC_ordered) 8335 DSAStack->setAssociatedLoops(Result.getExtValue()); 8336 return ICE; 8337 } 8338 8339 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 8340 SourceLocation LParenLoc, 8341 SourceLocation EndLoc) { 8342 // OpenMP [2.8.1, simd construct, Description] 8343 // The parameter of the safelen clause must be a constant 8344 // positive integer expression. 8345 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 8346 if (Safelen.isInvalid()) 8347 return nullptr; 8348 return new (Context) 8349 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 8350 } 8351 8352 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 8353 SourceLocation LParenLoc, 8354 SourceLocation EndLoc) { 8355 // OpenMP [2.8.1, simd construct, Description] 8356 // The parameter of the simdlen clause must be a constant 8357 // positive integer expression. 8358 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 8359 if (Simdlen.isInvalid()) 8360 return nullptr; 8361 return new (Context) 8362 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 8363 } 8364 8365 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 8366 SourceLocation StartLoc, 8367 SourceLocation LParenLoc, 8368 SourceLocation EndLoc) { 8369 // OpenMP [2.7.1, loop construct, Description] 8370 // OpenMP [2.8.1, simd construct, Description] 8371 // OpenMP [2.9.6, distribute construct, Description] 8372 // The parameter of the collapse clause must be a constant 8373 // positive integer expression. 8374 ExprResult NumForLoopsResult = 8375 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 8376 if (NumForLoopsResult.isInvalid()) 8377 return nullptr; 8378 return new (Context) 8379 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 8380 } 8381 8382 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 8383 SourceLocation EndLoc, 8384 SourceLocation LParenLoc, 8385 Expr *NumForLoops) { 8386 // OpenMP [2.7.1, loop construct, Description] 8387 // OpenMP [2.8.1, simd construct, Description] 8388 // OpenMP [2.9.6, distribute construct, Description] 8389 // The parameter of the ordered clause must be a constant 8390 // positive integer expression if any. 8391 if (NumForLoops && LParenLoc.isValid()) { 8392 ExprResult NumForLoopsResult = 8393 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 8394 if (NumForLoopsResult.isInvalid()) 8395 return nullptr; 8396 NumForLoops = NumForLoopsResult.get(); 8397 } else 8398 NumForLoops = nullptr; 8399 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 8400 return new (Context) 8401 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 8402 } 8403 8404 OMPClause *Sema::ActOnOpenMPSimpleClause( 8405 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 8406 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 8407 OMPClause *Res = nullptr; 8408 switch (Kind) { 8409 case OMPC_default: 8410 Res = 8411 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 8412 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 8413 break; 8414 case OMPC_proc_bind: 8415 Res = ActOnOpenMPProcBindClause( 8416 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 8417 LParenLoc, EndLoc); 8418 break; 8419 case OMPC_if: 8420 case OMPC_final: 8421 case OMPC_num_threads: 8422 case OMPC_safelen: 8423 case OMPC_simdlen: 8424 case OMPC_collapse: 8425 case OMPC_schedule: 8426 case OMPC_private: 8427 case OMPC_firstprivate: 8428 case OMPC_lastprivate: 8429 case OMPC_shared: 8430 case OMPC_reduction: 8431 case OMPC_task_reduction: 8432 case OMPC_in_reduction: 8433 case OMPC_linear: 8434 case OMPC_aligned: 8435 case OMPC_copyin: 8436 case OMPC_copyprivate: 8437 case OMPC_ordered: 8438 case OMPC_nowait: 8439 case OMPC_untied: 8440 case OMPC_mergeable: 8441 case OMPC_threadprivate: 8442 case OMPC_flush: 8443 case OMPC_read: 8444 case OMPC_write: 8445 case OMPC_update: 8446 case OMPC_capture: 8447 case OMPC_seq_cst: 8448 case OMPC_depend: 8449 case OMPC_device: 8450 case OMPC_threads: 8451 case OMPC_simd: 8452 case OMPC_map: 8453 case OMPC_num_teams: 8454 case OMPC_thread_limit: 8455 case OMPC_priority: 8456 case OMPC_grainsize: 8457 case OMPC_nogroup: 8458 case OMPC_num_tasks: 8459 case OMPC_hint: 8460 case OMPC_dist_schedule: 8461 case OMPC_defaultmap: 8462 case OMPC_unknown: 8463 case OMPC_uniform: 8464 case OMPC_to: 8465 case OMPC_from: 8466 case OMPC_use_device_ptr: 8467 case OMPC_is_device_ptr: 8468 llvm_unreachable("Clause is not allowed."); 8469 } 8470 return Res; 8471 } 8472 8473 static std::string 8474 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 8475 ArrayRef<unsigned> Exclude = llvm::None) { 8476 std::string Values; 8477 unsigned Bound = Last >= 2 ? Last - 2 : 0; 8478 unsigned Skipped = Exclude.size(); 8479 auto S = Exclude.begin(), E = Exclude.end(); 8480 for (unsigned i = First; i < Last; ++i) { 8481 if (std::find(S, E, i) != E) { 8482 --Skipped; 8483 continue; 8484 } 8485 Values += "'"; 8486 Values += getOpenMPSimpleClauseTypeName(K, i); 8487 Values += "'"; 8488 if (i == Bound - Skipped) 8489 Values += " or "; 8490 else if (i != Bound + 1 - Skipped) 8491 Values += ", "; 8492 } 8493 return Values; 8494 } 8495 8496 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 8497 SourceLocation KindKwLoc, 8498 SourceLocation StartLoc, 8499 SourceLocation LParenLoc, 8500 SourceLocation EndLoc) { 8501 if (Kind == OMPC_DEFAULT_unknown) { 8502 static_assert(OMPC_DEFAULT_unknown > 0, 8503 "OMPC_DEFAULT_unknown not greater than 0"); 8504 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 8505 << getListOfPossibleValues(OMPC_default, /*First=*/0, 8506 /*Last=*/OMPC_DEFAULT_unknown) 8507 << getOpenMPClauseName(OMPC_default); 8508 return nullptr; 8509 } 8510 switch (Kind) { 8511 case OMPC_DEFAULT_none: 8512 DSAStack->setDefaultDSANone(KindKwLoc); 8513 break; 8514 case OMPC_DEFAULT_shared: 8515 DSAStack->setDefaultDSAShared(KindKwLoc); 8516 break; 8517 case OMPC_DEFAULT_unknown: 8518 llvm_unreachable("Clause kind is not allowed."); 8519 break; 8520 } 8521 return new (Context) 8522 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 8523 } 8524 8525 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 8526 SourceLocation KindKwLoc, 8527 SourceLocation StartLoc, 8528 SourceLocation LParenLoc, 8529 SourceLocation EndLoc) { 8530 if (Kind == OMPC_PROC_BIND_unknown) { 8531 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 8532 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 8533 /*Last=*/OMPC_PROC_BIND_unknown) 8534 << getOpenMPClauseName(OMPC_proc_bind); 8535 return nullptr; 8536 } 8537 return new (Context) 8538 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 8539 } 8540 8541 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 8542 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 8543 SourceLocation StartLoc, SourceLocation LParenLoc, 8544 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 8545 SourceLocation EndLoc) { 8546 OMPClause *Res = nullptr; 8547 switch (Kind) { 8548 case OMPC_schedule: 8549 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 8550 assert(Argument.size() == NumberOfElements && 8551 ArgumentLoc.size() == NumberOfElements); 8552 Res = ActOnOpenMPScheduleClause( 8553 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 8554 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 8555 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 8556 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 8557 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 8558 break; 8559 case OMPC_if: 8560 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 8561 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 8562 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 8563 DelimLoc, EndLoc); 8564 break; 8565 case OMPC_dist_schedule: 8566 Res = ActOnOpenMPDistScheduleClause( 8567 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 8568 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 8569 break; 8570 case OMPC_defaultmap: 8571 enum { Modifier, DefaultmapKind }; 8572 Res = ActOnOpenMPDefaultmapClause( 8573 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 8574 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 8575 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 8576 EndLoc); 8577 break; 8578 case OMPC_final: 8579 case OMPC_num_threads: 8580 case OMPC_safelen: 8581 case OMPC_simdlen: 8582 case OMPC_collapse: 8583 case OMPC_default: 8584 case OMPC_proc_bind: 8585 case OMPC_private: 8586 case OMPC_firstprivate: 8587 case OMPC_lastprivate: 8588 case OMPC_shared: 8589 case OMPC_reduction: 8590 case OMPC_task_reduction: 8591 case OMPC_in_reduction: 8592 case OMPC_linear: 8593 case OMPC_aligned: 8594 case OMPC_copyin: 8595 case OMPC_copyprivate: 8596 case OMPC_ordered: 8597 case OMPC_nowait: 8598 case OMPC_untied: 8599 case OMPC_mergeable: 8600 case OMPC_threadprivate: 8601 case OMPC_flush: 8602 case OMPC_read: 8603 case OMPC_write: 8604 case OMPC_update: 8605 case OMPC_capture: 8606 case OMPC_seq_cst: 8607 case OMPC_depend: 8608 case OMPC_device: 8609 case OMPC_threads: 8610 case OMPC_simd: 8611 case OMPC_map: 8612 case OMPC_num_teams: 8613 case OMPC_thread_limit: 8614 case OMPC_priority: 8615 case OMPC_grainsize: 8616 case OMPC_nogroup: 8617 case OMPC_num_tasks: 8618 case OMPC_hint: 8619 case OMPC_unknown: 8620 case OMPC_uniform: 8621 case OMPC_to: 8622 case OMPC_from: 8623 case OMPC_use_device_ptr: 8624 case OMPC_is_device_ptr: 8625 llvm_unreachable("Clause is not allowed."); 8626 } 8627 return Res; 8628 } 8629 8630 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 8631 OpenMPScheduleClauseModifier M2, 8632 SourceLocation M1Loc, SourceLocation M2Loc) { 8633 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 8634 SmallVector<unsigned, 2> Excluded; 8635 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 8636 Excluded.push_back(M2); 8637 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 8638 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 8639 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 8640 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 8641 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 8642 << getListOfPossibleValues(OMPC_schedule, 8643 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 8644 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 8645 Excluded) 8646 << getOpenMPClauseName(OMPC_schedule); 8647 return true; 8648 } 8649 return false; 8650 } 8651 8652 OMPClause *Sema::ActOnOpenMPScheduleClause( 8653 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 8654 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 8655 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 8656 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 8657 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 8658 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 8659 return nullptr; 8660 // OpenMP, 2.7.1, Loop Construct, Restrictions 8661 // Either the monotonic modifier or the nonmonotonic modifier can be specified 8662 // but not both. 8663 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 8664 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 8665 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 8666 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 8667 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 8668 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 8669 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 8670 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 8671 return nullptr; 8672 } 8673 if (Kind == OMPC_SCHEDULE_unknown) { 8674 std::string Values; 8675 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 8676 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 8677 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 8678 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 8679 Exclude); 8680 } else { 8681 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 8682 /*Last=*/OMPC_SCHEDULE_unknown); 8683 } 8684 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 8685 << Values << getOpenMPClauseName(OMPC_schedule); 8686 return nullptr; 8687 } 8688 // OpenMP, 2.7.1, Loop Construct, Restrictions 8689 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 8690 // schedule(guided). 8691 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 8692 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 8693 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 8694 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 8695 diag::err_omp_schedule_nonmonotonic_static); 8696 return nullptr; 8697 } 8698 Expr *ValExpr = ChunkSize; 8699 Stmt *HelperValStmt = nullptr; 8700 if (ChunkSize) { 8701 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 8702 !ChunkSize->isInstantiationDependent() && 8703 !ChunkSize->containsUnexpandedParameterPack()) { 8704 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 8705 ExprResult Val = 8706 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 8707 if (Val.isInvalid()) 8708 return nullptr; 8709 8710 ValExpr = Val.get(); 8711 8712 // OpenMP [2.7.1, Restrictions] 8713 // chunk_size must be a loop invariant integer expression with a positive 8714 // value. 8715 llvm::APSInt Result; 8716 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 8717 if (Result.isSigned() && !Result.isStrictlyPositive()) { 8718 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 8719 << "schedule" << 1 << ChunkSize->getSourceRange(); 8720 return nullptr; 8721 } 8722 } else if (getOpenMPCaptureRegionForClause( 8723 DSAStack->getCurrentDirective(), OMPC_schedule) != 8724 OMPD_unknown && 8725 !CurContext->isDependentContext()) { 8726 ValExpr = MakeFullExpr(ValExpr).get(); 8727 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 8728 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 8729 HelperValStmt = buildPreInits(Context, Captures); 8730 } 8731 } 8732 } 8733 8734 return new (Context) 8735 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 8736 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 8737 } 8738 8739 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 8740 SourceLocation StartLoc, 8741 SourceLocation EndLoc) { 8742 OMPClause *Res = nullptr; 8743 switch (Kind) { 8744 case OMPC_ordered: 8745 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 8746 break; 8747 case OMPC_nowait: 8748 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 8749 break; 8750 case OMPC_untied: 8751 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 8752 break; 8753 case OMPC_mergeable: 8754 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 8755 break; 8756 case OMPC_read: 8757 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 8758 break; 8759 case OMPC_write: 8760 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 8761 break; 8762 case OMPC_update: 8763 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 8764 break; 8765 case OMPC_capture: 8766 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 8767 break; 8768 case OMPC_seq_cst: 8769 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 8770 break; 8771 case OMPC_threads: 8772 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 8773 break; 8774 case OMPC_simd: 8775 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 8776 break; 8777 case OMPC_nogroup: 8778 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 8779 break; 8780 case OMPC_if: 8781 case OMPC_final: 8782 case OMPC_num_threads: 8783 case OMPC_safelen: 8784 case OMPC_simdlen: 8785 case OMPC_collapse: 8786 case OMPC_schedule: 8787 case OMPC_private: 8788 case OMPC_firstprivate: 8789 case OMPC_lastprivate: 8790 case OMPC_shared: 8791 case OMPC_reduction: 8792 case OMPC_task_reduction: 8793 case OMPC_in_reduction: 8794 case OMPC_linear: 8795 case OMPC_aligned: 8796 case OMPC_copyin: 8797 case OMPC_copyprivate: 8798 case OMPC_default: 8799 case OMPC_proc_bind: 8800 case OMPC_threadprivate: 8801 case OMPC_flush: 8802 case OMPC_depend: 8803 case OMPC_device: 8804 case OMPC_map: 8805 case OMPC_num_teams: 8806 case OMPC_thread_limit: 8807 case OMPC_priority: 8808 case OMPC_grainsize: 8809 case OMPC_num_tasks: 8810 case OMPC_hint: 8811 case OMPC_dist_schedule: 8812 case OMPC_defaultmap: 8813 case OMPC_unknown: 8814 case OMPC_uniform: 8815 case OMPC_to: 8816 case OMPC_from: 8817 case OMPC_use_device_ptr: 8818 case OMPC_is_device_ptr: 8819 llvm_unreachable("Clause is not allowed."); 8820 } 8821 return Res; 8822 } 8823 8824 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 8825 SourceLocation EndLoc) { 8826 DSAStack->setNowaitRegion(); 8827 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 8828 } 8829 8830 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 8831 SourceLocation EndLoc) { 8832 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 8833 } 8834 8835 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 8836 SourceLocation EndLoc) { 8837 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 8838 } 8839 8840 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 8841 SourceLocation EndLoc) { 8842 return new (Context) OMPReadClause(StartLoc, EndLoc); 8843 } 8844 8845 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 8846 SourceLocation EndLoc) { 8847 return new (Context) OMPWriteClause(StartLoc, EndLoc); 8848 } 8849 8850 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 8851 SourceLocation EndLoc) { 8852 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 8853 } 8854 8855 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 8856 SourceLocation EndLoc) { 8857 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 8858 } 8859 8860 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 8861 SourceLocation EndLoc) { 8862 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 8863 } 8864 8865 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 8866 SourceLocation EndLoc) { 8867 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 8868 } 8869 8870 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 8871 SourceLocation EndLoc) { 8872 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 8873 } 8874 8875 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 8876 SourceLocation EndLoc) { 8877 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 8878 } 8879 8880 OMPClause *Sema::ActOnOpenMPVarListClause( 8881 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 8882 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 8883 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 8884 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 8885 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 8886 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 8887 SourceLocation DepLinMapLoc) { 8888 OMPClause *Res = nullptr; 8889 switch (Kind) { 8890 case OMPC_private: 8891 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8892 break; 8893 case OMPC_firstprivate: 8894 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8895 break; 8896 case OMPC_lastprivate: 8897 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8898 break; 8899 case OMPC_shared: 8900 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 8901 break; 8902 case OMPC_reduction: 8903 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8904 EndLoc, ReductionIdScopeSpec, ReductionId); 8905 break; 8906 case OMPC_task_reduction: 8907 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8908 EndLoc, ReductionIdScopeSpec, 8909 ReductionId); 8910 break; 8911 case OMPC_in_reduction: 8912 Res = 8913 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8914 EndLoc, ReductionIdScopeSpec, ReductionId); 8915 break; 8916 case OMPC_linear: 8917 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 8918 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 8919 break; 8920 case OMPC_aligned: 8921 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 8922 ColonLoc, EndLoc); 8923 break; 8924 case OMPC_copyin: 8925 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 8926 break; 8927 case OMPC_copyprivate: 8928 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8929 break; 8930 case OMPC_flush: 8931 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 8932 break; 8933 case OMPC_depend: 8934 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 8935 StartLoc, LParenLoc, EndLoc); 8936 break; 8937 case OMPC_map: 8938 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 8939 DepLinMapLoc, ColonLoc, VarList, StartLoc, 8940 LParenLoc, EndLoc); 8941 break; 8942 case OMPC_to: 8943 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 8944 break; 8945 case OMPC_from: 8946 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 8947 break; 8948 case OMPC_use_device_ptr: 8949 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 8950 break; 8951 case OMPC_is_device_ptr: 8952 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 8953 break; 8954 case OMPC_if: 8955 case OMPC_final: 8956 case OMPC_num_threads: 8957 case OMPC_safelen: 8958 case OMPC_simdlen: 8959 case OMPC_collapse: 8960 case OMPC_default: 8961 case OMPC_proc_bind: 8962 case OMPC_schedule: 8963 case OMPC_ordered: 8964 case OMPC_nowait: 8965 case OMPC_untied: 8966 case OMPC_mergeable: 8967 case OMPC_threadprivate: 8968 case OMPC_read: 8969 case OMPC_write: 8970 case OMPC_update: 8971 case OMPC_capture: 8972 case OMPC_seq_cst: 8973 case OMPC_device: 8974 case OMPC_threads: 8975 case OMPC_simd: 8976 case OMPC_num_teams: 8977 case OMPC_thread_limit: 8978 case OMPC_priority: 8979 case OMPC_grainsize: 8980 case OMPC_nogroup: 8981 case OMPC_num_tasks: 8982 case OMPC_hint: 8983 case OMPC_dist_schedule: 8984 case OMPC_defaultmap: 8985 case OMPC_unknown: 8986 case OMPC_uniform: 8987 llvm_unreachable("Clause is not allowed."); 8988 } 8989 return Res; 8990 } 8991 8992 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 8993 ExprObjectKind OK, SourceLocation Loc) { 8994 ExprResult Res = BuildDeclRefExpr( 8995 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 8996 if (!Res.isUsable()) 8997 return ExprError(); 8998 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 8999 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 9000 if (!Res.isUsable()) 9001 return ExprError(); 9002 } 9003 if (VK != VK_LValue && Res.get()->isGLValue()) { 9004 Res = DefaultLvalueConversion(Res.get()); 9005 if (!Res.isUsable()) 9006 return ExprError(); 9007 } 9008 return Res; 9009 } 9010 9011 static std::pair<ValueDecl *, bool> 9012 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 9013 SourceRange &ERange, bool AllowArraySection = false) { 9014 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 9015 RefExpr->containsUnexpandedParameterPack()) 9016 return std::make_pair(nullptr, true); 9017 9018 // OpenMP [3.1, C/C++] 9019 // A list item is a variable name. 9020 // OpenMP [2.9.3.3, Restrictions, p.1] 9021 // A variable that is part of another variable (as an array or 9022 // structure element) cannot appear in a private clause. 9023 RefExpr = RefExpr->IgnoreParens(); 9024 enum { 9025 NoArrayExpr = -1, 9026 ArraySubscript = 0, 9027 OMPArraySection = 1 9028 } IsArrayExpr = NoArrayExpr; 9029 if (AllowArraySection) { 9030 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 9031 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 9032 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 9033 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9034 RefExpr = Base; 9035 IsArrayExpr = ArraySubscript; 9036 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 9037 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 9038 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 9039 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 9040 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 9041 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9042 RefExpr = Base; 9043 IsArrayExpr = OMPArraySection; 9044 } 9045 } 9046 ELoc = RefExpr->getExprLoc(); 9047 ERange = RefExpr->getSourceRange(); 9048 RefExpr = RefExpr->IgnoreParenImpCasts(); 9049 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 9050 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 9051 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 9052 (S.getCurrentThisType().isNull() || !ME || 9053 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 9054 !isa<FieldDecl>(ME->getMemberDecl()))) { 9055 if (IsArrayExpr != NoArrayExpr) 9056 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 9057 << ERange; 9058 else { 9059 S.Diag(ELoc, 9060 AllowArraySection 9061 ? diag::err_omp_expected_var_name_member_expr_or_array_item 9062 : diag::err_omp_expected_var_name_member_expr) 9063 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 9064 } 9065 return std::make_pair(nullptr, false); 9066 } 9067 return std::make_pair( 9068 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 9069 } 9070 9071 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 9072 SourceLocation StartLoc, 9073 SourceLocation LParenLoc, 9074 SourceLocation EndLoc) { 9075 SmallVector<Expr *, 8> Vars; 9076 SmallVector<Expr *, 8> PrivateCopies; 9077 for (auto &RefExpr : VarList) { 9078 assert(RefExpr && "NULL expr in OpenMP private clause."); 9079 SourceLocation ELoc; 9080 SourceRange ERange; 9081 Expr *SimpleRefExpr = RefExpr; 9082 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9083 if (Res.second) { 9084 // It will be analyzed later. 9085 Vars.push_back(RefExpr); 9086 PrivateCopies.push_back(nullptr); 9087 } 9088 ValueDecl *D = Res.first; 9089 if (!D) 9090 continue; 9091 9092 QualType Type = D->getType(); 9093 auto *VD = dyn_cast<VarDecl>(D); 9094 9095 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9096 // A variable that appears in a private clause must not have an incomplete 9097 // type or a reference type. 9098 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 9099 continue; 9100 Type = Type.getNonReferenceType(); 9101 9102 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9103 // in a Construct] 9104 // Variables with the predetermined data-sharing attributes may not be 9105 // listed in data-sharing attributes clauses, except for the cases 9106 // listed below. For these exceptions only, listing a predetermined 9107 // variable in a data-sharing attribute clause is allowed and overrides 9108 // the variable's predetermined data-sharing attributes. 9109 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9110 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 9111 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9112 << getOpenMPClauseName(OMPC_private); 9113 ReportOriginalDSA(*this, DSAStack, D, DVar); 9114 continue; 9115 } 9116 9117 auto CurrDir = DSAStack->getCurrentDirective(); 9118 // Variably modified types are not supported for tasks. 9119 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 9120 isOpenMPTaskingDirective(CurrDir)) { 9121 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9122 << getOpenMPClauseName(OMPC_private) << Type 9123 << getOpenMPDirectiveName(CurrDir); 9124 bool IsDecl = 9125 !VD || 9126 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9127 Diag(D->getLocation(), 9128 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9129 << D; 9130 continue; 9131 } 9132 9133 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 9134 // A list item cannot appear in both a map clause and a data-sharing 9135 // attribute clause on the same construct 9136 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 9137 CurrDir == OMPD_target_teams || 9138 CurrDir == OMPD_target_teams_distribute || 9139 CurrDir == OMPD_target_teams_distribute_parallel_for || 9140 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 9141 CurrDir == OMPD_target_teams_distribute_simd || 9142 CurrDir == OMPD_target_parallel_for_simd || 9143 CurrDir == OMPD_target_parallel_for) { 9144 OpenMPClauseKind ConflictKind; 9145 if (DSAStack->checkMappableExprComponentListsForDecl( 9146 VD, /*CurrentRegionOnly=*/true, 9147 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 9148 OpenMPClauseKind WhereFoundClauseKind) -> bool { 9149 ConflictKind = WhereFoundClauseKind; 9150 return true; 9151 })) { 9152 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 9153 << getOpenMPClauseName(OMPC_private) 9154 << getOpenMPClauseName(ConflictKind) 9155 << getOpenMPDirectiveName(CurrDir); 9156 ReportOriginalDSA(*this, DSAStack, D, DVar); 9157 continue; 9158 } 9159 } 9160 9161 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 9162 // A variable of class type (or array thereof) that appears in a private 9163 // clause requires an accessible, unambiguous default constructor for the 9164 // class type. 9165 // Generate helper private variable and initialize it with the default 9166 // value. The address of the original variable is replaced by the address of 9167 // the new private variable in CodeGen. This new variable is not added to 9168 // IdResolver, so the code in the OpenMP region uses original variable for 9169 // proper diagnostics. 9170 Type = Type.getUnqualifiedType(); 9171 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 9172 D->hasAttrs() ? &D->getAttrs() : nullptr); 9173 ActOnUninitializedDecl(VDPrivate); 9174 if (VDPrivate->isInvalidDecl()) 9175 continue; 9176 auto VDPrivateRefExpr = buildDeclRefExpr( 9177 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 9178 9179 DeclRefExpr *Ref = nullptr; 9180 if (!VD && !CurContext->isDependentContext()) 9181 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9182 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 9183 Vars.push_back((VD || CurContext->isDependentContext()) 9184 ? RefExpr->IgnoreParens() 9185 : Ref); 9186 PrivateCopies.push_back(VDPrivateRefExpr); 9187 } 9188 9189 if (Vars.empty()) 9190 return nullptr; 9191 9192 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 9193 PrivateCopies); 9194 } 9195 9196 namespace { 9197 class DiagsUninitializedSeveretyRAII { 9198 private: 9199 DiagnosticsEngine &Diags; 9200 SourceLocation SavedLoc; 9201 bool IsIgnored; 9202 9203 public: 9204 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 9205 bool IsIgnored) 9206 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 9207 if (!IsIgnored) { 9208 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 9209 /*Map*/ diag::Severity::Ignored, Loc); 9210 } 9211 } 9212 ~DiagsUninitializedSeveretyRAII() { 9213 if (!IsIgnored) 9214 Diags.popMappings(SavedLoc); 9215 } 9216 }; 9217 } 9218 9219 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 9220 SourceLocation StartLoc, 9221 SourceLocation LParenLoc, 9222 SourceLocation EndLoc) { 9223 SmallVector<Expr *, 8> Vars; 9224 SmallVector<Expr *, 8> PrivateCopies; 9225 SmallVector<Expr *, 8> Inits; 9226 SmallVector<Decl *, 4> ExprCaptures; 9227 bool IsImplicitClause = 9228 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 9229 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 9230 9231 for (auto &RefExpr : VarList) { 9232 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 9233 SourceLocation ELoc; 9234 SourceRange ERange; 9235 Expr *SimpleRefExpr = RefExpr; 9236 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9237 if (Res.second) { 9238 // It will be analyzed later. 9239 Vars.push_back(RefExpr); 9240 PrivateCopies.push_back(nullptr); 9241 Inits.push_back(nullptr); 9242 } 9243 ValueDecl *D = Res.first; 9244 if (!D) 9245 continue; 9246 9247 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 9248 QualType Type = D->getType(); 9249 auto *VD = dyn_cast<VarDecl>(D); 9250 9251 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9252 // A variable that appears in a private clause must not have an incomplete 9253 // type or a reference type. 9254 if (RequireCompleteType(ELoc, Type, 9255 diag::err_omp_firstprivate_incomplete_type)) 9256 continue; 9257 Type = Type.getNonReferenceType(); 9258 9259 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 9260 // A variable of class type (or array thereof) that appears in a private 9261 // clause requires an accessible, unambiguous copy constructor for the 9262 // class type. 9263 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 9264 9265 // If an implicit firstprivate variable found it was checked already. 9266 DSAStackTy::DSAVarData TopDVar; 9267 if (!IsImplicitClause) { 9268 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9269 TopDVar = DVar; 9270 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9271 bool IsConstant = ElemType.isConstant(Context); 9272 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 9273 // A list item that specifies a given variable may not appear in more 9274 // than one clause on the same directive, except that a variable may be 9275 // specified in both firstprivate and lastprivate clauses. 9276 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 9277 // A list item may appear in a firstprivate or lastprivate clause but not 9278 // both. 9279 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 9280 (isOpenMPDistributeDirective(CurrDir) || 9281 DVar.CKind != OMPC_lastprivate) && 9282 DVar.RefExpr) { 9283 Diag(ELoc, diag::err_omp_wrong_dsa) 9284 << getOpenMPClauseName(DVar.CKind) 9285 << getOpenMPClauseName(OMPC_firstprivate); 9286 ReportOriginalDSA(*this, DSAStack, D, DVar); 9287 continue; 9288 } 9289 9290 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9291 // in a Construct] 9292 // Variables with the predetermined data-sharing attributes may not be 9293 // listed in data-sharing attributes clauses, except for the cases 9294 // listed below. For these exceptions only, listing a predetermined 9295 // variable in a data-sharing attribute clause is allowed and overrides 9296 // the variable's predetermined data-sharing attributes. 9297 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9298 // in a Construct, C/C++, p.2] 9299 // Variables with const-qualified type having no mutable member may be 9300 // listed in a firstprivate clause, even if they are static data members. 9301 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 9302 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 9303 Diag(ELoc, diag::err_omp_wrong_dsa) 9304 << getOpenMPClauseName(DVar.CKind) 9305 << getOpenMPClauseName(OMPC_firstprivate); 9306 ReportOriginalDSA(*this, DSAStack, D, DVar); 9307 continue; 9308 } 9309 9310 // OpenMP [2.9.3.4, Restrictions, p.2] 9311 // A list item that is private within a parallel region must not appear 9312 // in a firstprivate clause on a worksharing construct if any of the 9313 // worksharing regions arising from the worksharing construct ever bind 9314 // to any of the parallel regions arising from the parallel construct. 9315 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 9316 // A list item that is private within a teams region must not appear in a 9317 // firstprivate clause on a distribute construct if any of the distribute 9318 // regions arising from the distribute construct ever bind to any of the 9319 // teams regions arising from the teams construct. 9320 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 9321 // A list item that appears in a reduction clause of a teams construct 9322 // must not appear in a firstprivate clause on a distribute construct if 9323 // any of the distribute regions arising from the distribute construct 9324 // ever bind to any of the teams regions arising from the teams construct. 9325 if ((isOpenMPWorksharingDirective(CurrDir) || 9326 isOpenMPDistributeDirective(CurrDir)) && 9327 !isOpenMPParallelDirective(CurrDir) && 9328 !isOpenMPTeamsDirective(CurrDir)) { 9329 DVar = DSAStack->getImplicitDSA(D, true); 9330 if (DVar.CKind != OMPC_shared && 9331 (isOpenMPParallelDirective(DVar.DKind) || 9332 isOpenMPTeamsDirective(DVar.DKind) || 9333 DVar.DKind == OMPD_unknown)) { 9334 Diag(ELoc, diag::err_omp_required_access) 9335 << getOpenMPClauseName(OMPC_firstprivate) 9336 << getOpenMPClauseName(OMPC_shared); 9337 ReportOriginalDSA(*this, DSAStack, D, DVar); 9338 continue; 9339 } 9340 } 9341 // OpenMP [2.9.3.4, Restrictions, p.3] 9342 // A list item that appears in a reduction clause of a parallel construct 9343 // must not appear in a firstprivate clause on a worksharing or task 9344 // construct if any of the worksharing or task regions arising from the 9345 // worksharing or task construct ever bind to any of the parallel regions 9346 // arising from the parallel construct. 9347 // OpenMP [2.9.3.4, Restrictions, p.4] 9348 // A list item that appears in a reduction clause in worksharing 9349 // construct must not appear in a firstprivate clause in a task construct 9350 // encountered during execution of any of the worksharing regions arising 9351 // from the worksharing construct. 9352 if (isOpenMPTaskingDirective(CurrDir)) { 9353 DVar = DSAStack->hasInnermostDSA( 9354 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 9355 [](OpenMPDirectiveKind K) -> bool { 9356 return isOpenMPParallelDirective(K) || 9357 isOpenMPWorksharingDirective(K) || 9358 isOpenMPTeamsDirective(K); 9359 }, 9360 /*FromParent=*/true); 9361 if (DVar.CKind == OMPC_reduction && 9362 (isOpenMPParallelDirective(DVar.DKind) || 9363 isOpenMPWorksharingDirective(DVar.DKind) || 9364 isOpenMPTeamsDirective(DVar.DKind))) { 9365 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 9366 << getOpenMPDirectiveName(DVar.DKind); 9367 ReportOriginalDSA(*this, DSAStack, D, DVar); 9368 continue; 9369 } 9370 } 9371 9372 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 9373 // A list item cannot appear in both a map clause and a data-sharing 9374 // attribute clause on the same construct 9375 if (isOpenMPTargetExecutionDirective(CurrDir)) { 9376 OpenMPClauseKind ConflictKind; 9377 if (DSAStack->checkMappableExprComponentListsForDecl( 9378 VD, /*CurrentRegionOnly=*/true, 9379 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 9380 OpenMPClauseKind WhereFoundClauseKind) -> bool { 9381 ConflictKind = WhereFoundClauseKind; 9382 return true; 9383 })) { 9384 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 9385 << getOpenMPClauseName(OMPC_firstprivate) 9386 << getOpenMPClauseName(ConflictKind) 9387 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 9388 ReportOriginalDSA(*this, DSAStack, D, DVar); 9389 continue; 9390 } 9391 } 9392 } 9393 9394 // Variably modified types are not supported for tasks. 9395 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 9396 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 9397 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9398 << getOpenMPClauseName(OMPC_firstprivate) << Type 9399 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 9400 bool IsDecl = 9401 !VD || 9402 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9403 Diag(D->getLocation(), 9404 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9405 << D; 9406 continue; 9407 } 9408 9409 Type = Type.getUnqualifiedType(); 9410 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 9411 D->hasAttrs() ? &D->getAttrs() : nullptr); 9412 // Generate helper private variable and initialize it with the value of the 9413 // original variable. The address of the original variable is replaced by 9414 // the address of the new private variable in the CodeGen. This new variable 9415 // is not added to IdResolver, so the code in the OpenMP region uses 9416 // original variable for proper diagnostics and variable capturing. 9417 Expr *VDInitRefExpr = nullptr; 9418 // For arrays generate initializer for single element and replace it by the 9419 // original array element in CodeGen. 9420 if (Type->isArrayType()) { 9421 auto VDInit = 9422 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 9423 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 9424 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 9425 ElemType = ElemType.getUnqualifiedType(); 9426 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 9427 ".firstprivate.temp"); 9428 InitializedEntity Entity = 9429 InitializedEntity::InitializeVariable(VDInitTemp); 9430 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 9431 9432 InitializationSequence InitSeq(*this, Entity, Kind, Init); 9433 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 9434 if (Result.isInvalid()) 9435 VDPrivate->setInvalidDecl(); 9436 else 9437 VDPrivate->setInit(Result.getAs<Expr>()); 9438 // Remove temp variable declaration. 9439 Context.Deallocate(VDInitTemp); 9440 } else { 9441 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 9442 ".firstprivate.temp"); 9443 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 9444 RefExpr->getExprLoc()); 9445 AddInitializerToDecl(VDPrivate, 9446 DefaultLvalueConversion(VDInitRefExpr).get(), 9447 /*DirectInit=*/false); 9448 } 9449 if (VDPrivate->isInvalidDecl()) { 9450 if (IsImplicitClause) { 9451 Diag(RefExpr->getExprLoc(), 9452 diag::note_omp_task_predetermined_firstprivate_here); 9453 } 9454 continue; 9455 } 9456 CurContext->addDecl(VDPrivate); 9457 auto VDPrivateRefExpr = buildDeclRefExpr( 9458 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 9459 RefExpr->getExprLoc()); 9460 DeclRefExpr *Ref = nullptr; 9461 if (!VD && !CurContext->isDependentContext()) { 9462 if (TopDVar.CKind == OMPC_lastprivate) 9463 Ref = TopDVar.PrivateCopy; 9464 else { 9465 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9466 if (!IsOpenMPCapturedDecl(D)) 9467 ExprCaptures.push_back(Ref->getDecl()); 9468 } 9469 } 9470 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 9471 Vars.push_back((VD || CurContext->isDependentContext()) 9472 ? RefExpr->IgnoreParens() 9473 : Ref); 9474 PrivateCopies.push_back(VDPrivateRefExpr); 9475 Inits.push_back(VDInitRefExpr); 9476 } 9477 9478 if (Vars.empty()) 9479 return nullptr; 9480 9481 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9482 Vars, PrivateCopies, Inits, 9483 buildPreInits(Context, ExprCaptures)); 9484 } 9485 9486 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 9487 SourceLocation StartLoc, 9488 SourceLocation LParenLoc, 9489 SourceLocation EndLoc) { 9490 SmallVector<Expr *, 8> Vars; 9491 SmallVector<Expr *, 8> SrcExprs; 9492 SmallVector<Expr *, 8> DstExprs; 9493 SmallVector<Expr *, 8> AssignmentOps; 9494 SmallVector<Decl *, 4> ExprCaptures; 9495 SmallVector<Expr *, 4> ExprPostUpdates; 9496 for (auto &RefExpr : VarList) { 9497 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 9498 SourceLocation ELoc; 9499 SourceRange ERange; 9500 Expr *SimpleRefExpr = RefExpr; 9501 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9502 if (Res.second) { 9503 // It will be analyzed later. 9504 Vars.push_back(RefExpr); 9505 SrcExprs.push_back(nullptr); 9506 DstExprs.push_back(nullptr); 9507 AssignmentOps.push_back(nullptr); 9508 } 9509 ValueDecl *D = Res.first; 9510 if (!D) 9511 continue; 9512 9513 QualType Type = D->getType(); 9514 auto *VD = dyn_cast<VarDecl>(D); 9515 9516 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 9517 // A variable that appears in a lastprivate clause must not have an 9518 // incomplete type or a reference type. 9519 if (RequireCompleteType(ELoc, Type, 9520 diag::err_omp_lastprivate_incomplete_type)) 9521 continue; 9522 Type = Type.getNonReferenceType(); 9523 9524 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9525 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 9526 // in a Construct] 9527 // Variables with the predetermined data-sharing attributes may not be 9528 // listed in data-sharing attributes clauses, except for the cases 9529 // listed below. 9530 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 9531 // A list item may appear in a firstprivate or lastprivate clause but not 9532 // both. 9533 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9534 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 9535 (isOpenMPDistributeDirective(CurrDir) || 9536 DVar.CKind != OMPC_firstprivate) && 9537 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 9538 Diag(ELoc, diag::err_omp_wrong_dsa) 9539 << getOpenMPClauseName(DVar.CKind) 9540 << getOpenMPClauseName(OMPC_lastprivate); 9541 ReportOriginalDSA(*this, DSAStack, D, DVar); 9542 continue; 9543 } 9544 9545 // OpenMP [2.14.3.5, Restrictions, p.2] 9546 // A list item that is private within a parallel region, or that appears in 9547 // the reduction clause of a parallel construct, must not appear in a 9548 // lastprivate clause on a worksharing construct if any of the corresponding 9549 // worksharing regions ever binds to any of the corresponding parallel 9550 // regions. 9551 DSAStackTy::DSAVarData TopDVar = DVar; 9552 if (isOpenMPWorksharingDirective(CurrDir) && 9553 !isOpenMPParallelDirective(CurrDir) && 9554 !isOpenMPTeamsDirective(CurrDir)) { 9555 DVar = DSAStack->getImplicitDSA(D, true); 9556 if (DVar.CKind != OMPC_shared) { 9557 Diag(ELoc, diag::err_omp_required_access) 9558 << getOpenMPClauseName(OMPC_lastprivate) 9559 << getOpenMPClauseName(OMPC_shared); 9560 ReportOriginalDSA(*this, DSAStack, D, DVar); 9561 continue; 9562 } 9563 } 9564 9565 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 9566 // A variable of class type (or array thereof) that appears in a 9567 // lastprivate clause requires an accessible, unambiguous default 9568 // constructor for the class type, unless the list item is also specified 9569 // in a firstprivate clause. 9570 // A variable of class type (or array thereof) that appears in a 9571 // lastprivate clause requires an accessible, unambiguous copy assignment 9572 // operator for the class type. 9573 Type = Context.getBaseElementType(Type).getNonReferenceType(); 9574 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 9575 Type.getUnqualifiedType(), ".lastprivate.src", 9576 D->hasAttrs() ? &D->getAttrs() : nullptr); 9577 auto *PseudoSrcExpr = 9578 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 9579 auto *DstVD = 9580 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 9581 D->hasAttrs() ? &D->getAttrs() : nullptr); 9582 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 9583 // For arrays generate assignment operation for single element and replace 9584 // it by the original array element in CodeGen. 9585 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 9586 PseudoDstExpr, PseudoSrcExpr); 9587 if (AssignmentOp.isInvalid()) 9588 continue; 9589 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 9590 /*DiscardedValue=*/true); 9591 if (AssignmentOp.isInvalid()) 9592 continue; 9593 9594 DeclRefExpr *Ref = nullptr; 9595 if (!VD && !CurContext->isDependentContext()) { 9596 if (TopDVar.CKind == OMPC_firstprivate) 9597 Ref = TopDVar.PrivateCopy; 9598 else { 9599 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9600 if (!IsOpenMPCapturedDecl(D)) 9601 ExprCaptures.push_back(Ref->getDecl()); 9602 } 9603 if (TopDVar.CKind == OMPC_firstprivate || 9604 (!IsOpenMPCapturedDecl(D) && 9605 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 9606 ExprResult RefRes = DefaultLvalueConversion(Ref); 9607 if (!RefRes.isUsable()) 9608 continue; 9609 ExprResult PostUpdateRes = 9610 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 9611 RefRes.get()); 9612 if (!PostUpdateRes.isUsable()) 9613 continue; 9614 ExprPostUpdates.push_back( 9615 IgnoredValueConversions(PostUpdateRes.get()).get()); 9616 } 9617 } 9618 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 9619 Vars.push_back((VD || CurContext->isDependentContext()) 9620 ? RefExpr->IgnoreParens() 9621 : Ref); 9622 SrcExprs.push_back(PseudoSrcExpr); 9623 DstExprs.push_back(PseudoDstExpr); 9624 AssignmentOps.push_back(AssignmentOp.get()); 9625 } 9626 9627 if (Vars.empty()) 9628 return nullptr; 9629 9630 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9631 Vars, SrcExprs, DstExprs, AssignmentOps, 9632 buildPreInits(Context, ExprCaptures), 9633 buildPostUpdate(*this, ExprPostUpdates)); 9634 } 9635 9636 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 9637 SourceLocation StartLoc, 9638 SourceLocation LParenLoc, 9639 SourceLocation EndLoc) { 9640 SmallVector<Expr *, 8> Vars; 9641 for (auto &RefExpr : VarList) { 9642 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 9643 SourceLocation ELoc; 9644 SourceRange ERange; 9645 Expr *SimpleRefExpr = RefExpr; 9646 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9647 if (Res.second) { 9648 // It will be analyzed later. 9649 Vars.push_back(RefExpr); 9650 } 9651 ValueDecl *D = Res.first; 9652 if (!D) 9653 continue; 9654 9655 auto *VD = dyn_cast<VarDecl>(D); 9656 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9657 // in a Construct] 9658 // Variables with the predetermined data-sharing attributes may not be 9659 // listed in data-sharing attributes clauses, except for the cases 9660 // listed below. For these exceptions only, listing a predetermined 9661 // variable in a data-sharing attribute clause is allowed and overrides 9662 // the variable's predetermined data-sharing attributes. 9663 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9664 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 9665 DVar.RefExpr) { 9666 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9667 << getOpenMPClauseName(OMPC_shared); 9668 ReportOriginalDSA(*this, DSAStack, D, DVar); 9669 continue; 9670 } 9671 9672 DeclRefExpr *Ref = nullptr; 9673 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 9674 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9675 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 9676 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 9677 ? RefExpr->IgnoreParens() 9678 : Ref); 9679 } 9680 9681 if (Vars.empty()) 9682 return nullptr; 9683 9684 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 9685 } 9686 9687 namespace { 9688 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 9689 DSAStackTy *Stack; 9690 9691 public: 9692 bool VisitDeclRefExpr(DeclRefExpr *E) { 9693 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 9694 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 9695 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 9696 return false; 9697 if (DVar.CKind != OMPC_unknown) 9698 return true; 9699 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 9700 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 9701 /*FromParent=*/true); 9702 if (DVarPrivate.CKind != OMPC_unknown) 9703 return true; 9704 return false; 9705 } 9706 return false; 9707 } 9708 bool VisitStmt(Stmt *S) { 9709 for (auto Child : S->children()) { 9710 if (Child && Visit(Child)) 9711 return true; 9712 } 9713 return false; 9714 } 9715 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 9716 }; 9717 } // namespace 9718 9719 namespace { 9720 // Transform MemberExpression for specified FieldDecl of current class to 9721 // DeclRefExpr to specified OMPCapturedExprDecl. 9722 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 9723 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 9724 ValueDecl *Field; 9725 DeclRefExpr *CapturedExpr; 9726 9727 public: 9728 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 9729 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 9730 9731 ExprResult TransformMemberExpr(MemberExpr *E) { 9732 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 9733 E->getMemberDecl() == Field) { 9734 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 9735 return CapturedExpr; 9736 } 9737 return BaseTransform::TransformMemberExpr(E); 9738 } 9739 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 9740 }; 9741 } // namespace 9742 9743 template <typename T> 9744 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 9745 const llvm::function_ref<T(ValueDecl *)> &Gen) { 9746 for (auto &Set : Lookups) { 9747 for (auto *D : Set) { 9748 if (auto Res = Gen(cast<ValueDecl>(D))) 9749 return Res; 9750 } 9751 } 9752 return T(); 9753 } 9754 9755 static ExprResult 9756 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 9757 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 9758 const DeclarationNameInfo &ReductionId, QualType Ty, 9759 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 9760 if (ReductionIdScopeSpec.isInvalid()) 9761 return ExprError(); 9762 SmallVector<UnresolvedSet<8>, 4> Lookups; 9763 if (S) { 9764 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 9765 Lookup.suppressDiagnostics(); 9766 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 9767 auto *D = Lookup.getRepresentativeDecl(); 9768 do { 9769 S = S->getParent(); 9770 } while (S && !S->isDeclScope(D)); 9771 if (S) 9772 S = S->getParent(); 9773 Lookups.push_back(UnresolvedSet<8>()); 9774 Lookups.back().append(Lookup.begin(), Lookup.end()); 9775 Lookup.clear(); 9776 } 9777 } else if (auto *ULE = 9778 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 9779 Lookups.push_back(UnresolvedSet<8>()); 9780 Decl *PrevD = nullptr; 9781 for (auto *D : ULE->decls()) { 9782 if (D == PrevD) 9783 Lookups.push_back(UnresolvedSet<8>()); 9784 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 9785 Lookups.back().addDecl(DRD); 9786 PrevD = D; 9787 } 9788 } 9789 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 9790 Ty->isInstantiationDependentType() || 9791 Ty->containsUnexpandedParameterPack() || 9792 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 9793 return !D->isInvalidDecl() && 9794 (D->getType()->isDependentType() || 9795 D->getType()->isInstantiationDependentType() || 9796 D->getType()->containsUnexpandedParameterPack()); 9797 })) { 9798 UnresolvedSet<8> ResSet; 9799 for (auto &Set : Lookups) { 9800 ResSet.append(Set.begin(), Set.end()); 9801 // The last item marks the end of all declarations at the specified scope. 9802 ResSet.addDecl(Set[Set.size() - 1]); 9803 } 9804 return UnresolvedLookupExpr::Create( 9805 SemaRef.Context, /*NamingClass=*/nullptr, 9806 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 9807 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 9808 } 9809 if (auto *VD = filterLookupForUDR<ValueDecl *>( 9810 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 9811 if (!D->isInvalidDecl() && 9812 SemaRef.Context.hasSameType(D->getType(), Ty)) 9813 return D; 9814 return nullptr; 9815 })) 9816 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 9817 if (auto *VD = filterLookupForUDR<ValueDecl *>( 9818 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 9819 if (!D->isInvalidDecl() && 9820 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 9821 !Ty.isMoreQualifiedThan(D->getType())) 9822 return D; 9823 return nullptr; 9824 })) { 9825 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9826 /*DetectVirtual=*/false); 9827 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 9828 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 9829 VD->getType().getUnqualifiedType()))) { 9830 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 9831 /*DiagID=*/0) != 9832 Sema::AR_inaccessible) { 9833 SemaRef.BuildBasePathArray(Paths, BasePath); 9834 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 9835 } 9836 } 9837 } 9838 } 9839 if (ReductionIdScopeSpec.isSet()) { 9840 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 9841 return ExprError(); 9842 } 9843 return ExprEmpty(); 9844 } 9845 9846 namespace { 9847 /// Data for the reduction-based clauses. 9848 struct ReductionData { 9849 /// List of original reduction items. 9850 SmallVector<Expr *, 8> Vars; 9851 /// List of private copies of the reduction items. 9852 SmallVector<Expr *, 8> Privates; 9853 /// LHS expressions for the reduction_op expressions. 9854 SmallVector<Expr *, 8> LHSs; 9855 /// RHS expressions for the reduction_op expressions. 9856 SmallVector<Expr *, 8> RHSs; 9857 /// Reduction operation expression. 9858 SmallVector<Expr *, 8> ReductionOps; 9859 /// Taskgroup descriptors for the corresponding reduction items in 9860 /// in_reduction clauses. 9861 SmallVector<Expr *, 8> TaskgroupDescriptors; 9862 /// List of captures for clause. 9863 SmallVector<Decl *, 4> ExprCaptures; 9864 /// List of postupdate expressions. 9865 SmallVector<Expr *, 4> ExprPostUpdates; 9866 ReductionData() = delete; 9867 /// Reserves required memory for the reduction data. 9868 ReductionData(unsigned Size) { 9869 Vars.reserve(Size); 9870 Privates.reserve(Size); 9871 LHSs.reserve(Size); 9872 RHSs.reserve(Size); 9873 ReductionOps.reserve(Size); 9874 TaskgroupDescriptors.reserve(Size); 9875 ExprCaptures.reserve(Size); 9876 ExprPostUpdates.reserve(Size); 9877 } 9878 /// Stores reduction item and reduction operation only (required for dependent 9879 /// reduction item). 9880 void push(Expr *Item, Expr *ReductionOp) { 9881 Vars.emplace_back(Item); 9882 Privates.emplace_back(nullptr); 9883 LHSs.emplace_back(nullptr); 9884 RHSs.emplace_back(nullptr); 9885 ReductionOps.emplace_back(ReductionOp); 9886 TaskgroupDescriptors.emplace_back(nullptr); 9887 } 9888 /// Stores reduction data. 9889 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 9890 Expr *TaskgroupDescriptor) { 9891 Vars.emplace_back(Item); 9892 Privates.emplace_back(Private); 9893 LHSs.emplace_back(LHS); 9894 RHSs.emplace_back(RHS); 9895 ReductionOps.emplace_back(ReductionOp); 9896 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 9897 } 9898 }; 9899 } // namespace 9900 9901 static bool CheckOMPArraySectionConstantForReduction( 9902 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 9903 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 9904 const Expr *Length = OASE->getLength(); 9905 if (Length == nullptr) { 9906 // For array sections of the form [1:] or [:], we would need to analyze 9907 // the lower bound... 9908 if (OASE->getColonLoc().isValid()) 9909 return false; 9910 9911 // This is an array subscript which has implicit length 1! 9912 SingleElement = true; 9913 ArraySizes.push_back(llvm::APSInt::get(1)); 9914 } else { 9915 llvm::APSInt ConstantLengthValue; 9916 if (!Length->EvaluateAsInt(ConstantLengthValue, Context)) 9917 return false; 9918 9919 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 9920 ArraySizes.push_back(ConstantLengthValue); 9921 } 9922 9923 // Get the base of this array section and walk up from there. 9924 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 9925 9926 // We require length = 1 for all array sections except the right-most to 9927 // guarantee that the memory region is contiguous and has no holes in it. 9928 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 9929 Length = TempOASE->getLength(); 9930 if (Length == nullptr) { 9931 // For array sections of the form [1:] or [:], we would need to analyze 9932 // the lower bound... 9933 if (OASE->getColonLoc().isValid()) 9934 return false; 9935 9936 // This is an array subscript which has implicit length 1! 9937 ArraySizes.push_back(llvm::APSInt::get(1)); 9938 } else { 9939 llvm::APSInt ConstantLengthValue; 9940 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) || 9941 ConstantLengthValue.getSExtValue() != 1) 9942 return false; 9943 9944 ArraySizes.push_back(ConstantLengthValue); 9945 } 9946 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 9947 } 9948 9949 // If we have a single element, we don't need to add the implicit lengths. 9950 if (!SingleElement) { 9951 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 9952 // Has implicit length 1! 9953 ArraySizes.push_back(llvm::APSInt::get(1)); 9954 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9955 } 9956 } 9957 9958 // This array section can be privatized as a single value or as a constant 9959 // sized array. 9960 return true; 9961 } 9962 9963 static bool ActOnOMPReductionKindClause( 9964 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 9965 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 9966 SourceLocation ColonLoc, SourceLocation EndLoc, 9967 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 9968 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 9969 auto DN = ReductionId.getName(); 9970 auto OOK = DN.getCXXOverloadedOperator(); 9971 BinaryOperatorKind BOK = BO_Comma; 9972 9973 ASTContext &Context = S.Context; 9974 // OpenMP [2.14.3.6, reduction clause] 9975 // C 9976 // reduction-identifier is either an identifier or one of the following 9977 // operators: +, -, *, &, |, ^, && and || 9978 // C++ 9979 // reduction-identifier is either an id-expression or one of the following 9980 // operators: +, -, *, &, |, ^, && and || 9981 switch (OOK) { 9982 case OO_Plus: 9983 case OO_Minus: 9984 BOK = BO_Add; 9985 break; 9986 case OO_Star: 9987 BOK = BO_Mul; 9988 break; 9989 case OO_Amp: 9990 BOK = BO_And; 9991 break; 9992 case OO_Pipe: 9993 BOK = BO_Or; 9994 break; 9995 case OO_Caret: 9996 BOK = BO_Xor; 9997 break; 9998 case OO_AmpAmp: 9999 BOK = BO_LAnd; 10000 break; 10001 case OO_PipePipe: 10002 BOK = BO_LOr; 10003 break; 10004 case OO_New: 10005 case OO_Delete: 10006 case OO_Array_New: 10007 case OO_Array_Delete: 10008 case OO_Slash: 10009 case OO_Percent: 10010 case OO_Tilde: 10011 case OO_Exclaim: 10012 case OO_Equal: 10013 case OO_Less: 10014 case OO_Greater: 10015 case OO_LessEqual: 10016 case OO_GreaterEqual: 10017 case OO_PlusEqual: 10018 case OO_MinusEqual: 10019 case OO_StarEqual: 10020 case OO_SlashEqual: 10021 case OO_PercentEqual: 10022 case OO_CaretEqual: 10023 case OO_AmpEqual: 10024 case OO_PipeEqual: 10025 case OO_LessLess: 10026 case OO_GreaterGreater: 10027 case OO_LessLessEqual: 10028 case OO_GreaterGreaterEqual: 10029 case OO_EqualEqual: 10030 case OO_ExclaimEqual: 10031 case OO_Spaceship: 10032 case OO_PlusPlus: 10033 case OO_MinusMinus: 10034 case OO_Comma: 10035 case OO_ArrowStar: 10036 case OO_Arrow: 10037 case OO_Call: 10038 case OO_Subscript: 10039 case OO_Conditional: 10040 case OO_Coawait: 10041 case NUM_OVERLOADED_OPERATORS: 10042 llvm_unreachable("Unexpected reduction identifier"); 10043 case OO_None: 10044 if (auto *II = DN.getAsIdentifierInfo()) { 10045 if (II->isStr("max")) 10046 BOK = BO_GT; 10047 else if (II->isStr("min")) 10048 BOK = BO_LT; 10049 } 10050 break; 10051 } 10052 SourceRange ReductionIdRange; 10053 if (ReductionIdScopeSpec.isValid()) 10054 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 10055 else 10056 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 10057 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 10058 10059 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 10060 bool FirstIter = true; 10061 for (auto RefExpr : VarList) { 10062 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 10063 // OpenMP [2.1, C/C++] 10064 // A list item is a variable or array section, subject to the restrictions 10065 // specified in Section 2.4 on page 42 and in each of the sections 10066 // describing clauses and directives for which a list appears. 10067 // OpenMP [2.14.3.3, Restrictions, p.1] 10068 // A variable that is part of another variable (as an array or 10069 // structure element) cannot appear in a private clause. 10070 if (!FirstIter && IR != ER) 10071 ++IR; 10072 FirstIter = false; 10073 SourceLocation ELoc; 10074 SourceRange ERange; 10075 Expr *SimpleRefExpr = RefExpr; 10076 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 10077 /*AllowArraySection=*/true); 10078 if (Res.second) { 10079 // Try to find 'declare reduction' corresponding construct before using 10080 // builtin/overloaded operators. 10081 QualType Type = Context.DependentTy; 10082 CXXCastPath BasePath; 10083 ExprResult DeclareReductionRef = buildDeclareReductionRef( 10084 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 10085 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 10086 Expr *ReductionOp = nullptr; 10087 if (S.CurContext->isDependentContext() && 10088 (DeclareReductionRef.isUnset() || 10089 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 10090 ReductionOp = DeclareReductionRef.get(); 10091 // It will be analyzed later. 10092 RD.push(RefExpr, ReductionOp); 10093 } 10094 ValueDecl *D = Res.first; 10095 if (!D) 10096 continue; 10097 10098 Expr *TaskgroupDescriptor = nullptr; 10099 QualType Type; 10100 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 10101 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 10102 if (ASE) 10103 Type = ASE->getType().getNonReferenceType(); 10104 else if (OASE) { 10105 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 10106 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 10107 Type = ATy->getElementType(); 10108 else 10109 Type = BaseType->getPointeeType(); 10110 Type = Type.getNonReferenceType(); 10111 } else 10112 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 10113 auto *VD = dyn_cast<VarDecl>(D); 10114 10115 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 10116 // A variable that appears in a private clause must not have an incomplete 10117 // type or a reference type. 10118 if (S.RequireCompleteType(ELoc, Type, 10119 diag::err_omp_reduction_incomplete_type)) 10120 continue; 10121 // OpenMP [2.14.3.6, reduction clause, Restrictions] 10122 // A list item that appears in a reduction clause must not be 10123 // const-qualified. 10124 if (Type.getNonReferenceType().isConstant(Context)) { 10125 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange; 10126 if (!ASE && !OASE) { 10127 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 10128 VarDecl::DeclarationOnly; 10129 S.Diag(D->getLocation(), 10130 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10131 << D; 10132 } 10133 continue; 10134 } 10135 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 10136 // If a list-item is a reference type then it must bind to the same object 10137 // for all threads of the team. 10138 if (!ASE && !OASE && VD) { 10139 VarDecl *VDDef = VD->getDefinition(); 10140 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 10141 DSARefChecker Check(Stack); 10142 if (Check.Visit(VDDef->getInit())) { 10143 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 10144 << getOpenMPClauseName(ClauseKind) << ERange; 10145 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 10146 continue; 10147 } 10148 } 10149 } 10150 10151 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 10152 // in a Construct] 10153 // Variables with the predetermined data-sharing attributes may not be 10154 // listed in data-sharing attributes clauses, except for the cases 10155 // listed below. For these exceptions only, listing a predetermined 10156 // variable in a data-sharing attribute clause is allowed and overrides 10157 // the variable's predetermined data-sharing attributes. 10158 // OpenMP [2.14.3.6, Restrictions, p.3] 10159 // Any number of reduction clauses can be specified on the directive, 10160 // but a list item can appear only once in the reduction clauses for that 10161 // directive. 10162 DSAStackTy::DSAVarData DVar; 10163 DVar = Stack->getTopDSA(D, false); 10164 if (DVar.CKind == OMPC_reduction) { 10165 S.Diag(ELoc, diag::err_omp_once_referenced) 10166 << getOpenMPClauseName(ClauseKind); 10167 if (DVar.RefExpr) 10168 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 10169 continue; 10170 } else if (DVar.CKind != OMPC_unknown) { 10171 S.Diag(ELoc, diag::err_omp_wrong_dsa) 10172 << getOpenMPClauseName(DVar.CKind) 10173 << getOpenMPClauseName(OMPC_reduction); 10174 ReportOriginalDSA(S, Stack, D, DVar); 10175 continue; 10176 } 10177 10178 // OpenMP [2.14.3.6, Restrictions, p.1] 10179 // A list item that appears in a reduction clause of a worksharing 10180 // construct must be shared in the parallel regions to which any of the 10181 // worksharing regions arising from the worksharing construct bind. 10182 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 10183 if (isOpenMPWorksharingDirective(CurrDir) && 10184 !isOpenMPParallelDirective(CurrDir) && 10185 !isOpenMPTeamsDirective(CurrDir)) { 10186 DVar = Stack->getImplicitDSA(D, true); 10187 if (DVar.CKind != OMPC_shared) { 10188 S.Diag(ELoc, diag::err_omp_required_access) 10189 << getOpenMPClauseName(OMPC_reduction) 10190 << getOpenMPClauseName(OMPC_shared); 10191 ReportOriginalDSA(S, Stack, D, DVar); 10192 continue; 10193 } 10194 } 10195 10196 // Try to find 'declare reduction' corresponding construct before using 10197 // builtin/overloaded operators. 10198 CXXCastPath BasePath; 10199 ExprResult DeclareReductionRef = buildDeclareReductionRef( 10200 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 10201 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 10202 if (DeclareReductionRef.isInvalid()) 10203 continue; 10204 if (S.CurContext->isDependentContext() && 10205 (DeclareReductionRef.isUnset() || 10206 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 10207 RD.push(RefExpr, DeclareReductionRef.get()); 10208 continue; 10209 } 10210 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 10211 // Not allowed reduction identifier is found. 10212 S.Diag(ReductionId.getLocStart(), 10213 diag::err_omp_unknown_reduction_identifier) 10214 << Type << ReductionIdRange; 10215 continue; 10216 } 10217 10218 // OpenMP [2.14.3.6, reduction clause, Restrictions] 10219 // The type of a list item that appears in a reduction clause must be valid 10220 // for the reduction-identifier. For a max or min reduction in C, the type 10221 // of the list item must be an allowed arithmetic data type: char, int, 10222 // float, double, or _Bool, possibly modified with long, short, signed, or 10223 // unsigned. For a max or min reduction in C++, the type of the list item 10224 // must be an allowed arithmetic data type: char, wchar_t, int, float, 10225 // double, or bool, possibly modified with long, short, signed, or unsigned. 10226 if (DeclareReductionRef.isUnset()) { 10227 if ((BOK == BO_GT || BOK == BO_LT) && 10228 !(Type->isScalarType() || 10229 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 10230 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 10231 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 10232 if (!ASE && !OASE) { 10233 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 10234 VarDecl::DeclarationOnly; 10235 S.Diag(D->getLocation(), 10236 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10237 << D; 10238 } 10239 continue; 10240 } 10241 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 10242 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 10243 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 10244 << getOpenMPClauseName(ClauseKind); 10245 if (!ASE && !OASE) { 10246 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 10247 VarDecl::DeclarationOnly; 10248 S.Diag(D->getLocation(), 10249 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10250 << D; 10251 } 10252 continue; 10253 } 10254 } 10255 10256 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 10257 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 10258 D->hasAttrs() ? &D->getAttrs() : nullptr); 10259 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 10260 D->hasAttrs() ? &D->getAttrs() : nullptr); 10261 auto PrivateTy = Type; 10262 10263 // Try if we can determine constant lengths for all array sections and avoid 10264 // the VLA. 10265 bool ConstantLengthOASE = false; 10266 if (OASE) { 10267 bool SingleElement; 10268 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 10269 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction( 10270 Context, OASE, SingleElement, ArraySizes); 10271 10272 // If we don't have a single element, we must emit a constant array type. 10273 if (ConstantLengthOASE && !SingleElement) { 10274 for (auto &Size : ArraySizes) { 10275 PrivateTy = Context.getConstantArrayType( 10276 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0); 10277 } 10278 } 10279 } 10280 10281 if ((OASE && !ConstantLengthOASE) || 10282 (!OASE && !ASE && 10283 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 10284 if (!Context.getTargetInfo().isVLASupported() && 10285 S.shouldDiagnoseTargetSupportFromOpenMP()) { 10286 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 10287 S.Diag(ELoc, diag::note_vla_unsupported); 10288 continue; 10289 } 10290 // For arrays/array sections only: 10291 // Create pseudo array type for private copy. The size for this array will 10292 // be generated during codegen. 10293 // For array subscripts or single variables Private Ty is the same as Type 10294 // (type of the variable or single array element). 10295 PrivateTy = Context.getVariableArrayType( 10296 Type, 10297 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue), 10298 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 10299 } else if (!ASE && !OASE && 10300 Context.getAsArrayType(D->getType().getNonReferenceType())) 10301 PrivateTy = D->getType().getNonReferenceType(); 10302 // Private copy. 10303 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(), 10304 D->hasAttrs() ? &D->getAttrs() : nullptr); 10305 // Add initializer for private variable. 10306 Expr *Init = nullptr; 10307 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 10308 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 10309 if (DeclareReductionRef.isUsable()) { 10310 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 10311 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 10312 if (DRD->getInitializer()) { 10313 Init = DRDRef; 10314 RHSVD->setInit(DRDRef); 10315 RHSVD->setInitStyle(VarDecl::CallInit); 10316 } 10317 } else { 10318 switch (BOK) { 10319 case BO_Add: 10320 case BO_Xor: 10321 case BO_Or: 10322 case BO_LOr: 10323 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 10324 if (Type->isScalarType() || Type->isAnyComplexType()) 10325 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 10326 break; 10327 case BO_Mul: 10328 case BO_LAnd: 10329 if (Type->isScalarType() || Type->isAnyComplexType()) { 10330 // '*' and '&&' reduction ops - initializer is '1'. 10331 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 10332 } 10333 break; 10334 case BO_And: { 10335 // '&' reduction op - initializer is '~0'. 10336 QualType OrigType = Type; 10337 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 10338 Type = ComplexTy->getElementType(); 10339 if (Type->isRealFloatingType()) { 10340 llvm::APFloat InitValue = 10341 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 10342 /*isIEEE=*/true); 10343 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 10344 Type, ELoc); 10345 } else if (Type->isScalarType()) { 10346 auto Size = Context.getTypeSize(Type); 10347 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 10348 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 10349 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 10350 } 10351 if (Init && OrigType->isAnyComplexType()) { 10352 // Init = 0xFFFF + 0xFFFFi; 10353 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 10354 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 10355 } 10356 Type = OrigType; 10357 break; 10358 } 10359 case BO_LT: 10360 case BO_GT: { 10361 // 'min' reduction op - initializer is 'Largest representable number in 10362 // the reduction list item type'. 10363 // 'max' reduction op - initializer is 'Least representable number in 10364 // the reduction list item type'. 10365 if (Type->isIntegerType() || Type->isPointerType()) { 10366 bool IsSigned = Type->hasSignedIntegerRepresentation(); 10367 auto Size = Context.getTypeSize(Type); 10368 QualType IntTy = 10369 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 10370 llvm::APInt InitValue = 10371 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 10372 : llvm::APInt::getMinValue(Size) 10373 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 10374 : llvm::APInt::getMaxValue(Size); 10375 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 10376 if (Type->isPointerType()) { 10377 // Cast to pointer type. 10378 auto CastExpr = S.BuildCStyleCastExpr( 10379 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 10380 if (CastExpr.isInvalid()) 10381 continue; 10382 Init = CastExpr.get(); 10383 } 10384 } else if (Type->isRealFloatingType()) { 10385 llvm::APFloat InitValue = llvm::APFloat::getLargest( 10386 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 10387 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 10388 Type, ELoc); 10389 } 10390 break; 10391 } 10392 case BO_PtrMemD: 10393 case BO_PtrMemI: 10394 case BO_MulAssign: 10395 case BO_Div: 10396 case BO_Rem: 10397 case BO_Sub: 10398 case BO_Shl: 10399 case BO_Shr: 10400 case BO_LE: 10401 case BO_GE: 10402 case BO_EQ: 10403 case BO_NE: 10404 case BO_Cmp: 10405 case BO_AndAssign: 10406 case BO_XorAssign: 10407 case BO_OrAssign: 10408 case BO_Assign: 10409 case BO_AddAssign: 10410 case BO_SubAssign: 10411 case BO_DivAssign: 10412 case BO_RemAssign: 10413 case BO_ShlAssign: 10414 case BO_ShrAssign: 10415 case BO_Comma: 10416 llvm_unreachable("Unexpected reduction operation"); 10417 } 10418 } 10419 if (Init && DeclareReductionRef.isUnset()) 10420 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 10421 else if (!Init) 10422 S.ActOnUninitializedDecl(RHSVD); 10423 if (RHSVD->isInvalidDecl()) 10424 continue; 10425 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 10426 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 10427 << Type << ReductionIdRange; 10428 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 10429 VarDecl::DeclarationOnly; 10430 S.Diag(D->getLocation(), 10431 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10432 << D; 10433 continue; 10434 } 10435 // Store initializer for single element in private copy. Will be used during 10436 // codegen. 10437 PrivateVD->setInit(RHSVD->getInit()); 10438 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 10439 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 10440 ExprResult ReductionOp; 10441 if (DeclareReductionRef.isUsable()) { 10442 QualType RedTy = DeclareReductionRef.get()->getType(); 10443 QualType PtrRedTy = Context.getPointerType(RedTy); 10444 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 10445 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 10446 if (!BasePath.empty()) { 10447 LHS = S.DefaultLvalueConversion(LHS.get()); 10448 RHS = S.DefaultLvalueConversion(RHS.get()); 10449 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 10450 CK_UncheckedDerivedToBase, LHS.get(), 10451 &BasePath, LHS.get()->getValueKind()); 10452 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 10453 CK_UncheckedDerivedToBase, RHS.get(), 10454 &BasePath, RHS.get()->getValueKind()); 10455 } 10456 FunctionProtoType::ExtProtoInfo EPI; 10457 QualType Params[] = {PtrRedTy, PtrRedTy}; 10458 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 10459 auto *OVE = new (Context) OpaqueValueExpr( 10460 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 10461 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 10462 Expr *Args[] = {LHS.get(), RHS.get()}; 10463 ReductionOp = new (Context) 10464 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 10465 } else { 10466 ReductionOp = S.BuildBinOp( 10467 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 10468 if (ReductionOp.isUsable()) { 10469 if (BOK != BO_LT && BOK != BO_GT) { 10470 ReductionOp = 10471 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), 10472 BO_Assign, LHSDRE, ReductionOp.get()); 10473 } else { 10474 auto *ConditionalOp = new (Context) 10475 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE, 10476 Type, VK_LValue, OK_Ordinary); 10477 ReductionOp = 10478 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), 10479 BO_Assign, LHSDRE, ConditionalOp); 10480 } 10481 if (ReductionOp.isUsable()) 10482 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get()); 10483 } 10484 if (!ReductionOp.isUsable()) 10485 continue; 10486 } 10487 10488 // OpenMP [2.15.4.6, Restrictions, p.2] 10489 // A list item that appears in an in_reduction clause of a task construct 10490 // must appear in a task_reduction clause of a construct associated with a 10491 // taskgroup region that includes the participating task in its taskgroup 10492 // set. The construct associated with the innermost region that meets this 10493 // condition must specify the same reduction-identifier as the in_reduction 10494 // clause. 10495 if (ClauseKind == OMPC_in_reduction) { 10496 SourceRange ParentSR; 10497 BinaryOperatorKind ParentBOK; 10498 const Expr *ParentReductionOp; 10499 Expr *ParentBOKTD, *ParentReductionOpTD; 10500 DSAStackTy::DSAVarData ParentBOKDSA = 10501 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 10502 ParentBOKTD); 10503 DSAStackTy::DSAVarData ParentReductionOpDSA = 10504 Stack->getTopMostTaskgroupReductionData( 10505 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 10506 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 10507 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 10508 if (!IsParentBOK && !IsParentReductionOp) { 10509 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction); 10510 continue; 10511 } 10512 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 10513 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK || 10514 IsParentReductionOp) { 10515 bool EmitError = true; 10516 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 10517 llvm::FoldingSetNodeID RedId, ParentRedId; 10518 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 10519 DeclareReductionRef.get()->Profile(RedId, Context, 10520 /*Canonical=*/true); 10521 EmitError = RedId != ParentRedId; 10522 } 10523 if (EmitError) { 10524 S.Diag(ReductionId.getLocStart(), 10525 diag::err_omp_reduction_identifier_mismatch) 10526 << ReductionIdRange << RefExpr->getSourceRange(); 10527 S.Diag(ParentSR.getBegin(), 10528 diag::note_omp_previous_reduction_identifier) 10529 << ParentSR 10530 << (IsParentBOK ? ParentBOKDSA.RefExpr 10531 : ParentReductionOpDSA.RefExpr) 10532 ->getSourceRange(); 10533 continue; 10534 } 10535 } 10536 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 10537 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined."); 10538 } 10539 10540 DeclRefExpr *Ref = nullptr; 10541 Expr *VarsExpr = RefExpr->IgnoreParens(); 10542 if (!VD && !S.CurContext->isDependentContext()) { 10543 if (ASE || OASE) { 10544 TransformExprToCaptures RebuildToCapture(S, D); 10545 VarsExpr = 10546 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 10547 Ref = RebuildToCapture.getCapturedExpr(); 10548 } else { 10549 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 10550 } 10551 if (!S.IsOpenMPCapturedDecl(D)) { 10552 RD.ExprCaptures.emplace_back(Ref->getDecl()); 10553 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 10554 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 10555 if (!RefRes.isUsable()) 10556 continue; 10557 ExprResult PostUpdateRes = 10558 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 10559 RefRes.get()); 10560 if (!PostUpdateRes.isUsable()) 10561 continue; 10562 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 10563 Stack->getCurrentDirective() == OMPD_taskgroup) { 10564 S.Diag(RefExpr->getExprLoc(), 10565 diag::err_omp_reduction_non_addressable_expression) 10566 << RefExpr->getSourceRange(); 10567 continue; 10568 } 10569 RD.ExprPostUpdates.emplace_back( 10570 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 10571 } 10572 } 10573 } 10574 // All reduction items are still marked as reduction (to do not increase 10575 // code base size). 10576 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 10577 if (CurrDir == OMPD_taskgroup) { 10578 if (DeclareReductionRef.isUsable()) 10579 Stack->addTaskgroupReductionData(D, ReductionIdRange, 10580 DeclareReductionRef.get()); 10581 else 10582 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 10583 } 10584 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 10585 TaskgroupDescriptor); 10586 } 10587 return RD.Vars.empty(); 10588 } 10589 10590 OMPClause *Sema::ActOnOpenMPReductionClause( 10591 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10592 SourceLocation ColonLoc, SourceLocation EndLoc, 10593 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10594 ArrayRef<Expr *> UnresolvedReductions) { 10595 ReductionData RD(VarList.size()); 10596 10597 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 10598 StartLoc, LParenLoc, ColonLoc, EndLoc, 10599 ReductionIdScopeSpec, ReductionId, 10600 UnresolvedReductions, RD)) 10601 return nullptr; 10602 10603 return OMPReductionClause::Create( 10604 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 10605 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 10606 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 10607 buildPreInits(Context, RD.ExprCaptures), 10608 buildPostUpdate(*this, RD.ExprPostUpdates)); 10609 } 10610 10611 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 10612 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10613 SourceLocation ColonLoc, SourceLocation EndLoc, 10614 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10615 ArrayRef<Expr *> UnresolvedReductions) { 10616 ReductionData RD(VarList.size()); 10617 10618 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, 10619 VarList, StartLoc, LParenLoc, ColonLoc, 10620 EndLoc, ReductionIdScopeSpec, ReductionId, 10621 UnresolvedReductions, RD)) 10622 return nullptr; 10623 10624 return OMPTaskReductionClause::Create( 10625 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 10626 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 10627 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 10628 buildPreInits(Context, RD.ExprCaptures), 10629 buildPostUpdate(*this, RD.ExprPostUpdates)); 10630 } 10631 10632 OMPClause *Sema::ActOnOpenMPInReductionClause( 10633 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10634 SourceLocation ColonLoc, SourceLocation EndLoc, 10635 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10636 ArrayRef<Expr *> UnresolvedReductions) { 10637 ReductionData RD(VarList.size()); 10638 10639 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 10640 StartLoc, LParenLoc, ColonLoc, EndLoc, 10641 ReductionIdScopeSpec, ReductionId, 10642 UnresolvedReductions, RD)) 10643 return nullptr; 10644 10645 return OMPInReductionClause::Create( 10646 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 10647 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 10648 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 10649 buildPreInits(Context, RD.ExprCaptures), 10650 buildPostUpdate(*this, RD.ExprPostUpdates)); 10651 } 10652 10653 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 10654 SourceLocation LinLoc) { 10655 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 10656 LinKind == OMPC_LINEAR_unknown) { 10657 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 10658 return true; 10659 } 10660 return false; 10661 } 10662 10663 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 10664 OpenMPLinearClauseKind LinKind, 10665 QualType Type) { 10666 auto *VD = dyn_cast_or_null<VarDecl>(D); 10667 // A variable must not have an incomplete type or a reference type. 10668 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 10669 return true; 10670 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 10671 !Type->isReferenceType()) { 10672 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 10673 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 10674 return true; 10675 } 10676 Type = Type.getNonReferenceType(); 10677 10678 // A list item must not be const-qualified. 10679 if (Type.isConstant(Context)) { 10680 Diag(ELoc, diag::err_omp_const_variable) 10681 << getOpenMPClauseName(OMPC_linear); 10682 if (D) { 10683 bool IsDecl = 10684 !VD || 10685 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10686 Diag(D->getLocation(), 10687 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10688 << D; 10689 } 10690 return true; 10691 } 10692 10693 // A list item must be of integral or pointer type. 10694 Type = Type.getUnqualifiedType().getCanonicalType(); 10695 const auto *Ty = Type.getTypePtrOrNull(); 10696 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 10697 !Ty->isPointerType())) { 10698 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 10699 if (D) { 10700 bool IsDecl = 10701 !VD || 10702 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10703 Diag(D->getLocation(), 10704 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10705 << D; 10706 } 10707 return true; 10708 } 10709 return false; 10710 } 10711 10712 OMPClause *Sema::ActOnOpenMPLinearClause( 10713 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 10714 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 10715 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 10716 SmallVector<Expr *, 8> Vars; 10717 SmallVector<Expr *, 8> Privates; 10718 SmallVector<Expr *, 8> Inits; 10719 SmallVector<Decl *, 4> ExprCaptures; 10720 SmallVector<Expr *, 4> ExprPostUpdates; 10721 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 10722 LinKind = OMPC_LINEAR_val; 10723 for (auto &RefExpr : VarList) { 10724 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10725 SourceLocation ELoc; 10726 SourceRange ERange; 10727 Expr *SimpleRefExpr = RefExpr; 10728 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10729 /*AllowArraySection=*/false); 10730 if (Res.second) { 10731 // It will be analyzed later. 10732 Vars.push_back(RefExpr); 10733 Privates.push_back(nullptr); 10734 Inits.push_back(nullptr); 10735 } 10736 ValueDecl *D = Res.first; 10737 if (!D) 10738 continue; 10739 10740 QualType Type = D->getType(); 10741 auto *VD = dyn_cast<VarDecl>(D); 10742 10743 // OpenMP [2.14.3.7, linear clause] 10744 // A list-item cannot appear in more than one linear clause. 10745 // A list-item that appears in a linear clause cannot appear in any 10746 // other data-sharing attribute clause. 10747 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 10748 if (DVar.RefExpr) { 10749 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 10750 << getOpenMPClauseName(OMPC_linear); 10751 ReportOriginalDSA(*this, DSAStack, D, DVar); 10752 continue; 10753 } 10754 10755 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 10756 continue; 10757 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 10758 10759 // Build private copy of original var. 10760 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 10761 D->hasAttrs() ? &D->getAttrs() : nullptr); 10762 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 10763 // Build var to save initial value. 10764 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 10765 Expr *InitExpr; 10766 DeclRefExpr *Ref = nullptr; 10767 if (!VD && !CurContext->isDependentContext()) { 10768 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 10769 if (!IsOpenMPCapturedDecl(D)) { 10770 ExprCaptures.push_back(Ref->getDecl()); 10771 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 10772 ExprResult RefRes = DefaultLvalueConversion(Ref); 10773 if (!RefRes.isUsable()) 10774 continue; 10775 ExprResult PostUpdateRes = 10776 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 10777 SimpleRefExpr, RefRes.get()); 10778 if (!PostUpdateRes.isUsable()) 10779 continue; 10780 ExprPostUpdates.push_back( 10781 IgnoredValueConversions(PostUpdateRes.get()).get()); 10782 } 10783 } 10784 } 10785 if (LinKind == OMPC_LINEAR_uval) 10786 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 10787 else 10788 InitExpr = VD ? SimpleRefExpr : Ref; 10789 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 10790 /*DirectInit=*/false); 10791 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 10792 10793 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 10794 Vars.push_back((VD || CurContext->isDependentContext()) 10795 ? RefExpr->IgnoreParens() 10796 : Ref); 10797 Privates.push_back(PrivateRef); 10798 Inits.push_back(InitRef); 10799 } 10800 10801 if (Vars.empty()) 10802 return nullptr; 10803 10804 Expr *StepExpr = Step; 10805 Expr *CalcStepExpr = nullptr; 10806 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 10807 !Step->isInstantiationDependent() && 10808 !Step->containsUnexpandedParameterPack()) { 10809 SourceLocation StepLoc = Step->getLocStart(); 10810 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 10811 if (Val.isInvalid()) 10812 return nullptr; 10813 StepExpr = Val.get(); 10814 10815 // Build var to save the step value. 10816 VarDecl *SaveVar = 10817 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 10818 ExprResult SaveRef = 10819 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 10820 ExprResult CalcStep = 10821 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 10822 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 10823 10824 // Warn about zero linear step (it would be probably better specified as 10825 // making corresponding variables 'const'). 10826 llvm::APSInt Result; 10827 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 10828 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 10829 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 10830 << (Vars.size() > 1); 10831 if (!IsConstant && CalcStep.isUsable()) { 10832 // Calculate the step beforehand instead of doing this on each iteration. 10833 // (This is not used if the number of iterations may be kfold-ed). 10834 CalcStepExpr = CalcStep.get(); 10835 } 10836 } 10837 10838 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 10839 ColonLoc, EndLoc, Vars, Privates, Inits, 10840 StepExpr, CalcStepExpr, 10841 buildPreInits(Context, ExprCaptures), 10842 buildPostUpdate(*this, ExprPostUpdates)); 10843 } 10844 10845 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 10846 Expr *NumIterations, Sema &SemaRef, 10847 Scope *S, DSAStackTy *Stack) { 10848 // Walk the vars and build update/final expressions for the CodeGen. 10849 SmallVector<Expr *, 8> Updates; 10850 SmallVector<Expr *, 8> Finals; 10851 Expr *Step = Clause.getStep(); 10852 Expr *CalcStep = Clause.getCalcStep(); 10853 // OpenMP [2.14.3.7, linear clause] 10854 // If linear-step is not specified it is assumed to be 1. 10855 if (Step == nullptr) 10856 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 10857 else if (CalcStep) { 10858 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 10859 } 10860 bool HasErrors = false; 10861 auto CurInit = Clause.inits().begin(); 10862 auto CurPrivate = Clause.privates().begin(); 10863 auto LinKind = Clause.getModifier(); 10864 for (auto &RefExpr : Clause.varlists()) { 10865 SourceLocation ELoc; 10866 SourceRange ERange; 10867 Expr *SimpleRefExpr = RefExpr; 10868 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 10869 /*AllowArraySection=*/false); 10870 ValueDecl *D = Res.first; 10871 if (Res.second || !D) { 10872 Updates.push_back(nullptr); 10873 Finals.push_back(nullptr); 10874 HasErrors = true; 10875 continue; 10876 } 10877 auto &&Info = Stack->isLoopControlVariable(D); 10878 // OpenMP [2.15.11, distribute simd Construct] 10879 // A list item may not appear in a linear clause, unless it is the loop 10880 // iteration variable. 10881 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 10882 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 10883 SemaRef.Diag(ELoc, 10884 diag::err_omp_linear_distribute_var_non_loop_iteration); 10885 Updates.push_back(nullptr); 10886 Finals.push_back(nullptr); 10887 HasErrors = true; 10888 continue; 10889 } 10890 Expr *InitExpr = *CurInit; 10891 10892 // Build privatized reference to the current linear var. 10893 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 10894 Expr *CapturedRef; 10895 if (LinKind == OMPC_LINEAR_uval) 10896 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 10897 else 10898 CapturedRef = 10899 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 10900 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 10901 /*RefersToCapture=*/true); 10902 10903 // Build update: Var = InitExpr + IV * Step 10904 ExprResult Update; 10905 if (!Info.first) { 10906 Update = 10907 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 10908 InitExpr, IV, Step, /* Subtract */ false); 10909 } else 10910 Update = *CurPrivate; 10911 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 10912 /*DiscardedValue=*/true); 10913 10914 // Build final: Var = InitExpr + NumIterations * Step 10915 ExprResult Final; 10916 if (!Info.first) { 10917 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 10918 InitExpr, NumIterations, Step, 10919 /* Subtract */ false); 10920 } else 10921 Final = *CurPrivate; 10922 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 10923 /*DiscardedValue=*/true); 10924 10925 if (!Update.isUsable() || !Final.isUsable()) { 10926 Updates.push_back(nullptr); 10927 Finals.push_back(nullptr); 10928 HasErrors = true; 10929 } else { 10930 Updates.push_back(Update.get()); 10931 Finals.push_back(Final.get()); 10932 } 10933 ++CurInit; 10934 ++CurPrivate; 10935 } 10936 Clause.setUpdates(Updates); 10937 Clause.setFinals(Finals); 10938 return HasErrors; 10939 } 10940 10941 OMPClause *Sema::ActOnOpenMPAlignedClause( 10942 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 10943 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 10944 10945 SmallVector<Expr *, 8> Vars; 10946 for (auto &RefExpr : VarList) { 10947 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10948 SourceLocation ELoc; 10949 SourceRange ERange; 10950 Expr *SimpleRefExpr = RefExpr; 10951 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10952 /*AllowArraySection=*/false); 10953 if (Res.second) { 10954 // It will be analyzed later. 10955 Vars.push_back(RefExpr); 10956 } 10957 ValueDecl *D = Res.first; 10958 if (!D) 10959 continue; 10960 10961 QualType QType = D->getType(); 10962 auto *VD = dyn_cast<VarDecl>(D); 10963 10964 // OpenMP [2.8.1, simd construct, Restrictions] 10965 // The type of list items appearing in the aligned clause must be 10966 // array, pointer, reference to array, or reference to pointer. 10967 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 10968 const Type *Ty = QType.getTypePtrOrNull(); 10969 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 10970 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 10971 << QType << getLangOpts().CPlusPlus << ERange; 10972 bool IsDecl = 10973 !VD || 10974 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10975 Diag(D->getLocation(), 10976 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10977 << D; 10978 continue; 10979 } 10980 10981 // OpenMP [2.8.1, simd construct, Restrictions] 10982 // A list-item cannot appear in more than one aligned clause. 10983 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 10984 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 10985 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 10986 << getOpenMPClauseName(OMPC_aligned); 10987 continue; 10988 } 10989 10990 DeclRefExpr *Ref = nullptr; 10991 if (!VD && IsOpenMPCapturedDecl(D)) 10992 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 10993 Vars.push_back(DefaultFunctionArrayConversion( 10994 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 10995 .get()); 10996 } 10997 10998 // OpenMP [2.8.1, simd construct, Description] 10999 // The parameter of the aligned clause, alignment, must be a constant 11000 // positive integer expression. 11001 // If no optional parameter is specified, implementation-defined default 11002 // alignments for SIMD instructions on the target platforms are assumed. 11003 if (Alignment != nullptr) { 11004 ExprResult AlignResult = 11005 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 11006 if (AlignResult.isInvalid()) 11007 return nullptr; 11008 Alignment = AlignResult.get(); 11009 } 11010 if (Vars.empty()) 11011 return nullptr; 11012 11013 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 11014 EndLoc, Vars, Alignment); 11015 } 11016 11017 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 11018 SourceLocation StartLoc, 11019 SourceLocation LParenLoc, 11020 SourceLocation EndLoc) { 11021 SmallVector<Expr *, 8> Vars; 11022 SmallVector<Expr *, 8> SrcExprs; 11023 SmallVector<Expr *, 8> DstExprs; 11024 SmallVector<Expr *, 8> AssignmentOps; 11025 for (auto &RefExpr : VarList) { 11026 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 11027 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 11028 // It will be analyzed later. 11029 Vars.push_back(RefExpr); 11030 SrcExprs.push_back(nullptr); 11031 DstExprs.push_back(nullptr); 11032 AssignmentOps.push_back(nullptr); 11033 continue; 11034 } 11035 11036 SourceLocation ELoc = RefExpr->getExprLoc(); 11037 // OpenMP [2.1, C/C++] 11038 // A list item is a variable name. 11039 // OpenMP [2.14.4.1, Restrictions, p.1] 11040 // A list item that appears in a copyin clause must be threadprivate. 11041 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 11042 if (!DE || !isa<VarDecl>(DE->getDecl())) { 11043 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 11044 << 0 << RefExpr->getSourceRange(); 11045 continue; 11046 } 11047 11048 Decl *D = DE->getDecl(); 11049 VarDecl *VD = cast<VarDecl>(D); 11050 11051 QualType Type = VD->getType(); 11052 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 11053 // It will be analyzed later. 11054 Vars.push_back(DE); 11055 SrcExprs.push_back(nullptr); 11056 DstExprs.push_back(nullptr); 11057 AssignmentOps.push_back(nullptr); 11058 continue; 11059 } 11060 11061 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 11062 // A list item that appears in a copyin clause must be threadprivate. 11063 if (!DSAStack->isThreadPrivate(VD)) { 11064 Diag(ELoc, diag::err_omp_required_access) 11065 << getOpenMPClauseName(OMPC_copyin) 11066 << getOpenMPDirectiveName(OMPD_threadprivate); 11067 continue; 11068 } 11069 11070 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 11071 // A variable of class type (or array thereof) that appears in a 11072 // copyin clause requires an accessible, unambiguous copy assignment 11073 // operator for the class type. 11074 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 11075 auto *SrcVD = 11076 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 11077 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 11078 auto *PseudoSrcExpr = buildDeclRefExpr( 11079 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 11080 auto *DstVD = 11081 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 11082 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 11083 auto *PseudoDstExpr = 11084 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 11085 // For arrays generate assignment operation for single element and replace 11086 // it by the original array element in CodeGen. 11087 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 11088 PseudoDstExpr, PseudoSrcExpr); 11089 if (AssignmentOp.isInvalid()) 11090 continue; 11091 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 11092 /*DiscardedValue=*/true); 11093 if (AssignmentOp.isInvalid()) 11094 continue; 11095 11096 DSAStack->addDSA(VD, DE, OMPC_copyin); 11097 Vars.push_back(DE); 11098 SrcExprs.push_back(PseudoSrcExpr); 11099 DstExprs.push_back(PseudoDstExpr); 11100 AssignmentOps.push_back(AssignmentOp.get()); 11101 } 11102 11103 if (Vars.empty()) 11104 return nullptr; 11105 11106 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 11107 SrcExprs, DstExprs, AssignmentOps); 11108 } 11109 11110 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 11111 SourceLocation StartLoc, 11112 SourceLocation LParenLoc, 11113 SourceLocation EndLoc) { 11114 SmallVector<Expr *, 8> Vars; 11115 SmallVector<Expr *, 8> SrcExprs; 11116 SmallVector<Expr *, 8> DstExprs; 11117 SmallVector<Expr *, 8> AssignmentOps; 11118 for (auto &RefExpr : VarList) { 11119 assert(RefExpr && "NULL expr in OpenMP linear clause."); 11120 SourceLocation ELoc; 11121 SourceRange ERange; 11122 Expr *SimpleRefExpr = RefExpr; 11123 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 11124 /*AllowArraySection=*/false); 11125 if (Res.second) { 11126 // It will be analyzed later. 11127 Vars.push_back(RefExpr); 11128 SrcExprs.push_back(nullptr); 11129 DstExprs.push_back(nullptr); 11130 AssignmentOps.push_back(nullptr); 11131 } 11132 ValueDecl *D = Res.first; 11133 if (!D) 11134 continue; 11135 11136 QualType Type = D->getType(); 11137 auto *VD = dyn_cast<VarDecl>(D); 11138 11139 // OpenMP [2.14.4.2, Restrictions, p.2] 11140 // A list item that appears in a copyprivate clause may not appear in a 11141 // private or firstprivate clause on the single construct. 11142 if (!VD || !DSAStack->isThreadPrivate(VD)) { 11143 auto DVar = DSAStack->getTopDSA(D, false); 11144 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 11145 DVar.RefExpr) { 11146 Diag(ELoc, diag::err_omp_wrong_dsa) 11147 << getOpenMPClauseName(DVar.CKind) 11148 << getOpenMPClauseName(OMPC_copyprivate); 11149 ReportOriginalDSA(*this, DSAStack, D, DVar); 11150 continue; 11151 } 11152 11153 // OpenMP [2.11.4.2, Restrictions, p.1] 11154 // All list items that appear in a copyprivate clause must be either 11155 // threadprivate or private in the enclosing context. 11156 if (DVar.CKind == OMPC_unknown) { 11157 DVar = DSAStack->getImplicitDSA(D, false); 11158 if (DVar.CKind == OMPC_shared) { 11159 Diag(ELoc, diag::err_omp_required_access) 11160 << getOpenMPClauseName(OMPC_copyprivate) 11161 << "threadprivate or private in the enclosing context"; 11162 ReportOriginalDSA(*this, DSAStack, D, DVar); 11163 continue; 11164 } 11165 } 11166 } 11167 11168 // Variably modified types are not supported. 11169 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 11170 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 11171 << getOpenMPClauseName(OMPC_copyprivate) << Type 11172 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 11173 bool IsDecl = 11174 !VD || 11175 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11176 Diag(D->getLocation(), 11177 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11178 << D; 11179 continue; 11180 } 11181 11182 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 11183 // A variable of class type (or array thereof) that appears in a 11184 // copyin clause requires an accessible, unambiguous copy assignment 11185 // operator for the class type. 11186 Type = Context.getBaseElementType(Type.getNonReferenceType()) 11187 .getUnqualifiedType(); 11188 auto *SrcVD = 11189 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 11190 D->hasAttrs() ? &D->getAttrs() : nullptr); 11191 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 11192 auto *DstVD = 11193 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 11194 D->hasAttrs() ? &D->getAttrs() : nullptr); 11195 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 11196 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 11197 PseudoDstExpr, PseudoSrcExpr); 11198 if (AssignmentOp.isInvalid()) 11199 continue; 11200 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 11201 /*DiscardedValue=*/true); 11202 if (AssignmentOp.isInvalid()) 11203 continue; 11204 11205 // No need to mark vars as copyprivate, they are already threadprivate or 11206 // implicitly private. 11207 assert(VD || IsOpenMPCapturedDecl(D)); 11208 Vars.push_back( 11209 VD ? RefExpr->IgnoreParens() 11210 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 11211 SrcExprs.push_back(PseudoSrcExpr); 11212 DstExprs.push_back(PseudoDstExpr); 11213 AssignmentOps.push_back(AssignmentOp.get()); 11214 } 11215 11216 if (Vars.empty()) 11217 return nullptr; 11218 11219 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11220 Vars, SrcExprs, DstExprs, AssignmentOps); 11221 } 11222 11223 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 11224 SourceLocation StartLoc, 11225 SourceLocation LParenLoc, 11226 SourceLocation EndLoc) { 11227 if (VarList.empty()) 11228 return nullptr; 11229 11230 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 11231 } 11232 11233 OMPClause * 11234 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 11235 SourceLocation DepLoc, SourceLocation ColonLoc, 11236 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 11237 SourceLocation LParenLoc, SourceLocation EndLoc) { 11238 if (DSAStack->getCurrentDirective() == OMPD_ordered && 11239 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 11240 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 11241 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 11242 return nullptr; 11243 } 11244 if (DSAStack->getCurrentDirective() != OMPD_ordered && 11245 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 11246 DepKind == OMPC_DEPEND_sink)) { 11247 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 11248 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 11249 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 11250 /*Last=*/OMPC_DEPEND_unknown, Except) 11251 << getOpenMPClauseName(OMPC_depend); 11252 return nullptr; 11253 } 11254 SmallVector<Expr *, 8> Vars; 11255 DSAStackTy::OperatorOffsetTy OpsOffs; 11256 llvm::APSInt DepCounter(/*BitWidth=*/32); 11257 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 11258 if (DepKind == OMPC_DEPEND_sink) { 11259 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 11260 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 11261 TotalDepCount.setIsUnsigned(/*Val=*/true); 11262 } 11263 } 11264 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || 11265 DSAStack->getParentOrderedRegionParam()) { 11266 for (auto &RefExpr : VarList) { 11267 assert(RefExpr && "NULL expr in OpenMP shared clause."); 11268 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 11269 // It will be analyzed later. 11270 Vars.push_back(RefExpr); 11271 continue; 11272 } 11273 11274 SourceLocation ELoc = RefExpr->getExprLoc(); 11275 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 11276 if (DepKind == OMPC_DEPEND_sink) { 11277 if (DepCounter >= TotalDepCount) { 11278 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 11279 continue; 11280 } 11281 ++DepCounter; 11282 // OpenMP [2.13.9, Summary] 11283 // depend(dependence-type : vec), where dependence-type is: 11284 // 'sink' and where vec is the iteration vector, which has the form: 11285 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 11286 // where n is the value specified by the ordered clause in the loop 11287 // directive, xi denotes the loop iteration variable of the i-th nested 11288 // loop associated with the loop directive, and di is a constant 11289 // non-negative integer. 11290 if (CurContext->isDependentContext()) { 11291 // It will be analyzed later. 11292 Vars.push_back(RefExpr); 11293 continue; 11294 } 11295 SimpleExpr = SimpleExpr->IgnoreImplicit(); 11296 OverloadedOperatorKind OOK = OO_None; 11297 SourceLocation OOLoc; 11298 Expr *LHS = SimpleExpr; 11299 Expr *RHS = nullptr; 11300 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 11301 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 11302 OOLoc = BO->getOperatorLoc(); 11303 LHS = BO->getLHS()->IgnoreParenImpCasts(); 11304 RHS = BO->getRHS()->IgnoreParenImpCasts(); 11305 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 11306 OOK = OCE->getOperator(); 11307 OOLoc = OCE->getOperatorLoc(); 11308 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 11309 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 11310 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 11311 OOK = MCE->getMethodDecl() 11312 ->getNameInfo() 11313 .getName() 11314 .getCXXOverloadedOperator(); 11315 OOLoc = MCE->getCallee()->getExprLoc(); 11316 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 11317 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 11318 } 11319 SourceLocation ELoc; 11320 SourceRange ERange; 11321 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 11322 /*AllowArraySection=*/false); 11323 if (Res.second) { 11324 // It will be analyzed later. 11325 Vars.push_back(RefExpr); 11326 } 11327 ValueDecl *D = Res.first; 11328 if (!D) 11329 continue; 11330 11331 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 11332 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 11333 continue; 11334 } 11335 if (RHS) { 11336 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 11337 RHS, OMPC_depend, /*StrictlyPositive=*/false); 11338 if (RHSRes.isInvalid()) 11339 continue; 11340 } 11341 if (!CurContext->isDependentContext() && 11342 DSAStack->getParentOrderedRegionParam() && 11343 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 11344 ValueDecl* VD = DSAStack->getParentLoopControlVariable( 11345 DepCounter.getZExtValue()); 11346 if (VD) { 11347 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 11348 << 1 << VD; 11349 } else { 11350 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 11351 } 11352 continue; 11353 } 11354 OpsOffs.push_back({RHS, OOK}); 11355 } else { 11356 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 11357 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 11358 (ASE && 11359 !ASE->getBase() 11360 ->getType() 11361 .getNonReferenceType() 11362 ->isPointerType() && 11363 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 11364 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 11365 << RefExpr->getSourceRange(); 11366 continue; 11367 } 11368 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 11369 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 11370 ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, 11371 RefExpr->IgnoreParenImpCasts()); 11372 getDiagnostics().setSuppressAllDiagnostics(Suppress); 11373 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) { 11374 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 11375 << RefExpr->getSourceRange(); 11376 continue; 11377 } 11378 } 11379 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 11380 } 11381 11382 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 11383 TotalDepCount > VarList.size() && 11384 DSAStack->getParentOrderedRegionParam() && 11385 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 11386 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1 11387 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 11388 } 11389 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 11390 Vars.empty()) 11391 return nullptr; 11392 } 11393 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11394 DepKind, DepLoc, ColonLoc, Vars); 11395 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) 11396 DSAStack->addDoacrossDependClause(C, OpsOffs); 11397 return C; 11398 } 11399 11400 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 11401 SourceLocation LParenLoc, 11402 SourceLocation EndLoc) { 11403 Expr *ValExpr = Device; 11404 Stmt *HelperValStmt = nullptr; 11405 11406 // OpenMP [2.9.1, Restrictions] 11407 // The device expression must evaluate to a non-negative integer value. 11408 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 11409 /*StrictlyPositive=*/false)) 11410 return nullptr; 11411 11412 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11413 OpenMPDirectiveKind CaptureRegion = 11414 getOpenMPCaptureRegionForClause(DKind, OMPC_device); 11415 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 11416 ValExpr = MakeFullExpr(ValExpr).get(); 11417 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11418 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11419 HelperValStmt = buildPreInits(Context, Captures); 11420 } 11421 11422 return new (Context) 11423 OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc); 11424 } 11425 11426 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 11427 DSAStackTy *Stack, QualType QTy) { 11428 NamedDecl *ND; 11429 if (QTy->isIncompleteType(&ND)) { 11430 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 11431 return false; 11432 } 11433 return true; 11434 } 11435 11436 /// \brief Return true if it can be proven that the provided array expression 11437 /// (array section or array subscript) does NOT specify the whole size of the 11438 /// array whose base type is \a BaseQTy. 11439 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 11440 const Expr *E, 11441 QualType BaseQTy) { 11442 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 11443 11444 // If this is an array subscript, it refers to the whole size if the size of 11445 // the dimension is constant and equals 1. Also, an array section assumes the 11446 // format of an array subscript if no colon is used. 11447 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 11448 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 11449 return ATy->getSize().getSExtValue() != 1; 11450 // Size can't be evaluated statically. 11451 return false; 11452 } 11453 11454 assert(OASE && "Expecting array section if not an array subscript."); 11455 auto *LowerBound = OASE->getLowerBound(); 11456 auto *Length = OASE->getLength(); 11457 11458 // If there is a lower bound that does not evaluates to zero, we are not 11459 // covering the whole dimension. 11460 if (LowerBound) { 11461 llvm::APSInt ConstLowerBound; 11462 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 11463 return false; // Can't get the integer value as a constant. 11464 if (ConstLowerBound.getSExtValue()) 11465 return true; 11466 } 11467 11468 // If we don't have a length we covering the whole dimension. 11469 if (!Length) 11470 return false; 11471 11472 // If the base is a pointer, we don't have a way to get the size of the 11473 // pointee. 11474 if (BaseQTy->isPointerType()) 11475 return false; 11476 11477 // We can only check if the length is the same as the size of the dimension 11478 // if we have a constant array. 11479 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 11480 if (!CATy) 11481 return false; 11482 11483 llvm::APSInt ConstLength; 11484 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 11485 return false; // Can't get the integer value as a constant. 11486 11487 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 11488 } 11489 11490 // Return true if it can be proven that the provided array expression (array 11491 // section or array subscript) does NOT specify a single element of the array 11492 // whose base type is \a BaseQTy. 11493 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 11494 const Expr *E, 11495 QualType BaseQTy) { 11496 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 11497 11498 // An array subscript always refer to a single element. Also, an array section 11499 // assumes the format of an array subscript if no colon is used. 11500 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 11501 return false; 11502 11503 assert(OASE && "Expecting array section if not an array subscript."); 11504 auto *Length = OASE->getLength(); 11505 11506 // If we don't have a length we have to check if the array has unitary size 11507 // for this dimension. Also, we should always expect a length if the base type 11508 // is pointer. 11509 if (!Length) { 11510 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 11511 return ATy->getSize().getSExtValue() != 1; 11512 // We cannot assume anything. 11513 return false; 11514 } 11515 11516 // Check if the length evaluates to 1. 11517 llvm::APSInt ConstLength; 11518 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 11519 return false; // Can't get the integer value as a constant. 11520 11521 return ConstLength.getSExtValue() != 1; 11522 } 11523 11524 // Return the expression of the base of the mappable expression or null if it 11525 // cannot be determined and do all the necessary checks to see if the expression 11526 // is valid as a standalone mappable expression. In the process, record all the 11527 // components of the expression. 11528 static Expr *CheckMapClauseExpressionBase( 11529 Sema &SemaRef, Expr *E, 11530 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 11531 OpenMPClauseKind CKind, bool NoDiagnose) { 11532 SourceLocation ELoc = E->getExprLoc(); 11533 SourceRange ERange = E->getSourceRange(); 11534 11535 // The base of elements of list in a map clause have to be either: 11536 // - a reference to variable or field. 11537 // - a member expression. 11538 // - an array expression. 11539 // 11540 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 11541 // reference to 'r'. 11542 // 11543 // If we have: 11544 // 11545 // struct SS { 11546 // Bla S; 11547 // foo() { 11548 // #pragma omp target map (S.Arr[:12]); 11549 // } 11550 // } 11551 // 11552 // We want to retrieve the member expression 'this->S'; 11553 11554 Expr *RelevantExpr = nullptr; 11555 11556 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 11557 // If a list item is an array section, it must specify contiguous storage. 11558 // 11559 // For this restriction it is sufficient that we make sure only references 11560 // to variables or fields and array expressions, and that no array sections 11561 // exist except in the rightmost expression (unless they cover the whole 11562 // dimension of the array). E.g. these would be invalid: 11563 // 11564 // r.ArrS[3:5].Arr[6:7] 11565 // 11566 // r.ArrS[3:5].x 11567 // 11568 // but these would be valid: 11569 // r.ArrS[3].Arr[6:7] 11570 // 11571 // r.ArrS[3].x 11572 11573 bool AllowUnitySizeArraySection = true; 11574 bool AllowWholeSizeArraySection = true; 11575 11576 while (!RelevantExpr) { 11577 E = E->IgnoreParenImpCasts(); 11578 11579 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 11580 if (!isa<VarDecl>(CurE->getDecl())) 11581 return nullptr; 11582 11583 RelevantExpr = CurE; 11584 11585 // If we got a reference to a declaration, we should not expect any array 11586 // section before that. 11587 AllowUnitySizeArraySection = false; 11588 AllowWholeSizeArraySection = false; 11589 11590 // Record the component. 11591 CurComponents.emplace_back(CurE, CurE->getDecl()); 11592 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) { 11593 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 11594 11595 if (isa<CXXThisExpr>(BaseE)) 11596 // We found a base expression: this->Val. 11597 RelevantExpr = CurE; 11598 else 11599 E = BaseE; 11600 11601 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 11602 if (!NoDiagnose) { 11603 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 11604 << CurE->getSourceRange(); 11605 return nullptr; 11606 } 11607 if (RelevantExpr) 11608 return nullptr; 11609 continue; 11610 } 11611 11612 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 11613 11614 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 11615 // A bit-field cannot appear in a map clause. 11616 // 11617 if (FD->isBitField()) { 11618 if (!NoDiagnose) { 11619 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 11620 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 11621 return nullptr; 11622 } 11623 if (RelevantExpr) 11624 return nullptr; 11625 continue; 11626 } 11627 11628 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11629 // If the type of a list item is a reference to a type T then the type 11630 // will be considered to be T for all purposes of this clause. 11631 QualType CurType = BaseE->getType().getNonReferenceType(); 11632 11633 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 11634 // A list item cannot be a variable that is a member of a structure with 11635 // a union type. 11636 // 11637 if (auto *RT = CurType->getAs<RecordType>()) { 11638 if (RT->isUnionType()) { 11639 if (!NoDiagnose) { 11640 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 11641 << CurE->getSourceRange(); 11642 return nullptr; 11643 } 11644 continue; 11645 } 11646 } 11647 11648 // If we got a member expression, we should not expect any array section 11649 // before that: 11650 // 11651 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 11652 // If a list item is an element of a structure, only the rightmost symbol 11653 // of the variable reference can be an array section. 11654 // 11655 AllowUnitySizeArraySection = false; 11656 AllowWholeSizeArraySection = false; 11657 11658 // Record the component. 11659 CurComponents.emplace_back(CurE, FD); 11660 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 11661 E = CurE->getBase()->IgnoreParenImpCasts(); 11662 11663 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 11664 if (!NoDiagnose) { 11665 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 11666 << 0 << CurE->getSourceRange(); 11667 return nullptr; 11668 } 11669 continue; 11670 } 11671 11672 // If we got an array subscript that express the whole dimension we 11673 // can have any array expressions before. If it only expressing part of 11674 // the dimension, we can only have unitary-size array expressions. 11675 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 11676 E->getType())) 11677 AllowWholeSizeArraySection = false; 11678 11679 // Record the component - we don't have any declaration associated. 11680 CurComponents.emplace_back(CurE, nullptr); 11681 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 11682 assert(!NoDiagnose && "Array sections cannot be implicitly mapped."); 11683 E = CurE->getBase()->IgnoreParenImpCasts(); 11684 11685 QualType CurType = 11686 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 11687 11688 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11689 // If the type of a list item is a reference to a type T then the type 11690 // will be considered to be T for all purposes of this clause. 11691 if (CurType->isReferenceType()) 11692 CurType = CurType->getPointeeType(); 11693 11694 bool IsPointer = CurType->isAnyPointerType(); 11695 11696 if (!IsPointer && !CurType->isArrayType()) { 11697 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 11698 << 0 << CurE->getSourceRange(); 11699 return nullptr; 11700 } 11701 11702 bool NotWhole = 11703 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 11704 bool NotUnity = 11705 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 11706 11707 if (AllowWholeSizeArraySection) { 11708 // Any array section is currently allowed. Allowing a whole size array 11709 // section implies allowing a unity array section as well. 11710 // 11711 // If this array section refers to the whole dimension we can still 11712 // accept other array sections before this one, except if the base is a 11713 // pointer. Otherwise, only unitary sections are accepted. 11714 if (NotWhole || IsPointer) 11715 AllowWholeSizeArraySection = false; 11716 } else if (AllowUnitySizeArraySection && NotUnity) { 11717 // A unity or whole array section is not allowed and that is not 11718 // compatible with the properties of the current array section. 11719 SemaRef.Diag( 11720 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 11721 << CurE->getSourceRange(); 11722 return nullptr; 11723 } 11724 11725 // Record the component - we don't have any declaration associated. 11726 CurComponents.emplace_back(CurE, nullptr); 11727 } else { 11728 if (!NoDiagnose) { 11729 // If nothing else worked, this is not a valid map clause expression. 11730 SemaRef.Diag( 11731 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 11732 << ERange; 11733 } 11734 return nullptr; 11735 } 11736 } 11737 11738 return RelevantExpr; 11739 } 11740 11741 // Return true if expression E associated with value VD has conflicts with other 11742 // map information. 11743 static bool CheckMapConflicts( 11744 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 11745 bool CurrentRegionOnly, 11746 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 11747 OpenMPClauseKind CKind) { 11748 assert(VD && E); 11749 SourceLocation ELoc = E->getExprLoc(); 11750 SourceRange ERange = E->getSourceRange(); 11751 11752 // In order to easily check the conflicts we need to match each component of 11753 // the expression under test with the components of the expressions that are 11754 // already in the stack. 11755 11756 assert(!CurComponents.empty() && "Map clause expression with no components!"); 11757 assert(CurComponents.back().getAssociatedDeclaration() == VD && 11758 "Map clause expression with unexpected base!"); 11759 11760 // Variables to help detecting enclosing problems in data environment nests. 11761 bool IsEnclosedByDataEnvironmentExpr = false; 11762 const Expr *EnclosingExpr = nullptr; 11763 11764 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 11765 VD, CurrentRegionOnly, 11766 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 11767 StackComponents, 11768 OpenMPClauseKind) -> bool { 11769 11770 assert(!StackComponents.empty() && 11771 "Map clause expression with no components!"); 11772 assert(StackComponents.back().getAssociatedDeclaration() == VD && 11773 "Map clause expression with unexpected base!"); 11774 11775 // The whole expression in the stack. 11776 auto *RE = StackComponents.front().getAssociatedExpression(); 11777 11778 // Expressions must start from the same base. Here we detect at which 11779 // point both expressions diverge from each other and see if we can 11780 // detect if the memory referred to both expressions is contiguous and 11781 // do not overlap. 11782 auto CI = CurComponents.rbegin(); 11783 auto CE = CurComponents.rend(); 11784 auto SI = StackComponents.rbegin(); 11785 auto SE = StackComponents.rend(); 11786 for (; CI != CE && SI != SE; ++CI, ++SI) { 11787 11788 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 11789 // At most one list item can be an array item derived from a given 11790 // variable in map clauses of the same construct. 11791 if (CurrentRegionOnly && 11792 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 11793 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 11794 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 11795 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 11796 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 11797 diag::err_omp_multiple_array_items_in_map_clause) 11798 << CI->getAssociatedExpression()->getSourceRange(); 11799 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 11800 diag::note_used_here) 11801 << SI->getAssociatedExpression()->getSourceRange(); 11802 return true; 11803 } 11804 11805 // Do both expressions have the same kind? 11806 if (CI->getAssociatedExpression()->getStmtClass() != 11807 SI->getAssociatedExpression()->getStmtClass()) 11808 break; 11809 11810 // Are we dealing with different variables/fields? 11811 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 11812 break; 11813 } 11814 // Check if the extra components of the expressions in the enclosing 11815 // data environment are redundant for the current base declaration. 11816 // If they are, the maps completely overlap, which is legal. 11817 for (; SI != SE; ++SI) { 11818 QualType Type; 11819 if (auto *ASE = 11820 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 11821 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 11822 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>( 11823 SI->getAssociatedExpression())) { 11824 auto *E = OASE->getBase()->IgnoreParenImpCasts(); 11825 Type = 11826 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 11827 } 11828 if (Type.isNull() || Type->isAnyPointerType() || 11829 CheckArrayExpressionDoesNotReferToWholeSize( 11830 SemaRef, SI->getAssociatedExpression(), Type)) 11831 break; 11832 } 11833 11834 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 11835 // List items of map clauses in the same construct must not share 11836 // original storage. 11837 // 11838 // If the expressions are exactly the same or one is a subset of the 11839 // other, it means they are sharing storage. 11840 if (CI == CE && SI == SE) { 11841 if (CurrentRegionOnly) { 11842 if (CKind == OMPC_map) 11843 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 11844 else { 11845 assert(CKind == OMPC_to || CKind == OMPC_from); 11846 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 11847 << ERange; 11848 } 11849 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 11850 << RE->getSourceRange(); 11851 return true; 11852 } else { 11853 // If we find the same expression in the enclosing data environment, 11854 // that is legal. 11855 IsEnclosedByDataEnvironmentExpr = true; 11856 return false; 11857 } 11858 } 11859 11860 QualType DerivedType = 11861 std::prev(CI)->getAssociatedDeclaration()->getType(); 11862 SourceLocation DerivedLoc = 11863 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 11864 11865 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11866 // If the type of a list item is a reference to a type T then the type 11867 // will be considered to be T for all purposes of this clause. 11868 DerivedType = DerivedType.getNonReferenceType(); 11869 11870 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 11871 // A variable for which the type is pointer and an array section 11872 // derived from that variable must not appear as list items of map 11873 // clauses of the same construct. 11874 // 11875 // Also, cover one of the cases in: 11876 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 11877 // If any part of the original storage of a list item has corresponding 11878 // storage in the device data environment, all of the original storage 11879 // must have corresponding storage in the device data environment. 11880 // 11881 if (DerivedType->isAnyPointerType()) { 11882 if (CI == CE || SI == SE) { 11883 SemaRef.Diag( 11884 DerivedLoc, 11885 diag::err_omp_pointer_mapped_along_with_derived_section) 11886 << DerivedLoc; 11887 } else { 11888 assert(CI != CE && SI != SE); 11889 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) 11890 << DerivedLoc; 11891 } 11892 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 11893 << RE->getSourceRange(); 11894 return true; 11895 } 11896 11897 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 11898 // List items of map clauses in the same construct must not share 11899 // original storage. 11900 // 11901 // An expression is a subset of the other. 11902 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 11903 if (CKind == OMPC_map) 11904 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 11905 else { 11906 assert(CKind == OMPC_to || CKind == OMPC_from); 11907 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 11908 << ERange; 11909 } 11910 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 11911 << RE->getSourceRange(); 11912 return true; 11913 } 11914 11915 // The current expression uses the same base as other expression in the 11916 // data environment but does not contain it completely. 11917 if (!CurrentRegionOnly && SI != SE) 11918 EnclosingExpr = RE; 11919 11920 // The current expression is a subset of the expression in the data 11921 // environment. 11922 IsEnclosedByDataEnvironmentExpr |= 11923 (!CurrentRegionOnly && CI != CE && SI == SE); 11924 11925 return false; 11926 }); 11927 11928 if (CurrentRegionOnly) 11929 return FoundError; 11930 11931 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 11932 // If any part of the original storage of a list item has corresponding 11933 // storage in the device data environment, all of the original storage must 11934 // have corresponding storage in the device data environment. 11935 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 11936 // If a list item is an element of a structure, and a different element of 11937 // the structure has a corresponding list item in the device data environment 11938 // prior to a task encountering the construct associated with the map clause, 11939 // then the list item must also have a corresponding list item in the device 11940 // data environment prior to the task encountering the construct. 11941 // 11942 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 11943 SemaRef.Diag(ELoc, 11944 diag::err_omp_original_storage_is_shared_and_does_not_contain) 11945 << ERange; 11946 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 11947 << EnclosingExpr->getSourceRange(); 11948 return true; 11949 } 11950 11951 return FoundError; 11952 } 11953 11954 namespace { 11955 // Utility struct that gathers all the related lists associated with a mappable 11956 // expression. 11957 struct MappableVarListInfo final { 11958 // The list of expressions. 11959 ArrayRef<Expr *> VarList; 11960 // The list of processed expressions. 11961 SmallVector<Expr *, 16> ProcessedVarList; 11962 // The mappble components for each expression. 11963 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 11964 // The base declaration of the variable. 11965 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 11966 11967 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 11968 // We have a list of components and base declarations for each entry in the 11969 // variable list. 11970 VarComponents.reserve(VarList.size()); 11971 VarBaseDeclarations.reserve(VarList.size()); 11972 } 11973 }; 11974 } 11975 11976 // Check the validity of the provided variable list for the provided clause kind 11977 // \a CKind. In the check process the valid expressions, and mappable expression 11978 // components and variables are extracted and used to fill \a Vars, 11979 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 11980 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 11981 static void 11982 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 11983 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 11984 SourceLocation StartLoc, 11985 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 11986 bool IsMapTypeImplicit = false) { 11987 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 11988 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 11989 "Unexpected clause kind with mappable expressions!"); 11990 11991 // Keep track of the mappable components and base declarations in this clause. 11992 // Each entry in the list is going to have a list of components associated. We 11993 // record each set of the components so that we can build the clause later on. 11994 // In the end we should have the same amount of declarations and component 11995 // lists. 11996 11997 for (auto &RE : MVLI.VarList) { 11998 assert(RE && "Null expr in omp to/from/map clause"); 11999 SourceLocation ELoc = RE->getExprLoc(); 12000 12001 auto *VE = RE->IgnoreParenLValueCasts(); 12002 12003 if (VE->isValueDependent() || VE->isTypeDependent() || 12004 VE->isInstantiationDependent() || 12005 VE->containsUnexpandedParameterPack()) { 12006 // We can only analyze this information once the missing information is 12007 // resolved. 12008 MVLI.ProcessedVarList.push_back(RE); 12009 continue; 12010 } 12011 12012 auto *SimpleExpr = RE->IgnoreParenCasts(); 12013 12014 if (!RE->IgnoreParenImpCasts()->isLValue()) { 12015 SemaRef.Diag(ELoc, 12016 diag::err_omp_expected_named_var_member_or_array_expression) 12017 << RE->getSourceRange(); 12018 continue; 12019 } 12020 12021 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 12022 ValueDecl *CurDeclaration = nullptr; 12023 12024 // Obtain the array or member expression bases if required. Also, fill the 12025 // components array with all the components identified in the process. 12026 auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, 12027 CKind, /*NoDiagnose=*/false); 12028 if (!BE) 12029 continue; 12030 12031 assert(!CurComponents.empty() && 12032 "Invalid mappable expression information."); 12033 12034 // For the following checks, we rely on the base declaration which is 12035 // expected to be associated with the last component. The declaration is 12036 // expected to be a variable or a field (if 'this' is being mapped). 12037 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 12038 assert(CurDeclaration && "Null decl on map clause."); 12039 assert( 12040 CurDeclaration->isCanonicalDecl() && 12041 "Expecting components to have associated only canonical declarations."); 12042 12043 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 12044 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 12045 12046 assert((VD || FD) && "Only variables or fields are expected here!"); 12047 (void)FD; 12048 12049 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 12050 // threadprivate variables cannot appear in a map clause. 12051 // OpenMP 4.5 [2.10.5, target update Construct] 12052 // threadprivate variables cannot appear in a from clause. 12053 if (VD && DSAS->isThreadPrivate(VD)) { 12054 auto DVar = DSAS->getTopDSA(VD, false); 12055 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 12056 << getOpenMPClauseName(CKind); 12057 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 12058 continue; 12059 } 12060 12061 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 12062 // A list item cannot appear in both a map clause and a data-sharing 12063 // attribute clause on the same construct. 12064 12065 // Check conflicts with other map clause expressions. We check the conflicts 12066 // with the current construct separately from the enclosing data 12067 // environment, because the restrictions are different. We only have to 12068 // check conflicts across regions for the map clauses. 12069 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 12070 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 12071 break; 12072 if (CKind == OMPC_map && 12073 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 12074 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 12075 break; 12076 12077 // OpenMP 4.5 [2.10.5, target update Construct] 12078 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12079 // If the type of a list item is a reference to a type T then the type will 12080 // be considered to be T for all purposes of this clause. 12081 QualType Type = CurDeclaration->getType().getNonReferenceType(); 12082 12083 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 12084 // A list item in a to or from clause must have a mappable type. 12085 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 12086 // A list item must have a mappable type. 12087 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 12088 DSAS, Type)) 12089 continue; 12090 12091 if (CKind == OMPC_map) { 12092 // target enter data 12093 // OpenMP [2.10.2, Restrictions, p. 99] 12094 // A map-type must be specified in all map clauses and must be either 12095 // to or alloc. 12096 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 12097 if (DKind == OMPD_target_enter_data && 12098 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 12099 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 12100 << (IsMapTypeImplicit ? 1 : 0) 12101 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 12102 << getOpenMPDirectiveName(DKind); 12103 continue; 12104 } 12105 12106 // target exit_data 12107 // OpenMP [2.10.3, Restrictions, p. 102] 12108 // A map-type must be specified in all map clauses and must be either 12109 // from, release, or delete. 12110 if (DKind == OMPD_target_exit_data && 12111 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 12112 MapType == OMPC_MAP_delete)) { 12113 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 12114 << (IsMapTypeImplicit ? 1 : 0) 12115 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 12116 << getOpenMPDirectiveName(DKind); 12117 continue; 12118 } 12119 12120 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 12121 // A list item cannot appear in both a map clause and a data-sharing 12122 // attribute clause on the same construct 12123 if ((DKind == OMPD_target || DKind == OMPD_target_teams || 12124 DKind == OMPD_target_teams_distribute || 12125 DKind == OMPD_target_teams_distribute_parallel_for || 12126 DKind == OMPD_target_teams_distribute_parallel_for_simd || 12127 DKind == OMPD_target_teams_distribute_simd) && VD) { 12128 auto DVar = DSAS->getTopDSA(VD, false); 12129 if (isOpenMPPrivate(DVar.CKind)) { 12130 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 12131 << getOpenMPClauseName(DVar.CKind) 12132 << getOpenMPClauseName(OMPC_map) 12133 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 12134 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 12135 continue; 12136 } 12137 } 12138 } 12139 12140 // Save the current expression. 12141 MVLI.ProcessedVarList.push_back(RE); 12142 12143 // Store the components in the stack so that they can be used to check 12144 // against other clauses later on. 12145 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 12146 /*WhereFoundClauseKind=*/OMPC_map); 12147 12148 // Save the components and declaration to create the clause. For purposes of 12149 // the clause creation, any component list that has has base 'this' uses 12150 // null as base declaration. 12151 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 12152 MVLI.VarComponents.back().append(CurComponents.begin(), 12153 CurComponents.end()); 12154 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 12155 : CurDeclaration); 12156 } 12157 } 12158 12159 OMPClause * 12160 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 12161 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 12162 SourceLocation MapLoc, SourceLocation ColonLoc, 12163 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 12164 SourceLocation LParenLoc, SourceLocation EndLoc) { 12165 MappableVarListInfo MVLI(VarList); 12166 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 12167 MapType, IsMapTypeImplicit); 12168 12169 // We need to produce a map clause even if we don't have variables so that 12170 // other diagnostics related with non-existing map clauses are accurate. 12171 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12172 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 12173 MVLI.VarComponents, MapTypeModifier, MapType, 12174 IsMapTypeImplicit, MapLoc); 12175 } 12176 12177 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 12178 TypeResult ParsedType) { 12179 assert(ParsedType.isUsable()); 12180 12181 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 12182 if (ReductionType.isNull()) 12183 return QualType(); 12184 12185 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 12186 // A type name in a declare reduction directive cannot be a function type, an 12187 // array type, a reference type, or a type qualified with const, volatile or 12188 // restrict. 12189 if (ReductionType.hasQualifiers()) { 12190 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 12191 return QualType(); 12192 } 12193 12194 if (ReductionType->isFunctionType()) { 12195 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 12196 return QualType(); 12197 } 12198 if (ReductionType->isReferenceType()) { 12199 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 12200 return QualType(); 12201 } 12202 if (ReductionType->isArrayType()) { 12203 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 12204 return QualType(); 12205 } 12206 return ReductionType; 12207 } 12208 12209 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 12210 Scope *S, DeclContext *DC, DeclarationName Name, 12211 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 12212 AccessSpecifier AS, Decl *PrevDeclInScope) { 12213 SmallVector<Decl *, 8> Decls; 12214 Decls.reserve(ReductionTypes.size()); 12215 12216 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 12217 forRedeclarationInCurContext()); 12218 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 12219 // A reduction-identifier may not be re-declared in the current scope for the 12220 // same type or for a type that is compatible according to the base language 12221 // rules. 12222 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 12223 OMPDeclareReductionDecl *PrevDRD = nullptr; 12224 bool InCompoundScope = true; 12225 if (S != nullptr) { 12226 // Find previous declaration with the same name not referenced in other 12227 // declarations. 12228 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 12229 InCompoundScope = 12230 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 12231 LookupName(Lookup, S); 12232 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 12233 /*AllowInlineNamespace=*/false); 12234 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 12235 auto Filter = Lookup.makeFilter(); 12236 while (Filter.hasNext()) { 12237 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 12238 if (InCompoundScope) { 12239 auto I = UsedAsPrevious.find(PrevDecl); 12240 if (I == UsedAsPrevious.end()) 12241 UsedAsPrevious[PrevDecl] = false; 12242 if (auto *D = PrevDecl->getPrevDeclInScope()) 12243 UsedAsPrevious[D] = true; 12244 } 12245 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 12246 PrevDecl->getLocation(); 12247 } 12248 Filter.done(); 12249 if (InCompoundScope) { 12250 for (auto &PrevData : UsedAsPrevious) { 12251 if (!PrevData.second) { 12252 PrevDRD = PrevData.first; 12253 break; 12254 } 12255 } 12256 } 12257 } else if (PrevDeclInScope != nullptr) { 12258 auto *PrevDRDInScope = PrevDRD = 12259 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 12260 do { 12261 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 12262 PrevDRDInScope->getLocation(); 12263 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 12264 } while (PrevDRDInScope != nullptr); 12265 } 12266 for (auto &TyData : ReductionTypes) { 12267 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 12268 bool Invalid = false; 12269 if (I != PreviousRedeclTypes.end()) { 12270 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 12271 << TyData.first; 12272 Diag(I->second, diag::note_previous_definition); 12273 Invalid = true; 12274 } 12275 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 12276 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 12277 Name, TyData.first, PrevDRD); 12278 DC->addDecl(DRD); 12279 DRD->setAccess(AS); 12280 Decls.push_back(DRD); 12281 if (Invalid) 12282 DRD->setInvalidDecl(); 12283 else 12284 PrevDRD = DRD; 12285 } 12286 12287 return DeclGroupPtrTy::make( 12288 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 12289 } 12290 12291 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 12292 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12293 12294 // Enter new function scope. 12295 PushFunctionScope(); 12296 getCurFunction()->setHasBranchProtectedScope(); 12297 getCurFunction()->setHasOMPDeclareReductionCombiner(); 12298 12299 if (S != nullptr) 12300 PushDeclContext(S, DRD); 12301 else 12302 CurContext = DRD; 12303 12304 PushExpressionEvaluationContext( 12305 ExpressionEvaluationContext::PotentiallyEvaluated); 12306 12307 QualType ReductionType = DRD->getType(); 12308 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 12309 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 12310 // uses semantics of argument handles by value, but it should be passed by 12311 // reference. C lang does not support references, so pass all parameters as 12312 // pointers. 12313 // Create 'T omp_in;' variable. 12314 auto *OmpInParm = 12315 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 12316 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 12317 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 12318 // uses semantics of argument handles by value, but it should be passed by 12319 // reference. C lang does not support references, so pass all parameters as 12320 // pointers. 12321 // Create 'T omp_out;' variable. 12322 auto *OmpOutParm = 12323 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 12324 if (S != nullptr) { 12325 PushOnScopeChains(OmpInParm, S); 12326 PushOnScopeChains(OmpOutParm, S); 12327 } else { 12328 DRD->addDecl(OmpInParm); 12329 DRD->addDecl(OmpOutParm); 12330 } 12331 } 12332 12333 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 12334 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12335 DiscardCleanupsInEvaluationContext(); 12336 PopExpressionEvaluationContext(); 12337 12338 PopDeclContext(); 12339 PopFunctionScopeInfo(); 12340 12341 if (Combiner != nullptr) 12342 DRD->setCombiner(Combiner); 12343 else 12344 DRD->setInvalidDecl(); 12345 } 12346 12347 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 12348 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12349 12350 // Enter new function scope. 12351 PushFunctionScope(); 12352 getCurFunction()->setHasBranchProtectedScope(); 12353 12354 if (S != nullptr) 12355 PushDeclContext(S, DRD); 12356 else 12357 CurContext = DRD; 12358 12359 PushExpressionEvaluationContext( 12360 ExpressionEvaluationContext::PotentiallyEvaluated); 12361 12362 QualType ReductionType = DRD->getType(); 12363 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 12364 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 12365 // uses semantics of argument handles by value, but it should be passed by 12366 // reference. C lang does not support references, so pass all parameters as 12367 // pointers. 12368 // Create 'T omp_priv;' variable. 12369 auto *OmpPrivParm = 12370 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 12371 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 12372 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 12373 // uses semantics of argument handles by value, but it should be passed by 12374 // reference. C lang does not support references, so pass all parameters as 12375 // pointers. 12376 // Create 'T omp_orig;' variable. 12377 auto *OmpOrigParm = 12378 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 12379 if (S != nullptr) { 12380 PushOnScopeChains(OmpPrivParm, S); 12381 PushOnScopeChains(OmpOrigParm, S); 12382 } else { 12383 DRD->addDecl(OmpPrivParm); 12384 DRD->addDecl(OmpOrigParm); 12385 } 12386 return OmpPrivParm; 12387 } 12388 12389 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 12390 VarDecl *OmpPrivParm) { 12391 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12392 DiscardCleanupsInEvaluationContext(); 12393 PopExpressionEvaluationContext(); 12394 12395 PopDeclContext(); 12396 PopFunctionScopeInfo(); 12397 12398 if (Initializer != nullptr) { 12399 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 12400 } else if (OmpPrivParm->hasInit()) { 12401 DRD->setInitializer(OmpPrivParm->getInit(), 12402 OmpPrivParm->isDirectInit() 12403 ? OMPDeclareReductionDecl::DirectInit 12404 : OMPDeclareReductionDecl::CopyInit); 12405 } else { 12406 DRD->setInvalidDecl(); 12407 } 12408 } 12409 12410 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 12411 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 12412 for (auto *D : DeclReductions.get()) { 12413 if (IsValid) { 12414 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12415 if (S != nullptr) 12416 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 12417 } else 12418 D->setInvalidDecl(); 12419 } 12420 return DeclReductions; 12421 } 12422 12423 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 12424 SourceLocation StartLoc, 12425 SourceLocation LParenLoc, 12426 SourceLocation EndLoc) { 12427 Expr *ValExpr = NumTeams; 12428 Stmt *HelperValStmt = nullptr; 12429 12430 // OpenMP [teams Constrcut, Restrictions] 12431 // The num_teams expression must evaluate to a positive integer value. 12432 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 12433 /*StrictlyPositive=*/true)) 12434 return nullptr; 12435 12436 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12437 OpenMPDirectiveKind CaptureRegion = 12438 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 12439 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12440 ValExpr = MakeFullExpr(ValExpr).get(); 12441 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 12442 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12443 HelperValStmt = buildPreInits(Context, Captures); 12444 } 12445 12446 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 12447 StartLoc, LParenLoc, EndLoc); 12448 } 12449 12450 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 12451 SourceLocation StartLoc, 12452 SourceLocation LParenLoc, 12453 SourceLocation EndLoc) { 12454 Expr *ValExpr = ThreadLimit; 12455 Stmt *HelperValStmt = nullptr; 12456 12457 // OpenMP [teams Constrcut, Restrictions] 12458 // The thread_limit expression must evaluate to a positive integer value. 12459 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 12460 /*StrictlyPositive=*/true)) 12461 return nullptr; 12462 12463 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12464 OpenMPDirectiveKind CaptureRegion = 12465 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 12466 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12467 ValExpr = MakeFullExpr(ValExpr).get(); 12468 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 12469 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12470 HelperValStmt = buildPreInits(Context, Captures); 12471 } 12472 12473 return new (Context) OMPThreadLimitClause( 12474 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 12475 } 12476 12477 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 12478 SourceLocation StartLoc, 12479 SourceLocation LParenLoc, 12480 SourceLocation EndLoc) { 12481 Expr *ValExpr = Priority; 12482 12483 // OpenMP [2.9.1, task Constrcut] 12484 // The priority-value is a non-negative numerical scalar expression. 12485 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 12486 /*StrictlyPositive=*/false)) 12487 return nullptr; 12488 12489 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 12490 } 12491 12492 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 12493 SourceLocation StartLoc, 12494 SourceLocation LParenLoc, 12495 SourceLocation EndLoc) { 12496 Expr *ValExpr = Grainsize; 12497 12498 // OpenMP [2.9.2, taskloop Constrcut] 12499 // The parameter of the grainsize clause must be a positive integer 12500 // expression. 12501 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 12502 /*StrictlyPositive=*/true)) 12503 return nullptr; 12504 12505 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 12506 } 12507 12508 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 12509 SourceLocation StartLoc, 12510 SourceLocation LParenLoc, 12511 SourceLocation EndLoc) { 12512 Expr *ValExpr = NumTasks; 12513 12514 // OpenMP [2.9.2, taskloop Constrcut] 12515 // The parameter of the num_tasks clause must be a positive integer 12516 // expression. 12517 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 12518 /*StrictlyPositive=*/true)) 12519 return nullptr; 12520 12521 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 12522 } 12523 12524 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 12525 SourceLocation LParenLoc, 12526 SourceLocation EndLoc) { 12527 // OpenMP [2.13.2, critical construct, Description] 12528 // ... where hint-expression is an integer constant expression that evaluates 12529 // to a valid lock hint. 12530 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 12531 if (HintExpr.isInvalid()) 12532 return nullptr; 12533 return new (Context) 12534 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 12535 } 12536 12537 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 12538 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 12539 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 12540 SourceLocation EndLoc) { 12541 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 12542 std::string Values; 12543 Values += "'"; 12544 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 12545 Values += "'"; 12546 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 12547 << Values << getOpenMPClauseName(OMPC_dist_schedule); 12548 return nullptr; 12549 } 12550 Expr *ValExpr = ChunkSize; 12551 Stmt *HelperValStmt = nullptr; 12552 if (ChunkSize) { 12553 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 12554 !ChunkSize->isInstantiationDependent() && 12555 !ChunkSize->containsUnexpandedParameterPack()) { 12556 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 12557 ExprResult Val = 12558 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 12559 if (Val.isInvalid()) 12560 return nullptr; 12561 12562 ValExpr = Val.get(); 12563 12564 // OpenMP [2.7.1, Restrictions] 12565 // chunk_size must be a loop invariant integer expression with a positive 12566 // value. 12567 llvm::APSInt Result; 12568 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 12569 if (Result.isSigned() && !Result.isStrictlyPositive()) { 12570 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 12571 << "dist_schedule" << ChunkSize->getSourceRange(); 12572 return nullptr; 12573 } 12574 } else if (getOpenMPCaptureRegionForClause( 12575 DSAStack->getCurrentDirective(), OMPC_dist_schedule) != 12576 OMPD_unknown && 12577 !CurContext->isDependentContext()) { 12578 ValExpr = MakeFullExpr(ValExpr).get(); 12579 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 12580 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12581 HelperValStmt = buildPreInits(Context, Captures); 12582 } 12583 } 12584 } 12585 12586 return new (Context) 12587 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 12588 Kind, ValExpr, HelperValStmt); 12589 } 12590 12591 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 12592 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 12593 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 12594 SourceLocation KindLoc, SourceLocation EndLoc) { 12595 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 12596 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 12597 std::string Value; 12598 SourceLocation Loc; 12599 Value += "'"; 12600 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 12601 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 12602 OMPC_DEFAULTMAP_MODIFIER_tofrom); 12603 Loc = MLoc; 12604 } else { 12605 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 12606 OMPC_DEFAULTMAP_scalar); 12607 Loc = KindLoc; 12608 } 12609 Value += "'"; 12610 Diag(Loc, diag::err_omp_unexpected_clause_value) 12611 << Value << getOpenMPClauseName(OMPC_defaultmap); 12612 return nullptr; 12613 } 12614 DSAStack->setDefaultDMAToFromScalar(StartLoc); 12615 12616 return new (Context) 12617 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 12618 } 12619 12620 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 12621 DeclContext *CurLexicalContext = getCurLexicalContext(); 12622 if (!CurLexicalContext->isFileContext() && 12623 !CurLexicalContext->isExternCContext() && 12624 !CurLexicalContext->isExternCXXContext() && 12625 !isa<CXXRecordDecl>(CurLexicalContext) && 12626 !isa<ClassTemplateDecl>(CurLexicalContext) && 12627 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 12628 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 12629 Diag(Loc, diag::err_omp_region_not_file_context); 12630 return false; 12631 } 12632 if (IsInOpenMPDeclareTargetContext) { 12633 Diag(Loc, diag::err_omp_enclosed_declare_target); 12634 return false; 12635 } 12636 12637 IsInOpenMPDeclareTargetContext = true; 12638 return true; 12639 } 12640 12641 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 12642 assert(IsInOpenMPDeclareTargetContext && 12643 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 12644 12645 IsInOpenMPDeclareTargetContext = false; 12646 } 12647 12648 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 12649 CXXScopeSpec &ScopeSpec, 12650 const DeclarationNameInfo &Id, 12651 OMPDeclareTargetDeclAttr::MapTypeTy MT, 12652 NamedDeclSetType &SameDirectiveDecls) { 12653 LookupResult Lookup(*this, Id, LookupOrdinaryName); 12654 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 12655 12656 if (Lookup.isAmbiguous()) 12657 return; 12658 Lookup.suppressDiagnostics(); 12659 12660 if (!Lookup.isSingleResult()) { 12661 if (TypoCorrection Corrected = 12662 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 12663 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 12664 CTK_ErrorRecovery)) { 12665 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 12666 << Id.getName()); 12667 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 12668 return; 12669 } 12670 12671 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 12672 return; 12673 } 12674 12675 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 12676 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 12677 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 12678 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 12679 12680 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 12681 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 12682 ND->addAttr(A); 12683 if (ASTMutationListener *ML = Context.getASTMutationListener()) 12684 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 12685 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc()); 12686 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 12687 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 12688 << Id.getName(); 12689 } 12690 } else 12691 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 12692 } 12693 12694 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 12695 Sema &SemaRef, Decl *D) { 12696 if (!D) 12697 return; 12698 Decl *LD = nullptr; 12699 if (isa<TagDecl>(D)) { 12700 LD = cast<TagDecl>(D)->getDefinition(); 12701 } else if (isa<VarDecl>(D)) { 12702 LD = cast<VarDecl>(D)->getDefinition(); 12703 12704 // If this is an implicit variable that is legal and we do not need to do 12705 // anything. 12706 if (cast<VarDecl>(D)->isImplicit()) { 12707 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12708 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 12709 D->addAttr(A); 12710 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 12711 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12712 return; 12713 } 12714 12715 } else if (isa<FunctionDecl>(D)) { 12716 const FunctionDecl *FD = nullptr; 12717 if (cast<FunctionDecl>(D)->hasBody(FD)) 12718 LD = const_cast<FunctionDecl *>(FD); 12719 12720 // If the definition is associated with the current declaration in the 12721 // target region (it can be e.g. a lambda) that is legal and we do not need 12722 // to do anything else. 12723 if (LD == D) { 12724 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12725 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 12726 D->addAttr(A); 12727 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 12728 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12729 return; 12730 } 12731 } 12732 if (!LD) 12733 LD = D; 12734 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 12735 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 12736 // Outlined declaration is not declared target. 12737 if (LD->isOutOfLine()) { 12738 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 12739 SemaRef.Diag(SL, diag::note_used_here) << SR; 12740 } else { 12741 DeclContext *DC = LD->getDeclContext(); 12742 while (DC) { 12743 if (isa<FunctionDecl>(DC) && 12744 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 12745 break; 12746 DC = DC->getParent(); 12747 } 12748 if (DC) 12749 return; 12750 12751 // Is not declared in target context. 12752 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 12753 SemaRef.Diag(SL, diag::note_used_here) << SR; 12754 } 12755 // Mark decl as declared target to prevent further diagnostic. 12756 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12757 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 12758 D->addAttr(A); 12759 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 12760 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12761 } 12762 } 12763 12764 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 12765 Sema &SemaRef, DSAStackTy *Stack, 12766 ValueDecl *VD) { 12767 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 12768 return true; 12769 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) 12770 return false; 12771 return true; 12772 } 12773 12774 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 12775 SourceLocation IdLoc) { 12776 if (!D || D->isInvalidDecl()) 12777 return; 12778 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 12779 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 12780 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 12781 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12782 if (DSAStack->isThreadPrivate(VD)) { 12783 Diag(SL, diag::err_omp_threadprivate_in_target); 12784 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 12785 return; 12786 } 12787 } 12788 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 12789 // Problem if any with var declared with incomplete type will be reported 12790 // as normal, so no need to check it here. 12791 if ((E || !VD->getType()->isIncompleteType()) && 12792 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 12793 // Mark decl as declared target to prevent further diagnostic. 12794 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { 12795 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12796 Context, OMPDeclareTargetDeclAttr::MT_To); 12797 VD->addAttr(A); 12798 if (ASTMutationListener *ML = Context.getASTMutationListener()) 12799 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 12800 } 12801 return; 12802 } 12803 } 12804 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 12805 if (FD->hasAttr<OMPDeclareTargetDeclAttr>() && 12806 (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() == 12807 OMPDeclareTargetDeclAttr::MT_Link)) { 12808 assert(IdLoc.isValid() && "Source location is expected"); 12809 Diag(IdLoc, diag::err_omp_function_in_link_clause); 12810 Diag(FD->getLocation(), diag::note_defined_here) << FD; 12811 return; 12812 } 12813 } 12814 if (!E) { 12815 // Checking declaration inside declare target region. 12816 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 12817 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { 12818 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12819 Context, OMPDeclareTargetDeclAttr::MT_To); 12820 D->addAttr(A); 12821 if (ASTMutationListener *ML = Context.getASTMutationListener()) 12822 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12823 } 12824 return; 12825 } 12826 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 12827 } 12828 12829 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 12830 SourceLocation StartLoc, 12831 SourceLocation LParenLoc, 12832 SourceLocation EndLoc) { 12833 MappableVarListInfo MVLI(VarList); 12834 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 12835 if (MVLI.ProcessedVarList.empty()) 12836 return nullptr; 12837 12838 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12839 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 12840 MVLI.VarComponents); 12841 } 12842 12843 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 12844 SourceLocation StartLoc, 12845 SourceLocation LParenLoc, 12846 SourceLocation EndLoc) { 12847 MappableVarListInfo MVLI(VarList); 12848 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 12849 if (MVLI.ProcessedVarList.empty()) 12850 return nullptr; 12851 12852 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12853 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 12854 MVLI.VarComponents); 12855 } 12856 12857 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 12858 SourceLocation StartLoc, 12859 SourceLocation LParenLoc, 12860 SourceLocation EndLoc) { 12861 MappableVarListInfo MVLI(VarList); 12862 SmallVector<Expr *, 8> PrivateCopies; 12863 SmallVector<Expr *, 8> Inits; 12864 12865 for (auto &RefExpr : VarList) { 12866 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 12867 SourceLocation ELoc; 12868 SourceRange ERange; 12869 Expr *SimpleRefExpr = RefExpr; 12870 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12871 if (Res.second) { 12872 // It will be analyzed later. 12873 MVLI.ProcessedVarList.push_back(RefExpr); 12874 PrivateCopies.push_back(nullptr); 12875 Inits.push_back(nullptr); 12876 } 12877 ValueDecl *D = Res.first; 12878 if (!D) 12879 continue; 12880 12881 QualType Type = D->getType(); 12882 Type = Type.getNonReferenceType().getUnqualifiedType(); 12883 12884 auto *VD = dyn_cast<VarDecl>(D); 12885 12886 // Item should be a pointer or reference to pointer. 12887 if (!Type->isPointerType()) { 12888 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 12889 << 0 << RefExpr->getSourceRange(); 12890 continue; 12891 } 12892 12893 // Build the private variable and the expression that refers to it. 12894 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 12895 D->hasAttrs() ? &D->getAttrs() : nullptr); 12896 if (VDPrivate->isInvalidDecl()) 12897 continue; 12898 12899 CurContext->addDecl(VDPrivate); 12900 auto VDPrivateRefExpr = buildDeclRefExpr( 12901 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 12902 12903 // Add temporary variable to initialize the private copy of the pointer. 12904 auto *VDInit = 12905 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 12906 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 12907 RefExpr->getExprLoc()); 12908 AddInitializerToDecl(VDPrivate, 12909 DefaultLvalueConversion(VDInitRefExpr).get(), 12910 /*DirectInit=*/false); 12911 12912 // If required, build a capture to implement the privatization initialized 12913 // with the current list item value. 12914 DeclRefExpr *Ref = nullptr; 12915 if (!VD) 12916 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 12917 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 12918 PrivateCopies.push_back(VDPrivateRefExpr); 12919 Inits.push_back(VDInitRefExpr); 12920 12921 // We need to add a data sharing attribute for this variable to make sure it 12922 // is correctly captured. A variable that shows up in a use_device_ptr has 12923 // similar properties of a first private variable. 12924 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 12925 12926 // Create a mappable component for the list item. List items in this clause 12927 // only need a component. 12928 MVLI.VarBaseDeclarations.push_back(D); 12929 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 12930 MVLI.VarComponents.back().push_back( 12931 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 12932 } 12933 12934 if (MVLI.ProcessedVarList.empty()) 12935 return nullptr; 12936 12937 return OMPUseDevicePtrClause::Create( 12938 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 12939 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 12940 } 12941 12942 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 12943 SourceLocation StartLoc, 12944 SourceLocation LParenLoc, 12945 SourceLocation EndLoc) { 12946 MappableVarListInfo MVLI(VarList); 12947 for (auto &RefExpr : VarList) { 12948 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 12949 SourceLocation ELoc; 12950 SourceRange ERange; 12951 Expr *SimpleRefExpr = RefExpr; 12952 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12953 if (Res.second) { 12954 // It will be analyzed later. 12955 MVLI.ProcessedVarList.push_back(RefExpr); 12956 } 12957 ValueDecl *D = Res.first; 12958 if (!D) 12959 continue; 12960 12961 QualType Type = D->getType(); 12962 // item should be a pointer or array or reference to pointer or array 12963 if (!Type.getNonReferenceType()->isPointerType() && 12964 !Type.getNonReferenceType()->isArrayType()) { 12965 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 12966 << 0 << RefExpr->getSourceRange(); 12967 continue; 12968 } 12969 12970 // Check if the declaration in the clause does not show up in any data 12971 // sharing attribute. 12972 auto DVar = DSAStack->getTopDSA(D, false); 12973 if (isOpenMPPrivate(DVar.CKind)) { 12974 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 12975 << getOpenMPClauseName(DVar.CKind) 12976 << getOpenMPClauseName(OMPC_is_device_ptr) 12977 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 12978 ReportOriginalDSA(*this, DSAStack, D, DVar); 12979 continue; 12980 } 12981 12982 Expr *ConflictExpr; 12983 if (DSAStack->checkMappableExprComponentListsForDecl( 12984 D, /*CurrentRegionOnly=*/true, 12985 [&ConflictExpr]( 12986 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 12987 OpenMPClauseKind) -> bool { 12988 ConflictExpr = R.front().getAssociatedExpression(); 12989 return true; 12990 })) { 12991 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 12992 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 12993 << ConflictExpr->getSourceRange(); 12994 continue; 12995 } 12996 12997 // Store the components in the stack so that they can be used to check 12998 // against other clauses later on. 12999 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 13000 DSAStack->addMappableExpressionComponents( 13001 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 13002 13003 // Record the expression we've just processed. 13004 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 13005 13006 // Create a mappable component for the list item. List items in this clause 13007 // only need a component. We use a null declaration to signal fields in 13008 // 'this'. 13009 assert((isa<DeclRefExpr>(SimpleRefExpr) || 13010 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 13011 "Unexpected device pointer expression!"); 13012 MVLI.VarBaseDeclarations.push_back( 13013 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 13014 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 13015 MVLI.VarComponents.back().push_back(MC); 13016 } 13017 13018 if (MVLI.ProcessedVarList.empty()) 13019 return nullptr; 13020 13021 return OMPIsDevicePtrClause::Create( 13022 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 13023 MVLI.VarBaseDeclarations, MVLI.VarComponents); 13024 } 13025