1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// \file 9 /// This file implements semantic analysis for OpenMP directives and 10 /// clauses. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/DeclOpenMP.h" 21 #include "clang/AST/StmtCXX.h" 22 #include "clang/AST/StmtOpenMP.h" 23 #include "clang/AST/StmtVisitor.h" 24 #include "clang/AST/TypeOrdering.h" 25 #include "clang/Basic/OpenMPKinds.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Scope.h" 29 #include "clang/Sema/ScopeInfo.h" 30 #include "clang/Sema/SemaInternal.h" 31 #include "llvm/ADT/PointerEmbeddedInt.h" 32 using namespace clang; 33 34 //===----------------------------------------------------------------------===// 35 // Stack of data-sharing attributes for variables 36 //===----------------------------------------------------------------------===// 37 38 static const Expr *checkMapClauseExpressionBase( 39 Sema &SemaRef, Expr *E, 40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 41 OpenMPClauseKind CKind, bool NoDiagnose); 42 43 namespace { 44 /// Default data sharing attributes, which can be applied to directive. 45 enum DefaultDataSharingAttributes { 46 DSA_unspecified = 0, /// Data sharing attribute not specified. 47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'. 48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'. 49 }; 50 51 /// Attributes of the defaultmap clause. 52 enum DefaultMapAttributes { 53 DMA_unspecified, /// Default mapping is not specified. 54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'. 55 }; 56 57 /// Stack for tracking declarations used in OpenMP directives and 58 /// clauses and their data-sharing attributes. 59 class DSAStackTy { 60 public: 61 struct DSAVarData { 62 OpenMPDirectiveKind DKind = OMPD_unknown; 63 OpenMPClauseKind CKind = OMPC_unknown; 64 const Expr *RefExpr = nullptr; 65 DeclRefExpr *PrivateCopy = nullptr; 66 SourceLocation ImplicitDSALoc; 67 DSAVarData() = default; 68 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 69 const Expr *RefExpr, DeclRefExpr *PrivateCopy, 70 SourceLocation ImplicitDSALoc) 71 : DKind(DKind), CKind(CKind), RefExpr(RefExpr), 72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {} 73 }; 74 using OperatorOffsetTy = 75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>; 76 using DoacrossDependMapTy = 77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>; 78 79 private: 80 struct DSAInfo { 81 OpenMPClauseKind Attributes = OMPC_unknown; 82 /// Pointer to a reference expression and a flag which shows that the 83 /// variable is marked as lastprivate(true) or not (false). 84 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr; 85 DeclRefExpr *PrivateCopy = nullptr; 86 }; 87 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>; 88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>; 89 using LCDeclInfo = std::pair<unsigned, VarDecl *>; 90 using LoopControlVariablesMapTy = 91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>; 92 /// Struct that associates a component with the clause kind where they are 93 /// found. 94 struct MappedExprComponentTy { 95 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 96 OpenMPClauseKind Kind = OMPC_unknown; 97 }; 98 using MappedExprComponentsTy = 99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>; 100 using CriticalsWithHintsTy = 101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>; 102 struct ReductionData { 103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>; 104 SourceRange ReductionRange; 105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 106 ReductionData() = default; 107 void set(BinaryOperatorKind BO, SourceRange RR) { 108 ReductionRange = RR; 109 ReductionOp = BO; 110 } 111 void set(const Expr *RefExpr, SourceRange RR) { 112 ReductionRange = RR; 113 ReductionOp = RefExpr; 114 } 115 }; 116 using DeclReductionMapTy = 117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>; 118 119 struct SharingMapTy { 120 DeclSAMapTy SharingMap; 121 DeclReductionMapTy ReductionMap; 122 AlignedMapTy AlignedMap; 123 MappedExprComponentsTy MappedExprComponents; 124 LoopControlVariablesMapTy LCVMap; 125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 126 SourceLocation DefaultAttrLoc; 127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified; 128 SourceLocation DefaultMapAttrLoc; 129 OpenMPDirectiveKind Directive = OMPD_unknown; 130 DeclarationNameInfo DirectiveName; 131 Scope *CurScope = nullptr; 132 SourceLocation ConstructLoc; 133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 134 /// get the data (loop counters etc.) about enclosing loop-based construct. 135 /// This data is required during codegen. 136 DoacrossDependMapTy DoacrossDepends; 137 /// First argument (Expr *) contains optional argument of the 138 /// 'ordered' clause, the second one is true if the regions has 'ordered' 139 /// clause, false otherwise. 140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; 141 unsigned AssociatedLoops = 1; 142 const Decl *PossiblyLoopCounter = nullptr; 143 bool NowaitRegion = false; 144 bool CancelRegion = false; 145 bool LoopStart = false; 146 SourceLocation InnerTeamsRegionLoc; 147 /// Reference to the taskgroup task_reduction reference expression. 148 Expr *TaskgroupReductionRef = nullptr; 149 llvm::DenseSet<QualType> MappedClassesQualTypes; 150 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 151 Scope *CurScope, SourceLocation Loc) 152 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 153 ConstructLoc(Loc) {} 154 SharingMapTy() = default; 155 }; 156 157 using StackTy = SmallVector<SharingMapTy, 4>; 158 159 /// Stack of used declaration and their data-sharing attributes. 160 DeclSAMapTy Threadprivates; 161 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 162 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 163 /// true, if check for DSA must be from parent directive, false, if 164 /// from current directive. 165 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 166 Sema &SemaRef; 167 bool ForceCapturing = false; 168 /// true if all the vaiables in the target executable directives must be 169 /// captured by reference. 170 bool ForceCaptureByReferenceInTargetExecutable = false; 171 CriticalsWithHintsTy Criticals; 172 173 using iterator = StackTy::const_reverse_iterator; 174 175 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const; 176 177 /// Checks if the variable is a local for OpenMP region. 178 bool isOpenMPLocal(VarDecl *D, iterator Iter) const; 179 180 bool isStackEmpty() const { 181 return Stack.empty() || 182 Stack.back().second != CurrentNonCapturingFunctionScope || 183 Stack.back().first.empty(); 184 } 185 186 /// Vector of previously declared requires directives 187 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 188 189 public: 190 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 191 192 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 193 OpenMPClauseKind getClauseParsingMode() const { 194 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 195 return ClauseKindMode; 196 } 197 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 198 199 bool isForceVarCapturing() const { return ForceCapturing; } 200 void setForceVarCapturing(bool V) { ForceCapturing = V; } 201 202 void setForceCaptureByReferenceInTargetExecutable(bool V) { 203 ForceCaptureByReferenceInTargetExecutable = V; 204 } 205 bool isForceCaptureByReferenceInTargetExecutable() const { 206 return ForceCaptureByReferenceInTargetExecutable; 207 } 208 209 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 210 Scope *CurScope, SourceLocation Loc) { 211 if (Stack.empty() || 212 Stack.back().second != CurrentNonCapturingFunctionScope) 213 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 214 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 215 Stack.back().first.back().DefaultAttrLoc = Loc; 216 } 217 218 void pop() { 219 assert(!Stack.back().first.empty() && 220 "Data-sharing attributes stack is empty!"); 221 Stack.back().first.pop_back(); 222 } 223 224 /// Marks that we're started loop parsing. 225 void loopInit() { 226 assert(isOpenMPLoopDirective(getCurrentDirective()) && 227 "Expected loop-based directive."); 228 Stack.back().first.back().LoopStart = true; 229 } 230 /// Start capturing of the variables in the loop context. 231 void loopStart() { 232 assert(isOpenMPLoopDirective(getCurrentDirective()) && 233 "Expected loop-based directive."); 234 Stack.back().first.back().LoopStart = false; 235 } 236 /// true, if variables are captured, false otherwise. 237 bool isLoopStarted() const { 238 assert(isOpenMPLoopDirective(getCurrentDirective()) && 239 "Expected loop-based directive."); 240 return !Stack.back().first.back().LoopStart; 241 } 242 /// Marks (or clears) declaration as possibly loop counter. 243 void resetPossibleLoopCounter(const Decl *D = nullptr) { 244 Stack.back().first.back().PossiblyLoopCounter = 245 D ? D->getCanonicalDecl() : D; 246 } 247 /// Gets the possible loop counter decl. 248 const Decl *getPossiblyLoopCunter() const { 249 return Stack.back().first.back().PossiblyLoopCounter; 250 } 251 /// Start new OpenMP region stack in new non-capturing function. 252 void pushFunction() { 253 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 254 assert(!isa<CapturingScopeInfo>(CurFnScope)); 255 CurrentNonCapturingFunctionScope = CurFnScope; 256 } 257 /// Pop region stack for non-capturing function. 258 void popFunction(const FunctionScopeInfo *OldFSI) { 259 if (!Stack.empty() && Stack.back().second == OldFSI) { 260 assert(Stack.back().first.empty()); 261 Stack.pop_back(); 262 } 263 CurrentNonCapturingFunctionScope = nullptr; 264 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 265 if (!isa<CapturingScopeInfo>(FSI)) { 266 CurrentNonCapturingFunctionScope = FSI; 267 break; 268 } 269 } 270 } 271 272 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) { 273 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint); 274 } 275 const std::pair<const OMPCriticalDirective *, llvm::APSInt> 276 getCriticalWithHint(const DeclarationNameInfo &Name) const { 277 auto I = Criticals.find(Name.getAsString()); 278 if (I != Criticals.end()) 279 return I->second; 280 return std::make_pair(nullptr, llvm::APSInt()); 281 } 282 /// If 'aligned' declaration for given variable \a D was not seen yet, 283 /// add it and return NULL; otherwise return previous occurrence's expression 284 /// for diagnostics. 285 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE); 286 287 /// Register specified variable as loop control variable. 288 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture); 289 /// Check if the specified variable is a loop control variable for 290 /// current region. 291 /// \return The index of the loop control variable in the list of associated 292 /// for-loops (from outer to inner). 293 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const; 294 /// Check if the specified variable is a loop control variable for 295 /// parent region. 296 /// \return The index of the loop control variable in the list of associated 297 /// for-loops (from outer to inner). 298 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const; 299 /// Get the loop control variable for the I-th loop (or nullptr) in 300 /// parent directive. 301 const ValueDecl *getParentLoopControlVariable(unsigned I) const; 302 303 /// Adds explicit data sharing attribute to the specified declaration. 304 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 305 DeclRefExpr *PrivateCopy = nullptr); 306 307 /// Adds additional information for the reduction items with the reduction id 308 /// represented as an operator. 309 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 310 BinaryOperatorKind BOK); 311 /// Adds additional information for the reduction items with the reduction id 312 /// represented as reduction identifier. 313 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 314 const Expr *ReductionRef); 315 /// Returns the location and reduction operation from the innermost parent 316 /// region for the given \p D. 317 const DSAVarData 318 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 319 BinaryOperatorKind &BOK, 320 Expr *&TaskgroupDescriptor) const; 321 /// Returns the location and reduction operation from the innermost parent 322 /// region for the given \p D. 323 const DSAVarData 324 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 325 const Expr *&ReductionRef, 326 Expr *&TaskgroupDescriptor) const; 327 /// Return reduction reference expression for the current taskgroup. 328 Expr *getTaskgroupReductionRef() const { 329 assert(Stack.back().first.back().Directive == OMPD_taskgroup && 330 "taskgroup reference expression requested for non taskgroup " 331 "directive."); 332 return Stack.back().first.back().TaskgroupReductionRef; 333 } 334 /// Checks if the given \p VD declaration is actually a taskgroup reduction 335 /// descriptor variable at the \p Level of OpenMP regions. 336 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const { 337 return Stack.back().first[Level].TaskgroupReductionRef && 338 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef) 339 ->getDecl() == VD; 340 } 341 342 /// Returns data sharing attributes from top of the stack for the 343 /// specified declaration. 344 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 345 /// Returns data-sharing attributes for the specified declaration. 346 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const; 347 /// Checks if the specified variables has data-sharing attributes which 348 /// match specified \a CPred predicate in any directive which matches \a DPred 349 /// predicate. 350 const DSAVarData 351 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 352 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 353 bool FromParent) const; 354 /// Checks if the specified variables has data-sharing attributes which 355 /// match specified \a CPred predicate in any innermost directive which 356 /// matches \a DPred predicate. 357 const DSAVarData 358 hasInnermostDSA(ValueDecl *D, 359 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 360 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 361 bool FromParent) const; 362 /// Checks if the specified variables has explicit data-sharing 363 /// attributes which match specified \a CPred predicate at the specified 364 /// OpenMP region. 365 bool hasExplicitDSA(const ValueDecl *D, 366 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 367 unsigned Level, bool NotLastprivate = false) const; 368 369 /// Returns true if the directive at level \Level matches in the 370 /// specified \a DPred predicate. 371 bool hasExplicitDirective( 372 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 373 unsigned Level) const; 374 375 /// Finds a directive which matches specified \a DPred predicate. 376 bool hasDirective( 377 const llvm::function_ref<bool( 378 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> 379 DPred, 380 bool FromParent) const; 381 382 /// Returns currently analyzed directive. 383 OpenMPDirectiveKind getCurrentDirective() const { 384 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive; 385 } 386 /// Returns directive kind at specified level. 387 OpenMPDirectiveKind getDirective(unsigned Level) const { 388 assert(!isStackEmpty() && "No directive at specified level."); 389 return Stack.back().first[Level].Directive; 390 } 391 /// Returns parent directive. 392 OpenMPDirectiveKind getParentDirective() const { 393 if (isStackEmpty() || Stack.back().first.size() == 1) 394 return OMPD_unknown; 395 return std::next(Stack.back().first.rbegin())->Directive; 396 } 397 398 /// Add requires decl to internal vector 399 void addRequiresDecl(OMPRequiresDecl *RD) { 400 RequiresDecls.push_back(RD); 401 } 402 403 /// Checks for a duplicate clause amongst previously declared requires 404 /// directives 405 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 406 bool IsDuplicate = false; 407 for (OMPClause *CNew : ClauseList) { 408 for (const OMPRequiresDecl *D : RequiresDecls) { 409 for (const OMPClause *CPrev : D->clauselists()) { 410 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 411 SemaRef.Diag(CNew->getBeginLoc(), 412 diag::err_omp_requires_clause_redeclaration) 413 << getOpenMPClauseName(CNew->getClauseKind()); 414 SemaRef.Diag(CPrev->getBeginLoc(), 415 diag::note_omp_requires_previous_clause) 416 << getOpenMPClauseName(CPrev->getClauseKind()); 417 IsDuplicate = true; 418 } 419 } 420 } 421 } 422 return IsDuplicate; 423 } 424 425 /// Set default data sharing attribute to none. 426 void setDefaultDSANone(SourceLocation Loc) { 427 assert(!isStackEmpty()); 428 Stack.back().first.back().DefaultAttr = DSA_none; 429 Stack.back().first.back().DefaultAttrLoc = Loc; 430 } 431 /// Set default data sharing attribute to shared. 432 void setDefaultDSAShared(SourceLocation Loc) { 433 assert(!isStackEmpty()); 434 Stack.back().first.back().DefaultAttr = DSA_shared; 435 Stack.back().first.back().DefaultAttrLoc = Loc; 436 } 437 /// Set default data mapping attribute to 'tofrom:scalar'. 438 void setDefaultDMAToFromScalar(SourceLocation Loc) { 439 assert(!isStackEmpty()); 440 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar; 441 Stack.back().first.back().DefaultMapAttrLoc = Loc; 442 } 443 444 DefaultDataSharingAttributes getDefaultDSA() const { 445 return isStackEmpty() ? DSA_unspecified 446 : Stack.back().first.back().DefaultAttr; 447 } 448 SourceLocation getDefaultDSALocation() const { 449 return isStackEmpty() ? SourceLocation() 450 : Stack.back().first.back().DefaultAttrLoc; 451 } 452 DefaultMapAttributes getDefaultDMA() const { 453 return isStackEmpty() ? DMA_unspecified 454 : Stack.back().first.back().DefaultMapAttr; 455 } 456 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const { 457 return Stack.back().first[Level].DefaultMapAttr; 458 } 459 SourceLocation getDefaultDMALocation() const { 460 return isStackEmpty() ? SourceLocation() 461 : Stack.back().first.back().DefaultMapAttrLoc; 462 } 463 464 /// Checks if the specified variable is a threadprivate. 465 bool isThreadPrivate(VarDecl *D) { 466 const DSAVarData DVar = getTopDSA(D, false); 467 return isOpenMPThreadPrivate(DVar.CKind); 468 } 469 470 /// Marks current region as ordered (it has an 'ordered' clause). 471 void setOrderedRegion(bool IsOrdered, const Expr *Param, 472 OMPOrderedClause *Clause) { 473 assert(!isStackEmpty()); 474 if (IsOrdered) 475 Stack.back().first.back().OrderedRegion.emplace(Param, Clause); 476 else 477 Stack.back().first.back().OrderedRegion.reset(); 478 } 479 /// Returns true, if region is ordered (has associated 'ordered' clause), 480 /// false - otherwise. 481 bool isOrderedRegion() const { 482 if (isStackEmpty()) 483 return false; 484 return Stack.back().first.rbegin()->OrderedRegion.hasValue(); 485 } 486 /// Returns optional parameter for the ordered region. 487 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 488 if (isStackEmpty() || 489 !Stack.back().first.rbegin()->OrderedRegion.hasValue()) 490 return std::make_pair(nullptr, nullptr); 491 return Stack.back().first.rbegin()->OrderedRegion.getValue(); 492 } 493 /// Returns true, if parent region is ordered (has associated 494 /// 'ordered' clause), false - otherwise. 495 bool isParentOrderedRegion() const { 496 if (isStackEmpty() || Stack.back().first.size() == 1) 497 return false; 498 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue(); 499 } 500 /// Returns optional parameter for the ordered region. 501 std::pair<const Expr *, OMPOrderedClause *> 502 getParentOrderedRegionParam() const { 503 if (isStackEmpty() || Stack.back().first.size() == 1 || 504 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue()) 505 return std::make_pair(nullptr, nullptr); 506 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue(); 507 } 508 /// Marks current region as nowait (it has a 'nowait' clause). 509 void setNowaitRegion(bool IsNowait = true) { 510 assert(!isStackEmpty()); 511 Stack.back().first.back().NowaitRegion = IsNowait; 512 } 513 /// Returns true, if parent region is nowait (has associated 514 /// 'nowait' clause), false - otherwise. 515 bool isParentNowaitRegion() const { 516 if (isStackEmpty() || Stack.back().first.size() == 1) 517 return false; 518 return std::next(Stack.back().first.rbegin())->NowaitRegion; 519 } 520 /// Marks parent region as cancel region. 521 void setParentCancelRegion(bool Cancel = true) { 522 if (!isStackEmpty() && Stack.back().first.size() > 1) { 523 auto &StackElemRef = *std::next(Stack.back().first.rbegin()); 524 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel; 525 } 526 } 527 /// Return true if current region has inner cancel construct. 528 bool isCancelRegion() const { 529 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion; 530 } 531 532 /// Set collapse value for the region. 533 void setAssociatedLoops(unsigned Val) { 534 assert(!isStackEmpty()); 535 Stack.back().first.back().AssociatedLoops = Val; 536 } 537 /// Return collapse value for region. 538 unsigned getAssociatedLoops() const { 539 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops; 540 } 541 542 /// Marks current target region as one with closely nested teams 543 /// region. 544 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 545 if (!isStackEmpty() && Stack.back().first.size() > 1) { 546 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc = 547 TeamsRegionLoc; 548 } 549 } 550 /// Returns true, if current region has closely nested teams region. 551 bool hasInnerTeamsRegion() const { 552 return getInnerTeamsRegionLoc().isValid(); 553 } 554 /// Returns location of the nested teams region (if any). 555 SourceLocation getInnerTeamsRegionLoc() const { 556 return isStackEmpty() ? SourceLocation() 557 : Stack.back().first.back().InnerTeamsRegionLoc; 558 } 559 560 Scope *getCurScope() const { 561 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 562 } 563 SourceLocation getConstructLoc() const { 564 return isStackEmpty() ? SourceLocation() 565 : Stack.back().first.back().ConstructLoc; 566 } 567 568 /// Do the check specified in \a Check to all component lists and return true 569 /// if any issue is found. 570 bool checkMappableExprComponentListsForDecl( 571 const ValueDecl *VD, bool CurrentRegionOnly, 572 const llvm::function_ref< 573 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 574 OpenMPClauseKind)> 575 Check) const { 576 if (isStackEmpty()) 577 return false; 578 auto SI = Stack.back().first.rbegin(); 579 auto SE = Stack.back().first.rend(); 580 581 if (SI == SE) 582 return false; 583 584 if (CurrentRegionOnly) 585 SE = std::next(SI); 586 else 587 std::advance(SI, 1); 588 589 for (; SI != SE; ++SI) { 590 auto MI = SI->MappedExprComponents.find(VD); 591 if (MI != SI->MappedExprComponents.end()) 592 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 593 MI->second.Components) 594 if (Check(L, MI->second.Kind)) 595 return true; 596 } 597 return false; 598 } 599 600 /// Do the check specified in \a Check to all component lists at a given level 601 /// and return true if any issue is found. 602 bool checkMappableExprComponentListsForDeclAtLevel( 603 const ValueDecl *VD, unsigned Level, 604 const llvm::function_ref< 605 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 606 OpenMPClauseKind)> 607 Check) const { 608 if (isStackEmpty()) 609 return false; 610 611 auto StartI = Stack.back().first.begin(); 612 auto EndI = Stack.back().first.end(); 613 if (std::distance(StartI, EndI) <= (int)Level) 614 return false; 615 std::advance(StartI, Level); 616 617 auto MI = StartI->MappedExprComponents.find(VD); 618 if (MI != StartI->MappedExprComponents.end()) 619 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 620 MI->second.Components) 621 if (Check(L, MI->second.Kind)) 622 return true; 623 return false; 624 } 625 626 /// Create a new mappable expression component list associated with a given 627 /// declaration and initialize it with the provided list of components. 628 void addMappableExpressionComponents( 629 const ValueDecl *VD, 630 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 631 OpenMPClauseKind WhereFoundClauseKind) { 632 assert(!isStackEmpty() && 633 "Not expecting to retrieve components from a empty stack!"); 634 MappedExprComponentTy &MEC = 635 Stack.back().first.back().MappedExprComponents[VD]; 636 // Create new entry and append the new components there. 637 MEC.Components.resize(MEC.Components.size() + 1); 638 MEC.Components.back().append(Components.begin(), Components.end()); 639 MEC.Kind = WhereFoundClauseKind; 640 } 641 642 unsigned getNestingLevel() const { 643 assert(!isStackEmpty()); 644 return Stack.back().first.size() - 1; 645 } 646 void addDoacrossDependClause(OMPDependClause *C, 647 const OperatorOffsetTy &OpsOffs) { 648 assert(!isStackEmpty() && Stack.back().first.size() > 1); 649 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin()); 650 assert(isOpenMPWorksharingDirective(StackElem.Directive)); 651 StackElem.DoacrossDepends.try_emplace(C, OpsOffs); 652 } 653 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 654 getDoacrossDependClauses() const { 655 assert(!isStackEmpty()); 656 const SharingMapTy &StackElem = Stack.back().first.back(); 657 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 658 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 659 return llvm::make_range(Ref.begin(), Ref.end()); 660 } 661 return llvm::make_range(StackElem.DoacrossDepends.end(), 662 StackElem.DoacrossDepends.end()); 663 } 664 665 // Store types of classes which have been explicitly mapped 666 void addMappedClassesQualTypes(QualType QT) { 667 SharingMapTy &StackElem = Stack.back().first.back(); 668 StackElem.MappedClassesQualTypes.insert(QT); 669 } 670 671 // Return set of mapped classes types 672 bool isClassPreviouslyMapped(QualType QT) const { 673 const SharingMapTy &StackElem = Stack.back().first.back(); 674 return StackElem.MappedClassesQualTypes.count(QT) != 0; 675 } 676 677 }; 678 679 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 680 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 681 } 682 683 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 684 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown; 685 } 686 687 } // namespace 688 689 static const Expr *getExprAsWritten(const Expr *E) { 690 if (const auto *FE = dyn_cast<FullExpr>(E)) 691 E = FE->getSubExpr(); 692 693 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 694 E = MTE->GetTemporaryExpr(); 695 696 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 697 E = Binder->getSubExpr(); 698 699 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 700 E = ICE->getSubExprAsWritten(); 701 return E->IgnoreParens(); 702 } 703 704 static Expr *getExprAsWritten(Expr *E) { 705 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 706 } 707 708 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 709 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 710 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 711 D = ME->getMemberDecl(); 712 const auto *VD = dyn_cast<VarDecl>(D); 713 const auto *FD = dyn_cast<FieldDecl>(D); 714 if (VD != nullptr) { 715 VD = VD->getCanonicalDecl(); 716 D = VD; 717 } else { 718 assert(FD); 719 FD = FD->getCanonicalDecl(); 720 D = FD; 721 } 722 return D; 723 } 724 725 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 726 return const_cast<ValueDecl *>( 727 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 728 } 729 730 DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter, 731 ValueDecl *D) const { 732 D = getCanonicalDecl(D); 733 auto *VD = dyn_cast<VarDecl>(D); 734 const auto *FD = dyn_cast<FieldDecl>(D); 735 DSAVarData DVar; 736 if (isStackEmpty() || Iter == Stack.back().first.rend()) { 737 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 738 // in a region but not in construct] 739 // File-scope or namespace-scope variables referenced in called routines 740 // in the region are shared unless they appear in a threadprivate 741 // directive. 742 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 743 DVar.CKind = OMPC_shared; 744 745 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 746 // in a region but not in construct] 747 // Variables with static storage duration that are declared in called 748 // routines in the region are shared. 749 if (VD && VD->hasGlobalStorage()) 750 DVar.CKind = OMPC_shared; 751 752 // Non-static data members are shared by default. 753 if (FD) 754 DVar.CKind = OMPC_shared; 755 756 return DVar; 757 } 758 759 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 760 // in a Construct, C/C++, predetermined, p.1] 761 // Variables with automatic storage duration that are declared in a scope 762 // inside the construct are private. 763 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 764 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 765 DVar.CKind = OMPC_private; 766 return DVar; 767 } 768 769 DVar.DKind = Iter->Directive; 770 // Explicitly specified attributes and local variables with predetermined 771 // attributes. 772 if (Iter->SharingMap.count(D)) { 773 const DSAInfo &Data = Iter->SharingMap.lookup(D); 774 DVar.RefExpr = Data.RefExpr.getPointer(); 775 DVar.PrivateCopy = Data.PrivateCopy; 776 DVar.CKind = Data.Attributes; 777 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 778 return DVar; 779 } 780 781 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 782 // in a Construct, C/C++, implicitly determined, p.1] 783 // In a parallel or task construct, the data-sharing attributes of these 784 // variables are determined by the default clause, if present. 785 switch (Iter->DefaultAttr) { 786 case DSA_shared: 787 DVar.CKind = OMPC_shared; 788 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 789 return DVar; 790 case DSA_none: 791 return DVar; 792 case DSA_unspecified: 793 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 794 // in a Construct, implicitly determined, p.2] 795 // In a parallel construct, if no default clause is present, these 796 // variables are shared. 797 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 798 if (isOpenMPParallelDirective(DVar.DKind) || 799 isOpenMPTeamsDirective(DVar.DKind)) { 800 DVar.CKind = OMPC_shared; 801 return DVar; 802 } 803 804 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 805 // in a Construct, implicitly determined, p.4] 806 // In a task construct, if no default clause is present, a variable that in 807 // the enclosing context is determined to be shared by all implicit tasks 808 // bound to the current team is shared. 809 if (isOpenMPTaskingDirective(DVar.DKind)) { 810 DSAVarData DVarTemp; 811 iterator I = Iter, E = Stack.back().first.rend(); 812 do { 813 ++I; 814 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 815 // Referenced in a Construct, implicitly determined, p.6] 816 // In a task construct, if no default clause is present, a variable 817 // whose data-sharing attribute is not determined by the rules above is 818 // firstprivate. 819 DVarTemp = getDSA(I, D); 820 if (DVarTemp.CKind != OMPC_shared) { 821 DVar.RefExpr = nullptr; 822 DVar.CKind = OMPC_firstprivate; 823 return DVar; 824 } 825 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 826 DVar.CKind = 827 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 828 return DVar; 829 } 830 } 831 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 832 // in a Construct, implicitly determined, p.3] 833 // For constructs other than task, if no default clause is present, these 834 // variables inherit their data-sharing attributes from the enclosing 835 // context. 836 return getDSA(++Iter, D); 837 } 838 839 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 840 const Expr *NewDE) { 841 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 842 D = getCanonicalDecl(D); 843 SharingMapTy &StackElem = Stack.back().first.back(); 844 auto It = StackElem.AlignedMap.find(D); 845 if (It == StackElem.AlignedMap.end()) { 846 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 847 StackElem.AlignedMap[D] = NewDE; 848 return nullptr; 849 } 850 assert(It->second && "Unexpected nullptr expr in the aligned map"); 851 return It->second; 852 } 853 854 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 855 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 856 D = getCanonicalDecl(D); 857 SharingMapTy &StackElem = Stack.back().first.back(); 858 StackElem.LCVMap.try_emplace( 859 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 860 } 861 862 const DSAStackTy::LCDeclInfo 863 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 864 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 865 D = getCanonicalDecl(D); 866 const SharingMapTy &StackElem = Stack.back().first.back(); 867 auto It = StackElem.LCVMap.find(D); 868 if (It != StackElem.LCVMap.end()) 869 return It->second; 870 return {0, nullptr}; 871 } 872 873 const DSAStackTy::LCDeclInfo 874 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 875 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 876 "Data-sharing attributes stack is empty"); 877 D = getCanonicalDecl(D); 878 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin()); 879 auto It = StackElem.LCVMap.find(D); 880 if (It != StackElem.LCVMap.end()) 881 return It->second; 882 return {0, nullptr}; 883 } 884 885 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 886 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 887 "Data-sharing attributes stack is empty"); 888 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin()); 889 if (StackElem.LCVMap.size() < I) 890 return nullptr; 891 for (const auto &Pair : StackElem.LCVMap) 892 if (Pair.second.first == I) 893 return Pair.first; 894 return nullptr; 895 } 896 897 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 898 DeclRefExpr *PrivateCopy) { 899 D = getCanonicalDecl(D); 900 if (A == OMPC_threadprivate) { 901 DSAInfo &Data = Threadprivates[D]; 902 Data.Attributes = A; 903 Data.RefExpr.setPointer(E); 904 Data.PrivateCopy = nullptr; 905 } else { 906 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 907 DSAInfo &Data = Stack.back().first.back().SharingMap[D]; 908 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 909 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 910 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 911 (isLoopControlVariable(D).first && A == OMPC_private)); 912 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 913 Data.RefExpr.setInt(/*IntVal=*/true); 914 return; 915 } 916 const bool IsLastprivate = 917 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 918 Data.Attributes = A; 919 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 920 Data.PrivateCopy = PrivateCopy; 921 if (PrivateCopy) { 922 DSAInfo &Data = 923 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()]; 924 Data.Attributes = A; 925 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 926 Data.PrivateCopy = nullptr; 927 } 928 } 929 } 930 931 /// Build a variable declaration for OpenMP loop iteration variable. 932 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 933 StringRef Name, const AttrVec *Attrs = nullptr, 934 DeclRefExpr *OrigRef = nullptr) { 935 DeclContext *DC = SemaRef.CurContext; 936 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 937 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 938 auto *Decl = 939 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 940 if (Attrs) { 941 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 942 I != E; ++I) 943 Decl->addAttr(*I); 944 } 945 Decl->setImplicit(); 946 if (OrigRef) { 947 Decl->addAttr( 948 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 949 } 950 return Decl; 951 } 952 953 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 954 SourceLocation Loc, 955 bool RefersToCapture = false) { 956 D->setReferenced(); 957 D->markUsed(S.Context); 958 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 959 SourceLocation(), D, RefersToCapture, Loc, Ty, 960 VK_LValue); 961 } 962 963 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 964 BinaryOperatorKind BOK) { 965 D = getCanonicalDecl(D); 966 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 967 assert( 968 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 969 "Additional reduction info may be specified only for reduction items."); 970 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D]; 971 assert(ReductionData.ReductionRange.isInvalid() && 972 Stack.back().first.back().Directive == OMPD_taskgroup && 973 "Additional reduction info may be specified only once for reduction " 974 "items."); 975 ReductionData.set(BOK, SR); 976 Expr *&TaskgroupReductionRef = 977 Stack.back().first.back().TaskgroupReductionRef; 978 if (!TaskgroupReductionRef) { 979 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 980 SemaRef.Context.VoidPtrTy, ".task_red."); 981 TaskgroupReductionRef = 982 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 983 } 984 } 985 986 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 987 const Expr *ReductionRef) { 988 D = getCanonicalDecl(D); 989 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 990 assert( 991 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 992 "Additional reduction info may be specified only for reduction items."); 993 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D]; 994 assert(ReductionData.ReductionRange.isInvalid() && 995 Stack.back().first.back().Directive == OMPD_taskgroup && 996 "Additional reduction info may be specified only once for reduction " 997 "items."); 998 ReductionData.set(ReductionRef, SR); 999 Expr *&TaskgroupReductionRef = 1000 Stack.back().first.back().TaskgroupReductionRef; 1001 if (!TaskgroupReductionRef) { 1002 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1003 SemaRef.Context.VoidPtrTy, ".task_red."); 1004 TaskgroupReductionRef = 1005 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1006 } 1007 } 1008 1009 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1010 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1011 Expr *&TaskgroupDescriptor) const { 1012 D = getCanonicalDecl(D); 1013 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1014 if (Stack.back().first.empty()) 1015 return DSAVarData(); 1016 for (iterator I = std::next(Stack.back().first.rbegin(), 1), 1017 E = Stack.back().first.rend(); 1018 I != E; std::advance(I, 1)) { 1019 const DSAInfo &Data = I->SharingMap.lookup(D); 1020 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 1021 continue; 1022 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1023 if (!ReductionData.ReductionOp || 1024 ReductionData.ReductionOp.is<const Expr *>()) 1025 return DSAVarData(); 1026 SR = ReductionData.ReductionRange; 1027 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1028 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1029 "expression for the descriptor is not " 1030 "set."); 1031 TaskgroupDescriptor = I->TaskgroupReductionRef; 1032 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 1033 Data.PrivateCopy, I->DefaultAttrLoc); 1034 } 1035 return DSAVarData(); 1036 } 1037 1038 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1039 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1040 Expr *&TaskgroupDescriptor) const { 1041 D = getCanonicalDecl(D); 1042 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1043 if (Stack.back().first.empty()) 1044 return DSAVarData(); 1045 for (iterator I = std::next(Stack.back().first.rbegin(), 1), 1046 E = Stack.back().first.rend(); 1047 I != E; std::advance(I, 1)) { 1048 const DSAInfo &Data = I->SharingMap.lookup(D); 1049 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 1050 continue; 1051 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1052 if (!ReductionData.ReductionOp || 1053 !ReductionData.ReductionOp.is<const Expr *>()) 1054 return DSAVarData(); 1055 SR = ReductionData.ReductionRange; 1056 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1057 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1058 "expression for the descriptor is not " 1059 "set."); 1060 TaskgroupDescriptor = I->TaskgroupReductionRef; 1061 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 1062 Data.PrivateCopy, I->DefaultAttrLoc); 1063 } 1064 return DSAVarData(); 1065 } 1066 1067 bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const { 1068 D = D->getCanonicalDecl(); 1069 if (!isStackEmpty()) { 1070 iterator I = Iter, E = Stack.back().first.rend(); 1071 Scope *TopScope = nullptr; 1072 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) && 1073 !isOpenMPTargetExecutionDirective(I->Directive)) 1074 ++I; 1075 if (I == E) 1076 return false; 1077 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 1078 Scope *CurScope = getCurScope(); 1079 while (CurScope != TopScope && !CurScope->isDeclScope(D)) 1080 CurScope = CurScope->getParent(); 1081 return CurScope != TopScope; 1082 } 1083 return false; 1084 } 1085 1086 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1087 bool AcceptIfMutable = true, 1088 bool *IsClassType = nullptr) { 1089 ASTContext &Context = SemaRef.getASTContext(); 1090 Type = Type.getNonReferenceType().getCanonicalType(); 1091 bool IsConstant = Type.isConstant(Context); 1092 Type = Context.getBaseElementType(Type); 1093 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1094 ? Type->getAsCXXRecordDecl() 1095 : nullptr; 1096 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1097 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1098 RD = CTD->getTemplatedDecl(); 1099 if (IsClassType) 1100 *IsClassType = RD; 1101 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1102 RD->hasDefinition() && RD->hasMutableFields()); 1103 } 1104 1105 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1106 QualType Type, OpenMPClauseKind CKind, 1107 SourceLocation ELoc, 1108 bool AcceptIfMutable = true, 1109 bool ListItemNotVar = false) { 1110 ASTContext &Context = SemaRef.getASTContext(); 1111 bool IsClassType; 1112 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1113 unsigned Diag = ListItemNotVar 1114 ? diag::err_omp_const_list_item 1115 : IsClassType ? diag::err_omp_const_not_mutable_variable 1116 : diag::err_omp_const_variable; 1117 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1118 if (!ListItemNotVar && D) { 1119 const VarDecl *VD = dyn_cast<VarDecl>(D); 1120 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1121 VarDecl::DeclarationOnly; 1122 SemaRef.Diag(D->getLocation(), 1123 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1124 << D; 1125 } 1126 return true; 1127 } 1128 return false; 1129 } 1130 1131 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1132 bool FromParent) { 1133 D = getCanonicalDecl(D); 1134 DSAVarData DVar; 1135 1136 auto *VD = dyn_cast<VarDecl>(D); 1137 auto TI = Threadprivates.find(D); 1138 if (TI != Threadprivates.end()) { 1139 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1140 DVar.CKind = OMPC_threadprivate; 1141 return DVar; 1142 } 1143 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1144 DVar.RefExpr = buildDeclRefExpr( 1145 SemaRef, VD, D->getType().getNonReferenceType(), 1146 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1147 DVar.CKind = OMPC_threadprivate; 1148 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1149 return DVar; 1150 } 1151 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1152 // in a Construct, C/C++, predetermined, p.1] 1153 // Variables appearing in threadprivate directives are threadprivate. 1154 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1155 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1156 SemaRef.getLangOpts().OpenMPUseTLS && 1157 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1158 (VD && VD->getStorageClass() == SC_Register && 1159 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1160 DVar.RefExpr = buildDeclRefExpr( 1161 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1162 DVar.CKind = OMPC_threadprivate; 1163 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1164 return DVar; 1165 } 1166 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1167 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1168 !isLoopControlVariable(D).first) { 1169 iterator IterTarget = 1170 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(), 1171 [](const SharingMapTy &Data) { 1172 return isOpenMPTargetExecutionDirective(Data.Directive); 1173 }); 1174 if (IterTarget != Stack.back().first.rend()) { 1175 iterator ParentIterTarget = std::next(IterTarget, 1); 1176 for (iterator Iter = Stack.back().first.rbegin(); 1177 Iter != ParentIterTarget; std::advance(Iter, 1)) { 1178 if (isOpenMPLocal(VD, Iter)) { 1179 DVar.RefExpr = 1180 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1181 D->getLocation()); 1182 DVar.CKind = OMPC_threadprivate; 1183 return DVar; 1184 } 1185 } 1186 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) { 1187 auto DSAIter = IterTarget->SharingMap.find(D); 1188 if (DSAIter != IterTarget->SharingMap.end() && 1189 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1190 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1191 DVar.CKind = OMPC_threadprivate; 1192 return DVar; 1193 } 1194 iterator End = Stack.back().first.rend(); 1195 if (!SemaRef.isOpenMPCapturedByRef( 1196 D, std::distance(ParentIterTarget, End))) { 1197 DVar.RefExpr = 1198 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1199 IterTarget->ConstructLoc); 1200 DVar.CKind = OMPC_threadprivate; 1201 return DVar; 1202 } 1203 } 1204 } 1205 } 1206 1207 if (isStackEmpty()) 1208 // Not in OpenMP execution region and top scope was already checked. 1209 return DVar; 1210 1211 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1212 // in a Construct, C/C++, predetermined, p.4] 1213 // Static data members are shared. 1214 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1215 // in a Construct, C/C++, predetermined, p.7] 1216 // Variables with static storage duration that are declared in a scope 1217 // inside the construct are shared. 1218 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1219 if (VD && VD->isStaticDataMember()) { 1220 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 1221 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1222 return DVar; 1223 1224 DVar.CKind = OMPC_shared; 1225 return DVar; 1226 } 1227 1228 // The predetermined shared attribute for const-qualified types having no 1229 // mutable members was removed after OpenMP 3.1. 1230 if (SemaRef.LangOpts.OpenMP <= 31) { 1231 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1232 // in a Construct, C/C++, predetermined, p.6] 1233 // Variables with const qualified type having no mutable member are 1234 // shared. 1235 if (isConstNotMutableType(SemaRef, D->getType())) { 1236 // Variables with const-qualified type having no mutable member may be 1237 // listed in a firstprivate clause, even if they are static data members. 1238 DSAVarData DVarTemp = hasInnermostDSA( 1239 D, 1240 [](OpenMPClauseKind C) { 1241 return C == OMPC_firstprivate || C == OMPC_shared; 1242 }, 1243 MatchesAlways, FromParent); 1244 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1245 return DVarTemp; 1246 1247 DVar.CKind = OMPC_shared; 1248 return DVar; 1249 } 1250 } 1251 1252 // Explicitly specified attributes and local variables with predetermined 1253 // attributes. 1254 iterator I = Stack.back().first.rbegin(); 1255 iterator EndI = Stack.back().first.rend(); 1256 if (FromParent && I != EndI) 1257 std::advance(I, 1); 1258 auto It = I->SharingMap.find(D); 1259 if (It != I->SharingMap.end()) { 1260 const DSAInfo &Data = It->getSecond(); 1261 DVar.RefExpr = Data.RefExpr.getPointer(); 1262 DVar.PrivateCopy = Data.PrivateCopy; 1263 DVar.CKind = Data.Attributes; 1264 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1265 DVar.DKind = I->Directive; 1266 } 1267 1268 return DVar; 1269 } 1270 1271 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1272 bool FromParent) const { 1273 if (isStackEmpty()) { 1274 iterator I; 1275 return getDSA(I, D); 1276 } 1277 D = getCanonicalDecl(D); 1278 iterator StartI = Stack.back().first.rbegin(); 1279 iterator EndI = Stack.back().first.rend(); 1280 if (FromParent && StartI != EndI) 1281 std::advance(StartI, 1); 1282 return getDSA(StartI, D); 1283 } 1284 1285 const DSAStackTy::DSAVarData 1286 DSAStackTy::hasDSA(ValueDecl *D, 1287 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1288 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1289 bool FromParent) const { 1290 if (isStackEmpty()) 1291 return {}; 1292 D = getCanonicalDecl(D); 1293 iterator I = Stack.back().first.rbegin(); 1294 iterator EndI = Stack.back().first.rend(); 1295 if (FromParent && I != EndI) 1296 std::advance(I, 1); 1297 for (; I != EndI; std::advance(I, 1)) { 1298 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive)) 1299 continue; 1300 iterator NewI = I; 1301 DSAVarData DVar = getDSA(NewI, D); 1302 if (I == NewI && CPred(DVar.CKind)) 1303 return DVar; 1304 } 1305 return {}; 1306 } 1307 1308 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1309 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1310 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1311 bool FromParent) const { 1312 if (isStackEmpty()) 1313 return {}; 1314 D = getCanonicalDecl(D); 1315 iterator StartI = Stack.back().first.rbegin(); 1316 iterator EndI = Stack.back().first.rend(); 1317 if (FromParent && StartI != EndI) 1318 std::advance(StartI, 1); 1319 if (StartI == EndI || !DPred(StartI->Directive)) 1320 return {}; 1321 iterator NewI = StartI; 1322 DSAVarData DVar = getDSA(NewI, D); 1323 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); 1324 } 1325 1326 bool DSAStackTy::hasExplicitDSA( 1327 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1328 unsigned Level, bool NotLastprivate) const { 1329 if (isStackEmpty()) 1330 return false; 1331 D = getCanonicalDecl(D); 1332 auto StartI = Stack.back().first.begin(); 1333 auto EndI = Stack.back().first.end(); 1334 if (std::distance(StartI, EndI) <= (int)Level) 1335 return false; 1336 std::advance(StartI, Level); 1337 auto I = StartI->SharingMap.find(D); 1338 if ((I != StartI->SharingMap.end()) && 1339 I->getSecond().RefExpr.getPointer() && 1340 CPred(I->getSecond().Attributes) && 1341 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1342 return true; 1343 // Check predetermined rules for the loop control variables. 1344 auto LI = StartI->LCVMap.find(D); 1345 if (LI != StartI->LCVMap.end()) 1346 return CPred(OMPC_private); 1347 return false; 1348 } 1349 1350 bool DSAStackTy::hasExplicitDirective( 1351 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1352 unsigned Level) const { 1353 if (isStackEmpty()) 1354 return false; 1355 auto StartI = Stack.back().first.begin(); 1356 auto EndI = Stack.back().first.end(); 1357 if (std::distance(StartI, EndI) <= (int)Level) 1358 return false; 1359 std::advance(StartI, Level); 1360 return DPred(StartI->Directive); 1361 } 1362 1363 bool DSAStackTy::hasDirective( 1364 const llvm::function_ref<bool(OpenMPDirectiveKind, 1365 const DeclarationNameInfo &, SourceLocation)> 1366 DPred, 1367 bool FromParent) const { 1368 // We look only in the enclosing region. 1369 if (isStackEmpty()) 1370 return false; 1371 auto StartI = std::next(Stack.back().first.rbegin()); 1372 auto EndI = Stack.back().first.rend(); 1373 if (FromParent && StartI != EndI) 1374 StartI = std::next(StartI); 1375 for (auto I = StartI, EE = EndI; I != EE; ++I) { 1376 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1377 return true; 1378 } 1379 return false; 1380 } 1381 1382 void Sema::InitDataSharingAttributesStack() { 1383 VarDataSharingAttributesStack = new DSAStackTy(*this); 1384 } 1385 1386 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1387 1388 void Sema::pushOpenMPFunctionRegion() { 1389 DSAStack->pushFunction(); 1390 } 1391 1392 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1393 DSAStack->popFunction(OldFSI); 1394 } 1395 1396 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1397 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1398 "Expected OpenMP device compilation."); 1399 return !S.isInOpenMPTargetExecutionDirective() && 1400 !S.isInOpenMPDeclareTargetContext(); 1401 } 1402 1403 /// Do we know that we will eventually codegen the given function? 1404 static bool isKnownEmitted(Sema &S, FunctionDecl *FD) { 1405 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1406 "Expected OpenMP device compilation."); 1407 // Templates are emitted when they're instantiated. 1408 if (FD->isDependentContext()) 1409 return false; 1410 1411 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 1412 FD->getCanonicalDecl())) 1413 return true; 1414 1415 // Otherwise, the function is known-emitted if it's in our set of 1416 // known-emitted functions. 1417 return S.DeviceKnownEmittedFns.count(FD) > 0; 1418 } 1419 1420 Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1421 unsigned DiagID) { 1422 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1423 "Expected OpenMP device compilation."); 1424 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) && 1425 !isKnownEmitted(*this, getCurFunctionDecl())) 1426 ? DeviceDiagBuilder::K_Deferred 1427 : DeviceDiagBuilder::K_Immediate, 1428 Loc, DiagID, getCurFunctionDecl(), *this); 1429 } 1430 1431 void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) { 1432 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1433 "Expected OpenMP device compilation."); 1434 assert(Callee && "Callee may not be null."); 1435 FunctionDecl *Caller = getCurFunctionDecl(); 1436 1437 // If the caller is known-emitted, mark the callee as known-emitted. 1438 // Otherwise, mark the call in our call graph so we can traverse it later. 1439 if (!isOpenMPDeviceDelayedContext(*this) || 1440 (Caller && isKnownEmitted(*this, Caller))) 1441 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted); 1442 else if (Caller) 1443 DeviceCallGraph[Caller].insert({Callee, Loc}); 1444 } 1445 1446 void Sema::checkOpenMPDeviceExpr(const Expr *E) { 1447 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 1448 "OpenMP device compilation mode is expected."); 1449 QualType Ty = E->getType(); 1450 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) || 1451 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) || 1452 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 && 1453 !Context.getTargetInfo().hasInt128Type())) 1454 targetDiag(E->getExprLoc(), diag::err_type_unsupported) 1455 << Ty << E->getSourceRange(); 1456 } 1457 1458 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const { 1459 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1460 1461 ASTContext &Ctx = getASTContext(); 1462 bool IsByRef = true; 1463 1464 // Find the directive that is associated with the provided scope. 1465 D = cast<ValueDecl>(D->getCanonicalDecl()); 1466 QualType Ty = D->getType(); 1467 1468 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1469 // This table summarizes how a given variable should be passed to the device 1470 // given its type and the clauses where it appears. This table is based on 1471 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1472 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1473 // 1474 // ========================================================================= 1475 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1476 // | |(tofrom:scalar)| | pvt | | | | 1477 // ========================================================================= 1478 // | scl | | | | - | | bycopy| 1479 // | scl | | - | x | - | - | bycopy| 1480 // | scl | | x | - | - | - | null | 1481 // | scl | x | | | - | | byref | 1482 // | scl | x | - | x | - | - | bycopy| 1483 // | scl | x | x | - | - | - | null | 1484 // | scl | | - | - | - | x | byref | 1485 // | scl | x | - | - | - | x | byref | 1486 // 1487 // | agg | n.a. | | | - | | byref | 1488 // | agg | n.a. | - | x | - | - | byref | 1489 // | agg | n.a. | x | - | - | - | null | 1490 // | agg | n.a. | - | - | - | x | byref | 1491 // | agg | n.a. | - | - | - | x[] | byref | 1492 // 1493 // | ptr | n.a. | | | - | | bycopy| 1494 // | ptr | n.a. | - | x | - | - | bycopy| 1495 // | ptr | n.a. | x | - | - | - | null | 1496 // | ptr | n.a. | - | - | - | x | byref | 1497 // | ptr | n.a. | - | - | - | x[] | bycopy| 1498 // | ptr | n.a. | - | - | x | | bycopy| 1499 // | ptr | n.a. | - | - | x | x | bycopy| 1500 // | ptr | n.a. | - | - | x | x[] | bycopy| 1501 // ========================================================================= 1502 // Legend: 1503 // scl - scalar 1504 // ptr - pointer 1505 // agg - aggregate 1506 // x - applies 1507 // - - invalid in this combination 1508 // [] - mapped with an array section 1509 // byref - should be mapped by reference 1510 // byval - should be mapped by value 1511 // null - initialize a local variable to null on the device 1512 // 1513 // Observations: 1514 // - All scalar declarations that show up in a map clause have to be passed 1515 // by reference, because they may have been mapped in the enclosing data 1516 // environment. 1517 // - If the scalar value does not fit the size of uintptr, it has to be 1518 // passed by reference, regardless the result in the table above. 1519 // - For pointers mapped by value that have either an implicit map or an 1520 // array section, the runtime library may pass the NULL value to the 1521 // device instead of the value passed to it by the compiler. 1522 1523 if (Ty->isReferenceType()) 1524 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1525 1526 // Locate map clauses and see if the variable being captured is referred to 1527 // in any of those clauses. Here we only care about variables, not fields, 1528 // because fields are part of aggregates. 1529 bool IsVariableUsedInMapClause = false; 1530 bool IsVariableAssociatedWithSection = false; 1531 1532 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1533 D, Level, 1534 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D]( 1535 OMPClauseMappableExprCommon::MappableExprComponentListRef 1536 MapExprComponents, 1537 OpenMPClauseKind WhereFoundClauseKind) { 1538 // Only the map clause information influences how a variable is 1539 // captured. E.g. is_device_ptr does not require changing the default 1540 // behavior. 1541 if (WhereFoundClauseKind != OMPC_map) 1542 return false; 1543 1544 auto EI = MapExprComponents.rbegin(); 1545 auto EE = MapExprComponents.rend(); 1546 1547 assert(EI != EE && "Invalid map expression!"); 1548 1549 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1550 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1551 1552 ++EI; 1553 if (EI == EE) 1554 return false; 1555 1556 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1557 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1558 isa<MemberExpr>(EI->getAssociatedExpression())) { 1559 IsVariableAssociatedWithSection = true; 1560 // There is nothing more we need to know about this variable. 1561 return true; 1562 } 1563 1564 // Keep looking for more map info. 1565 return false; 1566 }); 1567 1568 if (IsVariableUsedInMapClause) { 1569 // If variable is identified in a map clause it is always captured by 1570 // reference except if it is a pointer that is dereferenced somehow. 1571 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1572 } else { 1573 // By default, all the data that has a scalar type is mapped by copy 1574 // (except for reduction variables). 1575 IsByRef = 1576 (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 1577 !Ty->isAnyPointerType()) || 1578 !Ty->isScalarType() || 1579 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar || 1580 DSAStack->hasExplicitDSA( 1581 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level); 1582 } 1583 } 1584 1585 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1586 IsByRef = 1587 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() && 1588 !Ty->isAnyPointerType()) || 1589 !DSAStack->hasExplicitDSA( 1590 D, 1591 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1592 Level, /*NotLastprivate=*/true)) && 1593 // If the variable is artificial and must be captured by value - try to 1594 // capture by value. 1595 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 1596 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()); 1597 } 1598 1599 // When passing data by copy, we need to make sure it fits the uintptr size 1600 // and alignment, because the runtime library only deals with uintptr types. 1601 // If it does not fit the uintptr size, we need to pass the data by reference 1602 // instead. 1603 if (!IsByRef && 1604 (Ctx.getTypeSizeInChars(Ty) > 1605 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1606 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1607 IsByRef = true; 1608 } 1609 1610 return IsByRef; 1611 } 1612 1613 unsigned Sema::getOpenMPNestingLevel() const { 1614 assert(getLangOpts().OpenMP); 1615 return DSAStack->getNestingLevel(); 1616 } 1617 1618 bool Sema::isInOpenMPTargetExecutionDirective() const { 1619 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 1620 !DSAStack->isClauseParsingMode()) || 1621 DSAStack->hasDirective( 1622 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1623 SourceLocation) -> bool { 1624 return isOpenMPTargetExecutionDirective(K); 1625 }, 1626 false); 1627 } 1628 1629 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) { 1630 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1631 D = getCanonicalDecl(D); 1632 1633 // If we are attempting to capture a global variable in a directive with 1634 // 'target' we return true so that this global is also mapped to the device. 1635 // 1636 auto *VD = dyn_cast<VarDecl>(D); 1637 if (VD && !VD->hasLocalStorage()) { 1638 if (isInOpenMPDeclareTargetContext() && 1639 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 1640 // Try to mark variable as declare target if it is used in capturing 1641 // regions. 1642 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 1643 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 1644 return nullptr; 1645 } else if (isInOpenMPTargetExecutionDirective()) { 1646 // If the declaration is enclosed in a 'declare target' directive, 1647 // then it should not be captured. 1648 // 1649 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 1650 return nullptr; 1651 return VD; 1652 } 1653 } 1654 // Capture variables captured by reference in lambdas for target-based 1655 // directives. 1656 if (VD && !DSAStack->isClauseParsingMode()) { 1657 if (const auto *RD = VD->getType() 1658 .getCanonicalType() 1659 .getNonReferenceType() 1660 ->getAsCXXRecordDecl()) { 1661 bool SavedForceCaptureByReferenceInTargetExecutable = 1662 DSAStack->isForceCaptureByReferenceInTargetExecutable(); 1663 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true); 1664 if (RD->isLambda()) { 1665 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 1666 FieldDecl *ThisCapture; 1667 RD->getCaptureFields(Captures, ThisCapture); 1668 for (const LambdaCapture &LC : RD->captures()) { 1669 if (LC.getCaptureKind() == LCK_ByRef) { 1670 VarDecl *VD = LC.getCapturedVar(); 1671 DeclContext *VDC = VD->getDeclContext(); 1672 if (!VDC->Encloses(CurContext)) 1673 continue; 1674 DSAStackTy::DSAVarData DVarPrivate = 1675 DSAStack->getTopDSA(VD, /*FromParent=*/false); 1676 // Do not capture already captured variables. 1677 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) && 1678 DVarPrivate.CKind == OMPC_unknown && 1679 !DSAStack->checkMappableExprComponentListsForDecl( 1680 D, /*CurrentRegionOnly=*/true, 1681 [](OMPClauseMappableExprCommon:: 1682 MappableExprComponentListRef, 1683 OpenMPClauseKind) { return true; })) 1684 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar()); 1685 } else if (LC.getCaptureKind() == LCK_This) { 1686 QualType ThisTy = getCurrentThisType(); 1687 if (!ThisTy.isNull() && 1688 Context.typesAreCompatible(ThisTy, ThisCapture->getType())) 1689 CheckCXXThisCapture(LC.getLocation()); 1690 } 1691 } 1692 } 1693 DSAStack->setForceCaptureByReferenceInTargetExecutable( 1694 SavedForceCaptureByReferenceInTargetExecutable); 1695 } 1696 } 1697 1698 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1699 (!DSAStack->isClauseParsingMode() || 1700 DSAStack->getParentDirective() != OMPD_unknown)) { 1701 auto &&Info = DSAStack->isLoopControlVariable(D); 1702 if (Info.first || 1703 (VD && VD->hasLocalStorage() && 1704 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 1705 (VD && DSAStack->isForceVarCapturing())) 1706 return VD ? VD : Info.second; 1707 DSAStackTy::DSAVarData DVarPrivate = 1708 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1709 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1710 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1711 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate, 1712 [](OpenMPDirectiveKind) { return true; }, 1713 DSAStack->isClauseParsingMode()); 1714 if (DVarPrivate.CKind != OMPC_unknown) 1715 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1716 } 1717 return nullptr; 1718 } 1719 1720 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 1721 unsigned Level) const { 1722 SmallVector<OpenMPDirectiveKind, 4> Regions; 1723 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 1724 FunctionScopesIndex -= Regions.size(); 1725 } 1726 1727 void Sema::startOpenMPLoop() { 1728 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 1729 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 1730 DSAStack->loopInit(); 1731 } 1732 1733 bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const { 1734 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1735 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 1736 if (DSAStack->getAssociatedLoops() > 0 && 1737 !DSAStack->isLoopStarted()) { 1738 DSAStack->resetPossibleLoopCounter(D); 1739 DSAStack->loopStart(); 1740 return true; 1741 } 1742 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 1743 DSAStack->isLoopControlVariable(D).first) && 1744 !DSAStack->hasExplicitDSA( 1745 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) && 1746 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 1747 return true; 1748 } 1749 return DSAStack->hasExplicitDSA( 1750 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) || 1751 (DSAStack->isClauseParsingMode() && 1752 DSAStack->getClauseParsingMode() == OMPC_private) || 1753 // Consider taskgroup reduction descriptor variable a private to avoid 1754 // possible capture in the region. 1755 (DSAStack->hasExplicitDirective( 1756 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; }, 1757 Level) && 1758 DSAStack->isTaskgroupReductionRef(D, Level)); 1759 } 1760 1761 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 1762 unsigned Level) { 1763 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1764 D = getCanonicalDecl(D); 1765 OpenMPClauseKind OMPC = OMPC_unknown; 1766 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 1767 const unsigned NewLevel = I - 1; 1768 if (DSAStack->hasExplicitDSA(D, 1769 [&OMPC](const OpenMPClauseKind K) { 1770 if (isOpenMPPrivate(K)) { 1771 OMPC = K; 1772 return true; 1773 } 1774 return false; 1775 }, 1776 NewLevel)) 1777 break; 1778 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1779 D, NewLevel, 1780 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 1781 OpenMPClauseKind) { return true; })) { 1782 OMPC = OMPC_map; 1783 break; 1784 } 1785 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1786 NewLevel)) { 1787 OMPC = OMPC_map; 1788 if (D->getType()->isScalarType() && 1789 DSAStack->getDefaultDMAAtLevel(NewLevel) != 1790 DefaultMapAttributes::DMA_tofrom_scalar) 1791 OMPC = OMPC_firstprivate; 1792 break; 1793 } 1794 } 1795 if (OMPC != OMPC_unknown) 1796 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC)); 1797 } 1798 1799 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, 1800 unsigned Level) const { 1801 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1802 // Return true if the current level is no longer enclosed in a target region. 1803 1804 const auto *VD = dyn_cast<VarDecl>(D); 1805 return VD && !VD->hasLocalStorage() && 1806 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1807 Level); 1808 } 1809 1810 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1811 1812 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1813 const DeclarationNameInfo &DirName, 1814 Scope *CurScope, SourceLocation Loc) { 1815 DSAStack->push(DKind, DirName, CurScope, Loc); 1816 PushExpressionEvaluationContext( 1817 ExpressionEvaluationContext::PotentiallyEvaluated); 1818 } 1819 1820 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1821 DSAStack->setClauseParsingMode(K); 1822 } 1823 1824 void Sema::EndOpenMPClause() { 1825 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1826 } 1827 1828 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1829 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1830 // A variable of class type (or array thereof) that appears in a lastprivate 1831 // clause requires an accessible, unambiguous default constructor for the 1832 // class type, unless the list item is also specified in a firstprivate 1833 // clause. 1834 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1835 for (OMPClause *C : D->clauses()) { 1836 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1837 SmallVector<Expr *, 8> PrivateCopies; 1838 for (Expr *DE : Clause->varlists()) { 1839 if (DE->isValueDependent() || DE->isTypeDependent()) { 1840 PrivateCopies.push_back(nullptr); 1841 continue; 1842 } 1843 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1844 auto *VD = cast<VarDecl>(DRE->getDecl()); 1845 QualType Type = VD->getType().getNonReferenceType(); 1846 const DSAStackTy::DSAVarData DVar = 1847 DSAStack->getTopDSA(VD, /*FromParent=*/false); 1848 if (DVar.CKind == OMPC_lastprivate) { 1849 // Generate helper private variable and initialize it with the 1850 // default value. The address of the original variable is replaced 1851 // by the address of the new private variable in CodeGen. This new 1852 // variable is not added to IdResolver, so the code in the OpenMP 1853 // region uses original variable for proper diagnostics. 1854 VarDecl *VDPrivate = buildVarDecl( 1855 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1856 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 1857 ActOnUninitializedDecl(VDPrivate); 1858 if (VDPrivate->isInvalidDecl()) 1859 continue; 1860 PrivateCopies.push_back(buildDeclRefExpr( 1861 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1862 } else { 1863 // The variable is also a firstprivate, so initialization sequence 1864 // for private copy is generated already. 1865 PrivateCopies.push_back(nullptr); 1866 } 1867 } 1868 // Set initializers to private copies if no errors were found. 1869 if (PrivateCopies.size() == Clause->varlist_size()) 1870 Clause->setPrivateCopies(PrivateCopies); 1871 } 1872 } 1873 } 1874 1875 DSAStack->pop(); 1876 DiscardCleanupsInEvaluationContext(); 1877 PopExpressionEvaluationContext(); 1878 } 1879 1880 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1881 Expr *NumIterations, Sema &SemaRef, 1882 Scope *S, DSAStackTy *Stack); 1883 1884 namespace { 1885 1886 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 1887 private: 1888 Sema &SemaRef; 1889 1890 public: 1891 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1892 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1893 NamedDecl *ND = Candidate.getCorrectionDecl(); 1894 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1895 return VD->hasGlobalStorage() && 1896 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1897 SemaRef.getCurScope()); 1898 } 1899 return false; 1900 } 1901 }; 1902 1903 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 1904 private: 1905 Sema &SemaRef; 1906 1907 public: 1908 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1909 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1910 NamedDecl *ND = Candidate.getCorrectionDecl(); 1911 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) || 1912 isa<FunctionDecl>(ND))) { 1913 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1914 SemaRef.getCurScope()); 1915 } 1916 return false; 1917 } 1918 }; 1919 1920 } // namespace 1921 1922 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1923 CXXScopeSpec &ScopeSpec, 1924 const DeclarationNameInfo &Id, 1925 OpenMPDirectiveKind Kind) { 1926 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1927 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1928 1929 if (Lookup.isAmbiguous()) 1930 return ExprError(); 1931 1932 VarDecl *VD; 1933 if (!Lookup.isSingleResult()) { 1934 if (TypoCorrection Corrected = CorrectTypo( 1935 Id, LookupOrdinaryName, CurScope, nullptr, 1936 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1937 diagnoseTypo(Corrected, 1938 PDiag(Lookup.empty() 1939 ? diag::err_undeclared_var_use_suggest 1940 : diag::err_omp_expected_var_arg_suggest) 1941 << Id.getName()); 1942 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1943 } else { 1944 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1945 : diag::err_omp_expected_var_arg) 1946 << Id.getName(); 1947 return ExprError(); 1948 } 1949 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1950 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1951 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1952 return ExprError(); 1953 } 1954 Lookup.suppressDiagnostics(); 1955 1956 // OpenMP [2.9.2, Syntax, C/C++] 1957 // Variables must be file-scope, namespace-scope, or static block-scope. 1958 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) { 1959 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1960 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal(); 1961 bool IsDecl = 1962 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1963 Diag(VD->getLocation(), 1964 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1965 << VD; 1966 return ExprError(); 1967 } 1968 1969 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1970 NamedDecl *ND = CanonicalVD; 1971 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1972 // A threadprivate directive for file-scope variables must appear outside 1973 // any definition or declaration. 1974 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1975 !getCurLexicalContext()->isTranslationUnit()) { 1976 Diag(Id.getLoc(), diag::err_omp_var_scope) 1977 << getOpenMPDirectiveName(Kind) << VD; 1978 bool IsDecl = 1979 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1980 Diag(VD->getLocation(), 1981 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1982 << VD; 1983 return ExprError(); 1984 } 1985 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1986 // A threadprivate directive for static class member variables must appear 1987 // in the class definition, in the same scope in which the member 1988 // variables are declared. 1989 if (CanonicalVD->isStaticDataMember() && 1990 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1991 Diag(Id.getLoc(), diag::err_omp_var_scope) 1992 << getOpenMPDirectiveName(Kind) << VD; 1993 bool IsDecl = 1994 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1995 Diag(VD->getLocation(), 1996 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1997 << VD; 1998 return ExprError(); 1999 } 2000 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 2001 // A threadprivate directive for namespace-scope variables must appear 2002 // outside any definition or declaration other than the namespace 2003 // definition itself. 2004 if (CanonicalVD->getDeclContext()->isNamespace() && 2005 (!getCurLexicalContext()->isFileContext() || 2006 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 2007 Diag(Id.getLoc(), diag::err_omp_var_scope) 2008 << getOpenMPDirectiveName(Kind) << VD; 2009 bool IsDecl = 2010 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2011 Diag(VD->getLocation(), 2012 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2013 << VD; 2014 return ExprError(); 2015 } 2016 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2017 // A threadprivate directive for static block-scope variables must appear 2018 // in the scope of the variable and not in a nested scope. 2019 if (CanonicalVD->isLocalVarDecl() && CurScope && 2020 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2021 Diag(Id.getLoc(), diag::err_omp_var_scope) 2022 << getOpenMPDirectiveName(Kind) << VD; 2023 bool IsDecl = 2024 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2025 Diag(VD->getLocation(), 2026 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2027 << VD; 2028 return ExprError(); 2029 } 2030 2031 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2032 // A threadprivate directive must lexically precede all references to any 2033 // of the variables in its list. 2034 if (Kind == OMPD_threadprivate && VD->isUsed() && 2035 !DSAStack->isThreadPrivate(VD)) { 2036 Diag(Id.getLoc(), diag::err_omp_var_used) 2037 << getOpenMPDirectiveName(Kind) << VD; 2038 return ExprError(); 2039 } 2040 2041 QualType ExprType = VD->getType().getNonReferenceType(); 2042 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2043 SourceLocation(), VD, 2044 /*RefersToEnclosingVariableOrCapture=*/false, 2045 Id.getLoc(), ExprType, VK_LValue); 2046 } 2047 2048 Sema::DeclGroupPtrTy 2049 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2050 ArrayRef<Expr *> VarList) { 2051 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2052 CurContext->addDecl(D); 2053 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2054 } 2055 return nullptr; 2056 } 2057 2058 namespace { 2059 class LocalVarRefChecker final 2060 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2061 Sema &SemaRef; 2062 2063 public: 2064 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2065 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2066 if (VD->hasLocalStorage()) { 2067 SemaRef.Diag(E->getBeginLoc(), 2068 diag::err_omp_local_var_in_threadprivate_init) 2069 << E->getSourceRange(); 2070 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2071 << VD << VD->getSourceRange(); 2072 return true; 2073 } 2074 } 2075 return false; 2076 } 2077 bool VisitStmt(const Stmt *S) { 2078 for (const Stmt *Child : S->children()) { 2079 if (Child && Visit(Child)) 2080 return true; 2081 } 2082 return false; 2083 } 2084 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2085 }; 2086 } // namespace 2087 2088 OMPThreadPrivateDecl * 2089 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2090 SmallVector<Expr *, 8> Vars; 2091 for (Expr *RefExpr : VarList) { 2092 auto *DE = cast<DeclRefExpr>(RefExpr); 2093 auto *VD = cast<VarDecl>(DE->getDecl()); 2094 SourceLocation ILoc = DE->getExprLoc(); 2095 2096 // Mark variable as used. 2097 VD->setReferenced(); 2098 VD->markUsed(Context); 2099 2100 QualType QType = VD->getType(); 2101 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 2102 // It will be analyzed later. 2103 Vars.push_back(DE); 2104 continue; 2105 } 2106 2107 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2108 // A threadprivate variable must not have an incomplete type. 2109 if (RequireCompleteType(ILoc, VD->getType(), 2110 diag::err_omp_threadprivate_incomplete_type)) { 2111 continue; 2112 } 2113 2114 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2115 // A threadprivate variable must not have a reference type. 2116 if (VD->getType()->isReferenceType()) { 2117 Diag(ILoc, diag::err_omp_ref_type_arg) 2118 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 2119 bool IsDecl = 2120 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2121 Diag(VD->getLocation(), 2122 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2123 << VD; 2124 continue; 2125 } 2126 2127 // Check if this is a TLS variable. If TLS is not being supported, produce 2128 // the corresponding diagnostic. 2129 if ((VD->getTLSKind() != VarDecl::TLS_None && 2130 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 2131 getLangOpts().OpenMPUseTLS && 2132 getASTContext().getTargetInfo().isTLSSupported())) || 2133 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 2134 !VD->isLocalVarDecl())) { 2135 Diag(ILoc, diag::err_omp_var_thread_local) 2136 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 2137 bool IsDecl = 2138 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2139 Diag(VD->getLocation(), 2140 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2141 << VD; 2142 continue; 2143 } 2144 2145 // Check if initial value of threadprivate variable reference variable with 2146 // local storage (it is not supported by runtime). 2147 if (const Expr *Init = VD->getAnyInitializer()) { 2148 LocalVarRefChecker Checker(*this); 2149 if (Checker.Visit(Init)) 2150 continue; 2151 } 2152 2153 Vars.push_back(RefExpr); 2154 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 2155 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 2156 Context, SourceRange(Loc, Loc))); 2157 if (ASTMutationListener *ML = Context.getASTMutationListener()) 2158 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 2159 } 2160 OMPThreadPrivateDecl *D = nullptr; 2161 if (!Vars.empty()) { 2162 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 2163 Vars); 2164 D->setAccess(AS_public); 2165 } 2166 return D; 2167 } 2168 2169 Sema::DeclGroupPtrTy 2170 Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, 2171 DeclContext *Owner) { 2172 SmallVector<Expr *, 8> Vars; 2173 for (Expr *RefExpr : VarList) { 2174 auto *DE = cast<DeclRefExpr>(RefExpr); 2175 auto *VD = cast<VarDecl>(DE->getDecl()); 2176 2177 // Check if this is a TLS variable or global register. 2178 if (VD->getTLSKind() != VarDecl::TLS_None || 2179 VD->hasAttr<OMPThreadPrivateDeclAttr>() || 2180 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 2181 !VD->isLocalVarDecl())) 2182 continue; 2183 // Do not apply for parameters. 2184 if (isa<ParmVarDecl>(VD)) 2185 continue; 2186 2187 Vars.push_back(RefExpr); 2188 VD->addAttr( 2189 OMPAllocateDeclAttr::CreateImplicit(Context, DE->getSourceRange())); 2190 if (ASTMutationListener *ML = Context.getASTMutationListener()) 2191 ML->DeclarationMarkedOpenMPAllocate(VD, 2192 VD->getAttr<OMPAllocateDeclAttr>()); 2193 } 2194 if (Vars.empty()) 2195 return nullptr; 2196 if (!Owner) 2197 Owner = getCurLexicalContext(); 2198 OMPAllocateDecl *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars); 2199 D->setAccess(AS_public); 2200 Owner->addDecl(D); 2201 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2202 } 2203 2204 Sema::DeclGroupPtrTy 2205 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 2206 ArrayRef<OMPClause *> ClauseList) { 2207 OMPRequiresDecl *D = nullptr; 2208 if (!CurContext->isFileContext()) { 2209 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 2210 } else { 2211 D = CheckOMPRequiresDecl(Loc, ClauseList); 2212 if (D) { 2213 CurContext->addDecl(D); 2214 DSAStack->addRequiresDecl(D); 2215 } 2216 } 2217 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2218 } 2219 2220 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 2221 ArrayRef<OMPClause *> ClauseList) { 2222 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 2223 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 2224 ClauseList); 2225 return nullptr; 2226 } 2227 2228 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 2229 const ValueDecl *D, 2230 const DSAStackTy::DSAVarData &DVar, 2231 bool IsLoopIterVar = false) { 2232 if (DVar.RefExpr) { 2233 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 2234 << getOpenMPClauseName(DVar.CKind); 2235 return; 2236 } 2237 enum { 2238 PDSA_StaticMemberShared, 2239 PDSA_StaticLocalVarShared, 2240 PDSA_LoopIterVarPrivate, 2241 PDSA_LoopIterVarLinear, 2242 PDSA_LoopIterVarLastprivate, 2243 PDSA_ConstVarShared, 2244 PDSA_GlobalVarShared, 2245 PDSA_TaskVarFirstprivate, 2246 PDSA_LocalVarPrivate, 2247 PDSA_Implicit 2248 } Reason = PDSA_Implicit; 2249 bool ReportHint = false; 2250 auto ReportLoc = D->getLocation(); 2251 auto *VD = dyn_cast<VarDecl>(D); 2252 if (IsLoopIterVar) { 2253 if (DVar.CKind == OMPC_private) 2254 Reason = PDSA_LoopIterVarPrivate; 2255 else if (DVar.CKind == OMPC_lastprivate) 2256 Reason = PDSA_LoopIterVarLastprivate; 2257 else 2258 Reason = PDSA_LoopIterVarLinear; 2259 } else if (isOpenMPTaskingDirective(DVar.DKind) && 2260 DVar.CKind == OMPC_firstprivate) { 2261 Reason = PDSA_TaskVarFirstprivate; 2262 ReportLoc = DVar.ImplicitDSALoc; 2263 } else if (VD && VD->isStaticLocal()) 2264 Reason = PDSA_StaticLocalVarShared; 2265 else if (VD && VD->isStaticDataMember()) 2266 Reason = PDSA_StaticMemberShared; 2267 else if (VD && VD->isFileVarDecl()) 2268 Reason = PDSA_GlobalVarShared; 2269 else if (D->getType().isConstant(SemaRef.getASTContext())) 2270 Reason = PDSA_ConstVarShared; 2271 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 2272 ReportHint = true; 2273 Reason = PDSA_LocalVarPrivate; 2274 } 2275 if (Reason != PDSA_Implicit) { 2276 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 2277 << Reason << ReportHint 2278 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 2279 } else if (DVar.ImplicitDSALoc.isValid()) { 2280 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 2281 << getOpenMPClauseName(DVar.CKind); 2282 } 2283 } 2284 2285 namespace { 2286 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 2287 DSAStackTy *Stack; 2288 Sema &SemaRef; 2289 bool ErrorFound = false; 2290 CapturedStmt *CS = nullptr; 2291 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 2292 llvm::SmallVector<Expr *, 4> ImplicitMap; 2293 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 2294 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 2295 2296 void VisitSubCaptures(OMPExecutableDirective *S) { 2297 // Check implicitly captured variables. 2298 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 2299 return; 2300 for (const CapturedStmt::Capture &Cap : 2301 S->getInnermostCapturedStmt()->captures()) { 2302 if (!Cap.capturesVariable()) 2303 continue; 2304 VarDecl *VD = Cap.getCapturedVar(); 2305 // Do not try to map the variable if it or its sub-component was mapped 2306 // already. 2307 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 2308 Stack->checkMappableExprComponentListsForDecl( 2309 VD, /*CurrentRegionOnly=*/true, 2310 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2311 OpenMPClauseKind) { return true; })) 2312 continue; 2313 DeclRefExpr *DRE = buildDeclRefExpr( 2314 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context), 2315 Cap.getLocation(), /*RefersToCapture=*/true); 2316 Visit(DRE); 2317 } 2318 } 2319 2320 public: 2321 void VisitDeclRefExpr(DeclRefExpr *E) { 2322 if (E->isTypeDependent() || E->isValueDependent() || 2323 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 2324 return; 2325 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2326 VD = VD->getCanonicalDecl(); 2327 // Skip internally declared variables. 2328 if (VD->hasLocalStorage() && !CS->capturesVariable(VD)) 2329 return; 2330 2331 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 2332 // Check if the variable has explicit DSA set and stop analysis if it so. 2333 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 2334 return; 2335 2336 // Skip internally declared static variables. 2337 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2338 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 2339 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) && 2340 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)) 2341 return; 2342 2343 SourceLocation ELoc = E->getExprLoc(); 2344 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 2345 // The default(none) clause requires that each variable that is referenced 2346 // in the construct, and does not have a predetermined data-sharing 2347 // attribute, must have its data-sharing attribute explicitly determined 2348 // by being listed in a data-sharing attribute clause. 2349 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 2350 isImplicitOrExplicitTaskingRegion(DKind) && 2351 VarsWithInheritedDSA.count(VD) == 0) { 2352 VarsWithInheritedDSA[VD] = E; 2353 return; 2354 } 2355 2356 if (isOpenMPTargetExecutionDirective(DKind) && 2357 !Stack->isLoopControlVariable(VD).first) { 2358 if (!Stack->checkMappableExprComponentListsForDecl( 2359 VD, /*CurrentRegionOnly=*/true, 2360 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 2361 StackComponents, 2362 OpenMPClauseKind) { 2363 // Variable is used if it has been marked as an array, array 2364 // section or the variable iself. 2365 return StackComponents.size() == 1 || 2366 std::all_of( 2367 std::next(StackComponents.rbegin()), 2368 StackComponents.rend(), 2369 [](const OMPClauseMappableExprCommon:: 2370 MappableComponent &MC) { 2371 return MC.getAssociatedDeclaration() == 2372 nullptr && 2373 (isa<OMPArraySectionExpr>( 2374 MC.getAssociatedExpression()) || 2375 isa<ArraySubscriptExpr>( 2376 MC.getAssociatedExpression())); 2377 }); 2378 })) { 2379 bool IsFirstprivate = false; 2380 // By default lambdas are captured as firstprivates. 2381 if (const auto *RD = 2382 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 2383 IsFirstprivate = RD->isLambda(); 2384 IsFirstprivate = 2385 IsFirstprivate || 2386 (VD->getType().getNonReferenceType()->isScalarType() && 2387 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res); 2388 if (IsFirstprivate) 2389 ImplicitFirstprivate.emplace_back(E); 2390 else 2391 ImplicitMap.emplace_back(E); 2392 return; 2393 } 2394 } 2395 2396 // OpenMP [2.9.3.6, Restrictions, p.2] 2397 // A list item that appears in a reduction clause of the innermost 2398 // enclosing worksharing or parallel construct may not be accessed in an 2399 // explicit task. 2400 DVar = Stack->hasInnermostDSA( 2401 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 2402 [](OpenMPDirectiveKind K) { 2403 return isOpenMPParallelDirective(K) || 2404 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 2405 }, 2406 /*FromParent=*/true); 2407 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 2408 ErrorFound = true; 2409 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 2410 reportOriginalDsa(SemaRef, Stack, VD, DVar); 2411 return; 2412 } 2413 2414 // Define implicit data-sharing attributes for task. 2415 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 2416 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 2417 !Stack->isLoopControlVariable(VD).first) 2418 ImplicitFirstprivate.push_back(E); 2419 } 2420 } 2421 void VisitMemberExpr(MemberExpr *E) { 2422 if (E->isTypeDependent() || E->isValueDependent() || 2423 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 2424 return; 2425 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 2426 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 2427 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) { 2428 if (!FD) 2429 return; 2430 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 2431 // Check if the variable has explicit DSA set and stop analysis if it 2432 // so. 2433 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 2434 return; 2435 2436 if (isOpenMPTargetExecutionDirective(DKind) && 2437 !Stack->isLoopControlVariable(FD).first && 2438 !Stack->checkMappableExprComponentListsForDecl( 2439 FD, /*CurrentRegionOnly=*/true, 2440 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 2441 StackComponents, 2442 OpenMPClauseKind) { 2443 return isa<CXXThisExpr>( 2444 cast<MemberExpr>( 2445 StackComponents.back().getAssociatedExpression()) 2446 ->getBase() 2447 ->IgnoreParens()); 2448 })) { 2449 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 2450 // A bit-field cannot appear in a map clause. 2451 // 2452 if (FD->isBitField()) 2453 return; 2454 2455 // Check to see if the member expression is referencing a class that 2456 // has already been explicitly mapped 2457 if (Stack->isClassPreviouslyMapped(TE->getType())) 2458 return; 2459 2460 ImplicitMap.emplace_back(E); 2461 return; 2462 } 2463 2464 SourceLocation ELoc = E->getExprLoc(); 2465 // OpenMP [2.9.3.6, Restrictions, p.2] 2466 // A list item that appears in a reduction clause of the innermost 2467 // enclosing worksharing or parallel construct may not be accessed in 2468 // an explicit task. 2469 DVar = Stack->hasInnermostDSA( 2470 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 2471 [](OpenMPDirectiveKind K) { 2472 return isOpenMPParallelDirective(K) || 2473 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 2474 }, 2475 /*FromParent=*/true); 2476 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 2477 ErrorFound = true; 2478 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 2479 reportOriginalDsa(SemaRef, Stack, FD, DVar); 2480 return; 2481 } 2482 2483 // Define implicit data-sharing attributes for task. 2484 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 2485 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 2486 !Stack->isLoopControlVariable(FD).first) { 2487 // Check if there is a captured expression for the current field in the 2488 // region. Do not mark it as firstprivate unless there is no captured 2489 // expression. 2490 // TODO: try to make it firstprivate. 2491 if (DVar.CKind != OMPC_unknown) 2492 ImplicitFirstprivate.push_back(E); 2493 } 2494 return; 2495 } 2496 if (isOpenMPTargetExecutionDirective(DKind)) { 2497 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 2498 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 2499 /*NoDiagnose=*/true)) 2500 return; 2501 const auto *VD = cast<ValueDecl>( 2502 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 2503 if (!Stack->checkMappableExprComponentListsForDecl( 2504 VD, /*CurrentRegionOnly=*/true, 2505 [&CurComponents]( 2506 OMPClauseMappableExprCommon::MappableExprComponentListRef 2507 StackComponents, 2508 OpenMPClauseKind) { 2509 auto CCI = CurComponents.rbegin(); 2510 auto CCE = CurComponents.rend(); 2511 for (const auto &SC : llvm::reverse(StackComponents)) { 2512 // Do both expressions have the same kind? 2513 if (CCI->getAssociatedExpression()->getStmtClass() != 2514 SC.getAssociatedExpression()->getStmtClass()) 2515 if (!(isa<OMPArraySectionExpr>( 2516 SC.getAssociatedExpression()) && 2517 isa<ArraySubscriptExpr>( 2518 CCI->getAssociatedExpression()))) 2519 return false; 2520 2521 const Decl *CCD = CCI->getAssociatedDeclaration(); 2522 const Decl *SCD = SC.getAssociatedDeclaration(); 2523 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 2524 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 2525 if (SCD != CCD) 2526 return false; 2527 std::advance(CCI, 1); 2528 if (CCI == CCE) 2529 break; 2530 } 2531 return true; 2532 })) { 2533 Visit(E->getBase()); 2534 } 2535 } else { 2536 Visit(E->getBase()); 2537 } 2538 } 2539 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 2540 for (OMPClause *C : S->clauses()) { 2541 // Skip analysis of arguments of implicitly defined firstprivate clause 2542 // for task|target directives. 2543 // Skip analysis of arguments of implicitly defined map clause for target 2544 // directives. 2545 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 2546 C->isImplicit())) { 2547 for (Stmt *CC : C->children()) { 2548 if (CC) 2549 Visit(CC); 2550 } 2551 } 2552 } 2553 // Check implicitly captured variables. 2554 VisitSubCaptures(S); 2555 } 2556 void VisitStmt(Stmt *S) { 2557 for (Stmt *C : S->children()) { 2558 if (C) { 2559 // Check implicitly captured variables in the task-based directives to 2560 // check if they must be firstprivatized. 2561 Visit(C); 2562 } 2563 } 2564 } 2565 2566 bool isErrorFound() const { return ErrorFound; } 2567 ArrayRef<Expr *> getImplicitFirstprivate() const { 2568 return ImplicitFirstprivate; 2569 } 2570 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; } 2571 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 2572 return VarsWithInheritedDSA; 2573 } 2574 2575 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 2576 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 2577 }; 2578 } // namespace 2579 2580 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 2581 switch (DKind) { 2582 case OMPD_parallel: 2583 case OMPD_parallel_for: 2584 case OMPD_parallel_for_simd: 2585 case OMPD_parallel_sections: 2586 case OMPD_teams: 2587 case OMPD_teams_distribute: 2588 case OMPD_teams_distribute_simd: { 2589 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2590 QualType KmpInt32PtrTy = 2591 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2592 Sema::CapturedParamNameType Params[] = { 2593 std::make_pair(".global_tid.", KmpInt32PtrTy), 2594 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2595 std::make_pair(StringRef(), QualType()) // __context with shared vars 2596 }; 2597 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2598 Params); 2599 break; 2600 } 2601 case OMPD_target_teams: 2602 case OMPD_target_parallel: 2603 case OMPD_target_parallel_for: 2604 case OMPD_target_parallel_for_simd: 2605 case OMPD_target_teams_distribute: 2606 case OMPD_target_teams_distribute_simd: { 2607 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2608 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2609 QualType KmpInt32PtrTy = 2610 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2611 QualType Args[] = {VoidPtrTy}; 2612 FunctionProtoType::ExtProtoInfo EPI; 2613 EPI.Variadic = true; 2614 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2615 Sema::CapturedParamNameType Params[] = { 2616 std::make_pair(".global_tid.", KmpInt32Ty), 2617 std::make_pair(".part_id.", KmpInt32PtrTy), 2618 std::make_pair(".privates.", VoidPtrTy), 2619 std::make_pair( 2620 ".copy_fn.", 2621 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2622 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2623 std::make_pair(StringRef(), QualType()) // __context with shared vars 2624 }; 2625 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2626 Params); 2627 // Mark this captured region as inlined, because we don't use outlined 2628 // function directly. 2629 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2630 AlwaysInlineAttr::CreateImplicit( 2631 Context, AlwaysInlineAttr::Keyword_forceinline)); 2632 Sema::CapturedParamNameType ParamsTarget[] = { 2633 std::make_pair(StringRef(), QualType()) // __context with shared vars 2634 }; 2635 // Start a captured region for 'target' with no implicit parameters. 2636 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2637 ParamsTarget); 2638 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 2639 std::make_pair(".global_tid.", KmpInt32PtrTy), 2640 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2641 std::make_pair(StringRef(), QualType()) // __context with shared vars 2642 }; 2643 // Start a captured region for 'teams' or 'parallel'. Both regions have 2644 // the same implicit parameters. 2645 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2646 ParamsTeamsOrParallel); 2647 break; 2648 } 2649 case OMPD_target: 2650 case OMPD_target_simd: { 2651 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2652 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2653 QualType KmpInt32PtrTy = 2654 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2655 QualType Args[] = {VoidPtrTy}; 2656 FunctionProtoType::ExtProtoInfo EPI; 2657 EPI.Variadic = true; 2658 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2659 Sema::CapturedParamNameType Params[] = { 2660 std::make_pair(".global_tid.", KmpInt32Ty), 2661 std::make_pair(".part_id.", KmpInt32PtrTy), 2662 std::make_pair(".privates.", VoidPtrTy), 2663 std::make_pair( 2664 ".copy_fn.", 2665 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2666 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2667 std::make_pair(StringRef(), QualType()) // __context with shared vars 2668 }; 2669 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2670 Params); 2671 // Mark this captured region as inlined, because we don't use outlined 2672 // function directly. 2673 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2674 AlwaysInlineAttr::CreateImplicit( 2675 Context, AlwaysInlineAttr::Keyword_forceinline)); 2676 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2677 std::make_pair(StringRef(), QualType())); 2678 break; 2679 } 2680 case OMPD_simd: 2681 case OMPD_for: 2682 case OMPD_for_simd: 2683 case OMPD_sections: 2684 case OMPD_section: 2685 case OMPD_single: 2686 case OMPD_master: 2687 case OMPD_critical: 2688 case OMPD_taskgroup: 2689 case OMPD_distribute: 2690 case OMPD_distribute_simd: 2691 case OMPD_ordered: 2692 case OMPD_atomic: 2693 case OMPD_target_data: { 2694 Sema::CapturedParamNameType Params[] = { 2695 std::make_pair(StringRef(), QualType()) // __context with shared vars 2696 }; 2697 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2698 Params); 2699 break; 2700 } 2701 case OMPD_task: { 2702 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2703 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2704 QualType KmpInt32PtrTy = 2705 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2706 QualType Args[] = {VoidPtrTy}; 2707 FunctionProtoType::ExtProtoInfo EPI; 2708 EPI.Variadic = true; 2709 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2710 Sema::CapturedParamNameType Params[] = { 2711 std::make_pair(".global_tid.", KmpInt32Ty), 2712 std::make_pair(".part_id.", KmpInt32PtrTy), 2713 std::make_pair(".privates.", VoidPtrTy), 2714 std::make_pair( 2715 ".copy_fn.", 2716 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2717 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2718 std::make_pair(StringRef(), QualType()) // __context with shared vars 2719 }; 2720 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2721 Params); 2722 // Mark this captured region as inlined, because we don't use outlined 2723 // function directly. 2724 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2725 AlwaysInlineAttr::CreateImplicit( 2726 Context, AlwaysInlineAttr::Keyword_forceinline)); 2727 break; 2728 } 2729 case OMPD_taskloop: 2730 case OMPD_taskloop_simd: { 2731 QualType KmpInt32Ty = 2732 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 2733 .withConst(); 2734 QualType KmpUInt64Ty = 2735 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 2736 .withConst(); 2737 QualType KmpInt64Ty = 2738 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 2739 .withConst(); 2740 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2741 QualType KmpInt32PtrTy = 2742 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2743 QualType Args[] = {VoidPtrTy}; 2744 FunctionProtoType::ExtProtoInfo EPI; 2745 EPI.Variadic = true; 2746 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2747 Sema::CapturedParamNameType Params[] = { 2748 std::make_pair(".global_tid.", KmpInt32Ty), 2749 std::make_pair(".part_id.", KmpInt32PtrTy), 2750 std::make_pair(".privates.", VoidPtrTy), 2751 std::make_pair( 2752 ".copy_fn.", 2753 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2754 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2755 std::make_pair(".lb.", KmpUInt64Ty), 2756 std::make_pair(".ub.", KmpUInt64Ty), 2757 std::make_pair(".st.", KmpInt64Ty), 2758 std::make_pair(".liter.", KmpInt32Ty), 2759 std::make_pair(".reductions.", VoidPtrTy), 2760 std::make_pair(StringRef(), QualType()) // __context with shared vars 2761 }; 2762 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2763 Params); 2764 // Mark this captured region as inlined, because we don't use outlined 2765 // function directly. 2766 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2767 AlwaysInlineAttr::CreateImplicit( 2768 Context, AlwaysInlineAttr::Keyword_forceinline)); 2769 break; 2770 } 2771 case OMPD_distribute_parallel_for_simd: 2772 case OMPD_distribute_parallel_for: { 2773 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2774 QualType KmpInt32PtrTy = 2775 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2776 Sema::CapturedParamNameType Params[] = { 2777 std::make_pair(".global_tid.", KmpInt32PtrTy), 2778 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2779 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 2780 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 2781 std::make_pair(StringRef(), QualType()) // __context with shared vars 2782 }; 2783 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2784 Params); 2785 break; 2786 } 2787 case OMPD_target_teams_distribute_parallel_for: 2788 case OMPD_target_teams_distribute_parallel_for_simd: { 2789 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2790 QualType KmpInt32PtrTy = 2791 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2792 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2793 2794 QualType Args[] = {VoidPtrTy}; 2795 FunctionProtoType::ExtProtoInfo EPI; 2796 EPI.Variadic = true; 2797 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2798 Sema::CapturedParamNameType Params[] = { 2799 std::make_pair(".global_tid.", KmpInt32Ty), 2800 std::make_pair(".part_id.", KmpInt32PtrTy), 2801 std::make_pair(".privates.", VoidPtrTy), 2802 std::make_pair( 2803 ".copy_fn.", 2804 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2805 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2806 std::make_pair(StringRef(), QualType()) // __context with shared vars 2807 }; 2808 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2809 Params); 2810 // Mark this captured region as inlined, because we don't use outlined 2811 // function directly. 2812 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2813 AlwaysInlineAttr::CreateImplicit( 2814 Context, AlwaysInlineAttr::Keyword_forceinline)); 2815 Sema::CapturedParamNameType ParamsTarget[] = { 2816 std::make_pair(StringRef(), QualType()) // __context with shared vars 2817 }; 2818 // Start a captured region for 'target' with no implicit parameters. 2819 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2820 ParamsTarget); 2821 2822 Sema::CapturedParamNameType ParamsTeams[] = { 2823 std::make_pair(".global_tid.", KmpInt32PtrTy), 2824 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2825 std::make_pair(StringRef(), QualType()) // __context with shared vars 2826 }; 2827 // Start a captured region for 'target' with no implicit parameters. 2828 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2829 ParamsTeams); 2830 2831 Sema::CapturedParamNameType ParamsParallel[] = { 2832 std::make_pair(".global_tid.", KmpInt32PtrTy), 2833 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2834 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 2835 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 2836 std::make_pair(StringRef(), QualType()) // __context with shared vars 2837 }; 2838 // Start a captured region for 'teams' or 'parallel'. Both regions have 2839 // the same implicit parameters. 2840 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2841 ParamsParallel); 2842 break; 2843 } 2844 2845 case OMPD_teams_distribute_parallel_for: 2846 case OMPD_teams_distribute_parallel_for_simd: { 2847 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2848 QualType KmpInt32PtrTy = 2849 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2850 2851 Sema::CapturedParamNameType ParamsTeams[] = { 2852 std::make_pair(".global_tid.", KmpInt32PtrTy), 2853 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2854 std::make_pair(StringRef(), QualType()) // __context with shared vars 2855 }; 2856 // Start a captured region for 'target' with no implicit parameters. 2857 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2858 ParamsTeams); 2859 2860 Sema::CapturedParamNameType ParamsParallel[] = { 2861 std::make_pair(".global_tid.", KmpInt32PtrTy), 2862 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2863 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 2864 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 2865 std::make_pair(StringRef(), QualType()) // __context with shared vars 2866 }; 2867 // Start a captured region for 'teams' or 'parallel'. Both regions have 2868 // the same implicit parameters. 2869 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2870 ParamsParallel); 2871 break; 2872 } 2873 case OMPD_target_update: 2874 case OMPD_target_enter_data: 2875 case OMPD_target_exit_data: { 2876 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2877 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2878 QualType KmpInt32PtrTy = 2879 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2880 QualType Args[] = {VoidPtrTy}; 2881 FunctionProtoType::ExtProtoInfo EPI; 2882 EPI.Variadic = true; 2883 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2884 Sema::CapturedParamNameType Params[] = { 2885 std::make_pair(".global_tid.", KmpInt32Ty), 2886 std::make_pair(".part_id.", KmpInt32PtrTy), 2887 std::make_pair(".privates.", VoidPtrTy), 2888 std::make_pair( 2889 ".copy_fn.", 2890 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2891 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2892 std::make_pair(StringRef(), QualType()) // __context with shared vars 2893 }; 2894 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2895 Params); 2896 // Mark this captured region as inlined, because we don't use outlined 2897 // function directly. 2898 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2899 AlwaysInlineAttr::CreateImplicit( 2900 Context, AlwaysInlineAttr::Keyword_forceinline)); 2901 break; 2902 } 2903 case OMPD_threadprivate: 2904 case OMPD_allocate: 2905 case OMPD_taskyield: 2906 case OMPD_barrier: 2907 case OMPD_taskwait: 2908 case OMPD_cancellation_point: 2909 case OMPD_cancel: 2910 case OMPD_flush: 2911 case OMPD_declare_reduction: 2912 case OMPD_declare_mapper: 2913 case OMPD_declare_simd: 2914 case OMPD_declare_target: 2915 case OMPD_end_declare_target: 2916 case OMPD_requires: 2917 llvm_unreachable("OpenMP Directive is not allowed"); 2918 case OMPD_unknown: 2919 llvm_unreachable("Unknown OpenMP directive"); 2920 } 2921 } 2922 2923 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 2924 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2925 getOpenMPCaptureRegions(CaptureRegions, DKind); 2926 return CaptureRegions.size(); 2927 } 2928 2929 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 2930 Expr *CaptureExpr, bool WithInit, 2931 bool AsExpression) { 2932 assert(CaptureExpr); 2933 ASTContext &C = S.getASTContext(); 2934 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 2935 QualType Ty = Init->getType(); 2936 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 2937 if (S.getLangOpts().CPlusPlus) { 2938 Ty = C.getLValueReferenceType(Ty); 2939 } else { 2940 Ty = C.getPointerType(Ty); 2941 ExprResult Res = 2942 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 2943 if (!Res.isUsable()) 2944 return nullptr; 2945 Init = Res.get(); 2946 } 2947 WithInit = true; 2948 } 2949 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 2950 CaptureExpr->getBeginLoc()); 2951 if (!WithInit) 2952 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 2953 S.CurContext->addHiddenDecl(CED); 2954 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 2955 return CED; 2956 } 2957 2958 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2959 bool WithInit) { 2960 OMPCapturedExprDecl *CD; 2961 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 2962 CD = cast<OMPCapturedExprDecl>(VD); 2963 else 2964 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 2965 /*AsExpression=*/false); 2966 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2967 CaptureExpr->getExprLoc()); 2968 } 2969 2970 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 2971 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 2972 if (!Ref) { 2973 OMPCapturedExprDecl *CD = buildCaptureDecl( 2974 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 2975 /*WithInit=*/true, /*AsExpression=*/true); 2976 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2977 CaptureExpr->getExprLoc()); 2978 } 2979 ExprResult Res = Ref; 2980 if (!S.getLangOpts().CPlusPlus && 2981 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 2982 Ref->getType()->isPointerType()) { 2983 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 2984 if (!Res.isUsable()) 2985 return ExprError(); 2986 } 2987 return S.DefaultLvalueConversion(Res.get()); 2988 } 2989 2990 namespace { 2991 // OpenMP directives parsed in this section are represented as a 2992 // CapturedStatement with an associated statement. If a syntax error 2993 // is detected during the parsing of the associated statement, the 2994 // compiler must abort processing and close the CapturedStatement. 2995 // 2996 // Combined directives such as 'target parallel' have more than one 2997 // nested CapturedStatements. This RAII ensures that we unwind out 2998 // of all the nested CapturedStatements when an error is found. 2999 class CaptureRegionUnwinderRAII { 3000 private: 3001 Sema &S; 3002 bool &ErrorFound; 3003 OpenMPDirectiveKind DKind = OMPD_unknown; 3004 3005 public: 3006 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 3007 OpenMPDirectiveKind DKind) 3008 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 3009 ~CaptureRegionUnwinderRAII() { 3010 if (ErrorFound) { 3011 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 3012 while (--ThisCaptureLevel >= 0) 3013 S.ActOnCapturedRegionError(); 3014 } 3015 } 3016 }; 3017 } // namespace 3018 3019 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 3020 ArrayRef<OMPClause *> Clauses) { 3021 bool ErrorFound = false; 3022 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 3023 *this, ErrorFound, DSAStack->getCurrentDirective()); 3024 if (!S.isUsable()) { 3025 ErrorFound = true; 3026 return StmtError(); 3027 } 3028 3029 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 3030 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 3031 OMPOrderedClause *OC = nullptr; 3032 OMPScheduleClause *SC = nullptr; 3033 SmallVector<const OMPLinearClause *, 4> LCs; 3034 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 3035 // This is required for proper codegen. 3036 for (OMPClause *Clause : Clauses) { 3037 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 3038 Clause->getClauseKind() == OMPC_in_reduction) { 3039 // Capture taskgroup task_reduction descriptors inside the tasking regions 3040 // with the corresponding in_reduction items. 3041 auto *IRC = cast<OMPInReductionClause>(Clause); 3042 for (Expr *E : IRC->taskgroup_descriptors()) 3043 if (E) 3044 MarkDeclarationsReferencedInExpr(E); 3045 } 3046 if (isOpenMPPrivate(Clause->getClauseKind()) || 3047 Clause->getClauseKind() == OMPC_copyprivate || 3048 (getLangOpts().OpenMPUseTLS && 3049 getASTContext().getTargetInfo().isTLSSupported() && 3050 Clause->getClauseKind() == OMPC_copyin)) { 3051 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 3052 // Mark all variables in private list clauses as used in inner region. 3053 for (Stmt *VarRef : Clause->children()) { 3054 if (auto *E = cast_or_null<Expr>(VarRef)) { 3055 MarkDeclarationsReferencedInExpr(E); 3056 } 3057 } 3058 DSAStack->setForceVarCapturing(/*V=*/false); 3059 } else if (CaptureRegions.size() > 1 || 3060 CaptureRegions.back() != OMPD_unknown) { 3061 if (auto *C = OMPClauseWithPreInit::get(Clause)) 3062 PICs.push_back(C); 3063 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 3064 if (Expr *E = C->getPostUpdateExpr()) 3065 MarkDeclarationsReferencedInExpr(E); 3066 } 3067 } 3068 if (Clause->getClauseKind() == OMPC_schedule) 3069 SC = cast<OMPScheduleClause>(Clause); 3070 else if (Clause->getClauseKind() == OMPC_ordered) 3071 OC = cast<OMPOrderedClause>(Clause); 3072 else if (Clause->getClauseKind() == OMPC_linear) 3073 LCs.push_back(cast<OMPLinearClause>(Clause)); 3074 } 3075 // OpenMP, 2.7.1 Loop Construct, Restrictions 3076 // The nonmonotonic modifier cannot be specified if an ordered clause is 3077 // specified. 3078 if (SC && 3079 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 3080 SC->getSecondScheduleModifier() == 3081 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 3082 OC) { 3083 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 3084 ? SC->getFirstScheduleModifierLoc() 3085 : SC->getSecondScheduleModifierLoc(), 3086 diag::err_omp_schedule_nonmonotonic_ordered) 3087 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 3088 ErrorFound = true; 3089 } 3090 if (!LCs.empty() && OC && OC->getNumForLoops()) { 3091 for (const OMPLinearClause *C : LCs) { 3092 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 3093 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 3094 } 3095 ErrorFound = true; 3096 } 3097 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 3098 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 3099 OC->getNumForLoops()) { 3100 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 3101 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 3102 ErrorFound = true; 3103 } 3104 if (ErrorFound) { 3105 return StmtError(); 3106 } 3107 StmtResult SR = S; 3108 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 3109 // Mark all variables in private list clauses as used in inner region. 3110 // Required for proper codegen of combined directives. 3111 // TODO: add processing for other clauses. 3112 if (ThisCaptureRegion != OMPD_unknown) { 3113 for (const clang::OMPClauseWithPreInit *C : PICs) { 3114 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 3115 // Find the particular capture region for the clause if the 3116 // directive is a combined one with multiple capture regions. 3117 // If the directive is not a combined one, the capture region 3118 // associated with the clause is OMPD_unknown and is generated 3119 // only once. 3120 if (CaptureRegion == ThisCaptureRegion || 3121 CaptureRegion == OMPD_unknown) { 3122 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 3123 for (Decl *D : DS->decls()) 3124 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 3125 } 3126 } 3127 } 3128 } 3129 SR = ActOnCapturedRegionEnd(SR.get()); 3130 } 3131 return SR; 3132 } 3133 3134 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 3135 OpenMPDirectiveKind CancelRegion, 3136 SourceLocation StartLoc) { 3137 // CancelRegion is only needed for cancel and cancellation_point. 3138 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 3139 return false; 3140 3141 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 3142 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 3143 return false; 3144 3145 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 3146 << getOpenMPDirectiveName(CancelRegion); 3147 return true; 3148 } 3149 3150 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 3151 OpenMPDirectiveKind CurrentRegion, 3152 const DeclarationNameInfo &CurrentName, 3153 OpenMPDirectiveKind CancelRegion, 3154 SourceLocation StartLoc) { 3155 if (Stack->getCurScope()) { 3156 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 3157 OpenMPDirectiveKind OffendingRegion = ParentRegion; 3158 bool NestingProhibited = false; 3159 bool CloseNesting = true; 3160 bool OrphanSeen = false; 3161 enum { 3162 NoRecommend, 3163 ShouldBeInParallelRegion, 3164 ShouldBeInOrderedRegion, 3165 ShouldBeInTargetRegion, 3166 ShouldBeInTeamsRegion 3167 } Recommend = NoRecommend; 3168 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 3169 // OpenMP [2.16, Nesting of Regions] 3170 // OpenMP constructs may not be nested inside a simd region. 3171 // OpenMP [2.8.1,simd Construct, Restrictions] 3172 // An ordered construct with the simd clause is the only OpenMP 3173 // construct that can appear in the simd region. 3174 // Allowing a SIMD construct nested in another SIMD construct is an 3175 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 3176 // message. 3177 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 3178 ? diag::err_omp_prohibited_region_simd 3179 : diag::warn_omp_nesting_simd); 3180 return CurrentRegion != OMPD_simd; 3181 } 3182 if (ParentRegion == OMPD_atomic) { 3183 // OpenMP [2.16, Nesting of Regions] 3184 // OpenMP constructs may not be nested inside an atomic region. 3185 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 3186 return true; 3187 } 3188 if (CurrentRegion == OMPD_section) { 3189 // OpenMP [2.7.2, sections Construct, Restrictions] 3190 // Orphaned section directives are prohibited. That is, the section 3191 // directives must appear within the sections construct and must not be 3192 // encountered elsewhere in the sections region. 3193 if (ParentRegion != OMPD_sections && 3194 ParentRegion != OMPD_parallel_sections) { 3195 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 3196 << (ParentRegion != OMPD_unknown) 3197 << getOpenMPDirectiveName(ParentRegion); 3198 return true; 3199 } 3200 return false; 3201 } 3202 // Allow some constructs (except teams and cancellation constructs) to be 3203 // orphaned (they could be used in functions, called from OpenMP regions 3204 // with the required preconditions). 3205 if (ParentRegion == OMPD_unknown && 3206 !isOpenMPNestingTeamsDirective(CurrentRegion) && 3207 CurrentRegion != OMPD_cancellation_point && 3208 CurrentRegion != OMPD_cancel) 3209 return false; 3210 if (CurrentRegion == OMPD_cancellation_point || 3211 CurrentRegion == OMPD_cancel) { 3212 // OpenMP [2.16, Nesting of Regions] 3213 // A cancellation point construct for which construct-type-clause is 3214 // taskgroup must be nested inside a task construct. A cancellation 3215 // point construct for which construct-type-clause is not taskgroup must 3216 // be closely nested inside an OpenMP construct that matches the type 3217 // specified in construct-type-clause. 3218 // A cancel construct for which construct-type-clause is taskgroup must be 3219 // nested inside a task construct. A cancel construct for which 3220 // construct-type-clause is not taskgroup must be closely nested inside an 3221 // OpenMP construct that matches the type specified in 3222 // construct-type-clause. 3223 NestingProhibited = 3224 !((CancelRegion == OMPD_parallel && 3225 (ParentRegion == OMPD_parallel || 3226 ParentRegion == OMPD_target_parallel)) || 3227 (CancelRegion == OMPD_for && 3228 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 3229 ParentRegion == OMPD_target_parallel_for || 3230 ParentRegion == OMPD_distribute_parallel_for || 3231 ParentRegion == OMPD_teams_distribute_parallel_for || 3232 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 3233 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 3234 (CancelRegion == OMPD_sections && 3235 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 3236 ParentRegion == OMPD_parallel_sections))); 3237 OrphanSeen = ParentRegion == OMPD_unknown; 3238 } else if (CurrentRegion == OMPD_master) { 3239 // OpenMP [2.16, Nesting of Regions] 3240 // A master region may not be closely nested inside a worksharing, 3241 // atomic, or explicit task region. 3242 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3243 isOpenMPTaskingDirective(ParentRegion); 3244 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 3245 // OpenMP [2.16, Nesting of Regions] 3246 // A critical region may not be nested (closely or otherwise) inside a 3247 // critical region with the same name. Note that this restriction is not 3248 // sufficient to prevent deadlock. 3249 SourceLocation PreviousCriticalLoc; 3250 bool DeadLock = Stack->hasDirective( 3251 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 3252 const DeclarationNameInfo &DNI, 3253 SourceLocation Loc) { 3254 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 3255 PreviousCriticalLoc = Loc; 3256 return true; 3257 } 3258 return false; 3259 }, 3260 false /* skip top directive */); 3261 if (DeadLock) { 3262 SemaRef.Diag(StartLoc, 3263 diag::err_omp_prohibited_region_critical_same_name) 3264 << CurrentName.getName(); 3265 if (PreviousCriticalLoc.isValid()) 3266 SemaRef.Diag(PreviousCriticalLoc, 3267 diag::note_omp_previous_critical_region); 3268 return true; 3269 } 3270 } else if (CurrentRegion == OMPD_barrier) { 3271 // OpenMP [2.16, Nesting of Regions] 3272 // A barrier region may not be closely nested inside a worksharing, 3273 // explicit task, critical, ordered, atomic, or master region. 3274 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3275 isOpenMPTaskingDirective(ParentRegion) || 3276 ParentRegion == OMPD_master || 3277 ParentRegion == OMPD_critical || 3278 ParentRegion == OMPD_ordered; 3279 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 3280 !isOpenMPParallelDirective(CurrentRegion) && 3281 !isOpenMPTeamsDirective(CurrentRegion)) { 3282 // OpenMP [2.16, Nesting of Regions] 3283 // A worksharing region may not be closely nested inside a worksharing, 3284 // explicit task, critical, ordered, atomic, or master region. 3285 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3286 isOpenMPTaskingDirective(ParentRegion) || 3287 ParentRegion == OMPD_master || 3288 ParentRegion == OMPD_critical || 3289 ParentRegion == OMPD_ordered; 3290 Recommend = ShouldBeInParallelRegion; 3291 } else if (CurrentRegion == OMPD_ordered) { 3292 // OpenMP [2.16, Nesting of Regions] 3293 // An ordered region may not be closely nested inside a critical, 3294 // atomic, or explicit task region. 3295 // An ordered region must be closely nested inside a loop region (or 3296 // parallel loop region) with an ordered clause. 3297 // OpenMP [2.8.1,simd Construct, Restrictions] 3298 // An ordered construct with the simd clause is the only OpenMP construct 3299 // that can appear in the simd region. 3300 NestingProhibited = ParentRegion == OMPD_critical || 3301 isOpenMPTaskingDirective(ParentRegion) || 3302 !(isOpenMPSimdDirective(ParentRegion) || 3303 Stack->isParentOrderedRegion()); 3304 Recommend = ShouldBeInOrderedRegion; 3305 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 3306 // OpenMP [2.16, Nesting of Regions] 3307 // If specified, a teams construct must be contained within a target 3308 // construct. 3309 NestingProhibited = ParentRegion != OMPD_target; 3310 OrphanSeen = ParentRegion == OMPD_unknown; 3311 Recommend = ShouldBeInTargetRegion; 3312 } 3313 if (!NestingProhibited && 3314 !isOpenMPTargetExecutionDirective(CurrentRegion) && 3315 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 3316 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 3317 // OpenMP [2.16, Nesting of Regions] 3318 // distribute, parallel, parallel sections, parallel workshare, and the 3319 // parallel loop and parallel loop SIMD constructs are the only OpenMP 3320 // constructs that can be closely nested in the teams region. 3321 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 3322 !isOpenMPDistributeDirective(CurrentRegion); 3323 Recommend = ShouldBeInParallelRegion; 3324 } 3325 if (!NestingProhibited && 3326 isOpenMPNestingDistributeDirective(CurrentRegion)) { 3327 // OpenMP 4.5 [2.17 Nesting of Regions] 3328 // The region associated with the distribute construct must be strictly 3329 // nested inside a teams region 3330 NestingProhibited = 3331 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 3332 Recommend = ShouldBeInTeamsRegion; 3333 } 3334 if (!NestingProhibited && 3335 (isOpenMPTargetExecutionDirective(CurrentRegion) || 3336 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 3337 // OpenMP 4.5 [2.17 Nesting of Regions] 3338 // If a target, target update, target data, target enter data, or 3339 // target exit data construct is encountered during execution of a 3340 // target region, the behavior is unspecified. 3341 NestingProhibited = Stack->hasDirective( 3342 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 3343 SourceLocation) { 3344 if (isOpenMPTargetExecutionDirective(K)) { 3345 OffendingRegion = K; 3346 return true; 3347 } 3348 return false; 3349 }, 3350 false /* don't skip top directive */); 3351 CloseNesting = false; 3352 } 3353 if (NestingProhibited) { 3354 if (OrphanSeen) { 3355 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 3356 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 3357 } else { 3358 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 3359 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 3360 << Recommend << getOpenMPDirectiveName(CurrentRegion); 3361 } 3362 return true; 3363 } 3364 } 3365 return false; 3366 } 3367 3368 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 3369 ArrayRef<OMPClause *> Clauses, 3370 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 3371 bool ErrorFound = false; 3372 unsigned NamedModifiersNumber = 0; 3373 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 3374 OMPD_unknown + 1); 3375 SmallVector<SourceLocation, 4> NameModifierLoc; 3376 for (const OMPClause *C : Clauses) { 3377 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 3378 // At most one if clause without a directive-name-modifier can appear on 3379 // the directive. 3380 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 3381 if (FoundNameModifiers[CurNM]) { 3382 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 3383 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 3384 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 3385 ErrorFound = true; 3386 } else if (CurNM != OMPD_unknown) { 3387 NameModifierLoc.push_back(IC->getNameModifierLoc()); 3388 ++NamedModifiersNumber; 3389 } 3390 FoundNameModifiers[CurNM] = IC; 3391 if (CurNM == OMPD_unknown) 3392 continue; 3393 // Check if the specified name modifier is allowed for the current 3394 // directive. 3395 // At most one if clause with the particular directive-name-modifier can 3396 // appear on the directive. 3397 bool MatchFound = false; 3398 for (auto NM : AllowedNameModifiers) { 3399 if (CurNM == NM) { 3400 MatchFound = true; 3401 break; 3402 } 3403 } 3404 if (!MatchFound) { 3405 S.Diag(IC->getNameModifierLoc(), 3406 diag::err_omp_wrong_if_directive_name_modifier) 3407 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 3408 ErrorFound = true; 3409 } 3410 } 3411 } 3412 // If any if clause on the directive includes a directive-name-modifier then 3413 // all if clauses on the directive must include a directive-name-modifier. 3414 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 3415 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 3416 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 3417 diag::err_omp_no_more_if_clause); 3418 } else { 3419 std::string Values; 3420 std::string Sep(", "); 3421 unsigned AllowedCnt = 0; 3422 unsigned TotalAllowedNum = 3423 AllowedNameModifiers.size() - NamedModifiersNumber; 3424 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 3425 ++Cnt) { 3426 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 3427 if (!FoundNameModifiers[NM]) { 3428 Values += "'"; 3429 Values += getOpenMPDirectiveName(NM); 3430 Values += "'"; 3431 if (AllowedCnt + 2 == TotalAllowedNum) 3432 Values += " or "; 3433 else if (AllowedCnt + 1 != TotalAllowedNum) 3434 Values += Sep; 3435 ++AllowedCnt; 3436 } 3437 } 3438 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 3439 diag::err_omp_unnamed_if_clause) 3440 << (TotalAllowedNum > 1) << Values; 3441 } 3442 for (SourceLocation Loc : NameModifierLoc) { 3443 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 3444 } 3445 ErrorFound = true; 3446 } 3447 return ErrorFound; 3448 } 3449 3450 StmtResult Sema::ActOnOpenMPExecutableDirective( 3451 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 3452 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 3453 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 3454 StmtResult Res = StmtError(); 3455 // First check CancelRegion which is then used in checkNestingOfRegions. 3456 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 3457 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 3458 StartLoc)) 3459 return StmtError(); 3460 3461 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 3462 VarsWithInheritedDSAType VarsWithInheritedDSA; 3463 bool ErrorFound = false; 3464 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 3465 if (AStmt && !CurContext->isDependentContext()) { 3466 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3467 3468 // Check default data sharing attributes for referenced variables. 3469 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 3470 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 3471 Stmt *S = AStmt; 3472 while (--ThisCaptureLevel >= 0) 3473 S = cast<CapturedStmt>(S)->getCapturedStmt(); 3474 DSAChecker.Visit(S); 3475 if (DSAChecker.isErrorFound()) 3476 return StmtError(); 3477 // Generate list of implicitly defined firstprivate variables. 3478 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 3479 3480 SmallVector<Expr *, 4> ImplicitFirstprivates( 3481 DSAChecker.getImplicitFirstprivate().begin(), 3482 DSAChecker.getImplicitFirstprivate().end()); 3483 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(), 3484 DSAChecker.getImplicitMap().end()); 3485 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 3486 for (OMPClause *C : Clauses) { 3487 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 3488 for (Expr *E : IRC->taskgroup_descriptors()) 3489 if (E) 3490 ImplicitFirstprivates.emplace_back(E); 3491 } 3492 } 3493 if (!ImplicitFirstprivates.empty()) { 3494 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 3495 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 3496 SourceLocation())) { 3497 ClausesWithImplicit.push_back(Implicit); 3498 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 3499 ImplicitFirstprivates.size(); 3500 } else { 3501 ErrorFound = true; 3502 } 3503 } 3504 if (!ImplicitMaps.empty()) { 3505 CXXScopeSpec MapperIdScopeSpec; 3506 DeclarationNameInfo MapperId; 3507 if (OMPClause *Implicit = ActOnOpenMPMapClause( 3508 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, 3509 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(), 3510 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) { 3511 ClausesWithImplicit.emplace_back(Implicit); 3512 ErrorFound |= 3513 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size(); 3514 } else { 3515 ErrorFound = true; 3516 } 3517 } 3518 } 3519 3520 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 3521 switch (Kind) { 3522 case OMPD_parallel: 3523 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 3524 EndLoc); 3525 AllowedNameModifiers.push_back(OMPD_parallel); 3526 break; 3527 case OMPD_simd: 3528 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3529 VarsWithInheritedDSA); 3530 break; 3531 case OMPD_for: 3532 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3533 VarsWithInheritedDSA); 3534 break; 3535 case OMPD_for_simd: 3536 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3537 EndLoc, VarsWithInheritedDSA); 3538 break; 3539 case OMPD_sections: 3540 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 3541 EndLoc); 3542 break; 3543 case OMPD_section: 3544 assert(ClausesWithImplicit.empty() && 3545 "No clauses are allowed for 'omp section' directive"); 3546 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 3547 break; 3548 case OMPD_single: 3549 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 3550 EndLoc); 3551 break; 3552 case OMPD_master: 3553 assert(ClausesWithImplicit.empty() && 3554 "No clauses are allowed for 'omp master' directive"); 3555 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 3556 break; 3557 case OMPD_critical: 3558 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 3559 StartLoc, EndLoc); 3560 break; 3561 case OMPD_parallel_for: 3562 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 3563 EndLoc, VarsWithInheritedDSA); 3564 AllowedNameModifiers.push_back(OMPD_parallel); 3565 break; 3566 case OMPD_parallel_for_simd: 3567 Res = ActOnOpenMPParallelForSimdDirective( 3568 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3569 AllowedNameModifiers.push_back(OMPD_parallel); 3570 break; 3571 case OMPD_parallel_sections: 3572 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 3573 StartLoc, EndLoc); 3574 AllowedNameModifiers.push_back(OMPD_parallel); 3575 break; 3576 case OMPD_task: 3577 Res = 3578 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3579 AllowedNameModifiers.push_back(OMPD_task); 3580 break; 3581 case OMPD_taskyield: 3582 assert(ClausesWithImplicit.empty() && 3583 "No clauses are allowed for 'omp taskyield' directive"); 3584 assert(AStmt == nullptr && 3585 "No associated statement allowed for 'omp taskyield' directive"); 3586 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 3587 break; 3588 case OMPD_barrier: 3589 assert(ClausesWithImplicit.empty() && 3590 "No clauses are allowed for 'omp barrier' directive"); 3591 assert(AStmt == nullptr && 3592 "No associated statement allowed for 'omp barrier' directive"); 3593 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 3594 break; 3595 case OMPD_taskwait: 3596 assert(ClausesWithImplicit.empty() && 3597 "No clauses are allowed for 'omp taskwait' directive"); 3598 assert(AStmt == nullptr && 3599 "No associated statement allowed for 'omp taskwait' directive"); 3600 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 3601 break; 3602 case OMPD_taskgroup: 3603 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 3604 EndLoc); 3605 break; 3606 case OMPD_flush: 3607 assert(AStmt == nullptr && 3608 "No associated statement allowed for 'omp flush' directive"); 3609 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 3610 break; 3611 case OMPD_ordered: 3612 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 3613 EndLoc); 3614 break; 3615 case OMPD_atomic: 3616 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 3617 EndLoc); 3618 break; 3619 case OMPD_teams: 3620 Res = 3621 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3622 break; 3623 case OMPD_target: 3624 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 3625 EndLoc); 3626 AllowedNameModifiers.push_back(OMPD_target); 3627 break; 3628 case OMPD_target_parallel: 3629 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 3630 StartLoc, EndLoc); 3631 AllowedNameModifiers.push_back(OMPD_target); 3632 AllowedNameModifiers.push_back(OMPD_parallel); 3633 break; 3634 case OMPD_target_parallel_for: 3635 Res = ActOnOpenMPTargetParallelForDirective( 3636 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3637 AllowedNameModifiers.push_back(OMPD_target); 3638 AllowedNameModifiers.push_back(OMPD_parallel); 3639 break; 3640 case OMPD_cancellation_point: 3641 assert(ClausesWithImplicit.empty() && 3642 "No clauses are allowed for 'omp cancellation point' directive"); 3643 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 3644 "cancellation point' directive"); 3645 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 3646 break; 3647 case OMPD_cancel: 3648 assert(AStmt == nullptr && 3649 "No associated statement allowed for 'omp cancel' directive"); 3650 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 3651 CancelRegion); 3652 AllowedNameModifiers.push_back(OMPD_cancel); 3653 break; 3654 case OMPD_target_data: 3655 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 3656 EndLoc); 3657 AllowedNameModifiers.push_back(OMPD_target_data); 3658 break; 3659 case OMPD_target_enter_data: 3660 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 3661 EndLoc, AStmt); 3662 AllowedNameModifiers.push_back(OMPD_target_enter_data); 3663 break; 3664 case OMPD_target_exit_data: 3665 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 3666 EndLoc, AStmt); 3667 AllowedNameModifiers.push_back(OMPD_target_exit_data); 3668 break; 3669 case OMPD_taskloop: 3670 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 3671 EndLoc, VarsWithInheritedDSA); 3672 AllowedNameModifiers.push_back(OMPD_taskloop); 3673 break; 3674 case OMPD_taskloop_simd: 3675 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3676 EndLoc, VarsWithInheritedDSA); 3677 AllowedNameModifiers.push_back(OMPD_taskloop); 3678 break; 3679 case OMPD_distribute: 3680 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 3681 EndLoc, VarsWithInheritedDSA); 3682 break; 3683 case OMPD_target_update: 3684 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 3685 EndLoc, AStmt); 3686 AllowedNameModifiers.push_back(OMPD_target_update); 3687 break; 3688 case OMPD_distribute_parallel_for: 3689 Res = ActOnOpenMPDistributeParallelForDirective( 3690 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3691 AllowedNameModifiers.push_back(OMPD_parallel); 3692 break; 3693 case OMPD_distribute_parallel_for_simd: 3694 Res = ActOnOpenMPDistributeParallelForSimdDirective( 3695 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3696 AllowedNameModifiers.push_back(OMPD_parallel); 3697 break; 3698 case OMPD_distribute_simd: 3699 Res = ActOnOpenMPDistributeSimdDirective( 3700 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3701 break; 3702 case OMPD_target_parallel_for_simd: 3703 Res = ActOnOpenMPTargetParallelForSimdDirective( 3704 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3705 AllowedNameModifiers.push_back(OMPD_target); 3706 AllowedNameModifiers.push_back(OMPD_parallel); 3707 break; 3708 case OMPD_target_simd: 3709 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3710 EndLoc, VarsWithInheritedDSA); 3711 AllowedNameModifiers.push_back(OMPD_target); 3712 break; 3713 case OMPD_teams_distribute: 3714 Res = ActOnOpenMPTeamsDistributeDirective( 3715 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3716 break; 3717 case OMPD_teams_distribute_simd: 3718 Res = ActOnOpenMPTeamsDistributeSimdDirective( 3719 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3720 break; 3721 case OMPD_teams_distribute_parallel_for_simd: 3722 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 3723 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3724 AllowedNameModifiers.push_back(OMPD_parallel); 3725 break; 3726 case OMPD_teams_distribute_parallel_for: 3727 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 3728 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3729 AllowedNameModifiers.push_back(OMPD_parallel); 3730 break; 3731 case OMPD_target_teams: 3732 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 3733 EndLoc); 3734 AllowedNameModifiers.push_back(OMPD_target); 3735 break; 3736 case OMPD_target_teams_distribute: 3737 Res = ActOnOpenMPTargetTeamsDistributeDirective( 3738 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3739 AllowedNameModifiers.push_back(OMPD_target); 3740 break; 3741 case OMPD_target_teams_distribute_parallel_for: 3742 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 3743 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3744 AllowedNameModifiers.push_back(OMPD_target); 3745 AllowedNameModifiers.push_back(OMPD_parallel); 3746 break; 3747 case OMPD_target_teams_distribute_parallel_for_simd: 3748 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 3749 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3750 AllowedNameModifiers.push_back(OMPD_target); 3751 AllowedNameModifiers.push_back(OMPD_parallel); 3752 break; 3753 case OMPD_target_teams_distribute_simd: 3754 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 3755 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3756 AllowedNameModifiers.push_back(OMPD_target); 3757 break; 3758 case OMPD_declare_target: 3759 case OMPD_end_declare_target: 3760 case OMPD_threadprivate: 3761 case OMPD_allocate: 3762 case OMPD_declare_reduction: 3763 case OMPD_declare_mapper: 3764 case OMPD_declare_simd: 3765 case OMPD_requires: 3766 llvm_unreachable("OpenMP Directive is not allowed"); 3767 case OMPD_unknown: 3768 llvm_unreachable("Unknown OpenMP directive"); 3769 } 3770 3771 for (const auto &P : VarsWithInheritedDSA) { 3772 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 3773 << P.first << P.second->getSourceRange(); 3774 } 3775 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 3776 3777 if (!AllowedNameModifiers.empty()) 3778 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 3779 ErrorFound; 3780 3781 if (ErrorFound) 3782 return StmtError(); 3783 return Res; 3784 } 3785 3786 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 3787 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 3788 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 3789 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 3790 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 3791 assert(Aligneds.size() == Alignments.size()); 3792 assert(Linears.size() == LinModifiers.size()); 3793 assert(Linears.size() == Steps.size()); 3794 if (!DG || DG.get().isNull()) 3795 return DeclGroupPtrTy(); 3796 3797 if (!DG.get().isSingleDecl()) { 3798 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 3799 return DG; 3800 } 3801 Decl *ADecl = DG.get().getSingleDecl(); 3802 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 3803 ADecl = FTD->getTemplatedDecl(); 3804 3805 auto *FD = dyn_cast<FunctionDecl>(ADecl); 3806 if (!FD) { 3807 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 3808 return DeclGroupPtrTy(); 3809 } 3810 3811 // OpenMP [2.8.2, declare simd construct, Description] 3812 // The parameter of the simdlen clause must be a constant positive integer 3813 // expression. 3814 ExprResult SL; 3815 if (Simdlen) 3816 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 3817 // OpenMP [2.8.2, declare simd construct, Description] 3818 // The special this pointer can be used as if was one of the arguments to the 3819 // function in any of the linear, aligned, or uniform clauses. 3820 // The uniform clause declares one or more arguments to have an invariant 3821 // value for all concurrent invocations of the function in the execution of a 3822 // single SIMD loop. 3823 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 3824 const Expr *UniformedLinearThis = nullptr; 3825 for (const Expr *E : Uniforms) { 3826 E = E->IgnoreParenImpCasts(); 3827 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 3828 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 3829 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3830 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3831 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 3832 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 3833 continue; 3834 } 3835 if (isa<CXXThisExpr>(E)) { 3836 UniformedLinearThis = E; 3837 continue; 3838 } 3839 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3840 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3841 } 3842 // OpenMP [2.8.2, declare simd construct, Description] 3843 // The aligned clause declares that the object to which each list item points 3844 // is aligned to the number of bytes expressed in the optional parameter of 3845 // the aligned clause. 3846 // The special this pointer can be used as if was one of the arguments to the 3847 // function in any of the linear, aligned, or uniform clauses. 3848 // The type of list items appearing in the aligned clause must be array, 3849 // pointer, reference to array, or reference to pointer. 3850 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 3851 const Expr *AlignedThis = nullptr; 3852 for (const Expr *E : Aligneds) { 3853 E = E->IgnoreParenImpCasts(); 3854 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 3855 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3856 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 3857 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3858 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3859 ->getCanonicalDecl() == CanonPVD) { 3860 // OpenMP [2.8.1, simd construct, Restrictions] 3861 // A list-item cannot appear in more than one aligned clause. 3862 if (AlignedArgs.count(CanonPVD) > 0) { 3863 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3864 << 1 << E->getSourceRange(); 3865 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 3866 diag::note_omp_explicit_dsa) 3867 << getOpenMPClauseName(OMPC_aligned); 3868 continue; 3869 } 3870 AlignedArgs[CanonPVD] = E; 3871 QualType QTy = PVD->getType() 3872 .getNonReferenceType() 3873 .getUnqualifiedType() 3874 .getCanonicalType(); 3875 const Type *Ty = QTy.getTypePtrOrNull(); 3876 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 3877 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 3878 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 3879 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 3880 } 3881 continue; 3882 } 3883 } 3884 if (isa<CXXThisExpr>(E)) { 3885 if (AlignedThis) { 3886 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3887 << 2 << E->getSourceRange(); 3888 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 3889 << getOpenMPClauseName(OMPC_aligned); 3890 } 3891 AlignedThis = E; 3892 continue; 3893 } 3894 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3895 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3896 } 3897 // The optional parameter of the aligned clause, alignment, must be a constant 3898 // positive integer expression. If no optional parameter is specified, 3899 // implementation-defined default alignments for SIMD instructions on the 3900 // target platforms are assumed. 3901 SmallVector<const Expr *, 4> NewAligns; 3902 for (Expr *E : Alignments) { 3903 ExprResult Align; 3904 if (E) 3905 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 3906 NewAligns.push_back(Align.get()); 3907 } 3908 // OpenMP [2.8.2, declare simd construct, Description] 3909 // The linear clause declares one or more list items to be private to a SIMD 3910 // lane and to have a linear relationship with respect to the iteration space 3911 // of a loop. 3912 // The special this pointer can be used as if was one of the arguments to the 3913 // function in any of the linear, aligned, or uniform clauses. 3914 // When a linear-step expression is specified in a linear clause it must be 3915 // either a constant integer expression or an integer-typed parameter that is 3916 // specified in a uniform clause on the directive. 3917 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 3918 const bool IsUniformedThis = UniformedLinearThis != nullptr; 3919 auto MI = LinModifiers.begin(); 3920 for (const Expr *E : Linears) { 3921 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 3922 ++MI; 3923 E = E->IgnoreParenImpCasts(); 3924 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 3925 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3926 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 3927 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3928 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3929 ->getCanonicalDecl() == CanonPVD) { 3930 // OpenMP [2.15.3.7, linear Clause, Restrictions] 3931 // A list-item cannot appear in more than one linear clause. 3932 if (LinearArgs.count(CanonPVD) > 0) { 3933 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3934 << getOpenMPClauseName(OMPC_linear) 3935 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 3936 Diag(LinearArgs[CanonPVD]->getExprLoc(), 3937 diag::note_omp_explicit_dsa) 3938 << getOpenMPClauseName(OMPC_linear); 3939 continue; 3940 } 3941 // Each argument can appear in at most one uniform or linear clause. 3942 if (UniformedArgs.count(CanonPVD) > 0) { 3943 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3944 << getOpenMPClauseName(OMPC_linear) 3945 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 3946 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 3947 diag::note_omp_explicit_dsa) 3948 << getOpenMPClauseName(OMPC_uniform); 3949 continue; 3950 } 3951 LinearArgs[CanonPVD] = E; 3952 if (E->isValueDependent() || E->isTypeDependent() || 3953 E->isInstantiationDependent() || 3954 E->containsUnexpandedParameterPack()) 3955 continue; 3956 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 3957 PVD->getOriginalType()); 3958 continue; 3959 } 3960 } 3961 if (isa<CXXThisExpr>(E)) { 3962 if (UniformedLinearThis) { 3963 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3964 << getOpenMPClauseName(OMPC_linear) 3965 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 3966 << E->getSourceRange(); 3967 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 3968 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 3969 : OMPC_linear); 3970 continue; 3971 } 3972 UniformedLinearThis = E; 3973 if (E->isValueDependent() || E->isTypeDependent() || 3974 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3975 continue; 3976 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 3977 E->getType()); 3978 continue; 3979 } 3980 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3981 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3982 } 3983 Expr *Step = nullptr; 3984 Expr *NewStep = nullptr; 3985 SmallVector<Expr *, 4> NewSteps; 3986 for (Expr *E : Steps) { 3987 // Skip the same step expression, it was checked already. 3988 if (Step == E || !E) { 3989 NewSteps.push_back(E ? NewStep : nullptr); 3990 continue; 3991 } 3992 Step = E; 3993 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 3994 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3995 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 3996 if (UniformedArgs.count(CanonPVD) == 0) { 3997 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 3998 << Step->getSourceRange(); 3999 } else if (E->isValueDependent() || E->isTypeDependent() || 4000 E->isInstantiationDependent() || 4001 E->containsUnexpandedParameterPack() || 4002 CanonPVD->getType()->hasIntegerRepresentation()) { 4003 NewSteps.push_back(Step); 4004 } else { 4005 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 4006 << Step->getSourceRange(); 4007 } 4008 continue; 4009 } 4010 NewStep = Step; 4011 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 4012 !Step->isInstantiationDependent() && 4013 !Step->containsUnexpandedParameterPack()) { 4014 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 4015 .get(); 4016 if (NewStep) 4017 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 4018 } 4019 NewSteps.push_back(NewStep); 4020 } 4021 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 4022 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 4023 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 4024 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 4025 const_cast<Expr **>(Linears.data()), Linears.size(), 4026 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 4027 NewSteps.data(), NewSteps.size(), SR); 4028 ADecl->addAttr(NewAttr); 4029 return ConvertDeclToDeclGroup(ADecl); 4030 } 4031 4032 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 4033 Stmt *AStmt, 4034 SourceLocation StartLoc, 4035 SourceLocation EndLoc) { 4036 if (!AStmt) 4037 return StmtError(); 4038 4039 auto *CS = cast<CapturedStmt>(AStmt); 4040 // 1.2.2 OpenMP Language Terminology 4041 // Structured block - An executable statement with a single entry at the 4042 // top and a single exit at the bottom. 4043 // The point of exit cannot be a branch out of the structured block. 4044 // longjmp() and throw() must not violate the entry/exit criteria. 4045 CS->getCapturedDecl()->setNothrow(); 4046 4047 setFunctionHasBranchProtectedScope(); 4048 4049 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4050 DSAStack->isCancelRegion()); 4051 } 4052 4053 namespace { 4054 /// Helper class for checking canonical form of the OpenMP loops and 4055 /// extracting iteration space of each loop in the loop nest, that will be used 4056 /// for IR generation. 4057 class OpenMPIterationSpaceChecker { 4058 /// Reference to Sema. 4059 Sema &SemaRef; 4060 /// A location for diagnostics (when there is no some better location). 4061 SourceLocation DefaultLoc; 4062 /// A location for diagnostics (when increment is not compatible). 4063 SourceLocation ConditionLoc; 4064 /// A source location for referring to loop init later. 4065 SourceRange InitSrcRange; 4066 /// A source location for referring to condition later. 4067 SourceRange ConditionSrcRange; 4068 /// A source location for referring to increment later. 4069 SourceRange IncrementSrcRange; 4070 /// Loop variable. 4071 ValueDecl *LCDecl = nullptr; 4072 /// Reference to loop variable. 4073 Expr *LCRef = nullptr; 4074 /// Lower bound (initializer for the var). 4075 Expr *LB = nullptr; 4076 /// Upper bound. 4077 Expr *UB = nullptr; 4078 /// Loop step (increment). 4079 Expr *Step = nullptr; 4080 /// This flag is true when condition is one of: 4081 /// Var < UB 4082 /// Var <= UB 4083 /// UB > Var 4084 /// UB >= Var 4085 /// This will have no value when the condition is != 4086 llvm::Optional<bool> TestIsLessOp; 4087 /// This flag is true when condition is strict ( < or > ). 4088 bool TestIsStrictOp = false; 4089 /// This flag is true when step is subtracted on each iteration. 4090 bool SubtractStep = false; 4091 4092 public: 4093 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 4094 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 4095 /// Check init-expr for canonical loop form and save loop counter 4096 /// variable - #Var and its initialization value - #LB. 4097 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 4098 /// Check test-expr for canonical form, save upper-bound (#UB), flags 4099 /// for less/greater and for strict/non-strict comparison. 4100 bool checkAndSetCond(Expr *S); 4101 /// Check incr-expr for canonical loop form and return true if it 4102 /// does not conform, otherwise save loop step (#Step). 4103 bool checkAndSetInc(Expr *S); 4104 /// Return the loop counter variable. 4105 ValueDecl *getLoopDecl() const { return LCDecl; } 4106 /// Return the reference expression to loop counter variable. 4107 Expr *getLoopDeclRefExpr() const { return LCRef; } 4108 /// Source range of the loop init. 4109 SourceRange getInitSrcRange() const { return InitSrcRange; } 4110 /// Source range of the loop condition. 4111 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 4112 /// Source range of the loop increment. 4113 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 4114 /// True if the step should be subtracted. 4115 bool shouldSubtractStep() const { return SubtractStep; } 4116 /// True, if the compare operator is strict (<, > or !=). 4117 bool isStrictTestOp() const { return TestIsStrictOp; } 4118 /// Build the expression to calculate the number of iterations. 4119 Expr *buildNumIterations( 4120 Scope *S, const bool LimitedType, 4121 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 4122 /// Build the precondition expression for the loops. 4123 Expr * 4124 buildPreCond(Scope *S, Expr *Cond, 4125 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 4126 /// Build reference expression to the counter be used for codegen. 4127 DeclRefExpr * 4128 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 4129 DSAStackTy &DSA) const; 4130 /// Build reference expression to the private counter be used for 4131 /// codegen. 4132 Expr *buildPrivateCounterVar() const; 4133 /// Build initialization of the counter be used for codegen. 4134 Expr *buildCounterInit() const; 4135 /// Build step of the counter be used for codegen. 4136 Expr *buildCounterStep() const; 4137 /// Build loop data with counter value for depend clauses in ordered 4138 /// directives. 4139 Expr * 4140 buildOrderedLoopData(Scope *S, Expr *Counter, 4141 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 4142 SourceLocation Loc, Expr *Inc = nullptr, 4143 OverloadedOperatorKind OOK = OO_Amp); 4144 /// Return true if any expression is dependent. 4145 bool dependent() const; 4146 4147 private: 4148 /// Check the right-hand side of an assignment in the increment 4149 /// expression. 4150 bool checkAndSetIncRHS(Expr *RHS); 4151 /// Helper to set loop counter variable and its initializer. 4152 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 4153 /// Helper to set upper bound. 4154 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 4155 SourceRange SR, SourceLocation SL); 4156 /// Helper to set loop increment. 4157 bool setStep(Expr *NewStep, bool Subtract); 4158 }; 4159 4160 bool OpenMPIterationSpaceChecker::dependent() const { 4161 if (!LCDecl) { 4162 assert(!LB && !UB && !Step); 4163 return false; 4164 } 4165 return LCDecl->getType()->isDependentType() || 4166 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 4167 (Step && Step->isValueDependent()); 4168 } 4169 4170 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 4171 Expr *NewLCRefExpr, 4172 Expr *NewLB) { 4173 // State consistency checking to ensure correct usage. 4174 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 4175 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 4176 if (!NewLCDecl || !NewLB) 4177 return true; 4178 LCDecl = getCanonicalDecl(NewLCDecl); 4179 LCRef = NewLCRefExpr; 4180 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 4181 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 4182 if ((Ctor->isCopyOrMoveConstructor() || 4183 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 4184 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 4185 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 4186 LB = NewLB; 4187 return false; 4188 } 4189 4190 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 4191 llvm::Optional<bool> LessOp, 4192 bool StrictOp, SourceRange SR, 4193 SourceLocation SL) { 4194 // State consistency checking to ensure correct usage. 4195 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 4196 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 4197 if (!NewUB) 4198 return true; 4199 UB = NewUB; 4200 if (LessOp) 4201 TestIsLessOp = LessOp; 4202 TestIsStrictOp = StrictOp; 4203 ConditionSrcRange = SR; 4204 ConditionLoc = SL; 4205 return false; 4206 } 4207 4208 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 4209 // State consistency checking to ensure correct usage. 4210 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 4211 if (!NewStep) 4212 return true; 4213 if (!NewStep->isValueDependent()) { 4214 // Check that the step is integer expression. 4215 SourceLocation StepLoc = NewStep->getBeginLoc(); 4216 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 4217 StepLoc, getExprAsWritten(NewStep)); 4218 if (Val.isInvalid()) 4219 return true; 4220 NewStep = Val.get(); 4221 4222 // OpenMP [2.6, Canonical Loop Form, Restrictions] 4223 // If test-expr is of form var relational-op b and relational-op is < or 4224 // <= then incr-expr must cause var to increase on each iteration of the 4225 // loop. If test-expr is of form var relational-op b and relational-op is 4226 // > or >= then incr-expr must cause var to decrease on each iteration of 4227 // the loop. 4228 // If test-expr is of form b relational-op var and relational-op is < or 4229 // <= then incr-expr must cause var to decrease on each iteration of the 4230 // loop. If test-expr is of form b relational-op var and relational-op is 4231 // > or >= then incr-expr must cause var to increase on each iteration of 4232 // the loop. 4233 llvm::APSInt Result; 4234 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 4235 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 4236 bool IsConstNeg = 4237 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 4238 bool IsConstPos = 4239 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 4240 bool IsConstZero = IsConstant && !Result.getBoolValue(); 4241 4242 // != with increment is treated as <; != with decrement is treated as > 4243 if (!TestIsLessOp.hasValue()) 4244 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 4245 if (UB && (IsConstZero || 4246 (TestIsLessOp.getValue() ? 4247 (IsConstNeg || (IsUnsigned && Subtract)) : 4248 (IsConstPos || (IsUnsigned && !Subtract))))) { 4249 SemaRef.Diag(NewStep->getExprLoc(), 4250 diag::err_omp_loop_incr_not_compatible) 4251 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 4252 SemaRef.Diag(ConditionLoc, 4253 diag::note_omp_loop_cond_requres_compatible_incr) 4254 << TestIsLessOp.getValue() << ConditionSrcRange; 4255 return true; 4256 } 4257 if (TestIsLessOp.getValue() == Subtract) { 4258 NewStep = 4259 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 4260 .get(); 4261 Subtract = !Subtract; 4262 } 4263 } 4264 4265 Step = NewStep; 4266 SubtractStep = Subtract; 4267 return false; 4268 } 4269 4270 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 4271 // Check init-expr for canonical loop form and save loop counter 4272 // variable - #Var and its initialization value - #LB. 4273 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 4274 // var = lb 4275 // integer-type var = lb 4276 // random-access-iterator-type var = lb 4277 // pointer-type var = lb 4278 // 4279 if (!S) { 4280 if (EmitDiags) { 4281 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 4282 } 4283 return true; 4284 } 4285 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 4286 if (!ExprTemp->cleanupsHaveSideEffects()) 4287 S = ExprTemp->getSubExpr(); 4288 4289 InitSrcRange = S->getSourceRange(); 4290 if (Expr *E = dyn_cast<Expr>(S)) 4291 S = E->IgnoreParens(); 4292 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 4293 if (BO->getOpcode() == BO_Assign) { 4294 Expr *LHS = BO->getLHS()->IgnoreParens(); 4295 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 4296 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 4297 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4298 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4299 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 4300 } 4301 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 4302 if (ME->isArrow() && 4303 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4304 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4305 } 4306 } 4307 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 4308 if (DS->isSingleDecl()) { 4309 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 4310 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 4311 // Accept non-canonical init form here but emit ext. warning. 4312 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 4313 SemaRef.Diag(S->getBeginLoc(), 4314 diag::ext_omp_loop_not_canonical_init) 4315 << S->getSourceRange(); 4316 return setLCDeclAndLB( 4317 Var, 4318 buildDeclRefExpr(SemaRef, Var, 4319 Var->getType().getNonReferenceType(), 4320 DS->getBeginLoc()), 4321 Var->getInit()); 4322 } 4323 } 4324 } 4325 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4326 if (CE->getOperator() == OO_Equal) { 4327 Expr *LHS = CE->getArg(0); 4328 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 4329 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 4330 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4331 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4332 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 4333 } 4334 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 4335 if (ME->isArrow() && 4336 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4337 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4338 } 4339 } 4340 } 4341 4342 if (dependent() || SemaRef.CurContext->isDependentContext()) 4343 return false; 4344 if (EmitDiags) { 4345 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 4346 << S->getSourceRange(); 4347 } 4348 return true; 4349 } 4350 4351 /// Ignore parenthesizes, implicit casts, copy constructor and return the 4352 /// variable (which may be the loop variable) if possible. 4353 static const ValueDecl *getInitLCDecl(const Expr *E) { 4354 if (!E) 4355 return nullptr; 4356 E = getExprAsWritten(E); 4357 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 4358 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 4359 if ((Ctor->isCopyOrMoveConstructor() || 4360 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 4361 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 4362 E = CE->getArg(0)->IgnoreParenImpCasts(); 4363 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 4364 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 4365 return getCanonicalDecl(VD); 4366 } 4367 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 4368 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4369 return getCanonicalDecl(ME->getMemberDecl()); 4370 return nullptr; 4371 } 4372 4373 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 4374 // Check test-expr for canonical form, save upper-bound UB, flags for 4375 // less/greater and for strict/non-strict comparison. 4376 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 4377 // var relational-op b 4378 // b relational-op var 4379 // 4380 if (!S) { 4381 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 4382 return true; 4383 } 4384 S = getExprAsWritten(S); 4385 SourceLocation CondLoc = S->getBeginLoc(); 4386 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 4387 if (BO->isRelationalOp()) { 4388 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4389 return setUB(BO->getRHS(), 4390 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 4391 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 4392 BO->getSourceRange(), BO->getOperatorLoc()); 4393 if (getInitLCDecl(BO->getRHS()) == LCDecl) 4394 return setUB(BO->getLHS(), 4395 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 4396 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 4397 BO->getSourceRange(), BO->getOperatorLoc()); 4398 } else if (BO->getOpcode() == BO_NE) 4399 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ? 4400 BO->getRHS() : BO->getLHS(), 4401 /*LessOp=*/llvm::None, 4402 /*StrictOp=*/true, 4403 BO->getSourceRange(), BO->getOperatorLoc()); 4404 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4405 if (CE->getNumArgs() == 2) { 4406 auto Op = CE->getOperator(); 4407 switch (Op) { 4408 case OO_Greater: 4409 case OO_GreaterEqual: 4410 case OO_Less: 4411 case OO_LessEqual: 4412 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4413 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 4414 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 4415 CE->getOperatorLoc()); 4416 if (getInitLCDecl(CE->getArg(1)) == LCDecl) 4417 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 4418 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 4419 CE->getOperatorLoc()); 4420 break; 4421 case OO_ExclaimEqual: 4422 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? 4423 CE->getArg(1) : CE->getArg(0), 4424 /*LessOp=*/llvm::None, 4425 /*StrictOp=*/true, 4426 CE->getSourceRange(), 4427 CE->getOperatorLoc()); 4428 break; 4429 default: 4430 break; 4431 } 4432 } 4433 } 4434 if (dependent() || SemaRef.CurContext->isDependentContext()) 4435 return false; 4436 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 4437 << S->getSourceRange() << LCDecl; 4438 return true; 4439 } 4440 4441 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 4442 // RHS of canonical loop form increment can be: 4443 // var + incr 4444 // incr + var 4445 // var - incr 4446 // 4447 RHS = RHS->IgnoreParenImpCasts(); 4448 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 4449 if (BO->isAdditiveOp()) { 4450 bool IsAdd = BO->getOpcode() == BO_Add; 4451 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4452 return setStep(BO->getRHS(), !IsAdd); 4453 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 4454 return setStep(BO->getLHS(), /*Subtract=*/false); 4455 } 4456 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 4457 bool IsAdd = CE->getOperator() == OO_Plus; 4458 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 4459 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4460 return setStep(CE->getArg(1), !IsAdd); 4461 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 4462 return setStep(CE->getArg(0), /*Subtract=*/false); 4463 } 4464 } 4465 if (dependent() || SemaRef.CurContext->isDependentContext()) 4466 return false; 4467 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 4468 << RHS->getSourceRange() << LCDecl; 4469 return true; 4470 } 4471 4472 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 4473 // Check incr-expr for canonical loop form and return true if it 4474 // does not conform. 4475 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 4476 // ++var 4477 // var++ 4478 // --var 4479 // var-- 4480 // var += incr 4481 // var -= incr 4482 // var = var + incr 4483 // var = incr + var 4484 // var = var - incr 4485 // 4486 if (!S) { 4487 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 4488 return true; 4489 } 4490 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 4491 if (!ExprTemp->cleanupsHaveSideEffects()) 4492 S = ExprTemp->getSubExpr(); 4493 4494 IncrementSrcRange = S->getSourceRange(); 4495 S = S->IgnoreParens(); 4496 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 4497 if (UO->isIncrementDecrementOp() && 4498 getInitLCDecl(UO->getSubExpr()) == LCDecl) 4499 return setStep(SemaRef 4500 .ActOnIntegerConstant(UO->getBeginLoc(), 4501 (UO->isDecrementOp() ? -1 : 1)) 4502 .get(), 4503 /*Subtract=*/false); 4504 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 4505 switch (BO->getOpcode()) { 4506 case BO_AddAssign: 4507 case BO_SubAssign: 4508 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4509 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 4510 break; 4511 case BO_Assign: 4512 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4513 return checkAndSetIncRHS(BO->getRHS()); 4514 break; 4515 default: 4516 break; 4517 } 4518 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4519 switch (CE->getOperator()) { 4520 case OO_PlusPlus: 4521 case OO_MinusMinus: 4522 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4523 return setStep(SemaRef 4524 .ActOnIntegerConstant( 4525 CE->getBeginLoc(), 4526 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 4527 .get(), 4528 /*Subtract=*/false); 4529 break; 4530 case OO_PlusEqual: 4531 case OO_MinusEqual: 4532 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4533 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 4534 break; 4535 case OO_Equal: 4536 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4537 return checkAndSetIncRHS(CE->getArg(1)); 4538 break; 4539 default: 4540 break; 4541 } 4542 } 4543 if (dependent() || SemaRef.CurContext->isDependentContext()) 4544 return false; 4545 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 4546 << S->getSourceRange() << LCDecl; 4547 return true; 4548 } 4549 4550 static ExprResult 4551 tryBuildCapture(Sema &SemaRef, Expr *Capture, 4552 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 4553 if (SemaRef.CurContext->isDependentContext()) 4554 return ExprResult(Capture); 4555 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 4556 return SemaRef.PerformImplicitConversion( 4557 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 4558 /*AllowExplicit=*/true); 4559 auto I = Captures.find(Capture); 4560 if (I != Captures.end()) 4561 return buildCapture(SemaRef, Capture, I->second); 4562 DeclRefExpr *Ref = nullptr; 4563 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 4564 Captures[Capture] = Ref; 4565 return Res; 4566 } 4567 4568 /// Build the expression to calculate the number of iterations. 4569 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 4570 Scope *S, const bool LimitedType, 4571 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 4572 ExprResult Diff; 4573 QualType VarType = LCDecl->getType().getNonReferenceType(); 4574 if (VarType->isIntegerType() || VarType->isPointerType() || 4575 SemaRef.getLangOpts().CPlusPlus) { 4576 // Upper - Lower 4577 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 4578 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 4579 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 4580 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 4581 if (!Upper || !Lower) 4582 return nullptr; 4583 4584 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 4585 4586 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 4587 // BuildBinOp already emitted error, this one is to point user to upper 4588 // and lower bound, and to tell what is passed to 'operator-'. 4589 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 4590 << Upper->getSourceRange() << Lower->getSourceRange(); 4591 return nullptr; 4592 } 4593 } 4594 4595 if (!Diff.isUsable()) 4596 return nullptr; 4597 4598 // Upper - Lower [- 1] 4599 if (TestIsStrictOp) 4600 Diff = SemaRef.BuildBinOp( 4601 S, DefaultLoc, BO_Sub, Diff.get(), 4602 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4603 if (!Diff.isUsable()) 4604 return nullptr; 4605 4606 // Upper - Lower [- 1] + Step 4607 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 4608 if (!NewStep.isUsable()) 4609 return nullptr; 4610 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 4611 if (!Diff.isUsable()) 4612 return nullptr; 4613 4614 // Parentheses (for dumping/debugging purposes only). 4615 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 4616 if (!Diff.isUsable()) 4617 return nullptr; 4618 4619 // (Upper - Lower [- 1] + Step) / Step 4620 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 4621 if (!Diff.isUsable()) 4622 return nullptr; 4623 4624 // OpenMP runtime requires 32-bit or 64-bit loop variables. 4625 QualType Type = Diff.get()->getType(); 4626 ASTContext &C = SemaRef.Context; 4627 bool UseVarType = VarType->hasIntegerRepresentation() && 4628 C.getTypeSize(Type) > C.getTypeSize(VarType); 4629 if (!Type->isIntegerType() || UseVarType) { 4630 unsigned NewSize = 4631 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 4632 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 4633 : Type->hasSignedIntegerRepresentation(); 4634 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 4635 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 4636 Diff = SemaRef.PerformImplicitConversion( 4637 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 4638 if (!Diff.isUsable()) 4639 return nullptr; 4640 } 4641 } 4642 if (LimitedType) { 4643 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 4644 if (NewSize != C.getTypeSize(Type)) { 4645 if (NewSize < C.getTypeSize(Type)) { 4646 assert(NewSize == 64 && "incorrect loop var size"); 4647 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 4648 << InitSrcRange << ConditionSrcRange; 4649 } 4650 QualType NewType = C.getIntTypeForBitwidth( 4651 NewSize, Type->hasSignedIntegerRepresentation() || 4652 C.getTypeSize(Type) < NewSize); 4653 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 4654 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 4655 Sema::AA_Converting, true); 4656 if (!Diff.isUsable()) 4657 return nullptr; 4658 } 4659 } 4660 } 4661 4662 return Diff.get(); 4663 } 4664 4665 Expr *OpenMPIterationSpaceChecker::buildPreCond( 4666 Scope *S, Expr *Cond, 4667 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 4668 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 4669 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4670 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4671 4672 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 4673 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 4674 if (!NewLB.isUsable() || !NewUB.isUsable()) 4675 return nullptr; 4676 4677 ExprResult CondExpr = 4678 SemaRef.BuildBinOp(S, DefaultLoc, 4679 TestIsLessOp.getValue() ? 4680 (TestIsStrictOp ? BO_LT : BO_LE) : 4681 (TestIsStrictOp ? BO_GT : BO_GE), 4682 NewLB.get(), NewUB.get()); 4683 if (CondExpr.isUsable()) { 4684 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 4685 SemaRef.Context.BoolTy)) 4686 CondExpr = SemaRef.PerformImplicitConversion( 4687 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 4688 /*AllowExplicit=*/true); 4689 } 4690 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4691 // Otherwise use original loop condition and evaluate it in runtime. 4692 return CondExpr.isUsable() ? CondExpr.get() : Cond; 4693 } 4694 4695 /// Build reference expression to the counter be used for codegen. 4696 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 4697 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 4698 DSAStackTy &DSA) const { 4699 auto *VD = dyn_cast<VarDecl>(LCDecl); 4700 if (!VD) { 4701 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 4702 DeclRefExpr *Ref = buildDeclRefExpr( 4703 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 4704 const DSAStackTy::DSAVarData Data = 4705 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 4706 // If the loop control decl is explicitly marked as private, do not mark it 4707 // as captured again. 4708 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 4709 Captures.insert(std::make_pair(LCRef, Ref)); 4710 return Ref; 4711 } 4712 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 4713 DefaultLoc); 4714 } 4715 4716 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 4717 if (LCDecl && !LCDecl->isInvalidDecl()) { 4718 QualType Type = LCDecl->getType().getNonReferenceType(); 4719 VarDecl *PrivateVar = buildVarDecl( 4720 SemaRef, DefaultLoc, Type, LCDecl->getName(), 4721 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 4722 isa<VarDecl>(LCDecl) 4723 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 4724 : nullptr); 4725 if (PrivateVar->isInvalidDecl()) 4726 return nullptr; 4727 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 4728 } 4729 return nullptr; 4730 } 4731 4732 /// Build initialization of the counter to be used for codegen. 4733 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 4734 4735 /// Build step of the counter be used for codegen. 4736 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 4737 4738 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 4739 Scope *S, Expr *Counter, 4740 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 4741 Expr *Inc, OverloadedOperatorKind OOK) { 4742 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 4743 if (!Cnt) 4744 return nullptr; 4745 if (Inc) { 4746 assert((OOK == OO_Plus || OOK == OO_Minus) && 4747 "Expected only + or - operations for depend clauses."); 4748 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 4749 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 4750 if (!Cnt) 4751 return nullptr; 4752 } 4753 ExprResult Diff; 4754 QualType VarType = LCDecl->getType().getNonReferenceType(); 4755 if (VarType->isIntegerType() || VarType->isPointerType() || 4756 SemaRef.getLangOpts().CPlusPlus) { 4757 // Upper - Lower 4758 Expr *Upper = TestIsLessOp.getValue() 4759 ? Cnt 4760 : tryBuildCapture(SemaRef, UB, Captures).get(); 4761 Expr *Lower = TestIsLessOp.getValue() 4762 ? tryBuildCapture(SemaRef, LB, Captures).get() 4763 : Cnt; 4764 if (!Upper || !Lower) 4765 return nullptr; 4766 4767 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 4768 4769 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 4770 // BuildBinOp already emitted error, this one is to point user to upper 4771 // and lower bound, and to tell what is passed to 'operator-'. 4772 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 4773 << Upper->getSourceRange() << Lower->getSourceRange(); 4774 return nullptr; 4775 } 4776 } 4777 4778 if (!Diff.isUsable()) 4779 return nullptr; 4780 4781 // Parentheses (for dumping/debugging purposes only). 4782 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 4783 if (!Diff.isUsable()) 4784 return nullptr; 4785 4786 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 4787 if (!NewStep.isUsable()) 4788 return nullptr; 4789 // (Upper - Lower) / Step 4790 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 4791 if (!Diff.isUsable()) 4792 return nullptr; 4793 4794 return Diff.get(); 4795 } 4796 4797 /// Iteration space of a single for loop. 4798 struct LoopIterationSpace final { 4799 /// True if the condition operator is the strict compare operator (<, > or 4800 /// !=). 4801 bool IsStrictCompare = false; 4802 /// Condition of the loop. 4803 Expr *PreCond = nullptr; 4804 /// This expression calculates the number of iterations in the loop. 4805 /// It is always possible to calculate it before starting the loop. 4806 Expr *NumIterations = nullptr; 4807 /// The loop counter variable. 4808 Expr *CounterVar = nullptr; 4809 /// Private loop counter variable. 4810 Expr *PrivateCounterVar = nullptr; 4811 /// This is initializer for the initial value of #CounterVar. 4812 Expr *CounterInit = nullptr; 4813 /// This is step for the #CounterVar used to generate its update: 4814 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 4815 Expr *CounterStep = nullptr; 4816 /// Should step be subtracted? 4817 bool Subtract = false; 4818 /// Source range of the loop init. 4819 SourceRange InitSrcRange; 4820 /// Source range of the loop condition. 4821 SourceRange CondSrcRange; 4822 /// Source range of the loop increment. 4823 SourceRange IncSrcRange; 4824 }; 4825 4826 } // namespace 4827 4828 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 4829 assert(getLangOpts().OpenMP && "OpenMP is not active."); 4830 assert(Init && "Expected loop in canonical form."); 4831 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 4832 if (AssociatedLoops > 0 && 4833 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 4834 DSAStack->loopStart(); 4835 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 4836 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 4837 if (ValueDecl *D = ISC.getLoopDecl()) { 4838 auto *VD = dyn_cast<VarDecl>(D); 4839 if (!VD) { 4840 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 4841 VD = Private; 4842 } else { 4843 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 4844 /*WithInit=*/false); 4845 VD = cast<VarDecl>(Ref->getDecl()); 4846 } 4847 } 4848 DSAStack->addLoopControlVariable(D, VD); 4849 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 4850 if (LD != D->getCanonicalDecl()) { 4851 DSAStack->resetPossibleLoopCounter(); 4852 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 4853 MarkDeclarationsReferencedInExpr( 4854 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 4855 Var->getType().getNonLValueExprType(Context), 4856 ForLoc, /*RefersToCapture=*/true)); 4857 } 4858 } 4859 } 4860 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 4861 } 4862 } 4863 4864 /// Called on a for stmt to check and extract its iteration space 4865 /// for further processing (such as collapsing). 4866 static bool checkOpenMPIterationSpace( 4867 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 4868 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 4869 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 4870 Expr *OrderedLoopCountExpr, 4871 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 4872 LoopIterationSpace &ResultIterSpace, 4873 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 4874 // OpenMP [2.6, Canonical Loop Form] 4875 // for (init-expr; test-expr; incr-expr) structured-block 4876 auto *For = dyn_cast_or_null<ForStmt>(S); 4877 if (!For) { 4878 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 4879 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 4880 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 4881 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 4882 if (TotalNestedLoopCount > 1) { 4883 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 4884 SemaRef.Diag(DSA.getConstructLoc(), 4885 diag::note_omp_collapse_ordered_expr) 4886 << 2 << CollapseLoopCountExpr->getSourceRange() 4887 << OrderedLoopCountExpr->getSourceRange(); 4888 else if (CollapseLoopCountExpr) 4889 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4890 diag::note_omp_collapse_ordered_expr) 4891 << 0 << CollapseLoopCountExpr->getSourceRange(); 4892 else 4893 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4894 diag::note_omp_collapse_ordered_expr) 4895 << 1 << OrderedLoopCountExpr->getSourceRange(); 4896 } 4897 return true; 4898 } 4899 assert(For->getBody()); 4900 4901 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 4902 4903 // Check init. 4904 Stmt *Init = For->getInit(); 4905 if (ISC.checkAndSetInit(Init)) 4906 return true; 4907 4908 bool HasErrors = false; 4909 4910 // Check loop variable's type. 4911 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 4912 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 4913 4914 // OpenMP [2.6, Canonical Loop Form] 4915 // Var is one of the following: 4916 // A variable of signed or unsigned integer type. 4917 // For C++, a variable of a random access iterator type. 4918 // For C, a variable of a pointer type. 4919 QualType VarType = LCDecl->getType().getNonReferenceType(); 4920 if (!VarType->isDependentType() && !VarType->isIntegerType() && 4921 !VarType->isPointerType() && 4922 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 4923 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 4924 << SemaRef.getLangOpts().CPlusPlus; 4925 HasErrors = true; 4926 } 4927 4928 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 4929 // a Construct 4930 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4931 // parallel for construct is (are) private. 4932 // The loop iteration variable in the associated for-loop of a simd 4933 // construct with just one associated for-loop is linear with a 4934 // constant-linear-step that is the increment of the associated for-loop. 4935 // Exclude loop var from the list of variables with implicitly defined data 4936 // sharing attributes. 4937 VarsWithImplicitDSA.erase(LCDecl); 4938 4939 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4940 // in a Construct, C/C++]. 4941 // The loop iteration variable in the associated for-loop of a simd 4942 // construct with just one associated for-loop may be listed in a linear 4943 // clause with a constant-linear-step that is the increment of the 4944 // associated for-loop. 4945 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4946 // parallel for construct may be listed in a private or lastprivate clause. 4947 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 4948 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 4949 // declared in the loop and it is predetermined as a private. 4950 OpenMPClauseKind PredeterminedCKind = 4951 isOpenMPSimdDirective(DKind) 4952 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 4953 : OMPC_private; 4954 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4955 DVar.CKind != PredeterminedCKind) || 4956 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 4957 isOpenMPDistributeDirective(DKind)) && 4958 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4959 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 4960 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 4961 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 4962 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 4963 << getOpenMPClauseName(PredeterminedCKind); 4964 if (DVar.RefExpr == nullptr) 4965 DVar.CKind = PredeterminedCKind; 4966 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 4967 HasErrors = true; 4968 } else if (LoopDeclRefExpr != nullptr) { 4969 // Make the loop iteration variable private (for worksharing constructs), 4970 // linear (for simd directives with the only one associated loop) or 4971 // lastprivate (for simd directives with several collapsed or ordered 4972 // loops). 4973 if (DVar.CKind == OMPC_unknown) 4974 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 4975 } 4976 4977 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 4978 4979 // Check test-expr. 4980 HasErrors |= ISC.checkAndSetCond(For->getCond()); 4981 4982 // Check incr-expr. 4983 HasErrors |= ISC.checkAndSetInc(For->getInc()); 4984 } 4985 4986 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 4987 return HasErrors; 4988 4989 // Build the loop's iteration space representation. 4990 ResultIterSpace.PreCond = 4991 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures); 4992 ResultIterSpace.NumIterations = ISC.buildNumIterations( 4993 DSA.getCurScope(), 4994 (isOpenMPWorksharingDirective(DKind) || 4995 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 4996 Captures); 4997 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA); 4998 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar(); 4999 ResultIterSpace.CounterInit = ISC.buildCounterInit(); 5000 ResultIterSpace.CounterStep = ISC.buildCounterStep(); 5001 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange(); 5002 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange(); 5003 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange(); 5004 ResultIterSpace.Subtract = ISC.shouldSubtractStep(); 5005 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp(); 5006 5007 HasErrors |= (ResultIterSpace.PreCond == nullptr || 5008 ResultIterSpace.NumIterations == nullptr || 5009 ResultIterSpace.CounterVar == nullptr || 5010 ResultIterSpace.PrivateCounterVar == nullptr || 5011 ResultIterSpace.CounterInit == nullptr || 5012 ResultIterSpace.CounterStep == nullptr); 5013 if (!HasErrors && DSA.isOrderedRegion()) { 5014 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 5015 if (CurrentNestedLoopCount < 5016 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 5017 DSA.getOrderedRegionParam().second->setLoopNumIterations( 5018 CurrentNestedLoopCount, ResultIterSpace.NumIterations); 5019 DSA.getOrderedRegionParam().second->setLoopCounter( 5020 CurrentNestedLoopCount, ResultIterSpace.CounterVar); 5021 } 5022 } 5023 for (auto &Pair : DSA.getDoacrossDependClauses()) { 5024 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 5025 // Erroneous case - clause has some problems. 5026 continue; 5027 } 5028 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 5029 Pair.second.size() <= CurrentNestedLoopCount) { 5030 // Erroneous case - clause has some problems. 5031 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 5032 continue; 5033 } 5034 Expr *CntValue; 5035 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 5036 CntValue = ISC.buildOrderedLoopData( 5037 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures, 5038 Pair.first->getDependencyLoc()); 5039 else 5040 CntValue = ISC.buildOrderedLoopData( 5041 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures, 5042 Pair.first->getDependencyLoc(), 5043 Pair.second[CurrentNestedLoopCount].first, 5044 Pair.second[CurrentNestedLoopCount].second); 5045 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 5046 } 5047 } 5048 5049 return HasErrors; 5050 } 5051 5052 /// Build 'VarRef = Start. 5053 static ExprResult 5054 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 5055 ExprResult Start, 5056 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 5057 // Build 'VarRef = Start. 5058 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 5059 if (!NewStart.isUsable()) 5060 return ExprError(); 5061 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 5062 VarRef.get()->getType())) { 5063 NewStart = SemaRef.PerformImplicitConversion( 5064 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 5065 /*AllowExplicit=*/true); 5066 if (!NewStart.isUsable()) 5067 return ExprError(); 5068 } 5069 5070 ExprResult Init = 5071 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 5072 return Init; 5073 } 5074 5075 /// Build 'VarRef = Start + Iter * Step'. 5076 static ExprResult buildCounterUpdate( 5077 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 5078 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 5079 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 5080 // Add parentheses (for debugging purposes only). 5081 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 5082 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 5083 !Step.isUsable()) 5084 return ExprError(); 5085 5086 ExprResult NewStep = Step; 5087 if (Captures) 5088 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 5089 if (NewStep.isInvalid()) 5090 return ExprError(); 5091 ExprResult Update = 5092 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 5093 if (!Update.isUsable()) 5094 return ExprError(); 5095 5096 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 5097 // 'VarRef = Start (+|-) Iter * Step'. 5098 ExprResult NewStart = Start; 5099 if (Captures) 5100 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 5101 if (NewStart.isInvalid()) 5102 return ExprError(); 5103 5104 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 5105 ExprResult SavedUpdate = Update; 5106 ExprResult UpdateVal; 5107 if (VarRef.get()->getType()->isOverloadableType() || 5108 NewStart.get()->getType()->isOverloadableType() || 5109 Update.get()->getType()->isOverloadableType()) { 5110 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 5111 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 5112 Update = 5113 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 5114 if (Update.isUsable()) { 5115 UpdateVal = 5116 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 5117 VarRef.get(), SavedUpdate.get()); 5118 if (UpdateVal.isUsable()) { 5119 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 5120 UpdateVal.get()); 5121 } 5122 } 5123 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 5124 } 5125 5126 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 5127 if (!Update.isUsable() || !UpdateVal.isUsable()) { 5128 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 5129 NewStart.get(), SavedUpdate.get()); 5130 if (!Update.isUsable()) 5131 return ExprError(); 5132 5133 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 5134 VarRef.get()->getType())) { 5135 Update = SemaRef.PerformImplicitConversion( 5136 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 5137 if (!Update.isUsable()) 5138 return ExprError(); 5139 } 5140 5141 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 5142 } 5143 return Update; 5144 } 5145 5146 /// Convert integer expression \a E to make it have at least \a Bits 5147 /// bits. 5148 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 5149 if (E == nullptr) 5150 return ExprError(); 5151 ASTContext &C = SemaRef.Context; 5152 QualType OldType = E->getType(); 5153 unsigned HasBits = C.getTypeSize(OldType); 5154 if (HasBits >= Bits) 5155 return ExprResult(E); 5156 // OK to convert to signed, because new type has more bits than old. 5157 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 5158 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 5159 true); 5160 } 5161 5162 /// Check if the given expression \a E is a constant integer that fits 5163 /// into \a Bits bits. 5164 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 5165 if (E == nullptr) 5166 return false; 5167 llvm::APSInt Result; 5168 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 5169 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 5170 return false; 5171 } 5172 5173 /// Build preinits statement for the given declarations. 5174 static Stmt *buildPreInits(ASTContext &Context, 5175 MutableArrayRef<Decl *> PreInits) { 5176 if (!PreInits.empty()) { 5177 return new (Context) DeclStmt( 5178 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 5179 SourceLocation(), SourceLocation()); 5180 } 5181 return nullptr; 5182 } 5183 5184 /// Build preinits statement for the given declarations. 5185 static Stmt * 5186 buildPreInits(ASTContext &Context, 5187 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 5188 if (!Captures.empty()) { 5189 SmallVector<Decl *, 16> PreInits; 5190 for (const auto &Pair : Captures) 5191 PreInits.push_back(Pair.second->getDecl()); 5192 return buildPreInits(Context, PreInits); 5193 } 5194 return nullptr; 5195 } 5196 5197 /// Build postupdate expression for the given list of postupdates expressions. 5198 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 5199 Expr *PostUpdate = nullptr; 5200 if (!PostUpdates.empty()) { 5201 for (Expr *E : PostUpdates) { 5202 Expr *ConvE = S.BuildCStyleCastExpr( 5203 E->getExprLoc(), 5204 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 5205 E->getExprLoc(), E) 5206 .get(); 5207 PostUpdate = PostUpdate 5208 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 5209 PostUpdate, ConvE) 5210 .get() 5211 : ConvE; 5212 } 5213 } 5214 return PostUpdate; 5215 } 5216 5217 /// Called on a for stmt to check itself and nested loops (if any). 5218 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 5219 /// number of collapsed loops otherwise. 5220 static unsigned 5221 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 5222 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 5223 DSAStackTy &DSA, 5224 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 5225 OMPLoopDirective::HelperExprs &Built) { 5226 unsigned NestedLoopCount = 1; 5227 if (CollapseLoopCountExpr) { 5228 // Found 'collapse' clause - calculate collapse number. 5229 Expr::EvalResult Result; 5230 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 5231 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 5232 } 5233 unsigned OrderedLoopCount = 1; 5234 if (OrderedLoopCountExpr) { 5235 // Found 'ordered' clause - calculate collapse number. 5236 Expr::EvalResult EVResult; 5237 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) { 5238 llvm::APSInt Result = EVResult.Val.getInt(); 5239 if (Result.getLimitedValue() < NestedLoopCount) { 5240 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 5241 diag::err_omp_wrong_ordered_loop_count) 5242 << OrderedLoopCountExpr->getSourceRange(); 5243 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 5244 diag::note_collapse_loop_count) 5245 << CollapseLoopCountExpr->getSourceRange(); 5246 } 5247 OrderedLoopCount = Result.getLimitedValue(); 5248 } 5249 } 5250 // This is helper routine for loop directives (e.g., 'for', 'simd', 5251 // 'for simd', etc.). 5252 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 5253 SmallVector<LoopIterationSpace, 4> IterSpaces( 5254 std::max(OrderedLoopCount, NestedLoopCount)); 5255 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 5256 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 5257 if (checkOpenMPIterationSpace( 5258 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 5259 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 5260 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt], 5261 Captures)) 5262 return 0; 5263 // Move on to the next nested for loop, or to the loop body. 5264 // OpenMP [2.8.1, simd construct, Restrictions] 5265 // All loops associated with the construct must be perfectly nested; that 5266 // is, there must be no intervening code nor any OpenMP directive between 5267 // any two loops. 5268 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 5269 } 5270 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) { 5271 if (checkOpenMPIterationSpace( 5272 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 5273 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 5274 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt], 5275 Captures)) 5276 return 0; 5277 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) { 5278 // Handle initialization of captured loop iterator variables. 5279 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 5280 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 5281 Captures[DRE] = DRE; 5282 } 5283 } 5284 // Move on to the next nested for loop, or to the loop body. 5285 // OpenMP [2.8.1, simd construct, Restrictions] 5286 // All loops associated with the construct must be perfectly nested; that 5287 // is, there must be no intervening code nor any OpenMP directive between 5288 // any two loops. 5289 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 5290 } 5291 5292 Built.clear(/* size */ NestedLoopCount); 5293 5294 if (SemaRef.CurContext->isDependentContext()) 5295 return NestedLoopCount; 5296 5297 // An example of what is generated for the following code: 5298 // 5299 // #pragma omp simd collapse(2) ordered(2) 5300 // for (i = 0; i < NI; ++i) 5301 // for (k = 0; k < NK; ++k) 5302 // for (j = J0; j < NJ; j+=2) { 5303 // <loop body> 5304 // } 5305 // 5306 // We generate the code below. 5307 // Note: the loop body may be outlined in CodeGen. 5308 // Note: some counters may be C++ classes, operator- is used to find number of 5309 // iterations and operator+= to calculate counter value. 5310 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 5311 // or i64 is currently supported). 5312 // 5313 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 5314 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 5315 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 5316 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 5317 // // similar updates for vars in clauses (e.g. 'linear') 5318 // <loop body (using local i and j)> 5319 // } 5320 // i = NI; // assign final values of counters 5321 // j = NJ; 5322 // 5323 5324 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 5325 // the iteration counts of the collapsed for loops. 5326 // Precondition tests if there is at least one iteration (all conditions are 5327 // true). 5328 auto PreCond = ExprResult(IterSpaces[0].PreCond); 5329 Expr *N0 = IterSpaces[0].NumIterations; 5330 ExprResult LastIteration32 = 5331 widenIterationCount(/*Bits=*/32, 5332 SemaRef 5333 .PerformImplicitConversion( 5334 N0->IgnoreImpCasts(), N0->getType(), 5335 Sema::AA_Converting, /*AllowExplicit=*/true) 5336 .get(), 5337 SemaRef); 5338 ExprResult LastIteration64 = widenIterationCount( 5339 /*Bits=*/64, 5340 SemaRef 5341 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 5342 Sema::AA_Converting, 5343 /*AllowExplicit=*/true) 5344 .get(), 5345 SemaRef); 5346 5347 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 5348 return NestedLoopCount; 5349 5350 ASTContext &C = SemaRef.Context; 5351 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 5352 5353 Scope *CurScope = DSA.getCurScope(); 5354 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 5355 if (PreCond.isUsable()) { 5356 PreCond = 5357 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 5358 PreCond.get(), IterSpaces[Cnt].PreCond); 5359 } 5360 Expr *N = IterSpaces[Cnt].NumIterations; 5361 SourceLocation Loc = N->getExprLoc(); 5362 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 5363 if (LastIteration32.isUsable()) 5364 LastIteration32 = SemaRef.BuildBinOp( 5365 CurScope, Loc, BO_Mul, LastIteration32.get(), 5366 SemaRef 5367 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 5368 Sema::AA_Converting, 5369 /*AllowExplicit=*/true) 5370 .get()); 5371 if (LastIteration64.isUsable()) 5372 LastIteration64 = SemaRef.BuildBinOp( 5373 CurScope, Loc, BO_Mul, LastIteration64.get(), 5374 SemaRef 5375 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 5376 Sema::AA_Converting, 5377 /*AllowExplicit=*/true) 5378 .get()); 5379 } 5380 5381 // Choose either the 32-bit or 64-bit version. 5382 ExprResult LastIteration = LastIteration64; 5383 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 5384 (LastIteration32.isUsable() && 5385 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 5386 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 5387 fitsInto( 5388 /*Bits=*/32, 5389 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 5390 LastIteration64.get(), SemaRef)))) 5391 LastIteration = LastIteration32; 5392 QualType VType = LastIteration.get()->getType(); 5393 QualType RealVType = VType; 5394 QualType StrideVType = VType; 5395 if (isOpenMPTaskLoopDirective(DKind)) { 5396 VType = 5397 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 5398 StrideVType = 5399 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 5400 } 5401 5402 if (!LastIteration.isUsable()) 5403 return 0; 5404 5405 // Save the number of iterations. 5406 ExprResult NumIterations = LastIteration; 5407 { 5408 LastIteration = SemaRef.BuildBinOp( 5409 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 5410 LastIteration.get(), 5411 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5412 if (!LastIteration.isUsable()) 5413 return 0; 5414 } 5415 5416 // Calculate the last iteration number beforehand instead of doing this on 5417 // each iteration. Do not do this if the number of iterations may be kfold-ed. 5418 llvm::APSInt Result; 5419 bool IsConstant = 5420 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 5421 ExprResult CalcLastIteration; 5422 if (!IsConstant) { 5423 ExprResult SaveRef = 5424 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 5425 LastIteration = SaveRef; 5426 5427 // Prepare SaveRef + 1. 5428 NumIterations = SemaRef.BuildBinOp( 5429 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 5430 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5431 if (!NumIterations.isUsable()) 5432 return 0; 5433 } 5434 5435 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 5436 5437 // Build variables passed into runtime, necessary for worksharing directives. 5438 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 5439 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 5440 isOpenMPDistributeDirective(DKind)) { 5441 // Lower bound variable, initialized with zero. 5442 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 5443 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 5444 SemaRef.AddInitializerToDecl(LBDecl, 5445 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5446 /*DirectInit*/ false); 5447 5448 // Upper bound variable, initialized with last iteration number. 5449 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 5450 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 5451 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 5452 /*DirectInit*/ false); 5453 5454 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 5455 // This will be used to implement clause 'lastprivate'. 5456 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 5457 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 5458 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 5459 SemaRef.AddInitializerToDecl(ILDecl, 5460 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5461 /*DirectInit*/ false); 5462 5463 // Stride variable returned by runtime (we initialize it to 1 by default). 5464 VarDecl *STDecl = 5465 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 5466 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 5467 SemaRef.AddInitializerToDecl(STDecl, 5468 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 5469 /*DirectInit*/ false); 5470 5471 // Build expression: UB = min(UB, LastIteration) 5472 // It is necessary for CodeGen of directives with static scheduling. 5473 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 5474 UB.get(), LastIteration.get()); 5475 ExprResult CondOp = SemaRef.ActOnConditionalOp( 5476 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 5477 LastIteration.get(), UB.get()); 5478 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 5479 CondOp.get()); 5480 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 5481 5482 // If we have a combined directive that combines 'distribute', 'for' or 5483 // 'simd' we need to be able to access the bounds of the schedule of the 5484 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 5485 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 5486 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5487 // Lower bound variable, initialized with zero. 5488 VarDecl *CombLBDecl = 5489 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 5490 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 5491 SemaRef.AddInitializerToDecl( 5492 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5493 /*DirectInit*/ false); 5494 5495 // Upper bound variable, initialized with last iteration number. 5496 VarDecl *CombUBDecl = 5497 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 5498 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 5499 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 5500 /*DirectInit*/ false); 5501 5502 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 5503 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 5504 ExprResult CombCondOp = 5505 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 5506 LastIteration.get(), CombUB.get()); 5507 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 5508 CombCondOp.get()); 5509 CombEUB = 5510 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 5511 5512 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 5513 // We expect to have at least 2 more parameters than the 'parallel' 5514 // directive does - the lower and upper bounds of the previous schedule. 5515 assert(CD->getNumParams() >= 4 && 5516 "Unexpected number of parameters in loop combined directive"); 5517 5518 // Set the proper type for the bounds given what we learned from the 5519 // enclosed loops. 5520 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 5521 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 5522 5523 // Previous lower and upper bounds are obtained from the region 5524 // parameters. 5525 PrevLB = 5526 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 5527 PrevUB = 5528 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 5529 } 5530 } 5531 5532 // Build the iteration variable and its initialization before loop. 5533 ExprResult IV; 5534 ExprResult Init, CombInit; 5535 { 5536 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 5537 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 5538 Expr *RHS = 5539 (isOpenMPWorksharingDirective(DKind) || 5540 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 5541 ? LB.get() 5542 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 5543 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 5544 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 5545 5546 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5547 Expr *CombRHS = 5548 (isOpenMPWorksharingDirective(DKind) || 5549 isOpenMPTaskLoopDirective(DKind) || 5550 isOpenMPDistributeDirective(DKind)) 5551 ? CombLB.get() 5552 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 5553 CombInit = 5554 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 5555 CombInit = 5556 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 5557 } 5558 } 5559 5560 bool UseStrictCompare = 5561 RealVType->hasUnsignedIntegerRepresentation() && 5562 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 5563 return LIS.IsStrictCompare; 5564 }); 5565 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 5566 // unsigned IV)) for worksharing loops. 5567 SourceLocation CondLoc = AStmt->getBeginLoc(); 5568 Expr *BoundUB = UB.get(); 5569 if (UseStrictCompare) { 5570 BoundUB = 5571 SemaRef 5572 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 5573 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 5574 .get(); 5575 BoundUB = 5576 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 5577 } 5578 ExprResult Cond = 5579 (isOpenMPWorksharingDirective(DKind) || 5580 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 5581 ? SemaRef.BuildBinOp(CurScope, CondLoc, 5582 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 5583 BoundUB) 5584 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 5585 NumIterations.get()); 5586 ExprResult CombDistCond; 5587 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5588 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 5589 NumIterations.get()); 5590 } 5591 5592 ExprResult CombCond; 5593 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5594 Expr *BoundCombUB = CombUB.get(); 5595 if (UseStrictCompare) { 5596 BoundCombUB = 5597 SemaRef 5598 .BuildBinOp( 5599 CurScope, CondLoc, BO_Add, BoundCombUB, 5600 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 5601 .get(); 5602 BoundCombUB = 5603 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 5604 .get(); 5605 } 5606 CombCond = 5607 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 5608 IV.get(), BoundCombUB); 5609 } 5610 // Loop increment (IV = IV + 1) 5611 SourceLocation IncLoc = AStmt->getBeginLoc(); 5612 ExprResult Inc = 5613 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 5614 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 5615 if (!Inc.isUsable()) 5616 return 0; 5617 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 5618 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 5619 if (!Inc.isUsable()) 5620 return 0; 5621 5622 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 5623 // Used for directives with static scheduling. 5624 // In combined construct, add combined version that use CombLB and CombUB 5625 // base variables for the update 5626 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 5627 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 5628 isOpenMPDistributeDirective(DKind)) { 5629 // LB + ST 5630 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 5631 if (!NextLB.isUsable()) 5632 return 0; 5633 // LB = LB + ST 5634 NextLB = 5635 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 5636 NextLB = 5637 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 5638 if (!NextLB.isUsable()) 5639 return 0; 5640 // UB + ST 5641 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 5642 if (!NextUB.isUsable()) 5643 return 0; 5644 // UB = UB + ST 5645 NextUB = 5646 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 5647 NextUB = 5648 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 5649 if (!NextUB.isUsable()) 5650 return 0; 5651 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5652 CombNextLB = 5653 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 5654 if (!NextLB.isUsable()) 5655 return 0; 5656 // LB = LB + ST 5657 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 5658 CombNextLB.get()); 5659 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 5660 /*DiscardedValue*/ false); 5661 if (!CombNextLB.isUsable()) 5662 return 0; 5663 // UB + ST 5664 CombNextUB = 5665 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 5666 if (!CombNextUB.isUsable()) 5667 return 0; 5668 // UB = UB + ST 5669 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 5670 CombNextUB.get()); 5671 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 5672 /*DiscardedValue*/ false); 5673 if (!CombNextUB.isUsable()) 5674 return 0; 5675 } 5676 } 5677 5678 // Create increment expression for distribute loop when combined in a same 5679 // directive with for as IV = IV + ST; ensure upper bound expression based 5680 // on PrevUB instead of NumIterations - used to implement 'for' when found 5681 // in combination with 'distribute', like in 'distribute parallel for' 5682 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 5683 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 5684 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5685 DistCond = SemaRef.BuildBinOp( 5686 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 5687 assert(DistCond.isUsable() && "distribute cond expr was not built"); 5688 5689 DistInc = 5690 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 5691 assert(DistInc.isUsable() && "distribute inc expr was not built"); 5692 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 5693 DistInc.get()); 5694 DistInc = 5695 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 5696 assert(DistInc.isUsable() && "distribute inc expr was not built"); 5697 5698 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 5699 // construct 5700 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 5701 ExprResult IsUBGreater = 5702 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 5703 ExprResult CondOp = SemaRef.ActOnConditionalOp( 5704 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 5705 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 5706 CondOp.get()); 5707 PrevEUB = 5708 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 5709 5710 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 5711 // parallel for is in combination with a distribute directive with 5712 // schedule(static, 1) 5713 Expr *BoundPrevUB = PrevUB.get(); 5714 if (UseStrictCompare) { 5715 BoundPrevUB = 5716 SemaRef 5717 .BuildBinOp( 5718 CurScope, CondLoc, BO_Add, BoundPrevUB, 5719 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 5720 .get(); 5721 BoundPrevUB = 5722 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 5723 .get(); 5724 } 5725 ParForInDistCond = 5726 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 5727 IV.get(), BoundPrevUB); 5728 } 5729 5730 // Build updates and final values of the loop counters. 5731 bool HasErrors = false; 5732 Built.Counters.resize(NestedLoopCount); 5733 Built.Inits.resize(NestedLoopCount); 5734 Built.Updates.resize(NestedLoopCount); 5735 Built.Finals.resize(NestedLoopCount); 5736 { 5737 // We implement the following algorithm for obtaining the 5738 // original loop iteration variable values based on the 5739 // value of the collapsed loop iteration variable IV. 5740 // 5741 // Let n+1 be the number of collapsed loops in the nest. 5742 // Iteration variables (I0, I1, .... In) 5743 // Iteration counts (N0, N1, ... Nn) 5744 // 5745 // Acc = IV; 5746 // 5747 // To compute Ik for loop k, 0 <= k <= n, generate: 5748 // Prod = N(k+1) * N(k+2) * ... * Nn; 5749 // Ik = Acc / Prod; 5750 // Acc -= Ik * Prod; 5751 // 5752 ExprResult Acc = IV; 5753 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 5754 LoopIterationSpace &IS = IterSpaces[Cnt]; 5755 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 5756 ExprResult Iter; 5757 5758 // Compute prod 5759 ExprResult Prod = 5760 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 5761 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K) 5762 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 5763 IterSpaces[K].NumIterations); 5764 5765 // Iter = Acc / Prod 5766 // If there is at least one more inner loop to avoid 5767 // multiplication by 1. 5768 if (Cnt + 1 < NestedLoopCount) 5769 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, 5770 Acc.get(), Prod.get()); 5771 else 5772 Iter = Acc; 5773 if (!Iter.isUsable()) { 5774 HasErrors = true; 5775 break; 5776 } 5777 5778 // Update Acc: 5779 // Acc -= Iter * Prod 5780 // Check if there is at least one more inner loop to avoid 5781 // multiplication by 1. 5782 if (Cnt + 1 < NestedLoopCount) 5783 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, 5784 Iter.get(), Prod.get()); 5785 else 5786 Prod = Iter; 5787 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, 5788 Acc.get(), Prod.get()); 5789 5790 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 5791 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 5792 DeclRefExpr *CounterVar = buildDeclRefExpr( 5793 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 5794 /*RefersToCapture=*/true); 5795 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 5796 IS.CounterInit, Captures); 5797 if (!Init.isUsable()) { 5798 HasErrors = true; 5799 break; 5800 } 5801 ExprResult Update = buildCounterUpdate( 5802 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 5803 IS.CounterStep, IS.Subtract, &Captures); 5804 if (!Update.isUsable()) { 5805 HasErrors = true; 5806 break; 5807 } 5808 5809 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 5810 ExprResult Final = buildCounterUpdate( 5811 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 5812 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 5813 if (!Final.isUsable()) { 5814 HasErrors = true; 5815 break; 5816 } 5817 5818 if (!Update.isUsable() || !Final.isUsable()) { 5819 HasErrors = true; 5820 break; 5821 } 5822 // Save results 5823 Built.Counters[Cnt] = IS.CounterVar; 5824 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 5825 Built.Inits[Cnt] = Init.get(); 5826 Built.Updates[Cnt] = Update.get(); 5827 Built.Finals[Cnt] = Final.get(); 5828 } 5829 } 5830 5831 if (HasErrors) 5832 return 0; 5833 5834 // Save results 5835 Built.IterationVarRef = IV.get(); 5836 Built.LastIteration = LastIteration.get(); 5837 Built.NumIterations = NumIterations.get(); 5838 Built.CalcLastIteration = SemaRef 5839 .ActOnFinishFullExpr(CalcLastIteration.get(), 5840 /*DiscardedValue*/ false) 5841 .get(); 5842 Built.PreCond = PreCond.get(); 5843 Built.PreInits = buildPreInits(C, Captures); 5844 Built.Cond = Cond.get(); 5845 Built.Init = Init.get(); 5846 Built.Inc = Inc.get(); 5847 Built.LB = LB.get(); 5848 Built.UB = UB.get(); 5849 Built.IL = IL.get(); 5850 Built.ST = ST.get(); 5851 Built.EUB = EUB.get(); 5852 Built.NLB = NextLB.get(); 5853 Built.NUB = NextUB.get(); 5854 Built.PrevLB = PrevLB.get(); 5855 Built.PrevUB = PrevUB.get(); 5856 Built.DistInc = DistInc.get(); 5857 Built.PrevEUB = PrevEUB.get(); 5858 Built.DistCombinedFields.LB = CombLB.get(); 5859 Built.DistCombinedFields.UB = CombUB.get(); 5860 Built.DistCombinedFields.EUB = CombEUB.get(); 5861 Built.DistCombinedFields.Init = CombInit.get(); 5862 Built.DistCombinedFields.Cond = CombCond.get(); 5863 Built.DistCombinedFields.NLB = CombNextLB.get(); 5864 Built.DistCombinedFields.NUB = CombNextUB.get(); 5865 Built.DistCombinedFields.DistCond = CombDistCond.get(); 5866 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 5867 5868 return NestedLoopCount; 5869 } 5870 5871 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 5872 auto CollapseClauses = 5873 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 5874 if (CollapseClauses.begin() != CollapseClauses.end()) 5875 return (*CollapseClauses.begin())->getNumForLoops(); 5876 return nullptr; 5877 } 5878 5879 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 5880 auto OrderedClauses = 5881 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 5882 if (OrderedClauses.begin() != OrderedClauses.end()) 5883 return (*OrderedClauses.begin())->getNumForLoops(); 5884 return nullptr; 5885 } 5886 5887 static bool checkSimdlenSafelenSpecified(Sema &S, 5888 const ArrayRef<OMPClause *> Clauses) { 5889 const OMPSafelenClause *Safelen = nullptr; 5890 const OMPSimdlenClause *Simdlen = nullptr; 5891 5892 for (const OMPClause *Clause : Clauses) { 5893 if (Clause->getClauseKind() == OMPC_safelen) 5894 Safelen = cast<OMPSafelenClause>(Clause); 5895 else if (Clause->getClauseKind() == OMPC_simdlen) 5896 Simdlen = cast<OMPSimdlenClause>(Clause); 5897 if (Safelen && Simdlen) 5898 break; 5899 } 5900 5901 if (Simdlen && Safelen) { 5902 const Expr *SimdlenLength = Simdlen->getSimdlen(); 5903 const Expr *SafelenLength = Safelen->getSafelen(); 5904 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 5905 SimdlenLength->isInstantiationDependent() || 5906 SimdlenLength->containsUnexpandedParameterPack()) 5907 return false; 5908 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 5909 SafelenLength->isInstantiationDependent() || 5910 SafelenLength->containsUnexpandedParameterPack()) 5911 return false; 5912 Expr::EvalResult SimdlenResult, SafelenResult; 5913 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 5914 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 5915 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 5916 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 5917 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 5918 // If both simdlen and safelen clauses are specified, the value of the 5919 // simdlen parameter must be less than or equal to the value of the safelen 5920 // parameter. 5921 if (SimdlenRes > SafelenRes) { 5922 S.Diag(SimdlenLength->getExprLoc(), 5923 diag::err_omp_wrong_simdlen_safelen_values) 5924 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 5925 return true; 5926 } 5927 } 5928 return false; 5929 } 5930 5931 StmtResult 5932 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 5933 SourceLocation StartLoc, SourceLocation EndLoc, 5934 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5935 if (!AStmt) 5936 return StmtError(); 5937 5938 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5939 OMPLoopDirective::HelperExprs B; 5940 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5941 // define the nested loops number. 5942 unsigned NestedLoopCount = checkOpenMPLoop( 5943 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5944 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5945 if (NestedLoopCount == 0) 5946 return StmtError(); 5947 5948 assert((CurContext->isDependentContext() || B.builtAll()) && 5949 "omp simd loop exprs were not built"); 5950 5951 if (!CurContext->isDependentContext()) { 5952 // Finalize the clauses that need pre-built expressions for CodeGen. 5953 for (OMPClause *C : Clauses) { 5954 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5955 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5956 B.NumIterations, *this, CurScope, 5957 DSAStack)) 5958 return StmtError(); 5959 } 5960 } 5961 5962 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5963 return StmtError(); 5964 5965 setFunctionHasBranchProtectedScope(); 5966 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5967 Clauses, AStmt, B); 5968 } 5969 5970 StmtResult 5971 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 5972 SourceLocation StartLoc, SourceLocation EndLoc, 5973 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5974 if (!AStmt) 5975 return StmtError(); 5976 5977 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5978 OMPLoopDirective::HelperExprs B; 5979 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5980 // define the nested loops number. 5981 unsigned NestedLoopCount = checkOpenMPLoop( 5982 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5983 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5984 if (NestedLoopCount == 0) 5985 return StmtError(); 5986 5987 assert((CurContext->isDependentContext() || B.builtAll()) && 5988 "omp for loop exprs were not built"); 5989 5990 if (!CurContext->isDependentContext()) { 5991 // Finalize the clauses that need pre-built expressions for CodeGen. 5992 for (OMPClause *C : Clauses) { 5993 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5994 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5995 B.NumIterations, *this, CurScope, 5996 DSAStack)) 5997 return StmtError(); 5998 } 5999 } 6000 6001 setFunctionHasBranchProtectedScope(); 6002 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 6003 Clauses, AStmt, B, DSAStack->isCancelRegion()); 6004 } 6005 6006 StmtResult Sema::ActOnOpenMPForSimdDirective( 6007 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6008 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 6009 if (!AStmt) 6010 return StmtError(); 6011 6012 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6013 OMPLoopDirective::HelperExprs B; 6014 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6015 // define the nested loops number. 6016 unsigned NestedLoopCount = 6017 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 6018 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6019 VarsWithImplicitDSA, B); 6020 if (NestedLoopCount == 0) 6021 return StmtError(); 6022 6023 assert((CurContext->isDependentContext() || B.builtAll()) && 6024 "omp for simd loop exprs were not built"); 6025 6026 if (!CurContext->isDependentContext()) { 6027 // Finalize the clauses that need pre-built expressions for CodeGen. 6028 for (OMPClause *C : Clauses) { 6029 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6030 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6031 B.NumIterations, *this, CurScope, 6032 DSAStack)) 6033 return StmtError(); 6034 } 6035 } 6036 6037 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6038 return StmtError(); 6039 6040 setFunctionHasBranchProtectedScope(); 6041 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 6042 Clauses, AStmt, B); 6043 } 6044 6045 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 6046 Stmt *AStmt, 6047 SourceLocation StartLoc, 6048 SourceLocation EndLoc) { 6049 if (!AStmt) 6050 return StmtError(); 6051 6052 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6053 auto BaseStmt = AStmt; 6054 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 6055 BaseStmt = CS->getCapturedStmt(); 6056 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 6057 auto S = C->children(); 6058 if (S.begin() == S.end()) 6059 return StmtError(); 6060 // All associated statements must be '#pragma omp section' except for 6061 // the first one. 6062 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 6063 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 6064 if (SectionStmt) 6065 Diag(SectionStmt->getBeginLoc(), 6066 diag::err_omp_sections_substmt_not_section); 6067 return StmtError(); 6068 } 6069 cast<OMPSectionDirective>(SectionStmt) 6070 ->setHasCancel(DSAStack->isCancelRegion()); 6071 } 6072 } else { 6073 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 6074 return StmtError(); 6075 } 6076 6077 setFunctionHasBranchProtectedScope(); 6078 6079 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6080 DSAStack->isCancelRegion()); 6081 } 6082 6083 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 6084 SourceLocation StartLoc, 6085 SourceLocation EndLoc) { 6086 if (!AStmt) 6087 return StmtError(); 6088 6089 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6090 6091 setFunctionHasBranchProtectedScope(); 6092 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 6093 6094 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 6095 DSAStack->isCancelRegion()); 6096 } 6097 6098 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 6099 Stmt *AStmt, 6100 SourceLocation StartLoc, 6101 SourceLocation EndLoc) { 6102 if (!AStmt) 6103 return StmtError(); 6104 6105 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6106 6107 setFunctionHasBranchProtectedScope(); 6108 6109 // OpenMP [2.7.3, single Construct, Restrictions] 6110 // The copyprivate clause must not be used with the nowait clause. 6111 const OMPClause *Nowait = nullptr; 6112 const OMPClause *Copyprivate = nullptr; 6113 for (const OMPClause *Clause : Clauses) { 6114 if (Clause->getClauseKind() == OMPC_nowait) 6115 Nowait = Clause; 6116 else if (Clause->getClauseKind() == OMPC_copyprivate) 6117 Copyprivate = Clause; 6118 if (Copyprivate && Nowait) { 6119 Diag(Copyprivate->getBeginLoc(), 6120 diag::err_omp_single_copyprivate_with_nowait); 6121 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 6122 return StmtError(); 6123 } 6124 } 6125 6126 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6127 } 6128 6129 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 6130 SourceLocation StartLoc, 6131 SourceLocation EndLoc) { 6132 if (!AStmt) 6133 return StmtError(); 6134 6135 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6136 6137 setFunctionHasBranchProtectedScope(); 6138 6139 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 6140 } 6141 6142 StmtResult Sema::ActOnOpenMPCriticalDirective( 6143 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 6144 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 6145 if (!AStmt) 6146 return StmtError(); 6147 6148 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6149 6150 bool ErrorFound = false; 6151 llvm::APSInt Hint; 6152 SourceLocation HintLoc; 6153 bool DependentHint = false; 6154 for (const OMPClause *C : Clauses) { 6155 if (C->getClauseKind() == OMPC_hint) { 6156 if (!DirName.getName()) { 6157 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 6158 ErrorFound = true; 6159 } 6160 Expr *E = cast<OMPHintClause>(C)->getHint(); 6161 if (E->isTypeDependent() || E->isValueDependent() || 6162 E->isInstantiationDependent()) { 6163 DependentHint = true; 6164 } else { 6165 Hint = E->EvaluateKnownConstInt(Context); 6166 HintLoc = C->getBeginLoc(); 6167 } 6168 } 6169 } 6170 if (ErrorFound) 6171 return StmtError(); 6172 const auto Pair = DSAStack->getCriticalWithHint(DirName); 6173 if (Pair.first && DirName.getName() && !DependentHint) { 6174 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 6175 Diag(StartLoc, diag::err_omp_critical_with_hint); 6176 if (HintLoc.isValid()) 6177 Diag(HintLoc, diag::note_omp_critical_hint_here) 6178 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 6179 else 6180 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 6181 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 6182 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 6183 << 1 6184 << C->getHint()->EvaluateKnownConstInt(Context).toString( 6185 /*Radix=*/10, /*Signed=*/false); 6186 } else { 6187 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 6188 } 6189 } 6190 } 6191 6192 setFunctionHasBranchProtectedScope(); 6193 6194 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 6195 Clauses, AStmt); 6196 if (!Pair.first && DirName.getName() && !DependentHint) 6197 DSAStack->addCriticalWithHint(Dir, Hint); 6198 return Dir; 6199 } 6200 6201 StmtResult Sema::ActOnOpenMPParallelForDirective( 6202 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6203 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 6204 if (!AStmt) 6205 return StmtError(); 6206 6207 auto *CS = cast<CapturedStmt>(AStmt); 6208 // 1.2.2 OpenMP Language Terminology 6209 // Structured block - An executable statement with a single entry at the 6210 // top and a single exit at the bottom. 6211 // The point of exit cannot be a branch out of the structured block. 6212 // longjmp() and throw() must not violate the entry/exit criteria. 6213 CS->getCapturedDecl()->setNothrow(); 6214 6215 OMPLoopDirective::HelperExprs B; 6216 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6217 // define the nested loops number. 6218 unsigned NestedLoopCount = 6219 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 6220 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6221 VarsWithImplicitDSA, B); 6222 if (NestedLoopCount == 0) 6223 return StmtError(); 6224 6225 assert((CurContext->isDependentContext() || B.builtAll()) && 6226 "omp parallel for loop exprs were not built"); 6227 6228 if (!CurContext->isDependentContext()) { 6229 // Finalize the clauses that need pre-built expressions for CodeGen. 6230 for (OMPClause *C : Clauses) { 6231 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6232 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6233 B.NumIterations, *this, CurScope, 6234 DSAStack)) 6235 return StmtError(); 6236 } 6237 } 6238 6239 setFunctionHasBranchProtectedScope(); 6240 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 6241 NestedLoopCount, Clauses, AStmt, B, 6242 DSAStack->isCancelRegion()); 6243 } 6244 6245 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 6246 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6247 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 6248 if (!AStmt) 6249 return StmtError(); 6250 6251 auto *CS = cast<CapturedStmt>(AStmt); 6252 // 1.2.2 OpenMP Language Terminology 6253 // Structured block - An executable statement with a single entry at the 6254 // top and a single exit at the bottom. 6255 // The point of exit cannot be a branch out of the structured block. 6256 // longjmp() and throw() must not violate the entry/exit criteria. 6257 CS->getCapturedDecl()->setNothrow(); 6258 6259 OMPLoopDirective::HelperExprs B; 6260 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6261 // define the nested loops number. 6262 unsigned NestedLoopCount = 6263 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 6264 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6265 VarsWithImplicitDSA, B); 6266 if (NestedLoopCount == 0) 6267 return StmtError(); 6268 6269 if (!CurContext->isDependentContext()) { 6270 // Finalize the clauses that need pre-built expressions for CodeGen. 6271 for (OMPClause *C : Clauses) { 6272 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6273 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6274 B.NumIterations, *this, CurScope, 6275 DSAStack)) 6276 return StmtError(); 6277 } 6278 } 6279 6280 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6281 return StmtError(); 6282 6283 setFunctionHasBranchProtectedScope(); 6284 return OMPParallelForSimdDirective::Create( 6285 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6286 } 6287 6288 StmtResult 6289 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 6290 Stmt *AStmt, SourceLocation StartLoc, 6291 SourceLocation EndLoc) { 6292 if (!AStmt) 6293 return StmtError(); 6294 6295 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6296 auto BaseStmt = AStmt; 6297 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 6298 BaseStmt = CS->getCapturedStmt(); 6299 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 6300 auto S = C->children(); 6301 if (S.begin() == S.end()) 6302 return StmtError(); 6303 // All associated statements must be '#pragma omp section' except for 6304 // the first one. 6305 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 6306 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 6307 if (SectionStmt) 6308 Diag(SectionStmt->getBeginLoc(), 6309 diag::err_omp_parallel_sections_substmt_not_section); 6310 return StmtError(); 6311 } 6312 cast<OMPSectionDirective>(SectionStmt) 6313 ->setHasCancel(DSAStack->isCancelRegion()); 6314 } 6315 } else { 6316 Diag(AStmt->getBeginLoc(), 6317 diag::err_omp_parallel_sections_not_compound_stmt); 6318 return StmtError(); 6319 } 6320 6321 setFunctionHasBranchProtectedScope(); 6322 6323 return OMPParallelSectionsDirective::Create( 6324 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 6325 } 6326 6327 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 6328 Stmt *AStmt, SourceLocation StartLoc, 6329 SourceLocation EndLoc) { 6330 if (!AStmt) 6331 return StmtError(); 6332 6333 auto *CS = cast<CapturedStmt>(AStmt); 6334 // 1.2.2 OpenMP Language Terminology 6335 // Structured block - An executable statement with a single entry at the 6336 // top and a single exit at the bottom. 6337 // The point of exit cannot be a branch out of the structured block. 6338 // longjmp() and throw() must not violate the entry/exit criteria. 6339 CS->getCapturedDecl()->setNothrow(); 6340 6341 setFunctionHasBranchProtectedScope(); 6342 6343 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6344 DSAStack->isCancelRegion()); 6345 } 6346 6347 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 6348 SourceLocation EndLoc) { 6349 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 6350 } 6351 6352 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 6353 SourceLocation EndLoc) { 6354 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 6355 } 6356 6357 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 6358 SourceLocation EndLoc) { 6359 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 6360 } 6361 6362 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 6363 Stmt *AStmt, 6364 SourceLocation StartLoc, 6365 SourceLocation EndLoc) { 6366 if (!AStmt) 6367 return StmtError(); 6368 6369 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6370 6371 setFunctionHasBranchProtectedScope(); 6372 6373 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 6374 AStmt, 6375 DSAStack->getTaskgroupReductionRef()); 6376 } 6377 6378 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 6379 SourceLocation StartLoc, 6380 SourceLocation EndLoc) { 6381 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 6382 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 6383 } 6384 6385 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 6386 Stmt *AStmt, 6387 SourceLocation StartLoc, 6388 SourceLocation EndLoc) { 6389 const OMPClause *DependFound = nullptr; 6390 const OMPClause *DependSourceClause = nullptr; 6391 const OMPClause *DependSinkClause = nullptr; 6392 bool ErrorFound = false; 6393 const OMPThreadsClause *TC = nullptr; 6394 const OMPSIMDClause *SC = nullptr; 6395 for (const OMPClause *C : Clauses) { 6396 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 6397 DependFound = C; 6398 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 6399 if (DependSourceClause) { 6400 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 6401 << getOpenMPDirectiveName(OMPD_ordered) 6402 << getOpenMPClauseName(OMPC_depend) << 2; 6403 ErrorFound = true; 6404 } else { 6405 DependSourceClause = C; 6406 } 6407 if (DependSinkClause) { 6408 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 6409 << 0; 6410 ErrorFound = true; 6411 } 6412 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 6413 if (DependSourceClause) { 6414 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 6415 << 1; 6416 ErrorFound = true; 6417 } 6418 DependSinkClause = C; 6419 } 6420 } else if (C->getClauseKind() == OMPC_threads) { 6421 TC = cast<OMPThreadsClause>(C); 6422 } else if (C->getClauseKind() == OMPC_simd) { 6423 SC = cast<OMPSIMDClause>(C); 6424 } 6425 } 6426 if (!ErrorFound && !SC && 6427 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 6428 // OpenMP [2.8.1,simd Construct, Restrictions] 6429 // An ordered construct with the simd clause is the only OpenMP construct 6430 // that can appear in the simd region. 6431 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 6432 ErrorFound = true; 6433 } else if (DependFound && (TC || SC)) { 6434 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 6435 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 6436 ErrorFound = true; 6437 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 6438 Diag(DependFound->getBeginLoc(), 6439 diag::err_omp_ordered_directive_without_param); 6440 ErrorFound = true; 6441 } else if (TC || Clauses.empty()) { 6442 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 6443 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 6444 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 6445 << (TC != nullptr); 6446 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param); 6447 ErrorFound = true; 6448 } 6449 } 6450 if ((!AStmt && !DependFound) || ErrorFound) 6451 return StmtError(); 6452 6453 if (AStmt) { 6454 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6455 6456 setFunctionHasBranchProtectedScope(); 6457 } 6458 6459 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6460 } 6461 6462 namespace { 6463 /// Helper class for checking expression in 'omp atomic [update]' 6464 /// construct. 6465 class OpenMPAtomicUpdateChecker { 6466 /// Error results for atomic update expressions. 6467 enum ExprAnalysisErrorCode { 6468 /// A statement is not an expression statement. 6469 NotAnExpression, 6470 /// Expression is not builtin binary or unary operation. 6471 NotABinaryOrUnaryExpression, 6472 /// Unary operation is not post-/pre- increment/decrement operation. 6473 NotAnUnaryIncDecExpression, 6474 /// An expression is not of scalar type. 6475 NotAScalarType, 6476 /// A binary operation is not an assignment operation. 6477 NotAnAssignmentOp, 6478 /// RHS part of the binary operation is not a binary expression. 6479 NotABinaryExpression, 6480 /// RHS part is not additive/multiplicative/shift/biwise binary 6481 /// expression. 6482 NotABinaryOperator, 6483 /// RHS binary operation does not have reference to the updated LHS 6484 /// part. 6485 NotAnUpdateExpression, 6486 /// No errors is found. 6487 NoError 6488 }; 6489 /// Reference to Sema. 6490 Sema &SemaRef; 6491 /// A location for note diagnostics (when error is found). 6492 SourceLocation NoteLoc; 6493 /// 'x' lvalue part of the source atomic expression. 6494 Expr *X; 6495 /// 'expr' rvalue part of the source atomic expression. 6496 Expr *E; 6497 /// Helper expression of the form 6498 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 6499 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 6500 Expr *UpdateExpr; 6501 /// Is 'x' a LHS in a RHS part of full update expression. It is 6502 /// important for non-associative operations. 6503 bool IsXLHSInRHSPart; 6504 BinaryOperatorKind Op; 6505 SourceLocation OpLoc; 6506 /// true if the source expression is a postfix unary operation, false 6507 /// if it is a prefix unary operation. 6508 bool IsPostfixUpdate; 6509 6510 public: 6511 OpenMPAtomicUpdateChecker(Sema &SemaRef) 6512 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 6513 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 6514 /// Check specified statement that it is suitable for 'atomic update' 6515 /// constructs and extract 'x', 'expr' and Operation from the original 6516 /// expression. If DiagId and NoteId == 0, then only check is performed 6517 /// without error notification. 6518 /// \param DiagId Diagnostic which should be emitted if error is found. 6519 /// \param NoteId Diagnostic note for the main error message. 6520 /// \return true if statement is not an update expression, false otherwise. 6521 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 6522 /// Return the 'x' lvalue part of the source atomic expression. 6523 Expr *getX() const { return X; } 6524 /// Return the 'expr' rvalue part of the source atomic expression. 6525 Expr *getExpr() const { return E; } 6526 /// Return the update expression used in calculation of the updated 6527 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 6528 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 6529 Expr *getUpdateExpr() const { return UpdateExpr; } 6530 /// Return true if 'x' is LHS in RHS part of full update expression, 6531 /// false otherwise. 6532 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 6533 6534 /// true if the source expression is a postfix unary operation, false 6535 /// if it is a prefix unary operation. 6536 bool isPostfixUpdate() const { return IsPostfixUpdate; } 6537 6538 private: 6539 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 6540 unsigned NoteId = 0); 6541 }; 6542 } // namespace 6543 6544 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 6545 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 6546 ExprAnalysisErrorCode ErrorFound = NoError; 6547 SourceLocation ErrorLoc, NoteLoc; 6548 SourceRange ErrorRange, NoteRange; 6549 // Allowed constructs are: 6550 // x = x binop expr; 6551 // x = expr binop x; 6552 if (AtomicBinOp->getOpcode() == BO_Assign) { 6553 X = AtomicBinOp->getLHS(); 6554 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 6555 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 6556 if (AtomicInnerBinOp->isMultiplicativeOp() || 6557 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 6558 AtomicInnerBinOp->isBitwiseOp()) { 6559 Op = AtomicInnerBinOp->getOpcode(); 6560 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 6561 Expr *LHS = AtomicInnerBinOp->getLHS(); 6562 Expr *RHS = AtomicInnerBinOp->getRHS(); 6563 llvm::FoldingSetNodeID XId, LHSId, RHSId; 6564 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 6565 /*Canonical=*/true); 6566 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 6567 /*Canonical=*/true); 6568 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 6569 /*Canonical=*/true); 6570 if (XId == LHSId) { 6571 E = RHS; 6572 IsXLHSInRHSPart = true; 6573 } else if (XId == RHSId) { 6574 E = LHS; 6575 IsXLHSInRHSPart = false; 6576 } else { 6577 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 6578 ErrorRange = AtomicInnerBinOp->getSourceRange(); 6579 NoteLoc = X->getExprLoc(); 6580 NoteRange = X->getSourceRange(); 6581 ErrorFound = NotAnUpdateExpression; 6582 } 6583 } else { 6584 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 6585 ErrorRange = AtomicInnerBinOp->getSourceRange(); 6586 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 6587 NoteRange = SourceRange(NoteLoc, NoteLoc); 6588 ErrorFound = NotABinaryOperator; 6589 } 6590 } else { 6591 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 6592 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 6593 ErrorFound = NotABinaryExpression; 6594 } 6595 } else { 6596 ErrorLoc = AtomicBinOp->getExprLoc(); 6597 ErrorRange = AtomicBinOp->getSourceRange(); 6598 NoteLoc = AtomicBinOp->getOperatorLoc(); 6599 NoteRange = SourceRange(NoteLoc, NoteLoc); 6600 ErrorFound = NotAnAssignmentOp; 6601 } 6602 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 6603 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 6604 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 6605 return true; 6606 } 6607 if (SemaRef.CurContext->isDependentContext()) 6608 E = X = UpdateExpr = nullptr; 6609 return ErrorFound != NoError; 6610 } 6611 6612 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 6613 unsigned NoteId) { 6614 ExprAnalysisErrorCode ErrorFound = NoError; 6615 SourceLocation ErrorLoc, NoteLoc; 6616 SourceRange ErrorRange, NoteRange; 6617 // Allowed constructs are: 6618 // x++; 6619 // x--; 6620 // ++x; 6621 // --x; 6622 // x binop= expr; 6623 // x = x binop expr; 6624 // x = expr binop x; 6625 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 6626 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 6627 if (AtomicBody->getType()->isScalarType() || 6628 AtomicBody->isInstantiationDependent()) { 6629 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 6630 AtomicBody->IgnoreParenImpCasts())) { 6631 // Check for Compound Assignment Operation 6632 Op = BinaryOperator::getOpForCompoundAssignment( 6633 AtomicCompAssignOp->getOpcode()); 6634 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 6635 E = AtomicCompAssignOp->getRHS(); 6636 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 6637 IsXLHSInRHSPart = true; 6638 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 6639 AtomicBody->IgnoreParenImpCasts())) { 6640 // Check for Binary Operation 6641 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 6642 return true; 6643 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 6644 AtomicBody->IgnoreParenImpCasts())) { 6645 // Check for Unary Operation 6646 if (AtomicUnaryOp->isIncrementDecrementOp()) { 6647 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 6648 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 6649 OpLoc = AtomicUnaryOp->getOperatorLoc(); 6650 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 6651 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 6652 IsXLHSInRHSPart = true; 6653 } else { 6654 ErrorFound = NotAnUnaryIncDecExpression; 6655 ErrorLoc = AtomicUnaryOp->getExprLoc(); 6656 ErrorRange = AtomicUnaryOp->getSourceRange(); 6657 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 6658 NoteRange = SourceRange(NoteLoc, NoteLoc); 6659 } 6660 } else if (!AtomicBody->isInstantiationDependent()) { 6661 ErrorFound = NotABinaryOrUnaryExpression; 6662 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 6663 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 6664 } 6665 } else { 6666 ErrorFound = NotAScalarType; 6667 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 6668 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6669 } 6670 } else { 6671 ErrorFound = NotAnExpression; 6672 NoteLoc = ErrorLoc = S->getBeginLoc(); 6673 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6674 } 6675 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 6676 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 6677 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 6678 return true; 6679 } 6680 if (SemaRef.CurContext->isDependentContext()) 6681 E = X = UpdateExpr = nullptr; 6682 if (ErrorFound == NoError && E && X) { 6683 // Build an update expression of form 'OpaqueValueExpr(x) binop 6684 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 6685 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 6686 auto *OVEX = new (SemaRef.getASTContext()) 6687 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 6688 auto *OVEExpr = new (SemaRef.getASTContext()) 6689 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 6690 ExprResult Update = 6691 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 6692 IsXLHSInRHSPart ? OVEExpr : OVEX); 6693 if (Update.isInvalid()) 6694 return true; 6695 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 6696 Sema::AA_Casting); 6697 if (Update.isInvalid()) 6698 return true; 6699 UpdateExpr = Update.get(); 6700 } 6701 return ErrorFound != NoError; 6702 } 6703 6704 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 6705 Stmt *AStmt, 6706 SourceLocation StartLoc, 6707 SourceLocation EndLoc) { 6708 if (!AStmt) 6709 return StmtError(); 6710 6711 auto *CS = cast<CapturedStmt>(AStmt); 6712 // 1.2.2 OpenMP Language Terminology 6713 // Structured block - An executable statement with a single entry at the 6714 // top and a single exit at the bottom. 6715 // The point of exit cannot be a branch out of the structured block. 6716 // longjmp() and throw() must not violate the entry/exit criteria. 6717 OpenMPClauseKind AtomicKind = OMPC_unknown; 6718 SourceLocation AtomicKindLoc; 6719 for (const OMPClause *C : Clauses) { 6720 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 6721 C->getClauseKind() == OMPC_update || 6722 C->getClauseKind() == OMPC_capture) { 6723 if (AtomicKind != OMPC_unknown) { 6724 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 6725 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 6726 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 6727 << getOpenMPClauseName(AtomicKind); 6728 } else { 6729 AtomicKind = C->getClauseKind(); 6730 AtomicKindLoc = C->getBeginLoc(); 6731 } 6732 } 6733 } 6734 6735 Stmt *Body = CS->getCapturedStmt(); 6736 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 6737 Body = EWC->getSubExpr(); 6738 6739 Expr *X = nullptr; 6740 Expr *V = nullptr; 6741 Expr *E = nullptr; 6742 Expr *UE = nullptr; 6743 bool IsXLHSInRHSPart = false; 6744 bool IsPostfixUpdate = false; 6745 // OpenMP [2.12.6, atomic Construct] 6746 // In the next expressions: 6747 // * x and v (as applicable) are both l-value expressions with scalar type. 6748 // * During the execution of an atomic region, multiple syntactic 6749 // occurrences of x must designate the same storage location. 6750 // * Neither of v and expr (as applicable) may access the storage location 6751 // designated by x. 6752 // * Neither of x and expr (as applicable) may access the storage location 6753 // designated by v. 6754 // * expr is an expression with scalar type. 6755 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 6756 // * binop, binop=, ++, and -- are not overloaded operators. 6757 // * The expression x binop expr must be numerically equivalent to x binop 6758 // (expr). This requirement is satisfied if the operators in expr have 6759 // precedence greater than binop, or by using parentheses around expr or 6760 // subexpressions of expr. 6761 // * The expression expr binop x must be numerically equivalent to (expr) 6762 // binop x. This requirement is satisfied if the operators in expr have 6763 // precedence equal to or greater than binop, or by using parentheses around 6764 // expr or subexpressions of expr. 6765 // * For forms that allow multiple occurrences of x, the number of times 6766 // that x is evaluated is unspecified. 6767 if (AtomicKind == OMPC_read) { 6768 enum { 6769 NotAnExpression, 6770 NotAnAssignmentOp, 6771 NotAScalarType, 6772 NotAnLValue, 6773 NoError 6774 } ErrorFound = NoError; 6775 SourceLocation ErrorLoc, NoteLoc; 6776 SourceRange ErrorRange, NoteRange; 6777 // If clause is read: 6778 // v = x; 6779 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 6780 const auto *AtomicBinOp = 6781 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6782 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6783 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6784 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 6785 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6786 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 6787 if (!X->isLValue() || !V->isLValue()) { 6788 const Expr *NotLValueExpr = X->isLValue() ? V : X; 6789 ErrorFound = NotAnLValue; 6790 ErrorLoc = AtomicBinOp->getExprLoc(); 6791 ErrorRange = AtomicBinOp->getSourceRange(); 6792 NoteLoc = NotLValueExpr->getExprLoc(); 6793 NoteRange = NotLValueExpr->getSourceRange(); 6794 } 6795 } else if (!X->isInstantiationDependent() || 6796 !V->isInstantiationDependent()) { 6797 const Expr *NotScalarExpr = 6798 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6799 ? V 6800 : X; 6801 ErrorFound = NotAScalarType; 6802 ErrorLoc = AtomicBinOp->getExprLoc(); 6803 ErrorRange = AtomicBinOp->getSourceRange(); 6804 NoteLoc = NotScalarExpr->getExprLoc(); 6805 NoteRange = NotScalarExpr->getSourceRange(); 6806 } 6807 } else if (!AtomicBody->isInstantiationDependent()) { 6808 ErrorFound = NotAnAssignmentOp; 6809 ErrorLoc = AtomicBody->getExprLoc(); 6810 ErrorRange = AtomicBody->getSourceRange(); 6811 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6812 : AtomicBody->getExprLoc(); 6813 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6814 : AtomicBody->getSourceRange(); 6815 } 6816 } else { 6817 ErrorFound = NotAnExpression; 6818 NoteLoc = ErrorLoc = Body->getBeginLoc(); 6819 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6820 } 6821 if (ErrorFound != NoError) { 6822 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 6823 << ErrorRange; 6824 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6825 << NoteRange; 6826 return StmtError(); 6827 } 6828 if (CurContext->isDependentContext()) 6829 V = X = nullptr; 6830 } else if (AtomicKind == OMPC_write) { 6831 enum { 6832 NotAnExpression, 6833 NotAnAssignmentOp, 6834 NotAScalarType, 6835 NotAnLValue, 6836 NoError 6837 } ErrorFound = NoError; 6838 SourceLocation ErrorLoc, NoteLoc; 6839 SourceRange ErrorRange, NoteRange; 6840 // If clause is write: 6841 // x = expr; 6842 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 6843 const auto *AtomicBinOp = 6844 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6845 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6846 X = AtomicBinOp->getLHS(); 6847 E = AtomicBinOp->getRHS(); 6848 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6849 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 6850 if (!X->isLValue()) { 6851 ErrorFound = NotAnLValue; 6852 ErrorLoc = AtomicBinOp->getExprLoc(); 6853 ErrorRange = AtomicBinOp->getSourceRange(); 6854 NoteLoc = X->getExprLoc(); 6855 NoteRange = X->getSourceRange(); 6856 } 6857 } else if (!X->isInstantiationDependent() || 6858 !E->isInstantiationDependent()) { 6859 const Expr *NotScalarExpr = 6860 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6861 ? E 6862 : X; 6863 ErrorFound = NotAScalarType; 6864 ErrorLoc = AtomicBinOp->getExprLoc(); 6865 ErrorRange = AtomicBinOp->getSourceRange(); 6866 NoteLoc = NotScalarExpr->getExprLoc(); 6867 NoteRange = NotScalarExpr->getSourceRange(); 6868 } 6869 } else if (!AtomicBody->isInstantiationDependent()) { 6870 ErrorFound = NotAnAssignmentOp; 6871 ErrorLoc = AtomicBody->getExprLoc(); 6872 ErrorRange = AtomicBody->getSourceRange(); 6873 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6874 : AtomicBody->getExprLoc(); 6875 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6876 : AtomicBody->getSourceRange(); 6877 } 6878 } else { 6879 ErrorFound = NotAnExpression; 6880 NoteLoc = ErrorLoc = Body->getBeginLoc(); 6881 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6882 } 6883 if (ErrorFound != NoError) { 6884 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 6885 << ErrorRange; 6886 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6887 << NoteRange; 6888 return StmtError(); 6889 } 6890 if (CurContext->isDependentContext()) 6891 E = X = nullptr; 6892 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 6893 // If clause is update: 6894 // x++; 6895 // x--; 6896 // ++x; 6897 // --x; 6898 // x binop= expr; 6899 // x = x binop expr; 6900 // x = expr binop x; 6901 OpenMPAtomicUpdateChecker Checker(*this); 6902 if (Checker.checkStatement( 6903 Body, (AtomicKind == OMPC_update) 6904 ? diag::err_omp_atomic_update_not_expression_statement 6905 : diag::err_omp_atomic_not_expression_statement, 6906 diag::note_omp_atomic_update)) 6907 return StmtError(); 6908 if (!CurContext->isDependentContext()) { 6909 E = Checker.getExpr(); 6910 X = Checker.getX(); 6911 UE = Checker.getUpdateExpr(); 6912 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6913 } 6914 } else if (AtomicKind == OMPC_capture) { 6915 enum { 6916 NotAnAssignmentOp, 6917 NotACompoundStatement, 6918 NotTwoSubstatements, 6919 NotASpecificExpression, 6920 NoError 6921 } ErrorFound = NoError; 6922 SourceLocation ErrorLoc, NoteLoc; 6923 SourceRange ErrorRange, NoteRange; 6924 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 6925 // If clause is a capture: 6926 // v = x++; 6927 // v = x--; 6928 // v = ++x; 6929 // v = --x; 6930 // v = x binop= expr; 6931 // v = x = x binop expr; 6932 // v = x = expr binop x; 6933 const auto *AtomicBinOp = 6934 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6935 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6936 V = AtomicBinOp->getLHS(); 6937 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6938 OpenMPAtomicUpdateChecker Checker(*this); 6939 if (Checker.checkStatement( 6940 Body, diag::err_omp_atomic_capture_not_expression_statement, 6941 diag::note_omp_atomic_update)) 6942 return StmtError(); 6943 E = Checker.getExpr(); 6944 X = Checker.getX(); 6945 UE = Checker.getUpdateExpr(); 6946 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6947 IsPostfixUpdate = Checker.isPostfixUpdate(); 6948 } else if (!AtomicBody->isInstantiationDependent()) { 6949 ErrorLoc = AtomicBody->getExprLoc(); 6950 ErrorRange = AtomicBody->getSourceRange(); 6951 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6952 : AtomicBody->getExprLoc(); 6953 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6954 : AtomicBody->getSourceRange(); 6955 ErrorFound = NotAnAssignmentOp; 6956 } 6957 if (ErrorFound != NoError) { 6958 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 6959 << ErrorRange; 6960 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6961 return StmtError(); 6962 } 6963 if (CurContext->isDependentContext()) 6964 UE = V = E = X = nullptr; 6965 } else { 6966 // If clause is a capture: 6967 // { v = x; x = expr; } 6968 // { v = x; x++; } 6969 // { v = x; x--; } 6970 // { v = x; ++x; } 6971 // { v = x; --x; } 6972 // { v = x; x binop= expr; } 6973 // { v = x; x = x binop expr; } 6974 // { v = x; x = expr binop x; } 6975 // { x++; v = x; } 6976 // { x--; v = x; } 6977 // { ++x; v = x; } 6978 // { --x; v = x; } 6979 // { x binop= expr; v = x; } 6980 // { x = x binop expr; v = x; } 6981 // { x = expr binop x; v = x; } 6982 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 6983 // Check that this is { expr1; expr2; } 6984 if (CS->size() == 2) { 6985 Stmt *First = CS->body_front(); 6986 Stmt *Second = CS->body_back(); 6987 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 6988 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 6989 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 6990 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 6991 // Need to find what subexpression is 'v' and what is 'x'. 6992 OpenMPAtomicUpdateChecker Checker(*this); 6993 bool IsUpdateExprFound = !Checker.checkStatement(Second); 6994 BinaryOperator *BinOp = nullptr; 6995 if (IsUpdateExprFound) { 6996 BinOp = dyn_cast<BinaryOperator>(First); 6997 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6998 } 6999 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 7000 // { v = x; x++; } 7001 // { v = x; x--; } 7002 // { v = x; ++x; } 7003 // { v = x; --x; } 7004 // { v = x; x binop= expr; } 7005 // { v = x; x = x binop expr; } 7006 // { v = x; x = expr binop x; } 7007 // Check that the first expression has form v = x. 7008 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 7009 llvm::FoldingSetNodeID XId, PossibleXId; 7010 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 7011 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 7012 IsUpdateExprFound = XId == PossibleXId; 7013 if (IsUpdateExprFound) { 7014 V = BinOp->getLHS(); 7015 X = Checker.getX(); 7016 E = Checker.getExpr(); 7017 UE = Checker.getUpdateExpr(); 7018 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 7019 IsPostfixUpdate = true; 7020 } 7021 } 7022 if (!IsUpdateExprFound) { 7023 IsUpdateExprFound = !Checker.checkStatement(First); 7024 BinOp = nullptr; 7025 if (IsUpdateExprFound) { 7026 BinOp = dyn_cast<BinaryOperator>(Second); 7027 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 7028 } 7029 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 7030 // { x++; v = x; } 7031 // { x--; v = x; } 7032 // { ++x; v = x; } 7033 // { --x; v = x; } 7034 // { x binop= expr; v = x; } 7035 // { x = x binop expr; v = x; } 7036 // { x = expr binop x; v = x; } 7037 // Check that the second expression has form v = x. 7038 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 7039 llvm::FoldingSetNodeID XId, PossibleXId; 7040 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 7041 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 7042 IsUpdateExprFound = XId == PossibleXId; 7043 if (IsUpdateExprFound) { 7044 V = BinOp->getLHS(); 7045 X = Checker.getX(); 7046 E = Checker.getExpr(); 7047 UE = Checker.getUpdateExpr(); 7048 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 7049 IsPostfixUpdate = false; 7050 } 7051 } 7052 } 7053 if (!IsUpdateExprFound) { 7054 // { v = x; x = expr; } 7055 auto *FirstExpr = dyn_cast<Expr>(First); 7056 auto *SecondExpr = dyn_cast<Expr>(Second); 7057 if (!FirstExpr || !SecondExpr || 7058 !(FirstExpr->isInstantiationDependent() || 7059 SecondExpr->isInstantiationDependent())) { 7060 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 7061 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 7062 ErrorFound = NotAnAssignmentOp; 7063 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 7064 : First->getBeginLoc(); 7065 NoteRange = ErrorRange = FirstBinOp 7066 ? FirstBinOp->getSourceRange() 7067 : SourceRange(ErrorLoc, ErrorLoc); 7068 } else { 7069 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 7070 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 7071 ErrorFound = NotAnAssignmentOp; 7072 NoteLoc = ErrorLoc = SecondBinOp 7073 ? SecondBinOp->getOperatorLoc() 7074 : Second->getBeginLoc(); 7075 NoteRange = ErrorRange = 7076 SecondBinOp ? SecondBinOp->getSourceRange() 7077 : SourceRange(ErrorLoc, ErrorLoc); 7078 } else { 7079 Expr *PossibleXRHSInFirst = 7080 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 7081 Expr *PossibleXLHSInSecond = 7082 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 7083 llvm::FoldingSetNodeID X1Id, X2Id; 7084 PossibleXRHSInFirst->Profile(X1Id, Context, 7085 /*Canonical=*/true); 7086 PossibleXLHSInSecond->Profile(X2Id, Context, 7087 /*Canonical=*/true); 7088 IsUpdateExprFound = X1Id == X2Id; 7089 if (IsUpdateExprFound) { 7090 V = FirstBinOp->getLHS(); 7091 X = SecondBinOp->getLHS(); 7092 E = SecondBinOp->getRHS(); 7093 UE = nullptr; 7094 IsXLHSInRHSPart = false; 7095 IsPostfixUpdate = true; 7096 } else { 7097 ErrorFound = NotASpecificExpression; 7098 ErrorLoc = FirstBinOp->getExprLoc(); 7099 ErrorRange = FirstBinOp->getSourceRange(); 7100 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 7101 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 7102 } 7103 } 7104 } 7105 } 7106 } 7107 } else { 7108 NoteLoc = ErrorLoc = Body->getBeginLoc(); 7109 NoteRange = ErrorRange = 7110 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 7111 ErrorFound = NotTwoSubstatements; 7112 } 7113 } else { 7114 NoteLoc = ErrorLoc = Body->getBeginLoc(); 7115 NoteRange = ErrorRange = 7116 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 7117 ErrorFound = NotACompoundStatement; 7118 } 7119 if (ErrorFound != NoError) { 7120 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 7121 << ErrorRange; 7122 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 7123 return StmtError(); 7124 } 7125 if (CurContext->isDependentContext()) 7126 UE = V = E = X = nullptr; 7127 } 7128 } 7129 7130 setFunctionHasBranchProtectedScope(); 7131 7132 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 7133 X, V, E, UE, IsXLHSInRHSPart, 7134 IsPostfixUpdate); 7135 } 7136 7137 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 7138 Stmt *AStmt, 7139 SourceLocation StartLoc, 7140 SourceLocation EndLoc) { 7141 if (!AStmt) 7142 return StmtError(); 7143 7144 auto *CS = cast<CapturedStmt>(AStmt); 7145 // 1.2.2 OpenMP Language Terminology 7146 // Structured block - An executable statement with a single entry at the 7147 // top and a single exit at the bottom. 7148 // The point of exit cannot be a branch out of the structured block. 7149 // longjmp() and throw() must not violate the entry/exit criteria. 7150 CS->getCapturedDecl()->setNothrow(); 7151 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 7152 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7153 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7154 // 1.2.2 OpenMP Language Terminology 7155 // Structured block - An executable statement with a single entry at the 7156 // top and a single exit at the bottom. 7157 // The point of exit cannot be a branch out of the structured block. 7158 // longjmp() and throw() must not violate the entry/exit criteria. 7159 CS->getCapturedDecl()->setNothrow(); 7160 } 7161 7162 // OpenMP [2.16, Nesting of Regions] 7163 // If specified, a teams construct must be contained within a target 7164 // construct. That target construct must contain no statements or directives 7165 // outside of the teams construct. 7166 if (DSAStack->hasInnerTeamsRegion()) { 7167 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 7168 bool OMPTeamsFound = true; 7169 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 7170 auto I = CS->body_begin(); 7171 while (I != CS->body_end()) { 7172 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 7173 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 7174 OMPTeamsFound) { 7175 7176 OMPTeamsFound = false; 7177 break; 7178 } 7179 ++I; 7180 } 7181 assert(I != CS->body_end() && "Not found statement"); 7182 S = *I; 7183 } else { 7184 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 7185 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 7186 } 7187 if (!OMPTeamsFound) { 7188 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 7189 Diag(DSAStack->getInnerTeamsRegionLoc(), 7190 diag::note_omp_nested_teams_construct_here); 7191 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 7192 << isa<OMPExecutableDirective>(S); 7193 return StmtError(); 7194 } 7195 } 7196 7197 setFunctionHasBranchProtectedScope(); 7198 7199 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 7200 } 7201 7202 StmtResult 7203 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 7204 Stmt *AStmt, SourceLocation StartLoc, 7205 SourceLocation EndLoc) { 7206 if (!AStmt) 7207 return StmtError(); 7208 7209 auto *CS = cast<CapturedStmt>(AStmt); 7210 // 1.2.2 OpenMP Language Terminology 7211 // Structured block - An executable statement with a single entry at the 7212 // top and a single exit at the bottom. 7213 // The point of exit cannot be a branch out of the structured block. 7214 // longjmp() and throw() must not violate the entry/exit criteria. 7215 CS->getCapturedDecl()->setNothrow(); 7216 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 7217 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7218 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7219 // 1.2.2 OpenMP Language Terminology 7220 // Structured block - An executable statement with a single entry at the 7221 // top and a single exit at the bottom. 7222 // The point of exit cannot be a branch out of the structured block. 7223 // longjmp() and throw() must not violate the entry/exit criteria. 7224 CS->getCapturedDecl()->setNothrow(); 7225 } 7226 7227 setFunctionHasBranchProtectedScope(); 7228 7229 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 7230 AStmt); 7231 } 7232 7233 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 7234 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7235 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7236 if (!AStmt) 7237 return StmtError(); 7238 7239 auto *CS = cast<CapturedStmt>(AStmt); 7240 // 1.2.2 OpenMP Language Terminology 7241 // Structured block - An executable statement with a single entry at the 7242 // top and a single exit at the bottom. 7243 // The point of exit cannot be a branch out of the structured block. 7244 // longjmp() and throw() must not violate the entry/exit criteria. 7245 CS->getCapturedDecl()->setNothrow(); 7246 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 7247 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7248 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7249 // 1.2.2 OpenMP Language Terminology 7250 // Structured block - An executable statement with a single entry at the 7251 // top and a single exit at the bottom. 7252 // The point of exit cannot be a branch out of the structured block. 7253 // longjmp() and throw() must not violate the entry/exit criteria. 7254 CS->getCapturedDecl()->setNothrow(); 7255 } 7256 7257 OMPLoopDirective::HelperExprs B; 7258 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7259 // define the nested loops number. 7260 unsigned NestedLoopCount = 7261 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 7262 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7263 VarsWithImplicitDSA, B); 7264 if (NestedLoopCount == 0) 7265 return StmtError(); 7266 7267 assert((CurContext->isDependentContext() || B.builtAll()) && 7268 "omp target parallel for loop exprs were not built"); 7269 7270 if (!CurContext->isDependentContext()) { 7271 // Finalize the clauses that need pre-built expressions for CodeGen. 7272 for (OMPClause *C : Clauses) { 7273 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7274 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7275 B.NumIterations, *this, CurScope, 7276 DSAStack)) 7277 return StmtError(); 7278 } 7279 } 7280 7281 setFunctionHasBranchProtectedScope(); 7282 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 7283 NestedLoopCount, Clauses, AStmt, 7284 B, DSAStack->isCancelRegion()); 7285 } 7286 7287 /// Check for existence of a map clause in the list of clauses. 7288 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 7289 const OpenMPClauseKind K) { 7290 return llvm::any_of( 7291 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 7292 } 7293 7294 template <typename... Params> 7295 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 7296 const Params... ClauseTypes) { 7297 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 7298 } 7299 7300 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 7301 Stmt *AStmt, 7302 SourceLocation StartLoc, 7303 SourceLocation EndLoc) { 7304 if (!AStmt) 7305 return StmtError(); 7306 7307 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7308 7309 // OpenMP [2.10.1, Restrictions, p. 97] 7310 // At least one map clause must appear on the directive. 7311 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { 7312 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 7313 << "'map' or 'use_device_ptr'" 7314 << getOpenMPDirectiveName(OMPD_target_data); 7315 return StmtError(); 7316 } 7317 7318 setFunctionHasBranchProtectedScope(); 7319 7320 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 7321 AStmt); 7322 } 7323 7324 StmtResult 7325 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 7326 SourceLocation StartLoc, 7327 SourceLocation EndLoc, Stmt *AStmt) { 7328 if (!AStmt) 7329 return StmtError(); 7330 7331 auto *CS = cast<CapturedStmt>(AStmt); 7332 // 1.2.2 OpenMP Language Terminology 7333 // Structured block - An executable statement with a single entry at the 7334 // top and a single exit at the bottom. 7335 // The point of exit cannot be a branch out of the structured block. 7336 // longjmp() and throw() must not violate the entry/exit criteria. 7337 CS->getCapturedDecl()->setNothrow(); 7338 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 7339 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7340 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7341 // 1.2.2 OpenMP Language Terminology 7342 // Structured block - An executable statement with a single entry at the 7343 // top and a single exit at the bottom. 7344 // The point of exit cannot be a branch out of the structured block. 7345 // longjmp() and throw() must not violate the entry/exit criteria. 7346 CS->getCapturedDecl()->setNothrow(); 7347 } 7348 7349 // OpenMP [2.10.2, Restrictions, p. 99] 7350 // At least one map clause must appear on the directive. 7351 if (!hasClauses(Clauses, OMPC_map)) { 7352 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 7353 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 7354 return StmtError(); 7355 } 7356 7357 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 7358 AStmt); 7359 } 7360 7361 StmtResult 7362 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 7363 SourceLocation StartLoc, 7364 SourceLocation EndLoc, Stmt *AStmt) { 7365 if (!AStmt) 7366 return StmtError(); 7367 7368 auto *CS = cast<CapturedStmt>(AStmt); 7369 // 1.2.2 OpenMP Language Terminology 7370 // Structured block - An executable statement with a single entry at the 7371 // top and a single exit at the bottom. 7372 // The point of exit cannot be a branch out of the structured block. 7373 // longjmp() and throw() must not violate the entry/exit criteria. 7374 CS->getCapturedDecl()->setNothrow(); 7375 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 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 // OpenMP [2.10.3, Restrictions, p. 102] 7387 // At least one map clause must appear on the directive. 7388 if (!hasClauses(Clauses, OMPC_map)) { 7389 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 7390 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 7391 return StmtError(); 7392 } 7393 7394 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 7395 AStmt); 7396 } 7397 7398 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 7399 SourceLocation StartLoc, 7400 SourceLocation EndLoc, 7401 Stmt *AStmt) { 7402 if (!AStmt) 7403 return StmtError(); 7404 7405 auto *CS = cast<CapturedStmt>(AStmt); 7406 // 1.2.2 OpenMP Language Terminology 7407 // Structured block - An executable statement with a single entry at the 7408 // top and a single exit at the bottom. 7409 // The point of exit cannot be a branch out of the structured block. 7410 // longjmp() and throw() must not violate the entry/exit criteria. 7411 CS->getCapturedDecl()->setNothrow(); 7412 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 7413 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7414 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7415 // 1.2.2 OpenMP Language Terminology 7416 // Structured block - An executable statement with a single entry at the 7417 // top and a single exit at the bottom. 7418 // The point of exit cannot be a branch out of the structured block. 7419 // longjmp() and throw() must not violate the entry/exit criteria. 7420 CS->getCapturedDecl()->setNothrow(); 7421 } 7422 7423 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 7424 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 7425 return StmtError(); 7426 } 7427 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 7428 AStmt); 7429 } 7430 7431 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 7432 Stmt *AStmt, SourceLocation StartLoc, 7433 SourceLocation EndLoc) { 7434 if (!AStmt) 7435 return StmtError(); 7436 7437 auto *CS = cast<CapturedStmt>(AStmt); 7438 // 1.2.2 OpenMP Language Terminology 7439 // Structured block - An executable statement with a single entry at the 7440 // top and a single exit at the bottom. 7441 // The point of exit cannot be a branch out of the structured block. 7442 // longjmp() and throw() must not violate the entry/exit criteria. 7443 CS->getCapturedDecl()->setNothrow(); 7444 7445 setFunctionHasBranchProtectedScope(); 7446 7447 DSAStack->setParentTeamsRegionLoc(StartLoc); 7448 7449 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 7450 } 7451 7452 StmtResult 7453 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 7454 SourceLocation EndLoc, 7455 OpenMPDirectiveKind CancelRegion) { 7456 if (DSAStack->isParentNowaitRegion()) { 7457 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 7458 return StmtError(); 7459 } 7460 if (DSAStack->isParentOrderedRegion()) { 7461 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 7462 return StmtError(); 7463 } 7464 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 7465 CancelRegion); 7466 } 7467 7468 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 7469 SourceLocation StartLoc, 7470 SourceLocation EndLoc, 7471 OpenMPDirectiveKind CancelRegion) { 7472 if (DSAStack->isParentNowaitRegion()) { 7473 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 7474 return StmtError(); 7475 } 7476 if (DSAStack->isParentOrderedRegion()) { 7477 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 7478 return StmtError(); 7479 } 7480 DSAStack->setParentCancelRegion(/*Cancel=*/true); 7481 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 7482 CancelRegion); 7483 } 7484 7485 static bool checkGrainsizeNumTasksClauses(Sema &S, 7486 ArrayRef<OMPClause *> Clauses) { 7487 const OMPClause *PrevClause = nullptr; 7488 bool ErrorFound = false; 7489 for (const OMPClause *C : Clauses) { 7490 if (C->getClauseKind() == OMPC_grainsize || 7491 C->getClauseKind() == OMPC_num_tasks) { 7492 if (!PrevClause) 7493 PrevClause = C; 7494 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 7495 S.Diag(C->getBeginLoc(), 7496 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 7497 << getOpenMPClauseName(C->getClauseKind()) 7498 << getOpenMPClauseName(PrevClause->getClauseKind()); 7499 S.Diag(PrevClause->getBeginLoc(), 7500 diag::note_omp_previous_grainsize_num_tasks) 7501 << getOpenMPClauseName(PrevClause->getClauseKind()); 7502 ErrorFound = true; 7503 } 7504 } 7505 } 7506 return ErrorFound; 7507 } 7508 7509 static bool checkReductionClauseWithNogroup(Sema &S, 7510 ArrayRef<OMPClause *> Clauses) { 7511 const OMPClause *ReductionClause = nullptr; 7512 const OMPClause *NogroupClause = nullptr; 7513 for (const OMPClause *C : Clauses) { 7514 if (C->getClauseKind() == OMPC_reduction) { 7515 ReductionClause = C; 7516 if (NogroupClause) 7517 break; 7518 continue; 7519 } 7520 if (C->getClauseKind() == OMPC_nogroup) { 7521 NogroupClause = C; 7522 if (ReductionClause) 7523 break; 7524 continue; 7525 } 7526 } 7527 if (ReductionClause && NogroupClause) { 7528 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 7529 << SourceRange(NogroupClause->getBeginLoc(), 7530 NogroupClause->getEndLoc()); 7531 return true; 7532 } 7533 return false; 7534 } 7535 7536 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 7537 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7538 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7539 if (!AStmt) 7540 return StmtError(); 7541 7542 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7543 OMPLoopDirective::HelperExprs B; 7544 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7545 // define the nested loops number. 7546 unsigned NestedLoopCount = 7547 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 7548 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 7549 VarsWithImplicitDSA, B); 7550 if (NestedLoopCount == 0) 7551 return StmtError(); 7552 7553 assert((CurContext->isDependentContext() || B.builtAll()) && 7554 "omp for loop exprs were not built"); 7555 7556 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7557 // The grainsize clause and num_tasks clause are mutually exclusive and may 7558 // not appear on the same taskloop directive. 7559 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 7560 return StmtError(); 7561 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7562 // If a reduction clause is present on the taskloop directive, the nogroup 7563 // clause must not be specified. 7564 if (checkReductionClauseWithNogroup(*this, Clauses)) 7565 return StmtError(); 7566 7567 setFunctionHasBranchProtectedScope(); 7568 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 7569 NestedLoopCount, Clauses, AStmt, B); 7570 } 7571 7572 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 7573 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7574 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7575 if (!AStmt) 7576 return StmtError(); 7577 7578 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7579 OMPLoopDirective::HelperExprs B; 7580 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7581 // define the nested loops number. 7582 unsigned NestedLoopCount = 7583 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 7584 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 7585 VarsWithImplicitDSA, B); 7586 if (NestedLoopCount == 0) 7587 return StmtError(); 7588 7589 assert((CurContext->isDependentContext() || B.builtAll()) && 7590 "omp for loop exprs were not built"); 7591 7592 if (!CurContext->isDependentContext()) { 7593 // Finalize the clauses that need pre-built expressions for CodeGen. 7594 for (OMPClause *C : Clauses) { 7595 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7596 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7597 B.NumIterations, *this, CurScope, 7598 DSAStack)) 7599 return StmtError(); 7600 } 7601 } 7602 7603 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7604 // The grainsize clause and num_tasks clause are mutually exclusive and may 7605 // not appear on the same taskloop directive. 7606 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 7607 return StmtError(); 7608 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7609 // If a reduction clause is present on the taskloop directive, the nogroup 7610 // clause must not be specified. 7611 if (checkReductionClauseWithNogroup(*this, Clauses)) 7612 return StmtError(); 7613 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7614 return StmtError(); 7615 7616 setFunctionHasBranchProtectedScope(); 7617 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 7618 NestedLoopCount, Clauses, AStmt, B); 7619 } 7620 7621 StmtResult Sema::ActOnOpenMPDistributeDirective( 7622 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7623 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7624 if (!AStmt) 7625 return StmtError(); 7626 7627 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7628 OMPLoopDirective::HelperExprs B; 7629 // In presence of clause 'collapse' with number of loops, it will 7630 // define the nested loops number. 7631 unsigned NestedLoopCount = 7632 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 7633 nullptr /*ordered not a clause on distribute*/, AStmt, 7634 *this, *DSAStack, VarsWithImplicitDSA, B); 7635 if (NestedLoopCount == 0) 7636 return StmtError(); 7637 7638 assert((CurContext->isDependentContext() || B.builtAll()) && 7639 "omp for loop exprs were not built"); 7640 7641 setFunctionHasBranchProtectedScope(); 7642 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 7643 NestedLoopCount, Clauses, AStmt, B); 7644 } 7645 7646 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 7647 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7648 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7649 if (!AStmt) 7650 return StmtError(); 7651 7652 auto *CS = cast<CapturedStmt>(AStmt); 7653 // 1.2.2 OpenMP Language Terminology 7654 // Structured block - An executable statement with a single entry at the 7655 // top and a single exit at the bottom. 7656 // The point of exit cannot be a branch out of the structured block. 7657 // longjmp() and throw() must not violate the entry/exit criteria. 7658 CS->getCapturedDecl()->setNothrow(); 7659 for (int ThisCaptureLevel = 7660 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 7661 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7662 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7663 // 1.2.2 OpenMP Language Terminology 7664 // Structured block - An executable statement with a single entry at the 7665 // top and a single exit at the bottom. 7666 // The point of exit cannot be a branch out of the structured block. 7667 // longjmp() and throw() must not violate the entry/exit criteria. 7668 CS->getCapturedDecl()->setNothrow(); 7669 } 7670 7671 OMPLoopDirective::HelperExprs B; 7672 // In presence of clause 'collapse' with number of loops, it will 7673 // define the nested loops number. 7674 unsigned NestedLoopCount = checkOpenMPLoop( 7675 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7676 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7677 VarsWithImplicitDSA, B); 7678 if (NestedLoopCount == 0) 7679 return StmtError(); 7680 7681 assert((CurContext->isDependentContext() || B.builtAll()) && 7682 "omp for loop exprs were not built"); 7683 7684 setFunctionHasBranchProtectedScope(); 7685 return OMPDistributeParallelForDirective::Create( 7686 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 7687 DSAStack->isCancelRegion()); 7688 } 7689 7690 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 7691 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7692 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7693 if (!AStmt) 7694 return StmtError(); 7695 7696 auto *CS = cast<CapturedStmt>(AStmt); 7697 // 1.2.2 OpenMP Language Terminology 7698 // Structured block - An executable statement with a single entry at the 7699 // top and a single exit at the bottom. 7700 // The point of exit cannot be a branch out of the structured block. 7701 // longjmp() and throw() must not violate the entry/exit criteria. 7702 CS->getCapturedDecl()->setNothrow(); 7703 for (int ThisCaptureLevel = 7704 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 7705 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7706 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7707 // 1.2.2 OpenMP Language Terminology 7708 // Structured block - An executable statement with a single entry at the 7709 // top and a single exit at the bottom. 7710 // The point of exit cannot be a branch out of the structured block. 7711 // longjmp() and throw() must not violate the entry/exit criteria. 7712 CS->getCapturedDecl()->setNothrow(); 7713 } 7714 7715 OMPLoopDirective::HelperExprs B; 7716 // In presence of clause 'collapse' with number of loops, it will 7717 // define the nested loops number. 7718 unsigned NestedLoopCount = checkOpenMPLoop( 7719 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 7720 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7721 VarsWithImplicitDSA, B); 7722 if (NestedLoopCount == 0) 7723 return StmtError(); 7724 7725 assert((CurContext->isDependentContext() || B.builtAll()) && 7726 "omp for loop exprs were not built"); 7727 7728 if (!CurContext->isDependentContext()) { 7729 // Finalize the clauses that need pre-built expressions for CodeGen. 7730 for (OMPClause *C : Clauses) { 7731 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7732 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7733 B.NumIterations, *this, CurScope, 7734 DSAStack)) 7735 return StmtError(); 7736 } 7737 } 7738 7739 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7740 return StmtError(); 7741 7742 setFunctionHasBranchProtectedScope(); 7743 return OMPDistributeParallelForSimdDirective::Create( 7744 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7745 } 7746 7747 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 7748 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7749 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7750 if (!AStmt) 7751 return StmtError(); 7752 7753 auto *CS = cast<CapturedStmt>(AStmt); 7754 // 1.2.2 OpenMP Language Terminology 7755 // Structured block - An executable statement with a single entry at the 7756 // top and a single exit at the bottom. 7757 // The point of exit cannot be a branch out of the structured block. 7758 // longjmp() and throw() must not violate the entry/exit criteria. 7759 CS->getCapturedDecl()->setNothrow(); 7760 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 7761 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7762 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7763 // 1.2.2 OpenMP Language Terminology 7764 // Structured block - An executable statement with a single entry at the 7765 // top and a single exit at the bottom. 7766 // The point of exit cannot be a branch out of the structured block. 7767 // longjmp() and throw() must not violate the entry/exit criteria. 7768 CS->getCapturedDecl()->setNothrow(); 7769 } 7770 7771 OMPLoopDirective::HelperExprs B; 7772 // In presence of clause 'collapse' with number of loops, it will 7773 // define the nested loops number. 7774 unsigned NestedLoopCount = 7775 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 7776 nullptr /*ordered not a clause on distribute*/, CS, *this, 7777 *DSAStack, VarsWithImplicitDSA, B); 7778 if (NestedLoopCount == 0) 7779 return StmtError(); 7780 7781 assert((CurContext->isDependentContext() || B.builtAll()) && 7782 "omp for loop exprs were not built"); 7783 7784 if (!CurContext->isDependentContext()) { 7785 // Finalize the clauses that need pre-built expressions for CodeGen. 7786 for (OMPClause *C : Clauses) { 7787 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7788 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7789 B.NumIterations, *this, CurScope, 7790 DSAStack)) 7791 return StmtError(); 7792 } 7793 } 7794 7795 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7796 return StmtError(); 7797 7798 setFunctionHasBranchProtectedScope(); 7799 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 7800 NestedLoopCount, Clauses, AStmt, B); 7801 } 7802 7803 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 7804 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7805 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7806 if (!AStmt) 7807 return StmtError(); 7808 7809 auto *CS = cast<CapturedStmt>(AStmt); 7810 // 1.2.2 OpenMP Language Terminology 7811 // Structured block - An executable statement with a single entry at the 7812 // top and a single exit at the bottom. 7813 // The point of exit cannot be a branch out of the structured block. 7814 // longjmp() and throw() must not violate the entry/exit criteria. 7815 CS->getCapturedDecl()->setNothrow(); 7816 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 7817 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7818 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7819 // 1.2.2 OpenMP Language Terminology 7820 // Structured block - An executable statement with a single entry at the 7821 // top and a single exit at the bottom. 7822 // The point of exit cannot be a branch out of the structured block. 7823 // longjmp() and throw() must not violate the entry/exit criteria. 7824 CS->getCapturedDecl()->setNothrow(); 7825 } 7826 7827 OMPLoopDirective::HelperExprs B; 7828 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7829 // define the nested loops number. 7830 unsigned NestedLoopCount = checkOpenMPLoop( 7831 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 7832 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7833 VarsWithImplicitDSA, B); 7834 if (NestedLoopCount == 0) 7835 return StmtError(); 7836 7837 assert((CurContext->isDependentContext() || B.builtAll()) && 7838 "omp target parallel for simd loop exprs were not built"); 7839 7840 if (!CurContext->isDependentContext()) { 7841 // Finalize the clauses that need pre-built expressions for CodeGen. 7842 for (OMPClause *C : Clauses) { 7843 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7844 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7845 B.NumIterations, *this, CurScope, 7846 DSAStack)) 7847 return StmtError(); 7848 } 7849 } 7850 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7851 return StmtError(); 7852 7853 setFunctionHasBranchProtectedScope(); 7854 return OMPTargetParallelForSimdDirective::Create( 7855 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7856 } 7857 7858 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 7859 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7860 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7861 if (!AStmt) 7862 return StmtError(); 7863 7864 auto *CS = cast<CapturedStmt>(AStmt); 7865 // 1.2.2 OpenMP Language Terminology 7866 // Structured block - An executable statement with a single entry at the 7867 // top and a single exit at the bottom. 7868 // The point of exit cannot be a branch out of the structured block. 7869 // longjmp() and throw() must not violate the entry/exit criteria. 7870 CS->getCapturedDecl()->setNothrow(); 7871 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 7872 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7873 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7874 // 1.2.2 OpenMP Language Terminology 7875 // Structured block - An executable statement with a single entry at the 7876 // top and a single exit at the bottom. 7877 // The point of exit cannot be a branch out of the structured block. 7878 // longjmp() and throw() must not violate the entry/exit criteria. 7879 CS->getCapturedDecl()->setNothrow(); 7880 } 7881 7882 OMPLoopDirective::HelperExprs B; 7883 // In presence of clause 'collapse' with number of loops, it will define the 7884 // nested loops number. 7885 unsigned NestedLoopCount = 7886 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 7887 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7888 VarsWithImplicitDSA, B); 7889 if (NestedLoopCount == 0) 7890 return StmtError(); 7891 7892 assert((CurContext->isDependentContext() || B.builtAll()) && 7893 "omp target simd loop exprs were not built"); 7894 7895 if (!CurContext->isDependentContext()) { 7896 // Finalize the clauses that need pre-built expressions for CodeGen. 7897 for (OMPClause *C : Clauses) { 7898 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7899 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7900 B.NumIterations, *this, CurScope, 7901 DSAStack)) 7902 return StmtError(); 7903 } 7904 } 7905 7906 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7907 return StmtError(); 7908 7909 setFunctionHasBranchProtectedScope(); 7910 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 7911 NestedLoopCount, Clauses, AStmt, B); 7912 } 7913 7914 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 7915 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7916 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7917 if (!AStmt) 7918 return StmtError(); 7919 7920 auto *CS = cast<CapturedStmt>(AStmt); 7921 // 1.2.2 OpenMP Language Terminology 7922 // Structured block - An executable statement with a single entry at the 7923 // top and a single exit at the bottom. 7924 // The point of exit cannot be a branch out of the structured block. 7925 // longjmp() and throw() must not violate the entry/exit criteria. 7926 CS->getCapturedDecl()->setNothrow(); 7927 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 7928 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7929 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7930 // 1.2.2 OpenMP Language Terminology 7931 // Structured block - An executable statement with a single entry at the 7932 // top and a single exit at the bottom. 7933 // The point of exit cannot be a branch out of the structured block. 7934 // longjmp() and throw() must not violate the entry/exit criteria. 7935 CS->getCapturedDecl()->setNothrow(); 7936 } 7937 7938 OMPLoopDirective::HelperExprs B; 7939 // In presence of clause 'collapse' with number of loops, it will 7940 // define the nested loops number. 7941 unsigned NestedLoopCount = 7942 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 7943 nullptr /*ordered not a clause on distribute*/, CS, *this, 7944 *DSAStack, VarsWithImplicitDSA, B); 7945 if (NestedLoopCount == 0) 7946 return StmtError(); 7947 7948 assert((CurContext->isDependentContext() || B.builtAll()) && 7949 "omp teams distribute loop exprs were not built"); 7950 7951 setFunctionHasBranchProtectedScope(); 7952 7953 DSAStack->setParentTeamsRegionLoc(StartLoc); 7954 7955 return OMPTeamsDistributeDirective::Create( 7956 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7957 } 7958 7959 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 7960 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7961 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7962 if (!AStmt) 7963 return StmtError(); 7964 7965 auto *CS = cast<CapturedStmt>(AStmt); 7966 // 1.2.2 OpenMP Language Terminology 7967 // Structured block - An executable statement with a single entry at the 7968 // top and a single exit at the bottom. 7969 // The point of exit cannot be a branch out of the structured block. 7970 // longjmp() and throw() must not violate the entry/exit criteria. 7971 CS->getCapturedDecl()->setNothrow(); 7972 for (int ThisCaptureLevel = 7973 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 7974 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7975 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7976 // 1.2.2 OpenMP Language Terminology 7977 // Structured block - An executable statement with a single entry at the 7978 // top and a single exit at the bottom. 7979 // The point of exit cannot be a branch out of the structured block. 7980 // longjmp() and throw() must not violate the entry/exit criteria. 7981 CS->getCapturedDecl()->setNothrow(); 7982 } 7983 7984 7985 OMPLoopDirective::HelperExprs B; 7986 // In presence of clause 'collapse' with number of loops, it will 7987 // define the nested loops number. 7988 unsigned NestedLoopCount = checkOpenMPLoop( 7989 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 7990 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7991 VarsWithImplicitDSA, B); 7992 7993 if (NestedLoopCount == 0) 7994 return StmtError(); 7995 7996 assert((CurContext->isDependentContext() || B.builtAll()) && 7997 "omp teams distribute simd loop exprs were not built"); 7998 7999 if (!CurContext->isDependentContext()) { 8000 // Finalize the clauses that need pre-built expressions for CodeGen. 8001 for (OMPClause *C : Clauses) { 8002 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8003 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8004 B.NumIterations, *this, CurScope, 8005 DSAStack)) 8006 return StmtError(); 8007 } 8008 } 8009 8010 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8011 return StmtError(); 8012 8013 setFunctionHasBranchProtectedScope(); 8014 8015 DSAStack->setParentTeamsRegionLoc(StartLoc); 8016 8017 return OMPTeamsDistributeSimdDirective::Create( 8018 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8019 } 8020 8021 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 8022 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8023 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8024 if (!AStmt) 8025 return StmtError(); 8026 8027 auto *CS = cast<CapturedStmt>(AStmt); 8028 // 1.2.2 OpenMP Language Terminology 8029 // Structured block - An executable statement with a single entry at the 8030 // top and a single exit at the bottom. 8031 // The point of exit cannot be a branch out of the structured block. 8032 // longjmp() and throw() must not violate the entry/exit criteria. 8033 CS->getCapturedDecl()->setNothrow(); 8034 8035 for (int ThisCaptureLevel = 8036 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 8037 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8038 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8039 // 1.2.2 OpenMP Language Terminology 8040 // Structured block - An executable statement with a single entry at the 8041 // top and a single exit at the bottom. 8042 // The point of exit cannot be a branch out of the structured block. 8043 // longjmp() and throw() must not violate the entry/exit criteria. 8044 CS->getCapturedDecl()->setNothrow(); 8045 } 8046 8047 OMPLoopDirective::HelperExprs B; 8048 // In presence of clause 'collapse' with number of loops, it will 8049 // define the nested loops number. 8050 unsigned NestedLoopCount = checkOpenMPLoop( 8051 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 8052 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8053 VarsWithImplicitDSA, B); 8054 8055 if (NestedLoopCount == 0) 8056 return StmtError(); 8057 8058 assert((CurContext->isDependentContext() || B.builtAll()) && 8059 "omp for loop exprs were not built"); 8060 8061 if (!CurContext->isDependentContext()) { 8062 // Finalize the clauses that need pre-built expressions for CodeGen. 8063 for (OMPClause *C : Clauses) { 8064 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8065 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8066 B.NumIterations, *this, CurScope, 8067 DSAStack)) 8068 return StmtError(); 8069 } 8070 } 8071 8072 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8073 return StmtError(); 8074 8075 setFunctionHasBranchProtectedScope(); 8076 8077 DSAStack->setParentTeamsRegionLoc(StartLoc); 8078 8079 return OMPTeamsDistributeParallelForSimdDirective::Create( 8080 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8081 } 8082 8083 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 8084 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8085 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8086 if (!AStmt) 8087 return StmtError(); 8088 8089 auto *CS = cast<CapturedStmt>(AStmt); 8090 // 1.2.2 OpenMP Language Terminology 8091 // Structured block - An executable statement with a single entry at the 8092 // top and a single exit at the bottom. 8093 // The point of exit cannot be a branch out of the structured block. 8094 // longjmp() and throw() must not violate the entry/exit criteria. 8095 CS->getCapturedDecl()->setNothrow(); 8096 8097 for (int ThisCaptureLevel = 8098 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 8099 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8100 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8101 // 1.2.2 OpenMP Language Terminology 8102 // Structured block - An executable statement with a single entry at the 8103 // top and a single exit at the bottom. 8104 // The point of exit cannot be a branch out of the structured block. 8105 // longjmp() and throw() must not violate the entry/exit criteria. 8106 CS->getCapturedDecl()->setNothrow(); 8107 } 8108 8109 OMPLoopDirective::HelperExprs B; 8110 // In presence of clause 'collapse' with number of loops, it will 8111 // define the nested loops number. 8112 unsigned NestedLoopCount = checkOpenMPLoop( 8113 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 8114 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8115 VarsWithImplicitDSA, B); 8116 8117 if (NestedLoopCount == 0) 8118 return StmtError(); 8119 8120 assert((CurContext->isDependentContext() || B.builtAll()) && 8121 "omp for loop exprs were not built"); 8122 8123 setFunctionHasBranchProtectedScope(); 8124 8125 DSAStack->setParentTeamsRegionLoc(StartLoc); 8126 8127 return OMPTeamsDistributeParallelForDirective::Create( 8128 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 8129 DSAStack->isCancelRegion()); 8130 } 8131 8132 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 8133 Stmt *AStmt, 8134 SourceLocation StartLoc, 8135 SourceLocation EndLoc) { 8136 if (!AStmt) 8137 return StmtError(); 8138 8139 auto *CS = cast<CapturedStmt>(AStmt); 8140 // 1.2.2 OpenMP Language Terminology 8141 // Structured block - An executable statement with a single entry at the 8142 // top and a single exit at the bottom. 8143 // The point of exit cannot be a branch out of the structured block. 8144 // longjmp() and throw() must not violate the entry/exit criteria. 8145 CS->getCapturedDecl()->setNothrow(); 8146 8147 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 8148 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8149 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8150 // 1.2.2 OpenMP Language Terminology 8151 // Structured block - An executable statement with a single entry at the 8152 // top and a single exit at the bottom. 8153 // The point of exit cannot be a branch out of the structured block. 8154 // longjmp() and throw() must not violate the entry/exit criteria. 8155 CS->getCapturedDecl()->setNothrow(); 8156 } 8157 setFunctionHasBranchProtectedScope(); 8158 8159 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 8160 AStmt); 8161 } 8162 8163 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 8164 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8165 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8166 if (!AStmt) 8167 return StmtError(); 8168 8169 auto *CS = cast<CapturedStmt>(AStmt); 8170 // 1.2.2 OpenMP Language Terminology 8171 // Structured block - An executable statement with a single entry at the 8172 // top and a single exit at the bottom. 8173 // The point of exit cannot be a branch out of the structured block. 8174 // longjmp() and throw() must not violate the entry/exit criteria. 8175 CS->getCapturedDecl()->setNothrow(); 8176 for (int ThisCaptureLevel = 8177 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 8178 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8179 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8180 // 1.2.2 OpenMP Language Terminology 8181 // Structured block - An executable statement with a single entry at the 8182 // top and a single exit at the bottom. 8183 // The point of exit cannot be a branch out of the structured block. 8184 // longjmp() and throw() must not violate the entry/exit criteria. 8185 CS->getCapturedDecl()->setNothrow(); 8186 } 8187 8188 OMPLoopDirective::HelperExprs B; 8189 // In presence of clause 'collapse' with number of loops, it will 8190 // define the nested loops number. 8191 unsigned NestedLoopCount = checkOpenMPLoop( 8192 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 8193 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8194 VarsWithImplicitDSA, B); 8195 if (NestedLoopCount == 0) 8196 return StmtError(); 8197 8198 assert((CurContext->isDependentContext() || B.builtAll()) && 8199 "omp target teams distribute loop exprs were not built"); 8200 8201 setFunctionHasBranchProtectedScope(); 8202 return OMPTargetTeamsDistributeDirective::Create( 8203 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8204 } 8205 8206 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 8207 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8208 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8209 if (!AStmt) 8210 return StmtError(); 8211 8212 auto *CS = cast<CapturedStmt>(AStmt); 8213 // 1.2.2 OpenMP Language Terminology 8214 // Structured block - An executable statement with a single entry at the 8215 // top and a single exit at the bottom. 8216 // The point of exit cannot be a branch out of the structured block. 8217 // longjmp() and throw() must not violate the entry/exit criteria. 8218 CS->getCapturedDecl()->setNothrow(); 8219 for (int ThisCaptureLevel = 8220 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 8221 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8222 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8223 // 1.2.2 OpenMP Language Terminology 8224 // Structured block - An executable statement with a single entry at the 8225 // top and a single exit at the bottom. 8226 // The point of exit cannot be a branch out of the structured block. 8227 // longjmp() and throw() must not violate the entry/exit criteria. 8228 CS->getCapturedDecl()->setNothrow(); 8229 } 8230 8231 OMPLoopDirective::HelperExprs B; 8232 // In presence of clause 'collapse' with number of loops, it will 8233 // define the nested loops number. 8234 unsigned NestedLoopCount = checkOpenMPLoop( 8235 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 8236 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8237 VarsWithImplicitDSA, B); 8238 if (NestedLoopCount == 0) 8239 return StmtError(); 8240 8241 assert((CurContext->isDependentContext() || B.builtAll()) && 8242 "omp target teams distribute parallel for loop exprs were not built"); 8243 8244 if (!CurContext->isDependentContext()) { 8245 // Finalize the clauses that need pre-built expressions for CodeGen. 8246 for (OMPClause *C : Clauses) { 8247 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8248 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8249 B.NumIterations, *this, CurScope, 8250 DSAStack)) 8251 return StmtError(); 8252 } 8253 } 8254 8255 setFunctionHasBranchProtectedScope(); 8256 return OMPTargetTeamsDistributeParallelForDirective::Create( 8257 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 8258 DSAStack->isCancelRegion()); 8259 } 8260 8261 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 8262 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8263 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8264 if (!AStmt) 8265 return StmtError(); 8266 8267 auto *CS = cast<CapturedStmt>(AStmt); 8268 // 1.2.2 OpenMP Language Terminology 8269 // Structured block - An executable statement with a single entry at the 8270 // top and a single exit at the bottom. 8271 // The point of exit cannot be a branch out of the structured block. 8272 // longjmp() and throw() must not violate the entry/exit criteria. 8273 CS->getCapturedDecl()->setNothrow(); 8274 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 8275 OMPD_target_teams_distribute_parallel_for_simd); 8276 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8277 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8278 // 1.2.2 OpenMP Language Terminology 8279 // Structured block - An executable statement with a single entry at the 8280 // top and a single exit at the bottom. 8281 // The point of exit cannot be a branch out of the structured block. 8282 // longjmp() and throw() must not violate the entry/exit criteria. 8283 CS->getCapturedDecl()->setNothrow(); 8284 } 8285 8286 OMPLoopDirective::HelperExprs B; 8287 // In presence of clause 'collapse' with number of loops, it will 8288 // define the nested loops number. 8289 unsigned NestedLoopCount = 8290 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 8291 getCollapseNumberExpr(Clauses), 8292 nullptr /*ordered not a clause on distribute*/, CS, *this, 8293 *DSAStack, VarsWithImplicitDSA, B); 8294 if (NestedLoopCount == 0) 8295 return StmtError(); 8296 8297 assert((CurContext->isDependentContext() || B.builtAll()) && 8298 "omp target teams distribute parallel for simd loop exprs were not " 8299 "built"); 8300 8301 if (!CurContext->isDependentContext()) { 8302 // Finalize the clauses that need pre-built expressions for CodeGen. 8303 for (OMPClause *C : Clauses) { 8304 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8305 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8306 B.NumIterations, *this, CurScope, 8307 DSAStack)) 8308 return StmtError(); 8309 } 8310 } 8311 8312 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8313 return StmtError(); 8314 8315 setFunctionHasBranchProtectedScope(); 8316 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 8317 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8318 } 8319 8320 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 8321 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8322 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8323 if (!AStmt) 8324 return StmtError(); 8325 8326 auto *CS = cast<CapturedStmt>(AStmt); 8327 // 1.2.2 OpenMP Language Terminology 8328 // Structured block - An executable statement with a single entry at the 8329 // top and a single exit at the bottom. 8330 // The point of exit cannot be a branch out of the structured block. 8331 // longjmp() and throw() must not violate the entry/exit criteria. 8332 CS->getCapturedDecl()->setNothrow(); 8333 for (int ThisCaptureLevel = 8334 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 8335 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8336 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8337 // 1.2.2 OpenMP Language Terminology 8338 // Structured block - An executable statement with a single entry at the 8339 // top and a single exit at the bottom. 8340 // The point of exit cannot be a branch out of the structured block. 8341 // longjmp() and throw() must not violate the entry/exit criteria. 8342 CS->getCapturedDecl()->setNothrow(); 8343 } 8344 8345 OMPLoopDirective::HelperExprs B; 8346 // In presence of clause 'collapse' with number of loops, it will 8347 // define the nested loops number. 8348 unsigned NestedLoopCount = checkOpenMPLoop( 8349 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 8350 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8351 VarsWithImplicitDSA, B); 8352 if (NestedLoopCount == 0) 8353 return StmtError(); 8354 8355 assert((CurContext->isDependentContext() || B.builtAll()) && 8356 "omp target teams distribute simd loop exprs were not built"); 8357 8358 if (!CurContext->isDependentContext()) { 8359 // Finalize the clauses that need pre-built expressions for CodeGen. 8360 for (OMPClause *C : Clauses) { 8361 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8362 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8363 B.NumIterations, *this, CurScope, 8364 DSAStack)) 8365 return StmtError(); 8366 } 8367 } 8368 8369 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8370 return StmtError(); 8371 8372 setFunctionHasBranchProtectedScope(); 8373 return OMPTargetTeamsDistributeSimdDirective::Create( 8374 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8375 } 8376 8377 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 8378 SourceLocation StartLoc, 8379 SourceLocation LParenLoc, 8380 SourceLocation EndLoc) { 8381 OMPClause *Res = nullptr; 8382 switch (Kind) { 8383 case OMPC_final: 8384 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 8385 break; 8386 case OMPC_num_threads: 8387 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 8388 break; 8389 case OMPC_safelen: 8390 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 8391 break; 8392 case OMPC_simdlen: 8393 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 8394 break; 8395 case OMPC_collapse: 8396 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 8397 break; 8398 case OMPC_ordered: 8399 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 8400 break; 8401 case OMPC_device: 8402 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 8403 break; 8404 case OMPC_num_teams: 8405 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 8406 break; 8407 case OMPC_thread_limit: 8408 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 8409 break; 8410 case OMPC_priority: 8411 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 8412 break; 8413 case OMPC_grainsize: 8414 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 8415 break; 8416 case OMPC_num_tasks: 8417 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 8418 break; 8419 case OMPC_hint: 8420 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 8421 break; 8422 case OMPC_if: 8423 case OMPC_default: 8424 case OMPC_proc_bind: 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_nowait: 8438 case OMPC_untied: 8439 case OMPC_mergeable: 8440 case OMPC_threadprivate: 8441 case OMPC_allocate: 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_threads: 8450 case OMPC_simd: 8451 case OMPC_map: 8452 case OMPC_nogroup: 8453 case OMPC_dist_schedule: 8454 case OMPC_defaultmap: 8455 case OMPC_unknown: 8456 case OMPC_uniform: 8457 case OMPC_to: 8458 case OMPC_from: 8459 case OMPC_use_device_ptr: 8460 case OMPC_is_device_ptr: 8461 case OMPC_unified_address: 8462 case OMPC_unified_shared_memory: 8463 case OMPC_reverse_offload: 8464 case OMPC_dynamic_allocators: 8465 case OMPC_atomic_default_mem_order: 8466 llvm_unreachable("Clause is not allowed."); 8467 } 8468 return Res; 8469 } 8470 8471 // An OpenMP directive such as 'target parallel' has two captured regions: 8472 // for the 'target' and 'parallel' respectively. This function returns 8473 // the region in which to capture expressions associated with a clause. 8474 // A return value of OMPD_unknown signifies that the expression should not 8475 // be captured. 8476 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 8477 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 8478 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 8479 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 8480 switch (CKind) { 8481 case OMPC_if: 8482 switch (DKind) { 8483 case OMPD_target_parallel: 8484 case OMPD_target_parallel_for: 8485 case OMPD_target_parallel_for_simd: 8486 // If this clause applies to the nested 'parallel' region, capture within 8487 // the 'target' region, otherwise do not capture. 8488 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 8489 CaptureRegion = OMPD_target; 8490 break; 8491 case OMPD_target_teams_distribute_parallel_for: 8492 case OMPD_target_teams_distribute_parallel_for_simd: 8493 // If this clause applies to the nested 'parallel' region, capture within 8494 // the 'teams' region, otherwise do not capture. 8495 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 8496 CaptureRegion = OMPD_teams; 8497 break; 8498 case OMPD_teams_distribute_parallel_for: 8499 case OMPD_teams_distribute_parallel_for_simd: 8500 CaptureRegion = OMPD_teams; 8501 break; 8502 case OMPD_target_update: 8503 case OMPD_target_enter_data: 8504 case OMPD_target_exit_data: 8505 CaptureRegion = OMPD_task; 8506 break; 8507 case OMPD_cancel: 8508 case OMPD_parallel: 8509 case OMPD_parallel_sections: 8510 case OMPD_parallel_for: 8511 case OMPD_parallel_for_simd: 8512 case OMPD_target: 8513 case OMPD_target_simd: 8514 case OMPD_target_teams: 8515 case OMPD_target_teams_distribute: 8516 case OMPD_target_teams_distribute_simd: 8517 case OMPD_distribute_parallel_for: 8518 case OMPD_distribute_parallel_for_simd: 8519 case OMPD_task: 8520 case OMPD_taskloop: 8521 case OMPD_taskloop_simd: 8522 case OMPD_target_data: 8523 // Do not capture if-clause expressions. 8524 break; 8525 case OMPD_threadprivate: 8526 case OMPD_allocate: 8527 case OMPD_taskyield: 8528 case OMPD_barrier: 8529 case OMPD_taskwait: 8530 case OMPD_cancellation_point: 8531 case OMPD_flush: 8532 case OMPD_declare_reduction: 8533 case OMPD_declare_mapper: 8534 case OMPD_declare_simd: 8535 case OMPD_declare_target: 8536 case OMPD_end_declare_target: 8537 case OMPD_teams: 8538 case OMPD_simd: 8539 case OMPD_for: 8540 case OMPD_for_simd: 8541 case OMPD_sections: 8542 case OMPD_section: 8543 case OMPD_single: 8544 case OMPD_master: 8545 case OMPD_critical: 8546 case OMPD_taskgroup: 8547 case OMPD_distribute: 8548 case OMPD_ordered: 8549 case OMPD_atomic: 8550 case OMPD_distribute_simd: 8551 case OMPD_teams_distribute: 8552 case OMPD_teams_distribute_simd: 8553 case OMPD_requires: 8554 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 8555 case OMPD_unknown: 8556 llvm_unreachable("Unknown OpenMP directive"); 8557 } 8558 break; 8559 case OMPC_num_threads: 8560 switch (DKind) { 8561 case OMPD_target_parallel: 8562 case OMPD_target_parallel_for: 8563 case OMPD_target_parallel_for_simd: 8564 CaptureRegion = OMPD_target; 8565 break; 8566 case OMPD_teams_distribute_parallel_for: 8567 case OMPD_teams_distribute_parallel_for_simd: 8568 case OMPD_target_teams_distribute_parallel_for: 8569 case OMPD_target_teams_distribute_parallel_for_simd: 8570 CaptureRegion = OMPD_teams; 8571 break; 8572 case OMPD_parallel: 8573 case OMPD_parallel_sections: 8574 case OMPD_parallel_for: 8575 case OMPD_parallel_for_simd: 8576 case OMPD_distribute_parallel_for: 8577 case OMPD_distribute_parallel_for_simd: 8578 // Do not capture num_threads-clause expressions. 8579 break; 8580 case OMPD_target_data: 8581 case OMPD_target_enter_data: 8582 case OMPD_target_exit_data: 8583 case OMPD_target_update: 8584 case OMPD_target: 8585 case OMPD_target_simd: 8586 case OMPD_target_teams: 8587 case OMPD_target_teams_distribute: 8588 case OMPD_target_teams_distribute_simd: 8589 case OMPD_cancel: 8590 case OMPD_task: 8591 case OMPD_taskloop: 8592 case OMPD_taskloop_simd: 8593 case OMPD_threadprivate: 8594 case OMPD_allocate: 8595 case OMPD_taskyield: 8596 case OMPD_barrier: 8597 case OMPD_taskwait: 8598 case OMPD_cancellation_point: 8599 case OMPD_flush: 8600 case OMPD_declare_reduction: 8601 case OMPD_declare_mapper: 8602 case OMPD_declare_simd: 8603 case OMPD_declare_target: 8604 case OMPD_end_declare_target: 8605 case OMPD_teams: 8606 case OMPD_simd: 8607 case OMPD_for: 8608 case OMPD_for_simd: 8609 case OMPD_sections: 8610 case OMPD_section: 8611 case OMPD_single: 8612 case OMPD_master: 8613 case OMPD_critical: 8614 case OMPD_taskgroup: 8615 case OMPD_distribute: 8616 case OMPD_ordered: 8617 case OMPD_atomic: 8618 case OMPD_distribute_simd: 8619 case OMPD_teams_distribute: 8620 case OMPD_teams_distribute_simd: 8621 case OMPD_requires: 8622 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 8623 case OMPD_unknown: 8624 llvm_unreachable("Unknown OpenMP directive"); 8625 } 8626 break; 8627 case OMPC_num_teams: 8628 switch (DKind) { 8629 case OMPD_target_teams: 8630 case OMPD_target_teams_distribute: 8631 case OMPD_target_teams_distribute_simd: 8632 case OMPD_target_teams_distribute_parallel_for: 8633 case OMPD_target_teams_distribute_parallel_for_simd: 8634 CaptureRegion = OMPD_target; 8635 break; 8636 case OMPD_teams_distribute_parallel_for: 8637 case OMPD_teams_distribute_parallel_for_simd: 8638 case OMPD_teams: 8639 case OMPD_teams_distribute: 8640 case OMPD_teams_distribute_simd: 8641 // Do not capture num_teams-clause expressions. 8642 break; 8643 case OMPD_distribute_parallel_for: 8644 case OMPD_distribute_parallel_for_simd: 8645 case OMPD_task: 8646 case OMPD_taskloop: 8647 case OMPD_taskloop_simd: 8648 case OMPD_target_data: 8649 case OMPD_target_enter_data: 8650 case OMPD_target_exit_data: 8651 case OMPD_target_update: 8652 case OMPD_cancel: 8653 case OMPD_parallel: 8654 case OMPD_parallel_sections: 8655 case OMPD_parallel_for: 8656 case OMPD_parallel_for_simd: 8657 case OMPD_target: 8658 case OMPD_target_simd: 8659 case OMPD_target_parallel: 8660 case OMPD_target_parallel_for: 8661 case OMPD_target_parallel_for_simd: 8662 case OMPD_threadprivate: 8663 case OMPD_allocate: 8664 case OMPD_taskyield: 8665 case OMPD_barrier: 8666 case OMPD_taskwait: 8667 case OMPD_cancellation_point: 8668 case OMPD_flush: 8669 case OMPD_declare_reduction: 8670 case OMPD_declare_mapper: 8671 case OMPD_declare_simd: 8672 case OMPD_declare_target: 8673 case OMPD_end_declare_target: 8674 case OMPD_simd: 8675 case OMPD_for: 8676 case OMPD_for_simd: 8677 case OMPD_sections: 8678 case OMPD_section: 8679 case OMPD_single: 8680 case OMPD_master: 8681 case OMPD_critical: 8682 case OMPD_taskgroup: 8683 case OMPD_distribute: 8684 case OMPD_ordered: 8685 case OMPD_atomic: 8686 case OMPD_distribute_simd: 8687 case OMPD_requires: 8688 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 8689 case OMPD_unknown: 8690 llvm_unreachable("Unknown OpenMP directive"); 8691 } 8692 break; 8693 case OMPC_thread_limit: 8694 switch (DKind) { 8695 case OMPD_target_teams: 8696 case OMPD_target_teams_distribute: 8697 case OMPD_target_teams_distribute_simd: 8698 case OMPD_target_teams_distribute_parallel_for: 8699 case OMPD_target_teams_distribute_parallel_for_simd: 8700 CaptureRegion = OMPD_target; 8701 break; 8702 case OMPD_teams_distribute_parallel_for: 8703 case OMPD_teams_distribute_parallel_for_simd: 8704 case OMPD_teams: 8705 case OMPD_teams_distribute: 8706 case OMPD_teams_distribute_simd: 8707 // Do not capture thread_limit-clause expressions. 8708 break; 8709 case OMPD_distribute_parallel_for: 8710 case OMPD_distribute_parallel_for_simd: 8711 case OMPD_task: 8712 case OMPD_taskloop: 8713 case OMPD_taskloop_simd: 8714 case OMPD_target_data: 8715 case OMPD_target_enter_data: 8716 case OMPD_target_exit_data: 8717 case OMPD_target_update: 8718 case OMPD_cancel: 8719 case OMPD_parallel: 8720 case OMPD_parallel_sections: 8721 case OMPD_parallel_for: 8722 case OMPD_parallel_for_simd: 8723 case OMPD_target: 8724 case OMPD_target_simd: 8725 case OMPD_target_parallel: 8726 case OMPD_target_parallel_for: 8727 case OMPD_target_parallel_for_simd: 8728 case OMPD_threadprivate: 8729 case OMPD_allocate: 8730 case OMPD_taskyield: 8731 case OMPD_barrier: 8732 case OMPD_taskwait: 8733 case OMPD_cancellation_point: 8734 case OMPD_flush: 8735 case OMPD_declare_reduction: 8736 case OMPD_declare_mapper: 8737 case OMPD_declare_simd: 8738 case OMPD_declare_target: 8739 case OMPD_end_declare_target: 8740 case OMPD_simd: 8741 case OMPD_for: 8742 case OMPD_for_simd: 8743 case OMPD_sections: 8744 case OMPD_section: 8745 case OMPD_single: 8746 case OMPD_master: 8747 case OMPD_critical: 8748 case OMPD_taskgroup: 8749 case OMPD_distribute: 8750 case OMPD_ordered: 8751 case OMPD_atomic: 8752 case OMPD_distribute_simd: 8753 case OMPD_requires: 8754 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 8755 case OMPD_unknown: 8756 llvm_unreachable("Unknown OpenMP directive"); 8757 } 8758 break; 8759 case OMPC_schedule: 8760 switch (DKind) { 8761 case OMPD_parallel_for: 8762 case OMPD_parallel_for_simd: 8763 case OMPD_distribute_parallel_for: 8764 case OMPD_distribute_parallel_for_simd: 8765 case OMPD_teams_distribute_parallel_for: 8766 case OMPD_teams_distribute_parallel_for_simd: 8767 case OMPD_target_parallel_for: 8768 case OMPD_target_parallel_for_simd: 8769 case OMPD_target_teams_distribute_parallel_for: 8770 case OMPD_target_teams_distribute_parallel_for_simd: 8771 CaptureRegion = OMPD_parallel; 8772 break; 8773 case OMPD_for: 8774 case OMPD_for_simd: 8775 // Do not capture schedule-clause expressions. 8776 break; 8777 case OMPD_task: 8778 case OMPD_taskloop: 8779 case OMPD_taskloop_simd: 8780 case OMPD_target_data: 8781 case OMPD_target_enter_data: 8782 case OMPD_target_exit_data: 8783 case OMPD_target_update: 8784 case OMPD_teams: 8785 case OMPD_teams_distribute: 8786 case OMPD_teams_distribute_simd: 8787 case OMPD_target_teams_distribute: 8788 case OMPD_target_teams_distribute_simd: 8789 case OMPD_target: 8790 case OMPD_target_simd: 8791 case OMPD_target_parallel: 8792 case OMPD_cancel: 8793 case OMPD_parallel: 8794 case OMPD_parallel_sections: 8795 case OMPD_threadprivate: 8796 case OMPD_allocate: 8797 case OMPD_taskyield: 8798 case OMPD_barrier: 8799 case OMPD_taskwait: 8800 case OMPD_cancellation_point: 8801 case OMPD_flush: 8802 case OMPD_declare_reduction: 8803 case OMPD_declare_mapper: 8804 case OMPD_declare_simd: 8805 case OMPD_declare_target: 8806 case OMPD_end_declare_target: 8807 case OMPD_simd: 8808 case OMPD_sections: 8809 case OMPD_section: 8810 case OMPD_single: 8811 case OMPD_master: 8812 case OMPD_critical: 8813 case OMPD_taskgroup: 8814 case OMPD_distribute: 8815 case OMPD_ordered: 8816 case OMPD_atomic: 8817 case OMPD_distribute_simd: 8818 case OMPD_target_teams: 8819 case OMPD_requires: 8820 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 8821 case OMPD_unknown: 8822 llvm_unreachable("Unknown OpenMP directive"); 8823 } 8824 break; 8825 case OMPC_dist_schedule: 8826 switch (DKind) { 8827 case OMPD_teams_distribute_parallel_for: 8828 case OMPD_teams_distribute_parallel_for_simd: 8829 case OMPD_teams_distribute: 8830 case OMPD_teams_distribute_simd: 8831 case OMPD_target_teams_distribute_parallel_for: 8832 case OMPD_target_teams_distribute_parallel_for_simd: 8833 case OMPD_target_teams_distribute: 8834 case OMPD_target_teams_distribute_simd: 8835 CaptureRegion = OMPD_teams; 8836 break; 8837 case OMPD_distribute_parallel_for: 8838 case OMPD_distribute_parallel_for_simd: 8839 case OMPD_distribute: 8840 case OMPD_distribute_simd: 8841 // Do not capture thread_limit-clause expressions. 8842 break; 8843 case OMPD_parallel_for: 8844 case OMPD_parallel_for_simd: 8845 case OMPD_target_parallel_for_simd: 8846 case OMPD_target_parallel_for: 8847 case OMPD_task: 8848 case OMPD_taskloop: 8849 case OMPD_taskloop_simd: 8850 case OMPD_target_data: 8851 case OMPD_target_enter_data: 8852 case OMPD_target_exit_data: 8853 case OMPD_target_update: 8854 case OMPD_teams: 8855 case OMPD_target: 8856 case OMPD_target_simd: 8857 case OMPD_target_parallel: 8858 case OMPD_cancel: 8859 case OMPD_parallel: 8860 case OMPD_parallel_sections: 8861 case OMPD_threadprivate: 8862 case OMPD_allocate: 8863 case OMPD_taskyield: 8864 case OMPD_barrier: 8865 case OMPD_taskwait: 8866 case OMPD_cancellation_point: 8867 case OMPD_flush: 8868 case OMPD_declare_reduction: 8869 case OMPD_declare_mapper: 8870 case OMPD_declare_simd: 8871 case OMPD_declare_target: 8872 case OMPD_end_declare_target: 8873 case OMPD_simd: 8874 case OMPD_for: 8875 case OMPD_for_simd: 8876 case OMPD_sections: 8877 case OMPD_section: 8878 case OMPD_single: 8879 case OMPD_master: 8880 case OMPD_critical: 8881 case OMPD_taskgroup: 8882 case OMPD_ordered: 8883 case OMPD_atomic: 8884 case OMPD_target_teams: 8885 case OMPD_requires: 8886 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 8887 case OMPD_unknown: 8888 llvm_unreachable("Unknown OpenMP directive"); 8889 } 8890 break; 8891 case OMPC_device: 8892 switch (DKind) { 8893 case OMPD_target_update: 8894 case OMPD_target_enter_data: 8895 case OMPD_target_exit_data: 8896 case OMPD_target: 8897 case OMPD_target_simd: 8898 case OMPD_target_teams: 8899 case OMPD_target_parallel: 8900 case OMPD_target_teams_distribute: 8901 case OMPD_target_teams_distribute_simd: 8902 case OMPD_target_parallel_for: 8903 case OMPD_target_parallel_for_simd: 8904 case OMPD_target_teams_distribute_parallel_for: 8905 case OMPD_target_teams_distribute_parallel_for_simd: 8906 CaptureRegion = OMPD_task; 8907 break; 8908 case OMPD_target_data: 8909 // Do not capture device-clause expressions. 8910 break; 8911 case OMPD_teams_distribute_parallel_for: 8912 case OMPD_teams_distribute_parallel_for_simd: 8913 case OMPD_teams: 8914 case OMPD_teams_distribute: 8915 case OMPD_teams_distribute_simd: 8916 case OMPD_distribute_parallel_for: 8917 case OMPD_distribute_parallel_for_simd: 8918 case OMPD_task: 8919 case OMPD_taskloop: 8920 case OMPD_taskloop_simd: 8921 case OMPD_cancel: 8922 case OMPD_parallel: 8923 case OMPD_parallel_sections: 8924 case OMPD_parallel_for: 8925 case OMPD_parallel_for_simd: 8926 case OMPD_threadprivate: 8927 case OMPD_allocate: 8928 case OMPD_taskyield: 8929 case OMPD_barrier: 8930 case OMPD_taskwait: 8931 case OMPD_cancellation_point: 8932 case OMPD_flush: 8933 case OMPD_declare_reduction: 8934 case OMPD_declare_mapper: 8935 case OMPD_declare_simd: 8936 case OMPD_declare_target: 8937 case OMPD_end_declare_target: 8938 case OMPD_simd: 8939 case OMPD_for: 8940 case OMPD_for_simd: 8941 case OMPD_sections: 8942 case OMPD_section: 8943 case OMPD_single: 8944 case OMPD_master: 8945 case OMPD_critical: 8946 case OMPD_taskgroup: 8947 case OMPD_distribute: 8948 case OMPD_ordered: 8949 case OMPD_atomic: 8950 case OMPD_distribute_simd: 8951 case OMPD_requires: 8952 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 8953 case OMPD_unknown: 8954 llvm_unreachable("Unknown OpenMP directive"); 8955 } 8956 break; 8957 case OMPC_firstprivate: 8958 case OMPC_lastprivate: 8959 case OMPC_reduction: 8960 case OMPC_task_reduction: 8961 case OMPC_in_reduction: 8962 case OMPC_linear: 8963 case OMPC_default: 8964 case OMPC_proc_bind: 8965 case OMPC_final: 8966 case OMPC_safelen: 8967 case OMPC_simdlen: 8968 case OMPC_collapse: 8969 case OMPC_private: 8970 case OMPC_shared: 8971 case OMPC_aligned: 8972 case OMPC_copyin: 8973 case OMPC_copyprivate: 8974 case OMPC_ordered: 8975 case OMPC_nowait: 8976 case OMPC_untied: 8977 case OMPC_mergeable: 8978 case OMPC_threadprivate: 8979 case OMPC_allocate: 8980 case OMPC_flush: 8981 case OMPC_read: 8982 case OMPC_write: 8983 case OMPC_update: 8984 case OMPC_capture: 8985 case OMPC_seq_cst: 8986 case OMPC_depend: 8987 case OMPC_threads: 8988 case OMPC_simd: 8989 case OMPC_map: 8990 case OMPC_priority: 8991 case OMPC_grainsize: 8992 case OMPC_nogroup: 8993 case OMPC_num_tasks: 8994 case OMPC_hint: 8995 case OMPC_defaultmap: 8996 case OMPC_unknown: 8997 case OMPC_uniform: 8998 case OMPC_to: 8999 case OMPC_from: 9000 case OMPC_use_device_ptr: 9001 case OMPC_is_device_ptr: 9002 case OMPC_unified_address: 9003 case OMPC_unified_shared_memory: 9004 case OMPC_reverse_offload: 9005 case OMPC_dynamic_allocators: 9006 case OMPC_atomic_default_mem_order: 9007 llvm_unreachable("Unexpected OpenMP clause."); 9008 } 9009 return CaptureRegion; 9010 } 9011 9012 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 9013 Expr *Condition, SourceLocation StartLoc, 9014 SourceLocation LParenLoc, 9015 SourceLocation NameModifierLoc, 9016 SourceLocation ColonLoc, 9017 SourceLocation EndLoc) { 9018 Expr *ValExpr = Condition; 9019 Stmt *HelperValStmt = nullptr; 9020 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 9021 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 9022 !Condition->isInstantiationDependent() && 9023 !Condition->containsUnexpandedParameterPack()) { 9024 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 9025 if (Val.isInvalid()) 9026 return nullptr; 9027 9028 ValExpr = Val.get(); 9029 9030 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 9031 CaptureRegion = 9032 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 9033 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 9034 ValExpr = MakeFullExpr(ValExpr).get(); 9035 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9036 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 9037 HelperValStmt = buildPreInits(Context, Captures); 9038 } 9039 } 9040 9041 return new (Context) 9042 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 9043 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 9044 } 9045 9046 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 9047 SourceLocation StartLoc, 9048 SourceLocation LParenLoc, 9049 SourceLocation EndLoc) { 9050 Expr *ValExpr = Condition; 9051 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 9052 !Condition->isInstantiationDependent() && 9053 !Condition->containsUnexpandedParameterPack()) { 9054 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 9055 if (Val.isInvalid()) 9056 return nullptr; 9057 9058 ValExpr = MakeFullExpr(Val.get()).get(); 9059 } 9060 9061 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 9062 } 9063 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 9064 Expr *Op) { 9065 if (!Op) 9066 return ExprError(); 9067 9068 class IntConvertDiagnoser : public ICEConvertDiagnoser { 9069 public: 9070 IntConvertDiagnoser() 9071 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 9072 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 9073 QualType T) override { 9074 return S.Diag(Loc, diag::err_omp_not_integral) << T; 9075 } 9076 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 9077 QualType T) override { 9078 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 9079 } 9080 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 9081 QualType T, 9082 QualType ConvTy) override { 9083 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 9084 } 9085 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 9086 QualType ConvTy) override { 9087 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 9088 << ConvTy->isEnumeralType() << ConvTy; 9089 } 9090 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 9091 QualType T) override { 9092 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 9093 } 9094 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 9095 QualType ConvTy) override { 9096 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 9097 << ConvTy->isEnumeralType() << ConvTy; 9098 } 9099 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 9100 QualType) override { 9101 llvm_unreachable("conversion functions are permitted"); 9102 } 9103 } ConvertDiagnoser; 9104 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 9105 } 9106 9107 static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 9108 OpenMPClauseKind CKind, 9109 bool StrictlyPositive) { 9110 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 9111 !ValExpr->isInstantiationDependent()) { 9112 SourceLocation Loc = ValExpr->getExprLoc(); 9113 ExprResult Value = 9114 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 9115 if (Value.isInvalid()) 9116 return false; 9117 9118 ValExpr = Value.get(); 9119 // The expression must evaluate to a non-negative integer value. 9120 llvm::APSInt Result; 9121 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 9122 Result.isSigned() && 9123 !((!StrictlyPositive && Result.isNonNegative()) || 9124 (StrictlyPositive && Result.isStrictlyPositive()))) { 9125 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 9126 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 9127 << ValExpr->getSourceRange(); 9128 return false; 9129 } 9130 } 9131 return true; 9132 } 9133 9134 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 9135 SourceLocation StartLoc, 9136 SourceLocation LParenLoc, 9137 SourceLocation EndLoc) { 9138 Expr *ValExpr = NumThreads; 9139 Stmt *HelperValStmt = nullptr; 9140 9141 // OpenMP [2.5, Restrictions] 9142 // The num_threads expression must evaluate to a positive integer value. 9143 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 9144 /*StrictlyPositive=*/true)) 9145 return nullptr; 9146 9147 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 9148 OpenMPDirectiveKind CaptureRegion = 9149 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 9150 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 9151 ValExpr = MakeFullExpr(ValExpr).get(); 9152 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9153 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 9154 HelperValStmt = buildPreInits(Context, Captures); 9155 } 9156 9157 return new (Context) OMPNumThreadsClause( 9158 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 9159 } 9160 9161 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 9162 OpenMPClauseKind CKind, 9163 bool StrictlyPositive) { 9164 if (!E) 9165 return ExprError(); 9166 if (E->isValueDependent() || E->isTypeDependent() || 9167 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 9168 return E; 9169 llvm::APSInt Result; 9170 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 9171 if (ICE.isInvalid()) 9172 return ExprError(); 9173 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 9174 (!StrictlyPositive && !Result.isNonNegative())) { 9175 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 9176 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 9177 << E->getSourceRange(); 9178 return ExprError(); 9179 } 9180 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 9181 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 9182 << E->getSourceRange(); 9183 return ExprError(); 9184 } 9185 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 9186 DSAStack->setAssociatedLoops(Result.getExtValue()); 9187 else if (CKind == OMPC_ordered) 9188 DSAStack->setAssociatedLoops(Result.getExtValue()); 9189 return ICE; 9190 } 9191 9192 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 9193 SourceLocation LParenLoc, 9194 SourceLocation EndLoc) { 9195 // OpenMP [2.8.1, simd construct, Description] 9196 // The parameter of the safelen clause must be a constant 9197 // positive integer expression. 9198 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 9199 if (Safelen.isInvalid()) 9200 return nullptr; 9201 return new (Context) 9202 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 9203 } 9204 9205 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 9206 SourceLocation LParenLoc, 9207 SourceLocation EndLoc) { 9208 // OpenMP [2.8.1, simd construct, Description] 9209 // The parameter of the simdlen clause must be a constant 9210 // positive integer expression. 9211 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 9212 if (Simdlen.isInvalid()) 9213 return nullptr; 9214 return new (Context) 9215 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 9216 } 9217 9218 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 9219 SourceLocation StartLoc, 9220 SourceLocation LParenLoc, 9221 SourceLocation EndLoc) { 9222 // OpenMP [2.7.1, loop construct, Description] 9223 // OpenMP [2.8.1, simd construct, Description] 9224 // OpenMP [2.9.6, distribute construct, Description] 9225 // The parameter of the collapse clause must be a constant 9226 // positive integer expression. 9227 ExprResult NumForLoopsResult = 9228 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 9229 if (NumForLoopsResult.isInvalid()) 9230 return nullptr; 9231 return new (Context) 9232 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 9233 } 9234 9235 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 9236 SourceLocation EndLoc, 9237 SourceLocation LParenLoc, 9238 Expr *NumForLoops) { 9239 // OpenMP [2.7.1, loop construct, Description] 9240 // OpenMP [2.8.1, simd construct, Description] 9241 // OpenMP [2.9.6, distribute construct, Description] 9242 // The parameter of the ordered clause must be a constant 9243 // positive integer expression if any. 9244 if (NumForLoops && LParenLoc.isValid()) { 9245 ExprResult NumForLoopsResult = 9246 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 9247 if (NumForLoopsResult.isInvalid()) 9248 return nullptr; 9249 NumForLoops = NumForLoopsResult.get(); 9250 } else { 9251 NumForLoops = nullptr; 9252 } 9253 auto *Clause = OMPOrderedClause::Create( 9254 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 9255 StartLoc, LParenLoc, EndLoc); 9256 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 9257 return Clause; 9258 } 9259 9260 OMPClause *Sema::ActOnOpenMPSimpleClause( 9261 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 9262 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 9263 OMPClause *Res = nullptr; 9264 switch (Kind) { 9265 case OMPC_default: 9266 Res = 9267 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 9268 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 9269 break; 9270 case OMPC_proc_bind: 9271 Res = ActOnOpenMPProcBindClause( 9272 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 9273 LParenLoc, EndLoc); 9274 break; 9275 case OMPC_atomic_default_mem_order: 9276 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 9277 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 9278 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 9279 break; 9280 case OMPC_if: 9281 case OMPC_final: 9282 case OMPC_num_threads: 9283 case OMPC_safelen: 9284 case OMPC_simdlen: 9285 case OMPC_collapse: 9286 case OMPC_schedule: 9287 case OMPC_private: 9288 case OMPC_firstprivate: 9289 case OMPC_lastprivate: 9290 case OMPC_shared: 9291 case OMPC_reduction: 9292 case OMPC_task_reduction: 9293 case OMPC_in_reduction: 9294 case OMPC_linear: 9295 case OMPC_aligned: 9296 case OMPC_copyin: 9297 case OMPC_copyprivate: 9298 case OMPC_ordered: 9299 case OMPC_nowait: 9300 case OMPC_untied: 9301 case OMPC_mergeable: 9302 case OMPC_threadprivate: 9303 case OMPC_allocate: 9304 case OMPC_flush: 9305 case OMPC_read: 9306 case OMPC_write: 9307 case OMPC_update: 9308 case OMPC_capture: 9309 case OMPC_seq_cst: 9310 case OMPC_depend: 9311 case OMPC_device: 9312 case OMPC_threads: 9313 case OMPC_simd: 9314 case OMPC_map: 9315 case OMPC_num_teams: 9316 case OMPC_thread_limit: 9317 case OMPC_priority: 9318 case OMPC_grainsize: 9319 case OMPC_nogroup: 9320 case OMPC_num_tasks: 9321 case OMPC_hint: 9322 case OMPC_dist_schedule: 9323 case OMPC_defaultmap: 9324 case OMPC_unknown: 9325 case OMPC_uniform: 9326 case OMPC_to: 9327 case OMPC_from: 9328 case OMPC_use_device_ptr: 9329 case OMPC_is_device_ptr: 9330 case OMPC_unified_address: 9331 case OMPC_unified_shared_memory: 9332 case OMPC_reverse_offload: 9333 case OMPC_dynamic_allocators: 9334 llvm_unreachable("Clause is not allowed."); 9335 } 9336 return Res; 9337 } 9338 9339 static std::string 9340 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 9341 ArrayRef<unsigned> Exclude = llvm::None) { 9342 SmallString<256> Buffer; 9343 llvm::raw_svector_ostream Out(Buffer); 9344 unsigned Bound = Last >= 2 ? Last - 2 : 0; 9345 unsigned Skipped = Exclude.size(); 9346 auto S = Exclude.begin(), E = Exclude.end(); 9347 for (unsigned I = First; I < Last; ++I) { 9348 if (std::find(S, E, I) != E) { 9349 --Skipped; 9350 continue; 9351 } 9352 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 9353 if (I == Bound - Skipped) 9354 Out << " or "; 9355 else if (I != Bound + 1 - Skipped) 9356 Out << ", "; 9357 } 9358 return Out.str(); 9359 } 9360 9361 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 9362 SourceLocation KindKwLoc, 9363 SourceLocation StartLoc, 9364 SourceLocation LParenLoc, 9365 SourceLocation EndLoc) { 9366 if (Kind == OMPC_DEFAULT_unknown) { 9367 static_assert(OMPC_DEFAULT_unknown > 0, 9368 "OMPC_DEFAULT_unknown not greater than 0"); 9369 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 9370 << getListOfPossibleValues(OMPC_default, /*First=*/0, 9371 /*Last=*/OMPC_DEFAULT_unknown) 9372 << getOpenMPClauseName(OMPC_default); 9373 return nullptr; 9374 } 9375 switch (Kind) { 9376 case OMPC_DEFAULT_none: 9377 DSAStack->setDefaultDSANone(KindKwLoc); 9378 break; 9379 case OMPC_DEFAULT_shared: 9380 DSAStack->setDefaultDSAShared(KindKwLoc); 9381 break; 9382 case OMPC_DEFAULT_unknown: 9383 llvm_unreachable("Clause kind is not allowed."); 9384 break; 9385 } 9386 return new (Context) 9387 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 9388 } 9389 9390 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 9391 SourceLocation KindKwLoc, 9392 SourceLocation StartLoc, 9393 SourceLocation LParenLoc, 9394 SourceLocation EndLoc) { 9395 if (Kind == OMPC_PROC_BIND_unknown) { 9396 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 9397 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 9398 /*Last=*/OMPC_PROC_BIND_unknown) 9399 << getOpenMPClauseName(OMPC_proc_bind); 9400 return nullptr; 9401 } 9402 return new (Context) 9403 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 9404 } 9405 9406 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 9407 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 9408 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 9409 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 9410 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 9411 << getListOfPossibleValues( 9412 OMPC_atomic_default_mem_order, /*First=*/0, 9413 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 9414 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 9415 return nullptr; 9416 } 9417 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 9418 LParenLoc, EndLoc); 9419 } 9420 9421 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 9422 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 9423 SourceLocation StartLoc, SourceLocation LParenLoc, 9424 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 9425 SourceLocation EndLoc) { 9426 OMPClause *Res = nullptr; 9427 switch (Kind) { 9428 case OMPC_schedule: 9429 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 9430 assert(Argument.size() == NumberOfElements && 9431 ArgumentLoc.size() == NumberOfElements); 9432 Res = ActOnOpenMPScheduleClause( 9433 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 9434 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 9435 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 9436 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 9437 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 9438 break; 9439 case OMPC_if: 9440 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 9441 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 9442 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 9443 DelimLoc, EndLoc); 9444 break; 9445 case OMPC_dist_schedule: 9446 Res = ActOnOpenMPDistScheduleClause( 9447 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 9448 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 9449 break; 9450 case OMPC_defaultmap: 9451 enum { Modifier, DefaultmapKind }; 9452 Res = ActOnOpenMPDefaultmapClause( 9453 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 9454 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 9455 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 9456 EndLoc); 9457 break; 9458 case OMPC_final: 9459 case OMPC_num_threads: 9460 case OMPC_safelen: 9461 case OMPC_simdlen: 9462 case OMPC_collapse: 9463 case OMPC_default: 9464 case OMPC_proc_bind: 9465 case OMPC_private: 9466 case OMPC_firstprivate: 9467 case OMPC_lastprivate: 9468 case OMPC_shared: 9469 case OMPC_reduction: 9470 case OMPC_task_reduction: 9471 case OMPC_in_reduction: 9472 case OMPC_linear: 9473 case OMPC_aligned: 9474 case OMPC_copyin: 9475 case OMPC_copyprivate: 9476 case OMPC_ordered: 9477 case OMPC_nowait: 9478 case OMPC_untied: 9479 case OMPC_mergeable: 9480 case OMPC_threadprivate: 9481 case OMPC_allocate: 9482 case OMPC_flush: 9483 case OMPC_read: 9484 case OMPC_write: 9485 case OMPC_update: 9486 case OMPC_capture: 9487 case OMPC_seq_cst: 9488 case OMPC_depend: 9489 case OMPC_device: 9490 case OMPC_threads: 9491 case OMPC_simd: 9492 case OMPC_map: 9493 case OMPC_num_teams: 9494 case OMPC_thread_limit: 9495 case OMPC_priority: 9496 case OMPC_grainsize: 9497 case OMPC_nogroup: 9498 case OMPC_num_tasks: 9499 case OMPC_hint: 9500 case OMPC_unknown: 9501 case OMPC_uniform: 9502 case OMPC_to: 9503 case OMPC_from: 9504 case OMPC_use_device_ptr: 9505 case OMPC_is_device_ptr: 9506 case OMPC_unified_address: 9507 case OMPC_unified_shared_memory: 9508 case OMPC_reverse_offload: 9509 case OMPC_dynamic_allocators: 9510 case OMPC_atomic_default_mem_order: 9511 llvm_unreachable("Clause is not allowed."); 9512 } 9513 return Res; 9514 } 9515 9516 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 9517 OpenMPScheduleClauseModifier M2, 9518 SourceLocation M1Loc, SourceLocation M2Loc) { 9519 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 9520 SmallVector<unsigned, 2> Excluded; 9521 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 9522 Excluded.push_back(M2); 9523 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 9524 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 9525 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 9526 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 9527 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 9528 << getListOfPossibleValues(OMPC_schedule, 9529 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 9530 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 9531 Excluded) 9532 << getOpenMPClauseName(OMPC_schedule); 9533 return true; 9534 } 9535 return false; 9536 } 9537 9538 OMPClause *Sema::ActOnOpenMPScheduleClause( 9539 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 9540 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 9541 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 9542 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 9543 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 9544 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 9545 return nullptr; 9546 // OpenMP, 2.7.1, Loop Construct, Restrictions 9547 // Either the monotonic modifier or the nonmonotonic modifier can be specified 9548 // but not both. 9549 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 9550 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 9551 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 9552 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 9553 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 9554 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 9555 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 9556 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 9557 return nullptr; 9558 } 9559 if (Kind == OMPC_SCHEDULE_unknown) { 9560 std::string Values; 9561 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 9562 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 9563 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 9564 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 9565 Exclude); 9566 } else { 9567 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 9568 /*Last=*/OMPC_SCHEDULE_unknown); 9569 } 9570 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 9571 << Values << getOpenMPClauseName(OMPC_schedule); 9572 return nullptr; 9573 } 9574 // OpenMP, 2.7.1, Loop Construct, Restrictions 9575 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 9576 // schedule(guided). 9577 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 9578 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 9579 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 9580 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 9581 diag::err_omp_schedule_nonmonotonic_static); 9582 return nullptr; 9583 } 9584 Expr *ValExpr = ChunkSize; 9585 Stmt *HelperValStmt = nullptr; 9586 if (ChunkSize) { 9587 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 9588 !ChunkSize->isInstantiationDependent() && 9589 !ChunkSize->containsUnexpandedParameterPack()) { 9590 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 9591 ExprResult Val = 9592 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 9593 if (Val.isInvalid()) 9594 return nullptr; 9595 9596 ValExpr = Val.get(); 9597 9598 // OpenMP [2.7.1, Restrictions] 9599 // chunk_size must be a loop invariant integer expression with a positive 9600 // value. 9601 llvm::APSInt Result; 9602 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 9603 if (Result.isSigned() && !Result.isStrictlyPositive()) { 9604 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 9605 << "schedule" << 1 << ChunkSize->getSourceRange(); 9606 return nullptr; 9607 } 9608 } else if (getOpenMPCaptureRegionForClause( 9609 DSAStack->getCurrentDirective(), OMPC_schedule) != 9610 OMPD_unknown && 9611 !CurContext->isDependentContext()) { 9612 ValExpr = MakeFullExpr(ValExpr).get(); 9613 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9614 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 9615 HelperValStmt = buildPreInits(Context, Captures); 9616 } 9617 } 9618 } 9619 9620 return new (Context) 9621 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 9622 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 9623 } 9624 9625 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 9626 SourceLocation StartLoc, 9627 SourceLocation EndLoc) { 9628 OMPClause *Res = nullptr; 9629 switch (Kind) { 9630 case OMPC_ordered: 9631 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 9632 break; 9633 case OMPC_nowait: 9634 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 9635 break; 9636 case OMPC_untied: 9637 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 9638 break; 9639 case OMPC_mergeable: 9640 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 9641 break; 9642 case OMPC_read: 9643 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 9644 break; 9645 case OMPC_write: 9646 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 9647 break; 9648 case OMPC_update: 9649 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 9650 break; 9651 case OMPC_capture: 9652 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 9653 break; 9654 case OMPC_seq_cst: 9655 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 9656 break; 9657 case OMPC_threads: 9658 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 9659 break; 9660 case OMPC_simd: 9661 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 9662 break; 9663 case OMPC_nogroup: 9664 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 9665 break; 9666 case OMPC_unified_address: 9667 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 9668 break; 9669 case OMPC_unified_shared_memory: 9670 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 9671 break; 9672 case OMPC_reverse_offload: 9673 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 9674 break; 9675 case OMPC_dynamic_allocators: 9676 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 9677 break; 9678 case OMPC_if: 9679 case OMPC_final: 9680 case OMPC_num_threads: 9681 case OMPC_safelen: 9682 case OMPC_simdlen: 9683 case OMPC_collapse: 9684 case OMPC_schedule: 9685 case OMPC_private: 9686 case OMPC_firstprivate: 9687 case OMPC_lastprivate: 9688 case OMPC_shared: 9689 case OMPC_reduction: 9690 case OMPC_task_reduction: 9691 case OMPC_in_reduction: 9692 case OMPC_linear: 9693 case OMPC_aligned: 9694 case OMPC_copyin: 9695 case OMPC_copyprivate: 9696 case OMPC_default: 9697 case OMPC_proc_bind: 9698 case OMPC_threadprivate: 9699 case OMPC_allocate: 9700 case OMPC_flush: 9701 case OMPC_depend: 9702 case OMPC_device: 9703 case OMPC_map: 9704 case OMPC_num_teams: 9705 case OMPC_thread_limit: 9706 case OMPC_priority: 9707 case OMPC_grainsize: 9708 case OMPC_num_tasks: 9709 case OMPC_hint: 9710 case OMPC_dist_schedule: 9711 case OMPC_defaultmap: 9712 case OMPC_unknown: 9713 case OMPC_uniform: 9714 case OMPC_to: 9715 case OMPC_from: 9716 case OMPC_use_device_ptr: 9717 case OMPC_is_device_ptr: 9718 case OMPC_atomic_default_mem_order: 9719 llvm_unreachable("Clause is not allowed."); 9720 } 9721 return Res; 9722 } 9723 9724 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 9725 SourceLocation EndLoc) { 9726 DSAStack->setNowaitRegion(); 9727 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 9728 } 9729 9730 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 9731 SourceLocation EndLoc) { 9732 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 9733 } 9734 9735 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 9736 SourceLocation EndLoc) { 9737 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 9738 } 9739 9740 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 9741 SourceLocation EndLoc) { 9742 return new (Context) OMPReadClause(StartLoc, EndLoc); 9743 } 9744 9745 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 9746 SourceLocation EndLoc) { 9747 return new (Context) OMPWriteClause(StartLoc, EndLoc); 9748 } 9749 9750 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 9751 SourceLocation EndLoc) { 9752 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 9753 } 9754 9755 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 9756 SourceLocation EndLoc) { 9757 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 9758 } 9759 9760 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 9761 SourceLocation EndLoc) { 9762 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 9763 } 9764 9765 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 9766 SourceLocation EndLoc) { 9767 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 9768 } 9769 9770 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 9771 SourceLocation EndLoc) { 9772 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 9773 } 9774 9775 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 9776 SourceLocation EndLoc) { 9777 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 9778 } 9779 9780 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 9781 SourceLocation EndLoc) { 9782 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 9783 } 9784 9785 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 9786 SourceLocation EndLoc) { 9787 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 9788 } 9789 9790 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 9791 SourceLocation EndLoc) { 9792 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 9793 } 9794 9795 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 9796 SourceLocation EndLoc) { 9797 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 9798 } 9799 9800 OMPClause *Sema::ActOnOpenMPVarListClause( 9801 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 9802 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 9803 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 9804 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind, 9805 OpenMPLinearClauseKind LinKind, 9806 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 9807 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType, 9808 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) { 9809 SourceLocation StartLoc = Locs.StartLoc; 9810 SourceLocation LParenLoc = Locs.LParenLoc; 9811 SourceLocation EndLoc = Locs.EndLoc; 9812 OMPClause *Res = nullptr; 9813 switch (Kind) { 9814 case OMPC_private: 9815 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9816 break; 9817 case OMPC_firstprivate: 9818 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9819 break; 9820 case OMPC_lastprivate: 9821 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9822 break; 9823 case OMPC_shared: 9824 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 9825 break; 9826 case OMPC_reduction: 9827 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9828 EndLoc, ReductionOrMapperIdScopeSpec, 9829 ReductionOrMapperId); 9830 break; 9831 case OMPC_task_reduction: 9832 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9833 EndLoc, ReductionOrMapperIdScopeSpec, 9834 ReductionOrMapperId); 9835 break; 9836 case OMPC_in_reduction: 9837 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9838 EndLoc, ReductionOrMapperIdScopeSpec, 9839 ReductionOrMapperId); 9840 break; 9841 case OMPC_linear: 9842 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 9843 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 9844 break; 9845 case OMPC_aligned: 9846 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 9847 ColonLoc, EndLoc); 9848 break; 9849 case OMPC_copyin: 9850 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 9851 break; 9852 case OMPC_copyprivate: 9853 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9854 break; 9855 case OMPC_flush: 9856 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 9857 break; 9858 case OMPC_depend: 9859 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 9860 StartLoc, LParenLoc, EndLoc); 9861 break; 9862 case OMPC_map: 9863 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc, 9864 ReductionOrMapperIdScopeSpec, 9865 ReductionOrMapperId, MapType, IsMapTypeImplicit, 9866 DepLinMapLoc, ColonLoc, VarList, Locs); 9867 break; 9868 case OMPC_to: 9869 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec, 9870 ReductionOrMapperId, Locs); 9871 break; 9872 case OMPC_from: 9873 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec, 9874 ReductionOrMapperId, Locs); 9875 break; 9876 case OMPC_use_device_ptr: 9877 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs); 9878 break; 9879 case OMPC_is_device_ptr: 9880 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs); 9881 break; 9882 case OMPC_if: 9883 case OMPC_final: 9884 case OMPC_num_threads: 9885 case OMPC_safelen: 9886 case OMPC_simdlen: 9887 case OMPC_collapse: 9888 case OMPC_default: 9889 case OMPC_proc_bind: 9890 case OMPC_schedule: 9891 case OMPC_ordered: 9892 case OMPC_nowait: 9893 case OMPC_untied: 9894 case OMPC_mergeable: 9895 case OMPC_threadprivate: 9896 case OMPC_allocate: 9897 case OMPC_read: 9898 case OMPC_write: 9899 case OMPC_update: 9900 case OMPC_capture: 9901 case OMPC_seq_cst: 9902 case OMPC_device: 9903 case OMPC_threads: 9904 case OMPC_simd: 9905 case OMPC_num_teams: 9906 case OMPC_thread_limit: 9907 case OMPC_priority: 9908 case OMPC_grainsize: 9909 case OMPC_nogroup: 9910 case OMPC_num_tasks: 9911 case OMPC_hint: 9912 case OMPC_dist_schedule: 9913 case OMPC_defaultmap: 9914 case OMPC_unknown: 9915 case OMPC_uniform: 9916 case OMPC_unified_address: 9917 case OMPC_unified_shared_memory: 9918 case OMPC_reverse_offload: 9919 case OMPC_dynamic_allocators: 9920 case OMPC_atomic_default_mem_order: 9921 llvm_unreachable("Clause is not allowed."); 9922 } 9923 return Res; 9924 } 9925 9926 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 9927 ExprObjectKind OK, SourceLocation Loc) { 9928 ExprResult Res = BuildDeclRefExpr( 9929 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 9930 if (!Res.isUsable()) 9931 return ExprError(); 9932 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 9933 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 9934 if (!Res.isUsable()) 9935 return ExprError(); 9936 } 9937 if (VK != VK_LValue && Res.get()->isGLValue()) { 9938 Res = DefaultLvalueConversion(Res.get()); 9939 if (!Res.isUsable()) 9940 return ExprError(); 9941 } 9942 return Res; 9943 } 9944 9945 static std::pair<ValueDecl *, bool> 9946 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 9947 SourceRange &ERange, bool AllowArraySection = false) { 9948 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 9949 RefExpr->containsUnexpandedParameterPack()) 9950 return std::make_pair(nullptr, true); 9951 9952 // OpenMP [3.1, C/C++] 9953 // A list item is a variable name. 9954 // OpenMP [2.9.3.3, Restrictions, p.1] 9955 // A variable that is part of another variable (as an array or 9956 // structure element) cannot appear in a private clause. 9957 RefExpr = RefExpr->IgnoreParens(); 9958 enum { 9959 NoArrayExpr = -1, 9960 ArraySubscript = 0, 9961 OMPArraySection = 1 9962 } IsArrayExpr = NoArrayExpr; 9963 if (AllowArraySection) { 9964 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 9965 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 9966 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 9967 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9968 RefExpr = Base; 9969 IsArrayExpr = ArraySubscript; 9970 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 9971 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 9972 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 9973 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 9974 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 9975 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9976 RefExpr = Base; 9977 IsArrayExpr = OMPArraySection; 9978 } 9979 } 9980 ELoc = RefExpr->getExprLoc(); 9981 ERange = RefExpr->getSourceRange(); 9982 RefExpr = RefExpr->IgnoreParenImpCasts(); 9983 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 9984 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 9985 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 9986 (S.getCurrentThisType().isNull() || !ME || 9987 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 9988 !isa<FieldDecl>(ME->getMemberDecl()))) { 9989 if (IsArrayExpr != NoArrayExpr) { 9990 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 9991 << ERange; 9992 } else { 9993 S.Diag(ELoc, 9994 AllowArraySection 9995 ? diag::err_omp_expected_var_name_member_expr_or_array_item 9996 : diag::err_omp_expected_var_name_member_expr) 9997 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 9998 } 9999 return std::make_pair(nullptr, false); 10000 } 10001 return std::make_pair( 10002 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 10003 } 10004 10005 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 10006 SourceLocation StartLoc, 10007 SourceLocation LParenLoc, 10008 SourceLocation EndLoc) { 10009 SmallVector<Expr *, 8> Vars; 10010 SmallVector<Expr *, 8> PrivateCopies; 10011 for (Expr *RefExpr : VarList) { 10012 assert(RefExpr && "NULL expr in OpenMP private clause."); 10013 SourceLocation ELoc; 10014 SourceRange ERange; 10015 Expr *SimpleRefExpr = RefExpr; 10016 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10017 if (Res.second) { 10018 // It will be analyzed later. 10019 Vars.push_back(RefExpr); 10020 PrivateCopies.push_back(nullptr); 10021 } 10022 ValueDecl *D = Res.first; 10023 if (!D) 10024 continue; 10025 10026 QualType Type = D->getType(); 10027 auto *VD = dyn_cast<VarDecl>(D); 10028 10029 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 10030 // A variable that appears in a private clause must not have an incomplete 10031 // type or a reference type. 10032 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 10033 continue; 10034 Type = Type.getNonReferenceType(); 10035 10036 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 10037 // A variable that is privatized must not have a const-qualified type 10038 // unless it is of class type with a mutable member. This restriction does 10039 // not apply to the firstprivate clause. 10040 // 10041 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 10042 // A variable that appears in a private clause must not have a 10043 // const-qualified type unless it is of class type with a mutable member. 10044 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 10045 continue; 10046 10047 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 10048 // in a Construct] 10049 // Variables with the predetermined data-sharing attributes may not be 10050 // listed in data-sharing attributes clauses, except for the cases 10051 // listed below. For these exceptions only, listing a predetermined 10052 // variable in a data-sharing attribute clause is allowed and overrides 10053 // the variable's predetermined data-sharing attributes. 10054 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 10055 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 10056 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 10057 << getOpenMPClauseName(OMPC_private); 10058 reportOriginalDsa(*this, DSAStack, D, DVar); 10059 continue; 10060 } 10061 10062 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 10063 // Variably modified types are not supported for tasks. 10064 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 10065 isOpenMPTaskingDirective(CurrDir)) { 10066 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 10067 << getOpenMPClauseName(OMPC_private) << Type 10068 << getOpenMPDirectiveName(CurrDir); 10069 bool IsDecl = 10070 !VD || 10071 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10072 Diag(D->getLocation(), 10073 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10074 << D; 10075 continue; 10076 } 10077 10078 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10079 // A list item cannot appear in both a map clause and a data-sharing 10080 // attribute clause on the same construct 10081 if (isOpenMPTargetExecutionDirective(CurrDir)) { 10082 OpenMPClauseKind ConflictKind; 10083 if (DSAStack->checkMappableExprComponentListsForDecl( 10084 VD, /*CurrentRegionOnly=*/true, 10085 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 10086 OpenMPClauseKind WhereFoundClauseKind) -> bool { 10087 ConflictKind = WhereFoundClauseKind; 10088 return true; 10089 })) { 10090 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10091 << getOpenMPClauseName(OMPC_private) 10092 << getOpenMPClauseName(ConflictKind) 10093 << getOpenMPDirectiveName(CurrDir); 10094 reportOriginalDsa(*this, DSAStack, D, DVar); 10095 continue; 10096 } 10097 } 10098 10099 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 10100 // A variable of class type (or array thereof) that appears in a private 10101 // clause requires an accessible, unambiguous default constructor for the 10102 // class type. 10103 // Generate helper private variable and initialize it with the default 10104 // value. The address of the original variable is replaced by the address of 10105 // the new private variable in CodeGen. This new variable is not added to 10106 // IdResolver, so the code in the OpenMP region uses original variable for 10107 // proper diagnostics. 10108 Type = Type.getUnqualifiedType(); 10109 VarDecl *VDPrivate = 10110 buildVarDecl(*this, ELoc, Type, D->getName(), 10111 D->hasAttrs() ? &D->getAttrs() : nullptr, 10112 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 10113 ActOnUninitializedDecl(VDPrivate); 10114 if (VDPrivate->isInvalidDecl()) 10115 continue; 10116 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 10117 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 10118 10119 DeclRefExpr *Ref = nullptr; 10120 if (!VD && !CurContext->isDependentContext()) 10121 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 10122 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 10123 Vars.push_back((VD || CurContext->isDependentContext()) 10124 ? RefExpr->IgnoreParens() 10125 : Ref); 10126 PrivateCopies.push_back(VDPrivateRefExpr); 10127 } 10128 10129 if (Vars.empty()) 10130 return nullptr; 10131 10132 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 10133 PrivateCopies); 10134 } 10135 10136 namespace { 10137 class DiagsUninitializedSeveretyRAII { 10138 private: 10139 DiagnosticsEngine &Diags; 10140 SourceLocation SavedLoc; 10141 bool IsIgnored = false; 10142 10143 public: 10144 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 10145 bool IsIgnored) 10146 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 10147 if (!IsIgnored) { 10148 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 10149 /*Map*/ diag::Severity::Ignored, Loc); 10150 } 10151 } 10152 ~DiagsUninitializedSeveretyRAII() { 10153 if (!IsIgnored) 10154 Diags.popMappings(SavedLoc); 10155 } 10156 }; 10157 } 10158 10159 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 10160 SourceLocation StartLoc, 10161 SourceLocation LParenLoc, 10162 SourceLocation EndLoc) { 10163 SmallVector<Expr *, 8> Vars; 10164 SmallVector<Expr *, 8> PrivateCopies; 10165 SmallVector<Expr *, 8> Inits; 10166 SmallVector<Decl *, 4> ExprCaptures; 10167 bool IsImplicitClause = 10168 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 10169 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 10170 10171 for (Expr *RefExpr : VarList) { 10172 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 10173 SourceLocation ELoc; 10174 SourceRange ERange; 10175 Expr *SimpleRefExpr = RefExpr; 10176 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10177 if (Res.second) { 10178 // It will be analyzed later. 10179 Vars.push_back(RefExpr); 10180 PrivateCopies.push_back(nullptr); 10181 Inits.push_back(nullptr); 10182 } 10183 ValueDecl *D = Res.first; 10184 if (!D) 10185 continue; 10186 10187 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 10188 QualType Type = D->getType(); 10189 auto *VD = dyn_cast<VarDecl>(D); 10190 10191 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 10192 // A variable that appears in a private clause must not have an incomplete 10193 // type or a reference type. 10194 if (RequireCompleteType(ELoc, Type, 10195 diag::err_omp_firstprivate_incomplete_type)) 10196 continue; 10197 Type = Type.getNonReferenceType(); 10198 10199 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 10200 // A variable of class type (or array thereof) that appears in a private 10201 // clause requires an accessible, unambiguous copy constructor for the 10202 // class type. 10203 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 10204 10205 // If an implicit firstprivate variable found it was checked already. 10206 DSAStackTy::DSAVarData TopDVar; 10207 if (!IsImplicitClause) { 10208 DSAStackTy::DSAVarData DVar = 10209 DSAStack->getTopDSA(D, /*FromParent=*/false); 10210 TopDVar = DVar; 10211 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 10212 bool IsConstant = ElemType.isConstant(Context); 10213 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 10214 // A list item that specifies a given variable may not appear in more 10215 // than one clause on the same directive, except that a variable may be 10216 // specified in both firstprivate and lastprivate clauses. 10217 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 10218 // A list item may appear in a firstprivate or lastprivate clause but not 10219 // both. 10220 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 10221 (isOpenMPDistributeDirective(CurrDir) || 10222 DVar.CKind != OMPC_lastprivate) && 10223 DVar.RefExpr) { 10224 Diag(ELoc, diag::err_omp_wrong_dsa) 10225 << getOpenMPClauseName(DVar.CKind) 10226 << getOpenMPClauseName(OMPC_firstprivate); 10227 reportOriginalDsa(*this, DSAStack, D, DVar); 10228 continue; 10229 } 10230 10231 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 10232 // in a Construct] 10233 // Variables with the predetermined data-sharing attributes may not be 10234 // listed in data-sharing attributes clauses, except for the cases 10235 // listed below. For these exceptions only, listing a predetermined 10236 // variable in a data-sharing attribute clause is allowed and overrides 10237 // the variable's predetermined data-sharing attributes. 10238 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 10239 // in a Construct, C/C++, p.2] 10240 // Variables with const-qualified type having no mutable member may be 10241 // listed in a firstprivate clause, even if they are static data members. 10242 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 10243 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 10244 Diag(ELoc, diag::err_omp_wrong_dsa) 10245 << getOpenMPClauseName(DVar.CKind) 10246 << getOpenMPClauseName(OMPC_firstprivate); 10247 reportOriginalDsa(*this, DSAStack, D, DVar); 10248 continue; 10249 } 10250 10251 // OpenMP [2.9.3.4, Restrictions, p.2] 10252 // A list item that is private within a parallel region must not appear 10253 // in a firstprivate clause on a worksharing construct if any of the 10254 // worksharing regions arising from the worksharing construct ever bind 10255 // to any of the parallel regions arising from the parallel construct. 10256 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 10257 // A list item that is private within a teams region must not appear in a 10258 // firstprivate clause on a distribute construct if any of the distribute 10259 // regions arising from the distribute construct ever bind to any of the 10260 // teams regions arising from the teams construct. 10261 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 10262 // A list item that appears in a reduction clause of a teams construct 10263 // must not appear in a firstprivate clause on a distribute construct if 10264 // any of the distribute regions arising from the distribute construct 10265 // ever bind to any of the teams regions arising from the teams construct. 10266 if ((isOpenMPWorksharingDirective(CurrDir) || 10267 isOpenMPDistributeDirective(CurrDir)) && 10268 !isOpenMPParallelDirective(CurrDir) && 10269 !isOpenMPTeamsDirective(CurrDir)) { 10270 DVar = DSAStack->getImplicitDSA(D, true); 10271 if (DVar.CKind != OMPC_shared && 10272 (isOpenMPParallelDirective(DVar.DKind) || 10273 isOpenMPTeamsDirective(DVar.DKind) || 10274 DVar.DKind == OMPD_unknown)) { 10275 Diag(ELoc, diag::err_omp_required_access) 10276 << getOpenMPClauseName(OMPC_firstprivate) 10277 << getOpenMPClauseName(OMPC_shared); 10278 reportOriginalDsa(*this, DSAStack, D, DVar); 10279 continue; 10280 } 10281 } 10282 // OpenMP [2.9.3.4, Restrictions, p.3] 10283 // A list item that appears in a reduction clause of a parallel construct 10284 // must not appear in a firstprivate clause on a worksharing or task 10285 // construct if any of the worksharing or task regions arising from the 10286 // worksharing or task construct ever bind to any of the parallel regions 10287 // arising from the parallel construct. 10288 // OpenMP [2.9.3.4, Restrictions, p.4] 10289 // A list item that appears in a reduction clause in worksharing 10290 // construct must not appear in a firstprivate clause in a task construct 10291 // encountered during execution of any of the worksharing regions arising 10292 // from the worksharing construct. 10293 if (isOpenMPTaskingDirective(CurrDir)) { 10294 DVar = DSAStack->hasInnermostDSA( 10295 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 10296 [](OpenMPDirectiveKind K) { 10297 return isOpenMPParallelDirective(K) || 10298 isOpenMPWorksharingDirective(K) || 10299 isOpenMPTeamsDirective(K); 10300 }, 10301 /*FromParent=*/true); 10302 if (DVar.CKind == OMPC_reduction && 10303 (isOpenMPParallelDirective(DVar.DKind) || 10304 isOpenMPWorksharingDirective(DVar.DKind) || 10305 isOpenMPTeamsDirective(DVar.DKind))) { 10306 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 10307 << getOpenMPDirectiveName(DVar.DKind); 10308 reportOriginalDsa(*this, DSAStack, D, DVar); 10309 continue; 10310 } 10311 } 10312 10313 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10314 // A list item cannot appear in both a map clause and a data-sharing 10315 // attribute clause on the same construct 10316 if (isOpenMPTargetExecutionDirective(CurrDir)) { 10317 OpenMPClauseKind ConflictKind; 10318 if (DSAStack->checkMappableExprComponentListsForDecl( 10319 VD, /*CurrentRegionOnly=*/true, 10320 [&ConflictKind]( 10321 OMPClauseMappableExprCommon::MappableExprComponentListRef, 10322 OpenMPClauseKind WhereFoundClauseKind) { 10323 ConflictKind = WhereFoundClauseKind; 10324 return true; 10325 })) { 10326 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10327 << getOpenMPClauseName(OMPC_firstprivate) 10328 << getOpenMPClauseName(ConflictKind) 10329 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 10330 reportOriginalDsa(*this, DSAStack, D, DVar); 10331 continue; 10332 } 10333 } 10334 } 10335 10336 // Variably modified types are not supported for tasks. 10337 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 10338 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 10339 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 10340 << getOpenMPClauseName(OMPC_firstprivate) << Type 10341 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 10342 bool IsDecl = 10343 !VD || 10344 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10345 Diag(D->getLocation(), 10346 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10347 << D; 10348 continue; 10349 } 10350 10351 Type = Type.getUnqualifiedType(); 10352 VarDecl *VDPrivate = 10353 buildVarDecl(*this, ELoc, Type, D->getName(), 10354 D->hasAttrs() ? &D->getAttrs() : nullptr, 10355 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 10356 // Generate helper private variable and initialize it with the value of the 10357 // original variable. The address of the original variable is replaced by 10358 // the address of the new private variable in the CodeGen. This new variable 10359 // is not added to IdResolver, so the code in the OpenMP region uses 10360 // original variable for proper diagnostics and variable capturing. 10361 Expr *VDInitRefExpr = nullptr; 10362 // For arrays generate initializer for single element and replace it by the 10363 // original array element in CodeGen. 10364 if (Type->isArrayType()) { 10365 VarDecl *VDInit = 10366 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 10367 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 10368 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 10369 ElemType = ElemType.getUnqualifiedType(); 10370 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 10371 ".firstprivate.temp"); 10372 InitializedEntity Entity = 10373 InitializedEntity::InitializeVariable(VDInitTemp); 10374 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 10375 10376 InitializationSequence InitSeq(*this, Entity, Kind, Init); 10377 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 10378 if (Result.isInvalid()) 10379 VDPrivate->setInvalidDecl(); 10380 else 10381 VDPrivate->setInit(Result.getAs<Expr>()); 10382 // Remove temp variable declaration. 10383 Context.Deallocate(VDInitTemp); 10384 } else { 10385 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 10386 ".firstprivate.temp"); 10387 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 10388 RefExpr->getExprLoc()); 10389 AddInitializerToDecl(VDPrivate, 10390 DefaultLvalueConversion(VDInitRefExpr).get(), 10391 /*DirectInit=*/false); 10392 } 10393 if (VDPrivate->isInvalidDecl()) { 10394 if (IsImplicitClause) { 10395 Diag(RefExpr->getExprLoc(), 10396 diag::note_omp_task_predetermined_firstprivate_here); 10397 } 10398 continue; 10399 } 10400 CurContext->addDecl(VDPrivate); 10401 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 10402 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 10403 RefExpr->getExprLoc()); 10404 DeclRefExpr *Ref = nullptr; 10405 if (!VD && !CurContext->isDependentContext()) { 10406 if (TopDVar.CKind == OMPC_lastprivate) { 10407 Ref = TopDVar.PrivateCopy; 10408 } else { 10409 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 10410 if (!isOpenMPCapturedDecl(D)) 10411 ExprCaptures.push_back(Ref->getDecl()); 10412 } 10413 } 10414 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 10415 Vars.push_back((VD || CurContext->isDependentContext()) 10416 ? RefExpr->IgnoreParens() 10417 : Ref); 10418 PrivateCopies.push_back(VDPrivateRefExpr); 10419 Inits.push_back(VDInitRefExpr); 10420 } 10421 10422 if (Vars.empty()) 10423 return nullptr; 10424 10425 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10426 Vars, PrivateCopies, Inits, 10427 buildPreInits(Context, ExprCaptures)); 10428 } 10429 10430 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 10431 SourceLocation StartLoc, 10432 SourceLocation LParenLoc, 10433 SourceLocation EndLoc) { 10434 SmallVector<Expr *, 8> Vars; 10435 SmallVector<Expr *, 8> SrcExprs; 10436 SmallVector<Expr *, 8> DstExprs; 10437 SmallVector<Expr *, 8> AssignmentOps; 10438 SmallVector<Decl *, 4> ExprCaptures; 10439 SmallVector<Expr *, 4> ExprPostUpdates; 10440 for (Expr *RefExpr : VarList) { 10441 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 10442 SourceLocation ELoc; 10443 SourceRange ERange; 10444 Expr *SimpleRefExpr = RefExpr; 10445 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10446 if (Res.second) { 10447 // It will be analyzed later. 10448 Vars.push_back(RefExpr); 10449 SrcExprs.push_back(nullptr); 10450 DstExprs.push_back(nullptr); 10451 AssignmentOps.push_back(nullptr); 10452 } 10453 ValueDecl *D = Res.first; 10454 if (!D) 10455 continue; 10456 10457 QualType Type = D->getType(); 10458 auto *VD = dyn_cast<VarDecl>(D); 10459 10460 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 10461 // A variable that appears in a lastprivate clause must not have an 10462 // incomplete type or a reference type. 10463 if (RequireCompleteType(ELoc, Type, 10464 diag::err_omp_lastprivate_incomplete_type)) 10465 continue; 10466 Type = Type.getNonReferenceType(); 10467 10468 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 10469 // A variable that is privatized must not have a const-qualified type 10470 // unless it is of class type with a mutable member. This restriction does 10471 // not apply to the firstprivate clause. 10472 // 10473 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 10474 // A variable that appears in a lastprivate clause must not have a 10475 // const-qualified type unless it is of class type with a mutable member. 10476 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 10477 continue; 10478 10479 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 10480 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 10481 // in a Construct] 10482 // Variables with the predetermined data-sharing attributes may not be 10483 // listed in data-sharing attributes clauses, except for the cases 10484 // listed below. 10485 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 10486 // A list item may appear in a firstprivate or lastprivate clause but not 10487 // both. 10488 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 10489 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 10490 (isOpenMPDistributeDirective(CurrDir) || 10491 DVar.CKind != OMPC_firstprivate) && 10492 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 10493 Diag(ELoc, diag::err_omp_wrong_dsa) 10494 << getOpenMPClauseName(DVar.CKind) 10495 << getOpenMPClauseName(OMPC_lastprivate); 10496 reportOriginalDsa(*this, DSAStack, D, DVar); 10497 continue; 10498 } 10499 10500 // OpenMP [2.14.3.5, Restrictions, p.2] 10501 // A list item that is private within a parallel region, or that appears in 10502 // the reduction clause of a parallel construct, must not appear in a 10503 // lastprivate clause on a worksharing construct if any of the corresponding 10504 // worksharing regions ever binds to any of the corresponding parallel 10505 // regions. 10506 DSAStackTy::DSAVarData TopDVar = DVar; 10507 if (isOpenMPWorksharingDirective(CurrDir) && 10508 !isOpenMPParallelDirective(CurrDir) && 10509 !isOpenMPTeamsDirective(CurrDir)) { 10510 DVar = DSAStack->getImplicitDSA(D, true); 10511 if (DVar.CKind != OMPC_shared) { 10512 Diag(ELoc, diag::err_omp_required_access) 10513 << getOpenMPClauseName(OMPC_lastprivate) 10514 << getOpenMPClauseName(OMPC_shared); 10515 reportOriginalDsa(*this, DSAStack, D, DVar); 10516 continue; 10517 } 10518 } 10519 10520 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 10521 // A variable of class type (or array thereof) that appears in a 10522 // lastprivate clause requires an accessible, unambiguous default 10523 // constructor for the class type, unless the list item is also specified 10524 // in a firstprivate clause. 10525 // A variable of class type (or array thereof) that appears in a 10526 // lastprivate clause requires an accessible, unambiguous copy assignment 10527 // operator for the class type. 10528 Type = Context.getBaseElementType(Type).getNonReferenceType(); 10529 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 10530 Type.getUnqualifiedType(), ".lastprivate.src", 10531 D->hasAttrs() ? &D->getAttrs() : nullptr); 10532 DeclRefExpr *PseudoSrcExpr = 10533 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 10534 VarDecl *DstVD = 10535 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 10536 D->hasAttrs() ? &D->getAttrs() : nullptr); 10537 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 10538 // For arrays generate assignment operation for single element and replace 10539 // it by the original array element in CodeGen. 10540 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 10541 PseudoDstExpr, PseudoSrcExpr); 10542 if (AssignmentOp.isInvalid()) 10543 continue; 10544 AssignmentOp = 10545 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 10546 if (AssignmentOp.isInvalid()) 10547 continue; 10548 10549 DeclRefExpr *Ref = nullptr; 10550 if (!VD && !CurContext->isDependentContext()) { 10551 if (TopDVar.CKind == OMPC_firstprivate) { 10552 Ref = TopDVar.PrivateCopy; 10553 } else { 10554 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 10555 if (!isOpenMPCapturedDecl(D)) 10556 ExprCaptures.push_back(Ref->getDecl()); 10557 } 10558 if (TopDVar.CKind == OMPC_firstprivate || 10559 (!isOpenMPCapturedDecl(D) && 10560 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 10561 ExprResult RefRes = DefaultLvalueConversion(Ref); 10562 if (!RefRes.isUsable()) 10563 continue; 10564 ExprResult PostUpdateRes = 10565 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 10566 RefRes.get()); 10567 if (!PostUpdateRes.isUsable()) 10568 continue; 10569 ExprPostUpdates.push_back( 10570 IgnoredValueConversions(PostUpdateRes.get()).get()); 10571 } 10572 } 10573 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 10574 Vars.push_back((VD || CurContext->isDependentContext()) 10575 ? RefExpr->IgnoreParens() 10576 : Ref); 10577 SrcExprs.push_back(PseudoSrcExpr); 10578 DstExprs.push_back(PseudoDstExpr); 10579 AssignmentOps.push_back(AssignmentOp.get()); 10580 } 10581 10582 if (Vars.empty()) 10583 return nullptr; 10584 10585 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10586 Vars, SrcExprs, DstExprs, AssignmentOps, 10587 buildPreInits(Context, ExprCaptures), 10588 buildPostUpdate(*this, ExprPostUpdates)); 10589 } 10590 10591 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 10592 SourceLocation StartLoc, 10593 SourceLocation LParenLoc, 10594 SourceLocation EndLoc) { 10595 SmallVector<Expr *, 8> Vars; 10596 for (Expr *RefExpr : VarList) { 10597 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 10598 SourceLocation ELoc; 10599 SourceRange ERange; 10600 Expr *SimpleRefExpr = RefExpr; 10601 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10602 if (Res.second) { 10603 // It will be analyzed later. 10604 Vars.push_back(RefExpr); 10605 } 10606 ValueDecl *D = Res.first; 10607 if (!D) 10608 continue; 10609 10610 auto *VD = dyn_cast<VarDecl>(D); 10611 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 10612 // in a Construct] 10613 // Variables with the predetermined data-sharing attributes may not be 10614 // listed in data-sharing attributes clauses, except for the cases 10615 // listed below. For these exceptions only, listing a predetermined 10616 // variable in a data-sharing attribute clause is allowed and overrides 10617 // the variable's predetermined data-sharing attributes. 10618 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 10619 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 10620 DVar.RefExpr) { 10621 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 10622 << getOpenMPClauseName(OMPC_shared); 10623 reportOriginalDsa(*this, DSAStack, D, DVar); 10624 continue; 10625 } 10626 10627 DeclRefExpr *Ref = nullptr; 10628 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 10629 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 10630 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 10631 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 10632 ? RefExpr->IgnoreParens() 10633 : Ref); 10634 } 10635 10636 if (Vars.empty()) 10637 return nullptr; 10638 10639 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 10640 } 10641 10642 namespace { 10643 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 10644 DSAStackTy *Stack; 10645 10646 public: 10647 bool VisitDeclRefExpr(DeclRefExpr *E) { 10648 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 10649 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 10650 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 10651 return false; 10652 if (DVar.CKind != OMPC_unknown) 10653 return true; 10654 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 10655 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; }, 10656 /*FromParent=*/true); 10657 return DVarPrivate.CKind != OMPC_unknown; 10658 } 10659 return false; 10660 } 10661 bool VisitStmt(Stmt *S) { 10662 for (Stmt *Child : S->children()) { 10663 if (Child && Visit(Child)) 10664 return true; 10665 } 10666 return false; 10667 } 10668 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 10669 }; 10670 } // namespace 10671 10672 namespace { 10673 // Transform MemberExpression for specified FieldDecl of current class to 10674 // DeclRefExpr to specified OMPCapturedExprDecl. 10675 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 10676 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 10677 ValueDecl *Field = nullptr; 10678 DeclRefExpr *CapturedExpr = nullptr; 10679 10680 public: 10681 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 10682 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 10683 10684 ExprResult TransformMemberExpr(MemberExpr *E) { 10685 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 10686 E->getMemberDecl() == Field) { 10687 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 10688 return CapturedExpr; 10689 } 10690 return BaseTransform::TransformMemberExpr(E); 10691 } 10692 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 10693 }; 10694 } // namespace 10695 10696 template <typename T, typename U> 10697 static T filterLookupForUDReductionAndMapper( 10698 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) { 10699 for (U &Set : Lookups) { 10700 for (auto *D : Set) { 10701 if (T Res = Gen(cast<ValueDecl>(D))) 10702 return Res; 10703 } 10704 } 10705 return T(); 10706 } 10707 10708 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 10709 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 10710 10711 for (auto RD : D->redecls()) { 10712 // Don't bother with extra checks if we already know this one isn't visible. 10713 if (RD == D) 10714 continue; 10715 10716 auto ND = cast<NamedDecl>(RD); 10717 if (LookupResult::isVisible(SemaRef, ND)) 10718 return ND; 10719 } 10720 10721 return nullptr; 10722 } 10723 10724 static void 10725 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id, 10726 SourceLocation Loc, QualType Ty, 10727 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 10728 // Find all of the associated namespaces and classes based on the 10729 // arguments we have. 10730 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10731 Sema::AssociatedClassSet AssociatedClasses; 10732 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 10733 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 10734 AssociatedClasses); 10735 10736 // C++ [basic.lookup.argdep]p3: 10737 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10738 // and let Y be the lookup set produced by argument dependent 10739 // lookup (defined as follows). If X contains [...] then Y is 10740 // empty. Otherwise Y is the set of declarations found in the 10741 // namespaces associated with the argument types as described 10742 // below. The set of declarations found by the lookup of the name 10743 // is the union of X and Y. 10744 // 10745 // Here, we compute Y and add its members to the overloaded 10746 // candidate set. 10747 for (auto *NS : AssociatedNamespaces) { 10748 // When considering an associated namespace, the lookup is the 10749 // same as the lookup performed when the associated namespace is 10750 // used as a qualifier (3.4.3.2) except that: 10751 // 10752 // -- Any using-directives in the associated namespace are 10753 // ignored. 10754 // 10755 // -- Any namespace-scope friend functions declared in 10756 // associated classes are visible within their respective 10757 // namespaces even if they are not visible during an ordinary 10758 // lookup (11.4). 10759 DeclContext::lookup_result R = NS->lookup(Id.getName()); 10760 for (auto *D : R) { 10761 auto *Underlying = D; 10762 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 10763 Underlying = USD->getTargetDecl(); 10764 10765 if (!isa<OMPDeclareReductionDecl>(Underlying) && 10766 !isa<OMPDeclareMapperDecl>(Underlying)) 10767 continue; 10768 10769 if (!SemaRef.isVisible(D)) { 10770 D = findAcceptableDecl(SemaRef, D); 10771 if (!D) 10772 continue; 10773 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 10774 Underlying = USD->getTargetDecl(); 10775 } 10776 Lookups.emplace_back(); 10777 Lookups.back().addDecl(Underlying); 10778 } 10779 } 10780 } 10781 10782 static ExprResult 10783 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 10784 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 10785 const DeclarationNameInfo &ReductionId, QualType Ty, 10786 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 10787 if (ReductionIdScopeSpec.isInvalid()) 10788 return ExprError(); 10789 SmallVector<UnresolvedSet<8>, 4> Lookups; 10790 if (S) { 10791 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 10792 Lookup.suppressDiagnostics(); 10793 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 10794 NamedDecl *D = Lookup.getRepresentativeDecl(); 10795 do { 10796 S = S->getParent(); 10797 } while (S && !S->isDeclScope(D)); 10798 if (S) 10799 S = S->getParent(); 10800 Lookups.emplace_back(); 10801 Lookups.back().append(Lookup.begin(), Lookup.end()); 10802 Lookup.clear(); 10803 } 10804 } else if (auto *ULE = 10805 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 10806 Lookups.push_back(UnresolvedSet<8>()); 10807 Decl *PrevD = nullptr; 10808 for (NamedDecl *D : ULE->decls()) { 10809 if (D == PrevD) 10810 Lookups.push_back(UnresolvedSet<8>()); 10811 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 10812 Lookups.back().addDecl(DRD); 10813 PrevD = D; 10814 } 10815 } 10816 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 10817 Ty->isInstantiationDependentType() || 10818 Ty->containsUnexpandedParameterPack() || 10819 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 10820 return !D->isInvalidDecl() && 10821 (D->getType()->isDependentType() || 10822 D->getType()->isInstantiationDependentType() || 10823 D->getType()->containsUnexpandedParameterPack()); 10824 })) { 10825 UnresolvedSet<8> ResSet; 10826 for (const UnresolvedSet<8> &Set : Lookups) { 10827 if (Set.empty()) 10828 continue; 10829 ResSet.append(Set.begin(), Set.end()); 10830 // The last item marks the end of all declarations at the specified scope. 10831 ResSet.addDecl(Set[Set.size() - 1]); 10832 } 10833 return UnresolvedLookupExpr::Create( 10834 SemaRef.Context, /*NamingClass=*/nullptr, 10835 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 10836 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 10837 } 10838 // Lookup inside the classes. 10839 // C++ [over.match.oper]p3: 10840 // For a unary operator @ with an operand of a type whose 10841 // cv-unqualified version is T1, and for a binary operator @ with 10842 // a left operand of a type whose cv-unqualified version is T1 and 10843 // a right operand of a type whose cv-unqualified version is T2, 10844 // three sets of candidate functions, designated member 10845 // candidates, non-member candidates and built-in candidates, are 10846 // constructed as follows: 10847 // -- If T1 is a complete class type or a class currently being 10848 // defined, the set of member candidates is the result of the 10849 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 10850 // the set of member candidates is empty. 10851 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 10852 Lookup.suppressDiagnostics(); 10853 if (const auto *TyRec = Ty->getAs<RecordType>()) { 10854 // Complete the type if it can be completed. 10855 // If the type is neither complete nor being defined, bail out now. 10856 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 10857 TyRec->getDecl()->getDefinition()) { 10858 Lookup.clear(); 10859 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 10860 if (Lookup.empty()) { 10861 Lookups.emplace_back(); 10862 Lookups.back().append(Lookup.begin(), Lookup.end()); 10863 } 10864 } 10865 } 10866 // Perform ADL. 10867 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 10868 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 10869 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 10870 if (!D->isInvalidDecl() && 10871 SemaRef.Context.hasSameType(D->getType(), Ty)) 10872 return D; 10873 return nullptr; 10874 })) 10875 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 10876 VK_LValue, Loc); 10877 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 10878 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 10879 if (!D->isInvalidDecl() && 10880 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 10881 !Ty.isMoreQualifiedThan(D->getType())) 10882 return D; 10883 return nullptr; 10884 })) { 10885 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 10886 /*DetectVirtual=*/false); 10887 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 10888 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 10889 VD->getType().getUnqualifiedType()))) { 10890 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 10891 /*DiagID=*/0) != 10892 Sema::AR_inaccessible) { 10893 SemaRef.BuildBasePathArray(Paths, BasePath); 10894 return SemaRef.BuildDeclRefExpr( 10895 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 10896 } 10897 } 10898 } 10899 } 10900 if (ReductionIdScopeSpec.isSet()) { 10901 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 10902 return ExprError(); 10903 } 10904 return ExprEmpty(); 10905 } 10906 10907 namespace { 10908 /// Data for the reduction-based clauses. 10909 struct ReductionData { 10910 /// List of original reduction items. 10911 SmallVector<Expr *, 8> Vars; 10912 /// List of private copies of the reduction items. 10913 SmallVector<Expr *, 8> Privates; 10914 /// LHS expressions for the reduction_op expressions. 10915 SmallVector<Expr *, 8> LHSs; 10916 /// RHS expressions for the reduction_op expressions. 10917 SmallVector<Expr *, 8> RHSs; 10918 /// Reduction operation expression. 10919 SmallVector<Expr *, 8> ReductionOps; 10920 /// Taskgroup descriptors for the corresponding reduction items in 10921 /// in_reduction clauses. 10922 SmallVector<Expr *, 8> TaskgroupDescriptors; 10923 /// List of captures for clause. 10924 SmallVector<Decl *, 4> ExprCaptures; 10925 /// List of postupdate expressions. 10926 SmallVector<Expr *, 4> ExprPostUpdates; 10927 ReductionData() = delete; 10928 /// Reserves required memory for the reduction data. 10929 ReductionData(unsigned Size) { 10930 Vars.reserve(Size); 10931 Privates.reserve(Size); 10932 LHSs.reserve(Size); 10933 RHSs.reserve(Size); 10934 ReductionOps.reserve(Size); 10935 TaskgroupDescriptors.reserve(Size); 10936 ExprCaptures.reserve(Size); 10937 ExprPostUpdates.reserve(Size); 10938 } 10939 /// Stores reduction item and reduction operation only (required for dependent 10940 /// reduction item). 10941 void push(Expr *Item, Expr *ReductionOp) { 10942 Vars.emplace_back(Item); 10943 Privates.emplace_back(nullptr); 10944 LHSs.emplace_back(nullptr); 10945 RHSs.emplace_back(nullptr); 10946 ReductionOps.emplace_back(ReductionOp); 10947 TaskgroupDescriptors.emplace_back(nullptr); 10948 } 10949 /// Stores reduction data. 10950 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 10951 Expr *TaskgroupDescriptor) { 10952 Vars.emplace_back(Item); 10953 Privates.emplace_back(Private); 10954 LHSs.emplace_back(LHS); 10955 RHSs.emplace_back(RHS); 10956 ReductionOps.emplace_back(ReductionOp); 10957 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 10958 } 10959 }; 10960 } // namespace 10961 10962 static bool checkOMPArraySectionConstantForReduction( 10963 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 10964 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 10965 const Expr *Length = OASE->getLength(); 10966 if (Length == nullptr) { 10967 // For array sections of the form [1:] or [:], we would need to analyze 10968 // the lower bound... 10969 if (OASE->getColonLoc().isValid()) 10970 return false; 10971 10972 // This is an array subscript which has implicit length 1! 10973 SingleElement = true; 10974 ArraySizes.push_back(llvm::APSInt::get(1)); 10975 } else { 10976 Expr::EvalResult Result; 10977 if (!Length->EvaluateAsInt(Result, Context)) 10978 return false; 10979 10980 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 10981 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 10982 ArraySizes.push_back(ConstantLengthValue); 10983 } 10984 10985 // Get the base of this array section and walk up from there. 10986 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 10987 10988 // We require length = 1 for all array sections except the right-most to 10989 // guarantee that the memory region is contiguous and has no holes in it. 10990 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 10991 Length = TempOASE->getLength(); 10992 if (Length == nullptr) { 10993 // For array sections of the form [1:] or [:], we would need to analyze 10994 // the lower bound... 10995 if (OASE->getColonLoc().isValid()) 10996 return false; 10997 10998 // This is an array subscript which has implicit length 1! 10999 ArraySizes.push_back(llvm::APSInt::get(1)); 11000 } else { 11001 Expr::EvalResult Result; 11002 if (!Length->EvaluateAsInt(Result, Context)) 11003 return false; 11004 11005 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 11006 if (ConstantLengthValue.getSExtValue() != 1) 11007 return false; 11008 11009 ArraySizes.push_back(ConstantLengthValue); 11010 } 11011 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 11012 } 11013 11014 // If we have a single element, we don't need to add the implicit lengths. 11015 if (!SingleElement) { 11016 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 11017 // Has implicit length 1! 11018 ArraySizes.push_back(llvm::APSInt::get(1)); 11019 Base = TempASE->getBase()->IgnoreParenImpCasts(); 11020 } 11021 } 11022 11023 // This array section can be privatized as a single value or as a constant 11024 // sized array. 11025 return true; 11026 } 11027 11028 static bool actOnOMPReductionKindClause( 11029 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 11030 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11031 SourceLocation ColonLoc, SourceLocation EndLoc, 11032 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11033 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 11034 DeclarationName DN = ReductionId.getName(); 11035 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 11036 BinaryOperatorKind BOK = BO_Comma; 11037 11038 ASTContext &Context = S.Context; 11039 // OpenMP [2.14.3.6, reduction clause] 11040 // C 11041 // reduction-identifier is either an identifier or one of the following 11042 // operators: +, -, *, &, |, ^, && and || 11043 // C++ 11044 // reduction-identifier is either an id-expression or one of the following 11045 // operators: +, -, *, &, |, ^, && and || 11046 switch (OOK) { 11047 case OO_Plus: 11048 case OO_Minus: 11049 BOK = BO_Add; 11050 break; 11051 case OO_Star: 11052 BOK = BO_Mul; 11053 break; 11054 case OO_Amp: 11055 BOK = BO_And; 11056 break; 11057 case OO_Pipe: 11058 BOK = BO_Or; 11059 break; 11060 case OO_Caret: 11061 BOK = BO_Xor; 11062 break; 11063 case OO_AmpAmp: 11064 BOK = BO_LAnd; 11065 break; 11066 case OO_PipePipe: 11067 BOK = BO_LOr; 11068 break; 11069 case OO_New: 11070 case OO_Delete: 11071 case OO_Array_New: 11072 case OO_Array_Delete: 11073 case OO_Slash: 11074 case OO_Percent: 11075 case OO_Tilde: 11076 case OO_Exclaim: 11077 case OO_Equal: 11078 case OO_Less: 11079 case OO_Greater: 11080 case OO_LessEqual: 11081 case OO_GreaterEqual: 11082 case OO_PlusEqual: 11083 case OO_MinusEqual: 11084 case OO_StarEqual: 11085 case OO_SlashEqual: 11086 case OO_PercentEqual: 11087 case OO_CaretEqual: 11088 case OO_AmpEqual: 11089 case OO_PipeEqual: 11090 case OO_LessLess: 11091 case OO_GreaterGreater: 11092 case OO_LessLessEqual: 11093 case OO_GreaterGreaterEqual: 11094 case OO_EqualEqual: 11095 case OO_ExclaimEqual: 11096 case OO_Spaceship: 11097 case OO_PlusPlus: 11098 case OO_MinusMinus: 11099 case OO_Comma: 11100 case OO_ArrowStar: 11101 case OO_Arrow: 11102 case OO_Call: 11103 case OO_Subscript: 11104 case OO_Conditional: 11105 case OO_Coawait: 11106 case NUM_OVERLOADED_OPERATORS: 11107 llvm_unreachable("Unexpected reduction identifier"); 11108 case OO_None: 11109 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 11110 if (II->isStr("max")) 11111 BOK = BO_GT; 11112 else if (II->isStr("min")) 11113 BOK = BO_LT; 11114 } 11115 break; 11116 } 11117 SourceRange ReductionIdRange; 11118 if (ReductionIdScopeSpec.isValid()) 11119 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 11120 else 11121 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 11122 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 11123 11124 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 11125 bool FirstIter = true; 11126 for (Expr *RefExpr : VarList) { 11127 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 11128 // OpenMP [2.1, C/C++] 11129 // A list item is a variable or array section, subject to the restrictions 11130 // specified in Section 2.4 on page 42 and in each of the sections 11131 // describing clauses and directives for which a list appears. 11132 // OpenMP [2.14.3.3, Restrictions, p.1] 11133 // A variable that is part of another variable (as an array or 11134 // structure element) cannot appear in a private clause. 11135 if (!FirstIter && IR != ER) 11136 ++IR; 11137 FirstIter = false; 11138 SourceLocation ELoc; 11139 SourceRange ERange; 11140 Expr *SimpleRefExpr = RefExpr; 11141 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 11142 /*AllowArraySection=*/true); 11143 if (Res.second) { 11144 // Try to find 'declare reduction' corresponding construct before using 11145 // builtin/overloaded operators. 11146 QualType Type = Context.DependentTy; 11147 CXXCastPath BasePath; 11148 ExprResult DeclareReductionRef = buildDeclareReductionRef( 11149 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 11150 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 11151 Expr *ReductionOp = nullptr; 11152 if (S.CurContext->isDependentContext() && 11153 (DeclareReductionRef.isUnset() || 11154 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 11155 ReductionOp = DeclareReductionRef.get(); 11156 // It will be analyzed later. 11157 RD.push(RefExpr, ReductionOp); 11158 } 11159 ValueDecl *D = Res.first; 11160 if (!D) 11161 continue; 11162 11163 Expr *TaskgroupDescriptor = nullptr; 11164 QualType Type; 11165 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 11166 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 11167 if (ASE) { 11168 Type = ASE->getType().getNonReferenceType(); 11169 } else if (OASE) { 11170 QualType BaseType = 11171 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 11172 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 11173 Type = ATy->getElementType(); 11174 else 11175 Type = BaseType->getPointeeType(); 11176 Type = Type.getNonReferenceType(); 11177 } else { 11178 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 11179 } 11180 auto *VD = dyn_cast<VarDecl>(D); 11181 11182 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 11183 // A variable that appears in a private clause must not have an incomplete 11184 // type or a reference type. 11185 if (S.RequireCompleteType(ELoc, D->getType(), 11186 diag::err_omp_reduction_incomplete_type)) 11187 continue; 11188 // OpenMP [2.14.3.6, reduction clause, Restrictions] 11189 // A list item that appears in a reduction clause must not be 11190 // const-qualified. 11191 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 11192 /*AcceptIfMutable*/ false, ASE || OASE)) 11193 continue; 11194 11195 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 11196 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 11197 // If a list-item is a reference type then it must bind to the same object 11198 // for all threads of the team. 11199 if (!ASE && !OASE) { 11200 if (VD) { 11201 VarDecl *VDDef = VD->getDefinition(); 11202 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 11203 DSARefChecker Check(Stack); 11204 if (Check.Visit(VDDef->getInit())) { 11205 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 11206 << getOpenMPClauseName(ClauseKind) << ERange; 11207 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 11208 continue; 11209 } 11210 } 11211 } 11212 11213 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 11214 // in a Construct] 11215 // Variables with the predetermined data-sharing attributes may not be 11216 // listed in data-sharing attributes clauses, except for the cases 11217 // listed below. For these exceptions only, listing a predetermined 11218 // variable in a data-sharing attribute clause is allowed and overrides 11219 // the variable's predetermined data-sharing attributes. 11220 // OpenMP [2.14.3.6, Restrictions, p.3] 11221 // Any number of reduction clauses can be specified on the directive, 11222 // but a list item can appear only once in the reduction clauses for that 11223 // directive. 11224 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 11225 if (DVar.CKind == OMPC_reduction) { 11226 S.Diag(ELoc, diag::err_omp_once_referenced) 11227 << getOpenMPClauseName(ClauseKind); 11228 if (DVar.RefExpr) 11229 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 11230 continue; 11231 } 11232 if (DVar.CKind != OMPC_unknown) { 11233 S.Diag(ELoc, diag::err_omp_wrong_dsa) 11234 << getOpenMPClauseName(DVar.CKind) 11235 << getOpenMPClauseName(OMPC_reduction); 11236 reportOriginalDsa(S, Stack, D, DVar); 11237 continue; 11238 } 11239 11240 // OpenMP [2.14.3.6, Restrictions, p.1] 11241 // A list item that appears in a reduction clause of a worksharing 11242 // construct must be shared in the parallel regions to which any of the 11243 // worksharing regions arising from the worksharing construct bind. 11244 if (isOpenMPWorksharingDirective(CurrDir) && 11245 !isOpenMPParallelDirective(CurrDir) && 11246 !isOpenMPTeamsDirective(CurrDir)) { 11247 DVar = Stack->getImplicitDSA(D, true); 11248 if (DVar.CKind != OMPC_shared) { 11249 S.Diag(ELoc, diag::err_omp_required_access) 11250 << getOpenMPClauseName(OMPC_reduction) 11251 << getOpenMPClauseName(OMPC_shared); 11252 reportOriginalDsa(S, Stack, D, DVar); 11253 continue; 11254 } 11255 } 11256 } 11257 11258 // Try to find 'declare reduction' corresponding construct before using 11259 // builtin/overloaded operators. 11260 CXXCastPath BasePath; 11261 ExprResult DeclareReductionRef = buildDeclareReductionRef( 11262 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 11263 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 11264 if (DeclareReductionRef.isInvalid()) 11265 continue; 11266 if (S.CurContext->isDependentContext() && 11267 (DeclareReductionRef.isUnset() || 11268 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 11269 RD.push(RefExpr, DeclareReductionRef.get()); 11270 continue; 11271 } 11272 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 11273 // Not allowed reduction identifier is found. 11274 S.Diag(ReductionId.getBeginLoc(), 11275 diag::err_omp_unknown_reduction_identifier) 11276 << Type << ReductionIdRange; 11277 continue; 11278 } 11279 11280 // OpenMP [2.14.3.6, reduction clause, Restrictions] 11281 // The type of a list item that appears in a reduction clause must be valid 11282 // for the reduction-identifier. For a max or min reduction in C, the type 11283 // of the list item must be an allowed arithmetic data type: char, int, 11284 // float, double, or _Bool, possibly modified with long, short, signed, or 11285 // unsigned. For a max or min reduction in C++, the type of the list item 11286 // must be an allowed arithmetic data type: char, wchar_t, int, float, 11287 // double, or bool, possibly modified with long, short, signed, or unsigned. 11288 if (DeclareReductionRef.isUnset()) { 11289 if ((BOK == BO_GT || BOK == BO_LT) && 11290 !(Type->isScalarType() || 11291 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 11292 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 11293 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 11294 if (!ASE && !OASE) { 11295 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 11296 VarDecl::DeclarationOnly; 11297 S.Diag(D->getLocation(), 11298 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11299 << D; 11300 } 11301 continue; 11302 } 11303 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 11304 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 11305 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 11306 << getOpenMPClauseName(ClauseKind); 11307 if (!ASE && !OASE) { 11308 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 11309 VarDecl::DeclarationOnly; 11310 S.Diag(D->getLocation(), 11311 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11312 << D; 11313 } 11314 continue; 11315 } 11316 } 11317 11318 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 11319 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 11320 D->hasAttrs() ? &D->getAttrs() : nullptr); 11321 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 11322 D->hasAttrs() ? &D->getAttrs() : nullptr); 11323 QualType PrivateTy = Type; 11324 11325 // Try if we can determine constant lengths for all array sections and avoid 11326 // the VLA. 11327 bool ConstantLengthOASE = false; 11328 if (OASE) { 11329 bool SingleElement; 11330 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 11331 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 11332 Context, OASE, SingleElement, ArraySizes); 11333 11334 // If we don't have a single element, we must emit a constant array type. 11335 if (ConstantLengthOASE && !SingleElement) { 11336 for (llvm::APSInt &Size : ArraySizes) 11337 PrivateTy = Context.getConstantArrayType( 11338 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0); 11339 } 11340 } 11341 11342 if ((OASE && !ConstantLengthOASE) || 11343 (!OASE && !ASE && 11344 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 11345 if (!Context.getTargetInfo().isVLASupported() && 11346 S.shouldDiagnoseTargetSupportFromOpenMP()) { 11347 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 11348 S.Diag(ELoc, diag::note_vla_unsupported); 11349 continue; 11350 } 11351 // For arrays/array sections only: 11352 // Create pseudo array type for private copy. The size for this array will 11353 // be generated during codegen. 11354 // For array subscripts or single variables Private Ty is the same as Type 11355 // (type of the variable or single array element). 11356 PrivateTy = Context.getVariableArrayType( 11357 Type, 11358 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue), 11359 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 11360 } else if (!ASE && !OASE && 11361 Context.getAsArrayType(D->getType().getNonReferenceType())) { 11362 PrivateTy = D->getType().getNonReferenceType(); 11363 } 11364 // Private copy. 11365 VarDecl *PrivateVD = 11366 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 11367 D->hasAttrs() ? &D->getAttrs() : nullptr, 11368 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 11369 // Add initializer for private variable. 11370 Expr *Init = nullptr; 11371 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 11372 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 11373 if (DeclareReductionRef.isUsable()) { 11374 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 11375 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 11376 if (DRD->getInitializer()) { 11377 Init = DRDRef; 11378 RHSVD->setInit(DRDRef); 11379 RHSVD->setInitStyle(VarDecl::CallInit); 11380 } 11381 } else { 11382 switch (BOK) { 11383 case BO_Add: 11384 case BO_Xor: 11385 case BO_Or: 11386 case BO_LOr: 11387 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 11388 if (Type->isScalarType() || Type->isAnyComplexType()) 11389 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 11390 break; 11391 case BO_Mul: 11392 case BO_LAnd: 11393 if (Type->isScalarType() || Type->isAnyComplexType()) { 11394 // '*' and '&&' reduction ops - initializer is '1'. 11395 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 11396 } 11397 break; 11398 case BO_And: { 11399 // '&' reduction op - initializer is '~0'. 11400 QualType OrigType = Type; 11401 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 11402 Type = ComplexTy->getElementType(); 11403 if (Type->isRealFloatingType()) { 11404 llvm::APFloat InitValue = 11405 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 11406 /*isIEEE=*/true); 11407 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 11408 Type, ELoc); 11409 } else if (Type->isScalarType()) { 11410 uint64_t Size = Context.getTypeSize(Type); 11411 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 11412 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 11413 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 11414 } 11415 if (Init && OrigType->isAnyComplexType()) { 11416 // Init = 0xFFFF + 0xFFFFi; 11417 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 11418 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 11419 } 11420 Type = OrigType; 11421 break; 11422 } 11423 case BO_LT: 11424 case BO_GT: { 11425 // 'min' reduction op - initializer is 'Largest representable number in 11426 // the reduction list item type'. 11427 // 'max' reduction op - initializer is 'Least representable number in 11428 // the reduction list item type'. 11429 if (Type->isIntegerType() || Type->isPointerType()) { 11430 bool IsSigned = Type->hasSignedIntegerRepresentation(); 11431 uint64_t Size = Context.getTypeSize(Type); 11432 QualType IntTy = 11433 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 11434 llvm::APInt InitValue = 11435 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 11436 : llvm::APInt::getMinValue(Size) 11437 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 11438 : llvm::APInt::getMaxValue(Size); 11439 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 11440 if (Type->isPointerType()) { 11441 // Cast to pointer type. 11442 ExprResult CastExpr = S.BuildCStyleCastExpr( 11443 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 11444 if (CastExpr.isInvalid()) 11445 continue; 11446 Init = CastExpr.get(); 11447 } 11448 } else if (Type->isRealFloatingType()) { 11449 llvm::APFloat InitValue = llvm::APFloat::getLargest( 11450 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 11451 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 11452 Type, ELoc); 11453 } 11454 break; 11455 } 11456 case BO_PtrMemD: 11457 case BO_PtrMemI: 11458 case BO_MulAssign: 11459 case BO_Div: 11460 case BO_Rem: 11461 case BO_Sub: 11462 case BO_Shl: 11463 case BO_Shr: 11464 case BO_LE: 11465 case BO_GE: 11466 case BO_EQ: 11467 case BO_NE: 11468 case BO_Cmp: 11469 case BO_AndAssign: 11470 case BO_XorAssign: 11471 case BO_OrAssign: 11472 case BO_Assign: 11473 case BO_AddAssign: 11474 case BO_SubAssign: 11475 case BO_DivAssign: 11476 case BO_RemAssign: 11477 case BO_ShlAssign: 11478 case BO_ShrAssign: 11479 case BO_Comma: 11480 llvm_unreachable("Unexpected reduction operation"); 11481 } 11482 } 11483 if (Init && DeclareReductionRef.isUnset()) 11484 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 11485 else if (!Init) 11486 S.ActOnUninitializedDecl(RHSVD); 11487 if (RHSVD->isInvalidDecl()) 11488 continue; 11489 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 11490 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 11491 << Type << ReductionIdRange; 11492 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 11493 VarDecl::DeclarationOnly; 11494 S.Diag(D->getLocation(), 11495 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11496 << D; 11497 continue; 11498 } 11499 // Store initializer for single element in private copy. Will be used during 11500 // codegen. 11501 PrivateVD->setInit(RHSVD->getInit()); 11502 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 11503 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 11504 ExprResult ReductionOp; 11505 if (DeclareReductionRef.isUsable()) { 11506 QualType RedTy = DeclareReductionRef.get()->getType(); 11507 QualType PtrRedTy = Context.getPointerType(RedTy); 11508 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 11509 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 11510 if (!BasePath.empty()) { 11511 LHS = S.DefaultLvalueConversion(LHS.get()); 11512 RHS = S.DefaultLvalueConversion(RHS.get()); 11513 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 11514 CK_UncheckedDerivedToBase, LHS.get(), 11515 &BasePath, LHS.get()->getValueKind()); 11516 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 11517 CK_UncheckedDerivedToBase, RHS.get(), 11518 &BasePath, RHS.get()->getValueKind()); 11519 } 11520 FunctionProtoType::ExtProtoInfo EPI; 11521 QualType Params[] = {PtrRedTy, PtrRedTy}; 11522 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 11523 auto *OVE = new (Context) OpaqueValueExpr( 11524 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 11525 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 11526 Expr *Args[] = {LHS.get(), RHS.get()}; 11527 ReductionOp = 11528 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 11529 } else { 11530 ReductionOp = S.BuildBinOp( 11531 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE); 11532 if (ReductionOp.isUsable()) { 11533 if (BOK != BO_LT && BOK != BO_GT) { 11534 ReductionOp = 11535 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 11536 BO_Assign, LHSDRE, ReductionOp.get()); 11537 } else { 11538 auto *ConditionalOp = new (Context) 11539 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE, 11540 Type, VK_LValue, OK_Ordinary); 11541 ReductionOp = 11542 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 11543 BO_Assign, LHSDRE, ConditionalOp); 11544 } 11545 if (ReductionOp.isUsable()) 11546 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 11547 /*DiscardedValue*/ false); 11548 } 11549 if (!ReductionOp.isUsable()) 11550 continue; 11551 } 11552 11553 // OpenMP [2.15.4.6, Restrictions, p.2] 11554 // A list item that appears in an in_reduction clause of a task construct 11555 // must appear in a task_reduction clause of a construct associated with a 11556 // taskgroup region that includes the participating task in its taskgroup 11557 // set. The construct associated with the innermost region that meets this 11558 // condition must specify the same reduction-identifier as the in_reduction 11559 // clause. 11560 if (ClauseKind == OMPC_in_reduction) { 11561 SourceRange ParentSR; 11562 BinaryOperatorKind ParentBOK; 11563 const Expr *ParentReductionOp; 11564 Expr *ParentBOKTD, *ParentReductionOpTD; 11565 DSAStackTy::DSAVarData ParentBOKDSA = 11566 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 11567 ParentBOKTD); 11568 DSAStackTy::DSAVarData ParentReductionOpDSA = 11569 Stack->getTopMostTaskgroupReductionData( 11570 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 11571 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 11572 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 11573 if (!IsParentBOK && !IsParentReductionOp) { 11574 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction); 11575 continue; 11576 } 11577 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 11578 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK || 11579 IsParentReductionOp) { 11580 bool EmitError = true; 11581 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 11582 llvm::FoldingSetNodeID RedId, ParentRedId; 11583 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 11584 DeclareReductionRef.get()->Profile(RedId, Context, 11585 /*Canonical=*/true); 11586 EmitError = RedId != ParentRedId; 11587 } 11588 if (EmitError) { 11589 S.Diag(ReductionId.getBeginLoc(), 11590 diag::err_omp_reduction_identifier_mismatch) 11591 << ReductionIdRange << RefExpr->getSourceRange(); 11592 S.Diag(ParentSR.getBegin(), 11593 diag::note_omp_previous_reduction_identifier) 11594 << ParentSR 11595 << (IsParentBOK ? ParentBOKDSA.RefExpr 11596 : ParentReductionOpDSA.RefExpr) 11597 ->getSourceRange(); 11598 continue; 11599 } 11600 } 11601 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 11602 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined."); 11603 } 11604 11605 DeclRefExpr *Ref = nullptr; 11606 Expr *VarsExpr = RefExpr->IgnoreParens(); 11607 if (!VD && !S.CurContext->isDependentContext()) { 11608 if (ASE || OASE) { 11609 TransformExprToCaptures RebuildToCapture(S, D); 11610 VarsExpr = 11611 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 11612 Ref = RebuildToCapture.getCapturedExpr(); 11613 } else { 11614 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 11615 } 11616 if (!S.isOpenMPCapturedDecl(D)) { 11617 RD.ExprCaptures.emplace_back(Ref->getDecl()); 11618 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 11619 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 11620 if (!RefRes.isUsable()) 11621 continue; 11622 ExprResult PostUpdateRes = 11623 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 11624 RefRes.get()); 11625 if (!PostUpdateRes.isUsable()) 11626 continue; 11627 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 11628 Stack->getCurrentDirective() == OMPD_taskgroup) { 11629 S.Diag(RefExpr->getExprLoc(), 11630 diag::err_omp_reduction_non_addressable_expression) 11631 << RefExpr->getSourceRange(); 11632 continue; 11633 } 11634 RD.ExprPostUpdates.emplace_back( 11635 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 11636 } 11637 } 11638 } 11639 // All reduction items are still marked as reduction (to do not increase 11640 // code base size). 11641 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 11642 if (CurrDir == OMPD_taskgroup) { 11643 if (DeclareReductionRef.isUsable()) 11644 Stack->addTaskgroupReductionData(D, ReductionIdRange, 11645 DeclareReductionRef.get()); 11646 else 11647 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 11648 } 11649 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 11650 TaskgroupDescriptor); 11651 } 11652 return RD.Vars.empty(); 11653 } 11654 11655 OMPClause *Sema::ActOnOpenMPReductionClause( 11656 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11657 SourceLocation ColonLoc, SourceLocation EndLoc, 11658 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11659 ArrayRef<Expr *> UnresolvedReductions) { 11660 ReductionData RD(VarList.size()); 11661 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 11662 StartLoc, LParenLoc, ColonLoc, EndLoc, 11663 ReductionIdScopeSpec, ReductionId, 11664 UnresolvedReductions, RD)) 11665 return nullptr; 11666 11667 return OMPReductionClause::Create( 11668 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 11669 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 11670 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 11671 buildPreInits(Context, RD.ExprCaptures), 11672 buildPostUpdate(*this, RD.ExprPostUpdates)); 11673 } 11674 11675 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 11676 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11677 SourceLocation ColonLoc, SourceLocation EndLoc, 11678 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11679 ArrayRef<Expr *> UnresolvedReductions) { 11680 ReductionData RD(VarList.size()); 11681 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 11682 StartLoc, LParenLoc, ColonLoc, EndLoc, 11683 ReductionIdScopeSpec, ReductionId, 11684 UnresolvedReductions, RD)) 11685 return nullptr; 11686 11687 return OMPTaskReductionClause::Create( 11688 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 11689 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 11690 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 11691 buildPreInits(Context, RD.ExprCaptures), 11692 buildPostUpdate(*this, RD.ExprPostUpdates)); 11693 } 11694 11695 OMPClause *Sema::ActOnOpenMPInReductionClause( 11696 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11697 SourceLocation ColonLoc, SourceLocation EndLoc, 11698 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11699 ArrayRef<Expr *> UnresolvedReductions) { 11700 ReductionData RD(VarList.size()); 11701 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 11702 StartLoc, LParenLoc, ColonLoc, EndLoc, 11703 ReductionIdScopeSpec, ReductionId, 11704 UnresolvedReductions, RD)) 11705 return nullptr; 11706 11707 return OMPInReductionClause::Create( 11708 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 11709 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 11710 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 11711 buildPreInits(Context, RD.ExprCaptures), 11712 buildPostUpdate(*this, RD.ExprPostUpdates)); 11713 } 11714 11715 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 11716 SourceLocation LinLoc) { 11717 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 11718 LinKind == OMPC_LINEAR_unknown) { 11719 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 11720 return true; 11721 } 11722 return false; 11723 } 11724 11725 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 11726 OpenMPLinearClauseKind LinKind, 11727 QualType Type) { 11728 const auto *VD = dyn_cast_or_null<VarDecl>(D); 11729 // A variable must not have an incomplete type or a reference type. 11730 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 11731 return true; 11732 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 11733 !Type->isReferenceType()) { 11734 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 11735 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 11736 return true; 11737 } 11738 Type = Type.getNonReferenceType(); 11739 11740 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 11741 // A variable that is privatized must not have a const-qualified type 11742 // unless it is of class type with a mutable member. This restriction does 11743 // not apply to the firstprivate clause. 11744 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 11745 return true; 11746 11747 // A list item must be of integral or pointer type. 11748 Type = Type.getUnqualifiedType().getCanonicalType(); 11749 const auto *Ty = Type.getTypePtrOrNull(); 11750 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 11751 !Ty->isPointerType())) { 11752 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 11753 if (D) { 11754 bool IsDecl = 11755 !VD || 11756 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11757 Diag(D->getLocation(), 11758 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11759 << D; 11760 } 11761 return true; 11762 } 11763 return false; 11764 } 11765 11766 OMPClause *Sema::ActOnOpenMPLinearClause( 11767 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 11768 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 11769 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 11770 SmallVector<Expr *, 8> Vars; 11771 SmallVector<Expr *, 8> Privates; 11772 SmallVector<Expr *, 8> Inits; 11773 SmallVector<Decl *, 4> ExprCaptures; 11774 SmallVector<Expr *, 4> ExprPostUpdates; 11775 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 11776 LinKind = OMPC_LINEAR_val; 11777 for (Expr *RefExpr : VarList) { 11778 assert(RefExpr && "NULL expr in OpenMP linear clause."); 11779 SourceLocation ELoc; 11780 SourceRange ERange; 11781 Expr *SimpleRefExpr = RefExpr; 11782 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11783 if (Res.second) { 11784 // It will be analyzed later. 11785 Vars.push_back(RefExpr); 11786 Privates.push_back(nullptr); 11787 Inits.push_back(nullptr); 11788 } 11789 ValueDecl *D = Res.first; 11790 if (!D) 11791 continue; 11792 11793 QualType Type = D->getType(); 11794 auto *VD = dyn_cast<VarDecl>(D); 11795 11796 // OpenMP [2.14.3.7, linear clause] 11797 // A list-item cannot appear in more than one linear clause. 11798 // A list-item that appears in a linear clause cannot appear in any 11799 // other data-sharing attribute clause. 11800 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 11801 if (DVar.RefExpr) { 11802 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 11803 << getOpenMPClauseName(OMPC_linear); 11804 reportOriginalDsa(*this, DSAStack, D, DVar); 11805 continue; 11806 } 11807 11808 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 11809 continue; 11810 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 11811 11812 // Build private copy of original var. 11813 VarDecl *Private = 11814 buildVarDecl(*this, ELoc, Type, D->getName(), 11815 D->hasAttrs() ? &D->getAttrs() : nullptr, 11816 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 11817 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 11818 // Build var to save initial value. 11819 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 11820 Expr *InitExpr; 11821 DeclRefExpr *Ref = nullptr; 11822 if (!VD && !CurContext->isDependentContext()) { 11823 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 11824 if (!isOpenMPCapturedDecl(D)) { 11825 ExprCaptures.push_back(Ref->getDecl()); 11826 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 11827 ExprResult RefRes = DefaultLvalueConversion(Ref); 11828 if (!RefRes.isUsable()) 11829 continue; 11830 ExprResult PostUpdateRes = 11831 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 11832 SimpleRefExpr, RefRes.get()); 11833 if (!PostUpdateRes.isUsable()) 11834 continue; 11835 ExprPostUpdates.push_back( 11836 IgnoredValueConversions(PostUpdateRes.get()).get()); 11837 } 11838 } 11839 } 11840 if (LinKind == OMPC_LINEAR_uval) 11841 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 11842 else 11843 InitExpr = VD ? SimpleRefExpr : Ref; 11844 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 11845 /*DirectInit=*/false); 11846 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 11847 11848 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 11849 Vars.push_back((VD || CurContext->isDependentContext()) 11850 ? RefExpr->IgnoreParens() 11851 : Ref); 11852 Privates.push_back(PrivateRef); 11853 Inits.push_back(InitRef); 11854 } 11855 11856 if (Vars.empty()) 11857 return nullptr; 11858 11859 Expr *StepExpr = Step; 11860 Expr *CalcStepExpr = nullptr; 11861 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 11862 !Step->isInstantiationDependent() && 11863 !Step->containsUnexpandedParameterPack()) { 11864 SourceLocation StepLoc = Step->getBeginLoc(); 11865 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 11866 if (Val.isInvalid()) 11867 return nullptr; 11868 StepExpr = Val.get(); 11869 11870 // Build var to save the step value. 11871 VarDecl *SaveVar = 11872 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 11873 ExprResult SaveRef = 11874 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 11875 ExprResult CalcStep = 11876 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 11877 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 11878 11879 // Warn about zero linear step (it would be probably better specified as 11880 // making corresponding variables 'const'). 11881 llvm::APSInt Result; 11882 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 11883 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 11884 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 11885 << (Vars.size() > 1); 11886 if (!IsConstant && CalcStep.isUsable()) { 11887 // Calculate the step beforehand instead of doing this on each iteration. 11888 // (This is not used if the number of iterations may be kfold-ed). 11889 CalcStepExpr = CalcStep.get(); 11890 } 11891 } 11892 11893 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 11894 ColonLoc, EndLoc, Vars, Privates, Inits, 11895 StepExpr, CalcStepExpr, 11896 buildPreInits(Context, ExprCaptures), 11897 buildPostUpdate(*this, ExprPostUpdates)); 11898 } 11899 11900 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 11901 Expr *NumIterations, Sema &SemaRef, 11902 Scope *S, DSAStackTy *Stack) { 11903 // Walk the vars and build update/final expressions for the CodeGen. 11904 SmallVector<Expr *, 8> Updates; 11905 SmallVector<Expr *, 8> Finals; 11906 Expr *Step = Clause.getStep(); 11907 Expr *CalcStep = Clause.getCalcStep(); 11908 // OpenMP [2.14.3.7, linear clause] 11909 // If linear-step is not specified it is assumed to be 1. 11910 if (!Step) 11911 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 11912 else if (CalcStep) 11913 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 11914 bool HasErrors = false; 11915 auto CurInit = Clause.inits().begin(); 11916 auto CurPrivate = Clause.privates().begin(); 11917 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 11918 for (Expr *RefExpr : Clause.varlists()) { 11919 SourceLocation ELoc; 11920 SourceRange ERange; 11921 Expr *SimpleRefExpr = RefExpr; 11922 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 11923 ValueDecl *D = Res.first; 11924 if (Res.second || !D) { 11925 Updates.push_back(nullptr); 11926 Finals.push_back(nullptr); 11927 HasErrors = true; 11928 continue; 11929 } 11930 auto &&Info = Stack->isLoopControlVariable(D); 11931 // OpenMP [2.15.11, distribute simd Construct] 11932 // A list item may not appear in a linear clause, unless it is the loop 11933 // iteration variable. 11934 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 11935 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 11936 SemaRef.Diag(ELoc, 11937 diag::err_omp_linear_distribute_var_non_loop_iteration); 11938 Updates.push_back(nullptr); 11939 Finals.push_back(nullptr); 11940 HasErrors = true; 11941 continue; 11942 } 11943 Expr *InitExpr = *CurInit; 11944 11945 // Build privatized reference to the current linear var. 11946 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 11947 Expr *CapturedRef; 11948 if (LinKind == OMPC_LINEAR_uval) 11949 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 11950 else 11951 CapturedRef = 11952 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 11953 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 11954 /*RefersToCapture=*/true); 11955 11956 // Build update: Var = InitExpr + IV * Step 11957 ExprResult Update; 11958 if (!Info.first) 11959 Update = 11960 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 11961 InitExpr, IV, Step, /* Subtract */ false); 11962 else 11963 Update = *CurPrivate; 11964 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 11965 /*DiscardedValue*/ false); 11966 11967 // Build final: Var = InitExpr + NumIterations * Step 11968 ExprResult Final; 11969 if (!Info.first) 11970 Final = 11971 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 11972 InitExpr, NumIterations, Step, /*Subtract=*/false); 11973 else 11974 Final = *CurPrivate; 11975 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 11976 /*DiscardedValue*/ false); 11977 11978 if (!Update.isUsable() || !Final.isUsable()) { 11979 Updates.push_back(nullptr); 11980 Finals.push_back(nullptr); 11981 HasErrors = true; 11982 } else { 11983 Updates.push_back(Update.get()); 11984 Finals.push_back(Final.get()); 11985 } 11986 ++CurInit; 11987 ++CurPrivate; 11988 } 11989 Clause.setUpdates(Updates); 11990 Clause.setFinals(Finals); 11991 return HasErrors; 11992 } 11993 11994 OMPClause *Sema::ActOnOpenMPAlignedClause( 11995 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 11996 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 11997 SmallVector<Expr *, 8> Vars; 11998 for (Expr *RefExpr : VarList) { 11999 assert(RefExpr && "NULL expr in OpenMP linear clause."); 12000 SourceLocation ELoc; 12001 SourceRange ERange; 12002 Expr *SimpleRefExpr = RefExpr; 12003 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12004 if (Res.second) { 12005 // It will be analyzed later. 12006 Vars.push_back(RefExpr); 12007 } 12008 ValueDecl *D = Res.first; 12009 if (!D) 12010 continue; 12011 12012 QualType QType = D->getType(); 12013 auto *VD = dyn_cast<VarDecl>(D); 12014 12015 // OpenMP [2.8.1, simd construct, Restrictions] 12016 // The type of list items appearing in the aligned clause must be 12017 // array, pointer, reference to array, or reference to pointer. 12018 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 12019 const Type *Ty = QType.getTypePtrOrNull(); 12020 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 12021 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 12022 << QType << getLangOpts().CPlusPlus << ERange; 12023 bool IsDecl = 12024 !VD || 12025 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 12026 Diag(D->getLocation(), 12027 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 12028 << D; 12029 continue; 12030 } 12031 12032 // OpenMP [2.8.1, simd construct, Restrictions] 12033 // A list-item cannot appear in more than one aligned clause. 12034 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 12035 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 12036 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 12037 << getOpenMPClauseName(OMPC_aligned); 12038 continue; 12039 } 12040 12041 DeclRefExpr *Ref = nullptr; 12042 if (!VD && isOpenMPCapturedDecl(D)) 12043 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 12044 Vars.push_back(DefaultFunctionArrayConversion( 12045 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 12046 .get()); 12047 } 12048 12049 // OpenMP [2.8.1, simd construct, Description] 12050 // The parameter of the aligned clause, alignment, must be a constant 12051 // positive integer expression. 12052 // If no optional parameter is specified, implementation-defined default 12053 // alignments for SIMD instructions on the target platforms are assumed. 12054 if (Alignment != nullptr) { 12055 ExprResult AlignResult = 12056 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 12057 if (AlignResult.isInvalid()) 12058 return nullptr; 12059 Alignment = AlignResult.get(); 12060 } 12061 if (Vars.empty()) 12062 return nullptr; 12063 12064 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 12065 EndLoc, Vars, Alignment); 12066 } 12067 12068 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 12069 SourceLocation StartLoc, 12070 SourceLocation LParenLoc, 12071 SourceLocation EndLoc) { 12072 SmallVector<Expr *, 8> Vars; 12073 SmallVector<Expr *, 8> SrcExprs; 12074 SmallVector<Expr *, 8> DstExprs; 12075 SmallVector<Expr *, 8> AssignmentOps; 12076 for (Expr *RefExpr : VarList) { 12077 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 12078 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 12079 // It will be analyzed later. 12080 Vars.push_back(RefExpr); 12081 SrcExprs.push_back(nullptr); 12082 DstExprs.push_back(nullptr); 12083 AssignmentOps.push_back(nullptr); 12084 continue; 12085 } 12086 12087 SourceLocation ELoc = RefExpr->getExprLoc(); 12088 // OpenMP [2.1, C/C++] 12089 // A list item is a variable name. 12090 // OpenMP [2.14.4.1, Restrictions, p.1] 12091 // A list item that appears in a copyin clause must be threadprivate. 12092 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 12093 if (!DE || !isa<VarDecl>(DE->getDecl())) { 12094 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 12095 << 0 << RefExpr->getSourceRange(); 12096 continue; 12097 } 12098 12099 Decl *D = DE->getDecl(); 12100 auto *VD = cast<VarDecl>(D); 12101 12102 QualType Type = VD->getType(); 12103 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 12104 // It will be analyzed later. 12105 Vars.push_back(DE); 12106 SrcExprs.push_back(nullptr); 12107 DstExprs.push_back(nullptr); 12108 AssignmentOps.push_back(nullptr); 12109 continue; 12110 } 12111 12112 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 12113 // A list item that appears in a copyin clause must be threadprivate. 12114 if (!DSAStack->isThreadPrivate(VD)) { 12115 Diag(ELoc, diag::err_omp_required_access) 12116 << getOpenMPClauseName(OMPC_copyin) 12117 << getOpenMPDirectiveName(OMPD_threadprivate); 12118 continue; 12119 } 12120 12121 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 12122 // A variable of class type (or array thereof) that appears in a 12123 // copyin clause requires an accessible, unambiguous copy assignment 12124 // operator for the class type. 12125 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 12126 VarDecl *SrcVD = 12127 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 12128 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 12129 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 12130 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 12131 VarDecl *DstVD = 12132 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 12133 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 12134 DeclRefExpr *PseudoDstExpr = 12135 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 12136 // For arrays generate assignment operation for single element and replace 12137 // it by the original array element in CodeGen. 12138 ExprResult AssignmentOp = 12139 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 12140 PseudoSrcExpr); 12141 if (AssignmentOp.isInvalid()) 12142 continue; 12143 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 12144 /*DiscardedValue*/ false); 12145 if (AssignmentOp.isInvalid()) 12146 continue; 12147 12148 DSAStack->addDSA(VD, DE, OMPC_copyin); 12149 Vars.push_back(DE); 12150 SrcExprs.push_back(PseudoSrcExpr); 12151 DstExprs.push_back(PseudoDstExpr); 12152 AssignmentOps.push_back(AssignmentOp.get()); 12153 } 12154 12155 if (Vars.empty()) 12156 return nullptr; 12157 12158 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 12159 SrcExprs, DstExprs, AssignmentOps); 12160 } 12161 12162 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 12163 SourceLocation StartLoc, 12164 SourceLocation LParenLoc, 12165 SourceLocation EndLoc) { 12166 SmallVector<Expr *, 8> Vars; 12167 SmallVector<Expr *, 8> SrcExprs; 12168 SmallVector<Expr *, 8> DstExprs; 12169 SmallVector<Expr *, 8> AssignmentOps; 12170 for (Expr *RefExpr : VarList) { 12171 assert(RefExpr && "NULL expr in OpenMP linear clause."); 12172 SourceLocation ELoc; 12173 SourceRange ERange; 12174 Expr *SimpleRefExpr = RefExpr; 12175 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12176 if (Res.second) { 12177 // It will be analyzed later. 12178 Vars.push_back(RefExpr); 12179 SrcExprs.push_back(nullptr); 12180 DstExprs.push_back(nullptr); 12181 AssignmentOps.push_back(nullptr); 12182 } 12183 ValueDecl *D = Res.first; 12184 if (!D) 12185 continue; 12186 12187 QualType Type = D->getType(); 12188 auto *VD = dyn_cast<VarDecl>(D); 12189 12190 // OpenMP [2.14.4.2, Restrictions, p.2] 12191 // A list item that appears in a copyprivate clause may not appear in a 12192 // private or firstprivate clause on the single construct. 12193 if (!VD || !DSAStack->isThreadPrivate(VD)) { 12194 DSAStackTy::DSAVarData DVar = 12195 DSAStack->getTopDSA(D, /*FromParent=*/false); 12196 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 12197 DVar.RefExpr) { 12198 Diag(ELoc, diag::err_omp_wrong_dsa) 12199 << getOpenMPClauseName(DVar.CKind) 12200 << getOpenMPClauseName(OMPC_copyprivate); 12201 reportOriginalDsa(*this, DSAStack, D, DVar); 12202 continue; 12203 } 12204 12205 // OpenMP [2.11.4.2, Restrictions, p.1] 12206 // All list items that appear in a copyprivate clause must be either 12207 // threadprivate or private in the enclosing context. 12208 if (DVar.CKind == OMPC_unknown) { 12209 DVar = DSAStack->getImplicitDSA(D, false); 12210 if (DVar.CKind == OMPC_shared) { 12211 Diag(ELoc, diag::err_omp_required_access) 12212 << getOpenMPClauseName(OMPC_copyprivate) 12213 << "threadprivate or private in the enclosing context"; 12214 reportOriginalDsa(*this, DSAStack, D, DVar); 12215 continue; 12216 } 12217 } 12218 } 12219 12220 // Variably modified types are not supported. 12221 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 12222 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 12223 << getOpenMPClauseName(OMPC_copyprivate) << Type 12224 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 12225 bool IsDecl = 12226 !VD || 12227 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 12228 Diag(D->getLocation(), 12229 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 12230 << D; 12231 continue; 12232 } 12233 12234 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 12235 // A variable of class type (or array thereof) that appears in a 12236 // copyin clause requires an accessible, unambiguous copy assignment 12237 // operator for the class type. 12238 Type = Context.getBaseElementType(Type.getNonReferenceType()) 12239 .getUnqualifiedType(); 12240 VarDecl *SrcVD = 12241 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 12242 D->hasAttrs() ? &D->getAttrs() : nullptr); 12243 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 12244 VarDecl *DstVD = 12245 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 12246 D->hasAttrs() ? &D->getAttrs() : nullptr); 12247 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 12248 ExprResult AssignmentOp = BuildBinOp( 12249 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 12250 if (AssignmentOp.isInvalid()) 12251 continue; 12252 AssignmentOp = 12253 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 12254 if (AssignmentOp.isInvalid()) 12255 continue; 12256 12257 // No need to mark vars as copyprivate, they are already threadprivate or 12258 // implicitly private. 12259 assert(VD || isOpenMPCapturedDecl(D)); 12260 Vars.push_back( 12261 VD ? RefExpr->IgnoreParens() 12262 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 12263 SrcExprs.push_back(PseudoSrcExpr); 12264 DstExprs.push_back(PseudoDstExpr); 12265 AssignmentOps.push_back(AssignmentOp.get()); 12266 } 12267 12268 if (Vars.empty()) 12269 return nullptr; 12270 12271 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12272 Vars, SrcExprs, DstExprs, AssignmentOps); 12273 } 12274 12275 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 12276 SourceLocation StartLoc, 12277 SourceLocation LParenLoc, 12278 SourceLocation EndLoc) { 12279 if (VarList.empty()) 12280 return nullptr; 12281 12282 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 12283 } 12284 12285 OMPClause * 12286 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 12287 SourceLocation DepLoc, SourceLocation ColonLoc, 12288 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 12289 SourceLocation LParenLoc, SourceLocation EndLoc) { 12290 if (DSAStack->getCurrentDirective() == OMPD_ordered && 12291 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 12292 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 12293 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 12294 return nullptr; 12295 } 12296 if (DSAStack->getCurrentDirective() != OMPD_ordered && 12297 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 12298 DepKind == OMPC_DEPEND_sink)) { 12299 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 12300 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 12301 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 12302 /*Last=*/OMPC_DEPEND_unknown, Except) 12303 << getOpenMPClauseName(OMPC_depend); 12304 return nullptr; 12305 } 12306 SmallVector<Expr *, 8> Vars; 12307 DSAStackTy::OperatorOffsetTy OpsOffs; 12308 llvm::APSInt DepCounter(/*BitWidth=*/32); 12309 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 12310 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 12311 if (const Expr *OrderedCountExpr = 12312 DSAStack->getParentOrderedRegionParam().first) { 12313 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 12314 TotalDepCount.setIsUnsigned(/*Val=*/true); 12315 } 12316 } 12317 for (Expr *RefExpr : VarList) { 12318 assert(RefExpr && "NULL expr in OpenMP shared clause."); 12319 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 12320 // It will be analyzed later. 12321 Vars.push_back(RefExpr); 12322 continue; 12323 } 12324 12325 SourceLocation ELoc = RefExpr->getExprLoc(); 12326 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 12327 if (DepKind == OMPC_DEPEND_sink) { 12328 if (DSAStack->getParentOrderedRegionParam().first && 12329 DepCounter >= TotalDepCount) { 12330 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 12331 continue; 12332 } 12333 ++DepCounter; 12334 // OpenMP [2.13.9, Summary] 12335 // depend(dependence-type : vec), where dependence-type is: 12336 // 'sink' and where vec is the iteration vector, which has the form: 12337 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 12338 // where n is the value specified by the ordered clause in the loop 12339 // directive, xi denotes the loop iteration variable of the i-th nested 12340 // loop associated with the loop directive, and di is a constant 12341 // non-negative integer. 12342 if (CurContext->isDependentContext()) { 12343 // It will be analyzed later. 12344 Vars.push_back(RefExpr); 12345 continue; 12346 } 12347 SimpleExpr = SimpleExpr->IgnoreImplicit(); 12348 OverloadedOperatorKind OOK = OO_None; 12349 SourceLocation OOLoc; 12350 Expr *LHS = SimpleExpr; 12351 Expr *RHS = nullptr; 12352 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 12353 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 12354 OOLoc = BO->getOperatorLoc(); 12355 LHS = BO->getLHS()->IgnoreParenImpCasts(); 12356 RHS = BO->getRHS()->IgnoreParenImpCasts(); 12357 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 12358 OOK = OCE->getOperator(); 12359 OOLoc = OCE->getOperatorLoc(); 12360 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 12361 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 12362 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 12363 OOK = MCE->getMethodDecl() 12364 ->getNameInfo() 12365 .getName() 12366 .getCXXOverloadedOperator(); 12367 OOLoc = MCE->getCallee()->getExprLoc(); 12368 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 12369 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 12370 } 12371 SourceLocation ELoc; 12372 SourceRange ERange; 12373 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 12374 if (Res.second) { 12375 // It will be analyzed later. 12376 Vars.push_back(RefExpr); 12377 } 12378 ValueDecl *D = Res.first; 12379 if (!D) 12380 continue; 12381 12382 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 12383 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 12384 continue; 12385 } 12386 if (RHS) { 12387 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 12388 RHS, OMPC_depend, /*StrictlyPositive=*/false); 12389 if (RHSRes.isInvalid()) 12390 continue; 12391 } 12392 if (!CurContext->isDependentContext() && 12393 DSAStack->getParentOrderedRegionParam().first && 12394 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 12395 const ValueDecl *VD = 12396 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 12397 if (VD) 12398 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 12399 << 1 << VD; 12400 else 12401 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 12402 continue; 12403 } 12404 OpsOffs.emplace_back(RHS, OOK); 12405 } else { 12406 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 12407 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 12408 (ASE && 12409 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() && 12410 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 12411 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 12412 << RefExpr->getSourceRange(); 12413 continue; 12414 } 12415 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 12416 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 12417 ExprResult Res = 12418 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts()); 12419 getDiagnostics().setSuppressAllDiagnostics(Suppress); 12420 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) { 12421 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 12422 << RefExpr->getSourceRange(); 12423 continue; 12424 } 12425 } 12426 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 12427 } 12428 12429 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 12430 TotalDepCount > VarList.size() && 12431 DSAStack->getParentOrderedRegionParam().first && 12432 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 12433 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 12434 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 12435 } 12436 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 12437 Vars.empty()) 12438 return nullptr; 12439 12440 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12441 DepKind, DepLoc, ColonLoc, Vars, 12442 TotalDepCount.getZExtValue()); 12443 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 12444 DSAStack->isParentOrderedRegion()) 12445 DSAStack->addDoacrossDependClause(C, OpsOffs); 12446 return C; 12447 } 12448 12449 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 12450 SourceLocation LParenLoc, 12451 SourceLocation EndLoc) { 12452 Expr *ValExpr = Device; 12453 Stmt *HelperValStmt = nullptr; 12454 12455 // OpenMP [2.9.1, Restrictions] 12456 // The device expression must evaluate to a non-negative integer value. 12457 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 12458 /*StrictlyPositive=*/false)) 12459 return nullptr; 12460 12461 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12462 OpenMPDirectiveKind CaptureRegion = 12463 getOpenMPCaptureRegionForClause(DKind, OMPC_device); 12464 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12465 ValExpr = MakeFullExpr(ValExpr).get(); 12466 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 12467 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12468 HelperValStmt = buildPreInits(Context, Captures); 12469 } 12470 12471 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion, 12472 StartLoc, LParenLoc, EndLoc); 12473 } 12474 12475 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 12476 DSAStackTy *Stack, QualType QTy, 12477 bool FullCheck = true) { 12478 NamedDecl *ND; 12479 if (QTy->isIncompleteType(&ND)) { 12480 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 12481 return false; 12482 } 12483 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 12484 !QTy.isTrivialType(SemaRef.Context)) 12485 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 12486 return true; 12487 } 12488 12489 /// Return true if it can be proven that the provided array expression 12490 /// (array section or array subscript) does NOT specify the whole size of the 12491 /// array whose base type is \a BaseQTy. 12492 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 12493 const Expr *E, 12494 QualType BaseQTy) { 12495 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 12496 12497 // If this is an array subscript, it refers to the whole size if the size of 12498 // the dimension is constant and equals 1. Also, an array section assumes the 12499 // format of an array subscript if no colon is used. 12500 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 12501 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 12502 return ATy->getSize().getSExtValue() != 1; 12503 // Size can't be evaluated statically. 12504 return false; 12505 } 12506 12507 assert(OASE && "Expecting array section if not an array subscript."); 12508 const Expr *LowerBound = OASE->getLowerBound(); 12509 const Expr *Length = OASE->getLength(); 12510 12511 // If there is a lower bound that does not evaluates to zero, we are not 12512 // covering the whole dimension. 12513 if (LowerBound) { 12514 Expr::EvalResult Result; 12515 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 12516 return false; // Can't get the integer value as a constant. 12517 12518 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 12519 if (ConstLowerBound.getSExtValue()) 12520 return true; 12521 } 12522 12523 // If we don't have a length we covering the whole dimension. 12524 if (!Length) 12525 return false; 12526 12527 // If the base is a pointer, we don't have a way to get the size of the 12528 // pointee. 12529 if (BaseQTy->isPointerType()) 12530 return false; 12531 12532 // We can only check if the length is the same as the size of the dimension 12533 // if we have a constant array. 12534 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 12535 if (!CATy) 12536 return false; 12537 12538 Expr::EvalResult Result; 12539 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 12540 return false; // Can't get the integer value as a constant. 12541 12542 llvm::APSInt ConstLength = Result.Val.getInt(); 12543 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 12544 } 12545 12546 // Return true if it can be proven that the provided array expression (array 12547 // section or array subscript) does NOT specify a single element of the array 12548 // whose base type is \a BaseQTy. 12549 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 12550 const Expr *E, 12551 QualType BaseQTy) { 12552 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 12553 12554 // An array subscript always refer to a single element. Also, an array section 12555 // assumes the format of an array subscript if no colon is used. 12556 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 12557 return false; 12558 12559 assert(OASE && "Expecting array section if not an array subscript."); 12560 const Expr *Length = OASE->getLength(); 12561 12562 // If we don't have a length we have to check if the array has unitary size 12563 // for this dimension. Also, we should always expect a length if the base type 12564 // is pointer. 12565 if (!Length) { 12566 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 12567 return ATy->getSize().getSExtValue() != 1; 12568 // We cannot assume anything. 12569 return false; 12570 } 12571 12572 // Check if the length evaluates to 1. 12573 Expr::EvalResult Result; 12574 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 12575 return false; // Can't get the integer value as a constant. 12576 12577 llvm::APSInt ConstLength = Result.Val.getInt(); 12578 return ConstLength.getSExtValue() != 1; 12579 } 12580 12581 // Return the expression of the base of the mappable expression or null if it 12582 // cannot be determined and do all the necessary checks to see if the expression 12583 // is valid as a standalone mappable expression. In the process, record all the 12584 // components of the expression. 12585 static const Expr *checkMapClauseExpressionBase( 12586 Sema &SemaRef, Expr *E, 12587 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 12588 OpenMPClauseKind CKind, bool NoDiagnose) { 12589 SourceLocation ELoc = E->getExprLoc(); 12590 SourceRange ERange = E->getSourceRange(); 12591 12592 // The base of elements of list in a map clause have to be either: 12593 // - a reference to variable or field. 12594 // - a member expression. 12595 // - an array expression. 12596 // 12597 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 12598 // reference to 'r'. 12599 // 12600 // If we have: 12601 // 12602 // struct SS { 12603 // Bla S; 12604 // foo() { 12605 // #pragma omp target map (S.Arr[:12]); 12606 // } 12607 // } 12608 // 12609 // We want to retrieve the member expression 'this->S'; 12610 12611 const Expr *RelevantExpr = nullptr; 12612 12613 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 12614 // If a list item is an array section, it must specify contiguous storage. 12615 // 12616 // For this restriction it is sufficient that we make sure only references 12617 // to variables or fields and array expressions, and that no array sections 12618 // exist except in the rightmost expression (unless they cover the whole 12619 // dimension of the array). E.g. these would be invalid: 12620 // 12621 // r.ArrS[3:5].Arr[6:7] 12622 // 12623 // r.ArrS[3:5].x 12624 // 12625 // but these would be valid: 12626 // r.ArrS[3].Arr[6:7] 12627 // 12628 // r.ArrS[3].x 12629 12630 bool AllowUnitySizeArraySection = true; 12631 bool AllowWholeSizeArraySection = true; 12632 12633 while (!RelevantExpr) { 12634 E = E->IgnoreParenImpCasts(); 12635 12636 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 12637 if (!isa<VarDecl>(CurE->getDecl())) 12638 return nullptr; 12639 12640 RelevantExpr = CurE; 12641 12642 // If we got a reference to a declaration, we should not expect any array 12643 // section before that. 12644 AllowUnitySizeArraySection = false; 12645 AllowWholeSizeArraySection = false; 12646 12647 // Record the component. 12648 CurComponents.emplace_back(CurE, CurE->getDecl()); 12649 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) { 12650 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 12651 12652 if (isa<CXXThisExpr>(BaseE)) 12653 // We found a base expression: this->Val. 12654 RelevantExpr = CurE; 12655 else 12656 E = BaseE; 12657 12658 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 12659 if (!NoDiagnose) { 12660 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 12661 << CurE->getSourceRange(); 12662 return nullptr; 12663 } 12664 if (RelevantExpr) 12665 return nullptr; 12666 continue; 12667 } 12668 12669 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 12670 12671 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 12672 // A bit-field cannot appear in a map clause. 12673 // 12674 if (FD->isBitField()) { 12675 if (!NoDiagnose) { 12676 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 12677 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 12678 return nullptr; 12679 } 12680 if (RelevantExpr) 12681 return nullptr; 12682 continue; 12683 } 12684 12685 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12686 // If the type of a list item is a reference to a type T then the type 12687 // will be considered to be T for all purposes of this clause. 12688 QualType CurType = BaseE->getType().getNonReferenceType(); 12689 12690 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 12691 // A list item cannot be a variable that is a member of a structure with 12692 // a union type. 12693 // 12694 if (CurType->isUnionType()) { 12695 if (!NoDiagnose) { 12696 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 12697 << CurE->getSourceRange(); 12698 return nullptr; 12699 } 12700 continue; 12701 } 12702 12703 // If we got a member expression, we should not expect any array section 12704 // before that: 12705 // 12706 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 12707 // If a list item is an element of a structure, only the rightmost symbol 12708 // of the variable reference can be an array section. 12709 // 12710 AllowUnitySizeArraySection = false; 12711 AllowWholeSizeArraySection = false; 12712 12713 // Record the component. 12714 CurComponents.emplace_back(CurE, FD); 12715 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 12716 E = CurE->getBase()->IgnoreParenImpCasts(); 12717 12718 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 12719 if (!NoDiagnose) { 12720 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 12721 << 0 << CurE->getSourceRange(); 12722 return nullptr; 12723 } 12724 continue; 12725 } 12726 12727 // If we got an array subscript that express the whole dimension we 12728 // can have any array expressions before. If it only expressing part of 12729 // the dimension, we can only have unitary-size array expressions. 12730 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 12731 E->getType())) 12732 AllowWholeSizeArraySection = false; 12733 12734 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 12735 Expr::EvalResult Result; 12736 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) { 12737 if (!Result.Val.getInt().isNullValue()) { 12738 SemaRef.Diag(CurE->getIdx()->getExprLoc(), 12739 diag::err_omp_invalid_map_this_expr); 12740 SemaRef.Diag(CurE->getIdx()->getExprLoc(), 12741 diag::note_omp_invalid_subscript_on_this_ptr_map); 12742 } 12743 } 12744 RelevantExpr = TE; 12745 } 12746 12747 // Record the component - we don't have any declaration associated. 12748 CurComponents.emplace_back(CurE, nullptr); 12749 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 12750 assert(!NoDiagnose && "Array sections cannot be implicitly mapped."); 12751 E = CurE->getBase()->IgnoreParenImpCasts(); 12752 12753 QualType CurType = 12754 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 12755 12756 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12757 // If the type of a list item is a reference to a type T then the type 12758 // will be considered to be T for all purposes of this clause. 12759 if (CurType->isReferenceType()) 12760 CurType = CurType->getPointeeType(); 12761 12762 bool IsPointer = CurType->isAnyPointerType(); 12763 12764 if (!IsPointer && !CurType->isArrayType()) { 12765 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 12766 << 0 << CurE->getSourceRange(); 12767 return nullptr; 12768 } 12769 12770 bool NotWhole = 12771 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 12772 bool NotUnity = 12773 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 12774 12775 if (AllowWholeSizeArraySection) { 12776 // Any array section is currently allowed. Allowing a whole size array 12777 // section implies allowing a unity array section as well. 12778 // 12779 // If this array section refers to the whole dimension we can still 12780 // accept other array sections before this one, except if the base is a 12781 // pointer. Otherwise, only unitary sections are accepted. 12782 if (NotWhole || IsPointer) 12783 AllowWholeSizeArraySection = false; 12784 } else if (AllowUnitySizeArraySection && NotUnity) { 12785 // A unity or whole array section is not allowed and that is not 12786 // compatible with the properties of the current array section. 12787 SemaRef.Diag( 12788 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 12789 << CurE->getSourceRange(); 12790 return nullptr; 12791 } 12792 12793 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 12794 Expr::EvalResult ResultR; 12795 Expr::EvalResult ResultL; 12796 if (CurE->getLength()->EvaluateAsInt(ResultR, 12797 SemaRef.getASTContext())) { 12798 if (!ResultR.Val.getInt().isOneValue()) { 12799 SemaRef.Diag(CurE->getLength()->getExprLoc(), 12800 diag::err_omp_invalid_map_this_expr); 12801 SemaRef.Diag(CurE->getLength()->getExprLoc(), 12802 diag::note_omp_invalid_length_on_this_ptr_mapping); 12803 } 12804 } 12805 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt( 12806 ResultL, SemaRef.getASTContext())) { 12807 if (!ResultL.Val.getInt().isNullValue()) { 12808 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(), 12809 diag::err_omp_invalid_map_this_expr); 12810 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(), 12811 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 12812 } 12813 } 12814 RelevantExpr = TE; 12815 } 12816 12817 // Record the component - we don't have any declaration associated. 12818 CurComponents.emplace_back(CurE, nullptr); 12819 } else { 12820 if (!NoDiagnose) { 12821 // If nothing else worked, this is not a valid map clause expression. 12822 SemaRef.Diag( 12823 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 12824 << ERange; 12825 } 12826 return nullptr; 12827 } 12828 } 12829 12830 return RelevantExpr; 12831 } 12832 12833 // Return true if expression E associated with value VD has conflicts with other 12834 // map information. 12835 static bool checkMapConflicts( 12836 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 12837 bool CurrentRegionOnly, 12838 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 12839 OpenMPClauseKind CKind) { 12840 assert(VD && E); 12841 SourceLocation ELoc = E->getExprLoc(); 12842 SourceRange ERange = E->getSourceRange(); 12843 12844 // In order to easily check the conflicts we need to match each component of 12845 // the expression under test with the components of the expressions that are 12846 // already in the stack. 12847 12848 assert(!CurComponents.empty() && "Map clause expression with no components!"); 12849 assert(CurComponents.back().getAssociatedDeclaration() == VD && 12850 "Map clause expression with unexpected base!"); 12851 12852 // Variables to help detecting enclosing problems in data environment nests. 12853 bool IsEnclosedByDataEnvironmentExpr = false; 12854 const Expr *EnclosingExpr = nullptr; 12855 12856 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 12857 VD, CurrentRegionOnly, 12858 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 12859 ERange, CKind, &EnclosingExpr, 12860 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 12861 StackComponents, 12862 OpenMPClauseKind) { 12863 assert(!StackComponents.empty() && 12864 "Map clause expression with no components!"); 12865 assert(StackComponents.back().getAssociatedDeclaration() == VD && 12866 "Map clause expression with unexpected base!"); 12867 (void)VD; 12868 12869 // The whole expression in the stack. 12870 const Expr *RE = StackComponents.front().getAssociatedExpression(); 12871 12872 // Expressions must start from the same base. Here we detect at which 12873 // point both expressions diverge from each other and see if we can 12874 // detect if the memory referred to both expressions is contiguous and 12875 // do not overlap. 12876 auto CI = CurComponents.rbegin(); 12877 auto CE = CurComponents.rend(); 12878 auto SI = StackComponents.rbegin(); 12879 auto SE = StackComponents.rend(); 12880 for (; CI != CE && SI != SE; ++CI, ++SI) { 12881 12882 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 12883 // At most one list item can be an array item derived from a given 12884 // variable in map clauses of the same construct. 12885 if (CurrentRegionOnly && 12886 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 12887 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 12888 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 12889 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 12890 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 12891 diag::err_omp_multiple_array_items_in_map_clause) 12892 << CI->getAssociatedExpression()->getSourceRange(); 12893 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 12894 diag::note_used_here) 12895 << SI->getAssociatedExpression()->getSourceRange(); 12896 return true; 12897 } 12898 12899 // Do both expressions have the same kind? 12900 if (CI->getAssociatedExpression()->getStmtClass() != 12901 SI->getAssociatedExpression()->getStmtClass()) 12902 break; 12903 12904 // Are we dealing with different variables/fields? 12905 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 12906 break; 12907 } 12908 // Check if the extra components of the expressions in the enclosing 12909 // data environment are redundant for the current base declaration. 12910 // If they are, the maps completely overlap, which is legal. 12911 for (; SI != SE; ++SI) { 12912 QualType Type; 12913 if (const auto *ASE = 12914 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 12915 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 12916 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 12917 SI->getAssociatedExpression())) { 12918 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 12919 Type = 12920 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 12921 } 12922 if (Type.isNull() || Type->isAnyPointerType() || 12923 checkArrayExpressionDoesNotReferToWholeSize( 12924 SemaRef, SI->getAssociatedExpression(), Type)) 12925 break; 12926 } 12927 12928 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 12929 // List items of map clauses in the same construct must not share 12930 // original storage. 12931 // 12932 // If the expressions are exactly the same or one is a subset of the 12933 // other, it means they are sharing storage. 12934 if (CI == CE && SI == SE) { 12935 if (CurrentRegionOnly) { 12936 if (CKind == OMPC_map) { 12937 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 12938 } else { 12939 assert(CKind == OMPC_to || CKind == OMPC_from); 12940 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 12941 << ERange; 12942 } 12943 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12944 << RE->getSourceRange(); 12945 return true; 12946 } 12947 // If we find the same expression in the enclosing data environment, 12948 // that is legal. 12949 IsEnclosedByDataEnvironmentExpr = true; 12950 return false; 12951 } 12952 12953 QualType DerivedType = 12954 std::prev(CI)->getAssociatedDeclaration()->getType(); 12955 SourceLocation DerivedLoc = 12956 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 12957 12958 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12959 // If the type of a list item is a reference to a type T then the type 12960 // will be considered to be T for all purposes of this clause. 12961 DerivedType = DerivedType.getNonReferenceType(); 12962 12963 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 12964 // A variable for which the type is pointer and an array section 12965 // derived from that variable must not appear as list items of map 12966 // clauses of the same construct. 12967 // 12968 // Also, cover one of the cases in: 12969 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 12970 // If any part of the original storage of a list item has corresponding 12971 // storage in the device data environment, all of the original storage 12972 // must have corresponding storage in the device data environment. 12973 // 12974 if (DerivedType->isAnyPointerType()) { 12975 if (CI == CE || SI == SE) { 12976 SemaRef.Diag( 12977 DerivedLoc, 12978 diag::err_omp_pointer_mapped_along_with_derived_section) 12979 << DerivedLoc; 12980 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12981 << RE->getSourceRange(); 12982 return true; 12983 } 12984 if (CI->getAssociatedExpression()->getStmtClass() != 12985 SI->getAssociatedExpression()->getStmtClass() || 12986 CI->getAssociatedDeclaration()->getCanonicalDecl() == 12987 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 12988 assert(CI != CE && SI != SE); 12989 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 12990 << DerivedLoc; 12991 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12992 << RE->getSourceRange(); 12993 return true; 12994 } 12995 } 12996 12997 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 12998 // List items of map clauses in the same construct must not share 12999 // original storage. 13000 // 13001 // An expression is a subset of the other. 13002 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 13003 if (CKind == OMPC_map) { 13004 if (CI != CE || SI != SE) { 13005 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 13006 // a pointer. 13007 auto Begin = 13008 CI != CE ? CurComponents.begin() : StackComponents.begin(); 13009 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 13010 auto It = Begin; 13011 while (It != End && !It->getAssociatedDeclaration()) 13012 std::advance(It, 1); 13013 assert(It != End && 13014 "Expected at least one component with the declaration."); 13015 if (It != Begin && It->getAssociatedDeclaration() 13016 ->getType() 13017 .getCanonicalType() 13018 ->isAnyPointerType()) { 13019 IsEnclosedByDataEnvironmentExpr = false; 13020 EnclosingExpr = nullptr; 13021 return false; 13022 } 13023 } 13024 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 13025 } else { 13026 assert(CKind == OMPC_to || CKind == OMPC_from); 13027 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 13028 << ERange; 13029 } 13030 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 13031 << RE->getSourceRange(); 13032 return true; 13033 } 13034 13035 // The current expression uses the same base as other expression in the 13036 // data environment but does not contain it completely. 13037 if (!CurrentRegionOnly && SI != SE) 13038 EnclosingExpr = RE; 13039 13040 // The current expression is a subset of the expression in the data 13041 // environment. 13042 IsEnclosedByDataEnvironmentExpr |= 13043 (!CurrentRegionOnly && CI != CE && SI == SE); 13044 13045 return false; 13046 }); 13047 13048 if (CurrentRegionOnly) 13049 return FoundError; 13050 13051 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 13052 // If any part of the original storage of a list item has corresponding 13053 // storage in the device data environment, all of the original storage must 13054 // have corresponding storage in the device data environment. 13055 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 13056 // If a list item is an element of a structure, and a different element of 13057 // the structure has a corresponding list item in the device data environment 13058 // prior to a task encountering the construct associated with the map clause, 13059 // then the list item must also have a corresponding list item in the device 13060 // data environment prior to the task encountering the construct. 13061 // 13062 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 13063 SemaRef.Diag(ELoc, 13064 diag::err_omp_original_storage_is_shared_and_does_not_contain) 13065 << ERange; 13066 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 13067 << EnclosingExpr->getSourceRange(); 13068 return true; 13069 } 13070 13071 return FoundError; 13072 } 13073 13074 // Look up the user-defined mapper given the mapper name and mapped type, and 13075 // build a reference to it. 13076 ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 13077 CXXScopeSpec &MapperIdScopeSpec, 13078 const DeclarationNameInfo &MapperId, 13079 QualType Type, Expr *UnresolvedMapper) { 13080 if (MapperIdScopeSpec.isInvalid()) 13081 return ExprError(); 13082 // Find all user-defined mappers with the given MapperId. 13083 SmallVector<UnresolvedSet<8>, 4> Lookups; 13084 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); 13085 Lookup.suppressDiagnostics(); 13086 if (S) { 13087 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { 13088 NamedDecl *D = Lookup.getRepresentativeDecl(); 13089 while (S && !S->isDeclScope(D)) 13090 S = S->getParent(); 13091 if (S) 13092 S = S->getParent(); 13093 Lookups.emplace_back(); 13094 Lookups.back().append(Lookup.begin(), Lookup.end()); 13095 Lookup.clear(); 13096 } 13097 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) { 13098 // Extract the user-defined mappers with the given MapperId. 13099 Lookups.push_back(UnresolvedSet<8>()); 13100 for (NamedDecl *D : ULE->decls()) { 13101 auto *DMD = cast<OMPDeclareMapperDecl>(D); 13102 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation."); 13103 Lookups.back().addDecl(DMD); 13104 } 13105 } 13106 // Defer the lookup for dependent types. The results will be passed through 13107 // UnresolvedMapper on instantiation. 13108 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() || 13109 Type->isInstantiationDependentType() || 13110 Type->containsUnexpandedParameterPack() || 13111 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 13112 return !D->isInvalidDecl() && 13113 (D->getType()->isDependentType() || 13114 D->getType()->isInstantiationDependentType() || 13115 D->getType()->containsUnexpandedParameterPack()); 13116 })) { 13117 UnresolvedSet<8> URS; 13118 for (const UnresolvedSet<8> &Set : Lookups) { 13119 if (Set.empty()) 13120 continue; 13121 URS.append(Set.begin(), Set.end()); 13122 } 13123 return UnresolvedLookupExpr::Create( 13124 SemaRef.Context, /*NamingClass=*/nullptr, 13125 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId, 13126 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end()); 13127 } 13128 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 13129 // The type must be of struct, union or class type in C and C++ 13130 if (!Type->isStructureOrClassType() && !Type->isUnionType()) 13131 return ExprEmpty(); 13132 SourceLocation Loc = MapperId.getLoc(); 13133 // Perform argument dependent lookup. 13134 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet()) 13135 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups); 13136 // Return the first user-defined mapper with the desired type. 13137 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 13138 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * { 13139 if (!D->isInvalidDecl() && 13140 SemaRef.Context.hasSameType(D->getType(), Type)) 13141 return D; 13142 return nullptr; 13143 })) 13144 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 13145 // Find the first user-defined mapper with a type derived from the desired 13146 // type. 13147 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 13148 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * { 13149 if (!D->isInvalidDecl() && 13150 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) && 13151 !Type.isMoreQualifiedThan(D->getType())) 13152 return D; 13153 return nullptr; 13154 })) { 13155 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 13156 /*DetectVirtual=*/false); 13157 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) { 13158 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 13159 VD->getType().getUnqualifiedType()))) { 13160 if (SemaRef.CheckBaseClassAccess( 13161 Loc, VD->getType(), Type, Paths.front(), 13162 /*DiagID=*/0) != Sema::AR_inaccessible) { 13163 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 13164 } 13165 } 13166 } 13167 } 13168 // Report error if a mapper is specified, but cannot be found. 13169 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") { 13170 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper) 13171 << Type << MapperId.getName(); 13172 return ExprError(); 13173 } 13174 return ExprEmpty(); 13175 } 13176 13177 namespace { 13178 // Utility struct that gathers all the related lists associated with a mappable 13179 // expression. 13180 struct MappableVarListInfo { 13181 // The list of expressions. 13182 ArrayRef<Expr *> VarList; 13183 // The list of processed expressions. 13184 SmallVector<Expr *, 16> ProcessedVarList; 13185 // The mappble components for each expression. 13186 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 13187 // The base declaration of the variable. 13188 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 13189 // The reference to the user-defined mapper associated with every expression. 13190 SmallVector<Expr *, 16> UDMapperList; 13191 13192 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 13193 // We have a list of components and base declarations for each entry in the 13194 // variable list. 13195 VarComponents.reserve(VarList.size()); 13196 VarBaseDeclarations.reserve(VarList.size()); 13197 } 13198 }; 13199 } 13200 13201 // Check the validity of the provided variable list for the provided clause kind 13202 // \a CKind. In the check process the valid expressions, mappable expression 13203 // components, variables, and user-defined mappers are extracted and used to 13204 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a 13205 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec, 13206 // and \a MapperId are expected to be valid if the clause kind is 'map'. 13207 static void checkMappableExpressionList( 13208 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, 13209 MappableVarListInfo &MVLI, SourceLocation StartLoc, 13210 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId, 13211 ArrayRef<Expr *> UnresolvedMappers, 13212 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 13213 bool IsMapTypeImplicit = false) { 13214 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 13215 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 13216 "Unexpected clause kind with mappable expressions!"); 13217 13218 // If the identifier of user-defined mapper is not specified, it is "default". 13219 // We do not change the actual name in this clause to distinguish whether a 13220 // mapper is specified explicitly, i.e., it is not explicitly specified when 13221 // MapperId.getName() is empty. 13222 if (!MapperId.getName() || MapperId.getName().isEmpty()) { 13223 auto &DeclNames = SemaRef.getASTContext().DeclarationNames; 13224 MapperId.setName(DeclNames.getIdentifier( 13225 &SemaRef.getASTContext().Idents.get("default"))); 13226 } 13227 13228 // Iterators to find the current unresolved mapper expression. 13229 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end(); 13230 bool UpdateUMIt = false; 13231 Expr *UnresolvedMapper = nullptr; 13232 13233 // Keep track of the mappable components and base declarations in this clause. 13234 // Each entry in the list is going to have a list of components associated. We 13235 // record each set of the components so that we can build the clause later on. 13236 // In the end we should have the same amount of declarations and component 13237 // lists. 13238 13239 for (Expr *RE : MVLI.VarList) { 13240 assert(RE && "Null expr in omp to/from/map clause"); 13241 SourceLocation ELoc = RE->getExprLoc(); 13242 13243 // Find the current unresolved mapper expression. 13244 if (UpdateUMIt && UMIt != UMEnd) { 13245 UMIt++; 13246 assert( 13247 UMIt != UMEnd && 13248 "Expect the size of UnresolvedMappers to match with that of VarList"); 13249 } 13250 UpdateUMIt = true; 13251 if (UMIt != UMEnd) 13252 UnresolvedMapper = *UMIt; 13253 13254 const Expr *VE = RE->IgnoreParenLValueCasts(); 13255 13256 if (VE->isValueDependent() || VE->isTypeDependent() || 13257 VE->isInstantiationDependent() || 13258 VE->containsUnexpandedParameterPack()) { 13259 // Try to find the associated user-defined mapper. 13260 ExprResult ER = buildUserDefinedMapperRef( 13261 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 13262 VE->getType().getCanonicalType(), UnresolvedMapper); 13263 if (ER.isInvalid()) 13264 continue; 13265 MVLI.UDMapperList.push_back(ER.get()); 13266 // We can only analyze this information once the missing information is 13267 // resolved. 13268 MVLI.ProcessedVarList.push_back(RE); 13269 continue; 13270 } 13271 13272 Expr *SimpleExpr = RE->IgnoreParenCasts(); 13273 13274 if (!RE->IgnoreParenImpCasts()->isLValue()) { 13275 SemaRef.Diag(ELoc, 13276 diag::err_omp_expected_named_var_member_or_array_expression) 13277 << RE->getSourceRange(); 13278 continue; 13279 } 13280 13281 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 13282 ValueDecl *CurDeclaration = nullptr; 13283 13284 // Obtain the array or member expression bases if required. Also, fill the 13285 // components array with all the components identified in the process. 13286 const Expr *BE = checkMapClauseExpressionBase( 13287 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false); 13288 if (!BE) 13289 continue; 13290 13291 assert(!CurComponents.empty() && 13292 "Invalid mappable expression information."); 13293 13294 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 13295 // Add store "this" pointer to class in DSAStackTy for future checking 13296 DSAS->addMappedClassesQualTypes(TE->getType()); 13297 // Try to find the associated user-defined mapper. 13298 ExprResult ER = buildUserDefinedMapperRef( 13299 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 13300 VE->getType().getCanonicalType(), UnresolvedMapper); 13301 if (ER.isInvalid()) 13302 continue; 13303 MVLI.UDMapperList.push_back(ER.get()); 13304 // Skip restriction checking for variable or field declarations 13305 MVLI.ProcessedVarList.push_back(RE); 13306 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 13307 MVLI.VarComponents.back().append(CurComponents.begin(), 13308 CurComponents.end()); 13309 MVLI.VarBaseDeclarations.push_back(nullptr); 13310 continue; 13311 } 13312 13313 // For the following checks, we rely on the base declaration which is 13314 // expected to be associated with the last component. The declaration is 13315 // expected to be a variable or a field (if 'this' is being mapped). 13316 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 13317 assert(CurDeclaration && "Null decl on map clause."); 13318 assert( 13319 CurDeclaration->isCanonicalDecl() && 13320 "Expecting components to have associated only canonical declarations."); 13321 13322 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 13323 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 13324 13325 assert((VD || FD) && "Only variables or fields are expected here!"); 13326 (void)FD; 13327 13328 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 13329 // threadprivate variables cannot appear in a map clause. 13330 // OpenMP 4.5 [2.10.5, target update Construct] 13331 // threadprivate variables cannot appear in a from clause. 13332 if (VD && DSAS->isThreadPrivate(VD)) { 13333 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 13334 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 13335 << getOpenMPClauseName(CKind); 13336 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 13337 continue; 13338 } 13339 13340 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 13341 // A list item cannot appear in both a map clause and a data-sharing 13342 // attribute clause on the same construct. 13343 13344 // Check conflicts with other map clause expressions. We check the conflicts 13345 // with the current construct separately from the enclosing data 13346 // environment, because the restrictions are different. We only have to 13347 // check conflicts across regions for the map clauses. 13348 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 13349 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 13350 break; 13351 if (CKind == OMPC_map && 13352 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 13353 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 13354 break; 13355 13356 // OpenMP 4.5 [2.10.5, target update Construct] 13357 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 13358 // If the type of a list item is a reference to a type T then the type will 13359 // be considered to be T for all purposes of this clause. 13360 auto I = llvm::find_if( 13361 CurComponents, 13362 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 13363 return MC.getAssociatedDeclaration(); 13364 }); 13365 assert(I != CurComponents.end() && "Null decl on map clause."); 13366 QualType Type = 13367 I->getAssociatedDeclaration()->getType().getNonReferenceType(); 13368 13369 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 13370 // A list item in a to or from clause must have a mappable type. 13371 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 13372 // A list item must have a mappable type. 13373 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 13374 DSAS, Type)) 13375 continue; 13376 13377 if (CKind == OMPC_map) { 13378 // target enter data 13379 // OpenMP [2.10.2, Restrictions, p. 99] 13380 // A map-type must be specified in all map clauses and must be either 13381 // to or alloc. 13382 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 13383 if (DKind == OMPD_target_enter_data && 13384 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 13385 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 13386 << (IsMapTypeImplicit ? 1 : 0) 13387 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 13388 << getOpenMPDirectiveName(DKind); 13389 continue; 13390 } 13391 13392 // target exit_data 13393 // OpenMP [2.10.3, Restrictions, p. 102] 13394 // A map-type must be specified in all map clauses and must be either 13395 // from, release, or delete. 13396 if (DKind == OMPD_target_exit_data && 13397 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 13398 MapType == OMPC_MAP_delete)) { 13399 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 13400 << (IsMapTypeImplicit ? 1 : 0) 13401 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 13402 << getOpenMPDirectiveName(DKind); 13403 continue; 13404 } 13405 13406 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 13407 // A list item cannot appear in both a map clause and a data-sharing 13408 // attribute clause on the same construct 13409 if (VD && isOpenMPTargetExecutionDirective(DKind)) { 13410 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 13411 if (isOpenMPPrivate(DVar.CKind)) { 13412 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 13413 << getOpenMPClauseName(DVar.CKind) 13414 << getOpenMPClauseName(OMPC_map) 13415 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 13416 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 13417 continue; 13418 } 13419 } 13420 } 13421 13422 // Try to find the associated user-defined mapper. 13423 ExprResult ER = buildUserDefinedMapperRef( 13424 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 13425 Type.getCanonicalType(), UnresolvedMapper); 13426 if (ER.isInvalid()) 13427 continue; 13428 MVLI.UDMapperList.push_back(ER.get()); 13429 13430 // Save the current expression. 13431 MVLI.ProcessedVarList.push_back(RE); 13432 13433 // Store the components in the stack so that they can be used to check 13434 // against other clauses later on. 13435 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 13436 /*WhereFoundClauseKind=*/OMPC_map); 13437 13438 // Save the components and declaration to create the clause. For purposes of 13439 // the clause creation, any component list that has has base 'this' uses 13440 // null as base declaration. 13441 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 13442 MVLI.VarComponents.back().append(CurComponents.begin(), 13443 CurComponents.end()); 13444 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 13445 : CurDeclaration); 13446 } 13447 } 13448 13449 OMPClause *Sema::ActOnOpenMPMapClause( 13450 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 13451 ArrayRef<SourceLocation> MapTypeModifiersLoc, 13452 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 13453 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, 13454 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 13455 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 13456 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown, 13457 OMPC_MAP_MODIFIER_unknown, 13458 OMPC_MAP_MODIFIER_unknown}; 13459 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers]; 13460 13461 // Process map-type-modifiers, flag errors for duplicate modifiers. 13462 unsigned Count = 0; 13463 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 13464 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 13465 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) { 13466 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 13467 continue; 13468 } 13469 assert(Count < OMPMapClause::NumberOfModifiers && 13470 "Modifiers exceed the allowed number of map type modifiers"); 13471 Modifiers[Count] = MapTypeModifiers[I]; 13472 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 13473 ++Count; 13474 } 13475 13476 MappableVarListInfo MVLI(VarList); 13477 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc, 13478 MapperIdScopeSpec, MapperId, UnresolvedMappers, 13479 MapType, IsMapTypeImplicit); 13480 13481 // We need to produce a map clause even if we don't have variables so that 13482 // other diagnostics related with non-existing map clauses are accurate. 13483 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList, 13484 MVLI.VarBaseDeclarations, MVLI.VarComponents, 13485 MVLI.UDMapperList, Modifiers, ModifiersLoc, 13486 MapperIdScopeSpec.getWithLocInContext(Context), 13487 MapperId, MapType, IsMapTypeImplicit, MapLoc); 13488 } 13489 13490 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 13491 TypeResult ParsedType) { 13492 assert(ParsedType.isUsable()); 13493 13494 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 13495 if (ReductionType.isNull()) 13496 return QualType(); 13497 13498 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 13499 // A type name in a declare reduction directive cannot be a function type, an 13500 // array type, a reference type, or a type qualified with const, volatile or 13501 // restrict. 13502 if (ReductionType.hasQualifiers()) { 13503 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 13504 return QualType(); 13505 } 13506 13507 if (ReductionType->isFunctionType()) { 13508 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 13509 return QualType(); 13510 } 13511 if (ReductionType->isReferenceType()) { 13512 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 13513 return QualType(); 13514 } 13515 if (ReductionType->isArrayType()) { 13516 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 13517 return QualType(); 13518 } 13519 return ReductionType; 13520 } 13521 13522 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 13523 Scope *S, DeclContext *DC, DeclarationName Name, 13524 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 13525 AccessSpecifier AS, Decl *PrevDeclInScope) { 13526 SmallVector<Decl *, 8> Decls; 13527 Decls.reserve(ReductionTypes.size()); 13528 13529 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 13530 forRedeclarationInCurContext()); 13531 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 13532 // A reduction-identifier may not be re-declared in the current scope for the 13533 // same type or for a type that is compatible according to the base language 13534 // rules. 13535 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 13536 OMPDeclareReductionDecl *PrevDRD = nullptr; 13537 bool InCompoundScope = true; 13538 if (S != nullptr) { 13539 // Find previous declaration with the same name not referenced in other 13540 // declarations. 13541 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 13542 InCompoundScope = 13543 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 13544 LookupName(Lookup, S); 13545 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 13546 /*AllowInlineNamespace=*/false); 13547 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 13548 LookupResult::Filter Filter = Lookup.makeFilter(); 13549 while (Filter.hasNext()) { 13550 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 13551 if (InCompoundScope) { 13552 auto I = UsedAsPrevious.find(PrevDecl); 13553 if (I == UsedAsPrevious.end()) 13554 UsedAsPrevious[PrevDecl] = false; 13555 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 13556 UsedAsPrevious[D] = true; 13557 } 13558 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 13559 PrevDecl->getLocation(); 13560 } 13561 Filter.done(); 13562 if (InCompoundScope) { 13563 for (const auto &PrevData : UsedAsPrevious) { 13564 if (!PrevData.second) { 13565 PrevDRD = PrevData.first; 13566 break; 13567 } 13568 } 13569 } 13570 } else if (PrevDeclInScope != nullptr) { 13571 auto *PrevDRDInScope = PrevDRD = 13572 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 13573 do { 13574 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 13575 PrevDRDInScope->getLocation(); 13576 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 13577 } while (PrevDRDInScope != nullptr); 13578 } 13579 for (const auto &TyData : ReductionTypes) { 13580 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 13581 bool Invalid = false; 13582 if (I != PreviousRedeclTypes.end()) { 13583 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 13584 << TyData.first; 13585 Diag(I->second, diag::note_previous_definition); 13586 Invalid = true; 13587 } 13588 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 13589 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 13590 Name, TyData.first, PrevDRD); 13591 DC->addDecl(DRD); 13592 DRD->setAccess(AS); 13593 Decls.push_back(DRD); 13594 if (Invalid) 13595 DRD->setInvalidDecl(); 13596 else 13597 PrevDRD = DRD; 13598 } 13599 13600 return DeclGroupPtrTy::make( 13601 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 13602 } 13603 13604 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 13605 auto *DRD = cast<OMPDeclareReductionDecl>(D); 13606 13607 // Enter new function scope. 13608 PushFunctionScope(); 13609 setFunctionHasBranchProtectedScope(); 13610 getCurFunction()->setHasOMPDeclareReductionCombiner(); 13611 13612 if (S != nullptr) 13613 PushDeclContext(S, DRD); 13614 else 13615 CurContext = DRD; 13616 13617 PushExpressionEvaluationContext( 13618 ExpressionEvaluationContext::PotentiallyEvaluated); 13619 13620 QualType ReductionType = DRD->getType(); 13621 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 13622 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 13623 // uses semantics of argument handles by value, but it should be passed by 13624 // reference. C lang does not support references, so pass all parameters as 13625 // pointers. 13626 // Create 'T omp_in;' variable. 13627 VarDecl *OmpInParm = 13628 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 13629 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 13630 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 13631 // uses semantics of argument handles by value, but it should be passed by 13632 // reference. C lang does not support references, so pass all parameters as 13633 // pointers. 13634 // Create 'T omp_out;' variable. 13635 VarDecl *OmpOutParm = 13636 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 13637 if (S != nullptr) { 13638 PushOnScopeChains(OmpInParm, S); 13639 PushOnScopeChains(OmpOutParm, S); 13640 } else { 13641 DRD->addDecl(OmpInParm); 13642 DRD->addDecl(OmpOutParm); 13643 } 13644 Expr *InE = 13645 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 13646 Expr *OutE = 13647 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 13648 DRD->setCombinerData(InE, OutE); 13649 } 13650 13651 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 13652 auto *DRD = cast<OMPDeclareReductionDecl>(D); 13653 DiscardCleanupsInEvaluationContext(); 13654 PopExpressionEvaluationContext(); 13655 13656 PopDeclContext(); 13657 PopFunctionScopeInfo(); 13658 13659 if (Combiner != nullptr) 13660 DRD->setCombiner(Combiner); 13661 else 13662 DRD->setInvalidDecl(); 13663 } 13664 13665 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 13666 auto *DRD = cast<OMPDeclareReductionDecl>(D); 13667 13668 // Enter new function scope. 13669 PushFunctionScope(); 13670 setFunctionHasBranchProtectedScope(); 13671 13672 if (S != nullptr) 13673 PushDeclContext(S, DRD); 13674 else 13675 CurContext = DRD; 13676 13677 PushExpressionEvaluationContext( 13678 ExpressionEvaluationContext::PotentiallyEvaluated); 13679 13680 QualType ReductionType = DRD->getType(); 13681 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 13682 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 13683 // uses semantics of argument handles by value, but it should be passed by 13684 // reference. C lang does not support references, so pass all parameters as 13685 // pointers. 13686 // Create 'T omp_priv;' variable. 13687 VarDecl *OmpPrivParm = 13688 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 13689 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 13690 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 13691 // uses semantics of argument handles by value, but it should be passed by 13692 // reference. C lang does not support references, so pass all parameters as 13693 // pointers. 13694 // Create 'T omp_orig;' variable. 13695 VarDecl *OmpOrigParm = 13696 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 13697 if (S != nullptr) { 13698 PushOnScopeChains(OmpPrivParm, S); 13699 PushOnScopeChains(OmpOrigParm, S); 13700 } else { 13701 DRD->addDecl(OmpPrivParm); 13702 DRD->addDecl(OmpOrigParm); 13703 } 13704 Expr *OrigE = 13705 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 13706 Expr *PrivE = 13707 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 13708 DRD->setInitializerData(OrigE, PrivE); 13709 return OmpPrivParm; 13710 } 13711 13712 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 13713 VarDecl *OmpPrivParm) { 13714 auto *DRD = cast<OMPDeclareReductionDecl>(D); 13715 DiscardCleanupsInEvaluationContext(); 13716 PopExpressionEvaluationContext(); 13717 13718 PopDeclContext(); 13719 PopFunctionScopeInfo(); 13720 13721 if (Initializer != nullptr) { 13722 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 13723 } else if (OmpPrivParm->hasInit()) { 13724 DRD->setInitializer(OmpPrivParm->getInit(), 13725 OmpPrivParm->isDirectInit() 13726 ? OMPDeclareReductionDecl::DirectInit 13727 : OMPDeclareReductionDecl::CopyInit); 13728 } else { 13729 DRD->setInvalidDecl(); 13730 } 13731 } 13732 13733 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 13734 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 13735 for (Decl *D : DeclReductions.get()) { 13736 if (IsValid) { 13737 if (S) 13738 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 13739 /*AddToContext=*/false); 13740 } else { 13741 D->setInvalidDecl(); 13742 } 13743 } 13744 return DeclReductions; 13745 } 13746 13747 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 13748 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13749 QualType T = TInfo->getType(); 13750 if (D.isInvalidType()) 13751 return true; 13752 13753 if (getLangOpts().CPlusPlus) { 13754 // Check that there are no default arguments (C++ only). 13755 CheckExtraCXXDefaultArguments(D); 13756 } 13757 13758 return CreateParsedType(T, TInfo); 13759 } 13760 13761 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 13762 TypeResult ParsedType) { 13763 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 13764 13765 QualType MapperType = GetTypeFromParser(ParsedType.get()); 13766 assert(!MapperType.isNull() && "Expect valid mapper type"); 13767 13768 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 13769 // The type must be of struct, union or class type in C and C++ 13770 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 13771 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 13772 return QualType(); 13773 } 13774 return MapperType; 13775 } 13776 13777 OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart( 13778 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 13779 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 13780 Decl *PrevDeclInScope) { 13781 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 13782 forRedeclarationInCurContext()); 13783 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 13784 // A mapper-identifier may not be redeclared in the current scope for the 13785 // same type or for a type that is compatible according to the base language 13786 // rules. 13787 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 13788 OMPDeclareMapperDecl *PrevDMD = nullptr; 13789 bool InCompoundScope = true; 13790 if (S != nullptr) { 13791 // Find previous declaration with the same name not referenced in other 13792 // declarations. 13793 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 13794 InCompoundScope = 13795 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 13796 LookupName(Lookup, S); 13797 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 13798 /*AllowInlineNamespace=*/false); 13799 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 13800 LookupResult::Filter Filter = Lookup.makeFilter(); 13801 while (Filter.hasNext()) { 13802 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 13803 if (InCompoundScope) { 13804 auto I = UsedAsPrevious.find(PrevDecl); 13805 if (I == UsedAsPrevious.end()) 13806 UsedAsPrevious[PrevDecl] = false; 13807 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 13808 UsedAsPrevious[D] = true; 13809 } 13810 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 13811 PrevDecl->getLocation(); 13812 } 13813 Filter.done(); 13814 if (InCompoundScope) { 13815 for (const auto &PrevData : UsedAsPrevious) { 13816 if (!PrevData.second) { 13817 PrevDMD = PrevData.first; 13818 break; 13819 } 13820 } 13821 } 13822 } else if (PrevDeclInScope) { 13823 auto *PrevDMDInScope = PrevDMD = 13824 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 13825 do { 13826 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 13827 PrevDMDInScope->getLocation(); 13828 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 13829 } while (PrevDMDInScope != nullptr); 13830 } 13831 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 13832 bool Invalid = false; 13833 if (I != PreviousRedeclTypes.end()) { 13834 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 13835 << MapperType << Name; 13836 Diag(I->second, diag::note_previous_definition); 13837 Invalid = true; 13838 } 13839 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, 13840 MapperType, VN, PrevDMD); 13841 DC->addDecl(DMD); 13842 DMD->setAccess(AS); 13843 if (Invalid) 13844 DMD->setInvalidDecl(); 13845 13846 // Enter new function scope. 13847 PushFunctionScope(); 13848 setFunctionHasBranchProtectedScope(); 13849 13850 CurContext = DMD; 13851 13852 return DMD; 13853 } 13854 13855 void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, 13856 Scope *S, 13857 QualType MapperType, 13858 SourceLocation StartLoc, 13859 DeclarationName VN) { 13860 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString()); 13861 if (S) 13862 PushOnScopeChains(VD, S); 13863 else 13864 DMD->addDecl(VD); 13865 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 13866 DMD->setMapperVarRef(MapperVarRefExpr); 13867 } 13868 13869 Sema::DeclGroupPtrTy 13870 Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, 13871 ArrayRef<OMPClause *> ClauseList) { 13872 PopDeclContext(); 13873 PopFunctionScopeInfo(); 13874 13875 if (D) { 13876 if (S) 13877 PushOnScopeChains(D, S, /*AddToContext=*/false); 13878 D->CreateClauses(Context, ClauseList); 13879 } 13880 13881 return DeclGroupPtrTy::make(DeclGroupRef(D)); 13882 } 13883 13884 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 13885 SourceLocation StartLoc, 13886 SourceLocation LParenLoc, 13887 SourceLocation EndLoc) { 13888 Expr *ValExpr = NumTeams; 13889 Stmt *HelperValStmt = nullptr; 13890 13891 // OpenMP [teams Constrcut, Restrictions] 13892 // The num_teams expression must evaluate to a positive integer value. 13893 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 13894 /*StrictlyPositive=*/true)) 13895 return nullptr; 13896 13897 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 13898 OpenMPDirectiveKind CaptureRegion = 13899 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 13900 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 13901 ValExpr = MakeFullExpr(ValExpr).get(); 13902 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13903 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13904 HelperValStmt = buildPreInits(Context, Captures); 13905 } 13906 13907 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 13908 StartLoc, LParenLoc, EndLoc); 13909 } 13910 13911 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 13912 SourceLocation StartLoc, 13913 SourceLocation LParenLoc, 13914 SourceLocation EndLoc) { 13915 Expr *ValExpr = ThreadLimit; 13916 Stmt *HelperValStmt = nullptr; 13917 13918 // OpenMP [teams Constrcut, Restrictions] 13919 // The thread_limit expression must evaluate to a positive integer value. 13920 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 13921 /*StrictlyPositive=*/true)) 13922 return nullptr; 13923 13924 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 13925 OpenMPDirectiveKind CaptureRegion = 13926 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 13927 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 13928 ValExpr = MakeFullExpr(ValExpr).get(); 13929 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13930 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13931 HelperValStmt = buildPreInits(Context, Captures); 13932 } 13933 13934 return new (Context) OMPThreadLimitClause( 13935 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 13936 } 13937 13938 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 13939 SourceLocation StartLoc, 13940 SourceLocation LParenLoc, 13941 SourceLocation EndLoc) { 13942 Expr *ValExpr = Priority; 13943 13944 // OpenMP [2.9.1, task Constrcut] 13945 // The priority-value is a non-negative numerical scalar expression. 13946 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 13947 /*StrictlyPositive=*/false)) 13948 return nullptr; 13949 13950 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 13951 } 13952 13953 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 13954 SourceLocation StartLoc, 13955 SourceLocation LParenLoc, 13956 SourceLocation EndLoc) { 13957 Expr *ValExpr = Grainsize; 13958 13959 // OpenMP [2.9.2, taskloop Constrcut] 13960 // The parameter of the grainsize clause must be a positive integer 13961 // expression. 13962 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 13963 /*StrictlyPositive=*/true)) 13964 return nullptr; 13965 13966 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 13967 } 13968 13969 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 13970 SourceLocation StartLoc, 13971 SourceLocation LParenLoc, 13972 SourceLocation EndLoc) { 13973 Expr *ValExpr = NumTasks; 13974 13975 // OpenMP [2.9.2, taskloop Constrcut] 13976 // The parameter of the num_tasks clause must be a positive integer 13977 // expression. 13978 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 13979 /*StrictlyPositive=*/true)) 13980 return nullptr; 13981 13982 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 13983 } 13984 13985 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 13986 SourceLocation LParenLoc, 13987 SourceLocation EndLoc) { 13988 // OpenMP [2.13.2, critical construct, Description] 13989 // ... where hint-expression is an integer constant expression that evaluates 13990 // to a valid lock hint. 13991 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 13992 if (HintExpr.isInvalid()) 13993 return nullptr; 13994 return new (Context) 13995 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 13996 } 13997 13998 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 13999 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 14000 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 14001 SourceLocation EndLoc) { 14002 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 14003 std::string Values; 14004 Values += "'"; 14005 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 14006 Values += "'"; 14007 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 14008 << Values << getOpenMPClauseName(OMPC_dist_schedule); 14009 return nullptr; 14010 } 14011 Expr *ValExpr = ChunkSize; 14012 Stmt *HelperValStmt = nullptr; 14013 if (ChunkSize) { 14014 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 14015 !ChunkSize->isInstantiationDependent() && 14016 !ChunkSize->containsUnexpandedParameterPack()) { 14017 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 14018 ExprResult Val = 14019 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 14020 if (Val.isInvalid()) 14021 return nullptr; 14022 14023 ValExpr = Val.get(); 14024 14025 // OpenMP [2.7.1, Restrictions] 14026 // chunk_size must be a loop invariant integer expression with a positive 14027 // value. 14028 llvm::APSInt Result; 14029 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 14030 if (Result.isSigned() && !Result.isStrictlyPositive()) { 14031 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 14032 << "dist_schedule" << ChunkSize->getSourceRange(); 14033 return nullptr; 14034 } 14035 } else if (getOpenMPCaptureRegionForClause( 14036 DSAStack->getCurrentDirective(), OMPC_dist_schedule) != 14037 OMPD_unknown && 14038 !CurContext->isDependentContext()) { 14039 ValExpr = MakeFullExpr(ValExpr).get(); 14040 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14041 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14042 HelperValStmt = buildPreInits(Context, Captures); 14043 } 14044 } 14045 } 14046 14047 return new (Context) 14048 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 14049 Kind, ValExpr, HelperValStmt); 14050 } 14051 14052 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 14053 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 14054 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 14055 SourceLocation KindLoc, SourceLocation EndLoc) { 14056 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 14057 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 14058 std::string Value; 14059 SourceLocation Loc; 14060 Value += "'"; 14061 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 14062 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 14063 OMPC_DEFAULTMAP_MODIFIER_tofrom); 14064 Loc = MLoc; 14065 } else { 14066 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 14067 OMPC_DEFAULTMAP_scalar); 14068 Loc = KindLoc; 14069 } 14070 Value += "'"; 14071 Diag(Loc, diag::err_omp_unexpected_clause_value) 14072 << Value << getOpenMPClauseName(OMPC_defaultmap); 14073 return nullptr; 14074 } 14075 DSAStack->setDefaultDMAToFromScalar(StartLoc); 14076 14077 return new (Context) 14078 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 14079 } 14080 14081 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 14082 DeclContext *CurLexicalContext = getCurLexicalContext(); 14083 if (!CurLexicalContext->isFileContext() && 14084 !CurLexicalContext->isExternCContext() && 14085 !CurLexicalContext->isExternCXXContext() && 14086 !isa<CXXRecordDecl>(CurLexicalContext) && 14087 !isa<ClassTemplateDecl>(CurLexicalContext) && 14088 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 14089 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 14090 Diag(Loc, diag::err_omp_region_not_file_context); 14091 return false; 14092 } 14093 ++DeclareTargetNestingLevel; 14094 return true; 14095 } 14096 14097 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 14098 assert(DeclareTargetNestingLevel > 0 && 14099 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 14100 --DeclareTargetNestingLevel; 14101 } 14102 14103 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 14104 CXXScopeSpec &ScopeSpec, 14105 const DeclarationNameInfo &Id, 14106 OMPDeclareTargetDeclAttr::MapTypeTy MT, 14107 NamedDeclSetType &SameDirectiveDecls) { 14108 LookupResult Lookup(*this, Id, LookupOrdinaryName); 14109 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 14110 14111 if (Lookup.isAmbiguous()) 14112 return; 14113 Lookup.suppressDiagnostics(); 14114 14115 if (!Lookup.isSingleResult()) { 14116 if (TypoCorrection Corrected = 14117 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 14118 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 14119 CTK_ErrorRecovery)) { 14120 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 14121 << Id.getName()); 14122 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 14123 return; 14124 } 14125 14126 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 14127 return; 14128 } 14129 14130 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 14131 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 14132 isa<FunctionTemplateDecl>(ND)) { 14133 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 14134 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 14135 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 14136 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 14137 cast<ValueDecl>(ND)); 14138 if (!Res) { 14139 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 14140 ND->addAttr(A); 14141 if (ASTMutationListener *ML = Context.getASTMutationListener()) 14142 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 14143 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc()); 14144 } else if (*Res != MT) { 14145 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 14146 << Id.getName(); 14147 } 14148 } else { 14149 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 14150 } 14151 } 14152 14153 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 14154 Sema &SemaRef, Decl *D) { 14155 if (!D || !isa<VarDecl>(D)) 14156 return; 14157 auto *VD = cast<VarDecl>(D); 14158 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 14159 return; 14160 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 14161 SemaRef.Diag(SL, diag::note_used_here) << SR; 14162 } 14163 14164 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 14165 Sema &SemaRef, DSAStackTy *Stack, 14166 ValueDecl *VD) { 14167 return VD->hasAttr<OMPDeclareTargetDeclAttr>() || 14168 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 14169 /*FullCheck=*/false); 14170 } 14171 14172 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 14173 SourceLocation IdLoc) { 14174 if (!D || D->isInvalidDecl()) 14175 return; 14176 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 14177 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 14178 if (auto *VD = dyn_cast<VarDecl>(D)) { 14179 // Only global variables can be marked as declare target. 14180 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 14181 !VD->isStaticDataMember()) 14182 return; 14183 // 2.10.6: threadprivate variable cannot appear in a declare target 14184 // directive. 14185 if (DSAStack->isThreadPrivate(VD)) { 14186 Diag(SL, diag::err_omp_threadprivate_in_target); 14187 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 14188 return; 14189 } 14190 } 14191 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 14192 D = FTD->getTemplatedDecl(); 14193 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 14194 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 14195 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 14196 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 14197 assert(IdLoc.isValid() && "Source location is expected"); 14198 Diag(IdLoc, diag::err_omp_function_in_link_clause); 14199 Diag(FD->getLocation(), diag::note_defined_here) << FD; 14200 return; 14201 } 14202 } 14203 if (auto *VD = dyn_cast<ValueDecl>(D)) { 14204 // Problem if any with var declared with incomplete type will be reported 14205 // as normal, so no need to check it here. 14206 if ((E || !VD->getType()->isIncompleteType()) && 14207 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 14208 return; 14209 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 14210 // Checking declaration inside declare target region. 14211 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 14212 isa<FunctionTemplateDecl>(D)) { 14213 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 14214 Context, OMPDeclareTargetDeclAttr::MT_To); 14215 D->addAttr(A); 14216 if (ASTMutationListener *ML = Context.getASTMutationListener()) 14217 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 14218 } 14219 return; 14220 } 14221 } 14222 if (!E) 14223 return; 14224 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 14225 } 14226 14227 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 14228 CXXScopeSpec &MapperIdScopeSpec, 14229 DeclarationNameInfo &MapperId, 14230 const OMPVarListLocTy &Locs, 14231 ArrayRef<Expr *> UnresolvedMappers) { 14232 MappableVarListInfo MVLI(VarList); 14233 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc, 14234 MapperIdScopeSpec, MapperId, UnresolvedMappers); 14235 if (MVLI.ProcessedVarList.empty()) 14236 return nullptr; 14237 14238 return OMPToClause::Create( 14239 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 14240 MVLI.VarComponents, MVLI.UDMapperList, 14241 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 14242 } 14243 14244 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 14245 CXXScopeSpec &MapperIdScopeSpec, 14246 DeclarationNameInfo &MapperId, 14247 const OMPVarListLocTy &Locs, 14248 ArrayRef<Expr *> UnresolvedMappers) { 14249 MappableVarListInfo MVLI(VarList); 14250 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc, 14251 MapperIdScopeSpec, MapperId, UnresolvedMappers); 14252 if (MVLI.ProcessedVarList.empty()) 14253 return nullptr; 14254 14255 return OMPFromClause::Create( 14256 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 14257 MVLI.VarComponents, MVLI.UDMapperList, 14258 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 14259 } 14260 14261 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 14262 const OMPVarListLocTy &Locs) { 14263 MappableVarListInfo MVLI(VarList); 14264 SmallVector<Expr *, 8> PrivateCopies; 14265 SmallVector<Expr *, 8> Inits; 14266 14267 for (Expr *RefExpr : VarList) { 14268 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 14269 SourceLocation ELoc; 14270 SourceRange ERange; 14271 Expr *SimpleRefExpr = RefExpr; 14272 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 14273 if (Res.second) { 14274 // It will be analyzed later. 14275 MVLI.ProcessedVarList.push_back(RefExpr); 14276 PrivateCopies.push_back(nullptr); 14277 Inits.push_back(nullptr); 14278 } 14279 ValueDecl *D = Res.first; 14280 if (!D) 14281 continue; 14282 14283 QualType Type = D->getType(); 14284 Type = Type.getNonReferenceType().getUnqualifiedType(); 14285 14286 auto *VD = dyn_cast<VarDecl>(D); 14287 14288 // Item should be a pointer or reference to pointer. 14289 if (!Type->isPointerType()) { 14290 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 14291 << 0 << RefExpr->getSourceRange(); 14292 continue; 14293 } 14294 14295 // Build the private variable and the expression that refers to it. 14296 auto VDPrivate = 14297 buildVarDecl(*this, ELoc, Type, D->getName(), 14298 D->hasAttrs() ? &D->getAttrs() : nullptr, 14299 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 14300 if (VDPrivate->isInvalidDecl()) 14301 continue; 14302 14303 CurContext->addDecl(VDPrivate); 14304 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 14305 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 14306 14307 // Add temporary variable to initialize the private copy of the pointer. 14308 VarDecl *VDInit = 14309 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 14310 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 14311 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 14312 AddInitializerToDecl(VDPrivate, 14313 DefaultLvalueConversion(VDInitRefExpr).get(), 14314 /*DirectInit=*/false); 14315 14316 // If required, build a capture to implement the privatization initialized 14317 // with the current list item value. 14318 DeclRefExpr *Ref = nullptr; 14319 if (!VD) 14320 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 14321 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 14322 PrivateCopies.push_back(VDPrivateRefExpr); 14323 Inits.push_back(VDInitRefExpr); 14324 14325 // We need to add a data sharing attribute for this variable to make sure it 14326 // is correctly captured. A variable that shows up in a use_device_ptr has 14327 // similar properties of a first private variable. 14328 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 14329 14330 // Create a mappable component for the list item. List items in this clause 14331 // only need a component. 14332 MVLI.VarBaseDeclarations.push_back(D); 14333 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 14334 MVLI.VarComponents.back().push_back( 14335 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 14336 } 14337 14338 if (MVLI.ProcessedVarList.empty()) 14339 return nullptr; 14340 14341 return OMPUseDevicePtrClause::Create( 14342 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits, 14343 MVLI.VarBaseDeclarations, MVLI.VarComponents); 14344 } 14345 14346 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 14347 const OMPVarListLocTy &Locs) { 14348 MappableVarListInfo MVLI(VarList); 14349 for (Expr *RefExpr : VarList) { 14350 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 14351 SourceLocation ELoc; 14352 SourceRange ERange; 14353 Expr *SimpleRefExpr = RefExpr; 14354 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 14355 if (Res.second) { 14356 // It will be analyzed later. 14357 MVLI.ProcessedVarList.push_back(RefExpr); 14358 } 14359 ValueDecl *D = Res.first; 14360 if (!D) 14361 continue; 14362 14363 QualType Type = D->getType(); 14364 // item should be a pointer or array or reference to pointer or array 14365 if (!Type.getNonReferenceType()->isPointerType() && 14366 !Type.getNonReferenceType()->isArrayType()) { 14367 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 14368 << 0 << RefExpr->getSourceRange(); 14369 continue; 14370 } 14371 14372 // Check if the declaration in the clause does not show up in any data 14373 // sharing attribute. 14374 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 14375 if (isOpenMPPrivate(DVar.CKind)) { 14376 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 14377 << getOpenMPClauseName(DVar.CKind) 14378 << getOpenMPClauseName(OMPC_is_device_ptr) 14379 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 14380 reportOriginalDsa(*this, DSAStack, D, DVar); 14381 continue; 14382 } 14383 14384 const Expr *ConflictExpr; 14385 if (DSAStack->checkMappableExprComponentListsForDecl( 14386 D, /*CurrentRegionOnly=*/true, 14387 [&ConflictExpr]( 14388 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 14389 OpenMPClauseKind) -> bool { 14390 ConflictExpr = R.front().getAssociatedExpression(); 14391 return true; 14392 })) { 14393 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 14394 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 14395 << ConflictExpr->getSourceRange(); 14396 continue; 14397 } 14398 14399 // Store the components in the stack so that they can be used to check 14400 // against other clauses later on. 14401 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 14402 DSAStack->addMappableExpressionComponents( 14403 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 14404 14405 // Record the expression we've just processed. 14406 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 14407 14408 // Create a mappable component for the list item. List items in this clause 14409 // only need a component. We use a null declaration to signal fields in 14410 // 'this'. 14411 assert((isa<DeclRefExpr>(SimpleRefExpr) || 14412 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 14413 "Unexpected device pointer expression!"); 14414 MVLI.VarBaseDeclarations.push_back( 14415 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 14416 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 14417 MVLI.VarComponents.back().push_back(MC); 14418 } 14419 14420 if (MVLI.ProcessedVarList.empty()) 14421 return nullptr; 14422 14423 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList, 14424 MVLI.VarBaseDeclarations, 14425 MVLI.VarComponents); 14426 } 14427