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/OpenMPClause.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeOrdering.h" 26 #include "clang/Basic/DiagnosticSema.h" 27 #include "clang/Basic/OpenMPKinds.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Sema/Initialization.h" 31 #include "clang/Sema/Lookup.h" 32 #include "clang/Sema/Scope.h" 33 #include "clang/Sema/ScopeInfo.h" 34 #include "clang/Sema/SemaInternal.h" 35 #include "llvm/ADT/IndexedMap.h" 36 #include "llvm/ADT/PointerEmbeddedInt.h" 37 #include "llvm/ADT/STLExtras.h" 38 #include "llvm/ADT/StringExtras.h" 39 #include "llvm/Frontend/OpenMP/OMPConstants.h" 40 #include <set> 41 42 using namespace clang; 43 using namespace llvm::omp; 44 45 //===----------------------------------------------------------------------===// 46 // Stack of data-sharing attributes for variables 47 //===----------------------------------------------------------------------===// 48 49 static const Expr *checkMapClauseExpressionBase( 50 Sema &SemaRef, Expr *E, 51 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 52 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose); 53 54 namespace { 55 /// Default data sharing attributes, which can be applied to directive. 56 enum DefaultDataSharingAttributes { 57 DSA_unspecified = 0, /// Data sharing attribute not specified. 58 DSA_none = 1 << 0, /// Default data sharing attribute 'none'. 59 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'. 60 DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'. 61 }; 62 63 /// Stack for tracking declarations used in OpenMP directives and 64 /// clauses and their data-sharing attributes. 65 class DSAStackTy { 66 public: 67 struct DSAVarData { 68 OpenMPDirectiveKind DKind = OMPD_unknown; 69 OpenMPClauseKind CKind = OMPC_unknown; 70 unsigned Modifier = 0; 71 const Expr *RefExpr = nullptr; 72 DeclRefExpr *PrivateCopy = nullptr; 73 SourceLocation ImplicitDSALoc; 74 bool AppliedToPointee = false; 75 DSAVarData() = default; 76 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 77 const Expr *RefExpr, DeclRefExpr *PrivateCopy, 78 SourceLocation ImplicitDSALoc, unsigned Modifier, 79 bool AppliedToPointee) 80 : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr), 81 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc), 82 AppliedToPointee(AppliedToPointee) {} 83 }; 84 using OperatorOffsetTy = 85 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>; 86 using DoacrossDependMapTy = 87 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>; 88 /// Kind of the declaration used in the uses_allocators clauses. 89 enum class UsesAllocatorsDeclKind { 90 /// Predefined allocator 91 PredefinedAllocator, 92 /// User-defined allocator 93 UserDefinedAllocator, 94 /// The declaration that represent allocator trait 95 AllocatorTrait, 96 }; 97 98 private: 99 struct DSAInfo { 100 OpenMPClauseKind Attributes = OMPC_unknown; 101 unsigned Modifier = 0; 102 /// Pointer to a reference expression and a flag which shows that the 103 /// variable is marked as lastprivate(true) or not (false). 104 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr; 105 DeclRefExpr *PrivateCopy = nullptr; 106 /// true if the attribute is applied to the pointee, not the variable 107 /// itself. 108 bool AppliedToPointee = false; 109 }; 110 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>; 111 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>; 112 using LCDeclInfo = std::pair<unsigned, VarDecl *>; 113 using LoopControlVariablesMapTy = 114 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>; 115 /// Struct that associates a component with the clause kind where they are 116 /// found. 117 struct MappedExprComponentTy { 118 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 119 OpenMPClauseKind Kind = OMPC_unknown; 120 }; 121 using MappedExprComponentsTy = 122 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>; 123 using CriticalsWithHintsTy = 124 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>; 125 struct ReductionData { 126 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>; 127 SourceRange ReductionRange; 128 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 129 ReductionData() = default; 130 void set(BinaryOperatorKind BO, SourceRange RR) { 131 ReductionRange = RR; 132 ReductionOp = BO; 133 } 134 void set(const Expr *RefExpr, SourceRange RR) { 135 ReductionRange = RR; 136 ReductionOp = RefExpr; 137 } 138 }; 139 using DeclReductionMapTy = 140 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>; 141 struct DefaultmapInfo { 142 OpenMPDefaultmapClauseModifier ImplicitBehavior = 143 OMPC_DEFAULTMAP_MODIFIER_unknown; 144 SourceLocation SLoc; 145 DefaultmapInfo() = default; 146 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc) 147 : ImplicitBehavior(M), SLoc(Loc) {} 148 }; 149 150 struct SharingMapTy { 151 DeclSAMapTy SharingMap; 152 DeclReductionMapTy ReductionMap; 153 UsedRefMapTy AlignedMap; 154 UsedRefMapTy NontemporalMap; 155 MappedExprComponentsTy MappedExprComponents; 156 LoopControlVariablesMapTy LCVMap; 157 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 158 SourceLocation DefaultAttrLoc; 159 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown]; 160 OpenMPDirectiveKind Directive = OMPD_unknown; 161 DeclarationNameInfo DirectiveName; 162 Scope *CurScope = nullptr; 163 DeclContext *Context = nullptr; 164 SourceLocation ConstructLoc; 165 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 166 /// get the data (loop counters etc.) about enclosing loop-based construct. 167 /// This data is required during codegen. 168 DoacrossDependMapTy DoacrossDepends; 169 /// First argument (Expr *) contains optional argument of the 170 /// 'ordered' clause, the second one is true if the regions has 'ordered' 171 /// clause, false otherwise. 172 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; 173 unsigned AssociatedLoops = 1; 174 bool HasMutipleLoops = false; 175 const Decl *PossiblyLoopCounter = nullptr; 176 bool NowaitRegion = false; 177 bool CancelRegion = false; 178 bool LoopStart = false; 179 bool BodyComplete = false; 180 SourceLocation PrevScanLocation; 181 SourceLocation PrevOrderedLocation; 182 SourceLocation InnerTeamsRegionLoc; 183 /// Reference to the taskgroup task_reduction reference expression. 184 Expr *TaskgroupReductionRef = nullptr; 185 llvm::DenseSet<QualType> MappedClassesQualTypes; 186 SmallVector<Expr *, 4> InnerUsedAllocators; 187 llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates; 188 /// List of globals marked as declare target link in this target region 189 /// (isOpenMPTargetExecutionDirective(Directive) == true). 190 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls; 191 /// List of decls used in inclusive/exclusive clauses of the scan directive. 192 llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective; 193 llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind> 194 UsesAllocatorsDecls; 195 Expr *DeclareMapperVar = nullptr; 196 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 197 Scope *CurScope, SourceLocation Loc) 198 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 199 ConstructLoc(Loc) {} 200 SharingMapTy() = default; 201 }; 202 203 using StackTy = SmallVector<SharingMapTy, 4>; 204 205 /// Stack of used declaration and their data-sharing attributes. 206 DeclSAMapTy Threadprivates; 207 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 208 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 209 /// true, if check for DSA must be from parent directive, false, if 210 /// from current directive. 211 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 212 Sema &SemaRef; 213 bool ForceCapturing = false; 214 /// true if all the variables in the target executable directives must be 215 /// captured by reference. 216 bool ForceCaptureByReferenceInTargetExecutable = false; 217 CriticalsWithHintsTy Criticals; 218 unsigned IgnoredStackElements = 0; 219 220 /// Iterators over the stack iterate in order from innermost to outermost 221 /// directive. 222 using const_iterator = StackTy::const_reverse_iterator; 223 const_iterator begin() const { 224 return Stack.empty() ? const_iterator() 225 : Stack.back().first.rbegin() + IgnoredStackElements; 226 } 227 const_iterator end() const { 228 return Stack.empty() ? const_iterator() : Stack.back().first.rend(); 229 } 230 using iterator = StackTy::reverse_iterator; 231 iterator begin() { 232 return Stack.empty() ? iterator() 233 : Stack.back().first.rbegin() + IgnoredStackElements; 234 } 235 iterator end() { 236 return Stack.empty() ? iterator() : Stack.back().first.rend(); 237 } 238 239 // Convenience operations to get at the elements of the stack. 240 241 bool isStackEmpty() const { 242 return Stack.empty() || 243 Stack.back().second != CurrentNonCapturingFunctionScope || 244 Stack.back().first.size() <= IgnoredStackElements; 245 } 246 size_t getStackSize() const { 247 return isStackEmpty() ? 0 248 : Stack.back().first.size() - IgnoredStackElements; 249 } 250 251 SharingMapTy *getTopOfStackOrNull() { 252 size_t Size = getStackSize(); 253 if (Size == 0) 254 return nullptr; 255 return &Stack.back().first[Size - 1]; 256 } 257 const SharingMapTy *getTopOfStackOrNull() const { 258 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull(); 259 } 260 SharingMapTy &getTopOfStack() { 261 assert(!isStackEmpty() && "no current directive"); 262 return *getTopOfStackOrNull(); 263 } 264 const SharingMapTy &getTopOfStack() const { 265 return const_cast<DSAStackTy&>(*this).getTopOfStack(); 266 } 267 268 SharingMapTy *getSecondOnStackOrNull() { 269 size_t Size = getStackSize(); 270 if (Size <= 1) 271 return nullptr; 272 return &Stack.back().first[Size - 2]; 273 } 274 const SharingMapTy *getSecondOnStackOrNull() const { 275 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull(); 276 } 277 278 /// Get the stack element at a certain level (previously returned by 279 /// \c getNestingLevel). 280 /// 281 /// Note that nesting levels count from outermost to innermost, and this is 282 /// the reverse of our iteration order where new inner levels are pushed at 283 /// the front of the stack. 284 SharingMapTy &getStackElemAtLevel(unsigned Level) { 285 assert(Level < getStackSize() && "no such stack element"); 286 return Stack.back().first[Level]; 287 } 288 const SharingMapTy &getStackElemAtLevel(unsigned Level) const { 289 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level); 290 } 291 292 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const; 293 294 /// Checks if the variable is a local for OpenMP region. 295 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const; 296 297 /// Vector of previously declared requires directives 298 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 299 /// omp_allocator_handle_t type. 300 QualType OMPAllocatorHandleT; 301 /// omp_depend_t type. 302 QualType OMPDependT; 303 /// omp_event_handle_t type. 304 QualType OMPEventHandleT; 305 /// omp_alloctrait_t type. 306 QualType OMPAlloctraitT; 307 /// Expression for the predefined allocators. 308 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = { 309 nullptr}; 310 /// Vector of previously encountered target directives 311 SmallVector<SourceLocation, 2> TargetLocations; 312 SourceLocation AtomicLocation; 313 314 public: 315 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 316 317 /// Sets omp_allocator_handle_t type. 318 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; } 319 /// Gets omp_allocator_handle_t type. 320 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; } 321 /// Sets omp_alloctrait_t type. 322 void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; } 323 /// Gets omp_alloctrait_t type. 324 QualType getOMPAlloctraitT() const { return OMPAlloctraitT; } 325 /// Sets the given default allocator. 326 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 327 Expr *Allocator) { 328 OMPPredefinedAllocators[AllocatorKind] = Allocator; 329 } 330 /// Returns the specified default allocator. 331 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const { 332 return OMPPredefinedAllocators[AllocatorKind]; 333 } 334 /// Sets omp_depend_t type. 335 void setOMPDependT(QualType Ty) { OMPDependT = Ty; } 336 /// Gets omp_depend_t type. 337 QualType getOMPDependT() const { return OMPDependT; } 338 339 /// Sets omp_event_handle_t type. 340 void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; } 341 /// Gets omp_event_handle_t type. 342 QualType getOMPEventHandleT() const { return OMPEventHandleT; } 343 344 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 345 OpenMPClauseKind getClauseParsingMode() const { 346 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 347 return ClauseKindMode; 348 } 349 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 350 351 bool isBodyComplete() const { 352 const SharingMapTy *Top = getTopOfStackOrNull(); 353 return Top && Top->BodyComplete; 354 } 355 void setBodyComplete() { 356 getTopOfStack().BodyComplete = true; 357 } 358 359 bool isForceVarCapturing() const { return ForceCapturing; } 360 void setForceVarCapturing(bool V) { ForceCapturing = V; } 361 362 void setForceCaptureByReferenceInTargetExecutable(bool V) { 363 ForceCaptureByReferenceInTargetExecutable = V; 364 } 365 bool isForceCaptureByReferenceInTargetExecutable() const { 366 return ForceCaptureByReferenceInTargetExecutable; 367 } 368 369 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 370 Scope *CurScope, SourceLocation Loc) { 371 assert(!IgnoredStackElements && 372 "cannot change stack while ignoring elements"); 373 if (Stack.empty() || 374 Stack.back().second != CurrentNonCapturingFunctionScope) 375 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 376 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 377 Stack.back().first.back().DefaultAttrLoc = Loc; 378 } 379 380 void pop() { 381 assert(!IgnoredStackElements && 382 "cannot change stack while ignoring elements"); 383 assert(!Stack.back().first.empty() && 384 "Data-sharing attributes stack is empty!"); 385 Stack.back().first.pop_back(); 386 } 387 388 /// RAII object to temporarily leave the scope of a directive when we want to 389 /// logically operate in its parent. 390 class ParentDirectiveScope { 391 DSAStackTy &Self; 392 bool Active; 393 public: 394 ParentDirectiveScope(DSAStackTy &Self, bool Activate) 395 : Self(Self), Active(false) { 396 if (Activate) 397 enable(); 398 } 399 ~ParentDirectiveScope() { disable(); } 400 void disable() { 401 if (Active) { 402 --Self.IgnoredStackElements; 403 Active = false; 404 } 405 } 406 void enable() { 407 if (!Active) { 408 ++Self.IgnoredStackElements; 409 Active = true; 410 } 411 } 412 }; 413 414 /// Marks that we're started loop parsing. 415 void loopInit() { 416 assert(isOpenMPLoopDirective(getCurrentDirective()) && 417 "Expected loop-based directive."); 418 getTopOfStack().LoopStart = true; 419 } 420 /// Start capturing of the variables in the loop context. 421 void loopStart() { 422 assert(isOpenMPLoopDirective(getCurrentDirective()) && 423 "Expected loop-based directive."); 424 getTopOfStack().LoopStart = false; 425 } 426 /// true, if variables are captured, false otherwise. 427 bool isLoopStarted() const { 428 assert(isOpenMPLoopDirective(getCurrentDirective()) && 429 "Expected loop-based directive."); 430 return !getTopOfStack().LoopStart; 431 } 432 /// Marks (or clears) declaration as possibly loop counter. 433 void resetPossibleLoopCounter(const Decl *D = nullptr) { 434 getTopOfStack().PossiblyLoopCounter = 435 D ? D->getCanonicalDecl() : D; 436 } 437 /// Gets the possible loop counter decl. 438 const Decl *getPossiblyLoopCunter() const { 439 return getTopOfStack().PossiblyLoopCounter; 440 } 441 /// Start new OpenMP region stack in new non-capturing function. 442 void pushFunction() { 443 assert(!IgnoredStackElements && 444 "cannot change stack while ignoring elements"); 445 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 446 assert(!isa<CapturingScopeInfo>(CurFnScope)); 447 CurrentNonCapturingFunctionScope = CurFnScope; 448 } 449 /// Pop region stack for non-capturing function. 450 void popFunction(const FunctionScopeInfo *OldFSI) { 451 assert(!IgnoredStackElements && 452 "cannot change stack while ignoring elements"); 453 if (!Stack.empty() && Stack.back().second == OldFSI) { 454 assert(Stack.back().first.empty()); 455 Stack.pop_back(); 456 } 457 CurrentNonCapturingFunctionScope = nullptr; 458 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 459 if (!isa<CapturingScopeInfo>(FSI)) { 460 CurrentNonCapturingFunctionScope = FSI; 461 break; 462 } 463 } 464 } 465 466 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) { 467 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint); 468 } 469 const std::pair<const OMPCriticalDirective *, llvm::APSInt> 470 getCriticalWithHint(const DeclarationNameInfo &Name) const { 471 auto I = Criticals.find(Name.getAsString()); 472 if (I != Criticals.end()) 473 return I->second; 474 return std::make_pair(nullptr, llvm::APSInt()); 475 } 476 /// If 'aligned' declaration for given variable \a D was not seen yet, 477 /// add it and return NULL; otherwise return previous occurrence's expression 478 /// for diagnostics. 479 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE); 480 /// If 'nontemporal' declaration for given variable \a D was not seen yet, 481 /// add it and return NULL; otherwise return previous occurrence's expression 482 /// for diagnostics. 483 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE); 484 485 /// Register specified variable as loop control variable. 486 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture); 487 /// Check if the specified variable is a loop control variable for 488 /// current region. 489 /// \return The index of the loop control variable in the list of associated 490 /// for-loops (from outer to inner). 491 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const; 492 /// Check if the specified variable is a loop control variable for 493 /// parent region. 494 /// \return The index of the loop control variable in the list of associated 495 /// for-loops (from outer to inner). 496 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const; 497 /// Check if the specified variable is a loop control variable for 498 /// current region. 499 /// \return The index of the loop control variable in the list of associated 500 /// for-loops (from outer to inner). 501 const LCDeclInfo isLoopControlVariable(const ValueDecl *D, 502 unsigned Level) const; 503 /// Get the loop control variable for the I-th loop (or nullptr) in 504 /// parent directive. 505 const ValueDecl *getParentLoopControlVariable(unsigned I) const; 506 507 /// Marks the specified decl \p D as used in scan directive. 508 void markDeclAsUsedInScanDirective(ValueDecl *D) { 509 if (SharingMapTy *Stack = getSecondOnStackOrNull()) 510 Stack->UsedInScanDirective.insert(D); 511 } 512 513 /// Checks if the specified declaration was used in the inner scan directive. 514 bool isUsedInScanDirective(ValueDecl *D) const { 515 if (const SharingMapTy *Stack = getTopOfStackOrNull()) 516 return Stack->UsedInScanDirective.count(D) > 0; 517 return false; 518 } 519 520 /// Adds explicit data sharing attribute to the specified declaration. 521 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 522 DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0, 523 bool AppliedToPointee = false); 524 525 /// Adds additional information for the reduction items with the reduction id 526 /// represented as an operator. 527 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 528 BinaryOperatorKind BOK); 529 /// Adds additional information for the reduction items with the reduction id 530 /// represented as reduction identifier. 531 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 532 const Expr *ReductionRef); 533 /// Returns the location and reduction operation from the innermost parent 534 /// region for the given \p D. 535 const DSAVarData 536 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 537 BinaryOperatorKind &BOK, 538 Expr *&TaskgroupDescriptor) const; 539 /// Returns the location and reduction operation from the innermost parent 540 /// region for the given \p D. 541 const DSAVarData 542 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 543 const Expr *&ReductionRef, 544 Expr *&TaskgroupDescriptor) const; 545 /// Return reduction reference expression for the current taskgroup or 546 /// parallel/worksharing directives with task reductions. 547 Expr *getTaskgroupReductionRef() const { 548 assert((getTopOfStack().Directive == OMPD_taskgroup || 549 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 550 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 551 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 552 "taskgroup reference expression requested for non taskgroup or " 553 "parallel/worksharing directive."); 554 return getTopOfStack().TaskgroupReductionRef; 555 } 556 /// Checks if the given \p VD declaration is actually a taskgroup reduction 557 /// descriptor variable at the \p Level of OpenMP regions. 558 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const { 559 return getStackElemAtLevel(Level).TaskgroupReductionRef && 560 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef) 561 ->getDecl() == VD; 562 } 563 564 /// Returns data sharing attributes from top of the stack for the 565 /// specified declaration. 566 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 567 /// Returns data-sharing attributes for the specified declaration. 568 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const; 569 /// Returns data-sharing attributes for the specified declaration. 570 const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const; 571 /// Checks if the specified variables has data-sharing attributes which 572 /// match specified \a CPred predicate in any directive which matches \a DPred 573 /// predicate. 574 const DSAVarData 575 hasDSA(ValueDecl *D, 576 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 577 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 578 bool FromParent) const; 579 /// Checks if the specified variables has data-sharing attributes which 580 /// match specified \a CPred predicate in any innermost directive which 581 /// matches \a DPred predicate. 582 const DSAVarData 583 hasInnermostDSA(ValueDecl *D, 584 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 585 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 586 bool FromParent) const; 587 /// Checks if the specified variables has explicit data-sharing 588 /// attributes which match specified \a CPred predicate at the specified 589 /// OpenMP region. 590 bool 591 hasExplicitDSA(const ValueDecl *D, 592 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 593 unsigned Level, bool NotLastprivate = false) const; 594 595 /// Returns true if the directive at level \Level matches in the 596 /// specified \a DPred predicate. 597 bool hasExplicitDirective( 598 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 599 unsigned Level) const; 600 601 /// Finds a directive which matches specified \a DPred predicate. 602 bool hasDirective( 603 const llvm::function_ref<bool( 604 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> 605 DPred, 606 bool FromParent) const; 607 608 /// Returns currently analyzed directive. 609 OpenMPDirectiveKind getCurrentDirective() const { 610 const SharingMapTy *Top = getTopOfStackOrNull(); 611 return Top ? Top->Directive : OMPD_unknown; 612 } 613 /// Returns directive kind at specified level. 614 OpenMPDirectiveKind getDirective(unsigned Level) const { 615 assert(!isStackEmpty() && "No directive at specified level."); 616 return getStackElemAtLevel(Level).Directive; 617 } 618 /// Returns the capture region at the specified level. 619 OpenMPDirectiveKind getCaptureRegion(unsigned Level, 620 unsigned OpenMPCaptureLevel) const { 621 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 622 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level)); 623 return CaptureRegions[OpenMPCaptureLevel]; 624 } 625 /// Returns parent directive. 626 OpenMPDirectiveKind getParentDirective() const { 627 const SharingMapTy *Parent = getSecondOnStackOrNull(); 628 return Parent ? Parent->Directive : OMPD_unknown; 629 } 630 631 /// Add requires decl to internal vector 632 void addRequiresDecl(OMPRequiresDecl *RD) { 633 RequiresDecls.push_back(RD); 634 } 635 636 /// Checks if the defined 'requires' directive has specified type of clause. 637 template <typename ClauseType> 638 bool hasRequiresDeclWithClause() const { 639 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) { 640 return llvm::any_of(D->clauselists(), [](const OMPClause *C) { 641 return isa<ClauseType>(C); 642 }); 643 }); 644 } 645 646 /// Checks for a duplicate clause amongst previously declared requires 647 /// directives 648 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 649 bool IsDuplicate = false; 650 for (OMPClause *CNew : ClauseList) { 651 for (const OMPRequiresDecl *D : RequiresDecls) { 652 for (const OMPClause *CPrev : D->clauselists()) { 653 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 654 SemaRef.Diag(CNew->getBeginLoc(), 655 diag::err_omp_requires_clause_redeclaration) 656 << getOpenMPClauseName(CNew->getClauseKind()); 657 SemaRef.Diag(CPrev->getBeginLoc(), 658 diag::note_omp_requires_previous_clause) 659 << getOpenMPClauseName(CPrev->getClauseKind()); 660 IsDuplicate = true; 661 } 662 } 663 } 664 } 665 return IsDuplicate; 666 } 667 668 /// Add location of previously encountered target to internal vector 669 void addTargetDirLocation(SourceLocation LocStart) { 670 TargetLocations.push_back(LocStart); 671 } 672 673 /// Add location for the first encountered atomicc directive. 674 void addAtomicDirectiveLoc(SourceLocation Loc) { 675 if (AtomicLocation.isInvalid()) 676 AtomicLocation = Loc; 677 } 678 679 /// Returns the location of the first encountered atomic directive in the 680 /// module. 681 SourceLocation getAtomicDirectiveLoc() const { 682 return AtomicLocation; 683 } 684 685 // Return previously encountered target region locations. 686 ArrayRef<SourceLocation> getEncounteredTargetLocs() const { 687 return TargetLocations; 688 } 689 690 /// Set default data sharing attribute to none. 691 void setDefaultDSANone(SourceLocation Loc) { 692 getTopOfStack().DefaultAttr = DSA_none; 693 getTopOfStack().DefaultAttrLoc = Loc; 694 } 695 /// Set default data sharing attribute to shared. 696 void setDefaultDSAShared(SourceLocation Loc) { 697 getTopOfStack().DefaultAttr = DSA_shared; 698 getTopOfStack().DefaultAttrLoc = Loc; 699 } 700 /// Set default data sharing attribute to firstprivate. 701 void setDefaultDSAFirstPrivate(SourceLocation Loc) { 702 getTopOfStack().DefaultAttr = DSA_firstprivate; 703 getTopOfStack().DefaultAttrLoc = Loc; 704 } 705 /// Set default data mapping attribute to Modifier:Kind 706 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M, 707 OpenMPDefaultmapClauseKind Kind, 708 SourceLocation Loc) { 709 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind]; 710 DMI.ImplicitBehavior = M; 711 DMI.SLoc = Loc; 712 } 713 /// Check whether the implicit-behavior has been set in defaultmap 714 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) { 715 if (VariableCategory == OMPC_DEFAULTMAP_unknown) 716 return getTopOfStack() 717 .DefaultmapMap[OMPC_DEFAULTMAP_aggregate] 718 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 719 getTopOfStack() 720 .DefaultmapMap[OMPC_DEFAULTMAP_scalar] 721 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 722 getTopOfStack() 723 .DefaultmapMap[OMPC_DEFAULTMAP_pointer] 724 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown; 725 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior != 726 OMPC_DEFAULTMAP_MODIFIER_unknown; 727 } 728 729 DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const { 730 return getStackSize() <= Level ? DSA_unspecified 731 : getStackElemAtLevel(Level).DefaultAttr; 732 } 733 DefaultDataSharingAttributes getDefaultDSA() const { 734 return isStackEmpty() ? DSA_unspecified 735 : getTopOfStack().DefaultAttr; 736 } 737 SourceLocation getDefaultDSALocation() const { 738 return isStackEmpty() ? SourceLocation() 739 : getTopOfStack().DefaultAttrLoc; 740 } 741 OpenMPDefaultmapClauseModifier 742 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const { 743 return isStackEmpty() 744 ? OMPC_DEFAULTMAP_MODIFIER_unknown 745 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior; 746 } 747 OpenMPDefaultmapClauseModifier 748 getDefaultmapModifierAtLevel(unsigned Level, 749 OpenMPDefaultmapClauseKind Kind) const { 750 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior; 751 } 752 bool isDefaultmapCapturedByRef(unsigned Level, 753 OpenMPDefaultmapClauseKind Kind) const { 754 OpenMPDefaultmapClauseModifier M = 755 getDefaultmapModifierAtLevel(Level, Kind); 756 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) { 757 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) || 758 (M == OMPC_DEFAULTMAP_MODIFIER_to) || 759 (M == OMPC_DEFAULTMAP_MODIFIER_from) || 760 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom); 761 } 762 return true; 763 } 764 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M, 765 OpenMPDefaultmapClauseKind Kind) { 766 switch (Kind) { 767 case OMPC_DEFAULTMAP_scalar: 768 case OMPC_DEFAULTMAP_pointer: 769 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) || 770 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) || 771 (M == OMPC_DEFAULTMAP_MODIFIER_default); 772 case OMPC_DEFAULTMAP_aggregate: 773 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate; 774 default: 775 break; 776 } 777 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum"); 778 } 779 bool mustBeFirstprivateAtLevel(unsigned Level, 780 OpenMPDefaultmapClauseKind Kind) const { 781 OpenMPDefaultmapClauseModifier M = 782 getDefaultmapModifierAtLevel(Level, Kind); 783 return mustBeFirstprivateBase(M, Kind); 784 } 785 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const { 786 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind); 787 return mustBeFirstprivateBase(M, Kind); 788 } 789 790 /// Checks if the specified variable is a threadprivate. 791 bool isThreadPrivate(VarDecl *D) { 792 const DSAVarData DVar = getTopDSA(D, false); 793 return isOpenMPThreadPrivate(DVar.CKind); 794 } 795 796 /// Marks current region as ordered (it has an 'ordered' clause). 797 void setOrderedRegion(bool IsOrdered, const Expr *Param, 798 OMPOrderedClause *Clause) { 799 if (IsOrdered) 800 getTopOfStack().OrderedRegion.emplace(Param, Clause); 801 else 802 getTopOfStack().OrderedRegion.reset(); 803 } 804 /// Returns true, if region is ordered (has associated 'ordered' clause), 805 /// false - otherwise. 806 bool isOrderedRegion() const { 807 if (const SharingMapTy *Top = getTopOfStackOrNull()) 808 return Top->OrderedRegion.hasValue(); 809 return false; 810 } 811 /// Returns optional parameter for the ordered region. 812 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 813 if (const SharingMapTy *Top = getTopOfStackOrNull()) 814 if (Top->OrderedRegion.hasValue()) 815 return Top->OrderedRegion.getValue(); 816 return std::make_pair(nullptr, nullptr); 817 } 818 /// Returns true, if parent region is ordered (has associated 819 /// 'ordered' clause), false - otherwise. 820 bool isParentOrderedRegion() const { 821 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 822 return Parent->OrderedRegion.hasValue(); 823 return false; 824 } 825 /// Returns optional parameter for the ordered region. 826 std::pair<const Expr *, OMPOrderedClause *> 827 getParentOrderedRegionParam() const { 828 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 829 if (Parent->OrderedRegion.hasValue()) 830 return Parent->OrderedRegion.getValue(); 831 return std::make_pair(nullptr, nullptr); 832 } 833 /// Marks current region as nowait (it has a 'nowait' clause). 834 void setNowaitRegion(bool IsNowait = true) { 835 getTopOfStack().NowaitRegion = IsNowait; 836 } 837 /// Returns true, if parent region is nowait (has associated 838 /// 'nowait' clause), false - otherwise. 839 bool isParentNowaitRegion() const { 840 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 841 return Parent->NowaitRegion; 842 return false; 843 } 844 /// Marks parent region as cancel region. 845 void setParentCancelRegion(bool Cancel = true) { 846 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 847 Parent->CancelRegion |= Cancel; 848 } 849 /// Return true if current region has inner cancel construct. 850 bool isCancelRegion() const { 851 const SharingMapTy *Top = getTopOfStackOrNull(); 852 return Top ? Top->CancelRegion : false; 853 } 854 855 /// Mark that parent region already has scan directive. 856 void setParentHasScanDirective(SourceLocation Loc) { 857 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 858 Parent->PrevScanLocation = Loc; 859 } 860 /// Return true if current region has inner cancel construct. 861 bool doesParentHasScanDirective() const { 862 const SharingMapTy *Top = getSecondOnStackOrNull(); 863 return Top ? Top->PrevScanLocation.isValid() : false; 864 } 865 /// Return true if current region has inner cancel construct. 866 SourceLocation getParentScanDirectiveLoc() const { 867 const SharingMapTy *Top = getSecondOnStackOrNull(); 868 return Top ? Top->PrevScanLocation : SourceLocation(); 869 } 870 /// Mark that parent region already has ordered directive. 871 void setParentHasOrderedDirective(SourceLocation Loc) { 872 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 873 Parent->PrevOrderedLocation = Loc; 874 } 875 /// Return true if current region has inner ordered construct. 876 bool doesParentHasOrderedDirective() const { 877 const SharingMapTy *Top = getSecondOnStackOrNull(); 878 return Top ? Top->PrevOrderedLocation.isValid() : false; 879 } 880 /// Returns the location of the previously specified ordered directive. 881 SourceLocation getParentOrderedDirectiveLoc() const { 882 const SharingMapTy *Top = getSecondOnStackOrNull(); 883 return Top ? Top->PrevOrderedLocation : SourceLocation(); 884 } 885 886 /// Set collapse value for the region. 887 void setAssociatedLoops(unsigned Val) { 888 getTopOfStack().AssociatedLoops = Val; 889 if (Val > 1) 890 getTopOfStack().HasMutipleLoops = true; 891 } 892 /// Return collapse value for region. 893 unsigned getAssociatedLoops() const { 894 const SharingMapTy *Top = getTopOfStackOrNull(); 895 return Top ? Top->AssociatedLoops : 0; 896 } 897 /// Returns true if the construct is associated with multiple loops. 898 bool hasMutipleLoops() const { 899 const SharingMapTy *Top = getTopOfStackOrNull(); 900 return Top ? Top->HasMutipleLoops : false; 901 } 902 903 /// Marks current target region as one with closely nested teams 904 /// region. 905 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 906 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 907 Parent->InnerTeamsRegionLoc = TeamsRegionLoc; 908 } 909 /// Returns true, if current region has closely nested teams region. 910 bool hasInnerTeamsRegion() const { 911 return getInnerTeamsRegionLoc().isValid(); 912 } 913 /// Returns location of the nested teams region (if any). 914 SourceLocation getInnerTeamsRegionLoc() const { 915 const SharingMapTy *Top = getTopOfStackOrNull(); 916 return Top ? Top->InnerTeamsRegionLoc : SourceLocation(); 917 } 918 919 Scope *getCurScope() const { 920 const SharingMapTy *Top = getTopOfStackOrNull(); 921 return Top ? Top->CurScope : nullptr; 922 } 923 void setContext(DeclContext *DC) { getTopOfStack().Context = DC; } 924 SourceLocation getConstructLoc() const { 925 const SharingMapTy *Top = getTopOfStackOrNull(); 926 return Top ? Top->ConstructLoc : SourceLocation(); 927 } 928 929 /// Do the check specified in \a Check to all component lists and return true 930 /// if any issue is found. 931 bool checkMappableExprComponentListsForDecl( 932 const ValueDecl *VD, bool CurrentRegionOnly, 933 const llvm::function_ref< 934 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 935 OpenMPClauseKind)> 936 Check) const { 937 if (isStackEmpty()) 938 return false; 939 auto SI = begin(); 940 auto SE = end(); 941 942 if (SI == SE) 943 return false; 944 945 if (CurrentRegionOnly) 946 SE = std::next(SI); 947 else 948 std::advance(SI, 1); 949 950 for (; SI != SE; ++SI) { 951 auto MI = SI->MappedExprComponents.find(VD); 952 if (MI != SI->MappedExprComponents.end()) 953 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 954 MI->second.Components) 955 if (Check(L, MI->second.Kind)) 956 return true; 957 } 958 return false; 959 } 960 961 /// Do the check specified in \a Check to all component lists at a given level 962 /// and return true if any issue is found. 963 bool checkMappableExprComponentListsForDeclAtLevel( 964 const ValueDecl *VD, unsigned Level, 965 const llvm::function_ref< 966 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 967 OpenMPClauseKind)> 968 Check) const { 969 if (getStackSize() <= Level) 970 return false; 971 972 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 973 auto MI = StackElem.MappedExprComponents.find(VD); 974 if (MI != StackElem.MappedExprComponents.end()) 975 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 976 MI->second.Components) 977 if (Check(L, MI->second.Kind)) 978 return true; 979 return false; 980 } 981 982 /// Create a new mappable expression component list associated with a given 983 /// declaration and initialize it with the provided list of components. 984 void addMappableExpressionComponents( 985 const ValueDecl *VD, 986 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 987 OpenMPClauseKind WhereFoundClauseKind) { 988 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD]; 989 // Create new entry and append the new components there. 990 MEC.Components.resize(MEC.Components.size() + 1); 991 MEC.Components.back().append(Components.begin(), Components.end()); 992 MEC.Kind = WhereFoundClauseKind; 993 } 994 995 unsigned getNestingLevel() const { 996 assert(!isStackEmpty()); 997 return getStackSize() - 1; 998 } 999 void addDoacrossDependClause(OMPDependClause *C, 1000 const OperatorOffsetTy &OpsOffs) { 1001 SharingMapTy *Parent = getSecondOnStackOrNull(); 1002 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive)); 1003 Parent->DoacrossDepends.try_emplace(C, OpsOffs); 1004 } 1005 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 1006 getDoacrossDependClauses() const { 1007 const SharingMapTy &StackElem = getTopOfStack(); 1008 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 1009 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 1010 return llvm::make_range(Ref.begin(), Ref.end()); 1011 } 1012 return llvm::make_range(StackElem.DoacrossDepends.end(), 1013 StackElem.DoacrossDepends.end()); 1014 } 1015 1016 // Store types of classes which have been explicitly mapped 1017 void addMappedClassesQualTypes(QualType QT) { 1018 SharingMapTy &StackElem = getTopOfStack(); 1019 StackElem.MappedClassesQualTypes.insert(QT); 1020 } 1021 1022 // Return set of mapped classes types 1023 bool isClassPreviouslyMapped(QualType QT) const { 1024 const SharingMapTy &StackElem = getTopOfStack(); 1025 return StackElem.MappedClassesQualTypes.count(QT) != 0; 1026 } 1027 1028 /// Adds global declare target to the parent target region. 1029 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) { 1030 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 1031 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && 1032 "Expected declare target link global."); 1033 for (auto &Elem : *this) { 1034 if (isOpenMPTargetExecutionDirective(Elem.Directive)) { 1035 Elem.DeclareTargetLinkVarDecls.push_back(E); 1036 return; 1037 } 1038 } 1039 } 1040 1041 /// Returns the list of globals with declare target link if current directive 1042 /// is target. 1043 ArrayRef<DeclRefExpr *> getLinkGlobals() const { 1044 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) && 1045 "Expected target executable directive."); 1046 return getTopOfStack().DeclareTargetLinkVarDecls; 1047 } 1048 1049 /// Adds list of allocators expressions. 1050 void addInnerAllocatorExpr(Expr *E) { 1051 getTopOfStack().InnerUsedAllocators.push_back(E); 1052 } 1053 /// Return list of used allocators. 1054 ArrayRef<Expr *> getInnerAllocators() const { 1055 return getTopOfStack().InnerUsedAllocators; 1056 } 1057 /// Marks the declaration as implicitly firstprivate nin the task-based 1058 /// regions. 1059 void addImplicitTaskFirstprivate(unsigned Level, Decl *D) { 1060 getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D); 1061 } 1062 /// Checks if the decl is implicitly firstprivate in the task-based region. 1063 bool isImplicitTaskFirstprivate(Decl *D) const { 1064 return getTopOfStack().ImplicitTaskFirstprivates.count(D) > 0; 1065 } 1066 1067 /// Marks decl as used in uses_allocators clause as the allocator. 1068 void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) { 1069 getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind); 1070 } 1071 /// Checks if specified decl is used in uses allocator clause as the 1072 /// allocator. 1073 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level, 1074 const Decl *D) const { 1075 const SharingMapTy &StackElem = getTopOfStack(); 1076 auto I = StackElem.UsesAllocatorsDecls.find(D); 1077 if (I == StackElem.UsesAllocatorsDecls.end()) 1078 return None; 1079 return I->getSecond(); 1080 } 1081 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const { 1082 const SharingMapTy &StackElem = getTopOfStack(); 1083 auto I = StackElem.UsesAllocatorsDecls.find(D); 1084 if (I == StackElem.UsesAllocatorsDecls.end()) 1085 return None; 1086 return I->getSecond(); 1087 } 1088 1089 void addDeclareMapperVarRef(Expr *Ref) { 1090 SharingMapTy &StackElem = getTopOfStack(); 1091 StackElem.DeclareMapperVar = Ref; 1092 } 1093 const Expr *getDeclareMapperVarRef() const { 1094 const SharingMapTy *Top = getTopOfStackOrNull(); 1095 return Top ? Top->DeclareMapperVar : nullptr; 1096 } 1097 }; 1098 1099 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1100 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 1101 } 1102 1103 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1104 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || 1105 DKind == OMPD_unknown; 1106 } 1107 1108 } // namespace 1109 1110 static const Expr *getExprAsWritten(const Expr *E) { 1111 if (const auto *FE = dyn_cast<FullExpr>(E)) 1112 E = FE->getSubExpr(); 1113 1114 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 1115 E = MTE->getSubExpr(); 1116 1117 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 1118 E = Binder->getSubExpr(); 1119 1120 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 1121 E = ICE->getSubExprAsWritten(); 1122 return E->IgnoreParens(); 1123 } 1124 1125 static Expr *getExprAsWritten(Expr *E) { 1126 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 1127 } 1128 1129 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 1130 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 1131 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 1132 D = ME->getMemberDecl(); 1133 const auto *VD = dyn_cast<VarDecl>(D); 1134 const auto *FD = dyn_cast<FieldDecl>(D); 1135 if (VD != nullptr) { 1136 VD = VD->getCanonicalDecl(); 1137 D = VD; 1138 } else { 1139 assert(FD); 1140 FD = FD->getCanonicalDecl(); 1141 D = FD; 1142 } 1143 return D; 1144 } 1145 1146 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 1147 return const_cast<ValueDecl *>( 1148 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 1149 } 1150 1151 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter, 1152 ValueDecl *D) const { 1153 D = getCanonicalDecl(D); 1154 auto *VD = dyn_cast<VarDecl>(D); 1155 const auto *FD = dyn_cast<FieldDecl>(D); 1156 DSAVarData DVar; 1157 if (Iter == end()) { 1158 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1159 // in a region but not in construct] 1160 // File-scope or namespace-scope variables referenced in called routines 1161 // in the region are shared unless they appear in a threadprivate 1162 // directive. 1163 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 1164 DVar.CKind = OMPC_shared; 1165 1166 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 1167 // in a region but not in construct] 1168 // Variables with static storage duration that are declared in called 1169 // routines in the region are shared. 1170 if (VD && VD->hasGlobalStorage()) 1171 DVar.CKind = OMPC_shared; 1172 1173 // Non-static data members are shared by default. 1174 if (FD) 1175 DVar.CKind = OMPC_shared; 1176 1177 return DVar; 1178 } 1179 1180 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1181 // in a Construct, C/C++, predetermined, p.1] 1182 // Variables with automatic storage duration that are declared in a scope 1183 // inside the construct are private. 1184 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 1185 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 1186 DVar.CKind = OMPC_private; 1187 return DVar; 1188 } 1189 1190 DVar.DKind = Iter->Directive; 1191 // Explicitly specified attributes and local variables with predetermined 1192 // attributes. 1193 if (Iter->SharingMap.count(D)) { 1194 const DSAInfo &Data = Iter->SharingMap.lookup(D); 1195 DVar.RefExpr = Data.RefExpr.getPointer(); 1196 DVar.PrivateCopy = Data.PrivateCopy; 1197 DVar.CKind = Data.Attributes; 1198 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1199 DVar.Modifier = Data.Modifier; 1200 DVar.AppliedToPointee = Data.AppliedToPointee; 1201 return DVar; 1202 } 1203 1204 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1205 // in a Construct, C/C++, implicitly determined, p.1] 1206 // In a parallel or task construct, the data-sharing attributes of these 1207 // variables are determined by the default clause, if present. 1208 switch (Iter->DefaultAttr) { 1209 case DSA_shared: 1210 DVar.CKind = OMPC_shared; 1211 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1212 return DVar; 1213 case DSA_none: 1214 return DVar; 1215 case DSA_firstprivate: 1216 if (VD->getStorageDuration() == SD_Static && 1217 VD->getDeclContext()->isFileContext()) { 1218 DVar.CKind = OMPC_unknown; 1219 } else { 1220 DVar.CKind = OMPC_firstprivate; 1221 } 1222 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1223 return DVar; 1224 case DSA_unspecified: 1225 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1226 // in a Construct, implicitly determined, p.2] 1227 // In a parallel construct, if no default clause is present, these 1228 // variables are shared. 1229 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1230 if ((isOpenMPParallelDirective(DVar.DKind) && 1231 !isOpenMPTaskLoopDirective(DVar.DKind)) || 1232 isOpenMPTeamsDirective(DVar.DKind)) { 1233 DVar.CKind = OMPC_shared; 1234 return DVar; 1235 } 1236 1237 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1238 // in a Construct, implicitly determined, p.4] 1239 // In a task construct, if no default clause is present, a variable that in 1240 // the enclosing context is determined to be shared by all implicit tasks 1241 // bound to the current team is shared. 1242 if (isOpenMPTaskingDirective(DVar.DKind)) { 1243 DSAVarData DVarTemp; 1244 const_iterator I = Iter, E = end(); 1245 do { 1246 ++I; 1247 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 1248 // Referenced in a Construct, implicitly determined, p.6] 1249 // In a task construct, if no default clause is present, a variable 1250 // whose data-sharing attribute is not determined by the rules above is 1251 // firstprivate. 1252 DVarTemp = getDSA(I, D); 1253 if (DVarTemp.CKind != OMPC_shared) { 1254 DVar.RefExpr = nullptr; 1255 DVar.CKind = OMPC_firstprivate; 1256 return DVar; 1257 } 1258 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 1259 DVar.CKind = 1260 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 1261 return DVar; 1262 } 1263 } 1264 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1265 // in a Construct, implicitly determined, p.3] 1266 // For constructs other than task, if no default clause is present, these 1267 // variables inherit their data-sharing attributes from the enclosing 1268 // context. 1269 return getDSA(++Iter, D); 1270 } 1271 1272 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 1273 const Expr *NewDE) { 1274 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1275 D = getCanonicalDecl(D); 1276 SharingMapTy &StackElem = getTopOfStack(); 1277 auto It = StackElem.AlignedMap.find(D); 1278 if (It == StackElem.AlignedMap.end()) { 1279 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1280 StackElem.AlignedMap[D] = NewDE; 1281 return nullptr; 1282 } 1283 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1284 return It->second; 1285 } 1286 1287 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D, 1288 const Expr *NewDE) { 1289 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1290 D = getCanonicalDecl(D); 1291 SharingMapTy &StackElem = getTopOfStack(); 1292 auto It = StackElem.NontemporalMap.find(D); 1293 if (It == StackElem.NontemporalMap.end()) { 1294 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1295 StackElem.NontemporalMap[D] = NewDE; 1296 return nullptr; 1297 } 1298 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1299 return It->second; 1300 } 1301 1302 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 1303 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1304 D = getCanonicalDecl(D); 1305 SharingMapTy &StackElem = getTopOfStack(); 1306 StackElem.LCVMap.try_emplace( 1307 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 1308 } 1309 1310 const DSAStackTy::LCDeclInfo 1311 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 1312 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1313 D = getCanonicalDecl(D); 1314 const SharingMapTy &StackElem = getTopOfStack(); 1315 auto It = StackElem.LCVMap.find(D); 1316 if (It != StackElem.LCVMap.end()) 1317 return It->second; 1318 return {0, nullptr}; 1319 } 1320 1321 const DSAStackTy::LCDeclInfo 1322 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const { 1323 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1324 D = getCanonicalDecl(D); 1325 for (unsigned I = Level + 1; I > 0; --I) { 1326 const SharingMapTy &StackElem = getStackElemAtLevel(I - 1); 1327 auto It = StackElem.LCVMap.find(D); 1328 if (It != StackElem.LCVMap.end()) 1329 return It->second; 1330 } 1331 return {0, nullptr}; 1332 } 1333 1334 const DSAStackTy::LCDeclInfo 1335 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 1336 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1337 assert(Parent && "Data-sharing attributes stack is empty"); 1338 D = getCanonicalDecl(D); 1339 auto It = Parent->LCVMap.find(D); 1340 if (It != Parent->LCVMap.end()) 1341 return It->second; 1342 return {0, nullptr}; 1343 } 1344 1345 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 1346 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1347 assert(Parent && "Data-sharing attributes stack is empty"); 1348 if (Parent->LCVMap.size() < I) 1349 return nullptr; 1350 for (const auto &Pair : Parent->LCVMap) 1351 if (Pair.second.first == I) 1352 return Pair.first; 1353 return nullptr; 1354 } 1355 1356 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 1357 DeclRefExpr *PrivateCopy, unsigned Modifier, 1358 bool AppliedToPointee) { 1359 D = getCanonicalDecl(D); 1360 if (A == OMPC_threadprivate) { 1361 DSAInfo &Data = Threadprivates[D]; 1362 Data.Attributes = A; 1363 Data.RefExpr.setPointer(E); 1364 Data.PrivateCopy = nullptr; 1365 Data.Modifier = Modifier; 1366 } else { 1367 DSAInfo &Data = getTopOfStack().SharingMap[D]; 1368 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 1369 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 1370 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 1371 (isLoopControlVariable(D).first && A == OMPC_private)); 1372 Data.Modifier = Modifier; 1373 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 1374 Data.RefExpr.setInt(/*IntVal=*/true); 1375 return; 1376 } 1377 const bool IsLastprivate = 1378 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 1379 Data.Attributes = A; 1380 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 1381 Data.PrivateCopy = PrivateCopy; 1382 Data.AppliedToPointee = AppliedToPointee; 1383 if (PrivateCopy) { 1384 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()]; 1385 Data.Modifier = Modifier; 1386 Data.Attributes = A; 1387 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 1388 Data.PrivateCopy = nullptr; 1389 Data.AppliedToPointee = AppliedToPointee; 1390 } 1391 } 1392 } 1393 1394 /// Build a variable declaration for OpenMP loop iteration variable. 1395 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 1396 StringRef Name, const AttrVec *Attrs = nullptr, 1397 DeclRefExpr *OrigRef = nullptr) { 1398 DeclContext *DC = SemaRef.CurContext; 1399 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1400 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1401 auto *Decl = 1402 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 1403 if (Attrs) { 1404 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 1405 I != E; ++I) 1406 Decl->addAttr(*I); 1407 } 1408 Decl->setImplicit(); 1409 if (OrigRef) { 1410 Decl->addAttr( 1411 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 1412 } 1413 return Decl; 1414 } 1415 1416 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 1417 SourceLocation Loc, 1418 bool RefersToCapture = false) { 1419 D->setReferenced(); 1420 D->markUsed(S.Context); 1421 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 1422 SourceLocation(), D, RefersToCapture, Loc, Ty, 1423 VK_LValue); 1424 } 1425 1426 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1427 BinaryOperatorKind BOK) { 1428 D = getCanonicalDecl(D); 1429 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1430 assert( 1431 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1432 "Additional reduction info may be specified only for reduction items."); 1433 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1434 assert(ReductionData.ReductionRange.isInvalid() && 1435 (getTopOfStack().Directive == OMPD_taskgroup || 1436 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1437 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1438 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1439 "Additional reduction info may be specified only once for reduction " 1440 "items."); 1441 ReductionData.set(BOK, SR); 1442 Expr *&TaskgroupReductionRef = 1443 getTopOfStack().TaskgroupReductionRef; 1444 if (!TaskgroupReductionRef) { 1445 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1446 SemaRef.Context.VoidPtrTy, ".task_red."); 1447 TaskgroupReductionRef = 1448 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1449 } 1450 } 1451 1452 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1453 const Expr *ReductionRef) { 1454 D = getCanonicalDecl(D); 1455 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1456 assert( 1457 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1458 "Additional reduction info may be specified only for reduction items."); 1459 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1460 assert(ReductionData.ReductionRange.isInvalid() && 1461 (getTopOfStack().Directive == OMPD_taskgroup || 1462 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1463 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1464 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1465 "Additional reduction info may be specified only once for reduction " 1466 "items."); 1467 ReductionData.set(ReductionRef, SR); 1468 Expr *&TaskgroupReductionRef = 1469 getTopOfStack().TaskgroupReductionRef; 1470 if (!TaskgroupReductionRef) { 1471 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1472 SemaRef.Context.VoidPtrTy, ".task_red."); 1473 TaskgroupReductionRef = 1474 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1475 } 1476 } 1477 1478 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1479 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1480 Expr *&TaskgroupDescriptor) const { 1481 D = getCanonicalDecl(D); 1482 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1483 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1484 const DSAInfo &Data = I->SharingMap.lookup(D); 1485 if (Data.Attributes != OMPC_reduction || 1486 Data.Modifier != OMPC_REDUCTION_task) 1487 continue; 1488 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1489 if (!ReductionData.ReductionOp || 1490 ReductionData.ReductionOp.is<const Expr *>()) 1491 return DSAVarData(); 1492 SR = ReductionData.ReductionRange; 1493 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1494 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1495 "expression for the descriptor is not " 1496 "set."); 1497 TaskgroupDescriptor = I->TaskgroupReductionRef; 1498 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1499 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1500 /*AppliedToPointee=*/false); 1501 } 1502 return DSAVarData(); 1503 } 1504 1505 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1506 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1507 Expr *&TaskgroupDescriptor) const { 1508 D = getCanonicalDecl(D); 1509 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1510 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1511 const DSAInfo &Data = I->SharingMap.lookup(D); 1512 if (Data.Attributes != OMPC_reduction || 1513 Data.Modifier != OMPC_REDUCTION_task) 1514 continue; 1515 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1516 if (!ReductionData.ReductionOp || 1517 !ReductionData.ReductionOp.is<const Expr *>()) 1518 return DSAVarData(); 1519 SR = ReductionData.ReductionRange; 1520 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1521 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1522 "expression for the descriptor is not " 1523 "set."); 1524 TaskgroupDescriptor = I->TaskgroupReductionRef; 1525 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1526 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1527 /*AppliedToPointee=*/false); 1528 } 1529 return DSAVarData(); 1530 } 1531 1532 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const { 1533 D = D->getCanonicalDecl(); 1534 for (const_iterator E = end(); I != E; ++I) { 1535 if (isImplicitOrExplicitTaskingRegion(I->Directive) || 1536 isOpenMPTargetExecutionDirective(I->Directive)) { 1537 if (I->CurScope) { 1538 Scope *TopScope = I->CurScope->getParent(); 1539 Scope *CurScope = getCurScope(); 1540 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D)) 1541 CurScope = CurScope->getParent(); 1542 return CurScope != TopScope; 1543 } 1544 for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) 1545 if (I->Context == DC) 1546 return true; 1547 return false; 1548 } 1549 } 1550 return false; 1551 } 1552 1553 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1554 bool AcceptIfMutable = true, 1555 bool *IsClassType = nullptr) { 1556 ASTContext &Context = SemaRef.getASTContext(); 1557 Type = Type.getNonReferenceType().getCanonicalType(); 1558 bool IsConstant = Type.isConstant(Context); 1559 Type = Context.getBaseElementType(Type); 1560 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1561 ? Type->getAsCXXRecordDecl() 1562 : nullptr; 1563 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1564 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1565 RD = CTD->getTemplatedDecl(); 1566 if (IsClassType) 1567 *IsClassType = RD; 1568 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1569 RD->hasDefinition() && RD->hasMutableFields()); 1570 } 1571 1572 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1573 QualType Type, OpenMPClauseKind CKind, 1574 SourceLocation ELoc, 1575 bool AcceptIfMutable = true, 1576 bool ListItemNotVar = false) { 1577 ASTContext &Context = SemaRef.getASTContext(); 1578 bool IsClassType; 1579 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1580 unsigned Diag = ListItemNotVar 1581 ? diag::err_omp_const_list_item 1582 : IsClassType ? diag::err_omp_const_not_mutable_variable 1583 : diag::err_omp_const_variable; 1584 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1585 if (!ListItemNotVar && D) { 1586 const VarDecl *VD = dyn_cast<VarDecl>(D); 1587 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1588 VarDecl::DeclarationOnly; 1589 SemaRef.Diag(D->getLocation(), 1590 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1591 << D; 1592 } 1593 return true; 1594 } 1595 return false; 1596 } 1597 1598 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1599 bool FromParent) { 1600 D = getCanonicalDecl(D); 1601 DSAVarData DVar; 1602 1603 auto *VD = dyn_cast<VarDecl>(D); 1604 auto TI = Threadprivates.find(D); 1605 if (TI != Threadprivates.end()) { 1606 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1607 DVar.CKind = OMPC_threadprivate; 1608 DVar.Modifier = TI->getSecond().Modifier; 1609 return DVar; 1610 } 1611 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1612 DVar.RefExpr = buildDeclRefExpr( 1613 SemaRef, VD, D->getType().getNonReferenceType(), 1614 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1615 DVar.CKind = OMPC_threadprivate; 1616 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1617 return DVar; 1618 } 1619 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1620 // in a Construct, C/C++, predetermined, p.1] 1621 // Variables appearing in threadprivate directives are threadprivate. 1622 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1623 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1624 SemaRef.getLangOpts().OpenMPUseTLS && 1625 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1626 (VD && VD->getStorageClass() == SC_Register && 1627 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1628 DVar.RefExpr = buildDeclRefExpr( 1629 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1630 DVar.CKind = OMPC_threadprivate; 1631 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1632 return DVar; 1633 } 1634 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1635 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1636 !isLoopControlVariable(D).first) { 1637 const_iterator IterTarget = 1638 std::find_if(begin(), end(), [](const SharingMapTy &Data) { 1639 return isOpenMPTargetExecutionDirective(Data.Directive); 1640 }); 1641 if (IterTarget != end()) { 1642 const_iterator ParentIterTarget = IterTarget + 1; 1643 for (const_iterator Iter = begin(); 1644 Iter != ParentIterTarget; ++Iter) { 1645 if (isOpenMPLocal(VD, Iter)) { 1646 DVar.RefExpr = 1647 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1648 D->getLocation()); 1649 DVar.CKind = OMPC_threadprivate; 1650 return DVar; 1651 } 1652 } 1653 if (!isClauseParsingMode() || IterTarget != begin()) { 1654 auto DSAIter = IterTarget->SharingMap.find(D); 1655 if (DSAIter != IterTarget->SharingMap.end() && 1656 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1657 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1658 DVar.CKind = OMPC_threadprivate; 1659 return DVar; 1660 } 1661 const_iterator End = end(); 1662 if (!SemaRef.isOpenMPCapturedByRef( 1663 D, std::distance(ParentIterTarget, End), 1664 /*OpenMPCaptureLevel=*/0)) { 1665 DVar.RefExpr = 1666 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1667 IterTarget->ConstructLoc); 1668 DVar.CKind = OMPC_threadprivate; 1669 return DVar; 1670 } 1671 } 1672 } 1673 } 1674 1675 if (isStackEmpty()) 1676 // Not in OpenMP execution region and top scope was already checked. 1677 return DVar; 1678 1679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1680 // in a Construct, C/C++, predetermined, p.4] 1681 // Static data members are shared. 1682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1683 // in a Construct, C/C++, predetermined, p.7] 1684 // Variables with static storage duration that are declared in a scope 1685 // inside the construct are shared. 1686 if (VD && VD->isStaticDataMember()) { 1687 // Check for explicitly specified attributes. 1688 const_iterator I = begin(); 1689 const_iterator EndI = end(); 1690 if (FromParent && I != EndI) 1691 ++I; 1692 if (I != EndI) { 1693 auto It = I->SharingMap.find(D); 1694 if (It != I->SharingMap.end()) { 1695 const DSAInfo &Data = It->getSecond(); 1696 DVar.RefExpr = Data.RefExpr.getPointer(); 1697 DVar.PrivateCopy = Data.PrivateCopy; 1698 DVar.CKind = Data.Attributes; 1699 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1700 DVar.DKind = I->Directive; 1701 DVar.Modifier = Data.Modifier; 1702 DVar.AppliedToPointee = Data.AppliedToPointee; 1703 return DVar; 1704 } 1705 } 1706 1707 DVar.CKind = OMPC_shared; 1708 return DVar; 1709 } 1710 1711 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1712 // The predetermined shared attribute for const-qualified types having no 1713 // mutable members was removed after OpenMP 3.1. 1714 if (SemaRef.LangOpts.OpenMP <= 31) { 1715 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1716 // in a Construct, C/C++, predetermined, p.6] 1717 // Variables with const qualified type having no mutable member are 1718 // shared. 1719 if (isConstNotMutableType(SemaRef, D->getType())) { 1720 // Variables with const-qualified type having no mutable member may be 1721 // listed in a firstprivate clause, even if they are static data members. 1722 DSAVarData DVarTemp = hasInnermostDSA( 1723 D, 1724 [](OpenMPClauseKind C, bool) { 1725 return C == OMPC_firstprivate || C == OMPC_shared; 1726 }, 1727 MatchesAlways, FromParent); 1728 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1729 return DVarTemp; 1730 1731 DVar.CKind = OMPC_shared; 1732 return DVar; 1733 } 1734 } 1735 1736 // Explicitly specified attributes and local variables with predetermined 1737 // attributes. 1738 const_iterator I = begin(); 1739 const_iterator EndI = end(); 1740 if (FromParent && I != EndI) 1741 ++I; 1742 if (I == EndI) 1743 return DVar; 1744 auto It = I->SharingMap.find(D); 1745 if (It != I->SharingMap.end()) { 1746 const DSAInfo &Data = It->getSecond(); 1747 DVar.RefExpr = Data.RefExpr.getPointer(); 1748 DVar.PrivateCopy = Data.PrivateCopy; 1749 DVar.CKind = Data.Attributes; 1750 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1751 DVar.DKind = I->Directive; 1752 DVar.Modifier = Data.Modifier; 1753 DVar.AppliedToPointee = Data.AppliedToPointee; 1754 } 1755 1756 return DVar; 1757 } 1758 1759 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1760 bool FromParent) const { 1761 if (isStackEmpty()) { 1762 const_iterator I; 1763 return getDSA(I, D); 1764 } 1765 D = getCanonicalDecl(D); 1766 const_iterator StartI = begin(); 1767 const_iterator EndI = end(); 1768 if (FromParent && StartI != EndI) 1769 ++StartI; 1770 return getDSA(StartI, D); 1771 } 1772 1773 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1774 unsigned Level) const { 1775 if (getStackSize() <= Level) 1776 return DSAVarData(); 1777 D = getCanonicalDecl(D); 1778 const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level); 1779 return getDSA(StartI, D); 1780 } 1781 1782 const DSAStackTy::DSAVarData 1783 DSAStackTy::hasDSA(ValueDecl *D, 1784 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1785 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1786 bool FromParent) const { 1787 if (isStackEmpty()) 1788 return {}; 1789 D = getCanonicalDecl(D); 1790 const_iterator I = begin(); 1791 const_iterator EndI = end(); 1792 if (FromParent && I != EndI) 1793 ++I; 1794 for (; I != EndI; ++I) { 1795 if (!DPred(I->Directive) && 1796 !isImplicitOrExplicitTaskingRegion(I->Directive)) 1797 continue; 1798 const_iterator NewI = I; 1799 DSAVarData DVar = getDSA(NewI, D); 1800 if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1801 return DVar; 1802 } 1803 return {}; 1804 } 1805 1806 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1807 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1808 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1809 bool FromParent) const { 1810 if (isStackEmpty()) 1811 return {}; 1812 D = getCanonicalDecl(D); 1813 const_iterator StartI = begin(); 1814 const_iterator EndI = end(); 1815 if (FromParent && StartI != EndI) 1816 ++StartI; 1817 if (StartI == EndI || !DPred(StartI->Directive)) 1818 return {}; 1819 const_iterator NewI = StartI; 1820 DSAVarData DVar = getDSA(NewI, D); 1821 return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1822 ? DVar 1823 : DSAVarData(); 1824 } 1825 1826 bool DSAStackTy::hasExplicitDSA( 1827 const ValueDecl *D, 1828 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1829 unsigned Level, bool NotLastprivate) const { 1830 if (getStackSize() <= Level) 1831 return false; 1832 D = getCanonicalDecl(D); 1833 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1834 auto I = StackElem.SharingMap.find(D); 1835 if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() && 1836 CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) && 1837 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1838 return true; 1839 // Check predetermined rules for the loop control variables. 1840 auto LI = StackElem.LCVMap.find(D); 1841 if (LI != StackElem.LCVMap.end()) 1842 return CPred(OMPC_private, /*AppliedToPointee=*/false); 1843 return false; 1844 } 1845 1846 bool DSAStackTy::hasExplicitDirective( 1847 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1848 unsigned Level) const { 1849 if (getStackSize() <= Level) 1850 return false; 1851 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1852 return DPred(StackElem.Directive); 1853 } 1854 1855 bool DSAStackTy::hasDirective( 1856 const llvm::function_ref<bool(OpenMPDirectiveKind, 1857 const DeclarationNameInfo &, SourceLocation)> 1858 DPred, 1859 bool FromParent) const { 1860 // We look only in the enclosing region. 1861 size_t Skip = FromParent ? 2 : 1; 1862 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end(); 1863 I != E; ++I) { 1864 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1865 return true; 1866 } 1867 return false; 1868 } 1869 1870 void Sema::InitDataSharingAttributesStack() { 1871 VarDataSharingAttributesStack = new DSAStackTy(*this); 1872 } 1873 1874 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1875 1876 void Sema::pushOpenMPFunctionRegion() { 1877 DSAStack->pushFunction(); 1878 } 1879 1880 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1881 DSAStack->popFunction(OldFSI); 1882 } 1883 1884 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1885 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1886 "Expected OpenMP device compilation."); 1887 return !S.isInOpenMPTargetExecutionDirective(); 1888 } 1889 1890 namespace { 1891 /// Status of the function emission on the host/device. 1892 enum class FunctionEmissionStatus { 1893 Emitted, 1894 Discarded, 1895 Unknown, 1896 }; 1897 } // anonymous namespace 1898 1899 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1900 unsigned DiagID, 1901 FunctionDecl *FD) { 1902 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1903 "Expected OpenMP device compilation."); 1904 1905 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1906 if (FD) { 1907 FunctionEmissionStatus FES = getEmissionStatus(FD); 1908 switch (FES) { 1909 case FunctionEmissionStatus::Emitted: 1910 Kind = SemaDiagnosticBuilder::K_Immediate; 1911 break; 1912 case FunctionEmissionStatus::Unknown: 1913 // TODO: We should always delay diagnostics here in case a target 1914 // region is in a function we do not emit. However, as the 1915 // current diagnostics are associated with the function containing 1916 // the target region and we do not emit that one, we would miss out 1917 // on diagnostics for the target region itself. We need to anchor 1918 // the diagnostics with the new generated function *or* ensure we 1919 // emit diagnostics associated with the surrounding function. 1920 Kind = isOpenMPDeviceDelayedContext(*this) 1921 ? SemaDiagnosticBuilder::K_Deferred 1922 : SemaDiagnosticBuilder::K_Immediate; 1923 break; 1924 case FunctionEmissionStatus::TemplateDiscarded: 1925 case FunctionEmissionStatus::OMPDiscarded: 1926 Kind = SemaDiagnosticBuilder::K_Nop; 1927 break; 1928 case FunctionEmissionStatus::CUDADiscarded: 1929 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation"); 1930 break; 1931 } 1932 } 1933 1934 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1935 } 1936 1937 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc, 1938 unsigned DiagID, 1939 FunctionDecl *FD) { 1940 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && 1941 "Expected OpenMP host compilation."); 1942 FunctionEmissionStatus FES = getEmissionStatus(FD); 1943 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1944 switch (FES) { 1945 case FunctionEmissionStatus::Emitted: 1946 Kind = SemaDiagnosticBuilder::K_Immediate; 1947 break; 1948 case FunctionEmissionStatus::Unknown: 1949 Kind = SemaDiagnosticBuilder::K_Deferred; 1950 break; 1951 case FunctionEmissionStatus::TemplateDiscarded: 1952 case FunctionEmissionStatus::OMPDiscarded: 1953 case FunctionEmissionStatus::CUDADiscarded: 1954 Kind = SemaDiagnosticBuilder::K_Nop; 1955 break; 1956 } 1957 1958 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1959 } 1960 1961 static OpenMPDefaultmapClauseKind 1962 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) { 1963 if (LO.OpenMP <= 45) { 1964 if (VD->getType().getNonReferenceType()->isScalarType()) 1965 return OMPC_DEFAULTMAP_scalar; 1966 return OMPC_DEFAULTMAP_aggregate; 1967 } 1968 if (VD->getType().getNonReferenceType()->isAnyPointerType()) 1969 return OMPC_DEFAULTMAP_pointer; 1970 if (VD->getType().getNonReferenceType()->isScalarType()) 1971 return OMPC_DEFAULTMAP_scalar; 1972 return OMPC_DEFAULTMAP_aggregate; 1973 } 1974 1975 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 1976 unsigned OpenMPCaptureLevel) const { 1977 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1978 1979 ASTContext &Ctx = getASTContext(); 1980 bool IsByRef = true; 1981 1982 // Find the directive that is associated with the provided scope. 1983 D = cast<ValueDecl>(D->getCanonicalDecl()); 1984 QualType Ty = D->getType(); 1985 1986 bool IsVariableUsedInMapClause = false; 1987 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1988 // This table summarizes how a given variable should be passed to the device 1989 // given its type and the clauses where it appears. This table is based on 1990 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1991 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1992 // 1993 // ========================================================================= 1994 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1995 // | |(tofrom:scalar)| | pvt | | | | 1996 // ========================================================================= 1997 // | scl | | | | - | | bycopy| 1998 // | scl | | - | x | - | - | bycopy| 1999 // | scl | | x | - | - | - | null | 2000 // | scl | x | | | - | | byref | 2001 // | scl | x | - | x | - | - | bycopy| 2002 // | scl | x | x | - | - | - | null | 2003 // | scl | | - | - | - | x | byref | 2004 // | scl | x | - | - | - | x | byref | 2005 // 2006 // | agg | n.a. | | | - | | byref | 2007 // | agg | n.a. | - | x | - | - | byref | 2008 // | agg | n.a. | x | - | - | - | null | 2009 // | agg | n.a. | - | - | - | x | byref | 2010 // | agg | n.a. | - | - | - | x[] | byref | 2011 // 2012 // | ptr | n.a. | | | - | | bycopy| 2013 // | ptr | n.a. | - | x | - | - | bycopy| 2014 // | ptr | n.a. | x | - | - | - | null | 2015 // | ptr | n.a. | - | - | - | x | byref | 2016 // | ptr | n.a. | - | - | - | x[] | bycopy| 2017 // | ptr | n.a. | - | - | x | | bycopy| 2018 // | ptr | n.a. | - | - | x | x | bycopy| 2019 // | ptr | n.a. | - | - | x | x[] | bycopy| 2020 // ========================================================================= 2021 // Legend: 2022 // scl - scalar 2023 // ptr - pointer 2024 // agg - aggregate 2025 // x - applies 2026 // - - invalid in this combination 2027 // [] - mapped with an array section 2028 // byref - should be mapped by reference 2029 // byval - should be mapped by value 2030 // null - initialize a local variable to null on the device 2031 // 2032 // Observations: 2033 // - All scalar declarations that show up in a map clause have to be passed 2034 // by reference, because they may have been mapped in the enclosing data 2035 // environment. 2036 // - If the scalar value does not fit the size of uintptr, it has to be 2037 // passed by reference, regardless the result in the table above. 2038 // - For pointers mapped by value that have either an implicit map or an 2039 // array section, the runtime library may pass the NULL value to the 2040 // device instead of the value passed to it by the compiler. 2041 2042 if (Ty->isReferenceType()) 2043 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 2044 2045 // Locate map clauses and see if the variable being captured is referred to 2046 // in any of those clauses. Here we only care about variables, not fields, 2047 // because fields are part of aggregates. 2048 bool IsVariableAssociatedWithSection = false; 2049 2050 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2051 D, Level, 2052 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D]( 2053 OMPClauseMappableExprCommon::MappableExprComponentListRef 2054 MapExprComponents, 2055 OpenMPClauseKind WhereFoundClauseKind) { 2056 // Only the map clause information influences how a variable is 2057 // captured. E.g. is_device_ptr does not require changing the default 2058 // behavior. 2059 if (WhereFoundClauseKind != OMPC_map) 2060 return false; 2061 2062 auto EI = MapExprComponents.rbegin(); 2063 auto EE = MapExprComponents.rend(); 2064 2065 assert(EI != EE && "Invalid map expression!"); 2066 2067 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 2068 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 2069 2070 ++EI; 2071 if (EI == EE) 2072 return false; 2073 2074 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 2075 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 2076 isa<MemberExpr>(EI->getAssociatedExpression()) || 2077 isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) { 2078 IsVariableAssociatedWithSection = true; 2079 // There is nothing more we need to know about this variable. 2080 return true; 2081 } 2082 2083 // Keep looking for more map info. 2084 return false; 2085 }); 2086 2087 if (IsVariableUsedInMapClause) { 2088 // If variable is identified in a map clause it is always captured by 2089 // reference except if it is a pointer that is dereferenced somehow. 2090 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 2091 } else { 2092 // By default, all the data that has a scalar type is mapped by copy 2093 // (except for reduction variables). 2094 // Defaultmap scalar is mutual exclusive to defaultmap pointer 2095 IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 2096 !Ty->isAnyPointerType()) || 2097 !Ty->isScalarType() || 2098 DSAStack->isDefaultmapCapturedByRef( 2099 Level, getVariableCategoryFromDecl(LangOpts, D)) || 2100 DSAStack->hasExplicitDSA( 2101 D, 2102 [](OpenMPClauseKind K, bool AppliedToPointee) { 2103 return K == OMPC_reduction && !AppliedToPointee; 2104 }, 2105 Level); 2106 } 2107 } 2108 2109 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 2110 IsByRef = 2111 ((IsVariableUsedInMapClause && 2112 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) == 2113 OMPD_target) || 2114 !(DSAStack->hasExplicitDSA( 2115 D, 2116 [](OpenMPClauseKind K, bool AppliedToPointee) -> bool { 2117 return K == OMPC_firstprivate || 2118 (K == OMPC_reduction && AppliedToPointee); 2119 }, 2120 Level, /*NotLastprivate=*/true) || 2121 DSAStack->isUsesAllocatorsDecl(Level, D))) && 2122 // If the variable is artificial and must be captured by value - try to 2123 // capture by value. 2124 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 2125 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) && 2126 // If the variable is implicitly firstprivate and scalar - capture by 2127 // copy 2128 !(DSAStack->getDefaultDSA() == DSA_firstprivate && 2129 !DSAStack->hasExplicitDSA( 2130 D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; }, 2131 Level) && 2132 !DSAStack->isLoopControlVariable(D, Level).first); 2133 } 2134 2135 // When passing data by copy, we need to make sure it fits the uintptr size 2136 // and alignment, because the runtime library only deals with uintptr types. 2137 // If it does not fit the uintptr size, we need to pass the data by reference 2138 // instead. 2139 if (!IsByRef && 2140 (Ctx.getTypeSizeInChars(Ty) > 2141 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 2142 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 2143 IsByRef = true; 2144 } 2145 2146 return IsByRef; 2147 } 2148 2149 unsigned Sema::getOpenMPNestingLevel() const { 2150 assert(getLangOpts().OpenMP); 2151 return DSAStack->getNestingLevel(); 2152 } 2153 2154 bool Sema::isInOpenMPTargetExecutionDirective() const { 2155 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 2156 !DSAStack->isClauseParsingMode()) || 2157 DSAStack->hasDirective( 2158 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2159 SourceLocation) -> bool { 2160 return isOpenMPTargetExecutionDirective(K); 2161 }, 2162 false); 2163 } 2164 2165 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo, 2166 unsigned StopAt) { 2167 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2168 D = getCanonicalDecl(D); 2169 2170 auto *VD = dyn_cast<VarDecl>(D); 2171 // Do not capture constexpr variables. 2172 if (VD && VD->isConstexpr()) 2173 return nullptr; 2174 2175 // If we want to determine whether the variable should be captured from the 2176 // perspective of the current capturing scope, and we've already left all the 2177 // capturing scopes of the top directive on the stack, check from the 2178 // perspective of its parent directive (if any) instead. 2179 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII( 2180 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete()); 2181 2182 // If we are attempting to capture a global variable in a directive with 2183 // 'target' we return true so that this global is also mapped to the device. 2184 // 2185 if (VD && !VD->hasLocalStorage() && 2186 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 2187 if (isInOpenMPDeclareTargetContext()) { 2188 // Try to mark variable as declare target if it is used in capturing 2189 // regions. 2190 if (LangOpts.OpenMP <= 45 && 2191 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2192 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 2193 return nullptr; 2194 } 2195 if (isInOpenMPTargetExecutionDirective()) { 2196 // If the declaration is enclosed in a 'declare target' directive, 2197 // then it should not be captured. 2198 // 2199 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2200 return nullptr; 2201 CapturedRegionScopeInfo *CSI = nullptr; 2202 for (FunctionScopeInfo *FSI : llvm::drop_begin( 2203 llvm::reverse(FunctionScopes), 2204 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) { 2205 if (!isa<CapturingScopeInfo>(FSI)) 2206 return nullptr; 2207 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2208 if (RSI->CapRegionKind == CR_OpenMP) { 2209 CSI = RSI; 2210 break; 2211 } 2212 } 2213 assert(CSI && "Failed to find CapturedRegionScopeInfo"); 2214 SmallVector<OpenMPDirectiveKind, 4> Regions; 2215 getOpenMPCaptureRegions(Regions, 2216 DSAStack->getDirective(CSI->OpenMPLevel)); 2217 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task) 2218 return VD; 2219 } 2220 } 2221 2222 if (CheckScopeInfo) { 2223 bool OpenMPFound = false; 2224 for (unsigned I = StopAt + 1; I > 0; --I) { 2225 FunctionScopeInfo *FSI = FunctionScopes[I - 1]; 2226 if(!isa<CapturingScopeInfo>(FSI)) 2227 return nullptr; 2228 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2229 if (RSI->CapRegionKind == CR_OpenMP) { 2230 OpenMPFound = true; 2231 break; 2232 } 2233 } 2234 if (!OpenMPFound) 2235 return nullptr; 2236 } 2237 2238 if (DSAStack->getCurrentDirective() != OMPD_unknown && 2239 (!DSAStack->isClauseParsingMode() || 2240 DSAStack->getParentDirective() != OMPD_unknown)) { 2241 auto &&Info = DSAStack->isLoopControlVariable(D); 2242 if (Info.first || 2243 (VD && VD->hasLocalStorage() && 2244 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 2245 (VD && DSAStack->isForceVarCapturing())) 2246 return VD ? VD : Info.second; 2247 DSAStackTy::DSAVarData DVarTop = 2248 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2249 if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) && 2250 (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee)) 2251 return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl()); 2252 // Threadprivate variables must not be captured. 2253 if (isOpenMPThreadPrivate(DVarTop.CKind)) 2254 return nullptr; 2255 // The variable is not private or it is the variable in the directive with 2256 // default(none) clause and not used in any clause. 2257 DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA( 2258 D, 2259 [](OpenMPClauseKind C, bool AppliedToPointee) { 2260 return isOpenMPPrivate(C) && !AppliedToPointee; 2261 }, 2262 [](OpenMPDirectiveKind) { return true; }, 2263 DSAStack->isClauseParsingMode()); 2264 // Global shared must not be captured. 2265 if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown && 2266 ((DSAStack->getDefaultDSA() != DSA_none && 2267 DSAStack->getDefaultDSA() != DSA_firstprivate) || 2268 DVarTop.CKind == OMPC_shared)) 2269 return nullptr; 2270 if (DVarPrivate.CKind != OMPC_unknown || 2271 (VD && (DSAStack->getDefaultDSA() == DSA_none || 2272 DSAStack->getDefaultDSA() == DSA_firstprivate))) 2273 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 2274 } 2275 return nullptr; 2276 } 2277 2278 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 2279 unsigned Level) const { 2280 FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2281 } 2282 2283 void Sema::startOpenMPLoop() { 2284 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2285 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 2286 DSAStack->loopInit(); 2287 } 2288 2289 void Sema::startOpenMPCXXRangeFor() { 2290 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2291 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2292 DSAStack->resetPossibleLoopCounter(); 2293 DSAStack->loopStart(); 2294 } 2295 } 2296 2297 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 2298 unsigned CapLevel) const { 2299 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2300 if (DSAStack->hasExplicitDirective( 2301 [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); }, 2302 Level)) { 2303 bool IsTriviallyCopyable = 2304 D->getType().getNonReferenceType().isTriviallyCopyableType(Context) && 2305 !D->getType() 2306 .getNonReferenceType() 2307 .getCanonicalType() 2308 ->getAsCXXRecordDecl(); 2309 OpenMPDirectiveKind DKind = DSAStack->getDirective(Level); 2310 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2311 getOpenMPCaptureRegions(CaptureRegions, DKind); 2312 if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) && 2313 (IsTriviallyCopyable || 2314 !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) { 2315 if (DSAStack->hasExplicitDSA( 2316 D, 2317 [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; }, 2318 Level, /*NotLastprivate=*/true)) 2319 return OMPC_firstprivate; 2320 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2321 if (DVar.CKind != OMPC_shared && 2322 !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) { 2323 DSAStack->addImplicitTaskFirstprivate(Level, D); 2324 return OMPC_firstprivate; 2325 } 2326 } 2327 } 2328 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2329 if (DSAStack->getAssociatedLoops() > 0 && 2330 !DSAStack->isLoopStarted()) { 2331 DSAStack->resetPossibleLoopCounter(D); 2332 DSAStack->loopStart(); 2333 return OMPC_private; 2334 } 2335 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 2336 DSAStack->isLoopControlVariable(D).first) && 2337 !DSAStack->hasExplicitDSA( 2338 D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; }, 2339 Level) && 2340 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 2341 return OMPC_private; 2342 } 2343 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2344 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) && 2345 DSAStack->isForceVarCapturing() && 2346 !DSAStack->hasExplicitDSA( 2347 D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; }, 2348 Level)) 2349 return OMPC_private; 2350 } 2351 // User-defined allocators are private since they must be defined in the 2352 // context of target region. 2353 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) && 2354 DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr( 2355 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 2356 DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator) 2357 return OMPC_private; 2358 return (DSAStack->hasExplicitDSA( 2359 D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; }, 2360 Level) || 2361 (DSAStack->isClauseParsingMode() && 2362 DSAStack->getClauseParsingMode() == OMPC_private) || 2363 // Consider taskgroup reduction descriptor variable a private 2364 // to avoid possible capture in the region. 2365 (DSAStack->hasExplicitDirective( 2366 [](OpenMPDirectiveKind K) { 2367 return K == OMPD_taskgroup || 2368 ((isOpenMPParallelDirective(K) || 2369 isOpenMPWorksharingDirective(K)) && 2370 !isOpenMPSimdDirective(K)); 2371 }, 2372 Level) && 2373 DSAStack->isTaskgroupReductionRef(D, Level))) 2374 ? OMPC_private 2375 : OMPC_unknown; 2376 } 2377 2378 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 2379 unsigned Level) { 2380 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2381 D = getCanonicalDecl(D); 2382 OpenMPClauseKind OMPC = OMPC_unknown; 2383 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 2384 const unsigned NewLevel = I - 1; 2385 if (DSAStack->hasExplicitDSA( 2386 D, 2387 [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) { 2388 if (isOpenMPPrivate(K) && !AppliedToPointee) { 2389 OMPC = K; 2390 return true; 2391 } 2392 return false; 2393 }, 2394 NewLevel)) 2395 break; 2396 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2397 D, NewLevel, 2398 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2399 OpenMPClauseKind) { return true; })) { 2400 OMPC = OMPC_map; 2401 break; 2402 } 2403 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2404 NewLevel)) { 2405 OMPC = OMPC_map; 2406 if (DSAStack->mustBeFirstprivateAtLevel( 2407 NewLevel, getVariableCategoryFromDecl(LangOpts, D))) 2408 OMPC = OMPC_firstprivate; 2409 break; 2410 } 2411 } 2412 if (OMPC != OMPC_unknown) 2413 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC))); 2414 } 2415 2416 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 2417 unsigned CaptureLevel) const { 2418 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2419 // Return true if the current level is no longer enclosed in a target region. 2420 2421 SmallVector<OpenMPDirectiveKind, 4> Regions; 2422 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 2423 const auto *VD = dyn_cast<VarDecl>(D); 2424 return VD && !VD->hasLocalStorage() && 2425 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2426 Level) && 2427 Regions[CaptureLevel] != OMPD_task; 2428 } 2429 2430 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 2431 unsigned CaptureLevel) const { 2432 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2433 // Return true if the current level is no longer enclosed in a target region. 2434 2435 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2436 if (!VD->hasLocalStorage()) { 2437 if (isInOpenMPTargetExecutionDirective()) 2438 return true; 2439 DSAStackTy::DSAVarData TopDVar = 2440 DSAStack->getTopDSA(D, /*FromParent=*/false); 2441 unsigned NumLevels = 2442 getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2443 if (Level == 0) 2444 return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared; 2445 do { 2446 --Level; 2447 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2448 if (DVar.CKind != OMPC_shared) 2449 return true; 2450 } while (Level > 0); 2451 } 2452 } 2453 return true; 2454 } 2455 2456 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 2457 2458 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, 2459 OMPTraitInfo &TI) { 2460 OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI)); 2461 } 2462 2463 void Sema::ActOnOpenMPEndDeclareVariant() { 2464 assert(isInOpenMPDeclareVariantScope() && 2465 "Not in OpenMP declare variant scope!"); 2466 2467 OMPDeclareVariantScopes.pop_back(); 2468 } 2469 2470 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 2471 const FunctionDecl *Callee, 2472 SourceLocation Loc) { 2473 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode."); 2474 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 2475 OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl()); 2476 // Ignore host functions during device analyzis. 2477 if (LangOpts.OpenMPIsDevice && DevTy && 2478 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) 2479 return; 2480 // Ignore nohost functions during host analyzis. 2481 if (!LangOpts.OpenMPIsDevice && DevTy && 2482 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 2483 return; 2484 const FunctionDecl *FD = Callee->getMostRecentDecl(); 2485 DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD); 2486 if (LangOpts.OpenMPIsDevice && DevTy && 2487 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) { 2488 // Diagnose host function called during device codegen. 2489 StringRef HostDevTy = 2490 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host); 2491 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0; 2492 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2493 diag::note_omp_marked_device_type_here) 2494 << HostDevTy; 2495 return; 2496 } 2497 if (!LangOpts.OpenMPIsDevice && DevTy && 2498 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 2499 // Diagnose nohost function called during host codegen. 2500 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName( 2501 OMPC_device_type, OMPC_DEVICE_TYPE_nohost); 2502 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1; 2503 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2504 diag::note_omp_marked_device_type_here) 2505 << NoHostDevTy; 2506 } 2507 } 2508 2509 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 2510 const DeclarationNameInfo &DirName, 2511 Scope *CurScope, SourceLocation Loc) { 2512 DSAStack->push(DKind, DirName, CurScope, Loc); 2513 PushExpressionEvaluationContext( 2514 ExpressionEvaluationContext::PotentiallyEvaluated); 2515 } 2516 2517 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 2518 DSAStack->setClauseParsingMode(K); 2519 } 2520 2521 void Sema::EndOpenMPClause() { 2522 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 2523 } 2524 2525 static std::pair<ValueDecl *, bool> 2526 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 2527 SourceRange &ERange, bool AllowArraySection = false); 2528 2529 /// Check consistency of the reduction clauses. 2530 static void checkReductionClauses(Sema &S, DSAStackTy *Stack, 2531 ArrayRef<OMPClause *> Clauses) { 2532 bool InscanFound = false; 2533 SourceLocation InscanLoc; 2534 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions. 2535 // A reduction clause without the inscan reduction-modifier may not appear on 2536 // a construct on which a reduction clause with the inscan reduction-modifier 2537 // appears. 2538 for (OMPClause *C : Clauses) { 2539 if (C->getClauseKind() != OMPC_reduction) 2540 continue; 2541 auto *RC = cast<OMPReductionClause>(C); 2542 if (RC->getModifier() == OMPC_REDUCTION_inscan) { 2543 InscanFound = true; 2544 InscanLoc = RC->getModifierLoc(); 2545 continue; 2546 } 2547 if (RC->getModifier() == OMPC_REDUCTION_task) { 2548 // OpenMP 5.0, 2.19.5.4 reduction Clause. 2549 // A reduction clause with the task reduction-modifier may only appear on 2550 // a parallel construct, a worksharing construct or a combined or 2551 // composite construct for which any of the aforementioned constructs is a 2552 // constituent construct and simd or loop are not constituent constructs. 2553 OpenMPDirectiveKind CurDir = Stack->getCurrentDirective(); 2554 if (!(isOpenMPParallelDirective(CurDir) || 2555 isOpenMPWorksharingDirective(CurDir)) || 2556 isOpenMPSimdDirective(CurDir)) 2557 S.Diag(RC->getModifierLoc(), 2558 diag::err_omp_reduction_task_not_parallel_or_worksharing); 2559 continue; 2560 } 2561 } 2562 if (InscanFound) { 2563 for (OMPClause *C : Clauses) { 2564 if (C->getClauseKind() != OMPC_reduction) 2565 continue; 2566 auto *RC = cast<OMPReductionClause>(C); 2567 if (RC->getModifier() != OMPC_REDUCTION_inscan) { 2568 S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown 2569 ? RC->getBeginLoc() 2570 : RC->getModifierLoc(), 2571 diag::err_omp_inscan_reduction_expected); 2572 S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction); 2573 continue; 2574 } 2575 for (Expr *Ref : RC->varlists()) { 2576 assert(Ref && "NULL expr in OpenMP nontemporal clause."); 2577 SourceLocation ELoc; 2578 SourceRange ERange; 2579 Expr *SimpleRefExpr = Ref; 2580 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 2581 /*AllowArraySection=*/true); 2582 ValueDecl *D = Res.first; 2583 if (!D) 2584 continue; 2585 if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) { 2586 S.Diag(Ref->getExprLoc(), 2587 diag::err_omp_reduction_not_inclusive_exclusive) 2588 << Ref->getSourceRange(); 2589 } 2590 } 2591 } 2592 } 2593 } 2594 2595 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 2596 ArrayRef<OMPClause *> Clauses); 2597 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2598 bool WithInit); 2599 2600 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 2601 const ValueDecl *D, 2602 const DSAStackTy::DSAVarData &DVar, 2603 bool IsLoopIterVar = false); 2604 2605 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 2606 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 2607 // A variable of class type (or array thereof) that appears in a lastprivate 2608 // clause requires an accessible, unambiguous default constructor for the 2609 // class type, unless the list item is also specified in a firstprivate 2610 // clause. 2611 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 2612 for (OMPClause *C : D->clauses()) { 2613 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 2614 SmallVector<Expr *, 8> PrivateCopies; 2615 for (Expr *DE : Clause->varlists()) { 2616 if (DE->isValueDependent() || DE->isTypeDependent()) { 2617 PrivateCopies.push_back(nullptr); 2618 continue; 2619 } 2620 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 2621 auto *VD = cast<VarDecl>(DRE->getDecl()); 2622 QualType Type = VD->getType().getNonReferenceType(); 2623 const DSAStackTy::DSAVarData DVar = 2624 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2625 if (DVar.CKind == OMPC_lastprivate) { 2626 // Generate helper private variable and initialize it with the 2627 // default value. The address of the original variable is replaced 2628 // by the address of the new private variable in CodeGen. This new 2629 // variable is not added to IdResolver, so the code in the OpenMP 2630 // region uses original variable for proper diagnostics. 2631 VarDecl *VDPrivate = buildVarDecl( 2632 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 2633 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 2634 ActOnUninitializedDecl(VDPrivate); 2635 if (VDPrivate->isInvalidDecl()) { 2636 PrivateCopies.push_back(nullptr); 2637 continue; 2638 } 2639 PrivateCopies.push_back(buildDeclRefExpr( 2640 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 2641 } else { 2642 // The variable is also a firstprivate, so initialization sequence 2643 // for private copy is generated already. 2644 PrivateCopies.push_back(nullptr); 2645 } 2646 } 2647 Clause->setPrivateCopies(PrivateCopies); 2648 continue; 2649 } 2650 // Finalize nontemporal clause by handling private copies, if any. 2651 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) { 2652 SmallVector<Expr *, 8> PrivateRefs; 2653 for (Expr *RefExpr : Clause->varlists()) { 2654 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 2655 SourceLocation ELoc; 2656 SourceRange ERange; 2657 Expr *SimpleRefExpr = RefExpr; 2658 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 2659 if (Res.second) 2660 // It will be analyzed later. 2661 PrivateRefs.push_back(RefExpr); 2662 ValueDecl *D = Res.first; 2663 if (!D) 2664 continue; 2665 2666 const DSAStackTy::DSAVarData DVar = 2667 DSAStack->getTopDSA(D, /*FromParent=*/false); 2668 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy 2669 : SimpleRefExpr); 2670 } 2671 Clause->setPrivateRefs(PrivateRefs); 2672 continue; 2673 } 2674 if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) { 2675 for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) { 2676 OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I); 2677 auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts()); 2678 if (!DRE) 2679 continue; 2680 ValueDecl *VD = DRE->getDecl(); 2681 if (!VD || !isa<VarDecl>(VD)) 2682 continue; 2683 DSAStackTy::DSAVarData DVar = 2684 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2685 // OpenMP [2.12.5, target Construct] 2686 // Memory allocators that appear in a uses_allocators clause cannot 2687 // appear in other data-sharing attribute clauses or data-mapping 2688 // attribute clauses in the same construct. 2689 Expr *MapExpr = nullptr; 2690 if (DVar.RefExpr || 2691 DSAStack->checkMappableExprComponentListsForDecl( 2692 VD, /*CurrentRegionOnly=*/true, 2693 [VD, &MapExpr]( 2694 OMPClauseMappableExprCommon::MappableExprComponentListRef 2695 MapExprComponents, 2696 OpenMPClauseKind C) { 2697 auto MI = MapExprComponents.rbegin(); 2698 auto ME = MapExprComponents.rend(); 2699 if (MI != ME && 2700 MI->getAssociatedDeclaration()->getCanonicalDecl() == 2701 VD->getCanonicalDecl()) { 2702 MapExpr = MI->getAssociatedExpression(); 2703 return true; 2704 } 2705 return false; 2706 })) { 2707 Diag(D.Allocator->getExprLoc(), 2708 diag::err_omp_allocator_used_in_clauses) 2709 << D.Allocator->getSourceRange(); 2710 if (DVar.RefExpr) 2711 reportOriginalDsa(*this, DSAStack, VD, DVar); 2712 else 2713 Diag(MapExpr->getExprLoc(), diag::note_used_here) 2714 << MapExpr->getSourceRange(); 2715 } 2716 } 2717 continue; 2718 } 2719 } 2720 // Check allocate clauses. 2721 if (!CurContext->isDependentContext()) 2722 checkAllocateClauses(*this, DSAStack, D->clauses()); 2723 checkReductionClauses(*this, DSAStack, D->clauses()); 2724 } 2725 2726 DSAStack->pop(); 2727 DiscardCleanupsInEvaluationContext(); 2728 PopExpressionEvaluationContext(); 2729 } 2730 2731 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 2732 Expr *NumIterations, Sema &SemaRef, 2733 Scope *S, DSAStackTy *Stack); 2734 2735 namespace { 2736 2737 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 2738 private: 2739 Sema &SemaRef; 2740 2741 public: 2742 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 2743 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2744 NamedDecl *ND = Candidate.getCorrectionDecl(); 2745 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 2746 return VD->hasGlobalStorage() && 2747 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2748 SemaRef.getCurScope()); 2749 } 2750 return false; 2751 } 2752 2753 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2754 return std::make_unique<VarDeclFilterCCC>(*this); 2755 } 2756 2757 }; 2758 2759 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 2760 private: 2761 Sema &SemaRef; 2762 2763 public: 2764 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 2765 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2766 NamedDecl *ND = Candidate.getCorrectionDecl(); 2767 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) || 2768 isa<FunctionDecl>(ND))) { 2769 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2770 SemaRef.getCurScope()); 2771 } 2772 return false; 2773 } 2774 2775 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2776 return std::make_unique<VarOrFuncDeclFilterCCC>(*this); 2777 } 2778 }; 2779 2780 } // namespace 2781 2782 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 2783 CXXScopeSpec &ScopeSpec, 2784 const DeclarationNameInfo &Id, 2785 OpenMPDirectiveKind Kind) { 2786 LookupResult Lookup(*this, Id, LookupOrdinaryName); 2787 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 2788 2789 if (Lookup.isAmbiguous()) 2790 return ExprError(); 2791 2792 VarDecl *VD; 2793 if (!Lookup.isSingleResult()) { 2794 VarDeclFilterCCC CCC(*this); 2795 if (TypoCorrection Corrected = 2796 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 2797 CTK_ErrorRecovery)) { 2798 diagnoseTypo(Corrected, 2799 PDiag(Lookup.empty() 2800 ? diag::err_undeclared_var_use_suggest 2801 : diag::err_omp_expected_var_arg_suggest) 2802 << Id.getName()); 2803 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 2804 } else { 2805 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 2806 : diag::err_omp_expected_var_arg) 2807 << Id.getName(); 2808 return ExprError(); 2809 } 2810 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 2811 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 2812 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 2813 return ExprError(); 2814 } 2815 Lookup.suppressDiagnostics(); 2816 2817 // OpenMP [2.9.2, Syntax, C/C++] 2818 // Variables must be file-scope, namespace-scope, or static block-scope. 2819 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) { 2820 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 2821 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal(); 2822 bool IsDecl = 2823 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2824 Diag(VD->getLocation(), 2825 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2826 << VD; 2827 return ExprError(); 2828 } 2829 2830 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 2831 NamedDecl *ND = CanonicalVD; 2832 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 2833 // A threadprivate directive for file-scope variables must appear outside 2834 // any definition or declaration. 2835 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 2836 !getCurLexicalContext()->isTranslationUnit()) { 2837 Diag(Id.getLoc(), diag::err_omp_var_scope) 2838 << getOpenMPDirectiveName(Kind) << VD; 2839 bool IsDecl = 2840 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2841 Diag(VD->getLocation(), 2842 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2843 << VD; 2844 return ExprError(); 2845 } 2846 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 2847 // A threadprivate directive for static class member variables must appear 2848 // in the class definition, in the same scope in which the member 2849 // variables are declared. 2850 if (CanonicalVD->isStaticDataMember() && 2851 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 2852 Diag(Id.getLoc(), diag::err_omp_var_scope) 2853 << getOpenMPDirectiveName(Kind) << VD; 2854 bool IsDecl = 2855 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2856 Diag(VD->getLocation(), 2857 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2858 << VD; 2859 return ExprError(); 2860 } 2861 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 2862 // A threadprivate directive for namespace-scope variables must appear 2863 // outside any definition or declaration other than the namespace 2864 // definition itself. 2865 if (CanonicalVD->getDeclContext()->isNamespace() && 2866 (!getCurLexicalContext()->isFileContext() || 2867 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 2868 Diag(Id.getLoc(), diag::err_omp_var_scope) 2869 << getOpenMPDirectiveName(Kind) << VD; 2870 bool IsDecl = 2871 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2872 Diag(VD->getLocation(), 2873 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2874 << VD; 2875 return ExprError(); 2876 } 2877 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2878 // A threadprivate directive for static block-scope variables must appear 2879 // in the scope of the variable and not in a nested scope. 2880 if (CanonicalVD->isLocalVarDecl() && CurScope && 2881 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2882 Diag(Id.getLoc(), diag::err_omp_var_scope) 2883 << getOpenMPDirectiveName(Kind) << VD; 2884 bool IsDecl = 2885 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2886 Diag(VD->getLocation(), 2887 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2888 << VD; 2889 return ExprError(); 2890 } 2891 2892 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2893 // A threadprivate directive must lexically precede all references to any 2894 // of the variables in its list. 2895 if (Kind == OMPD_threadprivate && VD->isUsed() && 2896 !DSAStack->isThreadPrivate(VD)) { 2897 Diag(Id.getLoc(), diag::err_omp_var_used) 2898 << getOpenMPDirectiveName(Kind) << VD; 2899 return ExprError(); 2900 } 2901 2902 QualType ExprType = VD->getType().getNonReferenceType(); 2903 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2904 SourceLocation(), VD, 2905 /*RefersToEnclosingVariableOrCapture=*/false, 2906 Id.getLoc(), ExprType, VK_LValue); 2907 } 2908 2909 Sema::DeclGroupPtrTy 2910 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2911 ArrayRef<Expr *> VarList) { 2912 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2913 CurContext->addDecl(D); 2914 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2915 } 2916 return nullptr; 2917 } 2918 2919 namespace { 2920 class LocalVarRefChecker final 2921 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2922 Sema &SemaRef; 2923 2924 public: 2925 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2926 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2927 if (VD->hasLocalStorage()) { 2928 SemaRef.Diag(E->getBeginLoc(), 2929 diag::err_omp_local_var_in_threadprivate_init) 2930 << E->getSourceRange(); 2931 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2932 << VD << VD->getSourceRange(); 2933 return true; 2934 } 2935 } 2936 return false; 2937 } 2938 bool VisitStmt(const Stmt *S) { 2939 for (const Stmt *Child : S->children()) { 2940 if (Child && Visit(Child)) 2941 return true; 2942 } 2943 return false; 2944 } 2945 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2946 }; 2947 } // namespace 2948 2949 OMPThreadPrivateDecl * 2950 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2951 SmallVector<Expr *, 8> Vars; 2952 for (Expr *RefExpr : VarList) { 2953 auto *DE = cast<DeclRefExpr>(RefExpr); 2954 auto *VD = cast<VarDecl>(DE->getDecl()); 2955 SourceLocation ILoc = DE->getExprLoc(); 2956 2957 // Mark variable as used. 2958 VD->setReferenced(); 2959 VD->markUsed(Context); 2960 2961 QualType QType = VD->getType(); 2962 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 2963 // It will be analyzed later. 2964 Vars.push_back(DE); 2965 continue; 2966 } 2967 2968 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2969 // A threadprivate variable must not have an incomplete type. 2970 if (RequireCompleteType(ILoc, VD->getType(), 2971 diag::err_omp_threadprivate_incomplete_type)) { 2972 continue; 2973 } 2974 2975 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2976 // A threadprivate variable must not have a reference type. 2977 if (VD->getType()->isReferenceType()) { 2978 Diag(ILoc, diag::err_omp_ref_type_arg) 2979 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 2980 bool IsDecl = 2981 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2982 Diag(VD->getLocation(), 2983 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2984 << VD; 2985 continue; 2986 } 2987 2988 // Check if this is a TLS variable. If TLS is not being supported, produce 2989 // the corresponding diagnostic. 2990 if ((VD->getTLSKind() != VarDecl::TLS_None && 2991 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 2992 getLangOpts().OpenMPUseTLS && 2993 getASTContext().getTargetInfo().isTLSSupported())) || 2994 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 2995 !VD->isLocalVarDecl())) { 2996 Diag(ILoc, diag::err_omp_var_thread_local) 2997 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 2998 bool IsDecl = 2999 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 3000 Diag(VD->getLocation(), 3001 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3002 << VD; 3003 continue; 3004 } 3005 3006 // Check if initial value of threadprivate variable reference variable with 3007 // local storage (it is not supported by runtime). 3008 if (const Expr *Init = VD->getAnyInitializer()) { 3009 LocalVarRefChecker Checker(*this); 3010 if (Checker.Visit(Init)) 3011 continue; 3012 } 3013 3014 Vars.push_back(RefExpr); 3015 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 3016 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 3017 Context, SourceRange(Loc, Loc))); 3018 if (ASTMutationListener *ML = Context.getASTMutationListener()) 3019 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 3020 } 3021 OMPThreadPrivateDecl *D = nullptr; 3022 if (!Vars.empty()) { 3023 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 3024 Vars); 3025 D->setAccess(AS_public); 3026 } 3027 return D; 3028 } 3029 3030 static OMPAllocateDeclAttr::AllocatorTypeTy 3031 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) { 3032 if (!Allocator) 3033 return OMPAllocateDeclAttr::OMPNullMemAlloc; 3034 if (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3035 Allocator->isInstantiationDependent() || 3036 Allocator->containsUnexpandedParameterPack()) 3037 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3038 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3039 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3040 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 3041 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 3042 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind); 3043 llvm::FoldingSetNodeID AEId, DAEId; 3044 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true); 3045 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true); 3046 if (AEId == DAEId) { 3047 AllocatorKindRes = AllocatorKind; 3048 break; 3049 } 3050 } 3051 return AllocatorKindRes; 3052 } 3053 3054 static bool checkPreviousOMPAllocateAttribute( 3055 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD, 3056 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) { 3057 if (!VD->hasAttr<OMPAllocateDeclAttr>()) 3058 return false; 3059 const auto *A = VD->getAttr<OMPAllocateDeclAttr>(); 3060 Expr *PrevAllocator = A->getAllocator(); 3061 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind = 3062 getAllocatorKind(S, Stack, PrevAllocator); 3063 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind; 3064 if (AllocatorsMatch && 3065 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc && 3066 Allocator && PrevAllocator) { 3067 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3068 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts(); 3069 llvm::FoldingSetNodeID AEId, PAEId; 3070 AE->Profile(AEId, S.Context, /*Canonical=*/true); 3071 PAE->Profile(PAEId, S.Context, /*Canonical=*/true); 3072 AllocatorsMatch = AEId == PAEId; 3073 } 3074 if (!AllocatorsMatch) { 3075 SmallString<256> AllocatorBuffer; 3076 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer); 3077 if (Allocator) 3078 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy()); 3079 SmallString<256> PrevAllocatorBuffer; 3080 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer); 3081 if (PrevAllocator) 3082 PrevAllocator->printPretty(PrevAllocatorStream, nullptr, 3083 S.getPrintingPolicy()); 3084 3085 SourceLocation AllocatorLoc = 3086 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc(); 3087 SourceRange AllocatorRange = 3088 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange(); 3089 SourceLocation PrevAllocatorLoc = 3090 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation(); 3091 SourceRange PrevAllocatorRange = 3092 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange(); 3093 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator) 3094 << (Allocator ? 1 : 0) << AllocatorStream.str() 3095 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str() 3096 << AllocatorRange; 3097 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator) 3098 << PrevAllocatorRange; 3099 return true; 3100 } 3101 return false; 3102 } 3103 3104 static void 3105 applyOMPAllocateAttribute(Sema &S, VarDecl *VD, 3106 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 3107 Expr *Allocator, SourceRange SR) { 3108 if (VD->hasAttr<OMPAllocateDeclAttr>()) 3109 return; 3110 if (Allocator && 3111 (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3112 Allocator->isInstantiationDependent() || 3113 Allocator->containsUnexpandedParameterPack())) 3114 return; 3115 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind, 3116 Allocator, SR); 3117 VD->addAttr(A); 3118 if (ASTMutationListener *ML = S.Context.getASTMutationListener()) 3119 ML->DeclarationMarkedOpenMPAllocate(VD, A); 3120 } 3121 3122 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective( 3123 SourceLocation Loc, ArrayRef<Expr *> VarList, 3124 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) { 3125 assert(Clauses.size() <= 1 && "Expected at most one clause."); 3126 Expr *Allocator = nullptr; 3127 if (Clauses.empty()) { 3128 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions. 3129 // allocate directives that appear in a target region must specify an 3130 // allocator clause unless a requires directive with the dynamic_allocators 3131 // clause is present in the same compilation unit. 3132 if (LangOpts.OpenMPIsDevice && 3133 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 3134 targetDiag(Loc, diag::err_expected_allocator_clause); 3135 } else { 3136 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator(); 3137 } 3138 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 3139 getAllocatorKind(*this, DSAStack, Allocator); 3140 SmallVector<Expr *, 8> Vars; 3141 for (Expr *RefExpr : VarList) { 3142 auto *DE = cast<DeclRefExpr>(RefExpr); 3143 auto *VD = cast<VarDecl>(DE->getDecl()); 3144 3145 // Check if this is a TLS variable or global register. 3146 if (VD->getTLSKind() != VarDecl::TLS_None || 3147 VD->hasAttr<OMPThreadPrivateDeclAttr>() || 3148 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3149 !VD->isLocalVarDecl())) 3150 continue; 3151 3152 // If the used several times in the allocate directive, the same allocator 3153 // must be used. 3154 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD, 3155 AllocatorKind, Allocator)) 3156 continue; 3157 3158 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++ 3159 // If a list item has a static storage type, the allocator expression in the 3160 // allocator clause must be a constant expression that evaluates to one of 3161 // the predefined memory allocator values. 3162 if (Allocator && VD->hasGlobalStorage()) { 3163 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) { 3164 Diag(Allocator->getExprLoc(), 3165 diag::err_omp_expected_predefined_allocator) 3166 << Allocator->getSourceRange(); 3167 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 3168 VarDecl::DeclarationOnly; 3169 Diag(VD->getLocation(), 3170 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3171 << VD; 3172 continue; 3173 } 3174 } 3175 3176 Vars.push_back(RefExpr); 3177 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, 3178 DE->getSourceRange()); 3179 } 3180 if (Vars.empty()) 3181 return nullptr; 3182 if (!Owner) 3183 Owner = getCurLexicalContext(); 3184 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses); 3185 D->setAccess(AS_public); 3186 Owner->addDecl(D); 3187 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3188 } 3189 3190 Sema::DeclGroupPtrTy 3191 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 3192 ArrayRef<OMPClause *> ClauseList) { 3193 OMPRequiresDecl *D = nullptr; 3194 if (!CurContext->isFileContext()) { 3195 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 3196 } else { 3197 D = CheckOMPRequiresDecl(Loc, ClauseList); 3198 if (D) { 3199 CurContext->addDecl(D); 3200 DSAStack->addRequiresDecl(D); 3201 } 3202 } 3203 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3204 } 3205 3206 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc, 3207 OpenMPDirectiveKind DKind, 3208 ArrayRef<StringRef> Assumptions, 3209 bool SkippedClauses) { 3210 if (!SkippedClauses && Assumptions.empty()) 3211 Diag(Loc, diag::err_omp_no_clause_for_directive) 3212 << llvm::omp::getAllAssumeClauseOptions() 3213 << llvm::omp::getOpenMPDirectiveName(DKind); 3214 3215 auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc); 3216 if (DKind == llvm::omp::Directive::OMPD_begin_assumes) { 3217 OMPAssumeScoped.push_back(AA); 3218 return; 3219 } 3220 3221 // Global assumes without assumption clauses are ignored. 3222 if (Assumptions.empty()) 3223 return; 3224 3225 assert(DKind == llvm::omp::Directive::OMPD_assumes && 3226 "Unexpected omp assumption directive!"); 3227 OMPAssumeGlobal.push_back(AA); 3228 3229 // The OMPAssumeGlobal scope above will take care of new declarations but 3230 // we also want to apply the assumption to existing ones, e.g., to 3231 // declarations in included headers. To this end, we traverse all existing 3232 // declaration contexts and annotate function declarations here. 3233 SmallVector<DeclContext *, 8> DeclContexts; 3234 auto *Ctx = CurContext; 3235 while (Ctx->getLexicalParent()) 3236 Ctx = Ctx->getLexicalParent(); 3237 DeclContexts.push_back(Ctx); 3238 while (!DeclContexts.empty()) { 3239 DeclContext *DC = DeclContexts.pop_back_val(); 3240 for (auto *SubDC : DC->decls()) { 3241 if (SubDC->isInvalidDecl()) 3242 continue; 3243 if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) { 3244 DeclContexts.push_back(CTD->getTemplatedDecl()); 3245 for (auto *S : CTD->specializations()) 3246 DeclContexts.push_back(S); 3247 continue; 3248 } 3249 if (auto *DC = dyn_cast<DeclContext>(SubDC)) 3250 DeclContexts.push_back(DC); 3251 if (auto *F = dyn_cast<FunctionDecl>(SubDC)) { 3252 F->addAttr(AA); 3253 continue; 3254 } 3255 } 3256 } 3257 } 3258 3259 void Sema::ActOnOpenMPEndAssumesDirective() { 3260 assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!"); 3261 OMPAssumeScoped.pop_back(); 3262 } 3263 3264 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 3265 ArrayRef<OMPClause *> ClauseList) { 3266 /// For target specific clauses, the requires directive cannot be 3267 /// specified after the handling of any of the target regions in the 3268 /// current compilation unit. 3269 ArrayRef<SourceLocation> TargetLocations = 3270 DSAStack->getEncounteredTargetLocs(); 3271 SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc(); 3272 if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) { 3273 for (const OMPClause *CNew : ClauseList) { 3274 // Check if any of the requires clauses affect target regions. 3275 if (isa<OMPUnifiedSharedMemoryClause>(CNew) || 3276 isa<OMPUnifiedAddressClause>(CNew) || 3277 isa<OMPReverseOffloadClause>(CNew) || 3278 isa<OMPDynamicAllocatorsClause>(CNew)) { 3279 Diag(Loc, diag::err_omp_directive_before_requires) 3280 << "target" << getOpenMPClauseName(CNew->getClauseKind()); 3281 for (SourceLocation TargetLoc : TargetLocations) { 3282 Diag(TargetLoc, diag::note_omp_requires_encountered_directive) 3283 << "target"; 3284 } 3285 } else if (!AtomicLoc.isInvalid() && 3286 isa<OMPAtomicDefaultMemOrderClause>(CNew)) { 3287 Diag(Loc, diag::err_omp_directive_before_requires) 3288 << "atomic" << getOpenMPClauseName(CNew->getClauseKind()); 3289 Diag(AtomicLoc, diag::note_omp_requires_encountered_directive) 3290 << "atomic"; 3291 } 3292 } 3293 } 3294 3295 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 3296 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 3297 ClauseList); 3298 return nullptr; 3299 } 3300 3301 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 3302 const ValueDecl *D, 3303 const DSAStackTy::DSAVarData &DVar, 3304 bool IsLoopIterVar) { 3305 if (DVar.RefExpr) { 3306 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 3307 << getOpenMPClauseName(DVar.CKind); 3308 return; 3309 } 3310 enum { 3311 PDSA_StaticMemberShared, 3312 PDSA_StaticLocalVarShared, 3313 PDSA_LoopIterVarPrivate, 3314 PDSA_LoopIterVarLinear, 3315 PDSA_LoopIterVarLastprivate, 3316 PDSA_ConstVarShared, 3317 PDSA_GlobalVarShared, 3318 PDSA_TaskVarFirstprivate, 3319 PDSA_LocalVarPrivate, 3320 PDSA_Implicit 3321 } Reason = PDSA_Implicit; 3322 bool ReportHint = false; 3323 auto ReportLoc = D->getLocation(); 3324 auto *VD = dyn_cast<VarDecl>(D); 3325 if (IsLoopIterVar) { 3326 if (DVar.CKind == OMPC_private) 3327 Reason = PDSA_LoopIterVarPrivate; 3328 else if (DVar.CKind == OMPC_lastprivate) 3329 Reason = PDSA_LoopIterVarLastprivate; 3330 else 3331 Reason = PDSA_LoopIterVarLinear; 3332 } else if (isOpenMPTaskingDirective(DVar.DKind) && 3333 DVar.CKind == OMPC_firstprivate) { 3334 Reason = PDSA_TaskVarFirstprivate; 3335 ReportLoc = DVar.ImplicitDSALoc; 3336 } else if (VD && VD->isStaticLocal()) 3337 Reason = PDSA_StaticLocalVarShared; 3338 else if (VD && VD->isStaticDataMember()) 3339 Reason = PDSA_StaticMemberShared; 3340 else if (VD && VD->isFileVarDecl()) 3341 Reason = PDSA_GlobalVarShared; 3342 else if (D->getType().isConstant(SemaRef.getASTContext())) 3343 Reason = PDSA_ConstVarShared; 3344 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 3345 ReportHint = true; 3346 Reason = PDSA_LocalVarPrivate; 3347 } 3348 if (Reason != PDSA_Implicit) { 3349 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 3350 << Reason << ReportHint 3351 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 3352 } else if (DVar.ImplicitDSALoc.isValid()) { 3353 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 3354 << getOpenMPClauseName(DVar.CKind); 3355 } 3356 } 3357 3358 static OpenMPMapClauseKind 3359 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M, 3360 bool IsAggregateOrDeclareTarget) { 3361 OpenMPMapClauseKind Kind = OMPC_MAP_unknown; 3362 switch (M) { 3363 case OMPC_DEFAULTMAP_MODIFIER_alloc: 3364 Kind = OMPC_MAP_alloc; 3365 break; 3366 case OMPC_DEFAULTMAP_MODIFIER_to: 3367 Kind = OMPC_MAP_to; 3368 break; 3369 case OMPC_DEFAULTMAP_MODIFIER_from: 3370 Kind = OMPC_MAP_from; 3371 break; 3372 case OMPC_DEFAULTMAP_MODIFIER_tofrom: 3373 Kind = OMPC_MAP_tofrom; 3374 break; 3375 case OMPC_DEFAULTMAP_MODIFIER_present: 3376 // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description] 3377 // If implicit-behavior is present, each variable referenced in the 3378 // construct in the category specified by variable-category is treated as if 3379 // it had been listed in a map clause with the map-type of alloc and 3380 // map-type-modifier of present. 3381 Kind = OMPC_MAP_alloc; 3382 break; 3383 case OMPC_DEFAULTMAP_MODIFIER_firstprivate: 3384 case OMPC_DEFAULTMAP_MODIFIER_last: 3385 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3386 case OMPC_DEFAULTMAP_MODIFIER_none: 3387 case OMPC_DEFAULTMAP_MODIFIER_default: 3388 case OMPC_DEFAULTMAP_MODIFIER_unknown: 3389 // IsAggregateOrDeclareTarget could be true if: 3390 // 1. the implicit behavior for aggregate is tofrom 3391 // 2. it's a declare target link 3392 if (IsAggregateOrDeclareTarget) { 3393 Kind = OMPC_MAP_tofrom; 3394 break; 3395 } 3396 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3397 } 3398 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known"); 3399 return Kind; 3400 } 3401 3402 namespace { 3403 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 3404 DSAStackTy *Stack; 3405 Sema &SemaRef; 3406 bool ErrorFound = false; 3407 bool TryCaptureCXXThisMembers = false; 3408 CapturedStmt *CS = nullptr; 3409 const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 3410 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 3411 llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete]; 3412 llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 3413 ImplicitMapModifier[DefaultmapKindNum]; 3414 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 3415 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 3416 3417 void VisitSubCaptures(OMPExecutableDirective *S) { 3418 // Check implicitly captured variables. 3419 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 3420 return; 3421 if (S->getDirectiveKind() == OMPD_atomic || 3422 S->getDirectiveKind() == OMPD_critical || 3423 S->getDirectiveKind() == OMPD_section || 3424 S->getDirectiveKind() == OMPD_master || 3425 isOpenMPLoopTransformationDirective(S->getDirectiveKind())) { 3426 Visit(S->getAssociatedStmt()); 3427 return; 3428 } 3429 visitSubCaptures(S->getInnermostCapturedStmt()); 3430 // Try to capture inner this->member references to generate correct mappings 3431 // and diagnostics. 3432 if (TryCaptureCXXThisMembers || 3433 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3434 llvm::any_of(S->getInnermostCapturedStmt()->captures(), 3435 [](const CapturedStmt::Capture &C) { 3436 return C.capturesThis(); 3437 }))) { 3438 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers; 3439 TryCaptureCXXThisMembers = true; 3440 Visit(S->getInnermostCapturedStmt()->getCapturedStmt()); 3441 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers; 3442 } 3443 // In tasks firstprivates are not captured anymore, need to analyze them 3444 // explicitly. 3445 if (isOpenMPTaskingDirective(S->getDirectiveKind()) && 3446 !isOpenMPTaskLoopDirective(S->getDirectiveKind())) { 3447 for (OMPClause *C : S->clauses()) 3448 if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) { 3449 for (Expr *Ref : FC->varlists()) 3450 Visit(Ref); 3451 } 3452 } 3453 } 3454 3455 public: 3456 void VisitDeclRefExpr(DeclRefExpr *E) { 3457 if (TryCaptureCXXThisMembers || E->isTypeDependent() || 3458 E->isValueDependent() || E->containsUnexpandedParameterPack() || 3459 E->isInstantiationDependent()) 3460 return; 3461 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 3462 // Check the datasharing rules for the expressions in the clauses. 3463 if (!CS) { 3464 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3465 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) { 3466 Visit(CED->getInit()); 3467 return; 3468 } 3469 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD)) 3470 // Do not analyze internal variables and do not enclose them into 3471 // implicit clauses. 3472 return; 3473 VD = VD->getCanonicalDecl(); 3474 // Skip internally declared variables. 3475 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) && 3476 !Stack->isImplicitTaskFirstprivate(VD)) 3477 return; 3478 // Skip allocators in uses_allocators clauses. 3479 if (Stack->isUsesAllocatorsDecl(VD).hasValue()) 3480 return; 3481 3482 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 3483 // Check if the variable has explicit DSA set and stop analysis if it so. 3484 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 3485 return; 3486 3487 // Skip internally declared static variables. 3488 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3489 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 3490 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) && 3491 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 3492 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) && 3493 !Stack->isImplicitTaskFirstprivate(VD)) 3494 return; 3495 3496 SourceLocation ELoc = E->getExprLoc(); 3497 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3498 // The default(none) clause requires that each variable that is referenced 3499 // in the construct, and does not have a predetermined data-sharing 3500 // attribute, must have its data-sharing attribute explicitly determined 3501 // by being listed in a data-sharing attribute clause. 3502 if (DVar.CKind == OMPC_unknown && 3503 (Stack->getDefaultDSA() == DSA_none || 3504 Stack->getDefaultDSA() == DSA_firstprivate) && 3505 isImplicitOrExplicitTaskingRegion(DKind) && 3506 VarsWithInheritedDSA.count(VD) == 0) { 3507 bool InheritedDSA = Stack->getDefaultDSA() == DSA_none; 3508 if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) { 3509 DSAStackTy::DSAVarData DVar = 3510 Stack->getImplicitDSA(VD, /*FromParent=*/false); 3511 InheritedDSA = DVar.CKind == OMPC_unknown; 3512 } 3513 if (InheritedDSA) 3514 VarsWithInheritedDSA[VD] = E; 3515 return; 3516 } 3517 3518 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description] 3519 // If implicit-behavior is none, each variable referenced in the 3520 // construct that does not have a predetermined data-sharing attribute 3521 // and does not appear in a to or link clause on a declare target 3522 // directive must be listed in a data-mapping attribute clause, a 3523 // data-haring attribute clause (including a data-sharing attribute 3524 // clause on a combined construct where target. is one of the 3525 // constituent constructs), or an is_device_ptr clause. 3526 OpenMPDefaultmapClauseKind ClauseKind = 3527 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD); 3528 if (SemaRef.getLangOpts().OpenMP >= 50) { 3529 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) == 3530 OMPC_DEFAULTMAP_MODIFIER_none; 3531 if (DVar.CKind == OMPC_unknown && IsModifierNone && 3532 VarsWithInheritedDSA.count(VD) == 0 && !Res) { 3533 // Only check for data-mapping attribute and is_device_ptr here 3534 // since we have already make sure that the declaration does not 3535 // have a data-sharing attribute above 3536 if (!Stack->checkMappableExprComponentListsForDecl( 3537 VD, /*CurrentRegionOnly=*/true, 3538 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef 3539 MapExprComponents, 3540 OpenMPClauseKind) { 3541 auto MI = MapExprComponents.rbegin(); 3542 auto ME = MapExprComponents.rend(); 3543 return MI != ME && MI->getAssociatedDeclaration() == VD; 3544 })) { 3545 VarsWithInheritedDSA[VD] = E; 3546 return; 3547 } 3548 } 3549 } 3550 if (SemaRef.getLangOpts().OpenMP > 50) { 3551 bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) == 3552 OMPC_DEFAULTMAP_MODIFIER_present; 3553 if (IsModifierPresent) { 3554 if (llvm::find(ImplicitMapModifier[ClauseKind], 3555 OMPC_MAP_MODIFIER_present) == 3556 std::end(ImplicitMapModifier[ClauseKind])) { 3557 ImplicitMapModifier[ClauseKind].push_back( 3558 OMPC_MAP_MODIFIER_present); 3559 } 3560 } 3561 } 3562 3563 if (isOpenMPTargetExecutionDirective(DKind) && 3564 !Stack->isLoopControlVariable(VD).first) { 3565 if (!Stack->checkMappableExprComponentListsForDecl( 3566 VD, /*CurrentRegionOnly=*/true, 3567 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef 3568 StackComponents, 3569 OpenMPClauseKind) { 3570 if (SemaRef.LangOpts.OpenMP >= 50) 3571 return !StackComponents.empty(); 3572 // Variable is used if it has been marked as an array, array 3573 // section, array shaping or the variable iself. 3574 return StackComponents.size() == 1 || 3575 std::all_of( 3576 std::next(StackComponents.rbegin()), 3577 StackComponents.rend(), 3578 [](const OMPClauseMappableExprCommon:: 3579 MappableComponent &MC) { 3580 return MC.getAssociatedDeclaration() == 3581 nullptr && 3582 (isa<OMPArraySectionExpr>( 3583 MC.getAssociatedExpression()) || 3584 isa<OMPArrayShapingExpr>( 3585 MC.getAssociatedExpression()) || 3586 isa<ArraySubscriptExpr>( 3587 MC.getAssociatedExpression())); 3588 }); 3589 })) { 3590 bool IsFirstprivate = false; 3591 // By default lambdas are captured as firstprivates. 3592 if (const auto *RD = 3593 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 3594 IsFirstprivate = RD->isLambda(); 3595 IsFirstprivate = 3596 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res); 3597 if (IsFirstprivate) { 3598 ImplicitFirstprivate.emplace_back(E); 3599 } else { 3600 OpenMPDefaultmapClauseModifier M = 3601 Stack->getDefaultmapModifier(ClauseKind); 3602 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3603 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res); 3604 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3605 } 3606 return; 3607 } 3608 } 3609 3610 // OpenMP [2.9.3.6, Restrictions, p.2] 3611 // A list item that appears in a reduction clause of the innermost 3612 // enclosing worksharing or parallel construct may not be accessed in an 3613 // explicit task. 3614 DVar = Stack->hasInnermostDSA( 3615 VD, 3616 [](OpenMPClauseKind C, bool AppliedToPointee) { 3617 return C == OMPC_reduction && !AppliedToPointee; 3618 }, 3619 [](OpenMPDirectiveKind K) { 3620 return isOpenMPParallelDirective(K) || 3621 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3622 }, 3623 /*FromParent=*/true); 3624 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3625 ErrorFound = true; 3626 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3627 reportOriginalDsa(SemaRef, Stack, VD, DVar); 3628 return; 3629 } 3630 3631 // Define implicit data-sharing attributes for task. 3632 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 3633 if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) || 3634 (Stack->getDefaultDSA() == DSA_firstprivate && 3635 DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) && 3636 !Stack->isLoopControlVariable(VD).first) { 3637 ImplicitFirstprivate.push_back(E); 3638 return; 3639 } 3640 3641 // Store implicitly used globals with declare target link for parent 3642 // target. 3643 if (!isOpenMPTargetExecutionDirective(DKind) && Res && 3644 *Res == OMPDeclareTargetDeclAttr::MT_Link) { 3645 Stack->addToParentTargetRegionLinkGlobals(E); 3646 return; 3647 } 3648 } 3649 } 3650 void VisitMemberExpr(MemberExpr *E) { 3651 if (E->isTypeDependent() || E->isValueDependent() || 3652 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 3653 return; 3654 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 3655 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3656 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) { 3657 if (!FD) 3658 return; 3659 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 3660 // Check if the variable has explicit DSA set and stop analysis if it 3661 // so. 3662 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 3663 return; 3664 3665 if (isOpenMPTargetExecutionDirective(DKind) && 3666 !Stack->isLoopControlVariable(FD).first && 3667 !Stack->checkMappableExprComponentListsForDecl( 3668 FD, /*CurrentRegionOnly=*/true, 3669 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 3670 StackComponents, 3671 OpenMPClauseKind) { 3672 return isa<CXXThisExpr>( 3673 cast<MemberExpr>( 3674 StackComponents.back().getAssociatedExpression()) 3675 ->getBase() 3676 ->IgnoreParens()); 3677 })) { 3678 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 3679 // A bit-field cannot appear in a map clause. 3680 // 3681 if (FD->isBitField()) 3682 return; 3683 3684 // Check to see if the member expression is referencing a class that 3685 // has already been explicitly mapped 3686 if (Stack->isClassPreviouslyMapped(TE->getType())) 3687 return; 3688 3689 OpenMPDefaultmapClauseModifier Modifier = 3690 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate); 3691 OpenMPDefaultmapClauseKind ClauseKind = 3692 getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD); 3693 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3694 Modifier, /*IsAggregateOrDeclareTarget*/ true); 3695 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3696 return; 3697 } 3698 3699 SourceLocation ELoc = E->getExprLoc(); 3700 // OpenMP [2.9.3.6, Restrictions, p.2] 3701 // A list item that appears in a reduction clause of the innermost 3702 // enclosing worksharing or parallel construct may not be accessed in 3703 // an explicit task. 3704 DVar = Stack->hasInnermostDSA( 3705 FD, 3706 [](OpenMPClauseKind C, bool AppliedToPointee) { 3707 return C == OMPC_reduction && !AppliedToPointee; 3708 }, 3709 [](OpenMPDirectiveKind K) { 3710 return isOpenMPParallelDirective(K) || 3711 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3712 }, 3713 /*FromParent=*/true); 3714 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3715 ErrorFound = true; 3716 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3717 reportOriginalDsa(SemaRef, Stack, FD, DVar); 3718 return; 3719 } 3720 3721 // Define implicit data-sharing attributes for task. 3722 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 3723 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 3724 !Stack->isLoopControlVariable(FD).first) { 3725 // Check if there is a captured expression for the current field in the 3726 // region. Do not mark it as firstprivate unless there is no captured 3727 // expression. 3728 // TODO: try to make it firstprivate. 3729 if (DVar.CKind != OMPC_unknown) 3730 ImplicitFirstprivate.push_back(E); 3731 } 3732 return; 3733 } 3734 if (isOpenMPTargetExecutionDirective(DKind)) { 3735 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 3736 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 3737 Stack->getCurrentDirective(), 3738 /*NoDiagnose=*/true)) 3739 return; 3740 const auto *VD = cast<ValueDecl>( 3741 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 3742 if (!Stack->checkMappableExprComponentListsForDecl( 3743 VD, /*CurrentRegionOnly=*/true, 3744 [&CurComponents]( 3745 OMPClauseMappableExprCommon::MappableExprComponentListRef 3746 StackComponents, 3747 OpenMPClauseKind) { 3748 auto CCI = CurComponents.rbegin(); 3749 auto CCE = CurComponents.rend(); 3750 for (const auto &SC : llvm::reverse(StackComponents)) { 3751 // Do both expressions have the same kind? 3752 if (CCI->getAssociatedExpression()->getStmtClass() != 3753 SC.getAssociatedExpression()->getStmtClass()) 3754 if (!((isa<OMPArraySectionExpr>( 3755 SC.getAssociatedExpression()) || 3756 isa<OMPArrayShapingExpr>( 3757 SC.getAssociatedExpression())) && 3758 isa<ArraySubscriptExpr>( 3759 CCI->getAssociatedExpression()))) 3760 return false; 3761 3762 const Decl *CCD = CCI->getAssociatedDeclaration(); 3763 const Decl *SCD = SC.getAssociatedDeclaration(); 3764 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 3765 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 3766 if (SCD != CCD) 3767 return false; 3768 std::advance(CCI, 1); 3769 if (CCI == CCE) 3770 break; 3771 } 3772 return true; 3773 })) { 3774 Visit(E->getBase()); 3775 } 3776 } else if (!TryCaptureCXXThisMembers) { 3777 Visit(E->getBase()); 3778 } 3779 } 3780 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 3781 for (OMPClause *C : S->clauses()) { 3782 // Skip analysis of arguments of implicitly defined firstprivate clause 3783 // for task|target directives. 3784 // Skip analysis of arguments of implicitly defined map clause for target 3785 // directives. 3786 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 3787 C->isImplicit() && 3788 !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) { 3789 for (Stmt *CC : C->children()) { 3790 if (CC) 3791 Visit(CC); 3792 } 3793 } 3794 } 3795 // Check implicitly captured variables. 3796 VisitSubCaptures(S); 3797 } 3798 3799 void VisitOMPTileDirective(OMPTileDirective *S) { 3800 // #pragma omp tile does not introduce data sharing. 3801 VisitStmt(S); 3802 } 3803 3804 void VisitStmt(Stmt *S) { 3805 for (Stmt *C : S->children()) { 3806 if (C) { 3807 // Check implicitly captured variables in the task-based directives to 3808 // check if they must be firstprivatized. 3809 Visit(C); 3810 } 3811 } 3812 } 3813 3814 void visitSubCaptures(CapturedStmt *S) { 3815 for (const CapturedStmt::Capture &Cap : S->captures()) { 3816 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy()) 3817 continue; 3818 VarDecl *VD = Cap.getCapturedVar(); 3819 // Do not try to map the variable if it or its sub-component was mapped 3820 // already. 3821 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3822 Stack->checkMappableExprComponentListsForDecl( 3823 VD, /*CurrentRegionOnly=*/true, 3824 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 3825 OpenMPClauseKind) { return true; })) 3826 continue; 3827 DeclRefExpr *DRE = buildDeclRefExpr( 3828 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context), 3829 Cap.getLocation(), /*RefersToCapture=*/true); 3830 Visit(DRE); 3831 } 3832 } 3833 bool isErrorFound() const { return ErrorFound; } 3834 ArrayRef<Expr *> getImplicitFirstprivate() const { 3835 return ImplicitFirstprivate; 3836 } 3837 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK, 3838 OpenMPMapClauseKind MK) const { 3839 return ImplicitMap[DK][MK]; 3840 } 3841 ArrayRef<OpenMPMapModifierKind> 3842 getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const { 3843 return ImplicitMapModifier[Kind]; 3844 } 3845 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 3846 return VarsWithInheritedDSA; 3847 } 3848 3849 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 3850 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) { 3851 // Process declare target link variables for the target directives. 3852 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) { 3853 for (DeclRefExpr *E : Stack->getLinkGlobals()) 3854 Visit(E); 3855 } 3856 } 3857 }; 3858 } // namespace 3859 3860 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 3861 switch (DKind) { 3862 case OMPD_parallel: 3863 case OMPD_parallel_for: 3864 case OMPD_parallel_for_simd: 3865 case OMPD_parallel_sections: 3866 case OMPD_parallel_master: 3867 case OMPD_teams: 3868 case OMPD_teams_distribute: 3869 case OMPD_teams_distribute_simd: { 3870 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3871 QualType KmpInt32PtrTy = 3872 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3873 Sema::CapturedParamNameType Params[] = { 3874 std::make_pair(".global_tid.", KmpInt32PtrTy), 3875 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3876 std::make_pair(StringRef(), QualType()) // __context with shared vars 3877 }; 3878 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3879 Params); 3880 break; 3881 } 3882 case OMPD_target_teams: 3883 case OMPD_target_parallel: 3884 case OMPD_target_parallel_for: 3885 case OMPD_target_parallel_for_simd: 3886 case OMPD_target_teams_distribute: 3887 case OMPD_target_teams_distribute_simd: { 3888 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3889 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3890 QualType KmpInt32PtrTy = 3891 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3892 QualType Args[] = {VoidPtrTy}; 3893 FunctionProtoType::ExtProtoInfo EPI; 3894 EPI.Variadic = true; 3895 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3896 Sema::CapturedParamNameType Params[] = { 3897 std::make_pair(".global_tid.", KmpInt32Ty), 3898 std::make_pair(".part_id.", KmpInt32PtrTy), 3899 std::make_pair(".privates.", VoidPtrTy), 3900 std::make_pair( 3901 ".copy_fn.", 3902 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3903 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3904 std::make_pair(StringRef(), QualType()) // __context with shared vars 3905 }; 3906 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3907 Params, /*OpenMPCaptureLevel=*/0); 3908 // Mark this captured region as inlined, because we don't use outlined 3909 // function directly. 3910 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3911 AlwaysInlineAttr::CreateImplicit( 3912 Context, {}, AttributeCommonInfo::AS_Keyword, 3913 AlwaysInlineAttr::Keyword_forceinline)); 3914 Sema::CapturedParamNameType ParamsTarget[] = { 3915 std::make_pair(StringRef(), QualType()) // __context with shared vars 3916 }; 3917 // Start a captured region for 'target' with no implicit parameters. 3918 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3919 ParamsTarget, /*OpenMPCaptureLevel=*/1); 3920 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 3921 std::make_pair(".global_tid.", KmpInt32PtrTy), 3922 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3923 std::make_pair(StringRef(), QualType()) // __context with shared vars 3924 }; 3925 // Start a captured region for 'teams' or 'parallel'. Both regions have 3926 // the same implicit parameters. 3927 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3928 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2); 3929 break; 3930 } 3931 case OMPD_target: 3932 case OMPD_target_simd: { 3933 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3934 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3935 QualType KmpInt32PtrTy = 3936 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3937 QualType Args[] = {VoidPtrTy}; 3938 FunctionProtoType::ExtProtoInfo EPI; 3939 EPI.Variadic = true; 3940 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3941 Sema::CapturedParamNameType Params[] = { 3942 std::make_pair(".global_tid.", KmpInt32Ty), 3943 std::make_pair(".part_id.", KmpInt32PtrTy), 3944 std::make_pair(".privates.", VoidPtrTy), 3945 std::make_pair( 3946 ".copy_fn.", 3947 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3948 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3949 std::make_pair(StringRef(), QualType()) // __context with shared vars 3950 }; 3951 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3952 Params, /*OpenMPCaptureLevel=*/0); 3953 // Mark this captured region as inlined, because we don't use outlined 3954 // function directly. 3955 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3956 AlwaysInlineAttr::CreateImplicit( 3957 Context, {}, AttributeCommonInfo::AS_Keyword, 3958 AlwaysInlineAttr::Keyword_forceinline)); 3959 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3960 std::make_pair(StringRef(), QualType()), 3961 /*OpenMPCaptureLevel=*/1); 3962 break; 3963 } 3964 case OMPD_atomic: 3965 case OMPD_critical: 3966 case OMPD_section: 3967 case OMPD_master: 3968 case OMPD_tile: 3969 break; 3970 case OMPD_simd: 3971 case OMPD_for: 3972 case OMPD_for_simd: 3973 case OMPD_sections: 3974 case OMPD_single: 3975 case OMPD_taskgroup: 3976 case OMPD_distribute: 3977 case OMPD_distribute_simd: 3978 case OMPD_ordered: 3979 case OMPD_target_data: { 3980 Sema::CapturedParamNameType Params[] = { 3981 std::make_pair(StringRef(), QualType()) // __context with shared vars 3982 }; 3983 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3984 Params); 3985 break; 3986 } 3987 case OMPD_task: { 3988 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3989 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3990 QualType KmpInt32PtrTy = 3991 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3992 QualType Args[] = {VoidPtrTy}; 3993 FunctionProtoType::ExtProtoInfo EPI; 3994 EPI.Variadic = true; 3995 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3996 Sema::CapturedParamNameType Params[] = { 3997 std::make_pair(".global_tid.", KmpInt32Ty), 3998 std::make_pair(".part_id.", KmpInt32PtrTy), 3999 std::make_pair(".privates.", VoidPtrTy), 4000 std::make_pair( 4001 ".copy_fn.", 4002 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4003 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4004 std::make_pair(StringRef(), QualType()) // __context with shared vars 4005 }; 4006 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4007 Params); 4008 // Mark this captured region as inlined, because we don't use outlined 4009 // function directly. 4010 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4011 AlwaysInlineAttr::CreateImplicit( 4012 Context, {}, AttributeCommonInfo::AS_Keyword, 4013 AlwaysInlineAttr::Keyword_forceinline)); 4014 break; 4015 } 4016 case OMPD_taskloop: 4017 case OMPD_taskloop_simd: 4018 case OMPD_master_taskloop: 4019 case OMPD_master_taskloop_simd: { 4020 QualType KmpInt32Ty = 4021 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 4022 .withConst(); 4023 QualType KmpUInt64Ty = 4024 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 4025 .withConst(); 4026 QualType KmpInt64Ty = 4027 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 4028 .withConst(); 4029 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4030 QualType KmpInt32PtrTy = 4031 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4032 QualType Args[] = {VoidPtrTy}; 4033 FunctionProtoType::ExtProtoInfo EPI; 4034 EPI.Variadic = true; 4035 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4036 Sema::CapturedParamNameType Params[] = { 4037 std::make_pair(".global_tid.", KmpInt32Ty), 4038 std::make_pair(".part_id.", KmpInt32PtrTy), 4039 std::make_pair(".privates.", VoidPtrTy), 4040 std::make_pair( 4041 ".copy_fn.", 4042 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4043 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4044 std::make_pair(".lb.", KmpUInt64Ty), 4045 std::make_pair(".ub.", KmpUInt64Ty), 4046 std::make_pair(".st.", KmpInt64Ty), 4047 std::make_pair(".liter.", KmpInt32Ty), 4048 std::make_pair(".reductions.", VoidPtrTy), 4049 std::make_pair(StringRef(), QualType()) // __context with shared vars 4050 }; 4051 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4052 Params); 4053 // Mark this captured region as inlined, because we don't use outlined 4054 // function directly. 4055 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4056 AlwaysInlineAttr::CreateImplicit( 4057 Context, {}, AttributeCommonInfo::AS_Keyword, 4058 AlwaysInlineAttr::Keyword_forceinline)); 4059 break; 4060 } 4061 case OMPD_parallel_master_taskloop: 4062 case OMPD_parallel_master_taskloop_simd: { 4063 QualType KmpInt32Ty = 4064 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 4065 .withConst(); 4066 QualType KmpUInt64Ty = 4067 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 4068 .withConst(); 4069 QualType KmpInt64Ty = 4070 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 4071 .withConst(); 4072 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4073 QualType KmpInt32PtrTy = 4074 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4075 Sema::CapturedParamNameType ParamsParallel[] = { 4076 std::make_pair(".global_tid.", KmpInt32PtrTy), 4077 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4078 std::make_pair(StringRef(), QualType()) // __context with shared vars 4079 }; 4080 // Start a captured region for 'parallel'. 4081 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4082 ParamsParallel, /*OpenMPCaptureLevel=*/0); 4083 QualType Args[] = {VoidPtrTy}; 4084 FunctionProtoType::ExtProtoInfo EPI; 4085 EPI.Variadic = true; 4086 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4087 Sema::CapturedParamNameType Params[] = { 4088 std::make_pair(".global_tid.", KmpInt32Ty), 4089 std::make_pair(".part_id.", KmpInt32PtrTy), 4090 std::make_pair(".privates.", VoidPtrTy), 4091 std::make_pair( 4092 ".copy_fn.", 4093 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4094 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4095 std::make_pair(".lb.", KmpUInt64Ty), 4096 std::make_pair(".ub.", KmpUInt64Ty), 4097 std::make_pair(".st.", KmpInt64Ty), 4098 std::make_pair(".liter.", KmpInt32Ty), 4099 std::make_pair(".reductions.", VoidPtrTy), 4100 std::make_pair(StringRef(), QualType()) // __context with shared vars 4101 }; 4102 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4103 Params, /*OpenMPCaptureLevel=*/1); 4104 // Mark this captured region as inlined, because we don't use outlined 4105 // function directly. 4106 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4107 AlwaysInlineAttr::CreateImplicit( 4108 Context, {}, AttributeCommonInfo::AS_Keyword, 4109 AlwaysInlineAttr::Keyword_forceinline)); 4110 break; 4111 } 4112 case OMPD_distribute_parallel_for_simd: 4113 case OMPD_distribute_parallel_for: { 4114 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4115 QualType KmpInt32PtrTy = 4116 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4117 Sema::CapturedParamNameType Params[] = { 4118 std::make_pair(".global_tid.", KmpInt32PtrTy), 4119 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4120 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4121 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4122 std::make_pair(StringRef(), QualType()) // __context with shared vars 4123 }; 4124 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4125 Params); 4126 break; 4127 } 4128 case OMPD_target_teams_distribute_parallel_for: 4129 case OMPD_target_teams_distribute_parallel_for_simd: { 4130 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4131 QualType KmpInt32PtrTy = 4132 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4133 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4134 4135 QualType Args[] = {VoidPtrTy}; 4136 FunctionProtoType::ExtProtoInfo EPI; 4137 EPI.Variadic = true; 4138 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4139 Sema::CapturedParamNameType Params[] = { 4140 std::make_pair(".global_tid.", KmpInt32Ty), 4141 std::make_pair(".part_id.", KmpInt32PtrTy), 4142 std::make_pair(".privates.", VoidPtrTy), 4143 std::make_pair( 4144 ".copy_fn.", 4145 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4146 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4147 std::make_pair(StringRef(), QualType()) // __context with shared vars 4148 }; 4149 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4150 Params, /*OpenMPCaptureLevel=*/0); 4151 // Mark this captured region as inlined, because we don't use outlined 4152 // function directly. 4153 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4154 AlwaysInlineAttr::CreateImplicit( 4155 Context, {}, AttributeCommonInfo::AS_Keyword, 4156 AlwaysInlineAttr::Keyword_forceinline)); 4157 Sema::CapturedParamNameType ParamsTarget[] = { 4158 std::make_pair(StringRef(), QualType()) // __context with shared vars 4159 }; 4160 // Start a captured region for 'target' with no implicit parameters. 4161 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4162 ParamsTarget, /*OpenMPCaptureLevel=*/1); 4163 4164 Sema::CapturedParamNameType ParamsTeams[] = { 4165 std::make_pair(".global_tid.", KmpInt32PtrTy), 4166 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4167 std::make_pair(StringRef(), QualType()) // __context with shared vars 4168 }; 4169 // Start a captured region for 'target' with no implicit parameters. 4170 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4171 ParamsTeams, /*OpenMPCaptureLevel=*/2); 4172 4173 Sema::CapturedParamNameType ParamsParallel[] = { 4174 std::make_pair(".global_tid.", KmpInt32PtrTy), 4175 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4176 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4177 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4178 std::make_pair(StringRef(), QualType()) // __context with shared vars 4179 }; 4180 // Start a captured region for 'teams' or 'parallel'. Both regions have 4181 // the same implicit parameters. 4182 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4183 ParamsParallel, /*OpenMPCaptureLevel=*/3); 4184 break; 4185 } 4186 4187 case OMPD_teams_distribute_parallel_for: 4188 case OMPD_teams_distribute_parallel_for_simd: { 4189 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4190 QualType KmpInt32PtrTy = 4191 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4192 4193 Sema::CapturedParamNameType ParamsTeams[] = { 4194 std::make_pair(".global_tid.", KmpInt32PtrTy), 4195 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4196 std::make_pair(StringRef(), QualType()) // __context with shared vars 4197 }; 4198 // Start a captured region for 'target' with no implicit parameters. 4199 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4200 ParamsTeams, /*OpenMPCaptureLevel=*/0); 4201 4202 Sema::CapturedParamNameType ParamsParallel[] = { 4203 std::make_pair(".global_tid.", KmpInt32PtrTy), 4204 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4205 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4206 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4207 std::make_pair(StringRef(), QualType()) // __context with shared vars 4208 }; 4209 // Start a captured region for 'teams' or 'parallel'. Both regions have 4210 // the same implicit parameters. 4211 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4212 ParamsParallel, /*OpenMPCaptureLevel=*/1); 4213 break; 4214 } 4215 case OMPD_target_update: 4216 case OMPD_target_enter_data: 4217 case OMPD_target_exit_data: { 4218 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4219 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4220 QualType KmpInt32PtrTy = 4221 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4222 QualType Args[] = {VoidPtrTy}; 4223 FunctionProtoType::ExtProtoInfo EPI; 4224 EPI.Variadic = true; 4225 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4226 Sema::CapturedParamNameType Params[] = { 4227 std::make_pair(".global_tid.", KmpInt32Ty), 4228 std::make_pair(".part_id.", KmpInt32PtrTy), 4229 std::make_pair(".privates.", VoidPtrTy), 4230 std::make_pair( 4231 ".copy_fn.", 4232 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4233 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4234 std::make_pair(StringRef(), QualType()) // __context with shared vars 4235 }; 4236 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4237 Params); 4238 // Mark this captured region as inlined, because we don't use outlined 4239 // function directly. 4240 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4241 AlwaysInlineAttr::CreateImplicit( 4242 Context, {}, AttributeCommonInfo::AS_Keyword, 4243 AlwaysInlineAttr::Keyword_forceinline)); 4244 break; 4245 } 4246 case OMPD_threadprivate: 4247 case OMPD_allocate: 4248 case OMPD_taskyield: 4249 case OMPD_barrier: 4250 case OMPD_taskwait: 4251 case OMPD_cancellation_point: 4252 case OMPD_cancel: 4253 case OMPD_flush: 4254 case OMPD_depobj: 4255 case OMPD_scan: 4256 case OMPD_declare_reduction: 4257 case OMPD_declare_mapper: 4258 case OMPD_declare_simd: 4259 case OMPD_declare_target: 4260 case OMPD_end_declare_target: 4261 case OMPD_requires: 4262 case OMPD_declare_variant: 4263 case OMPD_begin_declare_variant: 4264 case OMPD_end_declare_variant: 4265 llvm_unreachable("OpenMP Directive is not allowed"); 4266 case OMPD_unknown: 4267 default: 4268 llvm_unreachable("Unknown OpenMP directive"); 4269 } 4270 DSAStack->setContext(CurContext); 4271 } 4272 4273 int Sema::getNumberOfConstructScopes(unsigned Level) const { 4274 return getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 4275 } 4276 4277 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 4278 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4279 getOpenMPCaptureRegions(CaptureRegions, DKind); 4280 return CaptureRegions.size(); 4281 } 4282 4283 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 4284 Expr *CaptureExpr, bool WithInit, 4285 bool AsExpression) { 4286 assert(CaptureExpr); 4287 ASTContext &C = S.getASTContext(); 4288 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 4289 QualType Ty = Init->getType(); 4290 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 4291 if (S.getLangOpts().CPlusPlus) { 4292 Ty = C.getLValueReferenceType(Ty); 4293 } else { 4294 Ty = C.getPointerType(Ty); 4295 ExprResult Res = 4296 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 4297 if (!Res.isUsable()) 4298 return nullptr; 4299 Init = Res.get(); 4300 } 4301 WithInit = true; 4302 } 4303 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 4304 CaptureExpr->getBeginLoc()); 4305 if (!WithInit) 4306 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 4307 S.CurContext->addHiddenDecl(CED); 4308 Sema::TentativeAnalysisScope Trap(S); 4309 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 4310 return CED; 4311 } 4312 4313 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 4314 bool WithInit) { 4315 OMPCapturedExprDecl *CD; 4316 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 4317 CD = cast<OMPCapturedExprDecl>(VD); 4318 else 4319 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 4320 /*AsExpression=*/false); 4321 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4322 CaptureExpr->getExprLoc()); 4323 } 4324 4325 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 4326 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 4327 if (!Ref) { 4328 OMPCapturedExprDecl *CD = buildCaptureDecl( 4329 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 4330 /*WithInit=*/true, /*AsExpression=*/true); 4331 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4332 CaptureExpr->getExprLoc()); 4333 } 4334 ExprResult Res = Ref; 4335 if (!S.getLangOpts().CPlusPlus && 4336 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 4337 Ref->getType()->isPointerType()) { 4338 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 4339 if (!Res.isUsable()) 4340 return ExprError(); 4341 } 4342 return S.DefaultLvalueConversion(Res.get()); 4343 } 4344 4345 namespace { 4346 // OpenMP directives parsed in this section are represented as a 4347 // CapturedStatement with an associated statement. If a syntax error 4348 // is detected during the parsing of the associated statement, the 4349 // compiler must abort processing and close the CapturedStatement. 4350 // 4351 // Combined directives such as 'target parallel' have more than one 4352 // nested CapturedStatements. This RAII ensures that we unwind out 4353 // of all the nested CapturedStatements when an error is found. 4354 class CaptureRegionUnwinderRAII { 4355 private: 4356 Sema &S; 4357 bool &ErrorFound; 4358 OpenMPDirectiveKind DKind = OMPD_unknown; 4359 4360 public: 4361 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 4362 OpenMPDirectiveKind DKind) 4363 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 4364 ~CaptureRegionUnwinderRAII() { 4365 if (ErrorFound) { 4366 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 4367 while (--ThisCaptureLevel >= 0) 4368 S.ActOnCapturedRegionError(); 4369 } 4370 } 4371 }; 4372 } // namespace 4373 4374 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) { 4375 // Capture variables captured by reference in lambdas for target-based 4376 // directives. 4377 if (!CurContext->isDependentContext() && 4378 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) || 4379 isOpenMPTargetDataManagementDirective( 4380 DSAStack->getCurrentDirective()))) { 4381 QualType Type = V->getType(); 4382 if (const auto *RD = Type.getCanonicalType() 4383 .getNonReferenceType() 4384 ->getAsCXXRecordDecl()) { 4385 bool SavedForceCaptureByReferenceInTargetExecutable = 4386 DSAStack->isForceCaptureByReferenceInTargetExecutable(); 4387 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4388 /*V=*/true); 4389 if (RD->isLambda()) { 4390 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 4391 FieldDecl *ThisCapture; 4392 RD->getCaptureFields(Captures, ThisCapture); 4393 for (const LambdaCapture &LC : RD->captures()) { 4394 if (LC.getCaptureKind() == LCK_ByRef) { 4395 VarDecl *VD = LC.getCapturedVar(); 4396 DeclContext *VDC = VD->getDeclContext(); 4397 if (!VDC->Encloses(CurContext)) 4398 continue; 4399 MarkVariableReferenced(LC.getLocation(), VD); 4400 } else if (LC.getCaptureKind() == LCK_This) { 4401 QualType ThisTy = getCurrentThisType(); 4402 if (!ThisTy.isNull() && 4403 Context.typesAreCompatible(ThisTy, ThisCapture->getType())) 4404 CheckCXXThisCapture(LC.getLocation()); 4405 } 4406 } 4407 } 4408 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4409 SavedForceCaptureByReferenceInTargetExecutable); 4410 } 4411 } 4412 } 4413 4414 static bool checkOrderedOrderSpecified(Sema &S, 4415 const ArrayRef<OMPClause *> Clauses) { 4416 const OMPOrderedClause *Ordered = nullptr; 4417 const OMPOrderClause *Order = nullptr; 4418 4419 for (const OMPClause *Clause : Clauses) { 4420 if (Clause->getClauseKind() == OMPC_ordered) 4421 Ordered = cast<OMPOrderedClause>(Clause); 4422 else if (Clause->getClauseKind() == OMPC_order) { 4423 Order = cast<OMPOrderClause>(Clause); 4424 if (Order->getKind() != OMPC_ORDER_concurrent) 4425 Order = nullptr; 4426 } 4427 if (Ordered && Order) 4428 break; 4429 } 4430 4431 if (Ordered && Order) { 4432 S.Diag(Order->getKindKwLoc(), 4433 diag::err_omp_simple_clause_incompatible_with_ordered) 4434 << getOpenMPClauseName(OMPC_order) 4435 << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent) 4436 << SourceRange(Order->getBeginLoc(), Order->getEndLoc()); 4437 S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param) 4438 << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc()); 4439 return true; 4440 } 4441 return false; 4442 } 4443 4444 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 4445 ArrayRef<OMPClause *> Clauses) { 4446 if (DSAStack->getCurrentDirective() == OMPD_atomic || 4447 DSAStack->getCurrentDirective() == OMPD_critical || 4448 DSAStack->getCurrentDirective() == OMPD_section || 4449 DSAStack->getCurrentDirective() == OMPD_master) 4450 return S; 4451 4452 bool ErrorFound = false; 4453 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 4454 *this, ErrorFound, DSAStack->getCurrentDirective()); 4455 if (!S.isUsable()) { 4456 ErrorFound = true; 4457 return StmtError(); 4458 } 4459 4460 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4461 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 4462 OMPOrderedClause *OC = nullptr; 4463 OMPScheduleClause *SC = nullptr; 4464 SmallVector<const OMPLinearClause *, 4> LCs; 4465 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 4466 // This is required for proper codegen. 4467 for (OMPClause *Clause : Clauses) { 4468 if (!LangOpts.OpenMPSimd && 4469 isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 4470 Clause->getClauseKind() == OMPC_in_reduction) { 4471 // Capture taskgroup task_reduction descriptors inside the tasking regions 4472 // with the corresponding in_reduction items. 4473 auto *IRC = cast<OMPInReductionClause>(Clause); 4474 for (Expr *E : IRC->taskgroup_descriptors()) 4475 if (E) 4476 MarkDeclarationsReferencedInExpr(E); 4477 } 4478 if (isOpenMPPrivate(Clause->getClauseKind()) || 4479 Clause->getClauseKind() == OMPC_copyprivate || 4480 (getLangOpts().OpenMPUseTLS && 4481 getASTContext().getTargetInfo().isTLSSupported() && 4482 Clause->getClauseKind() == OMPC_copyin)) { 4483 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 4484 // Mark all variables in private list clauses as used in inner region. 4485 for (Stmt *VarRef : Clause->children()) { 4486 if (auto *E = cast_or_null<Expr>(VarRef)) { 4487 MarkDeclarationsReferencedInExpr(E); 4488 } 4489 } 4490 DSAStack->setForceVarCapturing(/*V=*/false); 4491 } else if (isOpenMPLoopTransformationDirective( 4492 DSAStack->getCurrentDirective())) { 4493 assert(CaptureRegions.empty() && 4494 "No captured regions in loop transformation directives."); 4495 } else if (CaptureRegions.size() > 1 || 4496 CaptureRegions.back() != OMPD_unknown) { 4497 if (auto *C = OMPClauseWithPreInit::get(Clause)) 4498 PICs.push_back(C); 4499 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 4500 if (Expr *E = C->getPostUpdateExpr()) 4501 MarkDeclarationsReferencedInExpr(E); 4502 } 4503 } 4504 if (Clause->getClauseKind() == OMPC_schedule) 4505 SC = cast<OMPScheduleClause>(Clause); 4506 else if (Clause->getClauseKind() == OMPC_ordered) 4507 OC = cast<OMPOrderedClause>(Clause); 4508 else if (Clause->getClauseKind() == OMPC_linear) 4509 LCs.push_back(cast<OMPLinearClause>(Clause)); 4510 } 4511 // Capture allocator expressions if used. 4512 for (Expr *E : DSAStack->getInnerAllocators()) 4513 MarkDeclarationsReferencedInExpr(E); 4514 // OpenMP, 2.7.1 Loop Construct, Restrictions 4515 // The nonmonotonic modifier cannot be specified if an ordered clause is 4516 // specified. 4517 if (SC && 4518 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 4519 SC->getSecondScheduleModifier() == 4520 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 4521 OC) { 4522 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 4523 ? SC->getFirstScheduleModifierLoc() 4524 : SC->getSecondScheduleModifierLoc(), 4525 diag::err_omp_simple_clause_incompatible_with_ordered) 4526 << getOpenMPClauseName(OMPC_schedule) 4527 << getOpenMPSimpleClauseTypeName(OMPC_schedule, 4528 OMPC_SCHEDULE_MODIFIER_nonmonotonic) 4529 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4530 ErrorFound = true; 4531 } 4532 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions. 4533 // If an order(concurrent) clause is present, an ordered clause may not appear 4534 // on the same directive. 4535 if (checkOrderedOrderSpecified(*this, Clauses)) 4536 ErrorFound = true; 4537 if (!LCs.empty() && OC && OC->getNumForLoops()) { 4538 for (const OMPLinearClause *C : LCs) { 4539 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 4540 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4541 } 4542 ErrorFound = true; 4543 } 4544 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 4545 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 4546 OC->getNumForLoops()) { 4547 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 4548 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 4549 ErrorFound = true; 4550 } 4551 if (ErrorFound) { 4552 return StmtError(); 4553 } 4554 StmtResult SR = S; 4555 unsigned CompletedRegions = 0; 4556 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 4557 // Mark all variables in private list clauses as used in inner region. 4558 // Required for proper codegen of combined directives. 4559 // TODO: add processing for other clauses. 4560 if (ThisCaptureRegion != OMPD_unknown) { 4561 for (const clang::OMPClauseWithPreInit *C : PICs) { 4562 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 4563 // Find the particular capture region for the clause if the 4564 // directive is a combined one with multiple capture regions. 4565 // If the directive is not a combined one, the capture region 4566 // associated with the clause is OMPD_unknown and is generated 4567 // only once. 4568 if (CaptureRegion == ThisCaptureRegion || 4569 CaptureRegion == OMPD_unknown) { 4570 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 4571 for (Decl *D : DS->decls()) 4572 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 4573 } 4574 } 4575 } 4576 } 4577 if (ThisCaptureRegion == OMPD_target) { 4578 // Capture allocator traits in the target region. They are used implicitly 4579 // and, thus, are not captured by default. 4580 for (OMPClause *C : Clauses) { 4581 if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) { 4582 for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End; 4583 ++I) { 4584 OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I); 4585 if (Expr *E = D.AllocatorTraits) 4586 MarkDeclarationsReferencedInExpr(E); 4587 } 4588 continue; 4589 } 4590 } 4591 } 4592 if (++CompletedRegions == CaptureRegions.size()) 4593 DSAStack->setBodyComplete(); 4594 SR = ActOnCapturedRegionEnd(SR.get()); 4595 } 4596 return SR; 4597 } 4598 4599 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 4600 OpenMPDirectiveKind CancelRegion, 4601 SourceLocation StartLoc) { 4602 // CancelRegion is only needed for cancel and cancellation_point. 4603 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 4604 return false; 4605 4606 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 4607 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 4608 return false; 4609 4610 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 4611 << getOpenMPDirectiveName(CancelRegion); 4612 return true; 4613 } 4614 4615 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 4616 OpenMPDirectiveKind CurrentRegion, 4617 const DeclarationNameInfo &CurrentName, 4618 OpenMPDirectiveKind CancelRegion, 4619 SourceLocation StartLoc) { 4620 if (Stack->getCurScope()) { 4621 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 4622 OpenMPDirectiveKind OffendingRegion = ParentRegion; 4623 bool NestingProhibited = false; 4624 bool CloseNesting = true; 4625 bool OrphanSeen = false; 4626 enum { 4627 NoRecommend, 4628 ShouldBeInParallelRegion, 4629 ShouldBeInOrderedRegion, 4630 ShouldBeInTargetRegion, 4631 ShouldBeInTeamsRegion, 4632 ShouldBeInLoopSimdRegion, 4633 } Recommend = NoRecommend; 4634 if (isOpenMPSimdDirective(ParentRegion) && 4635 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) || 4636 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered && 4637 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic && 4638 CurrentRegion != OMPD_scan))) { 4639 // OpenMP [2.16, Nesting of Regions] 4640 // OpenMP constructs may not be nested inside a simd region. 4641 // OpenMP [2.8.1,simd Construct, Restrictions] 4642 // An ordered construct with the simd clause is the only OpenMP 4643 // construct that can appear in the simd region. 4644 // Allowing a SIMD construct nested in another SIMD construct is an 4645 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 4646 // message. 4647 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions] 4648 // The only OpenMP constructs that can be encountered during execution of 4649 // a simd region are the atomic construct, the loop construct, the simd 4650 // construct and the ordered construct with the simd clause. 4651 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 4652 ? diag::err_omp_prohibited_region_simd 4653 : diag::warn_omp_nesting_simd) 4654 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0); 4655 return CurrentRegion != OMPD_simd; 4656 } 4657 if (ParentRegion == OMPD_atomic) { 4658 // OpenMP [2.16, Nesting of Regions] 4659 // OpenMP constructs may not be nested inside an atomic region. 4660 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 4661 return true; 4662 } 4663 if (CurrentRegion == OMPD_section) { 4664 // OpenMP [2.7.2, sections Construct, Restrictions] 4665 // Orphaned section directives are prohibited. That is, the section 4666 // directives must appear within the sections construct and must not be 4667 // encountered elsewhere in the sections region. 4668 if (ParentRegion != OMPD_sections && 4669 ParentRegion != OMPD_parallel_sections) { 4670 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 4671 << (ParentRegion != OMPD_unknown) 4672 << getOpenMPDirectiveName(ParentRegion); 4673 return true; 4674 } 4675 return false; 4676 } 4677 // Allow some constructs (except teams and cancellation constructs) to be 4678 // orphaned (they could be used in functions, called from OpenMP regions 4679 // with the required preconditions). 4680 if (ParentRegion == OMPD_unknown && 4681 !isOpenMPNestingTeamsDirective(CurrentRegion) && 4682 CurrentRegion != OMPD_cancellation_point && 4683 CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan) 4684 return false; 4685 if (CurrentRegion == OMPD_cancellation_point || 4686 CurrentRegion == OMPD_cancel) { 4687 // OpenMP [2.16, Nesting of Regions] 4688 // A cancellation point construct for which construct-type-clause is 4689 // taskgroup must be nested inside a task construct. A cancellation 4690 // point construct for which construct-type-clause is not taskgroup must 4691 // be closely nested inside an OpenMP construct that matches the type 4692 // specified in construct-type-clause. 4693 // A cancel construct for which construct-type-clause is taskgroup must be 4694 // nested inside a task construct. A cancel construct for which 4695 // construct-type-clause is not taskgroup must be closely nested inside an 4696 // OpenMP construct that matches the type specified in 4697 // construct-type-clause. 4698 NestingProhibited = 4699 !((CancelRegion == OMPD_parallel && 4700 (ParentRegion == OMPD_parallel || 4701 ParentRegion == OMPD_target_parallel)) || 4702 (CancelRegion == OMPD_for && 4703 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 4704 ParentRegion == OMPD_target_parallel_for || 4705 ParentRegion == OMPD_distribute_parallel_for || 4706 ParentRegion == OMPD_teams_distribute_parallel_for || 4707 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 4708 (CancelRegion == OMPD_taskgroup && 4709 (ParentRegion == OMPD_task || 4710 (SemaRef.getLangOpts().OpenMP >= 50 && 4711 (ParentRegion == OMPD_taskloop || 4712 ParentRegion == OMPD_master_taskloop || 4713 ParentRegion == OMPD_parallel_master_taskloop)))) || 4714 (CancelRegion == OMPD_sections && 4715 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 4716 ParentRegion == OMPD_parallel_sections))); 4717 OrphanSeen = ParentRegion == OMPD_unknown; 4718 } else if (CurrentRegion == OMPD_master) { 4719 // OpenMP [2.16, Nesting of Regions] 4720 // A master region may not be closely nested inside a worksharing, 4721 // atomic, or explicit task region. 4722 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4723 isOpenMPTaskingDirective(ParentRegion); 4724 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 4725 // OpenMP [2.16, Nesting of Regions] 4726 // A critical region may not be nested (closely or otherwise) inside a 4727 // critical region with the same name. Note that this restriction is not 4728 // sufficient to prevent deadlock. 4729 SourceLocation PreviousCriticalLoc; 4730 bool DeadLock = Stack->hasDirective( 4731 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 4732 const DeclarationNameInfo &DNI, 4733 SourceLocation Loc) { 4734 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 4735 PreviousCriticalLoc = Loc; 4736 return true; 4737 } 4738 return false; 4739 }, 4740 false /* skip top directive */); 4741 if (DeadLock) { 4742 SemaRef.Diag(StartLoc, 4743 diag::err_omp_prohibited_region_critical_same_name) 4744 << CurrentName.getName(); 4745 if (PreviousCriticalLoc.isValid()) 4746 SemaRef.Diag(PreviousCriticalLoc, 4747 diag::note_omp_previous_critical_region); 4748 return true; 4749 } 4750 } else if (CurrentRegion == OMPD_barrier) { 4751 // OpenMP [2.16, Nesting of Regions] 4752 // A barrier region may not be closely nested inside a worksharing, 4753 // explicit task, critical, ordered, atomic, or master region. 4754 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4755 isOpenMPTaskingDirective(ParentRegion) || 4756 ParentRegion == OMPD_master || 4757 ParentRegion == OMPD_parallel_master || 4758 ParentRegion == OMPD_critical || 4759 ParentRegion == OMPD_ordered; 4760 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 4761 !isOpenMPParallelDirective(CurrentRegion) && 4762 !isOpenMPTeamsDirective(CurrentRegion)) { 4763 // OpenMP [2.16, Nesting of Regions] 4764 // A worksharing region may not be closely nested inside a worksharing, 4765 // explicit task, critical, ordered, atomic, or master region. 4766 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4767 isOpenMPTaskingDirective(ParentRegion) || 4768 ParentRegion == OMPD_master || 4769 ParentRegion == OMPD_parallel_master || 4770 ParentRegion == OMPD_critical || 4771 ParentRegion == OMPD_ordered; 4772 Recommend = ShouldBeInParallelRegion; 4773 } else if (CurrentRegion == OMPD_ordered) { 4774 // OpenMP [2.16, Nesting of Regions] 4775 // An ordered region may not be closely nested inside a critical, 4776 // atomic, or explicit task region. 4777 // An ordered region must be closely nested inside a loop region (or 4778 // parallel loop region) with an ordered clause. 4779 // OpenMP [2.8.1,simd Construct, Restrictions] 4780 // An ordered construct with the simd clause is the only OpenMP construct 4781 // that can appear in the simd region. 4782 NestingProhibited = ParentRegion == OMPD_critical || 4783 isOpenMPTaskingDirective(ParentRegion) || 4784 !(isOpenMPSimdDirective(ParentRegion) || 4785 Stack->isParentOrderedRegion()); 4786 Recommend = ShouldBeInOrderedRegion; 4787 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 4788 // OpenMP [2.16, Nesting of Regions] 4789 // If specified, a teams construct must be contained within a target 4790 // construct. 4791 NestingProhibited = 4792 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) || 4793 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown && 4794 ParentRegion != OMPD_target); 4795 OrphanSeen = ParentRegion == OMPD_unknown; 4796 Recommend = ShouldBeInTargetRegion; 4797 } else if (CurrentRegion == OMPD_scan) { 4798 // OpenMP [2.16, Nesting of Regions] 4799 // If specified, a teams construct must be contained within a target 4800 // construct. 4801 NestingProhibited = 4802 SemaRef.LangOpts.OpenMP < 50 || 4803 (ParentRegion != OMPD_simd && ParentRegion != OMPD_for && 4804 ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for && 4805 ParentRegion != OMPD_parallel_for_simd); 4806 OrphanSeen = ParentRegion == OMPD_unknown; 4807 Recommend = ShouldBeInLoopSimdRegion; 4808 } 4809 if (!NestingProhibited && 4810 !isOpenMPTargetExecutionDirective(CurrentRegion) && 4811 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 4812 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 4813 // OpenMP [2.16, Nesting of Regions] 4814 // distribute, parallel, parallel sections, parallel workshare, and the 4815 // parallel loop and parallel loop SIMD constructs are the only OpenMP 4816 // constructs that can be closely nested in the teams region. 4817 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 4818 !isOpenMPDistributeDirective(CurrentRegion); 4819 Recommend = ShouldBeInParallelRegion; 4820 } 4821 if (!NestingProhibited && 4822 isOpenMPNestingDistributeDirective(CurrentRegion)) { 4823 // OpenMP 4.5 [2.17 Nesting of Regions] 4824 // The region associated with the distribute construct must be strictly 4825 // nested inside a teams region 4826 NestingProhibited = 4827 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 4828 Recommend = ShouldBeInTeamsRegion; 4829 } 4830 if (!NestingProhibited && 4831 (isOpenMPTargetExecutionDirective(CurrentRegion) || 4832 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 4833 // OpenMP 4.5 [2.17 Nesting of Regions] 4834 // If a target, target update, target data, target enter data, or 4835 // target exit data construct is encountered during execution of a 4836 // target region, the behavior is unspecified. 4837 NestingProhibited = Stack->hasDirective( 4838 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 4839 SourceLocation) { 4840 if (isOpenMPTargetExecutionDirective(K)) { 4841 OffendingRegion = K; 4842 return true; 4843 } 4844 return false; 4845 }, 4846 false /* don't skip top directive */); 4847 CloseNesting = false; 4848 } 4849 if (NestingProhibited) { 4850 if (OrphanSeen) { 4851 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 4852 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 4853 } else { 4854 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 4855 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 4856 << Recommend << getOpenMPDirectiveName(CurrentRegion); 4857 } 4858 return true; 4859 } 4860 } 4861 return false; 4862 } 4863 4864 struct Kind2Unsigned { 4865 using argument_type = OpenMPDirectiveKind; 4866 unsigned operator()(argument_type DK) { return unsigned(DK); } 4867 }; 4868 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 4869 ArrayRef<OMPClause *> Clauses, 4870 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 4871 bool ErrorFound = false; 4872 unsigned NamedModifiersNumber = 0; 4873 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers; 4874 FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1); 4875 SmallVector<SourceLocation, 4> NameModifierLoc; 4876 for (const OMPClause *C : Clauses) { 4877 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 4878 // At most one if clause without a directive-name-modifier can appear on 4879 // the directive. 4880 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 4881 if (FoundNameModifiers[CurNM]) { 4882 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 4883 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 4884 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 4885 ErrorFound = true; 4886 } else if (CurNM != OMPD_unknown) { 4887 NameModifierLoc.push_back(IC->getNameModifierLoc()); 4888 ++NamedModifiersNumber; 4889 } 4890 FoundNameModifiers[CurNM] = IC; 4891 if (CurNM == OMPD_unknown) 4892 continue; 4893 // Check if the specified name modifier is allowed for the current 4894 // directive. 4895 // At most one if clause with the particular directive-name-modifier can 4896 // appear on the directive. 4897 bool MatchFound = false; 4898 for (auto NM : AllowedNameModifiers) { 4899 if (CurNM == NM) { 4900 MatchFound = true; 4901 break; 4902 } 4903 } 4904 if (!MatchFound) { 4905 S.Diag(IC->getNameModifierLoc(), 4906 diag::err_omp_wrong_if_directive_name_modifier) 4907 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 4908 ErrorFound = true; 4909 } 4910 } 4911 } 4912 // If any if clause on the directive includes a directive-name-modifier then 4913 // all if clauses on the directive must include a directive-name-modifier. 4914 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 4915 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 4916 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 4917 diag::err_omp_no_more_if_clause); 4918 } else { 4919 std::string Values; 4920 std::string Sep(", "); 4921 unsigned AllowedCnt = 0; 4922 unsigned TotalAllowedNum = 4923 AllowedNameModifiers.size() - NamedModifiersNumber; 4924 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 4925 ++Cnt) { 4926 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 4927 if (!FoundNameModifiers[NM]) { 4928 Values += "'"; 4929 Values += getOpenMPDirectiveName(NM); 4930 Values += "'"; 4931 if (AllowedCnt + 2 == TotalAllowedNum) 4932 Values += " or "; 4933 else if (AllowedCnt + 1 != TotalAllowedNum) 4934 Values += Sep; 4935 ++AllowedCnt; 4936 } 4937 } 4938 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 4939 diag::err_omp_unnamed_if_clause) 4940 << (TotalAllowedNum > 1) << Values; 4941 } 4942 for (SourceLocation Loc : NameModifierLoc) { 4943 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 4944 } 4945 ErrorFound = true; 4946 } 4947 return ErrorFound; 4948 } 4949 4950 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr, 4951 SourceLocation &ELoc, 4952 SourceRange &ERange, 4953 bool AllowArraySection) { 4954 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 4955 RefExpr->containsUnexpandedParameterPack()) 4956 return std::make_pair(nullptr, true); 4957 4958 // OpenMP [3.1, C/C++] 4959 // A list item is a variable name. 4960 // OpenMP [2.9.3.3, Restrictions, p.1] 4961 // A variable that is part of another variable (as an array or 4962 // structure element) cannot appear in a private clause. 4963 RefExpr = RefExpr->IgnoreParens(); 4964 enum { 4965 NoArrayExpr = -1, 4966 ArraySubscript = 0, 4967 OMPArraySection = 1 4968 } IsArrayExpr = NoArrayExpr; 4969 if (AllowArraySection) { 4970 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 4971 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 4972 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 4973 Base = TempASE->getBase()->IgnoreParenImpCasts(); 4974 RefExpr = Base; 4975 IsArrayExpr = ArraySubscript; 4976 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 4977 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 4978 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 4979 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 4980 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 4981 Base = TempASE->getBase()->IgnoreParenImpCasts(); 4982 RefExpr = Base; 4983 IsArrayExpr = OMPArraySection; 4984 } 4985 } 4986 ELoc = RefExpr->getExprLoc(); 4987 ERange = RefExpr->getSourceRange(); 4988 RefExpr = RefExpr->IgnoreParenImpCasts(); 4989 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 4990 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 4991 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 4992 (S.getCurrentThisType().isNull() || !ME || 4993 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 4994 !isa<FieldDecl>(ME->getMemberDecl()))) { 4995 if (IsArrayExpr != NoArrayExpr) { 4996 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 4997 << ERange; 4998 } else { 4999 S.Diag(ELoc, 5000 AllowArraySection 5001 ? diag::err_omp_expected_var_name_member_expr_or_array_item 5002 : diag::err_omp_expected_var_name_member_expr) 5003 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 5004 } 5005 return std::make_pair(nullptr, false); 5006 } 5007 return std::make_pair( 5008 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 5009 } 5010 5011 namespace { 5012 /// Checks if the allocator is used in uses_allocators clause to be allowed in 5013 /// target regions. 5014 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> { 5015 DSAStackTy *S = nullptr; 5016 5017 public: 5018 bool VisitDeclRefExpr(const DeclRefExpr *E) { 5019 return S->isUsesAllocatorsDecl(E->getDecl()) 5020 .getValueOr( 5021 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 5022 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait; 5023 } 5024 bool VisitStmt(const Stmt *S) { 5025 for (const Stmt *Child : S->children()) { 5026 if (Child && Visit(Child)) 5027 return true; 5028 } 5029 return false; 5030 } 5031 explicit AllocatorChecker(DSAStackTy *S) : S(S) {} 5032 }; 5033 } // namespace 5034 5035 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 5036 ArrayRef<OMPClause *> Clauses) { 5037 assert(!S.CurContext->isDependentContext() && 5038 "Expected non-dependent context."); 5039 auto AllocateRange = 5040 llvm::make_filter_range(Clauses, OMPAllocateClause::classof); 5041 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> 5042 DeclToCopy; 5043 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) { 5044 return isOpenMPPrivate(C->getClauseKind()); 5045 }); 5046 for (OMPClause *Cl : PrivateRange) { 5047 MutableArrayRef<Expr *>::iterator I, It, Et; 5048 if (Cl->getClauseKind() == OMPC_private) { 5049 auto *PC = cast<OMPPrivateClause>(Cl); 5050 I = PC->private_copies().begin(); 5051 It = PC->varlist_begin(); 5052 Et = PC->varlist_end(); 5053 } else if (Cl->getClauseKind() == OMPC_firstprivate) { 5054 auto *PC = cast<OMPFirstprivateClause>(Cl); 5055 I = PC->private_copies().begin(); 5056 It = PC->varlist_begin(); 5057 Et = PC->varlist_end(); 5058 } else if (Cl->getClauseKind() == OMPC_lastprivate) { 5059 auto *PC = cast<OMPLastprivateClause>(Cl); 5060 I = PC->private_copies().begin(); 5061 It = PC->varlist_begin(); 5062 Et = PC->varlist_end(); 5063 } else if (Cl->getClauseKind() == OMPC_linear) { 5064 auto *PC = cast<OMPLinearClause>(Cl); 5065 I = PC->privates().begin(); 5066 It = PC->varlist_begin(); 5067 Et = PC->varlist_end(); 5068 } else if (Cl->getClauseKind() == OMPC_reduction) { 5069 auto *PC = cast<OMPReductionClause>(Cl); 5070 I = PC->privates().begin(); 5071 It = PC->varlist_begin(); 5072 Et = PC->varlist_end(); 5073 } else if (Cl->getClauseKind() == OMPC_task_reduction) { 5074 auto *PC = cast<OMPTaskReductionClause>(Cl); 5075 I = PC->privates().begin(); 5076 It = PC->varlist_begin(); 5077 Et = PC->varlist_end(); 5078 } else if (Cl->getClauseKind() == OMPC_in_reduction) { 5079 auto *PC = cast<OMPInReductionClause>(Cl); 5080 I = PC->privates().begin(); 5081 It = PC->varlist_begin(); 5082 Et = PC->varlist_end(); 5083 } else { 5084 llvm_unreachable("Expected private clause."); 5085 } 5086 for (Expr *E : llvm::make_range(It, Et)) { 5087 if (!*I) { 5088 ++I; 5089 continue; 5090 } 5091 SourceLocation ELoc; 5092 SourceRange ERange; 5093 Expr *SimpleRefExpr = E; 5094 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 5095 /*AllowArraySection=*/true); 5096 DeclToCopy.try_emplace(Res.first, 5097 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl())); 5098 ++I; 5099 } 5100 } 5101 for (OMPClause *C : AllocateRange) { 5102 auto *AC = cast<OMPAllocateClause>(C); 5103 if (S.getLangOpts().OpenMP >= 50 && 5104 !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() && 5105 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 5106 AC->getAllocator()) { 5107 Expr *Allocator = AC->getAllocator(); 5108 // OpenMP, 2.12.5 target Construct 5109 // Memory allocators that do not appear in a uses_allocators clause cannot 5110 // appear as an allocator in an allocate clause or be used in the target 5111 // region unless a requires directive with the dynamic_allocators clause 5112 // is present in the same compilation unit. 5113 AllocatorChecker Checker(Stack); 5114 if (Checker.Visit(Allocator)) 5115 S.Diag(Allocator->getExprLoc(), 5116 diag::err_omp_allocator_not_in_uses_allocators) 5117 << Allocator->getSourceRange(); 5118 } 5119 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 5120 getAllocatorKind(S, Stack, AC->getAllocator()); 5121 // OpenMP, 2.11.4 allocate Clause, Restrictions. 5122 // For task, taskloop or target directives, allocation requests to memory 5123 // allocators with the trait access set to thread result in unspecified 5124 // behavior. 5125 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc && 5126 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 5127 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) { 5128 S.Diag(AC->getAllocator()->getExprLoc(), 5129 diag::warn_omp_allocate_thread_on_task_target_directive) 5130 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 5131 } 5132 for (Expr *E : AC->varlists()) { 5133 SourceLocation ELoc; 5134 SourceRange ERange; 5135 Expr *SimpleRefExpr = E; 5136 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange); 5137 ValueDecl *VD = Res.first; 5138 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false); 5139 if (!isOpenMPPrivate(Data.CKind)) { 5140 S.Diag(E->getExprLoc(), 5141 diag::err_omp_expected_private_copy_for_allocate); 5142 continue; 5143 } 5144 VarDecl *PrivateVD = DeclToCopy[VD]; 5145 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD, 5146 AllocatorKind, AC->getAllocator())) 5147 continue; 5148 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(), 5149 E->getSourceRange()); 5150 } 5151 } 5152 } 5153 5154 StmtResult Sema::ActOnOpenMPExecutableDirective( 5155 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 5156 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 5157 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5158 StmtResult Res = StmtError(); 5159 // First check CancelRegion which is then used in checkNestingOfRegions. 5160 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 5161 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 5162 StartLoc)) 5163 return StmtError(); 5164 5165 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 5166 VarsWithInheritedDSAType VarsWithInheritedDSA; 5167 bool ErrorFound = false; 5168 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 5169 if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic && 5170 Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master && 5171 !isOpenMPLoopTransformationDirective(Kind)) { 5172 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5173 5174 // Check default data sharing attributes for referenced variables. 5175 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 5176 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 5177 Stmt *S = AStmt; 5178 while (--ThisCaptureLevel >= 0) 5179 S = cast<CapturedStmt>(S)->getCapturedStmt(); 5180 DSAChecker.Visit(S); 5181 if (!isOpenMPTargetDataManagementDirective(Kind) && 5182 !isOpenMPTaskingDirective(Kind)) { 5183 // Visit subcaptures to generate implicit clauses for captured vars. 5184 auto *CS = cast<CapturedStmt>(AStmt); 5185 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 5186 getOpenMPCaptureRegions(CaptureRegions, Kind); 5187 // Ignore outer tasking regions for target directives. 5188 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task) 5189 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 5190 DSAChecker.visitSubCaptures(CS); 5191 } 5192 if (DSAChecker.isErrorFound()) 5193 return StmtError(); 5194 // Generate list of implicitly defined firstprivate variables. 5195 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 5196 5197 SmallVector<Expr *, 4> ImplicitFirstprivates( 5198 DSAChecker.getImplicitFirstprivate().begin(), 5199 DSAChecker.getImplicitFirstprivate().end()); 5200 const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 5201 SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete]; 5202 SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 5203 ImplicitMapModifiers[DefaultmapKindNum]; 5204 SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> 5205 ImplicitMapModifiersLoc[DefaultmapKindNum]; 5206 // Get the original location of present modifier from Defaultmap clause. 5207 SourceLocation PresentModifierLocs[DefaultmapKindNum]; 5208 for (OMPClause *C : Clauses) { 5209 if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C)) 5210 if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present) 5211 PresentModifierLocs[DMC->getDefaultmapKind()] = 5212 DMC->getDefaultmapModifierLoc(); 5213 } 5214 for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) { 5215 auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC); 5216 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) { 5217 ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap( 5218 Kind, static_cast<OpenMPMapClauseKind>(I)); 5219 ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end()); 5220 } 5221 ArrayRef<OpenMPMapModifierKind> ImplicitModifier = 5222 DSAChecker.getImplicitMapModifier(Kind); 5223 ImplicitMapModifiers[VC].append(ImplicitModifier.begin(), 5224 ImplicitModifier.end()); 5225 std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]), 5226 ImplicitModifier.size(), PresentModifierLocs[VC]); 5227 } 5228 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 5229 for (OMPClause *C : Clauses) { 5230 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 5231 for (Expr *E : IRC->taskgroup_descriptors()) 5232 if (E) 5233 ImplicitFirstprivates.emplace_back(E); 5234 } 5235 // OpenMP 5.0, 2.10.1 task Construct 5236 // [detach clause]... The event-handle will be considered as if it was 5237 // specified on a firstprivate clause. 5238 if (auto *DC = dyn_cast<OMPDetachClause>(C)) 5239 ImplicitFirstprivates.push_back(DC->getEventHandler()); 5240 } 5241 if (!ImplicitFirstprivates.empty()) { 5242 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 5243 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 5244 SourceLocation())) { 5245 ClausesWithImplicit.push_back(Implicit); 5246 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 5247 ImplicitFirstprivates.size(); 5248 } else { 5249 ErrorFound = true; 5250 } 5251 } 5252 for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) { 5253 int ClauseKindCnt = -1; 5254 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) { 5255 ++ClauseKindCnt; 5256 if (ImplicitMap.empty()) 5257 continue; 5258 CXXScopeSpec MapperIdScopeSpec; 5259 DeclarationNameInfo MapperId; 5260 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt); 5261 if (OMPClause *Implicit = ActOnOpenMPMapClause( 5262 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I], 5263 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true, 5264 SourceLocation(), SourceLocation(), ImplicitMap, 5265 OMPVarListLocTy())) { 5266 ClausesWithImplicit.emplace_back(Implicit); 5267 ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() != 5268 ImplicitMap.size(); 5269 } else { 5270 ErrorFound = true; 5271 } 5272 } 5273 } 5274 } 5275 5276 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 5277 switch (Kind) { 5278 case OMPD_parallel: 5279 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 5280 EndLoc); 5281 AllowedNameModifiers.push_back(OMPD_parallel); 5282 break; 5283 case OMPD_simd: 5284 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5285 VarsWithInheritedDSA); 5286 if (LangOpts.OpenMP >= 50) 5287 AllowedNameModifiers.push_back(OMPD_simd); 5288 break; 5289 case OMPD_tile: 5290 Res = 5291 ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 5292 break; 5293 case OMPD_for: 5294 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5295 VarsWithInheritedDSA); 5296 break; 5297 case OMPD_for_simd: 5298 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 5299 EndLoc, VarsWithInheritedDSA); 5300 if (LangOpts.OpenMP >= 50) 5301 AllowedNameModifiers.push_back(OMPD_simd); 5302 break; 5303 case OMPD_sections: 5304 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 5305 EndLoc); 5306 break; 5307 case OMPD_section: 5308 assert(ClausesWithImplicit.empty() && 5309 "No clauses are allowed for 'omp section' directive"); 5310 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 5311 break; 5312 case OMPD_single: 5313 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 5314 EndLoc); 5315 break; 5316 case OMPD_master: 5317 assert(ClausesWithImplicit.empty() && 5318 "No clauses are allowed for 'omp master' directive"); 5319 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 5320 break; 5321 case OMPD_critical: 5322 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 5323 StartLoc, EndLoc); 5324 break; 5325 case OMPD_parallel_for: 5326 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 5327 EndLoc, VarsWithInheritedDSA); 5328 AllowedNameModifiers.push_back(OMPD_parallel); 5329 break; 5330 case OMPD_parallel_for_simd: 5331 Res = ActOnOpenMPParallelForSimdDirective( 5332 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5333 AllowedNameModifiers.push_back(OMPD_parallel); 5334 if (LangOpts.OpenMP >= 50) 5335 AllowedNameModifiers.push_back(OMPD_simd); 5336 break; 5337 case OMPD_parallel_master: 5338 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt, 5339 StartLoc, EndLoc); 5340 AllowedNameModifiers.push_back(OMPD_parallel); 5341 break; 5342 case OMPD_parallel_sections: 5343 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 5344 StartLoc, EndLoc); 5345 AllowedNameModifiers.push_back(OMPD_parallel); 5346 break; 5347 case OMPD_task: 5348 Res = 5349 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 5350 AllowedNameModifiers.push_back(OMPD_task); 5351 break; 5352 case OMPD_taskyield: 5353 assert(ClausesWithImplicit.empty() && 5354 "No clauses are allowed for 'omp taskyield' directive"); 5355 assert(AStmt == nullptr && 5356 "No associated statement allowed for 'omp taskyield' directive"); 5357 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 5358 break; 5359 case OMPD_barrier: 5360 assert(ClausesWithImplicit.empty() && 5361 "No clauses are allowed for 'omp barrier' directive"); 5362 assert(AStmt == nullptr && 5363 "No associated statement allowed for 'omp barrier' directive"); 5364 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 5365 break; 5366 case OMPD_taskwait: 5367 assert(ClausesWithImplicit.empty() && 5368 "No clauses are allowed for 'omp taskwait' directive"); 5369 assert(AStmt == nullptr && 5370 "No associated statement allowed for 'omp taskwait' directive"); 5371 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 5372 break; 5373 case OMPD_taskgroup: 5374 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 5375 EndLoc); 5376 break; 5377 case OMPD_flush: 5378 assert(AStmt == nullptr && 5379 "No associated statement allowed for 'omp flush' directive"); 5380 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 5381 break; 5382 case OMPD_depobj: 5383 assert(AStmt == nullptr && 5384 "No associated statement allowed for 'omp depobj' directive"); 5385 Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc); 5386 break; 5387 case OMPD_scan: 5388 assert(AStmt == nullptr && 5389 "No associated statement allowed for 'omp scan' directive"); 5390 Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc); 5391 break; 5392 case OMPD_ordered: 5393 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 5394 EndLoc); 5395 break; 5396 case OMPD_atomic: 5397 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 5398 EndLoc); 5399 break; 5400 case OMPD_teams: 5401 Res = 5402 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 5403 break; 5404 case OMPD_target: 5405 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 5406 EndLoc); 5407 AllowedNameModifiers.push_back(OMPD_target); 5408 break; 5409 case OMPD_target_parallel: 5410 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 5411 StartLoc, EndLoc); 5412 AllowedNameModifiers.push_back(OMPD_target); 5413 AllowedNameModifiers.push_back(OMPD_parallel); 5414 break; 5415 case OMPD_target_parallel_for: 5416 Res = ActOnOpenMPTargetParallelForDirective( 5417 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5418 AllowedNameModifiers.push_back(OMPD_target); 5419 AllowedNameModifiers.push_back(OMPD_parallel); 5420 break; 5421 case OMPD_cancellation_point: 5422 assert(ClausesWithImplicit.empty() && 5423 "No clauses are allowed for 'omp cancellation point' directive"); 5424 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 5425 "cancellation point' directive"); 5426 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 5427 break; 5428 case OMPD_cancel: 5429 assert(AStmt == nullptr && 5430 "No associated statement allowed for 'omp cancel' directive"); 5431 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 5432 CancelRegion); 5433 AllowedNameModifiers.push_back(OMPD_cancel); 5434 break; 5435 case OMPD_target_data: 5436 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 5437 EndLoc); 5438 AllowedNameModifiers.push_back(OMPD_target_data); 5439 break; 5440 case OMPD_target_enter_data: 5441 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 5442 EndLoc, AStmt); 5443 AllowedNameModifiers.push_back(OMPD_target_enter_data); 5444 break; 5445 case OMPD_target_exit_data: 5446 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 5447 EndLoc, AStmt); 5448 AllowedNameModifiers.push_back(OMPD_target_exit_data); 5449 break; 5450 case OMPD_taskloop: 5451 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 5452 EndLoc, VarsWithInheritedDSA); 5453 AllowedNameModifiers.push_back(OMPD_taskloop); 5454 break; 5455 case OMPD_taskloop_simd: 5456 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 5457 EndLoc, VarsWithInheritedDSA); 5458 AllowedNameModifiers.push_back(OMPD_taskloop); 5459 if (LangOpts.OpenMP >= 50) 5460 AllowedNameModifiers.push_back(OMPD_simd); 5461 break; 5462 case OMPD_master_taskloop: 5463 Res = ActOnOpenMPMasterTaskLoopDirective( 5464 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5465 AllowedNameModifiers.push_back(OMPD_taskloop); 5466 break; 5467 case OMPD_master_taskloop_simd: 5468 Res = ActOnOpenMPMasterTaskLoopSimdDirective( 5469 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5470 AllowedNameModifiers.push_back(OMPD_taskloop); 5471 if (LangOpts.OpenMP >= 50) 5472 AllowedNameModifiers.push_back(OMPD_simd); 5473 break; 5474 case OMPD_parallel_master_taskloop: 5475 Res = ActOnOpenMPParallelMasterTaskLoopDirective( 5476 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5477 AllowedNameModifiers.push_back(OMPD_taskloop); 5478 AllowedNameModifiers.push_back(OMPD_parallel); 5479 break; 5480 case OMPD_parallel_master_taskloop_simd: 5481 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective( 5482 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5483 AllowedNameModifiers.push_back(OMPD_taskloop); 5484 AllowedNameModifiers.push_back(OMPD_parallel); 5485 if (LangOpts.OpenMP >= 50) 5486 AllowedNameModifiers.push_back(OMPD_simd); 5487 break; 5488 case OMPD_distribute: 5489 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 5490 EndLoc, VarsWithInheritedDSA); 5491 break; 5492 case OMPD_target_update: 5493 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 5494 EndLoc, AStmt); 5495 AllowedNameModifiers.push_back(OMPD_target_update); 5496 break; 5497 case OMPD_distribute_parallel_for: 5498 Res = ActOnOpenMPDistributeParallelForDirective( 5499 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5500 AllowedNameModifiers.push_back(OMPD_parallel); 5501 break; 5502 case OMPD_distribute_parallel_for_simd: 5503 Res = ActOnOpenMPDistributeParallelForSimdDirective( 5504 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5505 AllowedNameModifiers.push_back(OMPD_parallel); 5506 if (LangOpts.OpenMP >= 50) 5507 AllowedNameModifiers.push_back(OMPD_simd); 5508 break; 5509 case OMPD_distribute_simd: 5510 Res = ActOnOpenMPDistributeSimdDirective( 5511 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5512 if (LangOpts.OpenMP >= 50) 5513 AllowedNameModifiers.push_back(OMPD_simd); 5514 break; 5515 case OMPD_target_parallel_for_simd: 5516 Res = ActOnOpenMPTargetParallelForSimdDirective( 5517 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5518 AllowedNameModifiers.push_back(OMPD_target); 5519 AllowedNameModifiers.push_back(OMPD_parallel); 5520 if (LangOpts.OpenMP >= 50) 5521 AllowedNameModifiers.push_back(OMPD_simd); 5522 break; 5523 case OMPD_target_simd: 5524 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 5525 EndLoc, VarsWithInheritedDSA); 5526 AllowedNameModifiers.push_back(OMPD_target); 5527 if (LangOpts.OpenMP >= 50) 5528 AllowedNameModifiers.push_back(OMPD_simd); 5529 break; 5530 case OMPD_teams_distribute: 5531 Res = ActOnOpenMPTeamsDistributeDirective( 5532 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5533 break; 5534 case OMPD_teams_distribute_simd: 5535 Res = ActOnOpenMPTeamsDistributeSimdDirective( 5536 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5537 if (LangOpts.OpenMP >= 50) 5538 AllowedNameModifiers.push_back(OMPD_simd); 5539 break; 5540 case OMPD_teams_distribute_parallel_for_simd: 5541 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 5542 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5543 AllowedNameModifiers.push_back(OMPD_parallel); 5544 if (LangOpts.OpenMP >= 50) 5545 AllowedNameModifiers.push_back(OMPD_simd); 5546 break; 5547 case OMPD_teams_distribute_parallel_for: 5548 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 5549 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5550 AllowedNameModifiers.push_back(OMPD_parallel); 5551 break; 5552 case OMPD_target_teams: 5553 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 5554 EndLoc); 5555 AllowedNameModifiers.push_back(OMPD_target); 5556 break; 5557 case OMPD_target_teams_distribute: 5558 Res = ActOnOpenMPTargetTeamsDistributeDirective( 5559 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5560 AllowedNameModifiers.push_back(OMPD_target); 5561 break; 5562 case OMPD_target_teams_distribute_parallel_for: 5563 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 5564 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5565 AllowedNameModifiers.push_back(OMPD_target); 5566 AllowedNameModifiers.push_back(OMPD_parallel); 5567 break; 5568 case OMPD_target_teams_distribute_parallel_for_simd: 5569 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 5570 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5571 AllowedNameModifiers.push_back(OMPD_target); 5572 AllowedNameModifiers.push_back(OMPD_parallel); 5573 if (LangOpts.OpenMP >= 50) 5574 AllowedNameModifiers.push_back(OMPD_simd); 5575 break; 5576 case OMPD_target_teams_distribute_simd: 5577 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 5578 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5579 AllowedNameModifiers.push_back(OMPD_target); 5580 if (LangOpts.OpenMP >= 50) 5581 AllowedNameModifiers.push_back(OMPD_simd); 5582 break; 5583 case OMPD_declare_target: 5584 case OMPD_end_declare_target: 5585 case OMPD_threadprivate: 5586 case OMPD_allocate: 5587 case OMPD_declare_reduction: 5588 case OMPD_declare_mapper: 5589 case OMPD_declare_simd: 5590 case OMPD_requires: 5591 case OMPD_declare_variant: 5592 case OMPD_begin_declare_variant: 5593 case OMPD_end_declare_variant: 5594 llvm_unreachable("OpenMP Directive is not allowed"); 5595 case OMPD_unknown: 5596 default: 5597 llvm_unreachable("Unknown OpenMP directive"); 5598 } 5599 5600 ErrorFound = Res.isInvalid() || ErrorFound; 5601 5602 // Check variables in the clauses if default(none) or 5603 // default(firstprivate) was specified. 5604 if (DSAStack->getDefaultDSA() == DSA_none || 5605 DSAStack->getDefaultDSA() == DSA_firstprivate) { 5606 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr); 5607 for (OMPClause *C : Clauses) { 5608 switch (C->getClauseKind()) { 5609 case OMPC_num_threads: 5610 case OMPC_dist_schedule: 5611 // Do not analyse if no parent teams directive. 5612 if (isOpenMPTeamsDirective(Kind)) 5613 break; 5614 continue; 5615 case OMPC_if: 5616 if (isOpenMPTeamsDirective(Kind) && 5617 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target) 5618 break; 5619 if (isOpenMPParallelDirective(Kind) && 5620 isOpenMPTaskLoopDirective(Kind) && 5621 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel) 5622 break; 5623 continue; 5624 case OMPC_schedule: 5625 case OMPC_detach: 5626 break; 5627 case OMPC_grainsize: 5628 case OMPC_num_tasks: 5629 case OMPC_final: 5630 case OMPC_priority: 5631 // Do not analyze if no parent parallel directive. 5632 if (isOpenMPParallelDirective(Kind)) 5633 break; 5634 continue; 5635 case OMPC_ordered: 5636 case OMPC_device: 5637 case OMPC_num_teams: 5638 case OMPC_thread_limit: 5639 case OMPC_hint: 5640 case OMPC_collapse: 5641 case OMPC_safelen: 5642 case OMPC_simdlen: 5643 case OMPC_sizes: 5644 case OMPC_default: 5645 case OMPC_proc_bind: 5646 case OMPC_private: 5647 case OMPC_firstprivate: 5648 case OMPC_lastprivate: 5649 case OMPC_shared: 5650 case OMPC_reduction: 5651 case OMPC_task_reduction: 5652 case OMPC_in_reduction: 5653 case OMPC_linear: 5654 case OMPC_aligned: 5655 case OMPC_copyin: 5656 case OMPC_copyprivate: 5657 case OMPC_nowait: 5658 case OMPC_untied: 5659 case OMPC_mergeable: 5660 case OMPC_allocate: 5661 case OMPC_read: 5662 case OMPC_write: 5663 case OMPC_update: 5664 case OMPC_capture: 5665 case OMPC_seq_cst: 5666 case OMPC_acq_rel: 5667 case OMPC_acquire: 5668 case OMPC_release: 5669 case OMPC_relaxed: 5670 case OMPC_depend: 5671 case OMPC_threads: 5672 case OMPC_simd: 5673 case OMPC_map: 5674 case OMPC_nogroup: 5675 case OMPC_defaultmap: 5676 case OMPC_to: 5677 case OMPC_from: 5678 case OMPC_use_device_ptr: 5679 case OMPC_use_device_addr: 5680 case OMPC_is_device_ptr: 5681 case OMPC_nontemporal: 5682 case OMPC_order: 5683 case OMPC_destroy: 5684 case OMPC_inclusive: 5685 case OMPC_exclusive: 5686 case OMPC_uses_allocators: 5687 case OMPC_affinity: 5688 continue; 5689 case OMPC_allocator: 5690 case OMPC_flush: 5691 case OMPC_depobj: 5692 case OMPC_threadprivate: 5693 case OMPC_uniform: 5694 case OMPC_unknown: 5695 case OMPC_unified_address: 5696 case OMPC_unified_shared_memory: 5697 case OMPC_reverse_offload: 5698 case OMPC_dynamic_allocators: 5699 case OMPC_atomic_default_mem_order: 5700 case OMPC_device_type: 5701 case OMPC_match: 5702 default: 5703 llvm_unreachable("Unexpected clause"); 5704 } 5705 for (Stmt *CC : C->children()) { 5706 if (CC) 5707 DSAChecker.Visit(CC); 5708 } 5709 } 5710 for (const auto &P : DSAChecker.getVarsWithInheritedDSA()) 5711 VarsWithInheritedDSA[P.getFirst()] = P.getSecond(); 5712 } 5713 for (const auto &P : VarsWithInheritedDSA) { 5714 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst())) 5715 continue; 5716 ErrorFound = true; 5717 if (DSAStack->getDefaultDSA() == DSA_none || 5718 DSAStack->getDefaultDSA() == DSA_firstprivate) { 5719 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 5720 << P.first << P.second->getSourceRange(); 5721 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none); 5722 } else if (getLangOpts().OpenMP >= 50) { 5723 Diag(P.second->getExprLoc(), 5724 diag::err_omp_defaultmap_no_attr_for_variable) 5725 << P.first << P.second->getSourceRange(); 5726 Diag(DSAStack->getDefaultDSALocation(), 5727 diag::note_omp_defaultmap_attr_none); 5728 } 5729 } 5730 5731 if (!AllowedNameModifiers.empty()) 5732 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 5733 ErrorFound; 5734 5735 if (ErrorFound) 5736 return StmtError(); 5737 5738 if (!CurContext->isDependentContext() && 5739 isOpenMPTargetExecutionDirective(Kind) && 5740 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 5741 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() || 5742 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() || 5743 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) { 5744 // Register target to DSA Stack. 5745 DSAStack->addTargetDirLocation(StartLoc); 5746 } 5747 5748 return Res; 5749 } 5750 5751 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 5752 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 5753 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 5754 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 5755 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 5756 assert(Aligneds.size() == Alignments.size()); 5757 assert(Linears.size() == LinModifiers.size()); 5758 assert(Linears.size() == Steps.size()); 5759 if (!DG || DG.get().isNull()) 5760 return DeclGroupPtrTy(); 5761 5762 const int SimdId = 0; 5763 if (!DG.get().isSingleDecl()) { 5764 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 5765 << SimdId; 5766 return DG; 5767 } 5768 Decl *ADecl = DG.get().getSingleDecl(); 5769 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 5770 ADecl = FTD->getTemplatedDecl(); 5771 5772 auto *FD = dyn_cast<FunctionDecl>(ADecl); 5773 if (!FD) { 5774 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId; 5775 return DeclGroupPtrTy(); 5776 } 5777 5778 // OpenMP [2.8.2, declare simd construct, Description] 5779 // The parameter of the simdlen clause must be a constant positive integer 5780 // expression. 5781 ExprResult SL; 5782 if (Simdlen) 5783 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 5784 // OpenMP [2.8.2, declare simd construct, Description] 5785 // The special this pointer can be used as if was one of the arguments to the 5786 // function in any of the linear, aligned, or uniform clauses. 5787 // The uniform clause declares one or more arguments to have an invariant 5788 // value for all concurrent invocations of the function in the execution of a 5789 // single SIMD loop. 5790 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 5791 const Expr *UniformedLinearThis = nullptr; 5792 for (const Expr *E : Uniforms) { 5793 E = E->IgnoreParenImpCasts(); 5794 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 5795 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 5796 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 5797 FD->getParamDecl(PVD->getFunctionScopeIndex()) 5798 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 5799 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 5800 continue; 5801 } 5802 if (isa<CXXThisExpr>(E)) { 5803 UniformedLinearThis = E; 5804 continue; 5805 } 5806 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 5807 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 5808 } 5809 // OpenMP [2.8.2, declare simd construct, Description] 5810 // The aligned clause declares that the object to which each list item points 5811 // is aligned to the number of bytes expressed in the optional parameter of 5812 // the aligned clause. 5813 // The special this pointer can be used as if was one of the arguments to the 5814 // function in any of the linear, aligned, or uniform clauses. 5815 // The type of list items appearing in the aligned clause must be array, 5816 // pointer, reference to array, or reference to pointer. 5817 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 5818 const Expr *AlignedThis = nullptr; 5819 for (const Expr *E : Aligneds) { 5820 E = E->IgnoreParenImpCasts(); 5821 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 5822 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 5823 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 5824 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 5825 FD->getParamDecl(PVD->getFunctionScopeIndex()) 5826 ->getCanonicalDecl() == CanonPVD) { 5827 // OpenMP [2.8.1, simd construct, Restrictions] 5828 // A list-item cannot appear in more than one aligned clause. 5829 if (AlignedArgs.count(CanonPVD) > 0) { 5830 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 5831 << 1 << getOpenMPClauseName(OMPC_aligned) 5832 << E->getSourceRange(); 5833 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 5834 diag::note_omp_explicit_dsa) 5835 << getOpenMPClauseName(OMPC_aligned); 5836 continue; 5837 } 5838 AlignedArgs[CanonPVD] = E; 5839 QualType QTy = PVD->getType() 5840 .getNonReferenceType() 5841 .getUnqualifiedType() 5842 .getCanonicalType(); 5843 const Type *Ty = QTy.getTypePtrOrNull(); 5844 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 5845 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 5846 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 5847 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 5848 } 5849 continue; 5850 } 5851 } 5852 if (isa<CXXThisExpr>(E)) { 5853 if (AlignedThis) { 5854 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 5855 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange(); 5856 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 5857 << getOpenMPClauseName(OMPC_aligned); 5858 } 5859 AlignedThis = E; 5860 continue; 5861 } 5862 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 5863 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 5864 } 5865 // The optional parameter of the aligned clause, alignment, must be a constant 5866 // positive integer expression. If no optional parameter is specified, 5867 // implementation-defined default alignments for SIMD instructions on the 5868 // target platforms are assumed. 5869 SmallVector<const Expr *, 4> NewAligns; 5870 for (Expr *E : Alignments) { 5871 ExprResult Align; 5872 if (E) 5873 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 5874 NewAligns.push_back(Align.get()); 5875 } 5876 // OpenMP [2.8.2, declare simd construct, Description] 5877 // The linear clause declares one or more list items to be private to a SIMD 5878 // lane and to have a linear relationship with respect to the iteration space 5879 // of a loop. 5880 // The special this pointer can be used as if was one of the arguments to the 5881 // function in any of the linear, aligned, or uniform clauses. 5882 // When a linear-step expression is specified in a linear clause it must be 5883 // either a constant integer expression or an integer-typed parameter that is 5884 // specified in a uniform clause on the directive. 5885 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 5886 const bool IsUniformedThis = UniformedLinearThis != nullptr; 5887 auto MI = LinModifiers.begin(); 5888 for (const Expr *E : Linears) { 5889 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 5890 ++MI; 5891 E = E->IgnoreParenImpCasts(); 5892 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 5893 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 5894 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 5895 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 5896 FD->getParamDecl(PVD->getFunctionScopeIndex()) 5897 ->getCanonicalDecl() == CanonPVD) { 5898 // OpenMP [2.15.3.7, linear Clause, Restrictions] 5899 // A list-item cannot appear in more than one linear clause. 5900 if (LinearArgs.count(CanonPVD) > 0) { 5901 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 5902 << getOpenMPClauseName(OMPC_linear) 5903 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 5904 Diag(LinearArgs[CanonPVD]->getExprLoc(), 5905 diag::note_omp_explicit_dsa) 5906 << getOpenMPClauseName(OMPC_linear); 5907 continue; 5908 } 5909 // Each argument can appear in at most one uniform or linear clause. 5910 if (UniformedArgs.count(CanonPVD) > 0) { 5911 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 5912 << getOpenMPClauseName(OMPC_linear) 5913 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 5914 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 5915 diag::note_omp_explicit_dsa) 5916 << getOpenMPClauseName(OMPC_uniform); 5917 continue; 5918 } 5919 LinearArgs[CanonPVD] = E; 5920 if (E->isValueDependent() || E->isTypeDependent() || 5921 E->isInstantiationDependent() || 5922 E->containsUnexpandedParameterPack()) 5923 continue; 5924 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 5925 PVD->getOriginalType(), 5926 /*IsDeclareSimd=*/true); 5927 continue; 5928 } 5929 } 5930 if (isa<CXXThisExpr>(E)) { 5931 if (UniformedLinearThis) { 5932 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 5933 << getOpenMPClauseName(OMPC_linear) 5934 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 5935 << E->getSourceRange(); 5936 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 5937 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 5938 : OMPC_linear); 5939 continue; 5940 } 5941 UniformedLinearThis = E; 5942 if (E->isValueDependent() || E->isTypeDependent() || 5943 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 5944 continue; 5945 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 5946 E->getType(), /*IsDeclareSimd=*/true); 5947 continue; 5948 } 5949 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 5950 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 5951 } 5952 Expr *Step = nullptr; 5953 Expr *NewStep = nullptr; 5954 SmallVector<Expr *, 4> NewSteps; 5955 for (Expr *E : Steps) { 5956 // Skip the same step expression, it was checked already. 5957 if (Step == E || !E) { 5958 NewSteps.push_back(E ? NewStep : nullptr); 5959 continue; 5960 } 5961 Step = E; 5962 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 5963 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 5964 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 5965 if (UniformedArgs.count(CanonPVD) == 0) { 5966 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 5967 << Step->getSourceRange(); 5968 } else if (E->isValueDependent() || E->isTypeDependent() || 5969 E->isInstantiationDependent() || 5970 E->containsUnexpandedParameterPack() || 5971 CanonPVD->getType()->hasIntegerRepresentation()) { 5972 NewSteps.push_back(Step); 5973 } else { 5974 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 5975 << Step->getSourceRange(); 5976 } 5977 continue; 5978 } 5979 NewStep = Step; 5980 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 5981 !Step->isInstantiationDependent() && 5982 !Step->containsUnexpandedParameterPack()) { 5983 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 5984 .get(); 5985 if (NewStep) 5986 NewStep = 5987 VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get(); 5988 } 5989 NewSteps.push_back(NewStep); 5990 } 5991 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 5992 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 5993 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 5994 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 5995 const_cast<Expr **>(Linears.data()), Linears.size(), 5996 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 5997 NewSteps.data(), NewSteps.size(), SR); 5998 ADecl->addAttr(NewAttr); 5999 return DG; 6000 } 6001 6002 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto, 6003 QualType NewType) { 6004 assert(NewType->isFunctionProtoType() && 6005 "Expected function type with prototype."); 6006 assert(FD->getType()->isFunctionNoProtoType() && 6007 "Expected function with type with no prototype."); 6008 assert(FDWithProto->getType()->isFunctionProtoType() && 6009 "Expected function with prototype."); 6010 // Synthesize parameters with the same types. 6011 FD->setType(NewType); 6012 SmallVector<ParmVarDecl *, 16> Params; 6013 for (const ParmVarDecl *P : FDWithProto->parameters()) { 6014 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(), 6015 SourceLocation(), nullptr, P->getType(), 6016 /*TInfo=*/nullptr, SC_None, nullptr); 6017 Param->setScopeInfo(0, Params.size()); 6018 Param->setImplicit(); 6019 Params.push_back(Param); 6020 } 6021 6022 FD->setParams(Params); 6023 } 6024 6025 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) { 6026 if (D->isInvalidDecl()) 6027 return; 6028 FunctionDecl *FD = nullptr; 6029 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6030 FD = UTemplDecl->getTemplatedDecl(); 6031 else 6032 FD = cast<FunctionDecl>(D); 6033 assert(FD && "Expected a function declaration!"); 6034 6035 // If we are intantiating templates we do *not* apply scoped assumptions but 6036 // only global ones. We apply scoped assumption to the template definition 6037 // though. 6038 if (!inTemplateInstantiation()) { 6039 for (AssumptionAttr *AA : OMPAssumeScoped) 6040 FD->addAttr(AA); 6041 } 6042 for (AssumptionAttr *AA : OMPAssumeGlobal) 6043 FD->addAttr(AA); 6044 } 6045 6046 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI) 6047 : TI(&TI), NameSuffix(TI.getMangledName()) {} 6048 6049 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 6050 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, 6051 SmallVectorImpl<FunctionDecl *> &Bases) { 6052 if (!D.getIdentifier()) 6053 return; 6054 6055 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6056 6057 // Template specialization is an extension, check if we do it. 6058 bool IsTemplated = !TemplateParamLists.empty(); 6059 if (IsTemplated & 6060 !DVScope.TI->isExtensionActive( 6061 llvm::omp::TraitProperty::implementation_extension_allow_templates)) 6062 return; 6063 6064 IdentifierInfo *BaseII = D.getIdentifier(); 6065 LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(), 6066 LookupOrdinaryName); 6067 LookupParsedName(Lookup, S, &D.getCXXScopeSpec()); 6068 6069 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6070 QualType FType = TInfo->getType(); 6071 6072 bool IsConstexpr = 6073 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr; 6074 bool IsConsteval = 6075 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval; 6076 6077 for (auto *Candidate : Lookup) { 6078 auto *CandidateDecl = Candidate->getUnderlyingDecl(); 6079 FunctionDecl *UDecl = nullptr; 6080 if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) 6081 UDecl = cast<FunctionTemplateDecl>(CandidateDecl)->getTemplatedDecl(); 6082 else if (!IsTemplated) 6083 UDecl = dyn_cast<FunctionDecl>(CandidateDecl); 6084 if (!UDecl) 6085 continue; 6086 6087 // Don't specialize constexpr/consteval functions with 6088 // non-constexpr/consteval functions. 6089 if (UDecl->isConstexpr() && !IsConstexpr) 6090 continue; 6091 if (UDecl->isConsteval() && !IsConsteval) 6092 continue; 6093 6094 QualType UDeclTy = UDecl->getType(); 6095 if (!UDeclTy->isDependentType()) { 6096 QualType NewType = Context.mergeFunctionTypes( 6097 FType, UDeclTy, /* OfBlockPointer */ false, 6098 /* Unqualified */ false, /* AllowCXX */ true); 6099 if (NewType.isNull()) 6100 continue; 6101 } 6102 6103 // Found a base! 6104 Bases.push_back(UDecl); 6105 } 6106 6107 bool UseImplicitBase = !DVScope.TI->isExtensionActive( 6108 llvm::omp::TraitProperty::implementation_extension_disable_implicit_base); 6109 // If no base was found we create a declaration that we use as base. 6110 if (Bases.empty() && UseImplicitBase) { 6111 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 6112 Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists); 6113 BaseD->setImplicit(true); 6114 if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD)) 6115 Bases.push_back(BaseTemplD->getTemplatedDecl()); 6116 else 6117 Bases.push_back(cast<FunctionDecl>(BaseD)); 6118 } 6119 6120 std::string MangledName; 6121 MangledName += D.getIdentifier()->getName(); 6122 MangledName += getOpenMPVariantManglingSeparatorStr(); 6123 MangledName += DVScope.NameSuffix; 6124 IdentifierInfo &VariantII = Context.Idents.get(MangledName); 6125 6126 VariantII.setMangledOpenMPVariantName(true); 6127 D.SetIdentifier(&VariantII, D.getBeginLoc()); 6128 } 6129 6130 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 6131 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) { 6132 // Do not mark function as is used to prevent its emission if this is the 6133 // only place where it is used. 6134 EnterExpressionEvaluationContext Unevaluated( 6135 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6136 6137 FunctionDecl *FD = nullptr; 6138 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6139 FD = UTemplDecl->getTemplatedDecl(); 6140 else 6141 FD = cast<FunctionDecl>(D); 6142 auto *VariantFuncRef = DeclRefExpr::Create( 6143 Context, NestedNameSpecifierLoc(), SourceLocation(), FD, 6144 /* RefersToEnclosingVariableOrCapture */ false, 6145 /* NameLoc */ FD->getLocation(), FD->getType(), ExprValueKind::VK_RValue); 6146 6147 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6148 auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit( 6149 Context, VariantFuncRef, DVScope.TI); 6150 for (FunctionDecl *BaseFD : Bases) 6151 BaseFD->addAttr(OMPDeclareVariantA); 6152 } 6153 6154 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope, 6155 SourceLocation LParenLoc, 6156 MultiExprArg ArgExprs, 6157 SourceLocation RParenLoc, Expr *ExecConfig) { 6158 // The common case is a regular call we do not want to specialize at all. Try 6159 // to make that case fast by bailing early. 6160 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6161 if (!CE) 6162 return Call; 6163 6164 FunctionDecl *CalleeFnDecl = CE->getDirectCallee(); 6165 if (!CalleeFnDecl) 6166 return Call; 6167 6168 if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>()) 6169 return Call; 6170 6171 ASTContext &Context = getASTContext(); 6172 std::function<void(StringRef)> DiagUnknownTrait = [this, 6173 CE](StringRef ISATrait) { 6174 // TODO Track the selector locations in a way that is accessible here to 6175 // improve the diagnostic location. 6176 Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait) 6177 << ISATrait; 6178 }; 6179 TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait), 6180 getCurFunctionDecl()); 6181 6182 QualType CalleeFnType = CalleeFnDecl->getType(); 6183 6184 SmallVector<Expr *, 4> Exprs; 6185 SmallVector<VariantMatchInfo, 4> VMIs; 6186 while (CalleeFnDecl) { 6187 for (OMPDeclareVariantAttr *A : 6188 CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) { 6189 Expr *VariantRef = A->getVariantFuncRef(); 6190 6191 VariantMatchInfo VMI; 6192 OMPTraitInfo &TI = A->getTraitInfo(); 6193 TI.getAsVariantMatchInfo(Context, VMI); 6194 if (!isVariantApplicableInContext(VMI, OMPCtx, 6195 /* DeviceSetOnly */ false)) 6196 continue; 6197 6198 VMIs.push_back(VMI); 6199 Exprs.push_back(VariantRef); 6200 } 6201 6202 CalleeFnDecl = CalleeFnDecl->getPreviousDecl(); 6203 } 6204 6205 ExprResult NewCall; 6206 do { 6207 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx); 6208 if (BestIdx < 0) 6209 return Call; 6210 Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]); 6211 Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl(); 6212 6213 { 6214 // Try to build a (member) call expression for the current best applicable 6215 // variant expression. We allow this to fail in which case we continue 6216 // with the next best variant expression. The fail case is part of the 6217 // implementation defined behavior in the OpenMP standard when it talks 6218 // about what differences in the function prototypes: "Any differences 6219 // that the specific OpenMP context requires in the prototype of the 6220 // variant from the base function prototype are implementation defined." 6221 // This wording is there to allow the specialized variant to have a 6222 // different type than the base function. This is intended and OK but if 6223 // we cannot create a call the difference is not in the "implementation 6224 // defined range" we allow. 6225 Sema::TentativeAnalysisScope Trap(*this); 6226 6227 if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) { 6228 auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE); 6229 BestExpr = MemberExpr::CreateImplicit( 6230 Context, MemberCall->getImplicitObjectArgument(), 6231 /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy, 6232 MemberCall->getValueKind(), MemberCall->getObjectKind()); 6233 } 6234 NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc, 6235 ExecConfig); 6236 if (NewCall.isUsable()) { 6237 if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) { 6238 FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee(); 6239 QualType NewType = Context.mergeFunctionTypes( 6240 CalleeFnType, NewCalleeFnDecl->getType(), 6241 /* OfBlockPointer */ false, 6242 /* Unqualified */ false, /* AllowCXX */ true); 6243 if (!NewType.isNull()) 6244 break; 6245 // Don't use the call if the function type was not compatible. 6246 NewCall = nullptr; 6247 } 6248 } 6249 } 6250 6251 VMIs.erase(VMIs.begin() + BestIdx); 6252 Exprs.erase(Exprs.begin() + BestIdx); 6253 } while (!VMIs.empty()); 6254 6255 if (!NewCall.isUsable()) 6256 return Call; 6257 return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0); 6258 } 6259 6260 Optional<std::pair<FunctionDecl *, Expr *>> 6261 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG, 6262 Expr *VariantRef, OMPTraitInfo &TI, 6263 SourceRange SR) { 6264 if (!DG || DG.get().isNull()) 6265 return None; 6266 6267 const int VariantId = 1; 6268 // Must be applied only to single decl. 6269 if (!DG.get().isSingleDecl()) { 6270 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 6271 << VariantId << SR; 6272 return None; 6273 } 6274 Decl *ADecl = DG.get().getSingleDecl(); 6275 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 6276 ADecl = FTD->getTemplatedDecl(); 6277 6278 // Decl must be a function. 6279 auto *FD = dyn_cast<FunctionDecl>(ADecl); 6280 if (!FD) { 6281 Diag(ADecl->getLocation(), diag::err_omp_function_expected) 6282 << VariantId << SR; 6283 return None; 6284 } 6285 6286 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) { 6287 return FD->hasAttrs() && 6288 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() || 6289 FD->hasAttr<TargetAttr>()); 6290 }; 6291 // OpenMP is not compatible with CPU-specific attributes. 6292 if (HasMultiVersionAttributes(FD)) { 6293 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes) 6294 << SR; 6295 return None; 6296 } 6297 6298 // Allow #pragma omp declare variant only if the function is not used. 6299 if (FD->isUsed(false)) 6300 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used) 6301 << FD->getLocation(); 6302 6303 // Check if the function was emitted already. 6304 const FunctionDecl *Definition; 6305 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) && 6306 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition))) 6307 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted) 6308 << FD->getLocation(); 6309 6310 // The VariantRef must point to function. 6311 if (!VariantRef) { 6312 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId; 6313 return None; 6314 } 6315 6316 auto ShouldDelayChecks = [](Expr *&E, bool) { 6317 return E && (E->isTypeDependent() || E->isValueDependent() || 6318 E->containsUnexpandedParameterPack() || 6319 E->isInstantiationDependent()); 6320 }; 6321 // Do not check templates, wait until instantiation. 6322 if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) || 6323 TI.anyScoreOrCondition(ShouldDelayChecks)) 6324 return std::make_pair(FD, VariantRef); 6325 6326 // Deal with non-constant score and user condition expressions. 6327 auto HandleNonConstantScoresAndConditions = [this](Expr *&E, 6328 bool IsScore) -> bool { 6329 if (!E || E->isIntegerConstantExpr(Context)) 6330 return false; 6331 6332 if (IsScore) { 6333 // We warn on non-constant scores and pretend they were not present. 6334 Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant) 6335 << E; 6336 E = nullptr; 6337 } else { 6338 // We could replace a non-constant user condition with "false" but we 6339 // will soon need to handle these anyway for the dynamic version of 6340 // OpenMP context selectors. 6341 Diag(E->getExprLoc(), 6342 diag::err_omp_declare_variant_user_condition_not_constant) 6343 << E; 6344 } 6345 return true; 6346 }; 6347 if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions)) 6348 return None; 6349 6350 // Convert VariantRef expression to the type of the original function to 6351 // resolve possible conflicts. 6352 ExprResult VariantRefCast = VariantRef; 6353 if (LangOpts.CPlusPlus) { 6354 QualType FnPtrType; 6355 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6356 if (Method && !Method->isStatic()) { 6357 const Type *ClassType = 6358 Context.getTypeDeclType(Method->getParent()).getTypePtr(); 6359 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType); 6360 ExprResult ER; 6361 { 6362 // Build adrr_of unary op to correctly handle type checks for member 6363 // functions. 6364 Sema::TentativeAnalysisScope Trap(*this); 6365 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf, 6366 VariantRef); 6367 } 6368 if (!ER.isUsable()) { 6369 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 6370 << VariantId << VariantRef->getSourceRange(); 6371 return None; 6372 } 6373 VariantRef = ER.get(); 6374 } else { 6375 FnPtrType = Context.getPointerType(FD->getType()); 6376 } 6377 QualType VarianPtrType = Context.getPointerType(VariantRef->getType()); 6378 if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) { 6379 ImplicitConversionSequence ICS = TryImplicitConversion( 6380 VariantRef, FnPtrType.getUnqualifiedType(), 6381 /*SuppressUserConversions=*/false, AllowedExplicit::None, 6382 /*InOverloadResolution=*/false, 6383 /*CStyle=*/false, 6384 /*AllowObjCWritebackConversion=*/false); 6385 if (ICS.isFailure()) { 6386 Diag(VariantRef->getExprLoc(), 6387 diag::err_omp_declare_variant_incompat_types) 6388 << VariantRef->getType() 6389 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType()) 6390 << VariantRef->getSourceRange(); 6391 return None; 6392 } 6393 VariantRefCast = PerformImplicitConversion( 6394 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting); 6395 if (!VariantRefCast.isUsable()) 6396 return None; 6397 } 6398 // Drop previously built artificial addr_of unary op for member functions. 6399 if (Method && !Method->isStatic()) { 6400 Expr *PossibleAddrOfVariantRef = VariantRefCast.get(); 6401 if (auto *UO = dyn_cast<UnaryOperator>( 6402 PossibleAddrOfVariantRef->IgnoreImplicit())) 6403 VariantRefCast = UO->getSubExpr(); 6404 } 6405 } 6406 6407 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get()); 6408 if (!ER.isUsable() || 6409 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) { 6410 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 6411 << VariantId << VariantRef->getSourceRange(); 6412 return None; 6413 } 6414 6415 // The VariantRef must point to function. 6416 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts()); 6417 if (!DRE) { 6418 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 6419 << VariantId << VariantRef->getSourceRange(); 6420 return None; 6421 } 6422 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl()); 6423 if (!NewFD) { 6424 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 6425 << VariantId << VariantRef->getSourceRange(); 6426 return None; 6427 } 6428 6429 // Check if function types are compatible in C. 6430 if (!LangOpts.CPlusPlus) { 6431 QualType NewType = 6432 Context.mergeFunctionTypes(FD->getType(), NewFD->getType()); 6433 if (NewType.isNull()) { 6434 Diag(VariantRef->getExprLoc(), 6435 diag::err_omp_declare_variant_incompat_types) 6436 << NewFD->getType() << FD->getType() << VariantRef->getSourceRange(); 6437 return None; 6438 } 6439 if (NewType->isFunctionProtoType()) { 6440 if (FD->getType()->isFunctionNoProtoType()) 6441 setPrototype(*this, FD, NewFD, NewType); 6442 else if (NewFD->getType()->isFunctionNoProtoType()) 6443 setPrototype(*this, NewFD, FD, NewType); 6444 } 6445 } 6446 6447 // Check if variant function is not marked with declare variant directive. 6448 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) { 6449 Diag(VariantRef->getExprLoc(), 6450 diag::warn_omp_declare_variant_marked_as_declare_variant) 6451 << VariantRef->getSourceRange(); 6452 SourceRange SR = 6453 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange(); 6454 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR; 6455 return None; 6456 } 6457 6458 enum DoesntSupport { 6459 VirtFuncs = 1, 6460 Constructors = 3, 6461 Destructors = 4, 6462 DeletedFuncs = 5, 6463 DefaultedFuncs = 6, 6464 ConstexprFuncs = 7, 6465 ConstevalFuncs = 8, 6466 }; 6467 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 6468 if (CXXFD->isVirtual()) { 6469 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 6470 << VirtFuncs; 6471 return None; 6472 } 6473 6474 if (isa<CXXConstructorDecl>(FD)) { 6475 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 6476 << Constructors; 6477 return None; 6478 } 6479 6480 if (isa<CXXDestructorDecl>(FD)) { 6481 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 6482 << Destructors; 6483 return None; 6484 } 6485 } 6486 6487 if (FD->isDeleted()) { 6488 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 6489 << DeletedFuncs; 6490 return None; 6491 } 6492 6493 if (FD->isDefaulted()) { 6494 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 6495 << DefaultedFuncs; 6496 return None; 6497 } 6498 6499 if (FD->isConstexpr()) { 6500 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 6501 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 6502 return None; 6503 } 6504 6505 // Check general compatibility. 6506 if (areMultiversionVariantFunctionsCompatible( 6507 FD, NewFD, PartialDiagnostic::NullDiagnostic(), 6508 PartialDiagnosticAt(SourceLocation(), 6509 PartialDiagnostic::NullDiagnostic()), 6510 PartialDiagnosticAt( 6511 VariantRef->getExprLoc(), 6512 PDiag(diag::err_omp_declare_variant_doesnt_support)), 6513 PartialDiagnosticAt(VariantRef->getExprLoc(), 6514 PDiag(diag::err_omp_declare_variant_diff) 6515 << FD->getLocation()), 6516 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false, 6517 /*CLinkageMayDiffer=*/true)) 6518 return None; 6519 return std::make_pair(FD, cast<Expr>(DRE)); 6520 } 6521 6522 void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, 6523 Expr *VariantRef, 6524 OMPTraitInfo &TI, 6525 SourceRange SR) { 6526 auto *NewAttr = 6527 OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, &TI, SR); 6528 FD->addAttr(NewAttr); 6529 } 6530 6531 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 6532 Stmt *AStmt, 6533 SourceLocation StartLoc, 6534 SourceLocation EndLoc) { 6535 if (!AStmt) 6536 return StmtError(); 6537 6538 auto *CS = cast<CapturedStmt>(AStmt); 6539 // 1.2.2 OpenMP Language Terminology 6540 // Structured block - An executable statement with a single entry at the 6541 // top and a single exit at the bottom. 6542 // The point of exit cannot be a branch out of the structured block. 6543 // longjmp() and throw() must not violate the entry/exit criteria. 6544 CS->getCapturedDecl()->setNothrow(); 6545 6546 setFunctionHasBranchProtectedScope(); 6547 6548 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6549 DSAStack->getTaskgroupReductionRef(), 6550 DSAStack->isCancelRegion()); 6551 } 6552 6553 namespace { 6554 /// Iteration space of a single for loop. 6555 struct LoopIterationSpace final { 6556 /// True if the condition operator is the strict compare operator (<, > or 6557 /// !=). 6558 bool IsStrictCompare = false; 6559 /// Condition of the loop. 6560 Expr *PreCond = nullptr; 6561 /// This expression calculates the number of iterations in the loop. 6562 /// It is always possible to calculate it before starting the loop. 6563 Expr *NumIterations = nullptr; 6564 /// The loop counter variable. 6565 Expr *CounterVar = nullptr; 6566 /// Private loop counter variable. 6567 Expr *PrivateCounterVar = nullptr; 6568 /// This is initializer for the initial value of #CounterVar. 6569 Expr *CounterInit = nullptr; 6570 /// This is step for the #CounterVar used to generate its update: 6571 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 6572 Expr *CounterStep = nullptr; 6573 /// Should step be subtracted? 6574 bool Subtract = false; 6575 /// Source range of the loop init. 6576 SourceRange InitSrcRange; 6577 /// Source range of the loop condition. 6578 SourceRange CondSrcRange; 6579 /// Source range of the loop increment. 6580 SourceRange IncSrcRange; 6581 /// Minimum value that can have the loop control variable. Used to support 6582 /// non-rectangular loops. Applied only for LCV with the non-iterator types, 6583 /// since only such variables can be used in non-loop invariant expressions. 6584 Expr *MinValue = nullptr; 6585 /// Maximum value that can have the loop control variable. Used to support 6586 /// non-rectangular loops. Applied only for LCV with the non-iterator type, 6587 /// since only such variables can be used in non-loop invariant expressions. 6588 Expr *MaxValue = nullptr; 6589 /// true, if the lower bound depends on the outer loop control var. 6590 bool IsNonRectangularLB = false; 6591 /// true, if the upper bound depends on the outer loop control var. 6592 bool IsNonRectangularUB = false; 6593 /// Index of the loop this loop depends on and forms non-rectangular loop 6594 /// nest. 6595 unsigned LoopDependentIdx = 0; 6596 /// Final condition for the non-rectangular loop nest support. It is used to 6597 /// check that the number of iterations for this particular counter must be 6598 /// finished. 6599 Expr *FinalCondition = nullptr; 6600 }; 6601 6602 /// Helper class for checking canonical form of the OpenMP loops and 6603 /// extracting iteration space of each loop in the loop nest, that will be used 6604 /// for IR generation. 6605 class OpenMPIterationSpaceChecker { 6606 /// Reference to Sema. 6607 Sema &SemaRef; 6608 /// Does the loop associated directive support non-rectangular loops? 6609 bool SupportsNonRectangular; 6610 /// Data-sharing stack. 6611 DSAStackTy &Stack; 6612 /// A location for diagnostics (when there is no some better location). 6613 SourceLocation DefaultLoc; 6614 /// A location for diagnostics (when increment is not compatible). 6615 SourceLocation ConditionLoc; 6616 /// A source location for referring to loop init later. 6617 SourceRange InitSrcRange; 6618 /// A source location for referring to condition later. 6619 SourceRange ConditionSrcRange; 6620 /// A source location for referring to increment later. 6621 SourceRange IncrementSrcRange; 6622 /// Loop variable. 6623 ValueDecl *LCDecl = nullptr; 6624 /// Reference to loop variable. 6625 Expr *LCRef = nullptr; 6626 /// Lower bound (initializer for the var). 6627 Expr *LB = nullptr; 6628 /// Upper bound. 6629 Expr *UB = nullptr; 6630 /// Loop step (increment). 6631 Expr *Step = nullptr; 6632 /// This flag is true when condition is one of: 6633 /// Var < UB 6634 /// Var <= UB 6635 /// UB > Var 6636 /// UB >= Var 6637 /// This will have no value when the condition is != 6638 llvm::Optional<bool> TestIsLessOp; 6639 /// This flag is true when condition is strict ( < or > ). 6640 bool TestIsStrictOp = false; 6641 /// This flag is true when step is subtracted on each iteration. 6642 bool SubtractStep = false; 6643 /// The outer loop counter this loop depends on (if any). 6644 const ValueDecl *DepDecl = nullptr; 6645 /// Contains number of loop (starts from 1) on which loop counter init 6646 /// expression of this loop depends on. 6647 Optional<unsigned> InitDependOnLC; 6648 /// Contains number of loop (starts from 1) on which loop counter condition 6649 /// expression of this loop depends on. 6650 Optional<unsigned> CondDependOnLC; 6651 /// Checks if the provide statement depends on the loop counter. 6652 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer); 6653 /// Original condition required for checking of the exit condition for 6654 /// non-rectangular loop. 6655 Expr *Condition = nullptr; 6656 6657 public: 6658 OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular, 6659 DSAStackTy &Stack, SourceLocation DefaultLoc) 6660 : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular), 6661 Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 6662 /// Check init-expr for canonical loop form and save loop counter 6663 /// variable - #Var and its initialization value - #LB. 6664 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 6665 /// Check test-expr for canonical form, save upper-bound (#UB), flags 6666 /// for less/greater and for strict/non-strict comparison. 6667 bool checkAndSetCond(Expr *S); 6668 /// Check incr-expr for canonical loop form and return true if it 6669 /// does not conform, otherwise save loop step (#Step). 6670 bool checkAndSetInc(Expr *S); 6671 /// Return the loop counter variable. 6672 ValueDecl *getLoopDecl() const { return LCDecl; } 6673 /// Return the reference expression to loop counter variable. 6674 Expr *getLoopDeclRefExpr() const { return LCRef; } 6675 /// Source range of the loop init. 6676 SourceRange getInitSrcRange() const { return InitSrcRange; } 6677 /// Source range of the loop condition. 6678 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 6679 /// Source range of the loop increment. 6680 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 6681 /// True if the step should be subtracted. 6682 bool shouldSubtractStep() const { return SubtractStep; } 6683 /// True, if the compare operator is strict (<, > or !=). 6684 bool isStrictTestOp() const { return TestIsStrictOp; } 6685 /// Build the expression to calculate the number of iterations. 6686 Expr *buildNumIterations( 6687 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 6688 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 6689 /// Build the precondition expression for the loops. 6690 Expr * 6691 buildPreCond(Scope *S, Expr *Cond, 6692 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 6693 /// Build reference expression to the counter be used for codegen. 6694 DeclRefExpr * 6695 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 6696 DSAStackTy &DSA) const; 6697 /// Build reference expression to the private counter be used for 6698 /// codegen. 6699 Expr *buildPrivateCounterVar() const; 6700 /// Build initialization of the counter be used for codegen. 6701 Expr *buildCounterInit() const; 6702 /// Build step of the counter be used for codegen. 6703 Expr *buildCounterStep() const; 6704 /// Build loop data with counter value for depend clauses in ordered 6705 /// directives. 6706 Expr * 6707 buildOrderedLoopData(Scope *S, Expr *Counter, 6708 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 6709 SourceLocation Loc, Expr *Inc = nullptr, 6710 OverloadedOperatorKind OOK = OO_Amp); 6711 /// Builds the minimum value for the loop counter. 6712 std::pair<Expr *, Expr *> buildMinMaxValues( 6713 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 6714 /// Builds final condition for the non-rectangular loops. 6715 Expr *buildFinalCondition(Scope *S) const; 6716 /// Return true if any expression is dependent. 6717 bool dependent() const; 6718 /// Returns true if the initializer forms non-rectangular loop. 6719 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); } 6720 /// Returns true if the condition forms non-rectangular loop. 6721 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); } 6722 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise. 6723 unsigned getLoopDependentIdx() const { 6724 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0)); 6725 } 6726 6727 private: 6728 /// Check the right-hand side of an assignment in the increment 6729 /// expression. 6730 bool checkAndSetIncRHS(Expr *RHS); 6731 /// Helper to set loop counter variable and its initializer. 6732 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB, 6733 bool EmitDiags); 6734 /// Helper to set upper bound. 6735 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 6736 SourceRange SR, SourceLocation SL); 6737 /// Helper to set loop increment. 6738 bool setStep(Expr *NewStep, bool Subtract); 6739 }; 6740 6741 bool OpenMPIterationSpaceChecker::dependent() const { 6742 if (!LCDecl) { 6743 assert(!LB && !UB && !Step); 6744 return false; 6745 } 6746 return LCDecl->getType()->isDependentType() || 6747 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 6748 (Step && Step->isValueDependent()); 6749 } 6750 6751 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 6752 Expr *NewLCRefExpr, 6753 Expr *NewLB, bool EmitDiags) { 6754 // State consistency checking to ensure correct usage. 6755 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 6756 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 6757 if (!NewLCDecl || !NewLB) 6758 return true; 6759 LCDecl = getCanonicalDecl(NewLCDecl); 6760 LCRef = NewLCRefExpr; 6761 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 6762 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 6763 if ((Ctor->isCopyOrMoveConstructor() || 6764 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 6765 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 6766 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 6767 LB = NewLB; 6768 if (EmitDiags) 6769 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true); 6770 return false; 6771 } 6772 6773 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 6774 llvm::Optional<bool> LessOp, 6775 bool StrictOp, SourceRange SR, 6776 SourceLocation SL) { 6777 // State consistency checking to ensure correct usage. 6778 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 6779 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 6780 if (!NewUB) 6781 return true; 6782 UB = NewUB; 6783 if (LessOp) 6784 TestIsLessOp = LessOp; 6785 TestIsStrictOp = StrictOp; 6786 ConditionSrcRange = SR; 6787 ConditionLoc = SL; 6788 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false); 6789 return false; 6790 } 6791 6792 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 6793 // State consistency checking to ensure correct usage. 6794 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 6795 if (!NewStep) 6796 return true; 6797 if (!NewStep->isValueDependent()) { 6798 // Check that the step is integer expression. 6799 SourceLocation StepLoc = NewStep->getBeginLoc(); 6800 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 6801 StepLoc, getExprAsWritten(NewStep)); 6802 if (Val.isInvalid()) 6803 return true; 6804 NewStep = Val.get(); 6805 6806 // OpenMP [2.6, Canonical Loop Form, Restrictions] 6807 // If test-expr is of form var relational-op b and relational-op is < or 6808 // <= then incr-expr must cause var to increase on each iteration of the 6809 // loop. If test-expr is of form var relational-op b and relational-op is 6810 // > or >= then incr-expr must cause var to decrease on each iteration of 6811 // the loop. 6812 // If test-expr is of form b relational-op var and relational-op is < or 6813 // <= then incr-expr must cause var to decrease on each iteration of the 6814 // loop. If test-expr is of form b relational-op var and relational-op is 6815 // > or >= then incr-expr must cause var to increase on each iteration of 6816 // the loop. 6817 Optional<llvm::APSInt> Result = 6818 NewStep->getIntegerConstantExpr(SemaRef.Context); 6819 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 6820 bool IsConstNeg = 6821 Result && Result->isSigned() && (Subtract != Result->isNegative()); 6822 bool IsConstPos = 6823 Result && Result->isSigned() && (Subtract == Result->isNegative()); 6824 bool IsConstZero = Result && !Result->getBoolValue(); 6825 6826 // != with increment is treated as <; != with decrement is treated as > 6827 if (!TestIsLessOp.hasValue()) 6828 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 6829 if (UB && (IsConstZero || 6830 (TestIsLessOp.getValue() ? 6831 (IsConstNeg || (IsUnsigned && Subtract)) : 6832 (IsConstPos || (IsUnsigned && !Subtract))))) { 6833 SemaRef.Diag(NewStep->getExprLoc(), 6834 diag::err_omp_loop_incr_not_compatible) 6835 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 6836 SemaRef.Diag(ConditionLoc, 6837 diag::note_omp_loop_cond_requres_compatible_incr) 6838 << TestIsLessOp.getValue() << ConditionSrcRange; 6839 return true; 6840 } 6841 if (TestIsLessOp.getValue() == Subtract) { 6842 NewStep = 6843 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 6844 .get(); 6845 Subtract = !Subtract; 6846 } 6847 } 6848 6849 Step = NewStep; 6850 SubtractStep = Subtract; 6851 return false; 6852 } 6853 6854 namespace { 6855 /// Checker for the non-rectangular loops. Checks if the initializer or 6856 /// condition expression references loop counter variable. 6857 class LoopCounterRefChecker final 6858 : public ConstStmtVisitor<LoopCounterRefChecker, bool> { 6859 Sema &SemaRef; 6860 DSAStackTy &Stack; 6861 const ValueDecl *CurLCDecl = nullptr; 6862 const ValueDecl *DepDecl = nullptr; 6863 const ValueDecl *PrevDepDecl = nullptr; 6864 bool IsInitializer = true; 6865 bool SupportsNonRectangular; 6866 unsigned BaseLoopId = 0; 6867 bool checkDecl(const Expr *E, const ValueDecl *VD) { 6868 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) { 6869 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter) 6870 << (IsInitializer ? 0 : 1); 6871 return false; 6872 } 6873 const auto &&Data = Stack.isLoopControlVariable(VD); 6874 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions. 6875 // The type of the loop iterator on which we depend may not have a random 6876 // access iterator type. 6877 if (Data.first && VD->getType()->isRecordType()) { 6878 SmallString<128> Name; 6879 llvm::raw_svector_ostream OS(Name); 6880 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 6881 /*Qualified=*/true); 6882 SemaRef.Diag(E->getExprLoc(), 6883 diag::err_omp_wrong_dependency_iterator_type) 6884 << OS.str(); 6885 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD; 6886 return false; 6887 } 6888 if (Data.first && !SupportsNonRectangular) { 6889 SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency); 6890 return false; 6891 } 6892 if (Data.first && 6893 (DepDecl || (PrevDepDecl && 6894 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) { 6895 if (!DepDecl && PrevDepDecl) 6896 DepDecl = PrevDepDecl; 6897 SmallString<128> Name; 6898 llvm::raw_svector_ostream OS(Name); 6899 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 6900 /*Qualified=*/true); 6901 SemaRef.Diag(E->getExprLoc(), 6902 diag::err_omp_invariant_or_linear_dependency) 6903 << OS.str(); 6904 return false; 6905 } 6906 if (Data.first) { 6907 DepDecl = VD; 6908 BaseLoopId = Data.first; 6909 } 6910 return Data.first; 6911 } 6912 6913 public: 6914 bool VisitDeclRefExpr(const DeclRefExpr *E) { 6915 const ValueDecl *VD = E->getDecl(); 6916 if (isa<VarDecl>(VD)) 6917 return checkDecl(E, VD); 6918 return false; 6919 } 6920 bool VisitMemberExpr(const MemberExpr *E) { 6921 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 6922 const ValueDecl *VD = E->getMemberDecl(); 6923 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD)) 6924 return checkDecl(E, VD); 6925 } 6926 return false; 6927 } 6928 bool VisitStmt(const Stmt *S) { 6929 bool Res = false; 6930 for (const Stmt *Child : S->children()) 6931 Res = (Child && Visit(Child)) || Res; 6932 return Res; 6933 } 6934 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack, 6935 const ValueDecl *CurLCDecl, bool IsInitializer, 6936 const ValueDecl *PrevDepDecl = nullptr, 6937 bool SupportsNonRectangular = true) 6938 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl), 6939 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer), 6940 SupportsNonRectangular(SupportsNonRectangular) {} 6941 unsigned getBaseLoopId() const { 6942 assert(CurLCDecl && "Expected loop dependency."); 6943 return BaseLoopId; 6944 } 6945 const ValueDecl *getDepDecl() const { 6946 assert(CurLCDecl && "Expected loop dependency."); 6947 return DepDecl; 6948 } 6949 }; 6950 } // namespace 6951 6952 Optional<unsigned> 6953 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S, 6954 bool IsInitializer) { 6955 // Check for the non-rectangular loops. 6956 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer, 6957 DepDecl, SupportsNonRectangular); 6958 if (LoopStmtChecker.Visit(S)) { 6959 DepDecl = LoopStmtChecker.getDepDecl(); 6960 return LoopStmtChecker.getBaseLoopId(); 6961 } 6962 return llvm::None; 6963 } 6964 6965 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 6966 // Check init-expr for canonical loop form and save loop counter 6967 // variable - #Var and its initialization value - #LB. 6968 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 6969 // var = lb 6970 // integer-type var = lb 6971 // random-access-iterator-type var = lb 6972 // pointer-type var = lb 6973 // 6974 if (!S) { 6975 if (EmitDiags) { 6976 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 6977 } 6978 return true; 6979 } 6980 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 6981 if (!ExprTemp->cleanupsHaveSideEffects()) 6982 S = ExprTemp->getSubExpr(); 6983 6984 InitSrcRange = S->getSourceRange(); 6985 if (Expr *E = dyn_cast<Expr>(S)) 6986 S = E->IgnoreParens(); 6987 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 6988 if (BO->getOpcode() == BO_Assign) { 6989 Expr *LHS = BO->getLHS()->IgnoreParens(); 6990 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 6991 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 6992 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 6993 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 6994 EmitDiags); 6995 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags); 6996 } 6997 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 6998 if (ME->isArrow() && 6999 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7000 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7001 EmitDiags); 7002 } 7003 } 7004 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 7005 if (DS->isSingleDecl()) { 7006 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 7007 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 7008 // Accept non-canonical init form here but emit ext. warning. 7009 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 7010 SemaRef.Diag(S->getBeginLoc(), 7011 diag::ext_omp_loop_not_canonical_init) 7012 << S->getSourceRange(); 7013 return setLCDeclAndLB( 7014 Var, 7015 buildDeclRefExpr(SemaRef, Var, 7016 Var->getType().getNonReferenceType(), 7017 DS->getBeginLoc()), 7018 Var->getInit(), EmitDiags); 7019 } 7020 } 7021 } 7022 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7023 if (CE->getOperator() == OO_Equal) { 7024 Expr *LHS = CE->getArg(0); 7025 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7026 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7027 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7028 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7029 EmitDiags); 7030 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags); 7031 } 7032 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7033 if (ME->isArrow() && 7034 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7035 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7036 EmitDiags); 7037 } 7038 } 7039 } 7040 7041 if (dependent() || SemaRef.CurContext->isDependentContext()) 7042 return false; 7043 if (EmitDiags) { 7044 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 7045 << S->getSourceRange(); 7046 } 7047 return true; 7048 } 7049 7050 /// Ignore parenthesizes, implicit casts, copy constructor and return the 7051 /// variable (which may be the loop variable) if possible. 7052 static const ValueDecl *getInitLCDecl(const Expr *E) { 7053 if (!E) 7054 return nullptr; 7055 E = getExprAsWritten(E); 7056 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 7057 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7058 if ((Ctor->isCopyOrMoveConstructor() || 7059 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7060 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7061 E = CE->getArg(0)->IgnoreParenImpCasts(); 7062 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 7063 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 7064 return getCanonicalDecl(VD); 7065 } 7066 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 7067 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7068 return getCanonicalDecl(ME->getMemberDecl()); 7069 return nullptr; 7070 } 7071 7072 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 7073 // Check test-expr for canonical form, save upper-bound UB, flags for 7074 // less/greater and for strict/non-strict comparison. 7075 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following: 7076 // var relational-op b 7077 // b relational-op var 7078 // 7079 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50; 7080 if (!S) { 7081 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) 7082 << (IneqCondIsCanonical ? 1 : 0) << LCDecl; 7083 return true; 7084 } 7085 Condition = S; 7086 S = getExprAsWritten(S); 7087 SourceLocation CondLoc = S->getBeginLoc(); 7088 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7089 if (BO->isRelationalOp()) { 7090 if (getInitLCDecl(BO->getLHS()) == LCDecl) 7091 return setUB(BO->getRHS(), 7092 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 7093 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 7094 BO->getSourceRange(), BO->getOperatorLoc()); 7095 if (getInitLCDecl(BO->getRHS()) == LCDecl) 7096 return setUB(BO->getLHS(), 7097 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 7098 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 7099 BO->getSourceRange(), BO->getOperatorLoc()); 7100 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE) 7101 return setUB( 7102 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(), 7103 /*LessOp=*/llvm::None, 7104 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc()); 7105 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7106 if (CE->getNumArgs() == 2) { 7107 auto Op = CE->getOperator(); 7108 switch (Op) { 7109 case OO_Greater: 7110 case OO_GreaterEqual: 7111 case OO_Less: 7112 case OO_LessEqual: 7113 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7114 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 7115 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 7116 CE->getOperatorLoc()); 7117 if (getInitLCDecl(CE->getArg(1)) == LCDecl) 7118 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 7119 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 7120 CE->getOperatorLoc()); 7121 break; 7122 case OO_ExclaimEqual: 7123 if (IneqCondIsCanonical) 7124 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1) 7125 : CE->getArg(0), 7126 /*LessOp=*/llvm::None, 7127 /*StrictOp=*/true, CE->getSourceRange(), 7128 CE->getOperatorLoc()); 7129 break; 7130 default: 7131 break; 7132 } 7133 } 7134 } 7135 if (dependent() || SemaRef.CurContext->isDependentContext()) 7136 return false; 7137 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 7138 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl; 7139 return true; 7140 } 7141 7142 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 7143 // RHS of canonical loop form increment can be: 7144 // var + incr 7145 // incr + var 7146 // var - incr 7147 // 7148 RHS = RHS->IgnoreParenImpCasts(); 7149 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 7150 if (BO->isAdditiveOp()) { 7151 bool IsAdd = BO->getOpcode() == BO_Add; 7152 if (getInitLCDecl(BO->getLHS()) == LCDecl) 7153 return setStep(BO->getRHS(), !IsAdd); 7154 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 7155 return setStep(BO->getLHS(), /*Subtract=*/false); 7156 } 7157 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 7158 bool IsAdd = CE->getOperator() == OO_Plus; 7159 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 7160 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7161 return setStep(CE->getArg(1), !IsAdd); 7162 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 7163 return setStep(CE->getArg(0), /*Subtract=*/false); 7164 } 7165 } 7166 if (dependent() || SemaRef.CurContext->isDependentContext()) 7167 return false; 7168 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 7169 << RHS->getSourceRange() << LCDecl; 7170 return true; 7171 } 7172 7173 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 7174 // Check incr-expr for canonical loop form and return true if it 7175 // does not conform. 7176 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 7177 // ++var 7178 // var++ 7179 // --var 7180 // var-- 7181 // var += incr 7182 // var -= incr 7183 // var = var + incr 7184 // var = incr + var 7185 // var = var - incr 7186 // 7187 if (!S) { 7188 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 7189 return true; 7190 } 7191 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 7192 if (!ExprTemp->cleanupsHaveSideEffects()) 7193 S = ExprTemp->getSubExpr(); 7194 7195 IncrementSrcRange = S->getSourceRange(); 7196 S = S->IgnoreParens(); 7197 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 7198 if (UO->isIncrementDecrementOp() && 7199 getInitLCDecl(UO->getSubExpr()) == LCDecl) 7200 return setStep(SemaRef 7201 .ActOnIntegerConstant(UO->getBeginLoc(), 7202 (UO->isDecrementOp() ? -1 : 1)) 7203 .get(), 7204 /*Subtract=*/false); 7205 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7206 switch (BO->getOpcode()) { 7207 case BO_AddAssign: 7208 case BO_SubAssign: 7209 if (getInitLCDecl(BO->getLHS()) == LCDecl) 7210 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 7211 break; 7212 case BO_Assign: 7213 if (getInitLCDecl(BO->getLHS()) == LCDecl) 7214 return checkAndSetIncRHS(BO->getRHS()); 7215 break; 7216 default: 7217 break; 7218 } 7219 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7220 switch (CE->getOperator()) { 7221 case OO_PlusPlus: 7222 case OO_MinusMinus: 7223 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7224 return setStep(SemaRef 7225 .ActOnIntegerConstant( 7226 CE->getBeginLoc(), 7227 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 7228 .get(), 7229 /*Subtract=*/false); 7230 break; 7231 case OO_PlusEqual: 7232 case OO_MinusEqual: 7233 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7234 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 7235 break; 7236 case OO_Equal: 7237 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7238 return checkAndSetIncRHS(CE->getArg(1)); 7239 break; 7240 default: 7241 break; 7242 } 7243 } 7244 if (dependent() || SemaRef.CurContext->isDependentContext()) 7245 return false; 7246 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 7247 << S->getSourceRange() << LCDecl; 7248 return true; 7249 } 7250 7251 static ExprResult 7252 tryBuildCapture(Sema &SemaRef, Expr *Capture, 7253 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 7254 if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors()) 7255 return Capture; 7256 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 7257 return SemaRef.PerformImplicitConversion( 7258 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 7259 /*AllowExplicit=*/true); 7260 auto I = Captures.find(Capture); 7261 if (I != Captures.end()) 7262 return buildCapture(SemaRef, Capture, I->second); 7263 DeclRefExpr *Ref = nullptr; 7264 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 7265 Captures[Capture] = Ref; 7266 return Res; 7267 } 7268 7269 /// Calculate number of iterations, transforming to unsigned, if number of 7270 /// iterations may be larger than the original type. 7271 static Expr * 7272 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc, 7273 Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy, 7274 bool TestIsStrictOp, bool RoundToStep, 7275 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 7276 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 7277 if (!NewStep.isUsable()) 7278 return nullptr; 7279 llvm::APSInt LRes, SRes; 7280 bool IsLowerConst = false, IsStepConst = false; 7281 if (Optional<llvm::APSInt> Res = Lower->getIntegerConstantExpr(SemaRef.Context)) { 7282 LRes = *Res; 7283 IsLowerConst = true; 7284 } 7285 if (Optional<llvm::APSInt> Res = Step->getIntegerConstantExpr(SemaRef.Context)) { 7286 SRes = *Res; 7287 IsStepConst = true; 7288 } 7289 bool NoNeedToConvert = IsLowerConst && !RoundToStep && 7290 ((!TestIsStrictOp && LRes.isNonNegative()) || 7291 (TestIsStrictOp && LRes.isStrictlyPositive())); 7292 bool NeedToReorganize = false; 7293 // Check if any subexpressions in Lower -Step [+ 1] lead to overflow. 7294 if (!NoNeedToConvert && IsLowerConst && 7295 (TestIsStrictOp || (RoundToStep && IsStepConst))) { 7296 NoNeedToConvert = true; 7297 if (RoundToStep) { 7298 unsigned BW = LRes.getBitWidth() > SRes.getBitWidth() 7299 ? LRes.getBitWidth() 7300 : SRes.getBitWidth(); 7301 LRes = LRes.extend(BW + 1); 7302 LRes.setIsSigned(true); 7303 SRes = SRes.extend(BW + 1); 7304 SRes.setIsSigned(true); 7305 LRes -= SRes; 7306 NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes; 7307 LRes = LRes.trunc(BW); 7308 } 7309 if (TestIsStrictOp) { 7310 unsigned BW = LRes.getBitWidth(); 7311 LRes = LRes.extend(BW + 1); 7312 LRes.setIsSigned(true); 7313 ++LRes; 7314 NoNeedToConvert = 7315 NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes; 7316 // truncate to the original bitwidth. 7317 LRes = LRes.trunc(BW); 7318 } 7319 NeedToReorganize = NoNeedToConvert; 7320 } 7321 llvm::APSInt URes; 7322 bool IsUpperConst = false; 7323 if (Optional<llvm::APSInt> Res = Upper->getIntegerConstantExpr(SemaRef.Context)) { 7324 URes = *Res; 7325 IsUpperConst = true; 7326 } 7327 if (NoNeedToConvert && IsLowerConst && IsUpperConst && 7328 (!RoundToStep || IsStepConst)) { 7329 unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth() 7330 : URes.getBitWidth(); 7331 LRes = LRes.extend(BW + 1); 7332 LRes.setIsSigned(true); 7333 URes = URes.extend(BW + 1); 7334 URes.setIsSigned(true); 7335 URes -= LRes; 7336 NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes; 7337 NeedToReorganize = NoNeedToConvert; 7338 } 7339 // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant 7340 // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to 7341 // unsigned. 7342 if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) && 7343 !LCTy->isDependentType() && LCTy->isIntegerType()) { 7344 QualType LowerTy = Lower->getType(); 7345 QualType UpperTy = Upper->getType(); 7346 uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy); 7347 uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy); 7348 if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) || 7349 (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) { 7350 QualType CastType = SemaRef.Context.getIntTypeForBitwidth( 7351 LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0); 7352 Upper = 7353 SemaRef 7354 .PerformImplicitConversion( 7355 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 7356 CastType, Sema::AA_Converting) 7357 .get(); 7358 Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(); 7359 NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get()); 7360 } 7361 } 7362 if (!Lower || !Upper || NewStep.isInvalid()) 7363 return nullptr; 7364 7365 ExprResult Diff; 7366 // If need to reorganize, then calculate the form as Upper - (Lower - Step [+ 7367 // 1]). 7368 if (NeedToReorganize) { 7369 Diff = Lower; 7370 7371 if (RoundToStep) { 7372 // Lower - Step 7373 Diff = 7374 SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get()); 7375 if (!Diff.isUsable()) 7376 return nullptr; 7377 } 7378 7379 // Lower - Step [+ 1] 7380 if (TestIsStrictOp) 7381 Diff = SemaRef.BuildBinOp( 7382 S, DefaultLoc, BO_Add, Diff.get(), 7383 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 7384 if (!Diff.isUsable()) 7385 return nullptr; 7386 7387 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 7388 if (!Diff.isUsable()) 7389 return nullptr; 7390 7391 // Upper - (Lower - Step [+ 1]). 7392 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get()); 7393 if (!Diff.isUsable()) 7394 return nullptr; 7395 } else { 7396 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 7397 7398 if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) { 7399 // BuildBinOp already emitted error, this one is to point user to upper 7400 // and lower bound, and to tell what is passed to 'operator-'. 7401 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 7402 << Upper->getSourceRange() << Lower->getSourceRange(); 7403 return nullptr; 7404 } 7405 7406 if (!Diff.isUsable()) 7407 return nullptr; 7408 7409 // Upper - Lower [- 1] 7410 if (TestIsStrictOp) 7411 Diff = SemaRef.BuildBinOp( 7412 S, DefaultLoc, BO_Sub, Diff.get(), 7413 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 7414 if (!Diff.isUsable()) 7415 return nullptr; 7416 7417 if (RoundToStep) { 7418 // Upper - Lower [- 1] + Step 7419 Diff = 7420 SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 7421 if (!Diff.isUsable()) 7422 return nullptr; 7423 } 7424 } 7425 7426 // Parentheses (for dumping/debugging purposes only). 7427 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 7428 if (!Diff.isUsable()) 7429 return nullptr; 7430 7431 // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step 7432 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 7433 if (!Diff.isUsable()) 7434 return nullptr; 7435 7436 return Diff.get(); 7437 } 7438 7439 /// Build the expression to calculate the number of iterations. 7440 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 7441 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 7442 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 7443 QualType VarType = LCDecl->getType().getNonReferenceType(); 7444 if (!VarType->isIntegerType() && !VarType->isPointerType() && 7445 !SemaRef.getLangOpts().CPlusPlus) 7446 return nullptr; 7447 Expr *LBVal = LB; 7448 Expr *UBVal = UB; 7449 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) : 7450 // max(LB(MinVal), LB(MaxVal)) 7451 if (InitDependOnLC) { 7452 const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1]; 7453 if (!IS.MinValue || !IS.MaxValue) 7454 return nullptr; 7455 // OuterVar = Min 7456 ExprResult MinValue = 7457 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 7458 if (!MinValue.isUsable()) 7459 return nullptr; 7460 7461 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 7462 IS.CounterVar, MinValue.get()); 7463 if (!LBMinVal.isUsable()) 7464 return nullptr; 7465 // OuterVar = Min, LBVal 7466 LBMinVal = 7467 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal); 7468 if (!LBMinVal.isUsable()) 7469 return nullptr; 7470 // (OuterVar = Min, LBVal) 7471 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get()); 7472 if (!LBMinVal.isUsable()) 7473 return nullptr; 7474 7475 // OuterVar = Max 7476 ExprResult MaxValue = 7477 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 7478 if (!MaxValue.isUsable()) 7479 return nullptr; 7480 7481 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 7482 IS.CounterVar, MaxValue.get()); 7483 if (!LBMaxVal.isUsable()) 7484 return nullptr; 7485 // OuterVar = Max, LBVal 7486 LBMaxVal = 7487 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal); 7488 if (!LBMaxVal.isUsable()) 7489 return nullptr; 7490 // (OuterVar = Max, LBVal) 7491 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get()); 7492 if (!LBMaxVal.isUsable()) 7493 return nullptr; 7494 7495 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get(); 7496 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get(); 7497 if (!LBMin || !LBMax) 7498 return nullptr; 7499 // LB(MinVal) < LB(MaxVal) 7500 ExprResult MinLessMaxRes = 7501 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax); 7502 if (!MinLessMaxRes.isUsable()) 7503 return nullptr; 7504 Expr *MinLessMax = 7505 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get(); 7506 if (!MinLessMax) 7507 return nullptr; 7508 if (TestIsLessOp.getValue()) { 7509 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal), 7510 // LB(MaxVal)) 7511 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 7512 MinLessMax, LBMin, LBMax); 7513 if (!MinLB.isUsable()) 7514 return nullptr; 7515 LBVal = MinLB.get(); 7516 } else { 7517 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal), 7518 // LB(MaxVal)) 7519 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 7520 MinLessMax, LBMax, LBMin); 7521 if (!MaxLB.isUsable()) 7522 return nullptr; 7523 LBVal = MaxLB.get(); 7524 } 7525 } 7526 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) : 7527 // min(UB(MinVal), UB(MaxVal)) 7528 if (CondDependOnLC) { 7529 const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1]; 7530 if (!IS.MinValue || !IS.MaxValue) 7531 return nullptr; 7532 // OuterVar = Min 7533 ExprResult MinValue = 7534 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 7535 if (!MinValue.isUsable()) 7536 return nullptr; 7537 7538 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 7539 IS.CounterVar, MinValue.get()); 7540 if (!UBMinVal.isUsable()) 7541 return nullptr; 7542 // OuterVar = Min, UBVal 7543 UBMinVal = 7544 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal); 7545 if (!UBMinVal.isUsable()) 7546 return nullptr; 7547 // (OuterVar = Min, UBVal) 7548 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get()); 7549 if (!UBMinVal.isUsable()) 7550 return nullptr; 7551 7552 // OuterVar = Max 7553 ExprResult MaxValue = 7554 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 7555 if (!MaxValue.isUsable()) 7556 return nullptr; 7557 7558 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 7559 IS.CounterVar, MaxValue.get()); 7560 if (!UBMaxVal.isUsable()) 7561 return nullptr; 7562 // OuterVar = Max, UBVal 7563 UBMaxVal = 7564 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal); 7565 if (!UBMaxVal.isUsable()) 7566 return nullptr; 7567 // (OuterVar = Max, UBVal) 7568 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get()); 7569 if (!UBMaxVal.isUsable()) 7570 return nullptr; 7571 7572 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get(); 7573 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get(); 7574 if (!UBMin || !UBMax) 7575 return nullptr; 7576 // UB(MinVal) > UB(MaxVal) 7577 ExprResult MinGreaterMaxRes = 7578 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax); 7579 if (!MinGreaterMaxRes.isUsable()) 7580 return nullptr; 7581 Expr *MinGreaterMax = 7582 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get(); 7583 if (!MinGreaterMax) 7584 return nullptr; 7585 if (TestIsLessOp.getValue()) { 7586 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal), 7587 // UB(MaxVal)) 7588 ExprResult MaxUB = SemaRef.ActOnConditionalOp( 7589 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax); 7590 if (!MaxUB.isUsable()) 7591 return nullptr; 7592 UBVal = MaxUB.get(); 7593 } else { 7594 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal), 7595 // UB(MaxVal)) 7596 ExprResult MinUB = SemaRef.ActOnConditionalOp( 7597 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin); 7598 if (!MinUB.isUsable()) 7599 return nullptr; 7600 UBVal = MinUB.get(); 7601 } 7602 } 7603 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal; 7604 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal; 7605 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 7606 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 7607 if (!Upper || !Lower) 7608 return nullptr; 7609 7610 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 7611 Step, VarType, TestIsStrictOp, 7612 /*RoundToStep=*/true, Captures); 7613 if (!Diff.isUsable()) 7614 return nullptr; 7615 7616 // OpenMP runtime requires 32-bit or 64-bit loop variables. 7617 QualType Type = Diff.get()->getType(); 7618 ASTContext &C = SemaRef.Context; 7619 bool UseVarType = VarType->hasIntegerRepresentation() && 7620 C.getTypeSize(Type) > C.getTypeSize(VarType); 7621 if (!Type->isIntegerType() || UseVarType) { 7622 unsigned NewSize = 7623 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 7624 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 7625 : Type->hasSignedIntegerRepresentation(); 7626 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 7627 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 7628 Diff = SemaRef.PerformImplicitConversion( 7629 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 7630 if (!Diff.isUsable()) 7631 return nullptr; 7632 } 7633 } 7634 if (LimitedType) { 7635 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 7636 if (NewSize != C.getTypeSize(Type)) { 7637 if (NewSize < C.getTypeSize(Type)) { 7638 assert(NewSize == 64 && "incorrect loop var size"); 7639 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 7640 << InitSrcRange << ConditionSrcRange; 7641 } 7642 QualType NewType = C.getIntTypeForBitwidth( 7643 NewSize, Type->hasSignedIntegerRepresentation() || 7644 C.getTypeSize(Type) < NewSize); 7645 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 7646 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 7647 Sema::AA_Converting, true); 7648 if (!Diff.isUsable()) 7649 return nullptr; 7650 } 7651 } 7652 } 7653 7654 return Diff.get(); 7655 } 7656 7657 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues( 7658 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 7659 // Do not build for iterators, they cannot be used in non-rectangular loop 7660 // nests. 7661 if (LCDecl->getType()->isRecordType()) 7662 return std::make_pair(nullptr, nullptr); 7663 // If we subtract, the min is in the condition, otherwise the min is in the 7664 // init value. 7665 Expr *MinExpr = nullptr; 7666 Expr *MaxExpr = nullptr; 7667 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 7668 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 7669 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue() 7670 : CondDependOnLC.hasValue(); 7671 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue() 7672 : InitDependOnLC.hasValue(); 7673 Expr *Lower = 7674 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get(); 7675 Expr *Upper = 7676 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get(); 7677 if (!Upper || !Lower) 7678 return std::make_pair(nullptr, nullptr); 7679 7680 if (TestIsLessOp.getValue()) 7681 MinExpr = Lower; 7682 else 7683 MaxExpr = Upper; 7684 7685 // Build minimum/maximum value based on number of iterations. 7686 QualType VarType = LCDecl->getType().getNonReferenceType(); 7687 7688 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 7689 Step, VarType, TestIsStrictOp, 7690 /*RoundToStep=*/false, Captures); 7691 if (!Diff.isUsable()) 7692 return std::make_pair(nullptr, nullptr); 7693 7694 // ((Upper - Lower [- 1]) / Step) * Step 7695 // Parentheses (for dumping/debugging purposes only). 7696 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 7697 if (!Diff.isUsable()) 7698 return std::make_pair(nullptr, nullptr); 7699 7700 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 7701 if (!NewStep.isUsable()) 7702 return std::make_pair(nullptr, nullptr); 7703 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get()); 7704 if (!Diff.isUsable()) 7705 return std::make_pair(nullptr, nullptr); 7706 7707 // Parentheses (for dumping/debugging purposes only). 7708 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 7709 if (!Diff.isUsable()) 7710 return std::make_pair(nullptr, nullptr); 7711 7712 // Convert to the ptrdiff_t, if original type is pointer. 7713 if (VarType->isAnyPointerType() && 7714 !SemaRef.Context.hasSameType( 7715 Diff.get()->getType(), 7716 SemaRef.Context.getUnsignedPointerDiffType())) { 7717 Diff = SemaRef.PerformImplicitConversion( 7718 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(), 7719 Sema::AA_Converting, /*AllowExplicit=*/true); 7720 } 7721 if (!Diff.isUsable()) 7722 return std::make_pair(nullptr, nullptr); 7723 7724 if (TestIsLessOp.getValue()) { 7725 // MinExpr = Lower; 7726 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step) 7727 Diff = SemaRef.BuildBinOp( 7728 S, DefaultLoc, BO_Add, 7729 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(), 7730 Diff.get()); 7731 if (!Diff.isUsable()) 7732 return std::make_pair(nullptr, nullptr); 7733 } else { 7734 // MaxExpr = Upper; 7735 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step) 7736 Diff = SemaRef.BuildBinOp( 7737 S, DefaultLoc, BO_Sub, 7738 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 7739 Diff.get()); 7740 if (!Diff.isUsable()) 7741 return std::make_pair(nullptr, nullptr); 7742 } 7743 7744 // Convert to the original type. 7745 if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) 7746 Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType, 7747 Sema::AA_Converting, 7748 /*AllowExplicit=*/true); 7749 if (!Diff.isUsable()) 7750 return std::make_pair(nullptr, nullptr); 7751 7752 Sema::TentativeAnalysisScope Trap(SemaRef); 7753 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false); 7754 if (!Diff.isUsable()) 7755 return std::make_pair(nullptr, nullptr); 7756 7757 if (TestIsLessOp.getValue()) 7758 MaxExpr = Diff.get(); 7759 else 7760 MinExpr = Diff.get(); 7761 7762 return std::make_pair(MinExpr, MaxExpr); 7763 } 7764 7765 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const { 7766 if (InitDependOnLC || CondDependOnLC) 7767 return Condition; 7768 return nullptr; 7769 } 7770 7771 Expr *OpenMPIterationSpaceChecker::buildPreCond( 7772 Scope *S, Expr *Cond, 7773 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 7774 // Do not build a precondition when the condition/initialization is dependent 7775 // to prevent pessimistic early loop exit. 7776 // TODO: this can be improved by calculating min/max values but not sure that 7777 // it will be very effective. 7778 if (CondDependOnLC || InitDependOnLC) 7779 return SemaRef.PerformImplicitConversion( 7780 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(), 7781 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 7782 /*AllowExplicit=*/true).get(); 7783 7784 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 7785 Sema::TentativeAnalysisScope Trap(SemaRef); 7786 7787 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 7788 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 7789 if (!NewLB.isUsable() || !NewUB.isUsable()) 7790 return nullptr; 7791 7792 ExprResult CondExpr = 7793 SemaRef.BuildBinOp(S, DefaultLoc, 7794 TestIsLessOp.getValue() ? 7795 (TestIsStrictOp ? BO_LT : BO_LE) : 7796 (TestIsStrictOp ? BO_GT : BO_GE), 7797 NewLB.get(), NewUB.get()); 7798 if (CondExpr.isUsable()) { 7799 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 7800 SemaRef.Context.BoolTy)) 7801 CondExpr = SemaRef.PerformImplicitConversion( 7802 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 7803 /*AllowExplicit=*/true); 7804 } 7805 7806 // Otherwise use original loop condition and evaluate it in runtime. 7807 return CondExpr.isUsable() ? CondExpr.get() : Cond; 7808 } 7809 7810 /// Build reference expression to the counter be used for codegen. 7811 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 7812 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7813 DSAStackTy &DSA) const { 7814 auto *VD = dyn_cast<VarDecl>(LCDecl); 7815 if (!VD) { 7816 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 7817 DeclRefExpr *Ref = buildDeclRefExpr( 7818 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 7819 const DSAStackTy::DSAVarData Data = 7820 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 7821 // If the loop control decl is explicitly marked as private, do not mark it 7822 // as captured again. 7823 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 7824 Captures.insert(std::make_pair(LCRef, Ref)); 7825 return Ref; 7826 } 7827 return cast<DeclRefExpr>(LCRef); 7828 } 7829 7830 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 7831 if (LCDecl && !LCDecl->isInvalidDecl()) { 7832 QualType Type = LCDecl->getType().getNonReferenceType(); 7833 VarDecl *PrivateVar = buildVarDecl( 7834 SemaRef, DefaultLoc, Type, LCDecl->getName(), 7835 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 7836 isa<VarDecl>(LCDecl) 7837 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 7838 : nullptr); 7839 if (PrivateVar->isInvalidDecl()) 7840 return nullptr; 7841 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 7842 } 7843 return nullptr; 7844 } 7845 7846 /// Build initialization of the counter to be used for codegen. 7847 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 7848 7849 /// Build step of the counter be used for codegen. 7850 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 7851 7852 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 7853 Scope *S, Expr *Counter, 7854 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 7855 Expr *Inc, OverloadedOperatorKind OOK) { 7856 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 7857 if (!Cnt) 7858 return nullptr; 7859 if (Inc) { 7860 assert((OOK == OO_Plus || OOK == OO_Minus) && 7861 "Expected only + or - operations for depend clauses."); 7862 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 7863 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 7864 if (!Cnt) 7865 return nullptr; 7866 } 7867 QualType VarType = LCDecl->getType().getNonReferenceType(); 7868 if (!VarType->isIntegerType() && !VarType->isPointerType() && 7869 !SemaRef.getLangOpts().CPlusPlus) 7870 return nullptr; 7871 // Upper - Lower 7872 Expr *Upper = TestIsLessOp.getValue() 7873 ? Cnt 7874 : tryBuildCapture(SemaRef, LB, Captures).get(); 7875 Expr *Lower = TestIsLessOp.getValue() 7876 ? tryBuildCapture(SemaRef, LB, Captures).get() 7877 : Cnt; 7878 if (!Upper || !Lower) 7879 return nullptr; 7880 7881 ExprResult Diff = calculateNumIters( 7882 SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType, 7883 /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures); 7884 if (!Diff.isUsable()) 7885 return nullptr; 7886 7887 return Diff.get(); 7888 } 7889 } // namespace 7890 7891 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 7892 assert(getLangOpts().OpenMP && "OpenMP is not active."); 7893 assert(Init && "Expected loop in canonical form."); 7894 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 7895 if (AssociatedLoops > 0 && 7896 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 7897 DSAStack->loopStart(); 7898 OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true, 7899 *DSAStack, ForLoc); 7900 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 7901 if (ValueDecl *D = ISC.getLoopDecl()) { 7902 auto *VD = dyn_cast<VarDecl>(D); 7903 DeclRefExpr *PrivateRef = nullptr; 7904 if (!VD) { 7905 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 7906 VD = Private; 7907 } else { 7908 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 7909 /*WithInit=*/false); 7910 VD = cast<VarDecl>(PrivateRef->getDecl()); 7911 } 7912 } 7913 DSAStack->addLoopControlVariable(D, VD); 7914 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 7915 if (LD != D->getCanonicalDecl()) { 7916 DSAStack->resetPossibleLoopCounter(); 7917 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 7918 MarkDeclarationsReferencedInExpr( 7919 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 7920 Var->getType().getNonLValueExprType(Context), 7921 ForLoc, /*RefersToCapture=*/true)); 7922 } 7923 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7924 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables 7925 // Referenced in a Construct, C/C++]. The loop iteration variable in the 7926 // associated for-loop of a simd construct with just one associated 7927 // for-loop may be listed in a linear clause with a constant-linear-step 7928 // that is the increment of the associated for-loop. The loop iteration 7929 // variable(s) in the associated for-loop(s) of a for or parallel for 7930 // construct may be listed in a private or lastprivate clause. 7931 DSAStackTy::DSAVarData DVar = 7932 DSAStack->getTopDSA(D, /*FromParent=*/false); 7933 // If LoopVarRefExpr is nullptr it means the corresponding loop variable 7934 // is declared in the loop and it is predetermined as a private. 7935 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 7936 OpenMPClauseKind PredeterminedCKind = 7937 isOpenMPSimdDirective(DKind) 7938 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear) 7939 : OMPC_private; 7940 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 7941 DVar.CKind != PredeterminedCKind && DVar.RefExpr && 7942 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate && 7943 DVar.CKind != OMPC_private))) || 7944 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 7945 DKind == OMPD_master_taskloop || 7946 DKind == OMPD_parallel_master_taskloop || 7947 isOpenMPDistributeDirective(DKind)) && 7948 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 7949 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 7950 (DVar.CKind != OMPC_private || DVar.RefExpr)) { 7951 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 7952 << getOpenMPClauseName(DVar.CKind) 7953 << getOpenMPDirectiveName(DKind) 7954 << getOpenMPClauseName(PredeterminedCKind); 7955 if (DVar.RefExpr == nullptr) 7956 DVar.CKind = PredeterminedCKind; 7957 reportOriginalDsa(*this, DSAStack, D, DVar, 7958 /*IsLoopIterVar=*/true); 7959 } else if (LoopDeclRefExpr) { 7960 // Make the loop iteration variable private (for worksharing 7961 // constructs), linear (for simd directives with the only one 7962 // associated loop) or lastprivate (for simd directives with several 7963 // collapsed or ordered loops). 7964 if (DVar.CKind == OMPC_unknown) 7965 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind, 7966 PrivateRef); 7967 } 7968 } 7969 } 7970 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 7971 } 7972 } 7973 7974 /// Called on a for stmt to check and extract its iteration space 7975 /// for further processing (such as collapsing). 7976 static bool checkOpenMPIterationSpace( 7977 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 7978 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 7979 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 7980 Expr *OrderedLoopCountExpr, 7981 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 7982 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces, 7983 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 7984 bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind); 7985 // OpenMP [2.9.1, Canonical Loop Form] 7986 // for (init-expr; test-expr; incr-expr) structured-block 7987 // for (range-decl: range-expr) structured-block 7988 auto *For = dyn_cast_or_null<ForStmt>(S); 7989 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S); 7990 // Ranged for is supported only in OpenMP 5.0. 7991 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) { 7992 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 7993 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 7994 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 7995 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 7996 if (TotalNestedLoopCount > 1) { 7997 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 7998 SemaRef.Diag(DSA.getConstructLoc(), 7999 diag::note_omp_collapse_ordered_expr) 8000 << 2 << CollapseLoopCountExpr->getSourceRange() 8001 << OrderedLoopCountExpr->getSourceRange(); 8002 else if (CollapseLoopCountExpr) 8003 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 8004 diag::note_omp_collapse_ordered_expr) 8005 << 0 << CollapseLoopCountExpr->getSourceRange(); 8006 else 8007 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 8008 diag::note_omp_collapse_ordered_expr) 8009 << 1 << OrderedLoopCountExpr->getSourceRange(); 8010 } 8011 return true; 8012 } 8013 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) && 8014 "No loop body."); 8015 8016 OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA, 8017 For ? For->getForLoc() : CXXFor->getForLoc()); 8018 8019 // Check init. 8020 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt(); 8021 if (ISC.checkAndSetInit(Init)) 8022 return true; 8023 8024 bool HasErrors = false; 8025 8026 // Check loop variable's type. 8027 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 8028 // OpenMP [2.6, Canonical Loop Form] 8029 // Var is one of the following: 8030 // A variable of signed or unsigned integer type. 8031 // For C++, a variable of a random access iterator type. 8032 // For C, a variable of a pointer type. 8033 QualType VarType = LCDecl->getType().getNonReferenceType(); 8034 if (!VarType->isDependentType() && !VarType->isIntegerType() && 8035 !VarType->isPointerType() && 8036 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 8037 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 8038 << SemaRef.getLangOpts().CPlusPlus; 8039 HasErrors = true; 8040 } 8041 8042 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 8043 // a Construct 8044 // The loop iteration variable(s) in the associated for-loop(s) of a for or 8045 // parallel for construct is (are) private. 8046 // The loop iteration variable in the associated for-loop of a simd 8047 // construct with just one associated for-loop is linear with a 8048 // constant-linear-step that is the increment of the associated for-loop. 8049 // Exclude loop var from the list of variables with implicitly defined data 8050 // sharing attributes. 8051 VarsWithImplicitDSA.erase(LCDecl); 8052 8053 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 8054 8055 // Check test-expr. 8056 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond()); 8057 8058 // Check incr-expr. 8059 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc()); 8060 } 8061 8062 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 8063 return HasErrors; 8064 8065 // Build the loop's iteration space representation. 8066 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond( 8067 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures); 8068 ResultIterSpaces[CurrentNestedLoopCount].NumIterations = 8069 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces, 8070 (isOpenMPWorksharingDirective(DKind) || 8071 isOpenMPTaskLoopDirective(DKind) || 8072 isOpenMPDistributeDirective(DKind) || 8073 isOpenMPLoopTransformationDirective(DKind)), 8074 Captures); 8075 ResultIterSpaces[CurrentNestedLoopCount].CounterVar = 8076 ISC.buildCounterVar(Captures, DSA); 8077 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar = 8078 ISC.buildPrivateCounterVar(); 8079 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit(); 8080 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep(); 8081 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange(); 8082 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange = 8083 ISC.getConditionSrcRange(); 8084 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange = 8085 ISC.getIncrementSrcRange(); 8086 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep(); 8087 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare = 8088 ISC.isStrictTestOp(); 8089 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue, 8090 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) = 8091 ISC.buildMinMaxValues(DSA.getCurScope(), Captures); 8092 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition = 8093 ISC.buildFinalCondition(DSA.getCurScope()); 8094 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB = 8095 ISC.doesInitDependOnLC(); 8096 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB = 8097 ISC.doesCondDependOnLC(); 8098 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx = 8099 ISC.getLoopDependentIdx(); 8100 8101 HasErrors |= 8102 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr || 8103 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr || 8104 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr || 8105 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr || 8106 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr || 8107 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr); 8108 if (!HasErrors && DSA.isOrderedRegion()) { 8109 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 8110 if (CurrentNestedLoopCount < 8111 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 8112 DSA.getOrderedRegionParam().second->setLoopNumIterations( 8113 CurrentNestedLoopCount, 8114 ResultIterSpaces[CurrentNestedLoopCount].NumIterations); 8115 DSA.getOrderedRegionParam().second->setLoopCounter( 8116 CurrentNestedLoopCount, 8117 ResultIterSpaces[CurrentNestedLoopCount].CounterVar); 8118 } 8119 } 8120 for (auto &Pair : DSA.getDoacrossDependClauses()) { 8121 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 8122 // Erroneous case - clause has some problems. 8123 continue; 8124 } 8125 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 8126 Pair.second.size() <= CurrentNestedLoopCount) { 8127 // Erroneous case - clause has some problems. 8128 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 8129 continue; 8130 } 8131 Expr *CntValue; 8132 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 8133 CntValue = ISC.buildOrderedLoopData( 8134 DSA.getCurScope(), 8135 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 8136 Pair.first->getDependencyLoc()); 8137 else 8138 CntValue = ISC.buildOrderedLoopData( 8139 DSA.getCurScope(), 8140 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 8141 Pair.first->getDependencyLoc(), 8142 Pair.second[CurrentNestedLoopCount].first, 8143 Pair.second[CurrentNestedLoopCount].second); 8144 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 8145 } 8146 } 8147 8148 return HasErrors; 8149 } 8150 8151 /// Build 'VarRef = Start. 8152 static ExprResult 8153 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 8154 ExprResult Start, bool IsNonRectangularLB, 8155 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8156 // Build 'VarRef = Start. 8157 ExprResult NewStart = IsNonRectangularLB 8158 ? Start.get() 8159 : tryBuildCapture(SemaRef, Start.get(), Captures); 8160 if (!NewStart.isUsable()) 8161 return ExprError(); 8162 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 8163 VarRef.get()->getType())) { 8164 NewStart = SemaRef.PerformImplicitConversion( 8165 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 8166 /*AllowExplicit=*/true); 8167 if (!NewStart.isUsable()) 8168 return ExprError(); 8169 } 8170 8171 ExprResult Init = 8172 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 8173 return Init; 8174 } 8175 8176 /// Build 'VarRef = Start + Iter * Step'. 8177 static ExprResult buildCounterUpdate( 8178 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 8179 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 8180 bool IsNonRectangularLB, 8181 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 8182 // Add parentheses (for debugging purposes only). 8183 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 8184 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 8185 !Step.isUsable()) 8186 return ExprError(); 8187 8188 ExprResult NewStep = Step; 8189 if (Captures) 8190 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 8191 if (NewStep.isInvalid()) 8192 return ExprError(); 8193 ExprResult Update = 8194 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 8195 if (!Update.isUsable()) 8196 return ExprError(); 8197 8198 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 8199 // 'VarRef = Start (+|-) Iter * Step'. 8200 if (!Start.isUsable()) 8201 return ExprError(); 8202 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get()); 8203 if (!NewStart.isUsable()) 8204 return ExprError(); 8205 if (Captures && !IsNonRectangularLB) 8206 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 8207 if (NewStart.isInvalid()) 8208 return ExprError(); 8209 8210 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 8211 ExprResult SavedUpdate = Update; 8212 ExprResult UpdateVal; 8213 if (VarRef.get()->getType()->isOverloadableType() || 8214 NewStart.get()->getType()->isOverloadableType() || 8215 Update.get()->getType()->isOverloadableType()) { 8216 Sema::TentativeAnalysisScope Trap(SemaRef); 8217 8218 Update = 8219 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 8220 if (Update.isUsable()) { 8221 UpdateVal = 8222 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 8223 VarRef.get(), SavedUpdate.get()); 8224 if (UpdateVal.isUsable()) { 8225 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 8226 UpdateVal.get()); 8227 } 8228 } 8229 } 8230 8231 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 8232 if (!Update.isUsable() || !UpdateVal.isUsable()) { 8233 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 8234 NewStart.get(), SavedUpdate.get()); 8235 if (!Update.isUsable()) 8236 return ExprError(); 8237 8238 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 8239 VarRef.get()->getType())) { 8240 Update = SemaRef.PerformImplicitConversion( 8241 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 8242 if (!Update.isUsable()) 8243 return ExprError(); 8244 } 8245 8246 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 8247 } 8248 return Update; 8249 } 8250 8251 /// Convert integer expression \a E to make it have at least \a Bits 8252 /// bits. 8253 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 8254 if (E == nullptr) 8255 return ExprError(); 8256 ASTContext &C = SemaRef.Context; 8257 QualType OldType = E->getType(); 8258 unsigned HasBits = C.getTypeSize(OldType); 8259 if (HasBits >= Bits) 8260 return ExprResult(E); 8261 // OK to convert to signed, because new type has more bits than old. 8262 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 8263 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 8264 true); 8265 } 8266 8267 /// Check if the given expression \a E is a constant integer that fits 8268 /// into \a Bits bits. 8269 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 8270 if (E == nullptr) 8271 return false; 8272 if (Optional<llvm::APSInt> Result = 8273 E->getIntegerConstantExpr(SemaRef.Context)) 8274 return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits); 8275 return false; 8276 } 8277 8278 /// Build preinits statement for the given declarations. 8279 static Stmt *buildPreInits(ASTContext &Context, 8280 MutableArrayRef<Decl *> PreInits) { 8281 if (!PreInits.empty()) { 8282 return new (Context) DeclStmt( 8283 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 8284 SourceLocation(), SourceLocation()); 8285 } 8286 return nullptr; 8287 } 8288 8289 /// Build preinits statement for the given declarations. 8290 static Stmt * 8291 buildPreInits(ASTContext &Context, 8292 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8293 if (!Captures.empty()) { 8294 SmallVector<Decl *, 16> PreInits; 8295 for (const auto &Pair : Captures) 8296 PreInits.push_back(Pair.second->getDecl()); 8297 return buildPreInits(Context, PreInits); 8298 } 8299 return nullptr; 8300 } 8301 8302 /// Build postupdate expression for the given list of postupdates expressions. 8303 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 8304 Expr *PostUpdate = nullptr; 8305 if (!PostUpdates.empty()) { 8306 for (Expr *E : PostUpdates) { 8307 Expr *ConvE = S.BuildCStyleCastExpr( 8308 E->getExprLoc(), 8309 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 8310 E->getExprLoc(), E) 8311 .get(); 8312 PostUpdate = PostUpdate 8313 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 8314 PostUpdate, ConvE) 8315 .get() 8316 : ConvE; 8317 } 8318 } 8319 return PostUpdate; 8320 } 8321 8322 /// Called on a for stmt to check itself and nested loops (if any). 8323 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 8324 /// number of collapsed loops otherwise. 8325 static unsigned 8326 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 8327 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 8328 DSAStackTy &DSA, 8329 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 8330 OMPLoopBasedDirective::HelperExprs &Built) { 8331 unsigned NestedLoopCount = 1; 8332 bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) && 8333 !isOpenMPLoopTransformationDirective(DKind); 8334 8335 if (CollapseLoopCountExpr) { 8336 // Found 'collapse' clause - calculate collapse number. 8337 Expr::EvalResult Result; 8338 if (!CollapseLoopCountExpr->isValueDependent() && 8339 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 8340 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 8341 } else { 8342 Built.clear(/*Size=*/1); 8343 return 1; 8344 } 8345 } 8346 unsigned OrderedLoopCount = 1; 8347 if (OrderedLoopCountExpr) { 8348 // Found 'ordered' clause - calculate collapse number. 8349 Expr::EvalResult EVResult; 8350 if (!OrderedLoopCountExpr->isValueDependent() && 8351 OrderedLoopCountExpr->EvaluateAsInt(EVResult, 8352 SemaRef.getASTContext())) { 8353 llvm::APSInt Result = EVResult.Val.getInt(); 8354 if (Result.getLimitedValue() < NestedLoopCount) { 8355 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 8356 diag::err_omp_wrong_ordered_loop_count) 8357 << OrderedLoopCountExpr->getSourceRange(); 8358 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 8359 diag::note_collapse_loop_count) 8360 << CollapseLoopCountExpr->getSourceRange(); 8361 } 8362 OrderedLoopCount = Result.getLimitedValue(); 8363 } else { 8364 Built.clear(/*Size=*/1); 8365 return 1; 8366 } 8367 } 8368 // This is helper routine for loop directives (e.g., 'for', 'simd', 8369 // 'for simd', etc.). 8370 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 8371 unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount); 8372 SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops); 8373 if (!OMPLoopBasedDirective::doForAllLoops( 8374 AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)), 8375 SupportsNonPerfectlyNested, NumLoops, 8376 [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount, 8377 CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA, 8378 &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) { 8379 if (checkOpenMPIterationSpace( 8380 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 8381 NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr, 8382 VarsWithImplicitDSA, IterSpaces, Captures)) 8383 return true; 8384 if (Cnt > 0 && Cnt >= NestedLoopCount && 8385 IterSpaces[Cnt].CounterVar) { 8386 // Handle initialization of captured loop iterator variables. 8387 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 8388 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 8389 Captures[DRE] = DRE; 8390 } 8391 } 8392 return false; 8393 })) 8394 return 0; 8395 8396 Built.clear(/* size */ NestedLoopCount); 8397 8398 if (SemaRef.CurContext->isDependentContext()) 8399 return NestedLoopCount; 8400 8401 // An example of what is generated for the following code: 8402 // 8403 // #pragma omp simd collapse(2) ordered(2) 8404 // for (i = 0; i < NI; ++i) 8405 // for (k = 0; k < NK; ++k) 8406 // for (j = J0; j < NJ; j+=2) { 8407 // <loop body> 8408 // } 8409 // 8410 // We generate the code below. 8411 // Note: the loop body may be outlined in CodeGen. 8412 // Note: some counters may be C++ classes, operator- is used to find number of 8413 // iterations and operator+= to calculate counter value. 8414 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 8415 // or i64 is currently supported). 8416 // 8417 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 8418 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 8419 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 8420 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 8421 // // similar updates for vars in clauses (e.g. 'linear') 8422 // <loop body (using local i and j)> 8423 // } 8424 // i = NI; // assign final values of counters 8425 // j = NJ; 8426 // 8427 8428 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 8429 // the iteration counts of the collapsed for loops. 8430 // Precondition tests if there is at least one iteration (all conditions are 8431 // true). 8432 auto PreCond = ExprResult(IterSpaces[0].PreCond); 8433 Expr *N0 = IterSpaces[0].NumIterations; 8434 ExprResult LastIteration32 = 8435 widenIterationCount(/*Bits=*/32, 8436 SemaRef 8437 .PerformImplicitConversion( 8438 N0->IgnoreImpCasts(), N0->getType(), 8439 Sema::AA_Converting, /*AllowExplicit=*/true) 8440 .get(), 8441 SemaRef); 8442 ExprResult LastIteration64 = widenIterationCount( 8443 /*Bits=*/64, 8444 SemaRef 8445 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 8446 Sema::AA_Converting, 8447 /*AllowExplicit=*/true) 8448 .get(), 8449 SemaRef); 8450 8451 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 8452 return NestedLoopCount; 8453 8454 ASTContext &C = SemaRef.Context; 8455 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 8456 8457 Scope *CurScope = DSA.getCurScope(); 8458 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 8459 if (PreCond.isUsable()) { 8460 PreCond = 8461 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 8462 PreCond.get(), IterSpaces[Cnt].PreCond); 8463 } 8464 Expr *N = IterSpaces[Cnt].NumIterations; 8465 SourceLocation Loc = N->getExprLoc(); 8466 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 8467 if (LastIteration32.isUsable()) 8468 LastIteration32 = SemaRef.BuildBinOp( 8469 CurScope, Loc, BO_Mul, LastIteration32.get(), 8470 SemaRef 8471 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 8472 Sema::AA_Converting, 8473 /*AllowExplicit=*/true) 8474 .get()); 8475 if (LastIteration64.isUsable()) 8476 LastIteration64 = SemaRef.BuildBinOp( 8477 CurScope, Loc, BO_Mul, LastIteration64.get(), 8478 SemaRef 8479 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 8480 Sema::AA_Converting, 8481 /*AllowExplicit=*/true) 8482 .get()); 8483 } 8484 8485 // Choose either the 32-bit or 64-bit version. 8486 ExprResult LastIteration = LastIteration64; 8487 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 8488 (LastIteration32.isUsable() && 8489 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 8490 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 8491 fitsInto( 8492 /*Bits=*/32, 8493 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 8494 LastIteration64.get(), SemaRef)))) 8495 LastIteration = LastIteration32; 8496 QualType VType = LastIteration.get()->getType(); 8497 QualType RealVType = VType; 8498 QualType StrideVType = VType; 8499 if (isOpenMPTaskLoopDirective(DKind)) { 8500 VType = 8501 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 8502 StrideVType = 8503 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 8504 } 8505 8506 if (!LastIteration.isUsable()) 8507 return 0; 8508 8509 // Save the number of iterations. 8510 ExprResult NumIterations = LastIteration; 8511 { 8512 LastIteration = SemaRef.BuildBinOp( 8513 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 8514 LastIteration.get(), 8515 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8516 if (!LastIteration.isUsable()) 8517 return 0; 8518 } 8519 8520 // Calculate the last iteration number beforehand instead of doing this on 8521 // each iteration. Do not do this if the number of iterations may be kfold-ed. 8522 bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context); 8523 ExprResult CalcLastIteration; 8524 if (!IsConstant) { 8525 ExprResult SaveRef = 8526 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 8527 LastIteration = SaveRef; 8528 8529 // Prepare SaveRef + 1. 8530 NumIterations = SemaRef.BuildBinOp( 8531 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 8532 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8533 if (!NumIterations.isUsable()) 8534 return 0; 8535 } 8536 8537 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 8538 8539 // Build variables passed into runtime, necessary for worksharing directives. 8540 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 8541 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 8542 isOpenMPDistributeDirective(DKind) || 8543 isOpenMPLoopTransformationDirective(DKind)) { 8544 // Lower bound variable, initialized with zero. 8545 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 8546 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 8547 SemaRef.AddInitializerToDecl(LBDecl, 8548 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 8549 /*DirectInit*/ false); 8550 8551 // Upper bound variable, initialized with last iteration number. 8552 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 8553 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 8554 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 8555 /*DirectInit*/ false); 8556 8557 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 8558 // This will be used to implement clause 'lastprivate'. 8559 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 8560 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 8561 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 8562 SemaRef.AddInitializerToDecl(ILDecl, 8563 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 8564 /*DirectInit*/ false); 8565 8566 // Stride variable returned by runtime (we initialize it to 1 by default). 8567 VarDecl *STDecl = 8568 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 8569 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 8570 SemaRef.AddInitializerToDecl(STDecl, 8571 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 8572 /*DirectInit*/ false); 8573 8574 // Build expression: UB = min(UB, LastIteration) 8575 // It is necessary for CodeGen of directives with static scheduling. 8576 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 8577 UB.get(), LastIteration.get()); 8578 ExprResult CondOp = SemaRef.ActOnConditionalOp( 8579 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 8580 LastIteration.get(), UB.get()); 8581 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 8582 CondOp.get()); 8583 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 8584 8585 // If we have a combined directive that combines 'distribute', 'for' or 8586 // 'simd' we need to be able to access the bounds of the schedule of the 8587 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 8588 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 8589 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8590 // Lower bound variable, initialized with zero. 8591 VarDecl *CombLBDecl = 8592 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 8593 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 8594 SemaRef.AddInitializerToDecl( 8595 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 8596 /*DirectInit*/ false); 8597 8598 // Upper bound variable, initialized with last iteration number. 8599 VarDecl *CombUBDecl = 8600 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 8601 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 8602 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 8603 /*DirectInit*/ false); 8604 8605 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 8606 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 8607 ExprResult CombCondOp = 8608 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 8609 LastIteration.get(), CombUB.get()); 8610 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 8611 CombCondOp.get()); 8612 CombEUB = 8613 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 8614 8615 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 8616 // We expect to have at least 2 more parameters than the 'parallel' 8617 // directive does - the lower and upper bounds of the previous schedule. 8618 assert(CD->getNumParams() >= 4 && 8619 "Unexpected number of parameters in loop combined directive"); 8620 8621 // Set the proper type for the bounds given what we learned from the 8622 // enclosed loops. 8623 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 8624 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 8625 8626 // Previous lower and upper bounds are obtained from the region 8627 // parameters. 8628 PrevLB = 8629 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 8630 PrevUB = 8631 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 8632 } 8633 } 8634 8635 // Build the iteration variable and its initialization before loop. 8636 ExprResult IV; 8637 ExprResult Init, CombInit; 8638 { 8639 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 8640 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 8641 Expr *RHS = (isOpenMPWorksharingDirective(DKind) || 8642 isOpenMPTaskLoopDirective(DKind) || 8643 isOpenMPDistributeDirective(DKind) || 8644 isOpenMPLoopTransformationDirective(DKind)) 8645 ? LB.get() 8646 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 8647 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 8648 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 8649 8650 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8651 Expr *CombRHS = 8652 (isOpenMPWorksharingDirective(DKind) || 8653 isOpenMPTaskLoopDirective(DKind) || 8654 isOpenMPDistributeDirective(DKind)) 8655 ? CombLB.get() 8656 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 8657 CombInit = 8658 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 8659 CombInit = 8660 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 8661 } 8662 } 8663 8664 bool UseStrictCompare = 8665 RealVType->hasUnsignedIntegerRepresentation() && 8666 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 8667 return LIS.IsStrictCompare; 8668 }); 8669 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 8670 // unsigned IV)) for worksharing loops. 8671 SourceLocation CondLoc = AStmt->getBeginLoc(); 8672 Expr *BoundUB = UB.get(); 8673 if (UseStrictCompare) { 8674 BoundUB = 8675 SemaRef 8676 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 8677 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 8678 .get(); 8679 BoundUB = 8680 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 8681 } 8682 ExprResult Cond = 8683 (isOpenMPWorksharingDirective(DKind) || 8684 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) || 8685 isOpenMPLoopTransformationDirective(DKind)) 8686 ? SemaRef.BuildBinOp(CurScope, CondLoc, 8687 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 8688 BoundUB) 8689 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 8690 NumIterations.get()); 8691 ExprResult CombDistCond; 8692 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8693 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 8694 NumIterations.get()); 8695 } 8696 8697 ExprResult CombCond; 8698 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8699 Expr *BoundCombUB = CombUB.get(); 8700 if (UseStrictCompare) { 8701 BoundCombUB = 8702 SemaRef 8703 .BuildBinOp( 8704 CurScope, CondLoc, BO_Add, BoundCombUB, 8705 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 8706 .get(); 8707 BoundCombUB = 8708 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 8709 .get(); 8710 } 8711 CombCond = 8712 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 8713 IV.get(), BoundCombUB); 8714 } 8715 // Loop increment (IV = IV + 1) 8716 SourceLocation IncLoc = AStmt->getBeginLoc(); 8717 ExprResult Inc = 8718 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 8719 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 8720 if (!Inc.isUsable()) 8721 return 0; 8722 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 8723 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 8724 if (!Inc.isUsable()) 8725 return 0; 8726 8727 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 8728 // Used for directives with static scheduling. 8729 // In combined construct, add combined version that use CombLB and CombUB 8730 // base variables for the update 8731 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 8732 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 8733 isOpenMPDistributeDirective(DKind) || 8734 isOpenMPLoopTransformationDirective(DKind)) { 8735 // LB + ST 8736 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 8737 if (!NextLB.isUsable()) 8738 return 0; 8739 // LB = LB + ST 8740 NextLB = 8741 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 8742 NextLB = 8743 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 8744 if (!NextLB.isUsable()) 8745 return 0; 8746 // UB + ST 8747 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 8748 if (!NextUB.isUsable()) 8749 return 0; 8750 // UB = UB + ST 8751 NextUB = 8752 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 8753 NextUB = 8754 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 8755 if (!NextUB.isUsable()) 8756 return 0; 8757 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8758 CombNextLB = 8759 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 8760 if (!NextLB.isUsable()) 8761 return 0; 8762 // LB = LB + ST 8763 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 8764 CombNextLB.get()); 8765 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 8766 /*DiscardedValue*/ false); 8767 if (!CombNextLB.isUsable()) 8768 return 0; 8769 // UB + ST 8770 CombNextUB = 8771 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 8772 if (!CombNextUB.isUsable()) 8773 return 0; 8774 // UB = UB + ST 8775 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 8776 CombNextUB.get()); 8777 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 8778 /*DiscardedValue*/ false); 8779 if (!CombNextUB.isUsable()) 8780 return 0; 8781 } 8782 } 8783 8784 // Create increment expression for distribute loop when combined in a same 8785 // directive with for as IV = IV + ST; ensure upper bound expression based 8786 // on PrevUB instead of NumIterations - used to implement 'for' when found 8787 // in combination with 'distribute', like in 'distribute parallel for' 8788 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 8789 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 8790 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8791 DistCond = SemaRef.BuildBinOp( 8792 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 8793 assert(DistCond.isUsable() && "distribute cond expr was not built"); 8794 8795 DistInc = 8796 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 8797 assert(DistInc.isUsable() && "distribute inc expr was not built"); 8798 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 8799 DistInc.get()); 8800 DistInc = 8801 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 8802 assert(DistInc.isUsable() && "distribute inc expr was not built"); 8803 8804 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 8805 // construct 8806 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 8807 ExprResult IsUBGreater = 8808 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 8809 ExprResult CondOp = SemaRef.ActOnConditionalOp( 8810 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 8811 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 8812 CondOp.get()); 8813 PrevEUB = 8814 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 8815 8816 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 8817 // parallel for is in combination with a distribute directive with 8818 // schedule(static, 1) 8819 Expr *BoundPrevUB = PrevUB.get(); 8820 if (UseStrictCompare) { 8821 BoundPrevUB = 8822 SemaRef 8823 .BuildBinOp( 8824 CurScope, CondLoc, BO_Add, BoundPrevUB, 8825 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 8826 .get(); 8827 BoundPrevUB = 8828 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 8829 .get(); 8830 } 8831 ParForInDistCond = 8832 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 8833 IV.get(), BoundPrevUB); 8834 } 8835 8836 // Build updates and final values of the loop counters. 8837 bool HasErrors = false; 8838 Built.Counters.resize(NestedLoopCount); 8839 Built.Inits.resize(NestedLoopCount); 8840 Built.Updates.resize(NestedLoopCount); 8841 Built.Finals.resize(NestedLoopCount); 8842 Built.DependentCounters.resize(NestedLoopCount); 8843 Built.DependentInits.resize(NestedLoopCount); 8844 Built.FinalsConditions.resize(NestedLoopCount); 8845 { 8846 // We implement the following algorithm for obtaining the 8847 // original loop iteration variable values based on the 8848 // value of the collapsed loop iteration variable IV. 8849 // 8850 // Let n+1 be the number of collapsed loops in the nest. 8851 // Iteration variables (I0, I1, .... In) 8852 // Iteration counts (N0, N1, ... Nn) 8853 // 8854 // Acc = IV; 8855 // 8856 // To compute Ik for loop k, 0 <= k <= n, generate: 8857 // Prod = N(k+1) * N(k+2) * ... * Nn; 8858 // Ik = Acc / Prod; 8859 // Acc -= Ik * Prod; 8860 // 8861 ExprResult Acc = IV; 8862 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 8863 LoopIterationSpace &IS = IterSpaces[Cnt]; 8864 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 8865 ExprResult Iter; 8866 8867 // Compute prod 8868 ExprResult Prod = 8869 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 8870 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K) 8871 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 8872 IterSpaces[K].NumIterations); 8873 8874 // Iter = Acc / Prod 8875 // If there is at least one more inner loop to avoid 8876 // multiplication by 1. 8877 if (Cnt + 1 < NestedLoopCount) 8878 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, 8879 Acc.get(), Prod.get()); 8880 else 8881 Iter = Acc; 8882 if (!Iter.isUsable()) { 8883 HasErrors = true; 8884 break; 8885 } 8886 8887 // Update Acc: 8888 // Acc -= Iter * Prod 8889 // Check if there is at least one more inner loop to avoid 8890 // multiplication by 1. 8891 if (Cnt + 1 < NestedLoopCount) 8892 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, 8893 Iter.get(), Prod.get()); 8894 else 8895 Prod = Iter; 8896 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, 8897 Acc.get(), Prod.get()); 8898 8899 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 8900 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 8901 DeclRefExpr *CounterVar = buildDeclRefExpr( 8902 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 8903 /*RefersToCapture=*/true); 8904 ExprResult Init = 8905 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 8906 IS.CounterInit, IS.IsNonRectangularLB, Captures); 8907 if (!Init.isUsable()) { 8908 HasErrors = true; 8909 break; 8910 } 8911 ExprResult Update = buildCounterUpdate( 8912 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 8913 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures); 8914 if (!Update.isUsable()) { 8915 HasErrors = true; 8916 break; 8917 } 8918 8919 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 8920 ExprResult Final = 8921 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar, 8922 IS.CounterInit, IS.NumIterations, IS.CounterStep, 8923 IS.Subtract, IS.IsNonRectangularLB, &Captures); 8924 if (!Final.isUsable()) { 8925 HasErrors = true; 8926 break; 8927 } 8928 8929 if (!Update.isUsable() || !Final.isUsable()) { 8930 HasErrors = true; 8931 break; 8932 } 8933 // Save results 8934 Built.Counters[Cnt] = IS.CounterVar; 8935 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 8936 Built.Inits[Cnt] = Init.get(); 8937 Built.Updates[Cnt] = Update.get(); 8938 Built.Finals[Cnt] = Final.get(); 8939 Built.DependentCounters[Cnt] = nullptr; 8940 Built.DependentInits[Cnt] = nullptr; 8941 Built.FinalsConditions[Cnt] = nullptr; 8942 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) { 8943 Built.DependentCounters[Cnt] = 8944 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx]; 8945 Built.DependentInits[Cnt] = 8946 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx]; 8947 Built.FinalsConditions[Cnt] = IS.FinalCondition; 8948 } 8949 } 8950 } 8951 8952 if (HasErrors) 8953 return 0; 8954 8955 // Save results 8956 Built.IterationVarRef = IV.get(); 8957 Built.LastIteration = LastIteration.get(); 8958 Built.NumIterations = NumIterations.get(); 8959 Built.CalcLastIteration = SemaRef 8960 .ActOnFinishFullExpr(CalcLastIteration.get(), 8961 /*DiscardedValue=*/false) 8962 .get(); 8963 Built.PreCond = PreCond.get(); 8964 Built.PreInits = buildPreInits(C, Captures); 8965 Built.Cond = Cond.get(); 8966 Built.Init = Init.get(); 8967 Built.Inc = Inc.get(); 8968 Built.LB = LB.get(); 8969 Built.UB = UB.get(); 8970 Built.IL = IL.get(); 8971 Built.ST = ST.get(); 8972 Built.EUB = EUB.get(); 8973 Built.NLB = NextLB.get(); 8974 Built.NUB = NextUB.get(); 8975 Built.PrevLB = PrevLB.get(); 8976 Built.PrevUB = PrevUB.get(); 8977 Built.DistInc = DistInc.get(); 8978 Built.PrevEUB = PrevEUB.get(); 8979 Built.DistCombinedFields.LB = CombLB.get(); 8980 Built.DistCombinedFields.UB = CombUB.get(); 8981 Built.DistCombinedFields.EUB = CombEUB.get(); 8982 Built.DistCombinedFields.Init = CombInit.get(); 8983 Built.DistCombinedFields.Cond = CombCond.get(); 8984 Built.DistCombinedFields.NLB = CombNextLB.get(); 8985 Built.DistCombinedFields.NUB = CombNextUB.get(); 8986 Built.DistCombinedFields.DistCond = CombDistCond.get(); 8987 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 8988 8989 return NestedLoopCount; 8990 } 8991 8992 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 8993 auto CollapseClauses = 8994 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 8995 if (CollapseClauses.begin() != CollapseClauses.end()) 8996 return (*CollapseClauses.begin())->getNumForLoops(); 8997 return nullptr; 8998 } 8999 9000 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 9001 auto OrderedClauses = 9002 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 9003 if (OrderedClauses.begin() != OrderedClauses.end()) 9004 return (*OrderedClauses.begin())->getNumForLoops(); 9005 return nullptr; 9006 } 9007 9008 static bool checkSimdlenSafelenSpecified(Sema &S, 9009 const ArrayRef<OMPClause *> Clauses) { 9010 const OMPSafelenClause *Safelen = nullptr; 9011 const OMPSimdlenClause *Simdlen = nullptr; 9012 9013 for (const OMPClause *Clause : Clauses) { 9014 if (Clause->getClauseKind() == OMPC_safelen) 9015 Safelen = cast<OMPSafelenClause>(Clause); 9016 else if (Clause->getClauseKind() == OMPC_simdlen) 9017 Simdlen = cast<OMPSimdlenClause>(Clause); 9018 if (Safelen && Simdlen) 9019 break; 9020 } 9021 9022 if (Simdlen && Safelen) { 9023 const Expr *SimdlenLength = Simdlen->getSimdlen(); 9024 const Expr *SafelenLength = Safelen->getSafelen(); 9025 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 9026 SimdlenLength->isInstantiationDependent() || 9027 SimdlenLength->containsUnexpandedParameterPack()) 9028 return false; 9029 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 9030 SafelenLength->isInstantiationDependent() || 9031 SafelenLength->containsUnexpandedParameterPack()) 9032 return false; 9033 Expr::EvalResult SimdlenResult, SafelenResult; 9034 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 9035 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 9036 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 9037 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 9038 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 9039 // If both simdlen and safelen clauses are specified, the value of the 9040 // simdlen parameter must be less than or equal to the value of the safelen 9041 // parameter. 9042 if (SimdlenRes > SafelenRes) { 9043 S.Diag(SimdlenLength->getExprLoc(), 9044 diag::err_omp_wrong_simdlen_safelen_values) 9045 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 9046 return true; 9047 } 9048 } 9049 return false; 9050 } 9051 9052 StmtResult 9053 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 9054 SourceLocation StartLoc, SourceLocation EndLoc, 9055 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9056 if (!AStmt) 9057 return StmtError(); 9058 9059 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9060 OMPLoopBasedDirective::HelperExprs B; 9061 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9062 // define the nested loops number. 9063 unsigned NestedLoopCount = checkOpenMPLoop( 9064 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 9065 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 9066 if (NestedLoopCount == 0) 9067 return StmtError(); 9068 9069 assert((CurContext->isDependentContext() || B.builtAll()) && 9070 "omp simd loop exprs were not built"); 9071 9072 if (!CurContext->isDependentContext()) { 9073 // Finalize the clauses that need pre-built expressions for CodeGen. 9074 for (OMPClause *C : Clauses) { 9075 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9076 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9077 B.NumIterations, *this, CurScope, 9078 DSAStack)) 9079 return StmtError(); 9080 } 9081 } 9082 9083 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9084 return StmtError(); 9085 9086 setFunctionHasBranchProtectedScope(); 9087 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 9088 Clauses, AStmt, B); 9089 } 9090 9091 StmtResult 9092 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 9093 SourceLocation StartLoc, SourceLocation EndLoc, 9094 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9095 if (!AStmt) 9096 return StmtError(); 9097 9098 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9099 OMPLoopBasedDirective::HelperExprs B; 9100 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9101 // define the nested loops number. 9102 unsigned NestedLoopCount = checkOpenMPLoop( 9103 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 9104 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 9105 if (NestedLoopCount == 0) 9106 return StmtError(); 9107 9108 assert((CurContext->isDependentContext() || B.builtAll()) && 9109 "omp for loop exprs were not built"); 9110 9111 if (!CurContext->isDependentContext()) { 9112 // Finalize the clauses that need pre-built expressions for CodeGen. 9113 for (OMPClause *C : Clauses) { 9114 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9115 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9116 B.NumIterations, *this, CurScope, 9117 DSAStack)) 9118 return StmtError(); 9119 } 9120 } 9121 9122 setFunctionHasBranchProtectedScope(); 9123 return OMPForDirective::Create( 9124 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 9125 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 9126 } 9127 9128 StmtResult Sema::ActOnOpenMPForSimdDirective( 9129 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9130 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9131 if (!AStmt) 9132 return StmtError(); 9133 9134 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9135 OMPLoopBasedDirective::HelperExprs B; 9136 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9137 // define the nested loops number. 9138 unsigned NestedLoopCount = 9139 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 9140 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 9141 VarsWithImplicitDSA, B); 9142 if (NestedLoopCount == 0) 9143 return StmtError(); 9144 9145 assert((CurContext->isDependentContext() || B.builtAll()) && 9146 "omp for simd loop exprs were not built"); 9147 9148 if (!CurContext->isDependentContext()) { 9149 // Finalize the clauses that need pre-built expressions for CodeGen. 9150 for (OMPClause *C : Clauses) { 9151 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9152 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9153 B.NumIterations, *this, CurScope, 9154 DSAStack)) 9155 return StmtError(); 9156 } 9157 } 9158 9159 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9160 return StmtError(); 9161 9162 setFunctionHasBranchProtectedScope(); 9163 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 9164 Clauses, AStmt, B); 9165 } 9166 9167 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 9168 Stmt *AStmt, 9169 SourceLocation StartLoc, 9170 SourceLocation EndLoc) { 9171 if (!AStmt) 9172 return StmtError(); 9173 9174 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9175 auto BaseStmt = AStmt; 9176 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 9177 BaseStmt = CS->getCapturedStmt(); 9178 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 9179 auto S = C->children(); 9180 if (S.begin() == S.end()) 9181 return StmtError(); 9182 // All associated statements must be '#pragma omp section' except for 9183 // the first one. 9184 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 9185 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 9186 if (SectionStmt) 9187 Diag(SectionStmt->getBeginLoc(), 9188 diag::err_omp_sections_substmt_not_section); 9189 return StmtError(); 9190 } 9191 cast<OMPSectionDirective>(SectionStmt) 9192 ->setHasCancel(DSAStack->isCancelRegion()); 9193 } 9194 } else { 9195 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 9196 return StmtError(); 9197 } 9198 9199 setFunctionHasBranchProtectedScope(); 9200 9201 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 9202 DSAStack->getTaskgroupReductionRef(), 9203 DSAStack->isCancelRegion()); 9204 } 9205 9206 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 9207 SourceLocation StartLoc, 9208 SourceLocation EndLoc) { 9209 if (!AStmt) 9210 return StmtError(); 9211 9212 setFunctionHasBranchProtectedScope(); 9213 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 9214 9215 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 9216 DSAStack->isCancelRegion()); 9217 } 9218 9219 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 9220 Stmt *AStmt, 9221 SourceLocation StartLoc, 9222 SourceLocation EndLoc) { 9223 if (!AStmt) 9224 return StmtError(); 9225 9226 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9227 9228 setFunctionHasBranchProtectedScope(); 9229 9230 // OpenMP [2.7.3, single Construct, Restrictions] 9231 // The copyprivate clause must not be used with the nowait clause. 9232 const OMPClause *Nowait = nullptr; 9233 const OMPClause *Copyprivate = nullptr; 9234 for (const OMPClause *Clause : Clauses) { 9235 if (Clause->getClauseKind() == OMPC_nowait) 9236 Nowait = Clause; 9237 else if (Clause->getClauseKind() == OMPC_copyprivate) 9238 Copyprivate = Clause; 9239 if (Copyprivate && Nowait) { 9240 Diag(Copyprivate->getBeginLoc(), 9241 diag::err_omp_single_copyprivate_with_nowait); 9242 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 9243 return StmtError(); 9244 } 9245 } 9246 9247 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 9248 } 9249 9250 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 9251 SourceLocation StartLoc, 9252 SourceLocation EndLoc) { 9253 if (!AStmt) 9254 return StmtError(); 9255 9256 setFunctionHasBranchProtectedScope(); 9257 9258 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 9259 } 9260 9261 StmtResult Sema::ActOnOpenMPCriticalDirective( 9262 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 9263 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 9264 if (!AStmt) 9265 return StmtError(); 9266 9267 bool ErrorFound = false; 9268 llvm::APSInt Hint; 9269 SourceLocation HintLoc; 9270 bool DependentHint = false; 9271 for (const OMPClause *C : Clauses) { 9272 if (C->getClauseKind() == OMPC_hint) { 9273 if (!DirName.getName()) { 9274 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 9275 ErrorFound = true; 9276 } 9277 Expr *E = cast<OMPHintClause>(C)->getHint(); 9278 if (E->isTypeDependent() || E->isValueDependent() || 9279 E->isInstantiationDependent()) { 9280 DependentHint = true; 9281 } else { 9282 Hint = E->EvaluateKnownConstInt(Context); 9283 HintLoc = C->getBeginLoc(); 9284 } 9285 } 9286 } 9287 if (ErrorFound) 9288 return StmtError(); 9289 const auto Pair = DSAStack->getCriticalWithHint(DirName); 9290 if (Pair.first && DirName.getName() && !DependentHint) { 9291 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 9292 Diag(StartLoc, diag::err_omp_critical_with_hint); 9293 if (HintLoc.isValid()) 9294 Diag(HintLoc, diag::note_omp_critical_hint_here) 9295 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 9296 else 9297 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 9298 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 9299 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 9300 << 1 9301 << C->getHint()->EvaluateKnownConstInt(Context).toString( 9302 /*Radix=*/10, /*Signed=*/false); 9303 } else { 9304 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 9305 } 9306 } 9307 } 9308 9309 setFunctionHasBranchProtectedScope(); 9310 9311 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 9312 Clauses, AStmt); 9313 if (!Pair.first && DirName.getName() && !DependentHint) 9314 DSAStack->addCriticalWithHint(Dir, Hint); 9315 return Dir; 9316 } 9317 9318 StmtResult Sema::ActOnOpenMPParallelForDirective( 9319 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9320 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9321 if (!AStmt) 9322 return StmtError(); 9323 9324 auto *CS = cast<CapturedStmt>(AStmt); 9325 // 1.2.2 OpenMP Language Terminology 9326 // Structured block - An executable statement with a single entry at the 9327 // top and a single exit at the bottom. 9328 // The point of exit cannot be a branch out of the structured block. 9329 // longjmp() and throw() must not violate the entry/exit criteria. 9330 CS->getCapturedDecl()->setNothrow(); 9331 9332 OMPLoopBasedDirective::HelperExprs B; 9333 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9334 // define the nested loops number. 9335 unsigned NestedLoopCount = 9336 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 9337 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 9338 VarsWithImplicitDSA, B); 9339 if (NestedLoopCount == 0) 9340 return StmtError(); 9341 9342 assert((CurContext->isDependentContext() || B.builtAll()) && 9343 "omp parallel for loop exprs were not built"); 9344 9345 if (!CurContext->isDependentContext()) { 9346 // Finalize the clauses that need pre-built expressions for CodeGen. 9347 for (OMPClause *C : Clauses) { 9348 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9349 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9350 B.NumIterations, *this, CurScope, 9351 DSAStack)) 9352 return StmtError(); 9353 } 9354 } 9355 9356 setFunctionHasBranchProtectedScope(); 9357 return OMPParallelForDirective::Create( 9358 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 9359 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 9360 } 9361 9362 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 9363 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9364 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9365 if (!AStmt) 9366 return StmtError(); 9367 9368 auto *CS = cast<CapturedStmt>(AStmt); 9369 // 1.2.2 OpenMP Language Terminology 9370 // Structured block - An executable statement with a single entry at the 9371 // top and a single exit at the bottom. 9372 // The point of exit cannot be a branch out of the structured block. 9373 // longjmp() and throw() must not violate the entry/exit criteria. 9374 CS->getCapturedDecl()->setNothrow(); 9375 9376 OMPLoopBasedDirective::HelperExprs B; 9377 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9378 // define the nested loops number. 9379 unsigned NestedLoopCount = 9380 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 9381 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 9382 VarsWithImplicitDSA, B); 9383 if (NestedLoopCount == 0) 9384 return StmtError(); 9385 9386 if (!CurContext->isDependentContext()) { 9387 // Finalize the clauses that need pre-built expressions for CodeGen. 9388 for (OMPClause *C : Clauses) { 9389 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9390 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9391 B.NumIterations, *this, CurScope, 9392 DSAStack)) 9393 return StmtError(); 9394 } 9395 } 9396 9397 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9398 return StmtError(); 9399 9400 setFunctionHasBranchProtectedScope(); 9401 return OMPParallelForSimdDirective::Create( 9402 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 9403 } 9404 9405 StmtResult 9406 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 9407 Stmt *AStmt, SourceLocation StartLoc, 9408 SourceLocation EndLoc) { 9409 if (!AStmt) 9410 return StmtError(); 9411 9412 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9413 auto *CS = cast<CapturedStmt>(AStmt); 9414 // 1.2.2 OpenMP Language Terminology 9415 // Structured block - An executable statement with a single entry at the 9416 // top and a single exit at the bottom. 9417 // The point of exit cannot be a branch out of the structured block. 9418 // longjmp() and throw() must not violate the entry/exit criteria. 9419 CS->getCapturedDecl()->setNothrow(); 9420 9421 setFunctionHasBranchProtectedScope(); 9422 9423 return OMPParallelMasterDirective::Create( 9424 Context, StartLoc, EndLoc, Clauses, AStmt, 9425 DSAStack->getTaskgroupReductionRef()); 9426 } 9427 9428 StmtResult 9429 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 9430 Stmt *AStmt, SourceLocation StartLoc, 9431 SourceLocation EndLoc) { 9432 if (!AStmt) 9433 return StmtError(); 9434 9435 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9436 auto BaseStmt = AStmt; 9437 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 9438 BaseStmt = CS->getCapturedStmt(); 9439 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 9440 auto S = C->children(); 9441 if (S.begin() == S.end()) 9442 return StmtError(); 9443 // All associated statements must be '#pragma omp section' except for 9444 // the first one. 9445 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 9446 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 9447 if (SectionStmt) 9448 Diag(SectionStmt->getBeginLoc(), 9449 diag::err_omp_parallel_sections_substmt_not_section); 9450 return StmtError(); 9451 } 9452 cast<OMPSectionDirective>(SectionStmt) 9453 ->setHasCancel(DSAStack->isCancelRegion()); 9454 } 9455 } else { 9456 Diag(AStmt->getBeginLoc(), 9457 diag::err_omp_parallel_sections_not_compound_stmt); 9458 return StmtError(); 9459 } 9460 9461 setFunctionHasBranchProtectedScope(); 9462 9463 return OMPParallelSectionsDirective::Create( 9464 Context, StartLoc, EndLoc, Clauses, AStmt, 9465 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 9466 } 9467 9468 /// detach and mergeable clauses are mutially exclusive, check for it. 9469 static bool checkDetachMergeableClauses(Sema &S, 9470 ArrayRef<OMPClause *> Clauses) { 9471 const OMPClause *PrevClause = nullptr; 9472 bool ErrorFound = false; 9473 for (const OMPClause *C : Clauses) { 9474 if (C->getClauseKind() == OMPC_detach || 9475 C->getClauseKind() == OMPC_mergeable) { 9476 if (!PrevClause) { 9477 PrevClause = C; 9478 } else if (PrevClause->getClauseKind() != C->getClauseKind()) { 9479 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive) 9480 << getOpenMPClauseName(C->getClauseKind()) 9481 << getOpenMPClauseName(PrevClause->getClauseKind()); 9482 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause) 9483 << getOpenMPClauseName(PrevClause->getClauseKind()); 9484 ErrorFound = true; 9485 } 9486 } 9487 } 9488 return ErrorFound; 9489 } 9490 9491 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 9492 Stmt *AStmt, SourceLocation StartLoc, 9493 SourceLocation EndLoc) { 9494 if (!AStmt) 9495 return StmtError(); 9496 9497 // OpenMP 5.0, 2.10.1 task Construct 9498 // If a detach clause appears on the directive, then a mergeable clause cannot 9499 // appear on the same directive. 9500 if (checkDetachMergeableClauses(*this, Clauses)) 9501 return StmtError(); 9502 9503 auto *CS = cast<CapturedStmt>(AStmt); 9504 // 1.2.2 OpenMP Language Terminology 9505 // Structured block - An executable statement with a single entry at the 9506 // top and a single exit at the bottom. 9507 // The point of exit cannot be a branch out of the structured block. 9508 // longjmp() and throw() must not violate the entry/exit criteria. 9509 CS->getCapturedDecl()->setNothrow(); 9510 9511 setFunctionHasBranchProtectedScope(); 9512 9513 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 9514 DSAStack->isCancelRegion()); 9515 } 9516 9517 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 9518 SourceLocation EndLoc) { 9519 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 9520 } 9521 9522 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 9523 SourceLocation EndLoc) { 9524 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 9525 } 9526 9527 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 9528 SourceLocation EndLoc) { 9529 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 9530 } 9531 9532 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 9533 Stmt *AStmt, 9534 SourceLocation StartLoc, 9535 SourceLocation EndLoc) { 9536 if (!AStmt) 9537 return StmtError(); 9538 9539 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9540 9541 setFunctionHasBranchProtectedScope(); 9542 9543 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 9544 AStmt, 9545 DSAStack->getTaskgroupReductionRef()); 9546 } 9547 9548 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 9549 SourceLocation StartLoc, 9550 SourceLocation EndLoc) { 9551 OMPFlushClause *FC = nullptr; 9552 OMPClause *OrderClause = nullptr; 9553 for (OMPClause *C : Clauses) { 9554 if (C->getClauseKind() == OMPC_flush) 9555 FC = cast<OMPFlushClause>(C); 9556 else 9557 OrderClause = C; 9558 } 9559 OpenMPClauseKind MemOrderKind = OMPC_unknown; 9560 SourceLocation MemOrderLoc; 9561 for (const OMPClause *C : Clauses) { 9562 if (C->getClauseKind() == OMPC_acq_rel || 9563 C->getClauseKind() == OMPC_acquire || 9564 C->getClauseKind() == OMPC_release) { 9565 if (MemOrderKind != OMPC_unknown) { 9566 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 9567 << getOpenMPDirectiveName(OMPD_flush) << 1 9568 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 9569 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 9570 << getOpenMPClauseName(MemOrderKind); 9571 } else { 9572 MemOrderKind = C->getClauseKind(); 9573 MemOrderLoc = C->getBeginLoc(); 9574 } 9575 } 9576 } 9577 if (FC && OrderClause) { 9578 Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list) 9579 << getOpenMPClauseName(OrderClause->getClauseKind()); 9580 Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here) 9581 << getOpenMPClauseName(OrderClause->getClauseKind()); 9582 return StmtError(); 9583 } 9584 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 9585 } 9586 9587 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 9588 SourceLocation StartLoc, 9589 SourceLocation EndLoc) { 9590 if (Clauses.empty()) { 9591 Diag(StartLoc, diag::err_omp_depobj_expected); 9592 return StmtError(); 9593 } else if (Clauses[0]->getClauseKind() != OMPC_depobj) { 9594 Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected); 9595 return StmtError(); 9596 } 9597 // Only depobj expression and another single clause is allowed. 9598 if (Clauses.size() > 2) { 9599 Diag(Clauses[2]->getBeginLoc(), 9600 diag::err_omp_depobj_single_clause_expected); 9601 return StmtError(); 9602 } else if (Clauses.size() < 1) { 9603 Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected); 9604 return StmtError(); 9605 } 9606 return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses); 9607 } 9608 9609 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 9610 SourceLocation StartLoc, 9611 SourceLocation EndLoc) { 9612 // Check that exactly one clause is specified. 9613 if (Clauses.size() != 1) { 9614 Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(), 9615 diag::err_omp_scan_single_clause_expected); 9616 return StmtError(); 9617 } 9618 // Check that scan directive is used in the scopeof the OpenMP loop body. 9619 if (Scope *S = DSAStack->getCurScope()) { 9620 Scope *ParentS = S->getParent(); 9621 if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() || 9622 !ParentS->getBreakParent()->isOpenMPLoopScope()) 9623 return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive) 9624 << getOpenMPDirectiveName(OMPD_scan) << 5); 9625 } 9626 // Check that only one instance of scan directives is used in the same outer 9627 // region. 9628 if (DSAStack->doesParentHasScanDirective()) { 9629 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan"; 9630 Diag(DSAStack->getParentScanDirectiveLoc(), 9631 diag::note_omp_previous_directive) 9632 << "scan"; 9633 return StmtError(); 9634 } 9635 DSAStack->setParentHasScanDirective(StartLoc); 9636 return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses); 9637 } 9638 9639 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 9640 Stmt *AStmt, 9641 SourceLocation StartLoc, 9642 SourceLocation EndLoc) { 9643 const OMPClause *DependFound = nullptr; 9644 const OMPClause *DependSourceClause = nullptr; 9645 const OMPClause *DependSinkClause = nullptr; 9646 bool ErrorFound = false; 9647 const OMPThreadsClause *TC = nullptr; 9648 const OMPSIMDClause *SC = nullptr; 9649 for (const OMPClause *C : Clauses) { 9650 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 9651 DependFound = C; 9652 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 9653 if (DependSourceClause) { 9654 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 9655 << getOpenMPDirectiveName(OMPD_ordered) 9656 << getOpenMPClauseName(OMPC_depend) << 2; 9657 ErrorFound = true; 9658 } else { 9659 DependSourceClause = C; 9660 } 9661 if (DependSinkClause) { 9662 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 9663 << 0; 9664 ErrorFound = true; 9665 } 9666 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 9667 if (DependSourceClause) { 9668 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 9669 << 1; 9670 ErrorFound = true; 9671 } 9672 DependSinkClause = C; 9673 } 9674 } else if (C->getClauseKind() == OMPC_threads) { 9675 TC = cast<OMPThreadsClause>(C); 9676 } else if (C->getClauseKind() == OMPC_simd) { 9677 SC = cast<OMPSIMDClause>(C); 9678 } 9679 } 9680 if (!ErrorFound && !SC && 9681 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 9682 // OpenMP [2.8.1,simd Construct, Restrictions] 9683 // An ordered construct with the simd clause is the only OpenMP construct 9684 // that can appear in the simd region. 9685 Diag(StartLoc, diag::err_omp_prohibited_region_simd) 9686 << (LangOpts.OpenMP >= 50 ? 1 : 0); 9687 ErrorFound = true; 9688 } else if (DependFound && (TC || SC)) { 9689 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 9690 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 9691 ErrorFound = true; 9692 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 9693 Diag(DependFound->getBeginLoc(), 9694 diag::err_omp_ordered_directive_without_param); 9695 ErrorFound = true; 9696 } else if (TC || Clauses.empty()) { 9697 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 9698 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 9699 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 9700 << (TC != nullptr); 9701 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1; 9702 ErrorFound = true; 9703 } 9704 } 9705 if ((!AStmt && !DependFound) || ErrorFound) 9706 return StmtError(); 9707 9708 // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions. 9709 // During execution of an iteration of a worksharing-loop or a loop nest 9710 // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread 9711 // must not execute more than one ordered region corresponding to an ordered 9712 // construct without a depend clause. 9713 if (!DependFound) { 9714 if (DSAStack->doesParentHasOrderedDirective()) { 9715 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered"; 9716 Diag(DSAStack->getParentOrderedDirectiveLoc(), 9717 diag::note_omp_previous_directive) 9718 << "ordered"; 9719 return StmtError(); 9720 } 9721 DSAStack->setParentHasOrderedDirective(StartLoc); 9722 } 9723 9724 if (AStmt) { 9725 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9726 9727 setFunctionHasBranchProtectedScope(); 9728 } 9729 9730 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 9731 } 9732 9733 namespace { 9734 /// Helper class for checking expression in 'omp atomic [update]' 9735 /// construct. 9736 class OpenMPAtomicUpdateChecker { 9737 /// Error results for atomic update expressions. 9738 enum ExprAnalysisErrorCode { 9739 /// A statement is not an expression statement. 9740 NotAnExpression, 9741 /// Expression is not builtin binary or unary operation. 9742 NotABinaryOrUnaryExpression, 9743 /// Unary operation is not post-/pre- increment/decrement operation. 9744 NotAnUnaryIncDecExpression, 9745 /// An expression is not of scalar type. 9746 NotAScalarType, 9747 /// A binary operation is not an assignment operation. 9748 NotAnAssignmentOp, 9749 /// RHS part of the binary operation is not a binary expression. 9750 NotABinaryExpression, 9751 /// RHS part is not additive/multiplicative/shift/biwise binary 9752 /// expression. 9753 NotABinaryOperator, 9754 /// RHS binary operation does not have reference to the updated LHS 9755 /// part. 9756 NotAnUpdateExpression, 9757 /// No errors is found. 9758 NoError 9759 }; 9760 /// Reference to Sema. 9761 Sema &SemaRef; 9762 /// A location for note diagnostics (when error is found). 9763 SourceLocation NoteLoc; 9764 /// 'x' lvalue part of the source atomic expression. 9765 Expr *X; 9766 /// 'expr' rvalue part of the source atomic expression. 9767 Expr *E; 9768 /// Helper expression of the form 9769 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 9770 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 9771 Expr *UpdateExpr; 9772 /// Is 'x' a LHS in a RHS part of full update expression. It is 9773 /// important for non-associative operations. 9774 bool IsXLHSInRHSPart; 9775 BinaryOperatorKind Op; 9776 SourceLocation OpLoc; 9777 /// true if the source expression is a postfix unary operation, false 9778 /// if it is a prefix unary operation. 9779 bool IsPostfixUpdate; 9780 9781 public: 9782 OpenMPAtomicUpdateChecker(Sema &SemaRef) 9783 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 9784 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 9785 /// Check specified statement that it is suitable for 'atomic update' 9786 /// constructs and extract 'x', 'expr' and Operation from the original 9787 /// expression. If DiagId and NoteId == 0, then only check is performed 9788 /// without error notification. 9789 /// \param DiagId Diagnostic which should be emitted if error is found. 9790 /// \param NoteId Diagnostic note for the main error message. 9791 /// \return true if statement is not an update expression, false otherwise. 9792 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 9793 /// Return the 'x' lvalue part of the source atomic expression. 9794 Expr *getX() const { return X; } 9795 /// Return the 'expr' rvalue part of the source atomic expression. 9796 Expr *getExpr() const { return E; } 9797 /// Return the update expression used in calculation of the updated 9798 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 9799 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 9800 Expr *getUpdateExpr() const { return UpdateExpr; } 9801 /// Return true if 'x' is LHS in RHS part of full update expression, 9802 /// false otherwise. 9803 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 9804 9805 /// true if the source expression is a postfix unary operation, false 9806 /// if it is a prefix unary operation. 9807 bool isPostfixUpdate() const { return IsPostfixUpdate; } 9808 9809 private: 9810 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 9811 unsigned NoteId = 0); 9812 }; 9813 } // namespace 9814 9815 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 9816 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 9817 ExprAnalysisErrorCode ErrorFound = NoError; 9818 SourceLocation ErrorLoc, NoteLoc; 9819 SourceRange ErrorRange, NoteRange; 9820 // Allowed constructs are: 9821 // x = x binop expr; 9822 // x = expr binop x; 9823 if (AtomicBinOp->getOpcode() == BO_Assign) { 9824 X = AtomicBinOp->getLHS(); 9825 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 9826 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 9827 if (AtomicInnerBinOp->isMultiplicativeOp() || 9828 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 9829 AtomicInnerBinOp->isBitwiseOp()) { 9830 Op = AtomicInnerBinOp->getOpcode(); 9831 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 9832 Expr *LHS = AtomicInnerBinOp->getLHS(); 9833 Expr *RHS = AtomicInnerBinOp->getRHS(); 9834 llvm::FoldingSetNodeID XId, LHSId, RHSId; 9835 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 9836 /*Canonical=*/true); 9837 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 9838 /*Canonical=*/true); 9839 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 9840 /*Canonical=*/true); 9841 if (XId == LHSId) { 9842 E = RHS; 9843 IsXLHSInRHSPart = true; 9844 } else if (XId == RHSId) { 9845 E = LHS; 9846 IsXLHSInRHSPart = false; 9847 } else { 9848 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 9849 ErrorRange = AtomicInnerBinOp->getSourceRange(); 9850 NoteLoc = X->getExprLoc(); 9851 NoteRange = X->getSourceRange(); 9852 ErrorFound = NotAnUpdateExpression; 9853 } 9854 } else { 9855 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 9856 ErrorRange = AtomicInnerBinOp->getSourceRange(); 9857 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 9858 NoteRange = SourceRange(NoteLoc, NoteLoc); 9859 ErrorFound = NotABinaryOperator; 9860 } 9861 } else { 9862 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 9863 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 9864 ErrorFound = NotABinaryExpression; 9865 } 9866 } else { 9867 ErrorLoc = AtomicBinOp->getExprLoc(); 9868 ErrorRange = AtomicBinOp->getSourceRange(); 9869 NoteLoc = AtomicBinOp->getOperatorLoc(); 9870 NoteRange = SourceRange(NoteLoc, NoteLoc); 9871 ErrorFound = NotAnAssignmentOp; 9872 } 9873 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 9874 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 9875 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 9876 return true; 9877 } 9878 if (SemaRef.CurContext->isDependentContext()) 9879 E = X = UpdateExpr = nullptr; 9880 return ErrorFound != NoError; 9881 } 9882 9883 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 9884 unsigned NoteId) { 9885 ExprAnalysisErrorCode ErrorFound = NoError; 9886 SourceLocation ErrorLoc, NoteLoc; 9887 SourceRange ErrorRange, NoteRange; 9888 // Allowed constructs are: 9889 // x++; 9890 // x--; 9891 // ++x; 9892 // --x; 9893 // x binop= expr; 9894 // x = x binop expr; 9895 // x = expr binop x; 9896 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 9897 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 9898 if (AtomicBody->getType()->isScalarType() || 9899 AtomicBody->isInstantiationDependent()) { 9900 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 9901 AtomicBody->IgnoreParenImpCasts())) { 9902 // Check for Compound Assignment Operation 9903 Op = BinaryOperator::getOpForCompoundAssignment( 9904 AtomicCompAssignOp->getOpcode()); 9905 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 9906 E = AtomicCompAssignOp->getRHS(); 9907 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 9908 IsXLHSInRHSPart = true; 9909 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 9910 AtomicBody->IgnoreParenImpCasts())) { 9911 // Check for Binary Operation 9912 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 9913 return true; 9914 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 9915 AtomicBody->IgnoreParenImpCasts())) { 9916 // Check for Unary Operation 9917 if (AtomicUnaryOp->isIncrementDecrementOp()) { 9918 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 9919 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 9920 OpLoc = AtomicUnaryOp->getOperatorLoc(); 9921 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 9922 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 9923 IsXLHSInRHSPart = true; 9924 } else { 9925 ErrorFound = NotAnUnaryIncDecExpression; 9926 ErrorLoc = AtomicUnaryOp->getExprLoc(); 9927 ErrorRange = AtomicUnaryOp->getSourceRange(); 9928 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 9929 NoteRange = SourceRange(NoteLoc, NoteLoc); 9930 } 9931 } else if (!AtomicBody->isInstantiationDependent()) { 9932 ErrorFound = NotABinaryOrUnaryExpression; 9933 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 9934 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 9935 } 9936 } else { 9937 ErrorFound = NotAScalarType; 9938 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 9939 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 9940 } 9941 } else { 9942 ErrorFound = NotAnExpression; 9943 NoteLoc = ErrorLoc = S->getBeginLoc(); 9944 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 9945 } 9946 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 9947 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 9948 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 9949 return true; 9950 } 9951 if (SemaRef.CurContext->isDependentContext()) 9952 E = X = UpdateExpr = nullptr; 9953 if (ErrorFound == NoError && E && X) { 9954 // Build an update expression of form 'OpaqueValueExpr(x) binop 9955 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 9956 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 9957 auto *OVEX = new (SemaRef.getASTContext()) 9958 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 9959 auto *OVEExpr = new (SemaRef.getASTContext()) 9960 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 9961 ExprResult Update = 9962 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 9963 IsXLHSInRHSPart ? OVEExpr : OVEX); 9964 if (Update.isInvalid()) 9965 return true; 9966 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 9967 Sema::AA_Casting); 9968 if (Update.isInvalid()) 9969 return true; 9970 UpdateExpr = Update.get(); 9971 } 9972 return ErrorFound != NoError; 9973 } 9974 9975 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 9976 Stmt *AStmt, 9977 SourceLocation StartLoc, 9978 SourceLocation EndLoc) { 9979 // Register location of the first atomic directive. 9980 DSAStack->addAtomicDirectiveLoc(StartLoc); 9981 if (!AStmt) 9982 return StmtError(); 9983 9984 // 1.2.2 OpenMP Language Terminology 9985 // Structured block - An executable statement with a single entry at the 9986 // top and a single exit at the bottom. 9987 // The point of exit cannot be a branch out of the structured block. 9988 // longjmp() and throw() must not violate the entry/exit criteria. 9989 OpenMPClauseKind AtomicKind = OMPC_unknown; 9990 SourceLocation AtomicKindLoc; 9991 OpenMPClauseKind MemOrderKind = OMPC_unknown; 9992 SourceLocation MemOrderLoc; 9993 for (const OMPClause *C : Clauses) { 9994 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 9995 C->getClauseKind() == OMPC_update || 9996 C->getClauseKind() == OMPC_capture) { 9997 if (AtomicKind != OMPC_unknown) { 9998 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 9999 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10000 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause) 10001 << getOpenMPClauseName(AtomicKind); 10002 } else { 10003 AtomicKind = C->getClauseKind(); 10004 AtomicKindLoc = C->getBeginLoc(); 10005 } 10006 } 10007 if (C->getClauseKind() == OMPC_seq_cst || 10008 C->getClauseKind() == OMPC_acq_rel || 10009 C->getClauseKind() == OMPC_acquire || 10010 C->getClauseKind() == OMPC_release || 10011 C->getClauseKind() == OMPC_relaxed) { 10012 if (MemOrderKind != OMPC_unknown) { 10013 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 10014 << getOpenMPDirectiveName(OMPD_atomic) << 0 10015 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10016 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10017 << getOpenMPClauseName(MemOrderKind); 10018 } else { 10019 MemOrderKind = C->getClauseKind(); 10020 MemOrderLoc = C->getBeginLoc(); 10021 } 10022 } 10023 } 10024 // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions 10025 // If atomic-clause is read then memory-order-clause must not be acq_rel or 10026 // release. 10027 // If atomic-clause is write then memory-order-clause must not be acq_rel or 10028 // acquire. 10029 // If atomic-clause is update or not present then memory-order-clause must not 10030 // be acq_rel or acquire. 10031 if ((AtomicKind == OMPC_read && 10032 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) || 10033 ((AtomicKind == OMPC_write || AtomicKind == OMPC_update || 10034 AtomicKind == OMPC_unknown) && 10035 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) { 10036 SourceLocation Loc = AtomicKindLoc; 10037 if (AtomicKind == OMPC_unknown) 10038 Loc = StartLoc; 10039 Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause) 10040 << getOpenMPClauseName(AtomicKind) 10041 << (AtomicKind == OMPC_unknown ? 1 : 0) 10042 << getOpenMPClauseName(MemOrderKind); 10043 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10044 << getOpenMPClauseName(MemOrderKind); 10045 } 10046 10047 Stmt *Body = AStmt; 10048 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 10049 Body = EWC->getSubExpr(); 10050 10051 Expr *X = nullptr; 10052 Expr *V = nullptr; 10053 Expr *E = nullptr; 10054 Expr *UE = nullptr; 10055 bool IsXLHSInRHSPart = false; 10056 bool IsPostfixUpdate = false; 10057 // OpenMP [2.12.6, atomic Construct] 10058 // In the next expressions: 10059 // * x and v (as applicable) are both l-value expressions with scalar type. 10060 // * During the execution of an atomic region, multiple syntactic 10061 // occurrences of x must designate the same storage location. 10062 // * Neither of v and expr (as applicable) may access the storage location 10063 // designated by x. 10064 // * Neither of x and expr (as applicable) may access the storage location 10065 // designated by v. 10066 // * expr is an expression with scalar type. 10067 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 10068 // * binop, binop=, ++, and -- are not overloaded operators. 10069 // * The expression x binop expr must be numerically equivalent to x binop 10070 // (expr). This requirement is satisfied if the operators in expr have 10071 // precedence greater than binop, or by using parentheses around expr or 10072 // subexpressions of expr. 10073 // * The expression expr binop x must be numerically equivalent to (expr) 10074 // binop x. This requirement is satisfied if the operators in expr have 10075 // precedence equal to or greater than binop, or by using parentheses around 10076 // expr or subexpressions of expr. 10077 // * For forms that allow multiple occurrences of x, the number of times 10078 // that x is evaluated is unspecified. 10079 if (AtomicKind == OMPC_read) { 10080 enum { 10081 NotAnExpression, 10082 NotAnAssignmentOp, 10083 NotAScalarType, 10084 NotAnLValue, 10085 NoError 10086 } ErrorFound = NoError; 10087 SourceLocation ErrorLoc, NoteLoc; 10088 SourceRange ErrorRange, NoteRange; 10089 // If clause is read: 10090 // v = x; 10091 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 10092 const auto *AtomicBinOp = 10093 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 10094 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 10095 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 10096 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 10097 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 10098 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 10099 if (!X->isLValue() || !V->isLValue()) { 10100 const Expr *NotLValueExpr = X->isLValue() ? V : X; 10101 ErrorFound = NotAnLValue; 10102 ErrorLoc = AtomicBinOp->getExprLoc(); 10103 ErrorRange = AtomicBinOp->getSourceRange(); 10104 NoteLoc = NotLValueExpr->getExprLoc(); 10105 NoteRange = NotLValueExpr->getSourceRange(); 10106 } 10107 } else if (!X->isInstantiationDependent() || 10108 !V->isInstantiationDependent()) { 10109 const Expr *NotScalarExpr = 10110 (X->isInstantiationDependent() || X->getType()->isScalarType()) 10111 ? V 10112 : X; 10113 ErrorFound = NotAScalarType; 10114 ErrorLoc = AtomicBinOp->getExprLoc(); 10115 ErrorRange = AtomicBinOp->getSourceRange(); 10116 NoteLoc = NotScalarExpr->getExprLoc(); 10117 NoteRange = NotScalarExpr->getSourceRange(); 10118 } 10119 } else if (!AtomicBody->isInstantiationDependent()) { 10120 ErrorFound = NotAnAssignmentOp; 10121 ErrorLoc = AtomicBody->getExprLoc(); 10122 ErrorRange = AtomicBody->getSourceRange(); 10123 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 10124 : AtomicBody->getExprLoc(); 10125 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 10126 : AtomicBody->getSourceRange(); 10127 } 10128 } else { 10129 ErrorFound = NotAnExpression; 10130 NoteLoc = ErrorLoc = Body->getBeginLoc(); 10131 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10132 } 10133 if (ErrorFound != NoError) { 10134 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 10135 << ErrorRange; 10136 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 10137 << NoteRange; 10138 return StmtError(); 10139 } 10140 if (CurContext->isDependentContext()) 10141 V = X = nullptr; 10142 } else if (AtomicKind == OMPC_write) { 10143 enum { 10144 NotAnExpression, 10145 NotAnAssignmentOp, 10146 NotAScalarType, 10147 NotAnLValue, 10148 NoError 10149 } ErrorFound = NoError; 10150 SourceLocation ErrorLoc, NoteLoc; 10151 SourceRange ErrorRange, NoteRange; 10152 // If clause is write: 10153 // x = expr; 10154 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 10155 const auto *AtomicBinOp = 10156 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 10157 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 10158 X = AtomicBinOp->getLHS(); 10159 E = AtomicBinOp->getRHS(); 10160 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 10161 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 10162 if (!X->isLValue()) { 10163 ErrorFound = NotAnLValue; 10164 ErrorLoc = AtomicBinOp->getExprLoc(); 10165 ErrorRange = AtomicBinOp->getSourceRange(); 10166 NoteLoc = X->getExprLoc(); 10167 NoteRange = X->getSourceRange(); 10168 } 10169 } else if (!X->isInstantiationDependent() || 10170 !E->isInstantiationDependent()) { 10171 const Expr *NotScalarExpr = 10172 (X->isInstantiationDependent() || X->getType()->isScalarType()) 10173 ? E 10174 : X; 10175 ErrorFound = NotAScalarType; 10176 ErrorLoc = AtomicBinOp->getExprLoc(); 10177 ErrorRange = AtomicBinOp->getSourceRange(); 10178 NoteLoc = NotScalarExpr->getExprLoc(); 10179 NoteRange = NotScalarExpr->getSourceRange(); 10180 } 10181 } else if (!AtomicBody->isInstantiationDependent()) { 10182 ErrorFound = NotAnAssignmentOp; 10183 ErrorLoc = AtomicBody->getExprLoc(); 10184 ErrorRange = AtomicBody->getSourceRange(); 10185 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 10186 : AtomicBody->getExprLoc(); 10187 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 10188 : AtomicBody->getSourceRange(); 10189 } 10190 } else { 10191 ErrorFound = NotAnExpression; 10192 NoteLoc = ErrorLoc = Body->getBeginLoc(); 10193 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10194 } 10195 if (ErrorFound != NoError) { 10196 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 10197 << ErrorRange; 10198 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 10199 << NoteRange; 10200 return StmtError(); 10201 } 10202 if (CurContext->isDependentContext()) 10203 E = X = nullptr; 10204 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 10205 // If clause is update: 10206 // x++; 10207 // x--; 10208 // ++x; 10209 // --x; 10210 // x binop= expr; 10211 // x = x binop expr; 10212 // x = expr binop x; 10213 OpenMPAtomicUpdateChecker Checker(*this); 10214 if (Checker.checkStatement( 10215 Body, (AtomicKind == OMPC_update) 10216 ? diag::err_omp_atomic_update_not_expression_statement 10217 : diag::err_omp_atomic_not_expression_statement, 10218 diag::note_omp_atomic_update)) 10219 return StmtError(); 10220 if (!CurContext->isDependentContext()) { 10221 E = Checker.getExpr(); 10222 X = Checker.getX(); 10223 UE = Checker.getUpdateExpr(); 10224 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 10225 } 10226 } else if (AtomicKind == OMPC_capture) { 10227 enum { 10228 NotAnAssignmentOp, 10229 NotACompoundStatement, 10230 NotTwoSubstatements, 10231 NotASpecificExpression, 10232 NoError 10233 } ErrorFound = NoError; 10234 SourceLocation ErrorLoc, NoteLoc; 10235 SourceRange ErrorRange, NoteRange; 10236 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 10237 // If clause is a capture: 10238 // v = x++; 10239 // v = x--; 10240 // v = ++x; 10241 // v = --x; 10242 // v = x binop= expr; 10243 // v = x = x binop expr; 10244 // v = x = expr binop x; 10245 const auto *AtomicBinOp = 10246 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 10247 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 10248 V = AtomicBinOp->getLHS(); 10249 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 10250 OpenMPAtomicUpdateChecker Checker(*this); 10251 if (Checker.checkStatement( 10252 Body, diag::err_omp_atomic_capture_not_expression_statement, 10253 diag::note_omp_atomic_update)) 10254 return StmtError(); 10255 E = Checker.getExpr(); 10256 X = Checker.getX(); 10257 UE = Checker.getUpdateExpr(); 10258 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 10259 IsPostfixUpdate = Checker.isPostfixUpdate(); 10260 } else if (!AtomicBody->isInstantiationDependent()) { 10261 ErrorLoc = AtomicBody->getExprLoc(); 10262 ErrorRange = AtomicBody->getSourceRange(); 10263 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 10264 : AtomicBody->getExprLoc(); 10265 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 10266 : AtomicBody->getSourceRange(); 10267 ErrorFound = NotAnAssignmentOp; 10268 } 10269 if (ErrorFound != NoError) { 10270 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 10271 << ErrorRange; 10272 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 10273 return StmtError(); 10274 } 10275 if (CurContext->isDependentContext()) 10276 UE = V = E = X = nullptr; 10277 } else { 10278 // If clause is a capture: 10279 // { v = x; x = expr; } 10280 // { v = x; x++; } 10281 // { v = x; x--; } 10282 // { v = x; ++x; } 10283 // { v = x; --x; } 10284 // { v = x; x binop= expr; } 10285 // { v = x; x = x binop expr; } 10286 // { v = x; x = expr binop x; } 10287 // { x++; v = x; } 10288 // { x--; v = x; } 10289 // { ++x; v = x; } 10290 // { --x; v = x; } 10291 // { x binop= expr; v = x; } 10292 // { x = x binop expr; v = x; } 10293 // { x = expr binop x; v = x; } 10294 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 10295 // Check that this is { expr1; expr2; } 10296 if (CS->size() == 2) { 10297 Stmt *First = CS->body_front(); 10298 Stmt *Second = CS->body_back(); 10299 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 10300 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 10301 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 10302 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 10303 // Need to find what subexpression is 'v' and what is 'x'. 10304 OpenMPAtomicUpdateChecker Checker(*this); 10305 bool IsUpdateExprFound = !Checker.checkStatement(Second); 10306 BinaryOperator *BinOp = nullptr; 10307 if (IsUpdateExprFound) { 10308 BinOp = dyn_cast<BinaryOperator>(First); 10309 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 10310 } 10311 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 10312 // { v = x; x++; } 10313 // { v = x; x--; } 10314 // { v = x; ++x; } 10315 // { v = x; --x; } 10316 // { v = x; x binop= expr; } 10317 // { v = x; x = x binop expr; } 10318 // { v = x; x = expr binop x; } 10319 // Check that the first expression has form v = x. 10320 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 10321 llvm::FoldingSetNodeID XId, PossibleXId; 10322 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 10323 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 10324 IsUpdateExprFound = XId == PossibleXId; 10325 if (IsUpdateExprFound) { 10326 V = BinOp->getLHS(); 10327 X = Checker.getX(); 10328 E = Checker.getExpr(); 10329 UE = Checker.getUpdateExpr(); 10330 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 10331 IsPostfixUpdate = true; 10332 } 10333 } 10334 if (!IsUpdateExprFound) { 10335 IsUpdateExprFound = !Checker.checkStatement(First); 10336 BinOp = nullptr; 10337 if (IsUpdateExprFound) { 10338 BinOp = dyn_cast<BinaryOperator>(Second); 10339 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 10340 } 10341 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 10342 // { x++; v = x; } 10343 // { x--; v = x; } 10344 // { ++x; v = x; } 10345 // { --x; v = x; } 10346 // { x binop= expr; v = x; } 10347 // { x = x binop expr; v = x; } 10348 // { x = expr binop x; v = x; } 10349 // Check that the second expression has form v = x. 10350 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 10351 llvm::FoldingSetNodeID XId, PossibleXId; 10352 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 10353 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 10354 IsUpdateExprFound = XId == PossibleXId; 10355 if (IsUpdateExprFound) { 10356 V = BinOp->getLHS(); 10357 X = Checker.getX(); 10358 E = Checker.getExpr(); 10359 UE = Checker.getUpdateExpr(); 10360 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 10361 IsPostfixUpdate = false; 10362 } 10363 } 10364 } 10365 if (!IsUpdateExprFound) { 10366 // { v = x; x = expr; } 10367 auto *FirstExpr = dyn_cast<Expr>(First); 10368 auto *SecondExpr = dyn_cast<Expr>(Second); 10369 if (!FirstExpr || !SecondExpr || 10370 !(FirstExpr->isInstantiationDependent() || 10371 SecondExpr->isInstantiationDependent())) { 10372 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 10373 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 10374 ErrorFound = NotAnAssignmentOp; 10375 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 10376 : First->getBeginLoc(); 10377 NoteRange = ErrorRange = FirstBinOp 10378 ? FirstBinOp->getSourceRange() 10379 : SourceRange(ErrorLoc, ErrorLoc); 10380 } else { 10381 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 10382 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 10383 ErrorFound = NotAnAssignmentOp; 10384 NoteLoc = ErrorLoc = SecondBinOp 10385 ? SecondBinOp->getOperatorLoc() 10386 : Second->getBeginLoc(); 10387 NoteRange = ErrorRange = 10388 SecondBinOp ? SecondBinOp->getSourceRange() 10389 : SourceRange(ErrorLoc, ErrorLoc); 10390 } else { 10391 Expr *PossibleXRHSInFirst = 10392 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 10393 Expr *PossibleXLHSInSecond = 10394 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 10395 llvm::FoldingSetNodeID X1Id, X2Id; 10396 PossibleXRHSInFirst->Profile(X1Id, Context, 10397 /*Canonical=*/true); 10398 PossibleXLHSInSecond->Profile(X2Id, Context, 10399 /*Canonical=*/true); 10400 IsUpdateExprFound = X1Id == X2Id; 10401 if (IsUpdateExprFound) { 10402 V = FirstBinOp->getLHS(); 10403 X = SecondBinOp->getLHS(); 10404 E = SecondBinOp->getRHS(); 10405 UE = nullptr; 10406 IsXLHSInRHSPart = false; 10407 IsPostfixUpdate = true; 10408 } else { 10409 ErrorFound = NotASpecificExpression; 10410 ErrorLoc = FirstBinOp->getExprLoc(); 10411 ErrorRange = FirstBinOp->getSourceRange(); 10412 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 10413 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 10414 } 10415 } 10416 } 10417 } 10418 } 10419 } else { 10420 NoteLoc = ErrorLoc = Body->getBeginLoc(); 10421 NoteRange = ErrorRange = 10422 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 10423 ErrorFound = NotTwoSubstatements; 10424 } 10425 } else { 10426 NoteLoc = ErrorLoc = Body->getBeginLoc(); 10427 NoteRange = ErrorRange = 10428 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 10429 ErrorFound = NotACompoundStatement; 10430 } 10431 if (ErrorFound != NoError) { 10432 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 10433 << ErrorRange; 10434 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 10435 return StmtError(); 10436 } 10437 if (CurContext->isDependentContext()) 10438 UE = V = E = X = nullptr; 10439 } 10440 } 10441 10442 setFunctionHasBranchProtectedScope(); 10443 10444 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10445 X, V, E, UE, IsXLHSInRHSPart, 10446 IsPostfixUpdate); 10447 } 10448 10449 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 10450 Stmt *AStmt, 10451 SourceLocation StartLoc, 10452 SourceLocation EndLoc) { 10453 if (!AStmt) 10454 return StmtError(); 10455 10456 auto *CS = cast<CapturedStmt>(AStmt); 10457 // 1.2.2 OpenMP Language Terminology 10458 // Structured block - An executable statement with a single entry at the 10459 // top and a single exit at the bottom. 10460 // The point of exit cannot be a branch out of the structured block. 10461 // longjmp() and throw() must not violate the entry/exit criteria. 10462 CS->getCapturedDecl()->setNothrow(); 10463 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 10464 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10465 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10466 // 1.2.2 OpenMP Language Terminology 10467 // Structured block - An executable statement with a single entry at the 10468 // top and a single exit at the bottom. 10469 // The point of exit cannot be a branch out of the structured block. 10470 // longjmp() and throw() must not violate the entry/exit criteria. 10471 CS->getCapturedDecl()->setNothrow(); 10472 } 10473 10474 // OpenMP [2.16, Nesting of Regions] 10475 // If specified, a teams construct must be contained within a target 10476 // construct. That target construct must contain no statements or directives 10477 // outside of the teams construct. 10478 if (DSAStack->hasInnerTeamsRegion()) { 10479 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 10480 bool OMPTeamsFound = true; 10481 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 10482 auto I = CS->body_begin(); 10483 while (I != CS->body_end()) { 10484 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 10485 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 10486 OMPTeamsFound) { 10487 10488 OMPTeamsFound = false; 10489 break; 10490 } 10491 ++I; 10492 } 10493 assert(I != CS->body_end() && "Not found statement"); 10494 S = *I; 10495 } else { 10496 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 10497 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 10498 } 10499 if (!OMPTeamsFound) { 10500 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 10501 Diag(DSAStack->getInnerTeamsRegionLoc(), 10502 diag::note_omp_nested_teams_construct_here); 10503 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 10504 << isa<OMPExecutableDirective>(S); 10505 return StmtError(); 10506 } 10507 } 10508 10509 setFunctionHasBranchProtectedScope(); 10510 10511 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10512 } 10513 10514 StmtResult 10515 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 10516 Stmt *AStmt, SourceLocation StartLoc, 10517 SourceLocation EndLoc) { 10518 if (!AStmt) 10519 return StmtError(); 10520 10521 auto *CS = cast<CapturedStmt>(AStmt); 10522 // 1.2.2 OpenMP Language Terminology 10523 // Structured block - An executable statement with a single entry at the 10524 // top and a single exit at the bottom. 10525 // The point of exit cannot be a branch out of the structured block. 10526 // longjmp() and throw() must not violate the entry/exit criteria. 10527 CS->getCapturedDecl()->setNothrow(); 10528 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 10529 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10530 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10531 // 1.2.2 OpenMP Language Terminology 10532 // Structured block - An executable statement with a single entry at the 10533 // top and a single exit at the bottom. 10534 // The point of exit cannot be a branch out of the structured block. 10535 // longjmp() and throw() must not violate the entry/exit criteria. 10536 CS->getCapturedDecl()->setNothrow(); 10537 } 10538 10539 setFunctionHasBranchProtectedScope(); 10540 10541 return OMPTargetParallelDirective::Create( 10542 Context, StartLoc, EndLoc, Clauses, AStmt, 10543 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10544 } 10545 10546 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 10547 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10548 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10549 if (!AStmt) 10550 return StmtError(); 10551 10552 auto *CS = cast<CapturedStmt>(AStmt); 10553 // 1.2.2 OpenMP Language Terminology 10554 // Structured block - An executable statement with a single entry at the 10555 // top and a single exit at the bottom. 10556 // The point of exit cannot be a branch out of the structured block. 10557 // longjmp() and throw() must not violate the entry/exit criteria. 10558 CS->getCapturedDecl()->setNothrow(); 10559 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 10560 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10561 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10562 // 1.2.2 OpenMP Language Terminology 10563 // Structured block - An executable statement with a single entry at the 10564 // top and a single exit at the bottom. 10565 // The point of exit cannot be a branch out of the structured block. 10566 // longjmp() and throw() must not violate the entry/exit criteria. 10567 CS->getCapturedDecl()->setNothrow(); 10568 } 10569 10570 OMPLoopBasedDirective::HelperExprs B; 10571 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10572 // define the nested loops number. 10573 unsigned NestedLoopCount = 10574 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 10575 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 10576 VarsWithImplicitDSA, B); 10577 if (NestedLoopCount == 0) 10578 return StmtError(); 10579 10580 assert((CurContext->isDependentContext() || B.builtAll()) && 10581 "omp target parallel for loop exprs were not built"); 10582 10583 if (!CurContext->isDependentContext()) { 10584 // Finalize the clauses that need pre-built expressions for CodeGen. 10585 for (OMPClause *C : Clauses) { 10586 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10587 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10588 B.NumIterations, *this, CurScope, 10589 DSAStack)) 10590 return StmtError(); 10591 } 10592 } 10593 10594 setFunctionHasBranchProtectedScope(); 10595 return OMPTargetParallelForDirective::Create( 10596 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10597 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10598 } 10599 10600 /// Check for existence of a map clause in the list of clauses. 10601 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 10602 const OpenMPClauseKind K) { 10603 return llvm::any_of( 10604 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 10605 } 10606 10607 template <typename... Params> 10608 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 10609 const Params... ClauseTypes) { 10610 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 10611 } 10612 10613 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 10614 Stmt *AStmt, 10615 SourceLocation StartLoc, 10616 SourceLocation EndLoc) { 10617 if (!AStmt) 10618 return StmtError(); 10619 10620 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10621 10622 // OpenMP [2.12.2, target data Construct, Restrictions] 10623 // At least one map, use_device_addr or use_device_ptr clause must appear on 10624 // the directive. 10625 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) && 10626 (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) { 10627 StringRef Expected; 10628 if (LangOpts.OpenMP < 50) 10629 Expected = "'map' or 'use_device_ptr'"; 10630 else 10631 Expected = "'map', 'use_device_ptr', or 'use_device_addr'"; 10632 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 10633 << Expected << getOpenMPDirectiveName(OMPD_target_data); 10634 return StmtError(); 10635 } 10636 10637 setFunctionHasBranchProtectedScope(); 10638 10639 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 10640 AStmt); 10641 } 10642 10643 StmtResult 10644 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 10645 SourceLocation StartLoc, 10646 SourceLocation EndLoc, Stmt *AStmt) { 10647 if (!AStmt) 10648 return StmtError(); 10649 10650 auto *CS = cast<CapturedStmt>(AStmt); 10651 // 1.2.2 OpenMP Language Terminology 10652 // Structured block - An executable statement with a single entry at the 10653 // top and a single exit at the bottom. 10654 // The point of exit cannot be a branch out of the structured block. 10655 // longjmp() and throw() must not violate the entry/exit criteria. 10656 CS->getCapturedDecl()->setNothrow(); 10657 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 10658 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10659 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10660 // 1.2.2 OpenMP Language Terminology 10661 // Structured block - An executable statement with a single entry at the 10662 // top and a single exit at the bottom. 10663 // The point of exit cannot be a branch out of the structured block. 10664 // longjmp() and throw() must not violate the entry/exit criteria. 10665 CS->getCapturedDecl()->setNothrow(); 10666 } 10667 10668 // OpenMP [2.10.2, Restrictions, p. 99] 10669 // At least one map clause must appear on the directive. 10670 if (!hasClauses(Clauses, OMPC_map)) { 10671 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 10672 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 10673 return StmtError(); 10674 } 10675 10676 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 10677 AStmt); 10678 } 10679 10680 StmtResult 10681 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 10682 SourceLocation StartLoc, 10683 SourceLocation EndLoc, Stmt *AStmt) { 10684 if (!AStmt) 10685 return StmtError(); 10686 10687 auto *CS = cast<CapturedStmt>(AStmt); 10688 // 1.2.2 OpenMP Language Terminology 10689 // Structured block - An executable statement with a single entry at the 10690 // top and a single exit at the bottom. 10691 // The point of exit cannot be a branch out of the structured block. 10692 // longjmp() and throw() must not violate the entry/exit criteria. 10693 CS->getCapturedDecl()->setNothrow(); 10694 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 10695 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10696 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10697 // 1.2.2 OpenMP Language Terminology 10698 // Structured block - An executable statement with a single entry at the 10699 // top and a single exit at the bottom. 10700 // The point of exit cannot be a branch out of the structured block. 10701 // longjmp() and throw() must not violate the entry/exit criteria. 10702 CS->getCapturedDecl()->setNothrow(); 10703 } 10704 10705 // OpenMP [2.10.3, Restrictions, p. 102] 10706 // At least one map clause must appear on the directive. 10707 if (!hasClauses(Clauses, OMPC_map)) { 10708 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 10709 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 10710 return StmtError(); 10711 } 10712 10713 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 10714 AStmt); 10715 } 10716 10717 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 10718 SourceLocation StartLoc, 10719 SourceLocation EndLoc, 10720 Stmt *AStmt) { 10721 if (!AStmt) 10722 return StmtError(); 10723 10724 auto *CS = cast<CapturedStmt>(AStmt); 10725 // 1.2.2 OpenMP Language Terminology 10726 // Structured block - An executable statement with a single entry at the 10727 // top and a single exit at the bottom. 10728 // The point of exit cannot be a branch out of the structured block. 10729 // longjmp() and throw() must not violate the entry/exit criteria. 10730 CS->getCapturedDecl()->setNothrow(); 10731 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 10732 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10733 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10734 // 1.2.2 OpenMP Language Terminology 10735 // Structured block - An executable statement with a single entry at the 10736 // top and a single exit at the bottom. 10737 // The point of exit cannot be a branch out of the structured block. 10738 // longjmp() and throw() must not violate the entry/exit criteria. 10739 CS->getCapturedDecl()->setNothrow(); 10740 } 10741 10742 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 10743 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 10744 return StmtError(); 10745 } 10746 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 10747 AStmt); 10748 } 10749 10750 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 10751 Stmt *AStmt, SourceLocation StartLoc, 10752 SourceLocation EndLoc) { 10753 if (!AStmt) 10754 return StmtError(); 10755 10756 auto *CS = cast<CapturedStmt>(AStmt); 10757 // 1.2.2 OpenMP Language Terminology 10758 // Structured block - An executable statement with a single entry at the 10759 // top and a single exit at the bottom. 10760 // The point of exit cannot be a branch out of the structured block. 10761 // longjmp() and throw() must not violate the entry/exit criteria. 10762 CS->getCapturedDecl()->setNothrow(); 10763 10764 setFunctionHasBranchProtectedScope(); 10765 10766 DSAStack->setParentTeamsRegionLoc(StartLoc); 10767 10768 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10769 } 10770 10771 StmtResult 10772 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 10773 SourceLocation EndLoc, 10774 OpenMPDirectiveKind CancelRegion) { 10775 if (DSAStack->isParentNowaitRegion()) { 10776 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 10777 return StmtError(); 10778 } 10779 if (DSAStack->isParentOrderedRegion()) { 10780 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 10781 return StmtError(); 10782 } 10783 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 10784 CancelRegion); 10785 } 10786 10787 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 10788 SourceLocation StartLoc, 10789 SourceLocation EndLoc, 10790 OpenMPDirectiveKind CancelRegion) { 10791 if (DSAStack->isParentNowaitRegion()) { 10792 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 10793 return StmtError(); 10794 } 10795 if (DSAStack->isParentOrderedRegion()) { 10796 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 10797 return StmtError(); 10798 } 10799 DSAStack->setParentCancelRegion(/*Cancel=*/true); 10800 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 10801 CancelRegion); 10802 } 10803 10804 static bool checkGrainsizeNumTasksClauses(Sema &S, 10805 ArrayRef<OMPClause *> Clauses) { 10806 const OMPClause *PrevClause = nullptr; 10807 bool ErrorFound = false; 10808 for (const OMPClause *C : Clauses) { 10809 if (C->getClauseKind() == OMPC_grainsize || 10810 C->getClauseKind() == OMPC_num_tasks) { 10811 if (!PrevClause) 10812 PrevClause = C; 10813 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 10814 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive) 10815 << getOpenMPClauseName(C->getClauseKind()) 10816 << getOpenMPClauseName(PrevClause->getClauseKind()); 10817 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause) 10818 << getOpenMPClauseName(PrevClause->getClauseKind()); 10819 ErrorFound = true; 10820 } 10821 } 10822 } 10823 return ErrorFound; 10824 } 10825 10826 static bool checkReductionClauseWithNogroup(Sema &S, 10827 ArrayRef<OMPClause *> Clauses) { 10828 const OMPClause *ReductionClause = nullptr; 10829 const OMPClause *NogroupClause = nullptr; 10830 for (const OMPClause *C : Clauses) { 10831 if (C->getClauseKind() == OMPC_reduction) { 10832 ReductionClause = C; 10833 if (NogroupClause) 10834 break; 10835 continue; 10836 } 10837 if (C->getClauseKind() == OMPC_nogroup) { 10838 NogroupClause = C; 10839 if (ReductionClause) 10840 break; 10841 continue; 10842 } 10843 } 10844 if (ReductionClause && NogroupClause) { 10845 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 10846 << SourceRange(NogroupClause->getBeginLoc(), 10847 NogroupClause->getEndLoc()); 10848 return true; 10849 } 10850 return false; 10851 } 10852 10853 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 10854 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10855 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10856 if (!AStmt) 10857 return StmtError(); 10858 10859 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10860 OMPLoopBasedDirective::HelperExprs B; 10861 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10862 // define the nested loops number. 10863 unsigned NestedLoopCount = 10864 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 10865 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 10866 VarsWithImplicitDSA, B); 10867 if (NestedLoopCount == 0) 10868 return StmtError(); 10869 10870 assert((CurContext->isDependentContext() || B.builtAll()) && 10871 "omp for loop exprs were not built"); 10872 10873 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10874 // The grainsize clause and num_tasks clause are mutually exclusive and may 10875 // not appear on the same taskloop directive. 10876 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10877 return StmtError(); 10878 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10879 // If a reduction clause is present on the taskloop directive, the nogroup 10880 // clause must not be specified. 10881 if (checkReductionClauseWithNogroup(*this, Clauses)) 10882 return StmtError(); 10883 10884 setFunctionHasBranchProtectedScope(); 10885 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 10886 NestedLoopCount, Clauses, AStmt, B, 10887 DSAStack->isCancelRegion()); 10888 } 10889 10890 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 10891 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10892 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10893 if (!AStmt) 10894 return StmtError(); 10895 10896 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10897 OMPLoopBasedDirective::HelperExprs B; 10898 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10899 // define the nested loops number. 10900 unsigned NestedLoopCount = 10901 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 10902 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 10903 VarsWithImplicitDSA, B); 10904 if (NestedLoopCount == 0) 10905 return StmtError(); 10906 10907 assert((CurContext->isDependentContext() || B.builtAll()) && 10908 "omp for loop exprs were not built"); 10909 10910 if (!CurContext->isDependentContext()) { 10911 // Finalize the clauses that need pre-built expressions for CodeGen. 10912 for (OMPClause *C : Clauses) { 10913 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10914 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10915 B.NumIterations, *this, CurScope, 10916 DSAStack)) 10917 return StmtError(); 10918 } 10919 } 10920 10921 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10922 // The grainsize clause and num_tasks clause are mutually exclusive and may 10923 // not appear on the same taskloop directive. 10924 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10925 return StmtError(); 10926 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10927 // If a reduction clause is present on the taskloop directive, the nogroup 10928 // clause must not be specified. 10929 if (checkReductionClauseWithNogroup(*this, Clauses)) 10930 return StmtError(); 10931 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10932 return StmtError(); 10933 10934 setFunctionHasBranchProtectedScope(); 10935 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 10936 NestedLoopCount, Clauses, AStmt, B); 10937 } 10938 10939 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective( 10940 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10941 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10942 if (!AStmt) 10943 return StmtError(); 10944 10945 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10946 OMPLoopBasedDirective::HelperExprs B; 10947 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10948 // define the nested loops number. 10949 unsigned NestedLoopCount = 10950 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses), 10951 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 10952 VarsWithImplicitDSA, B); 10953 if (NestedLoopCount == 0) 10954 return StmtError(); 10955 10956 assert((CurContext->isDependentContext() || B.builtAll()) && 10957 "omp for loop exprs were not built"); 10958 10959 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10960 // The grainsize clause and num_tasks clause are mutually exclusive and may 10961 // not appear on the same taskloop directive. 10962 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10963 return StmtError(); 10964 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10965 // If a reduction clause is present on the taskloop directive, the nogroup 10966 // clause must not be specified. 10967 if (checkReductionClauseWithNogroup(*this, Clauses)) 10968 return StmtError(); 10969 10970 setFunctionHasBranchProtectedScope(); 10971 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc, 10972 NestedLoopCount, Clauses, AStmt, B, 10973 DSAStack->isCancelRegion()); 10974 } 10975 10976 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective( 10977 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10978 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10979 if (!AStmt) 10980 return StmtError(); 10981 10982 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10983 OMPLoopBasedDirective::HelperExprs B; 10984 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10985 // define the nested loops number. 10986 unsigned NestedLoopCount = 10987 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses), 10988 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 10989 VarsWithImplicitDSA, B); 10990 if (NestedLoopCount == 0) 10991 return StmtError(); 10992 10993 assert((CurContext->isDependentContext() || B.builtAll()) && 10994 "omp for loop exprs were not built"); 10995 10996 if (!CurContext->isDependentContext()) { 10997 // Finalize the clauses that need pre-built expressions for CodeGen. 10998 for (OMPClause *C : Clauses) { 10999 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11000 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11001 B.NumIterations, *this, CurScope, 11002 DSAStack)) 11003 return StmtError(); 11004 } 11005 } 11006 11007 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11008 // The grainsize clause and num_tasks clause are mutually exclusive and may 11009 // not appear on the same taskloop directive. 11010 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 11011 return StmtError(); 11012 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11013 // If a reduction clause is present on the taskloop directive, the nogroup 11014 // clause must not be specified. 11015 if (checkReductionClauseWithNogroup(*this, Clauses)) 11016 return StmtError(); 11017 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11018 return StmtError(); 11019 11020 setFunctionHasBranchProtectedScope(); 11021 return OMPMasterTaskLoopSimdDirective::Create( 11022 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11023 } 11024 11025 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective( 11026 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11027 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11028 if (!AStmt) 11029 return StmtError(); 11030 11031 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11032 auto *CS = cast<CapturedStmt>(AStmt); 11033 // 1.2.2 OpenMP Language Terminology 11034 // Structured block - An executable statement with a single entry at the 11035 // top and a single exit at the bottom. 11036 // The point of exit cannot be a branch out of the structured block. 11037 // longjmp() and throw() must not violate the entry/exit criteria. 11038 CS->getCapturedDecl()->setNothrow(); 11039 for (int ThisCaptureLevel = 11040 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop); 11041 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11042 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11043 // 1.2.2 OpenMP Language Terminology 11044 // Structured block - An executable statement with a single entry at the 11045 // top and a single exit at the bottom. 11046 // The point of exit cannot be a branch out of the structured block. 11047 // longjmp() and throw() must not violate the entry/exit criteria. 11048 CS->getCapturedDecl()->setNothrow(); 11049 } 11050 11051 OMPLoopBasedDirective::HelperExprs B; 11052 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11053 // define the nested loops number. 11054 unsigned NestedLoopCount = checkOpenMPLoop( 11055 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses), 11056 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 11057 VarsWithImplicitDSA, B); 11058 if (NestedLoopCount == 0) 11059 return StmtError(); 11060 11061 assert((CurContext->isDependentContext() || B.builtAll()) && 11062 "omp for loop exprs were not built"); 11063 11064 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11065 // The grainsize clause and num_tasks clause are mutually exclusive and may 11066 // not appear on the same taskloop directive. 11067 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 11068 return StmtError(); 11069 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11070 // If a reduction clause is present on the taskloop directive, the nogroup 11071 // clause must not be specified. 11072 if (checkReductionClauseWithNogroup(*this, Clauses)) 11073 return StmtError(); 11074 11075 setFunctionHasBranchProtectedScope(); 11076 return OMPParallelMasterTaskLoopDirective::Create( 11077 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11078 DSAStack->isCancelRegion()); 11079 } 11080 11081 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective( 11082 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11083 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11084 if (!AStmt) 11085 return StmtError(); 11086 11087 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11088 auto *CS = cast<CapturedStmt>(AStmt); 11089 // 1.2.2 OpenMP Language Terminology 11090 // Structured block - An executable statement with a single entry at the 11091 // top and a single exit at the bottom. 11092 // The point of exit cannot be a branch out of the structured block. 11093 // longjmp() and throw() must not violate the entry/exit criteria. 11094 CS->getCapturedDecl()->setNothrow(); 11095 for (int ThisCaptureLevel = 11096 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd); 11097 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11098 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11099 // 1.2.2 OpenMP Language Terminology 11100 // Structured block - An executable statement with a single entry at the 11101 // top and a single exit at the bottom. 11102 // The point of exit cannot be a branch out of the structured block. 11103 // longjmp() and throw() must not violate the entry/exit criteria. 11104 CS->getCapturedDecl()->setNothrow(); 11105 } 11106 11107 OMPLoopBasedDirective::HelperExprs B; 11108 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11109 // define the nested loops number. 11110 unsigned NestedLoopCount = checkOpenMPLoop( 11111 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses), 11112 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 11113 VarsWithImplicitDSA, B); 11114 if (NestedLoopCount == 0) 11115 return StmtError(); 11116 11117 assert((CurContext->isDependentContext() || B.builtAll()) && 11118 "omp for loop exprs were not built"); 11119 11120 if (!CurContext->isDependentContext()) { 11121 // Finalize the clauses that need pre-built expressions for CodeGen. 11122 for (OMPClause *C : Clauses) { 11123 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11124 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11125 B.NumIterations, *this, CurScope, 11126 DSAStack)) 11127 return StmtError(); 11128 } 11129 } 11130 11131 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11132 // The grainsize clause and num_tasks clause are mutually exclusive and may 11133 // not appear on the same taskloop directive. 11134 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 11135 return StmtError(); 11136 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11137 // If a reduction clause is present on the taskloop directive, the nogroup 11138 // clause must not be specified. 11139 if (checkReductionClauseWithNogroup(*this, Clauses)) 11140 return StmtError(); 11141 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11142 return StmtError(); 11143 11144 setFunctionHasBranchProtectedScope(); 11145 return OMPParallelMasterTaskLoopSimdDirective::Create( 11146 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11147 } 11148 11149 StmtResult Sema::ActOnOpenMPDistributeDirective( 11150 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11151 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11152 if (!AStmt) 11153 return StmtError(); 11154 11155 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11156 OMPLoopBasedDirective::HelperExprs B; 11157 // In presence of clause 'collapse' with number of loops, it will 11158 // define the nested loops number. 11159 unsigned NestedLoopCount = 11160 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 11161 nullptr /*ordered not a clause on distribute*/, AStmt, 11162 *this, *DSAStack, VarsWithImplicitDSA, B); 11163 if (NestedLoopCount == 0) 11164 return StmtError(); 11165 11166 assert((CurContext->isDependentContext() || B.builtAll()) && 11167 "omp for loop exprs were not built"); 11168 11169 setFunctionHasBranchProtectedScope(); 11170 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 11171 NestedLoopCount, Clauses, AStmt, B); 11172 } 11173 11174 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 11175 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11176 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11177 if (!AStmt) 11178 return StmtError(); 11179 11180 auto *CS = cast<CapturedStmt>(AStmt); 11181 // 1.2.2 OpenMP Language Terminology 11182 // Structured block - An executable statement with a single entry at the 11183 // top and a single exit at the bottom. 11184 // The point of exit cannot be a branch out of the structured block. 11185 // longjmp() and throw() must not violate the entry/exit criteria. 11186 CS->getCapturedDecl()->setNothrow(); 11187 for (int ThisCaptureLevel = 11188 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 11189 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11190 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11191 // 1.2.2 OpenMP Language Terminology 11192 // Structured block - An executable statement with a single entry at the 11193 // top and a single exit at the bottom. 11194 // The point of exit cannot be a branch out of the structured block. 11195 // longjmp() and throw() must not violate the entry/exit criteria. 11196 CS->getCapturedDecl()->setNothrow(); 11197 } 11198 11199 OMPLoopBasedDirective::HelperExprs B; 11200 // In presence of clause 'collapse' with number of loops, it will 11201 // define the nested loops number. 11202 unsigned NestedLoopCount = checkOpenMPLoop( 11203 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 11204 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11205 VarsWithImplicitDSA, B); 11206 if (NestedLoopCount == 0) 11207 return StmtError(); 11208 11209 assert((CurContext->isDependentContext() || B.builtAll()) && 11210 "omp for loop exprs were not built"); 11211 11212 setFunctionHasBranchProtectedScope(); 11213 return OMPDistributeParallelForDirective::Create( 11214 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11215 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11216 } 11217 11218 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 11219 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11220 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11221 if (!AStmt) 11222 return StmtError(); 11223 11224 auto *CS = cast<CapturedStmt>(AStmt); 11225 // 1.2.2 OpenMP Language Terminology 11226 // Structured block - An executable statement with a single entry at the 11227 // top and a single exit at the bottom. 11228 // The point of exit cannot be a branch out of the structured block. 11229 // longjmp() and throw() must not violate the entry/exit criteria. 11230 CS->getCapturedDecl()->setNothrow(); 11231 for (int ThisCaptureLevel = 11232 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 11233 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11234 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11235 // 1.2.2 OpenMP Language Terminology 11236 // Structured block - An executable statement with a single entry at the 11237 // top and a single exit at the bottom. 11238 // The point of exit cannot be a branch out of the structured block. 11239 // longjmp() and throw() must not violate the entry/exit criteria. 11240 CS->getCapturedDecl()->setNothrow(); 11241 } 11242 11243 OMPLoopBasedDirective::HelperExprs B; 11244 // In presence of clause 'collapse' with number of loops, it will 11245 // define the nested loops number. 11246 unsigned NestedLoopCount = checkOpenMPLoop( 11247 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 11248 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11249 VarsWithImplicitDSA, B); 11250 if (NestedLoopCount == 0) 11251 return StmtError(); 11252 11253 assert((CurContext->isDependentContext() || B.builtAll()) && 11254 "omp for loop exprs were not built"); 11255 11256 if (!CurContext->isDependentContext()) { 11257 // Finalize the clauses that need pre-built expressions for CodeGen. 11258 for (OMPClause *C : Clauses) { 11259 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11260 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11261 B.NumIterations, *this, CurScope, 11262 DSAStack)) 11263 return StmtError(); 11264 } 11265 } 11266 11267 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11268 return StmtError(); 11269 11270 setFunctionHasBranchProtectedScope(); 11271 return OMPDistributeParallelForSimdDirective::Create( 11272 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11273 } 11274 11275 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 11276 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11277 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11278 if (!AStmt) 11279 return StmtError(); 11280 11281 auto *CS = cast<CapturedStmt>(AStmt); 11282 // 1.2.2 OpenMP Language Terminology 11283 // Structured block - An executable statement with a single entry at the 11284 // top and a single exit at the bottom. 11285 // The point of exit cannot be a branch out of the structured block. 11286 // longjmp() and throw() must not violate the entry/exit criteria. 11287 CS->getCapturedDecl()->setNothrow(); 11288 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 11289 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11290 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11291 // 1.2.2 OpenMP Language Terminology 11292 // Structured block - An executable statement with a single entry at the 11293 // top and a single exit at the bottom. 11294 // The point of exit cannot be a branch out of the structured block. 11295 // longjmp() and throw() must not violate the entry/exit criteria. 11296 CS->getCapturedDecl()->setNothrow(); 11297 } 11298 11299 OMPLoopBasedDirective::HelperExprs B; 11300 // In presence of clause 'collapse' with number of loops, it will 11301 // define the nested loops number. 11302 unsigned NestedLoopCount = 11303 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 11304 nullptr /*ordered not a clause on distribute*/, CS, *this, 11305 *DSAStack, VarsWithImplicitDSA, B); 11306 if (NestedLoopCount == 0) 11307 return StmtError(); 11308 11309 assert((CurContext->isDependentContext() || B.builtAll()) && 11310 "omp for loop exprs were not built"); 11311 11312 if (!CurContext->isDependentContext()) { 11313 // Finalize the clauses that need pre-built expressions for CodeGen. 11314 for (OMPClause *C : Clauses) { 11315 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11316 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11317 B.NumIterations, *this, CurScope, 11318 DSAStack)) 11319 return StmtError(); 11320 } 11321 } 11322 11323 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11324 return StmtError(); 11325 11326 setFunctionHasBranchProtectedScope(); 11327 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 11328 NestedLoopCount, Clauses, AStmt, B); 11329 } 11330 11331 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 11332 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11333 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11334 if (!AStmt) 11335 return StmtError(); 11336 11337 auto *CS = cast<CapturedStmt>(AStmt); 11338 // 1.2.2 OpenMP Language Terminology 11339 // Structured block - An executable statement with a single entry at the 11340 // top and a single exit at the bottom. 11341 // The point of exit cannot be a branch out of the structured block. 11342 // longjmp() and throw() must not violate the entry/exit criteria. 11343 CS->getCapturedDecl()->setNothrow(); 11344 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 11345 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11346 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11347 // 1.2.2 OpenMP Language Terminology 11348 // Structured block - An executable statement with a single entry at the 11349 // top and a single exit at the bottom. 11350 // The point of exit cannot be a branch out of the structured block. 11351 // longjmp() and throw() must not violate the entry/exit criteria. 11352 CS->getCapturedDecl()->setNothrow(); 11353 } 11354 11355 OMPLoopBasedDirective::HelperExprs B; 11356 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11357 // define the nested loops number. 11358 unsigned NestedLoopCount = checkOpenMPLoop( 11359 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 11360 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 11361 VarsWithImplicitDSA, B); 11362 if (NestedLoopCount == 0) 11363 return StmtError(); 11364 11365 assert((CurContext->isDependentContext() || B.builtAll()) && 11366 "omp target parallel for simd loop exprs were not built"); 11367 11368 if (!CurContext->isDependentContext()) { 11369 // Finalize the clauses that need pre-built expressions for CodeGen. 11370 for (OMPClause *C : Clauses) { 11371 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11372 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11373 B.NumIterations, *this, CurScope, 11374 DSAStack)) 11375 return StmtError(); 11376 } 11377 } 11378 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11379 return StmtError(); 11380 11381 setFunctionHasBranchProtectedScope(); 11382 return OMPTargetParallelForSimdDirective::Create( 11383 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11384 } 11385 11386 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 11387 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11388 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11389 if (!AStmt) 11390 return StmtError(); 11391 11392 auto *CS = cast<CapturedStmt>(AStmt); 11393 // 1.2.2 OpenMP Language Terminology 11394 // Structured block - An executable statement with a single entry at the 11395 // top and a single exit at the bottom. 11396 // The point of exit cannot be a branch out of the structured block. 11397 // longjmp() and throw() must not violate the entry/exit criteria. 11398 CS->getCapturedDecl()->setNothrow(); 11399 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 11400 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11401 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11402 // 1.2.2 OpenMP Language Terminology 11403 // Structured block - An executable statement with a single entry at the 11404 // top and a single exit at the bottom. 11405 // The point of exit cannot be a branch out of the structured block. 11406 // longjmp() and throw() must not violate the entry/exit criteria. 11407 CS->getCapturedDecl()->setNothrow(); 11408 } 11409 11410 OMPLoopBasedDirective::HelperExprs B; 11411 // In presence of clause 'collapse' with number of loops, it will define the 11412 // nested loops number. 11413 unsigned NestedLoopCount = 11414 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 11415 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 11416 VarsWithImplicitDSA, B); 11417 if (NestedLoopCount == 0) 11418 return StmtError(); 11419 11420 assert((CurContext->isDependentContext() || B.builtAll()) && 11421 "omp target simd loop exprs were not built"); 11422 11423 if (!CurContext->isDependentContext()) { 11424 // Finalize the clauses that need pre-built expressions for CodeGen. 11425 for (OMPClause *C : Clauses) { 11426 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11427 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11428 B.NumIterations, *this, CurScope, 11429 DSAStack)) 11430 return StmtError(); 11431 } 11432 } 11433 11434 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11435 return StmtError(); 11436 11437 setFunctionHasBranchProtectedScope(); 11438 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 11439 NestedLoopCount, Clauses, AStmt, B); 11440 } 11441 11442 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 11443 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11444 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11445 if (!AStmt) 11446 return StmtError(); 11447 11448 auto *CS = cast<CapturedStmt>(AStmt); 11449 // 1.2.2 OpenMP Language Terminology 11450 // Structured block - An executable statement with a single entry at the 11451 // top and a single exit at the bottom. 11452 // The point of exit cannot be a branch out of the structured block. 11453 // longjmp() and throw() must not violate the entry/exit criteria. 11454 CS->getCapturedDecl()->setNothrow(); 11455 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 11456 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11457 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11458 // 1.2.2 OpenMP Language Terminology 11459 // Structured block - An executable statement with a single entry at the 11460 // top and a single exit at the bottom. 11461 // The point of exit cannot be a branch out of the structured block. 11462 // longjmp() and throw() must not violate the entry/exit criteria. 11463 CS->getCapturedDecl()->setNothrow(); 11464 } 11465 11466 OMPLoopBasedDirective::HelperExprs B; 11467 // In presence of clause 'collapse' with number of loops, it will 11468 // define the nested loops number. 11469 unsigned NestedLoopCount = 11470 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 11471 nullptr /*ordered not a clause on distribute*/, CS, *this, 11472 *DSAStack, VarsWithImplicitDSA, B); 11473 if (NestedLoopCount == 0) 11474 return StmtError(); 11475 11476 assert((CurContext->isDependentContext() || B.builtAll()) && 11477 "omp teams distribute loop exprs were not built"); 11478 11479 setFunctionHasBranchProtectedScope(); 11480 11481 DSAStack->setParentTeamsRegionLoc(StartLoc); 11482 11483 return OMPTeamsDistributeDirective::Create( 11484 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11485 } 11486 11487 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 11488 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11489 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11490 if (!AStmt) 11491 return StmtError(); 11492 11493 auto *CS = cast<CapturedStmt>(AStmt); 11494 // 1.2.2 OpenMP Language Terminology 11495 // Structured block - An executable statement with a single entry at the 11496 // top and a single exit at the bottom. 11497 // The point of exit cannot be a branch out of the structured block. 11498 // longjmp() and throw() must not violate the entry/exit criteria. 11499 CS->getCapturedDecl()->setNothrow(); 11500 for (int ThisCaptureLevel = 11501 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 11502 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11503 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11504 // 1.2.2 OpenMP Language Terminology 11505 // Structured block - An executable statement with a single entry at the 11506 // top and a single exit at the bottom. 11507 // The point of exit cannot be a branch out of the structured block. 11508 // longjmp() and throw() must not violate the entry/exit criteria. 11509 CS->getCapturedDecl()->setNothrow(); 11510 } 11511 11512 OMPLoopBasedDirective::HelperExprs B; 11513 // In presence of clause 'collapse' with number of loops, it will 11514 // define the nested loops number. 11515 unsigned NestedLoopCount = checkOpenMPLoop( 11516 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 11517 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11518 VarsWithImplicitDSA, B); 11519 11520 if (NestedLoopCount == 0) 11521 return StmtError(); 11522 11523 assert((CurContext->isDependentContext() || B.builtAll()) && 11524 "omp teams distribute simd loop exprs were not built"); 11525 11526 if (!CurContext->isDependentContext()) { 11527 // Finalize the clauses that need pre-built expressions for CodeGen. 11528 for (OMPClause *C : Clauses) { 11529 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11530 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11531 B.NumIterations, *this, CurScope, 11532 DSAStack)) 11533 return StmtError(); 11534 } 11535 } 11536 11537 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11538 return StmtError(); 11539 11540 setFunctionHasBranchProtectedScope(); 11541 11542 DSAStack->setParentTeamsRegionLoc(StartLoc); 11543 11544 return OMPTeamsDistributeSimdDirective::Create( 11545 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11546 } 11547 11548 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 11549 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11550 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11551 if (!AStmt) 11552 return StmtError(); 11553 11554 auto *CS = cast<CapturedStmt>(AStmt); 11555 // 1.2.2 OpenMP Language Terminology 11556 // Structured block - An executable statement with a single entry at the 11557 // top and a single exit at the bottom. 11558 // The point of exit cannot be a branch out of the structured block. 11559 // longjmp() and throw() must not violate the entry/exit criteria. 11560 CS->getCapturedDecl()->setNothrow(); 11561 11562 for (int ThisCaptureLevel = 11563 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 11564 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11565 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11566 // 1.2.2 OpenMP Language Terminology 11567 // Structured block - An executable statement with a single entry at the 11568 // top and a single exit at the bottom. 11569 // The point of exit cannot be a branch out of the structured block. 11570 // longjmp() and throw() must not violate the entry/exit criteria. 11571 CS->getCapturedDecl()->setNothrow(); 11572 } 11573 11574 OMPLoopBasedDirective::HelperExprs B; 11575 // In presence of clause 'collapse' with number of loops, it will 11576 // define the nested loops number. 11577 unsigned NestedLoopCount = checkOpenMPLoop( 11578 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 11579 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11580 VarsWithImplicitDSA, B); 11581 11582 if (NestedLoopCount == 0) 11583 return StmtError(); 11584 11585 assert((CurContext->isDependentContext() || B.builtAll()) && 11586 "omp for loop exprs were not built"); 11587 11588 if (!CurContext->isDependentContext()) { 11589 // Finalize the clauses that need pre-built expressions for CodeGen. 11590 for (OMPClause *C : Clauses) { 11591 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11592 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11593 B.NumIterations, *this, CurScope, 11594 DSAStack)) 11595 return StmtError(); 11596 } 11597 } 11598 11599 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11600 return StmtError(); 11601 11602 setFunctionHasBranchProtectedScope(); 11603 11604 DSAStack->setParentTeamsRegionLoc(StartLoc); 11605 11606 return OMPTeamsDistributeParallelForSimdDirective::Create( 11607 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11608 } 11609 11610 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 11611 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11612 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11613 if (!AStmt) 11614 return StmtError(); 11615 11616 auto *CS = cast<CapturedStmt>(AStmt); 11617 // 1.2.2 OpenMP Language Terminology 11618 // Structured block - An executable statement with a single entry at the 11619 // top and a single exit at the bottom. 11620 // The point of exit cannot be a branch out of the structured block. 11621 // longjmp() and throw() must not violate the entry/exit criteria. 11622 CS->getCapturedDecl()->setNothrow(); 11623 11624 for (int ThisCaptureLevel = 11625 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 11626 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11627 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11628 // 1.2.2 OpenMP Language Terminology 11629 // Structured block - An executable statement with a single entry at the 11630 // top and a single exit at the bottom. 11631 // The point of exit cannot be a branch out of the structured block. 11632 // longjmp() and throw() must not violate the entry/exit criteria. 11633 CS->getCapturedDecl()->setNothrow(); 11634 } 11635 11636 OMPLoopBasedDirective::HelperExprs B; 11637 // In presence of clause 'collapse' with number of loops, it will 11638 // define the nested loops number. 11639 unsigned NestedLoopCount = checkOpenMPLoop( 11640 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 11641 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11642 VarsWithImplicitDSA, B); 11643 11644 if (NestedLoopCount == 0) 11645 return StmtError(); 11646 11647 assert((CurContext->isDependentContext() || B.builtAll()) && 11648 "omp for loop exprs were not built"); 11649 11650 setFunctionHasBranchProtectedScope(); 11651 11652 DSAStack->setParentTeamsRegionLoc(StartLoc); 11653 11654 return OMPTeamsDistributeParallelForDirective::Create( 11655 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11656 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11657 } 11658 11659 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 11660 Stmt *AStmt, 11661 SourceLocation StartLoc, 11662 SourceLocation EndLoc) { 11663 if (!AStmt) 11664 return StmtError(); 11665 11666 auto *CS = cast<CapturedStmt>(AStmt); 11667 // 1.2.2 OpenMP Language Terminology 11668 // Structured block - An executable statement with a single entry at the 11669 // top and a single exit at the bottom. 11670 // The point of exit cannot be a branch out of the structured block. 11671 // longjmp() and throw() must not violate the entry/exit criteria. 11672 CS->getCapturedDecl()->setNothrow(); 11673 11674 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 11675 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11676 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11677 // 1.2.2 OpenMP Language Terminology 11678 // Structured block - An executable statement with a single entry at the 11679 // top and a single exit at the bottom. 11680 // The point of exit cannot be a branch out of the structured block. 11681 // longjmp() and throw() must not violate the entry/exit criteria. 11682 CS->getCapturedDecl()->setNothrow(); 11683 } 11684 setFunctionHasBranchProtectedScope(); 11685 11686 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 11687 AStmt); 11688 } 11689 11690 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 11691 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11692 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11693 if (!AStmt) 11694 return StmtError(); 11695 11696 auto *CS = cast<CapturedStmt>(AStmt); 11697 // 1.2.2 OpenMP Language Terminology 11698 // Structured block - An executable statement with a single entry at the 11699 // top and a single exit at the bottom. 11700 // The point of exit cannot be a branch out of the structured block. 11701 // longjmp() and throw() must not violate the entry/exit criteria. 11702 CS->getCapturedDecl()->setNothrow(); 11703 for (int ThisCaptureLevel = 11704 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 11705 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11706 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11707 // 1.2.2 OpenMP Language Terminology 11708 // Structured block - An executable statement with a single entry at the 11709 // top and a single exit at the bottom. 11710 // The point of exit cannot be a branch out of the structured block. 11711 // longjmp() and throw() must not violate the entry/exit criteria. 11712 CS->getCapturedDecl()->setNothrow(); 11713 } 11714 11715 OMPLoopBasedDirective::HelperExprs B; 11716 // In presence of clause 'collapse' with number of loops, it will 11717 // define the nested loops number. 11718 unsigned NestedLoopCount = checkOpenMPLoop( 11719 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 11720 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11721 VarsWithImplicitDSA, B); 11722 if (NestedLoopCount == 0) 11723 return StmtError(); 11724 11725 assert((CurContext->isDependentContext() || B.builtAll()) && 11726 "omp target teams distribute loop exprs were not built"); 11727 11728 setFunctionHasBranchProtectedScope(); 11729 return OMPTargetTeamsDistributeDirective::Create( 11730 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11731 } 11732 11733 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 11734 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11735 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11736 if (!AStmt) 11737 return StmtError(); 11738 11739 auto *CS = cast<CapturedStmt>(AStmt); 11740 // 1.2.2 OpenMP Language Terminology 11741 // Structured block - An executable statement with a single entry at the 11742 // top and a single exit at the bottom. 11743 // The point of exit cannot be a branch out of the structured block. 11744 // longjmp() and throw() must not violate the entry/exit criteria. 11745 CS->getCapturedDecl()->setNothrow(); 11746 for (int ThisCaptureLevel = 11747 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 11748 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11749 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11750 // 1.2.2 OpenMP Language Terminology 11751 // Structured block - An executable statement with a single entry at the 11752 // top and a single exit at the bottom. 11753 // The point of exit cannot be a branch out of the structured block. 11754 // longjmp() and throw() must not violate the entry/exit criteria. 11755 CS->getCapturedDecl()->setNothrow(); 11756 } 11757 11758 OMPLoopBasedDirective::HelperExprs B; 11759 // In presence of clause 'collapse' with number of loops, it will 11760 // define the nested loops number. 11761 unsigned NestedLoopCount = checkOpenMPLoop( 11762 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 11763 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11764 VarsWithImplicitDSA, B); 11765 if (NestedLoopCount == 0) 11766 return StmtError(); 11767 11768 assert((CurContext->isDependentContext() || B.builtAll()) && 11769 "omp target teams distribute parallel for loop exprs were not built"); 11770 11771 if (!CurContext->isDependentContext()) { 11772 // Finalize the clauses that need pre-built expressions for CodeGen. 11773 for (OMPClause *C : Clauses) { 11774 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11775 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11776 B.NumIterations, *this, CurScope, 11777 DSAStack)) 11778 return StmtError(); 11779 } 11780 } 11781 11782 setFunctionHasBranchProtectedScope(); 11783 return OMPTargetTeamsDistributeParallelForDirective::Create( 11784 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11785 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11786 } 11787 11788 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 11789 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11790 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11791 if (!AStmt) 11792 return StmtError(); 11793 11794 auto *CS = cast<CapturedStmt>(AStmt); 11795 // 1.2.2 OpenMP Language Terminology 11796 // Structured block - An executable statement with a single entry at the 11797 // top and a single exit at the bottom. 11798 // The point of exit cannot be a branch out of the structured block. 11799 // longjmp() and throw() must not violate the entry/exit criteria. 11800 CS->getCapturedDecl()->setNothrow(); 11801 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 11802 OMPD_target_teams_distribute_parallel_for_simd); 11803 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11804 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11805 // 1.2.2 OpenMP Language Terminology 11806 // Structured block - An executable statement with a single entry at the 11807 // top and a single exit at the bottom. 11808 // The point of exit cannot be a branch out of the structured block. 11809 // longjmp() and throw() must not violate the entry/exit criteria. 11810 CS->getCapturedDecl()->setNothrow(); 11811 } 11812 11813 OMPLoopBasedDirective::HelperExprs B; 11814 // In presence of clause 'collapse' with number of loops, it will 11815 // define the nested loops number. 11816 unsigned NestedLoopCount = 11817 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 11818 getCollapseNumberExpr(Clauses), 11819 nullptr /*ordered not a clause on distribute*/, CS, *this, 11820 *DSAStack, VarsWithImplicitDSA, B); 11821 if (NestedLoopCount == 0) 11822 return StmtError(); 11823 11824 assert((CurContext->isDependentContext() || B.builtAll()) && 11825 "omp target teams distribute parallel for simd loop exprs were not " 11826 "built"); 11827 11828 if (!CurContext->isDependentContext()) { 11829 // Finalize the clauses that need pre-built expressions for CodeGen. 11830 for (OMPClause *C : Clauses) { 11831 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11832 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11833 B.NumIterations, *this, CurScope, 11834 DSAStack)) 11835 return StmtError(); 11836 } 11837 } 11838 11839 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11840 return StmtError(); 11841 11842 setFunctionHasBranchProtectedScope(); 11843 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 11844 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11845 } 11846 11847 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 11848 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11849 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11850 if (!AStmt) 11851 return StmtError(); 11852 11853 auto *CS = cast<CapturedStmt>(AStmt); 11854 // 1.2.2 OpenMP Language Terminology 11855 // Structured block - An executable statement with a single entry at the 11856 // top and a single exit at the bottom. 11857 // The point of exit cannot be a branch out of the structured block. 11858 // longjmp() and throw() must not violate the entry/exit criteria. 11859 CS->getCapturedDecl()->setNothrow(); 11860 for (int ThisCaptureLevel = 11861 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 11862 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11863 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11864 // 1.2.2 OpenMP Language Terminology 11865 // Structured block - An executable statement with a single entry at the 11866 // top and a single exit at the bottom. 11867 // The point of exit cannot be a branch out of the structured block. 11868 // longjmp() and throw() must not violate the entry/exit criteria. 11869 CS->getCapturedDecl()->setNothrow(); 11870 } 11871 11872 OMPLoopBasedDirective::HelperExprs B; 11873 // In presence of clause 'collapse' with number of loops, it will 11874 // define the nested loops number. 11875 unsigned NestedLoopCount = checkOpenMPLoop( 11876 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 11877 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11878 VarsWithImplicitDSA, B); 11879 if (NestedLoopCount == 0) 11880 return StmtError(); 11881 11882 assert((CurContext->isDependentContext() || B.builtAll()) && 11883 "omp target teams distribute simd loop exprs were not built"); 11884 11885 if (!CurContext->isDependentContext()) { 11886 // Finalize the clauses that need pre-built expressions for CodeGen. 11887 for (OMPClause *C : Clauses) { 11888 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11889 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11890 B.NumIterations, *this, CurScope, 11891 DSAStack)) 11892 return StmtError(); 11893 } 11894 } 11895 11896 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11897 return StmtError(); 11898 11899 setFunctionHasBranchProtectedScope(); 11900 return OMPTargetTeamsDistributeSimdDirective::Create( 11901 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11902 } 11903 11904 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, 11905 Stmt *AStmt, SourceLocation StartLoc, 11906 SourceLocation EndLoc) { 11907 auto SizesClauses = 11908 OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses); 11909 if (SizesClauses.empty()) { 11910 // A missing 'sizes' clause is already reported by the parser. 11911 return StmtError(); 11912 } 11913 const OMPSizesClause *SizesClause = *SizesClauses.begin(); 11914 unsigned NumLoops = SizesClause->getNumSizes(); 11915 11916 // Empty statement should only be possible if there already was an error. 11917 if (!AStmt) 11918 return StmtError(); 11919 11920 // Verify and diagnose loop nest. 11921 SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops); 11922 Stmt *Body = nullptr; 11923 SmallVector<Stmt *, 4> OriginalInits; 11924 if (!OMPLoopBasedDirective::doForAllLoops( 11925 AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, 11926 NumLoops, 11927 [this, &LoopHelpers, &Body, &OriginalInits](unsigned Cnt, 11928 Stmt *CurStmt) { 11929 VarsWithInheritedDSAType TmpDSA; 11930 unsigned SingleNumLoops = 11931 checkOpenMPLoop(OMPD_tile, nullptr, nullptr, CurStmt, *this, 11932 *DSAStack, TmpDSA, LoopHelpers[Cnt]); 11933 if (SingleNumLoops == 0) 11934 return true; 11935 assert(SingleNumLoops == 1 && "Expect single loop iteration space"); 11936 if (auto *For = dyn_cast<ForStmt>(CurStmt)) { 11937 OriginalInits.push_back(For->getInit()); 11938 Body = For->getBody(); 11939 } else { 11940 assert(isa<CXXForRangeStmt>(CurStmt) && 11941 "Expected canonical for or range-based for loops."); 11942 auto *CXXFor = cast<CXXForRangeStmt>(CurStmt); 11943 OriginalInits.push_back(CXXFor->getBeginStmt()); 11944 Body = CXXFor->getBody(); 11945 } 11946 return false; 11947 })) 11948 return StmtError(); 11949 11950 // Delay tiling to when template is completely instantiated. 11951 if (CurContext->isDependentContext()) 11952 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, 11953 NumLoops, AStmt, nullptr, nullptr); 11954 11955 // Collection of generated variable declaration. 11956 SmallVector<Decl *, 4> PreInits; 11957 11958 // Create iteration variables for the generated loops. 11959 SmallVector<VarDecl *, 4> FloorIndVars; 11960 SmallVector<VarDecl *, 4> TileIndVars; 11961 FloorIndVars.resize(NumLoops); 11962 TileIndVars.resize(NumLoops); 11963 for (unsigned I = 0; I < NumLoops; ++I) { 11964 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 11965 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 11966 PreInits.append(PI->decl_begin(), PI->decl_end()); 11967 assert(LoopHelper.Counters.size() == 1 && 11968 "Expect single-dimensional loop iteration space"); 11969 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 11970 std::string OrigVarName = OrigCntVar->getNameInfo().getAsString(); 11971 DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 11972 QualType CntTy = IterVarRef->getType(); 11973 11974 // Iteration variable for the floor (i.e. outer) loop. 11975 { 11976 std::string FloorCntName = 11977 (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 11978 VarDecl *FloorCntDecl = 11979 buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar); 11980 FloorIndVars[I] = FloorCntDecl; 11981 } 11982 11983 // Iteration variable for the tile (i.e. inner) loop. 11984 { 11985 std::string TileCntName = 11986 (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 11987 11988 // Reuse the iteration variable created by checkOpenMPLoop. It is also 11989 // used by the expressions to derive the original iteration variable's 11990 // value from the logical iteration number. 11991 auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl()); 11992 TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName)); 11993 TileIndVars[I] = TileCntDecl; 11994 } 11995 if (auto *PI = dyn_cast_or_null<DeclStmt>(OriginalInits[I])) 11996 PreInits.append(PI->decl_begin(), PI->decl_end()); 11997 // Gather declarations for the data members used as counters. 11998 for (Expr *CounterRef : LoopHelper.Counters) { 11999 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 12000 if (isa<OMPCapturedExprDecl>(CounterDecl)) 12001 PreInits.push_back(CounterDecl); 12002 } 12003 } 12004 12005 // Once the original iteration values are set, append the innermost body. 12006 Stmt *Inner = Body; 12007 12008 // Create tile loops from the inside to the outside. 12009 for (int I = NumLoops - 1; I >= 0; --I) { 12010 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 12011 Expr *NumIterations = LoopHelper.NumIterations; 12012 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 12013 QualType CntTy = OrigCntVar->getType(); 12014 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 12015 Scope *CurScope = getCurScope(); 12016 12017 // Commonly used variables. 12018 DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy, 12019 OrigCntVar->getExprLoc()); 12020 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 12021 OrigCntVar->getExprLoc()); 12022 12023 // For init-statement: auto .tile.iv = .floor.iv 12024 AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(), 12025 /*DirectInit=*/false); 12026 Decl *CounterDecl = TileIndVars[I]; 12027 StmtResult InitStmt = new (Context) 12028 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 12029 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 12030 if (!InitStmt.isUsable()) 12031 return StmtError(); 12032 12033 // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize, 12034 // NumIterations) 12035 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 12036 BO_Add, FloorIV, DimTileSize); 12037 if (!EndOfTile.isUsable()) 12038 return StmtError(); 12039 ExprResult IsPartialTile = 12040 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, 12041 NumIterations, EndOfTile.get()); 12042 if (!IsPartialTile.isUsable()) 12043 return StmtError(); 12044 ExprResult MinTileAndIterSpace = ActOnConditionalOp( 12045 LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(), 12046 IsPartialTile.get(), NumIterations, EndOfTile.get()); 12047 if (!MinTileAndIterSpace.isUsable()) 12048 return StmtError(); 12049 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 12050 BO_LT, TileIV, MinTileAndIterSpace.get()); 12051 if (!CondExpr.isUsable()) 12052 return StmtError(); 12053 12054 // For incr-statement: ++.tile.iv 12055 ExprResult IncrStmt = 12056 BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV); 12057 if (!IncrStmt.isUsable()) 12058 return StmtError(); 12059 12060 // Statements to set the original iteration variable's value from the 12061 // logical iteration number. 12062 // Generated for loop is: 12063 // Original_for_init; 12064 // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize, 12065 // NumIterations); ++.tile.iv) { 12066 // Original_Body; 12067 // Original_counter_update; 12068 // } 12069 // FIXME: If the innermost body is an loop itself, inserting these 12070 // statements stops it being recognized as a perfectly nested loop (e.g. 12071 // for applying tiling again). If this is the case, sink the expressions 12072 // further into the inner loop. 12073 SmallVector<Stmt *, 4> BodyParts; 12074 BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 12075 BodyParts.push_back(Inner); 12076 Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(), 12077 Inner->getEndLoc()); 12078 Inner = new (Context) 12079 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 12080 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 12081 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 12082 } 12083 12084 // Create floor loops from the inside to the outside. 12085 for (int I = NumLoops - 1; I >= 0; --I) { 12086 auto &LoopHelper = LoopHelpers[I]; 12087 Expr *NumIterations = LoopHelper.NumIterations; 12088 DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 12089 QualType CntTy = OrigCntVar->getType(); 12090 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 12091 Scope *CurScope = getCurScope(); 12092 12093 // Commonly used variables. 12094 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 12095 OrigCntVar->getExprLoc()); 12096 12097 // For init-statement: auto .floor.iv = 0 12098 AddInitializerToDecl( 12099 FloorIndVars[I], 12100 ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 12101 /*DirectInit=*/false); 12102 Decl *CounterDecl = FloorIndVars[I]; 12103 StmtResult InitStmt = new (Context) 12104 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 12105 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 12106 if (!InitStmt.isUsable()) 12107 return StmtError(); 12108 12109 // For cond-expression: .floor.iv < NumIterations 12110 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 12111 BO_LT, FloorIV, NumIterations); 12112 if (!CondExpr.isUsable()) 12113 return StmtError(); 12114 12115 // For incr-statement: .floor.iv += DimTileSize 12116 ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), 12117 BO_AddAssign, FloorIV, DimTileSize); 12118 if (!IncrStmt.isUsable()) 12119 return StmtError(); 12120 12121 Inner = new (Context) 12122 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 12123 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 12124 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 12125 } 12126 12127 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops, 12128 AStmt, Inner, 12129 buildPreInits(Context, PreInits)); 12130 } 12131 12132 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 12133 SourceLocation StartLoc, 12134 SourceLocation LParenLoc, 12135 SourceLocation EndLoc) { 12136 OMPClause *Res = nullptr; 12137 switch (Kind) { 12138 case OMPC_final: 12139 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 12140 break; 12141 case OMPC_num_threads: 12142 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 12143 break; 12144 case OMPC_safelen: 12145 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 12146 break; 12147 case OMPC_simdlen: 12148 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 12149 break; 12150 case OMPC_allocator: 12151 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc); 12152 break; 12153 case OMPC_collapse: 12154 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 12155 break; 12156 case OMPC_ordered: 12157 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 12158 break; 12159 case OMPC_num_teams: 12160 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 12161 break; 12162 case OMPC_thread_limit: 12163 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 12164 break; 12165 case OMPC_priority: 12166 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 12167 break; 12168 case OMPC_grainsize: 12169 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 12170 break; 12171 case OMPC_num_tasks: 12172 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 12173 break; 12174 case OMPC_hint: 12175 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 12176 break; 12177 case OMPC_depobj: 12178 Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc); 12179 break; 12180 case OMPC_detach: 12181 Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc); 12182 break; 12183 case OMPC_device: 12184 case OMPC_if: 12185 case OMPC_default: 12186 case OMPC_proc_bind: 12187 case OMPC_schedule: 12188 case OMPC_private: 12189 case OMPC_firstprivate: 12190 case OMPC_lastprivate: 12191 case OMPC_shared: 12192 case OMPC_reduction: 12193 case OMPC_task_reduction: 12194 case OMPC_in_reduction: 12195 case OMPC_linear: 12196 case OMPC_aligned: 12197 case OMPC_copyin: 12198 case OMPC_copyprivate: 12199 case OMPC_nowait: 12200 case OMPC_untied: 12201 case OMPC_mergeable: 12202 case OMPC_threadprivate: 12203 case OMPC_sizes: 12204 case OMPC_allocate: 12205 case OMPC_flush: 12206 case OMPC_read: 12207 case OMPC_write: 12208 case OMPC_update: 12209 case OMPC_capture: 12210 case OMPC_seq_cst: 12211 case OMPC_acq_rel: 12212 case OMPC_acquire: 12213 case OMPC_release: 12214 case OMPC_relaxed: 12215 case OMPC_depend: 12216 case OMPC_threads: 12217 case OMPC_simd: 12218 case OMPC_map: 12219 case OMPC_nogroup: 12220 case OMPC_dist_schedule: 12221 case OMPC_defaultmap: 12222 case OMPC_unknown: 12223 case OMPC_uniform: 12224 case OMPC_to: 12225 case OMPC_from: 12226 case OMPC_use_device_ptr: 12227 case OMPC_use_device_addr: 12228 case OMPC_is_device_ptr: 12229 case OMPC_unified_address: 12230 case OMPC_unified_shared_memory: 12231 case OMPC_reverse_offload: 12232 case OMPC_dynamic_allocators: 12233 case OMPC_atomic_default_mem_order: 12234 case OMPC_device_type: 12235 case OMPC_match: 12236 case OMPC_nontemporal: 12237 case OMPC_order: 12238 case OMPC_destroy: 12239 case OMPC_inclusive: 12240 case OMPC_exclusive: 12241 case OMPC_uses_allocators: 12242 case OMPC_affinity: 12243 default: 12244 llvm_unreachable("Clause is not allowed."); 12245 } 12246 return Res; 12247 } 12248 12249 // An OpenMP directive such as 'target parallel' has two captured regions: 12250 // for the 'target' and 'parallel' respectively. This function returns 12251 // the region in which to capture expressions associated with a clause. 12252 // A return value of OMPD_unknown signifies that the expression should not 12253 // be captured. 12254 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 12255 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion, 12256 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 12257 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 12258 switch (CKind) { 12259 case OMPC_if: 12260 switch (DKind) { 12261 case OMPD_target_parallel_for_simd: 12262 if (OpenMPVersion >= 50 && 12263 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 12264 CaptureRegion = OMPD_parallel; 12265 break; 12266 } 12267 LLVM_FALLTHROUGH; 12268 case OMPD_target_parallel: 12269 case OMPD_target_parallel_for: 12270 // If this clause applies to the nested 'parallel' region, capture within 12271 // the 'target' region, otherwise do not capture. 12272 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 12273 CaptureRegion = OMPD_target; 12274 break; 12275 case OMPD_target_teams_distribute_parallel_for_simd: 12276 if (OpenMPVersion >= 50 && 12277 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 12278 CaptureRegion = OMPD_parallel; 12279 break; 12280 } 12281 LLVM_FALLTHROUGH; 12282 case OMPD_target_teams_distribute_parallel_for: 12283 // If this clause applies to the nested 'parallel' region, capture within 12284 // the 'teams' region, otherwise do not capture. 12285 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 12286 CaptureRegion = OMPD_teams; 12287 break; 12288 case OMPD_teams_distribute_parallel_for_simd: 12289 if (OpenMPVersion >= 50 && 12290 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 12291 CaptureRegion = OMPD_parallel; 12292 break; 12293 } 12294 LLVM_FALLTHROUGH; 12295 case OMPD_teams_distribute_parallel_for: 12296 CaptureRegion = OMPD_teams; 12297 break; 12298 case OMPD_target_update: 12299 case OMPD_target_enter_data: 12300 case OMPD_target_exit_data: 12301 CaptureRegion = OMPD_task; 12302 break; 12303 case OMPD_parallel_master_taskloop: 12304 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop) 12305 CaptureRegion = OMPD_parallel; 12306 break; 12307 case OMPD_parallel_master_taskloop_simd: 12308 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) || 12309 NameModifier == OMPD_taskloop) { 12310 CaptureRegion = OMPD_parallel; 12311 break; 12312 } 12313 if (OpenMPVersion <= 45) 12314 break; 12315 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 12316 CaptureRegion = OMPD_taskloop; 12317 break; 12318 case OMPD_parallel_for_simd: 12319 if (OpenMPVersion <= 45) 12320 break; 12321 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 12322 CaptureRegion = OMPD_parallel; 12323 break; 12324 case OMPD_taskloop_simd: 12325 case OMPD_master_taskloop_simd: 12326 if (OpenMPVersion <= 45) 12327 break; 12328 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 12329 CaptureRegion = OMPD_taskloop; 12330 break; 12331 case OMPD_distribute_parallel_for_simd: 12332 if (OpenMPVersion <= 45) 12333 break; 12334 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 12335 CaptureRegion = OMPD_parallel; 12336 break; 12337 case OMPD_target_simd: 12338 if (OpenMPVersion >= 50 && 12339 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 12340 CaptureRegion = OMPD_target; 12341 break; 12342 case OMPD_teams_distribute_simd: 12343 case OMPD_target_teams_distribute_simd: 12344 if (OpenMPVersion >= 50 && 12345 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 12346 CaptureRegion = OMPD_teams; 12347 break; 12348 case OMPD_cancel: 12349 case OMPD_parallel: 12350 case OMPD_parallel_master: 12351 case OMPD_parallel_sections: 12352 case OMPD_parallel_for: 12353 case OMPD_target: 12354 case OMPD_target_teams: 12355 case OMPD_target_teams_distribute: 12356 case OMPD_distribute_parallel_for: 12357 case OMPD_task: 12358 case OMPD_taskloop: 12359 case OMPD_master_taskloop: 12360 case OMPD_target_data: 12361 case OMPD_simd: 12362 case OMPD_for_simd: 12363 case OMPD_distribute_simd: 12364 // Do not capture if-clause expressions. 12365 break; 12366 case OMPD_threadprivate: 12367 case OMPD_allocate: 12368 case OMPD_taskyield: 12369 case OMPD_barrier: 12370 case OMPD_taskwait: 12371 case OMPD_cancellation_point: 12372 case OMPD_flush: 12373 case OMPD_depobj: 12374 case OMPD_scan: 12375 case OMPD_declare_reduction: 12376 case OMPD_declare_mapper: 12377 case OMPD_declare_simd: 12378 case OMPD_declare_variant: 12379 case OMPD_begin_declare_variant: 12380 case OMPD_end_declare_variant: 12381 case OMPD_declare_target: 12382 case OMPD_end_declare_target: 12383 case OMPD_teams: 12384 case OMPD_tile: 12385 case OMPD_for: 12386 case OMPD_sections: 12387 case OMPD_section: 12388 case OMPD_single: 12389 case OMPD_master: 12390 case OMPD_critical: 12391 case OMPD_taskgroup: 12392 case OMPD_distribute: 12393 case OMPD_ordered: 12394 case OMPD_atomic: 12395 case OMPD_teams_distribute: 12396 case OMPD_requires: 12397 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 12398 case OMPD_unknown: 12399 default: 12400 llvm_unreachable("Unknown OpenMP directive"); 12401 } 12402 break; 12403 case OMPC_num_threads: 12404 switch (DKind) { 12405 case OMPD_target_parallel: 12406 case OMPD_target_parallel_for: 12407 case OMPD_target_parallel_for_simd: 12408 CaptureRegion = OMPD_target; 12409 break; 12410 case OMPD_teams_distribute_parallel_for: 12411 case OMPD_teams_distribute_parallel_for_simd: 12412 case OMPD_target_teams_distribute_parallel_for: 12413 case OMPD_target_teams_distribute_parallel_for_simd: 12414 CaptureRegion = OMPD_teams; 12415 break; 12416 case OMPD_parallel: 12417 case OMPD_parallel_master: 12418 case OMPD_parallel_sections: 12419 case OMPD_parallel_for: 12420 case OMPD_parallel_for_simd: 12421 case OMPD_distribute_parallel_for: 12422 case OMPD_distribute_parallel_for_simd: 12423 case OMPD_parallel_master_taskloop: 12424 case OMPD_parallel_master_taskloop_simd: 12425 // Do not capture num_threads-clause expressions. 12426 break; 12427 case OMPD_target_data: 12428 case OMPD_target_enter_data: 12429 case OMPD_target_exit_data: 12430 case OMPD_target_update: 12431 case OMPD_target: 12432 case OMPD_target_simd: 12433 case OMPD_target_teams: 12434 case OMPD_target_teams_distribute: 12435 case OMPD_target_teams_distribute_simd: 12436 case OMPD_cancel: 12437 case OMPD_task: 12438 case OMPD_taskloop: 12439 case OMPD_taskloop_simd: 12440 case OMPD_master_taskloop: 12441 case OMPD_master_taskloop_simd: 12442 case OMPD_threadprivate: 12443 case OMPD_allocate: 12444 case OMPD_taskyield: 12445 case OMPD_barrier: 12446 case OMPD_taskwait: 12447 case OMPD_cancellation_point: 12448 case OMPD_flush: 12449 case OMPD_depobj: 12450 case OMPD_scan: 12451 case OMPD_declare_reduction: 12452 case OMPD_declare_mapper: 12453 case OMPD_declare_simd: 12454 case OMPD_declare_variant: 12455 case OMPD_begin_declare_variant: 12456 case OMPD_end_declare_variant: 12457 case OMPD_declare_target: 12458 case OMPD_end_declare_target: 12459 case OMPD_teams: 12460 case OMPD_simd: 12461 case OMPD_tile: 12462 case OMPD_for: 12463 case OMPD_for_simd: 12464 case OMPD_sections: 12465 case OMPD_section: 12466 case OMPD_single: 12467 case OMPD_master: 12468 case OMPD_critical: 12469 case OMPD_taskgroup: 12470 case OMPD_distribute: 12471 case OMPD_ordered: 12472 case OMPD_atomic: 12473 case OMPD_distribute_simd: 12474 case OMPD_teams_distribute: 12475 case OMPD_teams_distribute_simd: 12476 case OMPD_requires: 12477 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 12478 case OMPD_unknown: 12479 default: 12480 llvm_unreachable("Unknown OpenMP directive"); 12481 } 12482 break; 12483 case OMPC_num_teams: 12484 switch (DKind) { 12485 case OMPD_target_teams: 12486 case OMPD_target_teams_distribute: 12487 case OMPD_target_teams_distribute_simd: 12488 case OMPD_target_teams_distribute_parallel_for: 12489 case OMPD_target_teams_distribute_parallel_for_simd: 12490 CaptureRegion = OMPD_target; 12491 break; 12492 case OMPD_teams_distribute_parallel_for: 12493 case OMPD_teams_distribute_parallel_for_simd: 12494 case OMPD_teams: 12495 case OMPD_teams_distribute: 12496 case OMPD_teams_distribute_simd: 12497 // Do not capture num_teams-clause expressions. 12498 break; 12499 case OMPD_distribute_parallel_for: 12500 case OMPD_distribute_parallel_for_simd: 12501 case OMPD_task: 12502 case OMPD_taskloop: 12503 case OMPD_taskloop_simd: 12504 case OMPD_master_taskloop: 12505 case OMPD_master_taskloop_simd: 12506 case OMPD_parallel_master_taskloop: 12507 case OMPD_parallel_master_taskloop_simd: 12508 case OMPD_target_data: 12509 case OMPD_target_enter_data: 12510 case OMPD_target_exit_data: 12511 case OMPD_target_update: 12512 case OMPD_cancel: 12513 case OMPD_parallel: 12514 case OMPD_parallel_master: 12515 case OMPD_parallel_sections: 12516 case OMPD_parallel_for: 12517 case OMPD_parallel_for_simd: 12518 case OMPD_target: 12519 case OMPD_target_simd: 12520 case OMPD_target_parallel: 12521 case OMPD_target_parallel_for: 12522 case OMPD_target_parallel_for_simd: 12523 case OMPD_threadprivate: 12524 case OMPD_allocate: 12525 case OMPD_taskyield: 12526 case OMPD_barrier: 12527 case OMPD_taskwait: 12528 case OMPD_cancellation_point: 12529 case OMPD_flush: 12530 case OMPD_depobj: 12531 case OMPD_scan: 12532 case OMPD_declare_reduction: 12533 case OMPD_declare_mapper: 12534 case OMPD_declare_simd: 12535 case OMPD_declare_variant: 12536 case OMPD_begin_declare_variant: 12537 case OMPD_end_declare_variant: 12538 case OMPD_declare_target: 12539 case OMPD_end_declare_target: 12540 case OMPD_simd: 12541 case OMPD_tile: 12542 case OMPD_for: 12543 case OMPD_for_simd: 12544 case OMPD_sections: 12545 case OMPD_section: 12546 case OMPD_single: 12547 case OMPD_master: 12548 case OMPD_critical: 12549 case OMPD_taskgroup: 12550 case OMPD_distribute: 12551 case OMPD_ordered: 12552 case OMPD_atomic: 12553 case OMPD_distribute_simd: 12554 case OMPD_requires: 12555 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 12556 case OMPD_unknown: 12557 default: 12558 llvm_unreachable("Unknown OpenMP directive"); 12559 } 12560 break; 12561 case OMPC_thread_limit: 12562 switch (DKind) { 12563 case OMPD_target_teams: 12564 case OMPD_target_teams_distribute: 12565 case OMPD_target_teams_distribute_simd: 12566 case OMPD_target_teams_distribute_parallel_for: 12567 case OMPD_target_teams_distribute_parallel_for_simd: 12568 CaptureRegion = OMPD_target; 12569 break; 12570 case OMPD_teams_distribute_parallel_for: 12571 case OMPD_teams_distribute_parallel_for_simd: 12572 case OMPD_teams: 12573 case OMPD_teams_distribute: 12574 case OMPD_teams_distribute_simd: 12575 // Do not capture thread_limit-clause expressions. 12576 break; 12577 case OMPD_distribute_parallel_for: 12578 case OMPD_distribute_parallel_for_simd: 12579 case OMPD_task: 12580 case OMPD_taskloop: 12581 case OMPD_taskloop_simd: 12582 case OMPD_master_taskloop: 12583 case OMPD_master_taskloop_simd: 12584 case OMPD_parallel_master_taskloop: 12585 case OMPD_parallel_master_taskloop_simd: 12586 case OMPD_target_data: 12587 case OMPD_target_enter_data: 12588 case OMPD_target_exit_data: 12589 case OMPD_target_update: 12590 case OMPD_cancel: 12591 case OMPD_parallel: 12592 case OMPD_parallel_master: 12593 case OMPD_parallel_sections: 12594 case OMPD_parallel_for: 12595 case OMPD_parallel_for_simd: 12596 case OMPD_target: 12597 case OMPD_target_simd: 12598 case OMPD_target_parallel: 12599 case OMPD_target_parallel_for: 12600 case OMPD_target_parallel_for_simd: 12601 case OMPD_threadprivate: 12602 case OMPD_allocate: 12603 case OMPD_taskyield: 12604 case OMPD_barrier: 12605 case OMPD_taskwait: 12606 case OMPD_cancellation_point: 12607 case OMPD_flush: 12608 case OMPD_depobj: 12609 case OMPD_scan: 12610 case OMPD_declare_reduction: 12611 case OMPD_declare_mapper: 12612 case OMPD_declare_simd: 12613 case OMPD_declare_variant: 12614 case OMPD_begin_declare_variant: 12615 case OMPD_end_declare_variant: 12616 case OMPD_declare_target: 12617 case OMPD_end_declare_target: 12618 case OMPD_simd: 12619 case OMPD_tile: 12620 case OMPD_for: 12621 case OMPD_for_simd: 12622 case OMPD_sections: 12623 case OMPD_section: 12624 case OMPD_single: 12625 case OMPD_master: 12626 case OMPD_critical: 12627 case OMPD_taskgroup: 12628 case OMPD_distribute: 12629 case OMPD_ordered: 12630 case OMPD_atomic: 12631 case OMPD_distribute_simd: 12632 case OMPD_requires: 12633 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 12634 case OMPD_unknown: 12635 default: 12636 llvm_unreachable("Unknown OpenMP directive"); 12637 } 12638 break; 12639 case OMPC_schedule: 12640 switch (DKind) { 12641 case OMPD_parallel_for: 12642 case OMPD_parallel_for_simd: 12643 case OMPD_distribute_parallel_for: 12644 case OMPD_distribute_parallel_for_simd: 12645 case OMPD_teams_distribute_parallel_for: 12646 case OMPD_teams_distribute_parallel_for_simd: 12647 case OMPD_target_parallel_for: 12648 case OMPD_target_parallel_for_simd: 12649 case OMPD_target_teams_distribute_parallel_for: 12650 case OMPD_target_teams_distribute_parallel_for_simd: 12651 CaptureRegion = OMPD_parallel; 12652 break; 12653 case OMPD_for: 12654 case OMPD_for_simd: 12655 // Do not capture schedule-clause expressions. 12656 break; 12657 case OMPD_task: 12658 case OMPD_taskloop: 12659 case OMPD_taskloop_simd: 12660 case OMPD_master_taskloop: 12661 case OMPD_master_taskloop_simd: 12662 case OMPD_parallel_master_taskloop: 12663 case OMPD_parallel_master_taskloop_simd: 12664 case OMPD_target_data: 12665 case OMPD_target_enter_data: 12666 case OMPD_target_exit_data: 12667 case OMPD_target_update: 12668 case OMPD_teams: 12669 case OMPD_teams_distribute: 12670 case OMPD_teams_distribute_simd: 12671 case OMPD_target_teams_distribute: 12672 case OMPD_target_teams_distribute_simd: 12673 case OMPD_target: 12674 case OMPD_target_simd: 12675 case OMPD_target_parallel: 12676 case OMPD_cancel: 12677 case OMPD_parallel: 12678 case OMPD_parallel_master: 12679 case OMPD_parallel_sections: 12680 case OMPD_threadprivate: 12681 case OMPD_allocate: 12682 case OMPD_taskyield: 12683 case OMPD_barrier: 12684 case OMPD_taskwait: 12685 case OMPD_cancellation_point: 12686 case OMPD_flush: 12687 case OMPD_depobj: 12688 case OMPD_scan: 12689 case OMPD_declare_reduction: 12690 case OMPD_declare_mapper: 12691 case OMPD_declare_simd: 12692 case OMPD_declare_variant: 12693 case OMPD_begin_declare_variant: 12694 case OMPD_end_declare_variant: 12695 case OMPD_declare_target: 12696 case OMPD_end_declare_target: 12697 case OMPD_simd: 12698 case OMPD_tile: 12699 case OMPD_sections: 12700 case OMPD_section: 12701 case OMPD_single: 12702 case OMPD_master: 12703 case OMPD_critical: 12704 case OMPD_taskgroup: 12705 case OMPD_distribute: 12706 case OMPD_ordered: 12707 case OMPD_atomic: 12708 case OMPD_distribute_simd: 12709 case OMPD_target_teams: 12710 case OMPD_requires: 12711 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 12712 case OMPD_unknown: 12713 default: 12714 llvm_unreachable("Unknown OpenMP directive"); 12715 } 12716 break; 12717 case OMPC_dist_schedule: 12718 switch (DKind) { 12719 case OMPD_teams_distribute_parallel_for: 12720 case OMPD_teams_distribute_parallel_for_simd: 12721 case OMPD_teams_distribute: 12722 case OMPD_teams_distribute_simd: 12723 case OMPD_target_teams_distribute_parallel_for: 12724 case OMPD_target_teams_distribute_parallel_for_simd: 12725 case OMPD_target_teams_distribute: 12726 case OMPD_target_teams_distribute_simd: 12727 CaptureRegion = OMPD_teams; 12728 break; 12729 case OMPD_distribute_parallel_for: 12730 case OMPD_distribute_parallel_for_simd: 12731 case OMPD_distribute: 12732 case OMPD_distribute_simd: 12733 // Do not capture dist_schedule-clause expressions. 12734 break; 12735 case OMPD_parallel_for: 12736 case OMPD_parallel_for_simd: 12737 case OMPD_target_parallel_for_simd: 12738 case OMPD_target_parallel_for: 12739 case OMPD_task: 12740 case OMPD_taskloop: 12741 case OMPD_taskloop_simd: 12742 case OMPD_master_taskloop: 12743 case OMPD_master_taskloop_simd: 12744 case OMPD_parallel_master_taskloop: 12745 case OMPD_parallel_master_taskloop_simd: 12746 case OMPD_target_data: 12747 case OMPD_target_enter_data: 12748 case OMPD_target_exit_data: 12749 case OMPD_target_update: 12750 case OMPD_teams: 12751 case OMPD_target: 12752 case OMPD_target_simd: 12753 case OMPD_target_parallel: 12754 case OMPD_cancel: 12755 case OMPD_parallel: 12756 case OMPD_parallel_master: 12757 case OMPD_parallel_sections: 12758 case OMPD_threadprivate: 12759 case OMPD_allocate: 12760 case OMPD_taskyield: 12761 case OMPD_barrier: 12762 case OMPD_taskwait: 12763 case OMPD_cancellation_point: 12764 case OMPD_flush: 12765 case OMPD_depobj: 12766 case OMPD_scan: 12767 case OMPD_declare_reduction: 12768 case OMPD_declare_mapper: 12769 case OMPD_declare_simd: 12770 case OMPD_declare_variant: 12771 case OMPD_begin_declare_variant: 12772 case OMPD_end_declare_variant: 12773 case OMPD_declare_target: 12774 case OMPD_end_declare_target: 12775 case OMPD_simd: 12776 case OMPD_tile: 12777 case OMPD_for: 12778 case OMPD_for_simd: 12779 case OMPD_sections: 12780 case OMPD_section: 12781 case OMPD_single: 12782 case OMPD_master: 12783 case OMPD_critical: 12784 case OMPD_taskgroup: 12785 case OMPD_ordered: 12786 case OMPD_atomic: 12787 case OMPD_target_teams: 12788 case OMPD_requires: 12789 llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause"); 12790 case OMPD_unknown: 12791 default: 12792 llvm_unreachable("Unknown OpenMP directive"); 12793 } 12794 break; 12795 case OMPC_device: 12796 switch (DKind) { 12797 case OMPD_target_update: 12798 case OMPD_target_enter_data: 12799 case OMPD_target_exit_data: 12800 case OMPD_target: 12801 case OMPD_target_simd: 12802 case OMPD_target_teams: 12803 case OMPD_target_parallel: 12804 case OMPD_target_teams_distribute: 12805 case OMPD_target_teams_distribute_simd: 12806 case OMPD_target_parallel_for: 12807 case OMPD_target_parallel_for_simd: 12808 case OMPD_target_teams_distribute_parallel_for: 12809 case OMPD_target_teams_distribute_parallel_for_simd: 12810 CaptureRegion = OMPD_task; 12811 break; 12812 case OMPD_target_data: 12813 // Do not capture device-clause expressions. 12814 break; 12815 case OMPD_teams_distribute_parallel_for: 12816 case OMPD_teams_distribute_parallel_for_simd: 12817 case OMPD_teams: 12818 case OMPD_teams_distribute: 12819 case OMPD_teams_distribute_simd: 12820 case OMPD_distribute_parallel_for: 12821 case OMPD_distribute_parallel_for_simd: 12822 case OMPD_task: 12823 case OMPD_taskloop: 12824 case OMPD_taskloop_simd: 12825 case OMPD_master_taskloop: 12826 case OMPD_master_taskloop_simd: 12827 case OMPD_parallel_master_taskloop: 12828 case OMPD_parallel_master_taskloop_simd: 12829 case OMPD_cancel: 12830 case OMPD_parallel: 12831 case OMPD_parallel_master: 12832 case OMPD_parallel_sections: 12833 case OMPD_parallel_for: 12834 case OMPD_parallel_for_simd: 12835 case OMPD_threadprivate: 12836 case OMPD_allocate: 12837 case OMPD_taskyield: 12838 case OMPD_barrier: 12839 case OMPD_taskwait: 12840 case OMPD_cancellation_point: 12841 case OMPD_flush: 12842 case OMPD_depobj: 12843 case OMPD_scan: 12844 case OMPD_declare_reduction: 12845 case OMPD_declare_mapper: 12846 case OMPD_declare_simd: 12847 case OMPD_declare_variant: 12848 case OMPD_begin_declare_variant: 12849 case OMPD_end_declare_variant: 12850 case OMPD_declare_target: 12851 case OMPD_end_declare_target: 12852 case OMPD_simd: 12853 case OMPD_tile: 12854 case OMPD_for: 12855 case OMPD_for_simd: 12856 case OMPD_sections: 12857 case OMPD_section: 12858 case OMPD_single: 12859 case OMPD_master: 12860 case OMPD_critical: 12861 case OMPD_taskgroup: 12862 case OMPD_distribute: 12863 case OMPD_ordered: 12864 case OMPD_atomic: 12865 case OMPD_distribute_simd: 12866 case OMPD_requires: 12867 llvm_unreachable("Unexpected OpenMP directive with device-clause"); 12868 case OMPD_unknown: 12869 default: 12870 llvm_unreachable("Unknown OpenMP directive"); 12871 } 12872 break; 12873 case OMPC_grainsize: 12874 case OMPC_num_tasks: 12875 case OMPC_final: 12876 case OMPC_priority: 12877 switch (DKind) { 12878 case OMPD_task: 12879 case OMPD_taskloop: 12880 case OMPD_taskloop_simd: 12881 case OMPD_master_taskloop: 12882 case OMPD_master_taskloop_simd: 12883 break; 12884 case OMPD_parallel_master_taskloop: 12885 case OMPD_parallel_master_taskloop_simd: 12886 CaptureRegion = OMPD_parallel; 12887 break; 12888 case OMPD_target_update: 12889 case OMPD_target_enter_data: 12890 case OMPD_target_exit_data: 12891 case OMPD_target: 12892 case OMPD_target_simd: 12893 case OMPD_target_teams: 12894 case OMPD_target_parallel: 12895 case OMPD_target_teams_distribute: 12896 case OMPD_target_teams_distribute_simd: 12897 case OMPD_target_parallel_for: 12898 case OMPD_target_parallel_for_simd: 12899 case OMPD_target_teams_distribute_parallel_for: 12900 case OMPD_target_teams_distribute_parallel_for_simd: 12901 case OMPD_target_data: 12902 case OMPD_teams_distribute_parallel_for: 12903 case OMPD_teams_distribute_parallel_for_simd: 12904 case OMPD_teams: 12905 case OMPD_teams_distribute: 12906 case OMPD_teams_distribute_simd: 12907 case OMPD_distribute_parallel_for: 12908 case OMPD_distribute_parallel_for_simd: 12909 case OMPD_cancel: 12910 case OMPD_parallel: 12911 case OMPD_parallel_master: 12912 case OMPD_parallel_sections: 12913 case OMPD_parallel_for: 12914 case OMPD_parallel_for_simd: 12915 case OMPD_threadprivate: 12916 case OMPD_allocate: 12917 case OMPD_taskyield: 12918 case OMPD_barrier: 12919 case OMPD_taskwait: 12920 case OMPD_cancellation_point: 12921 case OMPD_flush: 12922 case OMPD_depobj: 12923 case OMPD_scan: 12924 case OMPD_declare_reduction: 12925 case OMPD_declare_mapper: 12926 case OMPD_declare_simd: 12927 case OMPD_declare_variant: 12928 case OMPD_begin_declare_variant: 12929 case OMPD_end_declare_variant: 12930 case OMPD_declare_target: 12931 case OMPD_end_declare_target: 12932 case OMPD_simd: 12933 case OMPD_tile: 12934 case OMPD_for: 12935 case OMPD_for_simd: 12936 case OMPD_sections: 12937 case OMPD_section: 12938 case OMPD_single: 12939 case OMPD_master: 12940 case OMPD_critical: 12941 case OMPD_taskgroup: 12942 case OMPD_distribute: 12943 case OMPD_ordered: 12944 case OMPD_atomic: 12945 case OMPD_distribute_simd: 12946 case OMPD_requires: 12947 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause"); 12948 case OMPD_unknown: 12949 default: 12950 llvm_unreachable("Unknown OpenMP directive"); 12951 } 12952 break; 12953 case OMPC_firstprivate: 12954 case OMPC_lastprivate: 12955 case OMPC_reduction: 12956 case OMPC_task_reduction: 12957 case OMPC_in_reduction: 12958 case OMPC_linear: 12959 case OMPC_default: 12960 case OMPC_proc_bind: 12961 case OMPC_safelen: 12962 case OMPC_simdlen: 12963 case OMPC_sizes: 12964 case OMPC_allocator: 12965 case OMPC_collapse: 12966 case OMPC_private: 12967 case OMPC_shared: 12968 case OMPC_aligned: 12969 case OMPC_copyin: 12970 case OMPC_copyprivate: 12971 case OMPC_ordered: 12972 case OMPC_nowait: 12973 case OMPC_untied: 12974 case OMPC_mergeable: 12975 case OMPC_threadprivate: 12976 case OMPC_allocate: 12977 case OMPC_flush: 12978 case OMPC_depobj: 12979 case OMPC_read: 12980 case OMPC_write: 12981 case OMPC_update: 12982 case OMPC_capture: 12983 case OMPC_seq_cst: 12984 case OMPC_acq_rel: 12985 case OMPC_acquire: 12986 case OMPC_release: 12987 case OMPC_relaxed: 12988 case OMPC_depend: 12989 case OMPC_threads: 12990 case OMPC_simd: 12991 case OMPC_map: 12992 case OMPC_nogroup: 12993 case OMPC_hint: 12994 case OMPC_defaultmap: 12995 case OMPC_unknown: 12996 case OMPC_uniform: 12997 case OMPC_to: 12998 case OMPC_from: 12999 case OMPC_use_device_ptr: 13000 case OMPC_use_device_addr: 13001 case OMPC_is_device_ptr: 13002 case OMPC_unified_address: 13003 case OMPC_unified_shared_memory: 13004 case OMPC_reverse_offload: 13005 case OMPC_dynamic_allocators: 13006 case OMPC_atomic_default_mem_order: 13007 case OMPC_device_type: 13008 case OMPC_match: 13009 case OMPC_nontemporal: 13010 case OMPC_order: 13011 case OMPC_destroy: 13012 case OMPC_detach: 13013 case OMPC_inclusive: 13014 case OMPC_exclusive: 13015 case OMPC_uses_allocators: 13016 case OMPC_affinity: 13017 default: 13018 llvm_unreachable("Unexpected OpenMP clause."); 13019 } 13020 return CaptureRegion; 13021 } 13022 13023 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 13024 Expr *Condition, SourceLocation StartLoc, 13025 SourceLocation LParenLoc, 13026 SourceLocation NameModifierLoc, 13027 SourceLocation ColonLoc, 13028 SourceLocation EndLoc) { 13029 Expr *ValExpr = Condition; 13030 Stmt *HelperValStmt = nullptr; 13031 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 13032 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 13033 !Condition->isInstantiationDependent() && 13034 !Condition->containsUnexpandedParameterPack()) { 13035 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 13036 if (Val.isInvalid()) 13037 return nullptr; 13038 13039 ValExpr = Val.get(); 13040 13041 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 13042 CaptureRegion = getOpenMPCaptureRegionForClause( 13043 DKind, OMPC_if, LangOpts.OpenMP, NameModifier); 13044 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 13045 ValExpr = MakeFullExpr(ValExpr).get(); 13046 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13047 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13048 HelperValStmt = buildPreInits(Context, Captures); 13049 } 13050 } 13051 13052 return new (Context) 13053 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 13054 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 13055 } 13056 13057 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 13058 SourceLocation StartLoc, 13059 SourceLocation LParenLoc, 13060 SourceLocation EndLoc) { 13061 Expr *ValExpr = Condition; 13062 Stmt *HelperValStmt = nullptr; 13063 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 13064 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 13065 !Condition->isInstantiationDependent() && 13066 !Condition->containsUnexpandedParameterPack()) { 13067 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 13068 if (Val.isInvalid()) 13069 return nullptr; 13070 13071 ValExpr = MakeFullExpr(Val.get()).get(); 13072 13073 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 13074 CaptureRegion = 13075 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP); 13076 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 13077 ValExpr = MakeFullExpr(ValExpr).get(); 13078 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13079 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13080 HelperValStmt = buildPreInits(Context, Captures); 13081 } 13082 } 13083 13084 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion, 13085 StartLoc, LParenLoc, EndLoc); 13086 } 13087 13088 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 13089 Expr *Op) { 13090 if (!Op) 13091 return ExprError(); 13092 13093 class IntConvertDiagnoser : public ICEConvertDiagnoser { 13094 public: 13095 IntConvertDiagnoser() 13096 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 13097 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13098 QualType T) override { 13099 return S.Diag(Loc, diag::err_omp_not_integral) << T; 13100 } 13101 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 13102 QualType T) override { 13103 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 13104 } 13105 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 13106 QualType T, 13107 QualType ConvTy) override { 13108 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 13109 } 13110 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 13111 QualType ConvTy) override { 13112 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 13113 << ConvTy->isEnumeralType() << ConvTy; 13114 } 13115 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 13116 QualType T) override { 13117 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 13118 } 13119 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 13120 QualType ConvTy) override { 13121 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 13122 << ConvTy->isEnumeralType() << ConvTy; 13123 } 13124 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 13125 QualType) override { 13126 llvm_unreachable("conversion functions are permitted"); 13127 } 13128 } ConvertDiagnoser; 13129 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 13130 } 13131 13132 static bool 13133 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind, 13134 bool StrictlyPositive, bool BuildCapture = false, 13135 OpenMPDirectiveKind DKind = OMPD_unknown, 13136 OpenMPDirectiveKind *CaptureRegion = nullptr, 13137 Stmt **HelperValStmt = nullptr) { 13138 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 13139 !ValExpr->isInstantiationDependent()) { 13140 SourceLocation Loc = ValExpr->getExprLoc(); 13141 ExprResult Value = 13142 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 13143 if (Value.isInvalid()) 13144 return false; 13145 13146 ValExpr = Value.get(); 13147 // The expression must evaluate to a non-negative integer value. 13148 if (Optional<llvm::APSInt> Result = 13149 ValExpr->getIntegerConstantExpr(SemaRef.Context)) { 13150 if (Result->isSigned() && 13151 !((!StrictlyPositive && Result->isNonNegative()) || 13152 (StrictlyPositive && Result->isStrictlyPositive()))) { 13153 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 13154 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 13155 << ValExpr->getSourceRange(); 13156 return false; 13157 } 13158 } 13159 if (!BuildCapture) 13160 return true; 13161 *CaptureRegion = 13162 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP); 13163 if (*CaptureRegion != OMPD_unknown && 13164 !SemaRef.CurContext->isDependentContext()) { 13165 ValExpr = SemaRef.MakeFullExpr(ValExpr).get(); 13166 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13167 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get(); 13168 *HelperValStmt = buildPreInits(SemaRef.Context, Captures); 13169 } 13170 } 13171 return true; 13172 } 13173 13174 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 13175 SourceLocation StartLoc, 13176 SourceLocation LParenLoc, 13177 SourceLocation EndLoc) { 13178 Expr *ValExpr = NumThreads; 13179 Stmt *HelperValStmt = nullptr; 13180 13181 // OpenMP [2.5, Restrictions] 13182 // The num_threads expression must evaluate to a positive integer value. 13183 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 13184 /*StrictlyPositive=*/true)) 13185 return nullptr; 13186 13187 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 13188 OpenMPDirectiveKind CaptureRegion = 13189 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP); 13190 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 13191 ValExpr = MakeFullExpr(ValExpr).get(); 13192 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13193 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13194 HelperValStmt = buildPreInits(Context, Captures); 13195 } 13196 13197 return new (Context) OMPNumThreadsClause( 13198 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 13199 } 13200 13201 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 13202 OpenMPClauseKind CKind, 13203 bool StrictlyPositive) { 13204 if (!E) 13205 return ExprError(); 13206 if (E->isValueDependent() || E->isTypeDependent() || 13207 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 13208 return E; 13209 llvm::APSInt Result; 13210 ExprResult ICE = 13211 VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold); 13212 if (ICE.isInvalid()) 13213 return ExprError(); 13214 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 13215 (!StrictlyPositive && !Result.isNonNegative())) { 13216 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 13217 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 13218 << E->getSourceRange(); 13219 return ExprError(); 13220 } 13221 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 13222 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 13223 << E->getSourceRange(); 13224 return ExprError(); 13225 } 13226 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 13227 DSAStack->setAssociatedLoops(Result.getExtValue()); 13228 else if (CKind == OMPC_ordered) 13229 DSAStack->setAssociatedLoops(Result.getExtValue()); 13230 return ICE; 13231 } 13232 13233 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 13234 SourceLocation LParenLoc, 13235 SourceLocation EndLoc) { 13236 // OpenMP [2.8.1, simd construct, Description] 13237 // The parameter of the safelen clause must be a constant 13238 // positive integer expression. 13239 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 13240 if (Safelen.isInvalid()) 13241 return nullptr; 13242 return new (Context) 13243 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 13244 } 13245 13246 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 13247 SourceLocation LParenLoc, 13248 SourceLocation EndLoc) { 13249 // OpenMP [2.8.1, simd construct, Description] 13250 // The parameter of the simdlen clause must be a constant 13251 // positive integer expression. 13252 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 13253 if (Simdlen.isInvalid()) 13254 return nullptr; 13255 return new (Context) 13256 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 13257 } 13258 13259 /// Tries to find omp_allocator_handle_t type. 13260 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc, 13261 DSAStackTy *Stack) { 13262 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT(); 13263 if (!OMPAllocatorHandleT.isNull()) 13264 return true; 13265 // Build the predefined allocator expressions. 13266 bool ErrorFound = false; 13267 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 13268 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 13269 StringRef Allocator = 13270 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 13271 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator); 13272 auto *VD = dyn_cast_or_null<ValueDecl>( 13273 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName)); 13274 if (!VD) { 13275 ErrorFound = true; 13276 break; 13277 } 13278 QualType AllocatorType = 13279 VD->getType().getNonLValueExprType(S.getASTContext()); 13280 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc); 13281 if (!Res.isUsable()) { 13282 ErrorFound = true; 13283 break; 13284 } 13285 if (OMPAllocatorHandleT.isNull()) 13286 OMPAllocatorHandleT = AllocatorType; 13287 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) { 13288 ErrorFound = true; 13289 break; 13290 } 13291 Stack->setAllocator(AllocatorKind, Res.get()); 13292 } 13293 if (ErrorFound) { 13294 S.Diag(Loc, diag::err_omp_implied_type_not_found) 13295 << "omp_allocator_handle_t"; 13296 return false; 13297 } 13298 OMPAllocatorHandleT.addConst(); 13299 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT); 13300 return true; 13301 } 13302 13303 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc, 13304 SourceLocation LParenLoc, 13305 SourceLocation EndLoc) { 13306 // OpenMP [2.11.3, allocate Directive, Description] 13307 // allocator is an expression of omp_allocator_handle_t type. 13308 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack)) 13309 return nullptr; 13310 13311 ExprResult Allocator = DefaultLvalueConversion(A); 13312 if (Allocator.isInvalid()) 13313 return nullptr; 13314 Allocator = PerformImplicitConversion(Allocator.get(), 13315 DSAStack->getOMPAllocatorHandleT(), 13316 Sema::AA_Initializing, 13317 /*AllowExplicit=*/true); 13318 if (Allocator.isInvalid()) 13319 return nullptr; 13320 return new (Context) 13321 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc); 13322 } 13323 13324 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 13325 SourceLocation StartLoc, 13326 SourceLocation LParenLoc, 13327 SourceLocation EndLoc) { 13328 // OpenMP [2.7.1, loop construct, Description] 13329 // OpenMP [2.8.1, simd construct, Description] 13330 // OpenMP [2.9.6, distribute construct, Description] 13331 // The parameter of the collapse clause must be a constant 13332 // positive integer expression. 13333 ExprResult NumForLoopsResult = 13334 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 13335 if (NumForLoopsResult.isInvalid()) 13336 return nullptr; 13337 return new (Context) 13338 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 13339 } 13340 13341 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 13342 SourceLocation EndLoc, 13343 SourceLocation LParenLoc, 13344 Expr *NumForLoops) { 13345 // OpenMP [2.7.1, loop construct, Description] 13346 // OpenMP [2.8.1, simd construct, Description] 13347 // OpenMP [2.9.6, distribute construct, Description] 13348 // The parameter of the ordered clause must be a constant 13349 // positive integer expression if any. 13350 if (NumForLoops && LParenLoc.isValid()) { 13351 ExprResult NumForLoopsResult = 13352 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 13353 if (NumForLoopsResult.isInvalid()) 13354 return nullptr; 13355 NumForLoops = NumForLoopsResult.get(); 13356 } else { 13357 NumForLoops = nullptr; 13358 } 13359 auto *Clause = OMPOrderedClause::Create( 13360 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 13361 StartLoc, LParenLoc, EndLoc); 13362 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 13363 return Clause; 13364 } 13365 13366 OMPClause *Sema::ActOnOpenMPSimpleClause( 13367 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 13368 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 13369 OMPClause *Res = nullptr; 13370 switch (Kind) { 13371 case OMPC_default: 13372 Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument), 13373 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 13374 break; 13375 case OMPC_proc_bind: 13376 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument), 13377 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 13378 break; 13379 case OMPC_atomic_default_mem_order: 13380 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 13381 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 13382 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 13383 break; 13384 case OMPC_order: 13385 Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument), 13386 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 13387 break; 13388 case OMPC_update: 13389 Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument), 13390 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 13391 break; 13392 case OMPC_if: 13393 case OMPC_final: 13394 case OMPC_num_threads: 13395 case OMPC_safelen: 13396 case OMPC_simdlen: 13397 case OMPC_sizes: 13398 case OMPC_allocator: 13399 case OMPC_collapse: 13400 case OMPC_schedule: 13401 case OMPC_private: 13402 case OMPC_firstprivate: 13403 case OMPC_lastprivate: 13404 case OMPC_shared: 13405 case OMPC_reduction: 13406 case OMPC_task_reduction: 13407 case OMPC_in_reduction: 13408 case OMPC_linear: 13409 case OMPC_aligned: 13410 case OMPC_copyin: 13411 case OMPC_copyprivate: 13412 case OMPC_ordered: 13413 case OMPC_nowait: 13414 case OMPC_untied: 13415 case OMPC_mergeable: 13416 case OMPC_threadprivate: 13417 case OMPC_allocate: 13418 case OMPC_flush: 13419 case OMPC_depobj: 13420 case OMPC_read: 13421 case OMPC_write: 13422 case OMPC_capture: 13423 case OMPC_seq_cst: 13424 case OMPC_acq_rel: 13425 case OMPC_acquire: 13426 case OMPC_release: 13427 case OMPC_relaxed: 13428 case OMPC_depend: 13429 case OMPC_device: 13430 case OMPC_threads: 13431 case OMPC_simd: 13432 case OMPC_map: 13433 case OMPC_num_teams: 13434 case OMPC_thread_limit: 13435 case OMPC_priority: 13436 case OMPC_grainsize: 13437 case OMPC_nogroup: 13438 case OMPC_num_tasks: 13439 case OMPC_hint: 13440 case OMPC_dist_schedule: 13441 case OMPC_defaultmap: 13442 case OMPC_unknown: 13443 case OMPC_uniform: 13444 case OMPC_to: 13445 case OMPC_from: 13446 case OMPC_use_device_ptr: 13447 case OMPC_use_device_addr: 13448 case OMPC_is_device_ptr: 13449 case OMPC_unified_address: 13450 case OMPC_unified_shared_memory: 13451 case OMPC_reverse_offload: 13452 case OMPC_dynamic_allocators: 13453 case OMPC_device_type: 13454 case OMPC_match: 13455 case OMPC_nontemporal: 13456 case OMPC_destroy: 13457 case OMPC_detach: 13458 case OMPC_inclusive: 13459 case OMPC_exclusive: 13460 case OMPC_uses_allocators: 13461 case OMPC_affinity: 13462 default: 13463 llvm_unreachable("Clause is not allowed."); 13464 } 13465 return Res; 13466 } 13467 13468 static std::string 13469 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 13470 ArrayRef<unsigned> Exclude = llvm::None) { 13471 SmallString<256> Buffer; 13472 llvm::raw_svector_ostream Out(Buffer); 13473 unsigned Skipped = Exclude.size(); 13474 auto S = Exclude.begin(), E = Exclude.end(); 13475 for (unsigned I = First; I < Last; ++I) { 13476 if (std::find(S, E, I) != E) { 13477 --Skipped; 13478 continue; 13479 } 13480 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 13481 if (I + Skipped + 2 == Last) 13482 Out << " or "; 13483 else if (I + Skipped + 1 != Last) 13484 Out << ", "; 13485 } 13486 return std::string(Out.str()); 13487 } 13488 13489 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind, 13490 SourceLocation KindKwLoc, 13491 SourceLocation StartLoc, 13492 SourceLocation LParenLoc, 13493 SourceLocation EndLoc) { 13494 if (Kind == OMP_DEFAULT_unknown) { 13495 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 13496 << getListOfPossibleValues(OMPC_default, /*First=*/0, 13497 /*Last=*/unsigned(OMP_DEFAULT_unknown)) 13498 << getOpenMPClauseName(OMPC_default); 13499 return nullptr; 13500 } 13501 13502 switch (Kind) { 13503 case OMP_DEFAULT_none: 13504 DSAStack->setDefaultDSANone(KindKwLoc); 13505 break; 13506 case OMP_DEFAULT_shared: 13507 DSAStack->setDefaultDSAShared(KindKwLoc); 13508 break; 13509 case OMP_DEFAULT_firstprivate: 13510 DSAStack->setDefaultDSAFirstPrivate(KindKwLoc); 13511 break; 13512 default: 13513 llvm_unreachable("DSA unexpected in OpenMP default clause"); 13514 } 13515 13516 return new (Context) 13517 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 13518 } 13519 13520 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind, 13521 SourceLocation KindKwLoc, 13522 SourceLocation StartLoc, 13523 SourceLocation LParenLoc, 13524 SourceLocation EndLoc) { 13525 if (Kind == OMP_PROC_BIND_unknown) { 13526 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 13527 << getListOfPossibleValues(OMPC_proc_bind, 13528 /*First=*/unsigned(OMP_PROC_BIND_master), 13529 /*Last=*/5) 13530 << getOpenMPClauseName(OMPC_proc_bind); 13531 return nullptr; 13532 } 13533 return new (Context) 13534 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 13535 } 13536 13537 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 13538 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 13539 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 13540 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 13541 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 13542 << getListOfPossibleValues( 13543 OMPC_atomic_default_mem_order, /*First=*/0, 13544 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 13545 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 13546 return nullptr; 13547 } 13548 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 13549 LParenLoc, EndLoc); 13550 } 13551 13552 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 13553 SourceLocation KindKwLoc, 13554 SourceLocation StartLoc, 13555 SourceLocation LParenLoc, 13556 SourceLocation EndLoc) { 13557 if (Kind == OMPC_ORDER_unknown) { 13558 static_assert(OMPC_ORDER_unknown > 0, 13559 "OMPC_ORDER_unknown not greater than 0"); 13560 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 13561 << getListOfPossibleValues(OMPC_order, /*First=*/0, 13562 /*Last=*/OMPC_ORDER_unknown) 13563 << getOpenMPClauseName(OMPC_order); 13564 return nullptr; 13565 } 13566 return new (Context) 13567 OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 13568 } 13569 13570 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 13571 SourceLocation KindKwLoc, 13572 SourceLocation StartLoc, 13573 SourceLocation LParenLoc, 13574 SourceLocation EndLoc) { 13575 if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source || 13576 Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) { 13577 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink, 13578 OMPC_DEPEND_depobj}; 13579 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 13580 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 13581 /*Last=*/OMPC_DEPEND_unknown, Except) 13582 << getOpenMPClauseName(OMPC_update); 13583 return nullptr; 13584 } 13585 return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind, 13586 EndLoc); 13587 } 13588 13589 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, 13590 SourceLocation StartLoc, 13591 SourceLocation LParenLoc, 13592 SourceLocation EndLoc) { 13593 for (Expr *SizeExpr : SizeExprs) { 13594 ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause( 13595 SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true); 13596 if (!NumForLoopsResult.isUsable()) 13597 return nullptr; 13598 } 13599 13600 DSAStack->setAssociatedLoops(SizeExprs.size()); 13601 return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc, 13602 SizeExprs); 13603 } 13604 13605 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 13606 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 13607 SourceLocation StartLoc, SourceLocation LParenLoc, 13608 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 13609 SourceLocation EndLoc) { 13610 OMPClause *Res = nullptr; 13611 switch (Kind) { 13612 case OMPC_schedule: 13613 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 13614 assert(Argument.size() == NumberOfElements && 13615 ArgumentLoc.size() == NumberOfElements); 13616 Res = ActOnOpenMPScheduleClause( 13617 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 13618 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 13619 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 13620 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 13621 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 13622 break; 13623 case OMPC_if: 13624 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 13625 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 13626 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 13627 DelimLoc, EndLoc); 13628 break; 13629 case OMPC_dist_schedule: 13630 Res = ActOnOpenMPDistScheduleClause( 13631 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 13632 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 13633 break; 13634 case OMPC_defaultmap: 13635 enum { Modifier, DefaultmapKind }; 13636 Res = ActOnOpenMPDefaultmapClause( 13637 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 13638 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 13639 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 13640 EndLoc); 13641 break; 13642 case OMPC_device: 13643 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 13644 Res = ActOnOpenMPDeviceClause( 13645 static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr, 13646 StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc); 13647 break; 13648 case OMPC_final: 13649 case OMPC_num_threads: 13650 case OMPC_safelen: 13651 case OMPC_simdlen: 13652 case OMPC_sizes: 13653 case OMPC_allocator: 13654 case OMPC_collapse: 13655 case OMPC_default: 13656 case OMPC_proc_bind: 13657 case OMPC_private: 13658 case OMPC_firstprivate: 13659 case OMPC_lastprivate: 13660 case OMPC_shared: 13661 case OMPC_reduction: 13662 case OMPC_task_reduction: 13663 case OMPC_in_reduction: 13664 case OMPC_linear: 13665 case OMPC_aligned: 13666 case OMPC_copyin: 13667 case OMPC_copyprivate: 13668 case OMPC_ordered: 13669 case OMPC_nowait: 13670 case OMPC_untied: 13671 case OMPC_mergeable: 13672 case OMPC_threadprivate: 13673 case OMPC_allocate: 13674 case OMPC_flush: 13675 case OMPC_depobj: 13676 case OMPC_read: 13677 case OMPC_write: 13678 case OMPC_update: 13679 case OMPC_capture: 13680 case OMPC_seq_cst: 13681 case OMPC_acq_rel: 13682 case OMPC_acquire: 13683 case OMPC_release: 13684 case OMPC_relaxed: 13685 case OMPC_depend: 13686 case OMPC_threads: 13687 case OMPC_simd: 13688 case OMPC_map: 13689 case OMPC_num_teams: 13690 case OMPC_thread_limit: 13691 case OMPC_priority: 13692 case OMPC_grainsize: 13693 case OMPC_nogroup: 13694 case OMPC_num_tasks: 13695 case OMPC_hint: 13696 case OMPC_unknown: 13697 case OMPC_uniform: 13698 case OMPC_to: 13699 case OMPC_from: 13700 case OMPC_use_device_ptr: 13701 case OMPC_use_device_addr: 13702 case OMPC_is_device_ptr: 13703 case OMPC_unified_address: 13704 case OMPC_unified_shared_memory: 13705 case OMPC_reverse_offload: 13706 case OMPC_dynamic_allocators: 13707 case OMPC_atomic_default_mem_order: 13708 case OMPC_device_type: 13709 case OMPC_match: 13710 case OMPC_nontemporal: 13711 case OMPC_order: 13712 case OMPC_destroy: 13713 case OMPC_detach: 13714 case OMPC_inclusive: 13715 case OMPC_exclusive: 13716 case OMPC_uses_allocators: 13717 case OMPC_affinity: 13718 default: 13719 llvm_unreachable("Clause is not allowed."); 13720 } 13721 return Res; 13722 } 13723 13724 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 13725 OpenMPScheduleClauseModifier M2, 13726 SourceLocation M1Loc, SourceLocation M2Loc) { 13727 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 13728 SmallVector<unsigned, 2> Excluded; 13729 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 13730 Excluded.push_back(M2); 13731 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 13732 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 13733 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 13734 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 13735 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 13736 << getListOfPossibleValues(OMPC_schedule, 13737 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 13738 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 13739 Excluded) 13740 << getOpenMPClauseName(OMPC_schedule); 13741 return true; 13742 } 13743 return false; 13744 } 13745 13746 OMPClause *Sema::ActOnOpenMPScheduleClause( 13747 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 13748 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 13749 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 13750 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 13751 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 13752 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 13753 return nullptr; 13754 // OpenMP, 2.7.1, Loop Construct, Restrictions 13755 // Either the monotonic modifier or the nonmonotonic modifier can be specified 13756 // but not both. 13757 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 13758 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 13759 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 13760 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 13761 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 13762 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 13763 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 13764 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 13765 return nullptr; 13766 } 13767 if (Kind == OMPC_SCHEDULE_unknown) { 13768 std::string Values; 13769 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 13770 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 13771 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 13772 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 13773 Exclude); 13774 } else { 13775 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 13776 /*Last=*/OMPC_SCHEDULE_unknown); 13777 } 13778 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 13779 << Values << getOpenMPClauseName(OMPC_schedule); 13780 return nullptr; 13781 } 13782 // OpenMP, 2.7.1, Loop Construct, Restrictions 13783 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 13784 // schedule(guided). 13785 // OpenMP 5.0 does not have this restriction. 13786 if (LangOpts.OpenMP < 50 && 13787 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 13788 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 13789 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 13790 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 13791 diag::err_omp_schedule_nonmonotonic_static); 13792 return nullptr; 13793 } 13794 Expr *ValExpr = ChunkSize; 13795 Stmt *HelperValStmt = nullptr; 13796 if (ChunkSize) { 13797 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 13798 !ChunkSize->isInstantiationDependent() && 13799 !ChunkSize->containsUnexpandedParameterPack()) { 13800 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 13801 ExprResult Val = 13802 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 13803 if (Val.isInvalid()) 13804 return nullptr; 13805 13806 ValExpr = Val.get(); 13807 13808 // OpenMP [2.7.1, Restrictions] 13809 // chunk_size must be a loop invariant integer expression with a positive 13810 // value. 13811 if (Optional<llvm::APSInt> Result = 13812 ValExpr->getIntegerConstantExpr(Context)) { 13813 if (Result->isSigned() && !Result->isStrictlyPositive()) { 13814 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 13815 << "schedule" << 1 << ChunkSize->getSourceRange(); 13816 return nullptr; 13817 } 13818 } else if (getOpenMPCaptureRegionForClause( 13819 DSAStack->getCurrentDirective(), OMPC_schedule, 13820 LangOpts.OpenMP) != OMPD_unknown && 13821 !CurContext->isDependentContext()) { 13822 ValExpr = MakeFullExpr(ValExpr).get(); 13823 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13824 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13825 HelperValStmt = buildPreInits(Context, Captures); 13826 } 13827 } 13828 } 13829 13830 return new (Context) 13831 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 13832 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 13833 } 13834 13835 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 13836 SourceLocation StartLoc, 13837 SourceLocation EndLoc) { 13838 OMPClause *Res = nullptr; 13839 switch (Kind) { 13840 case OMPC_ordered: 13841 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 13842 break; 13843 case OMPC_nowait: 13844 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 13845 break; 13846 case OMPC_untied: 13847 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 13848 break; 13849 case OMPC_mergeable: 13850 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 13851 break; 13852 case OMPC_read: 13853 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 13854 break; 13855 case OMPC_write: 13856 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 13857 break; 13858 case OMPC_update: 13859 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 13860 break; 13861 case OMPC_capture: 13862 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 13863 break; 13864 case OMPC_seq_cst: 13865 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 13866 break; 13867 case OMPC_acq_rel: 13868 Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc); 13869 break; 13870 case OMPC_acquire: 13871 Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc); 13872 break; 13873 case OMPC_release: 13874 Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc); 13875 break; 13876 case OMPC_relaxed: 13877 Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc); 13878 break; 13879 case OMPC_threads: 13880 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 13881 break; 13882 case OMPC_simd: 13883 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 13884 break; 13885 case OMPC_nogroup: 13886 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 13887 break; 13888 case OMPC_unified_address: 13889 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 13890 break; 13891 case OMPC_unified_shared_memory: 13892 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 13893 break; 13894 case OMPC_reverse_offload: 13895 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 13896 break; 13897 case OMPC_dynamic_allocators: 13898 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 13899 break; 13900 case OMPC_destroy: 13901 Res = ActOnOpenMPDestroyClause(StartLoc, EndLoc); 13902 break; 13903 case OMPC_if: 13904 case OMPC_final: 13905 case OMPC_num_threads: 13906 case OMPC_safelen: 13907 case OMPC_simdlen: 13908 case OMPC_sizes: 13909 case OMPC_allocator: 13910 case OMPC_collapse: 13911 case OMPC_schedule: 13912 case OMPC_private: 13913 case OMPC_firstprivate: 13914 case OMPC_lastprivate: 13915 case OMPC_shared: 13916 case OMPC_reduction: 13917 case OMPC_task_reduction: 13918 case OMPC_in_reduction: 13919 case OMPC_linear: 13920 case OMPC_aligned: 13921 case OMPC_copyin: 13922 case OMPC_copyprivate: 13923 case OMPC_default: 13924 case OMPC_proc_bind: 13925 case OMPC_threadprivate: 13926 case OMPC_allocate: 13927 case OMPC_flush: 13928 case OMPC_depobj: 13929 case OMPC_depend: 13930 case OMPC_device: 13931 case OMPC_map: 13932 case OMPC_num_teams: 13933 case OMPC_thread_limit: 13934 case OMPC_priority: 13935 case OMPC_grainsize: 13936 case OMPC_num_tasks: 13937 case OMPC_hint: 13938 case OMPC_dist_schedule: 13939 case OMPC_defaultmap: 13940 case OMPC_unknown: 13941 case OMPC_uniform: 13942 case OMPC_to: 13943 case OMPC_from: 13944 case OMPC_use_device_ptr: 13945 case OMPC_use_device_addr: 13946 case OMPC_is_device_ptr: 13947 case OMPC_atomic_default_mem_order: 13948 case OMPC_device_type: 13949 case OMPC_match: 13950 case OMPC_nontemporal: 13951 case OMPC_order: 13952 case OMPC_detach: 13953 case OMPC_inclusive: 13954 case OMPC_exclusive: 13955 case OMPC_uses_allocators: 13956 case OMPC_affinity: 13957 default: 13958 llvm_unreachable("Clause is not allowed."); 13959 } 13960 return Res; 13961 } 13962 13963 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 13964 SourceLocation EndLoc) { 13965 DSAStack->setNowaitRegion(); 13966 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 13967 } 13968 13969 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 13970 SourceLocation EndLoc) { 13971 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 13972 } 13973 13974 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 13975 SourceLocation EndLoc) { 13976 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 13977 } 13978 13979 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 13980 SourceLocation EndLoc) { 13981 return new (Context) OMPReadClause(StartLoc, EndLoc); 13982 } 13983 13984 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 13985 SourceLocation EndLoc) { 13986 return new (Context) OMPWriteClause(StartLoc, EndLoc); 13987 } 13988 13989 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 13990 SourceLocation EndLoc) { 13991 return OMPUpdateClause::Create(Context, StartLoc, EndLoc); 13992 } 13993 13994 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 13995 SourceLocation EndLoc) { 13996 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 13997 } 13998 13999 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 14000 SourceLocation EndLoc) { 14001 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 14002 } 14003 14004 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 14005 SourceLocation EndLoc) { 14006 return new (Context) OMPAcqRelClause(StartLoc, EndLoc); 14007 } 14008 14009 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc, 14010 SourceLocation EndLoc) { 14011 return new (Context) OMPAcquireClause(StartLoc, EndLoc); 14012 } 14013 14014 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc, 14015 SourceLocation EndLoc) { 14016 return new (Context) OMPReleaseClause(StartLoc, EndLoc); 14017 } 14018 14019 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 14020 SourceLocation EndLoc) { 14021 return new (Context) OMPRelaxedClause(StartLoc, EndLoc); 14022 } 14023 14024 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 14025 SourceLocation EndLoc) { 14026 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 14027 } 14028 14029 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 14030 SourceLocation EndLoc) { 14031 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 14032 } 14033 14034 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 14035 SourceLocation EndLoc) { 14036 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 14037 } 14038 14039 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 14040 SourceLocation EndLoc) { 14041 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 14042 } 14043 14044 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 14045 SourceLocation EndLoc) { 14046 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 14047 } 14048 14049 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 14050 SourceLocation EndLoc) { 14051 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 14052 } 14053 14054 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 14055 SourceLocation EndLoc) { 14056 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 14057 } 14058 14059 OMPClause *Sema::ActOnOpenMPDestroyClause(SourceLocation StartLoc, 14060 SourceLocation EndLoc) { 14061 return new (Context) OMPDestroyClause(StartLoc, EndLoc); 14062 } 14063 14064 OMPClause *Sema::ActOnOpenMPVarListClause( 14065 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr, 14066 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 14067 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 14068 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, 14069 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 14070 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, 14071 SourceLocation ExtraModifierLoc, 14072 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 14073 ArrayRef<SourceLocation> MotionModifiersLoc) { 14074 SourceLocation StartLoc = Locs.StartLoc; 14075 SourceLocation LParenLoc = Locs.LParenLoc; 14076 SourceLocation EndLoc = Locs.EndLoc; 14077 OMPClause *Res = nullptr; 14078 switch (Kind) { 14079 case OMPC_private: 14080 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 14081 break; 14082 case OMPC_firstprivate: 14083 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 14084 break; 14085 case OMPC_lastprivate: 14086 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown && 14087 "Unexpected lastprivate modifier."); 14088 Res = ActOnOpenMPLastprivateClause( 14089 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier), 14090 ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc); 14091 break; 14092 case OMPC_shared: 14093 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 14094 break; 14095 case OMPC_reduction: 14096 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown && 14097 "Unexpected lastprivate modifier."); 14098 Res = ActOnOpenMPReductionClause( 14099 VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier), 14100 StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc, 14101 ReductionOrMapperIdScopeSpec, ReductionOrMapperId); 14102 break; 14103 case OMPC_task_reduction: 14104 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 14105 EndLoc, ReductionOrMapperIdScopeSpec, 14106 ReductionOrMapperId); 14107 break; 14108 case OMPC_in_reduction: 14109 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 14110 EndLoc, ReductionOrMapperIdScopeSpec, 14111 ReductionOrMapperId); 14112 break; 14113 case OMPC_linear: 14114 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown && 14115 "Unexpected linear modifier."); 14116 Res = ActOnOpenMPLinearClause( 14117 VarList, DepModOrTailExpr, StartLoc, LParenLoc, 14118 static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc, 14119 ColonLoc, EndLoc); 14120 break; 14121 case OMPC_aligned: 14122 Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc, 14123 LParenLoc, ColonLoc, EndLoc); 14124 break; 14125 case OMPC_copyin: 14126 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 14127 break; 14128 case OMPC_copyprivate: 14129 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 14130 break; 14131 case OMPC_flush: 14132 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 14133 break; 14134 case OMPC_depend: 14135 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown && 14136 "Unexpected depend modifier."); 14137 Res = ActOnOpenMPDependClause( 14138 DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier), 14139 ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc); 14140 break; 14141 case OMPC_map: 14142 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown && 14143 "Unexpected map modifier."); 14144 Res = ActOnOpenMPMapClause( 14145 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec, 14146 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier), 14147 IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs); 14148 break; 14149 case OMPC_to: 14150 Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc, 14151 ReductionOrMapperIdScopeSpec, ReductionOrMapperId, 14152 ColonLoc, VarList, Locs); 14153 break; 14154 case OMPC_from: 14155 Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc, 14156 ReductionOrMapperIdScopeSpec, 14157 ReductionOrMapperId, ColonLoc, VarList, Locs); 14158 break; 14159 case OMPC_use_device_ptr: 14160 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs); 14161 break; 14162 case OMPC_use_device_addr: 14163 Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs); 14164 break; 14165 case OMPC_is_device_ptr: 14166 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs); 14167 break; 14168 case OMPC_allocate: 14169 Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc, 14170 LParenLoc, ColonLoc, EndLoc); 14171 break; 14172 case OMPC_nontemporal: 14173 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc); 14174 break; 14175 case OMPC_inclusive: 14176 Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 14177 break; 14178 case OMPC_exclusive: 14179 Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 14180 break; 14181 case OMPC_affinity: 14182 Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc, 14183 DepModOrTailExpr, VarList); 14184 break; 14185 case OMPC_if: 14186 case OMPC_depobj: 14187 case OMPC_final: 14188 case OMPC_num_threads: 14189 case OMPC_safelen: 14190 case OMPC_simdlen: 14191 case OMPC_sizes: 14192 case OMPC_allocator: 14193 case OMPC_collapse: 14194 case OMPC_default: 14195 case OMPC_proc_bind: 14196 case OMPC_schedule: 14197 case OMPC_ordered: 14198 case OMPC_nowait: 14199 case OMPC_untied: 14200 case OMPC_mergeable: 14201 case OMPC_threadprivate: 14202 case OMPC_read: 14203 case OMPC_write: 14204 case OMPC_update: 14205 case OMPC_capture: 14206 case OMPC_seq_cst: 14207 case OMPC_acq_rel: 14208 case OMPC_acquire: 14209 case OMPC_release: 14210 case OMPC_relaxed: 14211 case OMPC_device: 14212 case OMPC_threads: 14213 case OMPC_simd: 14214 case OMPC_num_teams: 14215 case OMPC_thread_limit: 14216 case OMPC_priority: 14217 case OMPC_grainsize: 14218 case OMPC_nogroup: 14219 case OMPC_num_tasks: 14220 case OMPC_hint: 14221 case OMPC_dist_schedule: 14222 case OMPC_defaultmap: 14223 case OMPC_unknown: 14224 case OMPC_uniform: 14225 case OMPC_unified_address: 14226 case OMPC_unified_shared_memory: 14227 case OMPC_reverse_offload: 14228 case OMPC_dynamic_allocators: 14229 case OMPC_atomic_default_mem_order: 14230 case OMPC_device_type: 14231 case OMPC_match: 14232 case OMPC_order: 14233 case OMPC_destroy: 14234 case OMPC_detach: 14235 case OMPC_uses_allocators: 14236 default: 14237 llvm_unreachable("Clause is not allowed."); 14238 } 14239 return Res; 14240 } 14241 14242 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 14243 ExprObjectKind OK, SourceLocation Loc) { 14244 ExprResult Res = BuildDeclRefExpr( 14245 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 14246 if (!Res.isUsable()) 14247 return ExprError(); 14248 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 14249 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 14250 if (!Res.isUsable()) 14251 return ExprError(); 14252 } 14253 if (VK != VK_LValue && Res.get()->isGLValue()) { 14254 Res = DefaultLvalueConversion(Res.get()); 14255 if (!Res.isUsable()) 14256 return ExprError(); 14257 } 14258 return Res; 14259 } 14260 14261 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 14262 SourceLocation StartLoc, 14263 SourceLocation LParenLoc, 14264 SourceLocation EndLoc) { 14265 SmallVector<Expr *, 8> Vars; 14266 SmallVector<Expr *, 8> PrivateCopies; 14267 for (Expr *RefExpr : VarList) { 14268 assert(RefExpr && "NULL expr in OpenMP private 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 Vars.push_back(RefExpr); 14276 PrivateCopies.push_back(nullptr); 14277 } 14278 ValueDecl *D = Res.first; 14279 if (!D) 14280 continue; 14281 14282 QualType Type = D->getType(); 14283 auto *VD = dyn_cast<VarDecl>(D); 14284 14285 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 14286 // A variable that appears in a private clause must not have an incomplete 14287 // type or a reference type. 14288 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 14289 continue; 14290 Type = Type.getNonReferenceType(); 14291 14292 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 14293 // A variable that is privatized must not have a const-qualified type 14294 // unless it is of class type with a mutable member. This restriction does 14295 // not apply to the firstprivate clause. 14296 // 14297 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 14298 // A variable that appears in a private clause must not have a 14299 // const-qualified type unless it is of class type with a mutable member. 14300 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 14301 continue; 14302 14303 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 14304 // in a Construct] 14305 // Variables with the predetermined data-sharing attributes may not be 14306 // listed in data-sharing attributes clauses, except for the cases 14307 // listed below. For these exceptions only, listing a predetermined 14308 // variable in a data-sharing attribute clause is allowed and overrides 14309 // the variable's predetermined data-sharing attributes. 14310 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 14311 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 14312 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 14313 << getOpenMPClauseName(OMPC_private); 14314 reportOriginalDsa(*this, DSAStack, D, DVar); 14315 continue; 14316 } 14317 14318 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 14319 // Variably modified types are not supported for tasks. 14320 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 14321 isOpenMPTaskingDirective(CurrDir)) { 14322 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 14323 << getOpenMPClauseName(OMPC_private) << Type 14324 << getOpenMPDirectiveName(CurrDir); 14325 bool IsDecl = 14326 !VD || 14327 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 14328 Diag(D->getLocation(), 14329 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 14330 << D; 14331 continue; 14332 } 14333 14334 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 14335 // A list item cannot appear in both a map clause and a data-sharing 14336 // attribute clause on the same construct 14337 // 14338 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 14339 // A list item cannot appear in both a map clause and a data-sharing 14340 // attribute clause on the same construct unless the construct is a 14341 // combined construct. 14342 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) || 14343 CurrDir == OMPD_target) { 14344 OpenMPClauseKind ConflictKind; 14345 if (DSAStack->checkMappableExprComponentListsForDecl( 14346 VD, /*CurrentRegionOnly=*/true, 14347 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 14348 OpenMPClauseKind WhereFoundClauseKind) -> bool { 14349 ConflictKind = WhereFoundClauseKind; 14350 return true; 14351 })) { 14352 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 14353 << getOpenMPClauseName(OMPC_private) 14354 << getOpenMPClauseName(ConflictKind) 14355 << getOpenMPDirectiveName(CurrDir); 14356 reportOriginalDsa(*this, DSAStack, D, DVar); 14357 continue; 14358 } 14359 } 14360 14361 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 14362 // A variable of class type (or array thereof) that appears in a private 14363 // clause requires an accessible, unambiguous default constructor for the 14364 // class type. 14365 // Generate helper private variable and initialize it with the default 14366 // value. The address of the original variable is replaced by the address of 14367 // the new private variable in CodeGen. This new variable is not added to 14368 // IdResolver, so the code in the OpenMP region uses original variable for 14369 // proper diagnostics. 14370 Type = Type.getUnqualifiedType(); 14371 VarDecl *VDPrivate = 14372 buildVarDecl(*this, ELoc, Type, D->getName(), 14373 D->hasAttrs() ? &D->getAttrs() : nullptr, 14374 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 14375 ActOnUninitializedDecl(VDPrivate); 14376 if (VDPrivate->isInvalidDecl()) 14377 continue; 14378 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 14379 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 14380 14381 DeclRefExpr *Ref = nullptr; 14382 if (!VD && !CurContext->isDependentContext()) 14383 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 14384 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 14385 Vars.push_back((VD || CurContext->isDependentContext()) 14386 ? RefExpr->IgnoreParens() 14387 : Ref); 14388 PrivateCopies.push_back(VDPrivateRefExpr); 14389 } 14390 14391 if (Vars.empty()) 14392 return nullptr; 14393 14394 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 14395 PrivateCopies); 14396 } 14397 14398 namespace { 14399 class DiagsUninitializedSeveretyRAII { 14400 private: 14401 DiagnosticsEngine &Diags; 14402 SourceLocation SavedLoc; 14403 bool IsIgnored = false; 14404 14405 public: 14406 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 14407 bool IsIgnored) 14408 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 14409 if (!IsIgnored) { 14410 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 14411 /*Map*/ diag::Severity::Ignored, Loc); 14412 } 14413 } 14414 ~DiagsUninitializedSeveretyRAII() { 14415 if (!IsIgnored) 14416 Diags.popMappings(SavedLoc); 14417 } 14418 }; 14419 } 14420 14421 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 14422 SourceLocation StartLoc, 14423 SourceLocation LParenLoc, 14424 SourceLocation EndLoc) { 14425 SmallVector<Expr *, 8> Vars; 14426 SmallVector<Expr *, 8> PrivateCopies; 14427 SmallVector<Expr *, 8> Inits; 14428 SmallVector<Decl *, 4> ExprCaptures; 14429 bool IsImplicitClause = 14430 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 14431 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 14432 14433 for (Expr *RefExpr : VarList) { 14434 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 14435 SourceLocation ELoc; 14436 SourceRange ERange; 14437 Expr *SimpleRefExpr = RefExpr; 14438 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 14439 if (Res.second) { 14440 // It will be analyzed later. 14441 Vars.push_back(RefExpr); 14442 PrivateCopies.push_back(nullptr); 14443 Inits.push_back(nullptr); 14444 } 14445 ValueDecl *D = Res.first; 14446 if (!D) 14447 continue; 14448 14449 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 14450 QualType Type = D->getType(); 14451 auto *VD = dyn_cast<VarDecl>(D); 14452 14453 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 14454 // A variable that appears in a private clause must not have an incomplete 14455 // type or a reference type. 14456 if (RequireCompleteType(ELoc, Type, 14457 diag::err_omp_firstprivate_incomplete_type)) 14458 continue; 14459 Type = Type.getNonReferenceType(); 14460 14461 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 14462 // A variable of class type (or array thereof) that appears in a private 14463 // clause requires an accessible, unambiguous copy constructor for the 14464 // class type. 14465 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 14466 14467 // If an implicit firstprivate variable found it was checked already. 14468 DSAStackTy::DSAVarData TopDVar; 14469 if (!IsImplicitClause) { 14470 DSAStackTy::DSAVarData DVar = 14471 DSAStack->getTopDSA(D, /*FromParent=*/false); 14472 TopDVar = DVar; 14473 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 14474 bool IsConstant = ElemType.isConstant(Context); 14475 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 14476 // A list item that specifies a given variable may not appear in more 14477 // than one clause on the same directive, except that a variable may be 14478 // specified in both firstprivate and lastprivate clauses. 14479 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 14480 // A list item may appear in a firstprivate or lastprivate clause but not 14481 // both. 14482 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 14483 (isOpenMPDistributeDirective(CurrDir) || 14484 DVar.CKind != OMPC_lastprivate) && 14485 DVar.RefExpr) { 14486 Diag(ELoc, diag::err_omp_wrong_dsa) 14487 << getOpenMPClauseName(DVar.CKind) 14488 << getOpenMPClauseName(OMPC_firstprivate); 14489 reportOriginalDsa(*this, DSAStack, D, DVar); 14490 continue; 14491 } 14492 14493 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 14494 // in a Construct] 14495 // Variables with the predetermined data-sharing attributes may not be 14496 // listed in data-sharing attributes clauses, except for the cases 14497 // listed below. For these exceptions only, listing a predetermined 14498 // variable in a data-sharing attribute clause is allowed and overrides 14499 // the variable's predetermined data-sharing attributes. 14500 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 14501 // in a Construct, C/C++, p.2] 14502 // Variables with const-qualified type having no mutable member may be 14503 // listed in a firstprivate clause, even if they are static data members. 14504 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 14505 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 14506 Diag(ELoc, diag::err_omp_wrong_dsa) 14507 << getOpenMPClauseName(DVar.CKind) 14508 << getOpenMPClauseName(OMPC_firstprivate); 14509 reportOriginalDsa(*this, DSAStack, D, DVar); 14510 continue; 14511 } 14512 14513 // OpenMP [2.9.3.4, Restrictions, p.2] 14514 // A list item that is private within a parallel region must not appear 14515 // in a firstprivate clause on a worksharing construct if any of the 14516 // worksharing regions arising from the worksharing construct ever bind 14517 // to any of the parallel regions arising from the parallel construct. 14518 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 14519 // A list item that is private within a teams region must not appear in a 14520 // firstprivate clause on a distribute construct if any of the distribute 14521 // regions arising from the distribute construct ever bind to any of the 14522 // teams regions arising from the teams construct. 14523 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 14524 // A list item that appears in a reduction clause of a teams construct 14525 // must not appear in a firstprivate clause on a distribute construct if 14526 // any of the distribute regions arising from the distribute construct 14527 // ever bind to any of the teams regions arising from the teams construct. 14528 if ((isOpenMPWorksharingDirective(CurrDir) || 14529 isOpenMPDistributeDirective(CurrDir)) && 14530 !isOpenMPParallelDirective(CurrDir) && 14531 !isOpenMPTeamsDirective(CurrDir)) { 14532 DVar = DSAStack->getImplicitDSA(D, true); 14533 if (DVar.CKind != OMPC_shared && 14534 (isOpenMPParallelDirective(DVar.DKind) || 14535 isOpenMPTeamsDirective(DVar.DKind) || 14536 DVar.DKind == OMPD_unknown)) { 14537 Diag(ELoc, diag::err_omp_required_access) 14538 << getOpenMPClauseName(OMPC_firstprivate) 14539 << getOpenMPClauseName(OMPC_shared); 14540 reportOriginalDsa(*this, DSAStack, D, DVar); 14541 continue; 14542 } 14543 } 14544 // OpenMP [2.9.3.4, Restrictions, p.3] 14545 // A list item that appears in a reduction clause of a parallel construct 14546 // must not appear in a firstprivate clause on a worksharing or task 14547 // construct if any of the worksharing or task regions arising from the 14548 // worksharing or task construct ever bind to any of the parallel regions 14549 // arising from the parallel construct. 14550 // OpenMP [2.9.3.4, Restrictions, p.4] 14551 // A list item that appears in a reduction clause in worksharing 14552 // construct must not appear in a firstprivate clause in a task construct 14553 // encountered during execution of any of the worksharing regions arising 14554 // from the worksharing construct. 14555 if (isOpenMPTaskingDirective(CurrDir)) { 14556 DVar = DSAStack->hasInnermostDSA( 14557 D, 14558 [](OpenMPClauseKind C, bool AppliedToPointee) { 14559 return C == OMPC_reduction && !AppliedToPointee; 14560 }, 14561 [](OpenMPDirectiveKind K) { 14562 return isOpenMPParallelDirective(K) || 14563 isOpenMPWorksharingDirective(K) || 14564 isOpenMPTeamsDirective(K); 14565 }, 14566 /*FromParent=*/true); 14567 if (DVar.CKind == OMPC_reduction && 14568 (isOpenMPParallelDirective(DVar.DKind) || 14569 isOpenMPWorksharingDirective(DVar.DKind) || 14570 isOpenMPTeamsDirective(DVar.DKind))) { 14571 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 14572 << getOpenMPDirectiveName(DVar.DKind); 14573 reportOriginalDsa(*this, DSAStack, D, DVar); 14574 continue; 14575 } 14576 } 14577 14578 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 14579 // A list item cannot appear in both a map clause and a data-sharing 14580 // attribute clause on the same construct 14581 // 14582 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 14583 // A list item cannot appear in both a map clause and a data-sharing 14584 // attribute clause on the same construct unless the construct is a 14585 // combined construct. 14586 if ((LangOpts.OpenMP <= 45 && 14587 isOpenMPTargetExecutionDirective(CurrDir)) || 14588 CurrDir == OMPD_target) { 14589 OpenMPClauseKind ConflictKind; 14590 if (DSAStack->checkMappableExprComponentListsForDecl( 14591 VD, /*CurrentRegionOnly=*/true, 14592 [&ConflictKind]( 14593 OMPClauseMappableExprCommon::MappableExprComponentListRef, 14594 OpenMPClauseKind WhereFoundClauseKind) { 14595 ConflictKind = WhereFoundClauseKind; 14596 return true; 14597 })) { 14598 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 14599 << getOpenMPClauseName(OMPC_firstprivate) 14600 << getOpenMPClauseName(ConflictKind) 14601 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 14602 reportOriginalDsa(*this, DSAStack, D, DVar); 14603 continue; 14604 } 14605 } 14606 } 14607 14608 // Variably modified types are not supported for tasks. 14609 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 14610 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 14611 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 14612 << getOpenMPClauseName(OMPC_firstprivate) << Type 14613 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 14614 bool IsDecl = 14615 !VD || 14616 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 14617 Diag(D->getLocation(), 14618 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 14619 << D; 14620 continue; 14621 } 14622 14623 Type = Type.getUnqualifiedType(); 14624 VarDecl *VDPrivate = 14625 buildVarDecl(*this, ELoc, Type, D->getName(), 14626 D->hasAttrs() ? &D->getAttrs() : nullptr, 14627 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 14628 // Generate helper private variable and initialize it with the value of the 14629 // original variable. The address of the original variable is replaced by 14630 // the address of the new private variable in the CodeGen. This new variable 14631 // is not added to IdResolver, so the code in the OpenMP region uses 14632 // original variable for proper diagnostics and variable capturing. 14633 Expr *VDInitRefExpr = nullptr; 14634 // For arrays generate initializer for single element and replace it by the 14635 // original array element in CodeGen. 14636 if (Type->isArrayType()) { 14637 VarDecl *VDInit = 14638 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 14639 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 14640 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 14641 ElemType = ElemType.getUnqualifiedType(); 14642 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 14643 ".firstprivate.temp"); 14644 InitializedEntity Entity = 14645 InitializedEntity::InitializeVariable(VDInitTemp); 14646 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 14647 14648 InitializationSequence InitSeq(*this, Entity, Kind, Init); 14649 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 14650 if (Result.isInvalid()) 14651 VDPrivate->setInvalidDecl(); 14652 else 14653 VDPrivate->setInit(Result.getAs<Expr>()); 14654 // Remove temp variable declaration. 14655 Context.Deallocate(VDInitTemp); 14656 } else { 14657 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 14658 ".firstprivate.temp"); 14659 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 14660 RefExpr->getExprLoc()); 14661 AddInitializerToDecl(VDPrivate, 14662 DefaultLvalueConversion(VDInitRefExpr).get(), 14663 /*DirectInit=*/false); 14664 } 14665 if (VDPrivate->isInvalidDecl()) { 14666 if (IsImplicitClause) { 14667 Diag(RefExpr->getExprLoc(), 14668 diag::note_omp_task_predetermined_firstprivate_here); 14669 } 14670 continue; 14671 } 14672 CurContext->addDecl(VDPrivate); 14673 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 14674 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 14675 RefExpr->getExprLoc()); 14676 DeclRefExpr *Ref = nullptr; 14677 if (!VD && !CurContext->isDependentContext()) { 14678 if (TopDVar.CKind == OMPC_lastprivate) { 14679 Ref = TopDVar.PrivateCopy; 14680 } else { 14681 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 14682 if (!isOpenMPCapturedDecl(D)) 14683 ExprCaptures.push_back(Ref->getDecl()); 14684 } 14685 } 14686 if (!IsImplicitClause) 14687 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 14688 Vars.push_back((VD || CurContext->isDependentContext()) 14689 ? RefExpr->IgnoreParens() 14690 : Ref); 14691 PrivateCopies.push_back(VDPrivateRefExpr); 14692 Inits.push_back(VDInitRefExpr); 14693 } 14694 14695 if (Vars.empty()) 14696 return nullptr; 14697 14698 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 14699 Vars, PrivateCopies, Inits, 14700 buildPreInits(Context, ExprCaptures)); 14701 } 14702 14703 OMPClause *Sema::ActOnOpenMPLastprivateClause( 14704 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 14705 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, 14706 SourceLocation LParenLoc, SourceLocation EndLoc) { 14707 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) { 14708 assert(ColonLoc.isValid() && "Colon location must be valid."); 14709 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value) 14710 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0, 14711 /*Last=*/OMPC_LASTPRIVATE_unknown) 14712 << getOpenMPClauseName(OMPC_lastprivate); 14713 return nullptr; 14714 } 14715 14716 SmallVector<Expr *, 8> Vars; 14717 SmallVector<Expr *, 8> SrcExprs; 14718 SmallVector<Expr *, 8> DstExprs; 14719 SmallVector<Expr *, 8> AssignmentOps; 14720 SmallVector<Decl *, 4> ExprCaptures; 14721 SmallVector<Expr *, 4> ExprPostUpdates; 14722 for (Expr *RefExpr : VarList) { 14723 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 14724 SourceLocation ELoc; 14725 SourceRange ERange; 14726 Expr *SimpleRefExpr = RefExpr; 14727 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 14728 if (Res.second) { 14729 // It will be analyzed later. 14730 Vars.push_back(RefExpr); 14731 SrcExprs.push_back(nullptr); 14732 DstExprs.push_back(nullptr); 14733 AssignmentOps.push_back(nullptr); 14734 } 14735 ValueDecl *D = Res.first; 14736 if (!D) 14737 continue; 14738 14739 QualType Type = D->getType(); 14740 auto *VD = dyn_cast<VarDecl>(D); 14741 14742 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 14743 // A variable that appears in a lastprivate clause must not have an 14744 // incomplete type or a reference type. 14745 if (RequireCompleteType(ELoc, Type, 14746 diag::err_omp_lastprivate_incomplete_type)) 14747 continue; 14748 Type = Type.getNonReferenceType(); 14749 14750 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 14751 // A variable that is privatized must not have a const-qualified type 14752 // unless it is of class type with a mutable member. This restriction does 14753 // not apply to the firstprivate clause. 14754 // 14755 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 14756 // A variable that appears in a lastprivate clause must not have a 14757 // const-qualified type unless it is of class type with a mutable member. 14758 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 14759 continue; 14760 14761 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions] 14762 // A list item that appears in a lastprivate clause with the conditional 14763 // modifier must be a scalar variable. 14764 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) { 14765 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar); 14766 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 14767 VarDecl::DeclarationOnly; 14768 Diag(D->getLocation(), 14769 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 14770 << D; 14771 continue; 14772 } 14773 14774 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 14775 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 14776 // in a Construct] 14777 // Variables with the predetermined data-sharing attributes may not be 14778 // listed in data-sharing attributes clauses, except for the cases 14779 // listed below. 14780 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 14781 // A list item may appear in a firstprivate or lastprivate clause but not 14782 // both. 14783 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 14784 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 14785 (isOpenMPDistributeDirective(CurrDir) || 14786 DVar.CKind != OMPC_firstprivate) && 14787 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 14788 Diag(ELoc, diag::err_omp_wrong_dsa) 14789 << getOpenMPClauseName(DVar.CKind) 14790 << getOpenMPClauseName(OMPC_lastprivate); 14791 reportOriginalDsa(*this, DSAStack, D, DVar); 14792 continue; 14793 } 14794 14795 // OpenMP [2.14.3.5, Restrictions, p.2] 14796 // A list item that is private within a parallel region, or that appears in 14797 // the reduction clause of a parallel construct, must not appear in a 14798 // lastprivate clause on a worksharing construct if any of the corresponding 14799 // worksharing regions ever binds to any of the corresponding parallel 14800 // regions. 14801 DSAStackTy::DSAVarData TopDVar = DVar; 14802 if (isOpenMPWorksharingDirective(CurrDir) && 14803 !isOpenMPParallelDirective(CurrDir) && 14804 !isOpenMPTeamsDirective(CurrDir)) { 14805 DVar = DSAStack->getImplicitDSA(D, true); 14806 if (DVar.CKind != OMPC_shared) { 14807 Diag(ELoc, diag::err_omp_required_access) 14808 << getOpenMPClauseName(OMPC_lastprivate) 14809 << getOpenMPClauseName(OMPC_shared); 14810 reportOriginalDsa(*this, DSAStack, D, DVar); 14811 continue; 14812 } 14813 } 14814 14815 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 14816 // A variable of class type (or array thereof) that appears in a 14817 // lastprivate clause requires an accessible, unambiguous default 14818 // constructor for the class type, unless the list item is also specified 14819 // in a firstprivate clause. 14820 // A variable of class type (or array thereof) that appears in a 14821 // lastprivate clause requires an accessible, unambiguous copy assignment 14822 // operator for the class type. 14823 Type = Context.getBaseElementType(Type).getNonReferenceType(); 14824 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 14825 Type.getUnqualifiedType(), ".lastprivate.src", 14826 D->hasAttrs() ? &D->getAttrs() : nullptr); 14827 DeclRefExpr *PseudoSrcExpr = 14828 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 14829 VarDecl *DstVD = 14830 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 14831 D->hasAttrs() ? &D->getAttrs() : nullptr); 14832 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 14833 // For arrays generate assignment operation for single element and replace 14834 // it by the original array element in CodeGen. 14835 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 14836 PseudoDstExpr, PseudoSrcExpr); 14837 if (AssignmentOp.isInvalid()) 14838 continue; 14839 AssignmentOp = 14840 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 14841 if (AssignmentOp.isInvalid()) 14842 continue; 14843 14844 DeclRefExpr *Ref = nullptr; 14845 if (!VD && !CurContext->isDependentContext()) { 14846 if (TopDVar.CKind == OMPC_firstprivate) { 14847 Ref = TopDVar.PrivateCopy; 14848 } else { 14849 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 14850 if (!isOpenMPCapturedDecl(D)) 14851 ExprCaptures.push_back(Ref->getDecl()); 14852 } 14853 if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) || 14854 (!isOpenMPCapturedDecl(D) && 14855 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 14856 ExprResult RefRes = DefaultLvalueConversion(Ref); 14857 if (!RefRes.isUsable()) 14858 continue; 14859 ExprResult PostUpdateRes = 14860 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 14861 RefRes.get()); 14862 if (!PostUpdateRes.isUsable()) 14863 continue; 14864 ExprPostUpdates.push_back( 14865 IgnoredValueConversions(PostUpdateRes.get()).get()); 14866 } 14867 } 14868 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 14869 Vars.push_back((VD || CurContext->isDependentContext()) 14870 ? RefExpr->IgnoreParens() 14871 : Ref); 14872 SrcExprs.push_back(PseudoSrcExpr); 14873 DstExprs.push_back(PseudoDstExpr); 14874 AssignmentOps.push_back(AssignmentOp.get()); 14875 } 14876 14877 if (Vars.empty()) 14878 return nullptr; 14879 14880 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 14881 Vars, SrcExprs, DstExprs, AssignmentOps, 14882 LPKind, LPKindLoc, ColonLoc, 14883 buildPreInits(Context, ExprCaptures), 14884 buildPostUpdate(*this, ExprPostUpdates)); 14885 } 14886 14887 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 14888 SourceLocation StartLoc, 14889 SourceLocation LParenLoc, 14890 SourceLocation EndLoc) { 14891 SmallVector<Expr *, 8> Vars; 14892 for (Expr *RefExpr : VarList) { 14893 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 14894 SourceLocation ELoc; 14895 SourceRange ERange; 14896 Expr *SimpleRefExpr = RefExpr; 14897 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 14898 if (Res.second) { 14899 // It will be analyzed later. 14900 Vars.push_back(RefExpr); 14901 } 14902 ValueDecl *D = Res.first; 14903 if (!D) 14904 continue; 14905 14906 auto *VD = dyn_cast<VarDecl>(D); 14907 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 14908 // in a Construct] 14909 // Variables with the predetermined data-sharing attributes may not be 14910 // listed in data-sharing attributes clauses, except for the cases 14911 // listed below. For these exceptions only, listing a predetermined 14912 // variable in a data-sharing attribute clause is allowed and overrides 14913 // the variable's predetermined data-sharing attributes. 14914 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 14915 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 14916 DVar.RefExpr) { 14917 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 14918 << getOpenMPClauseName(OMPC_shared); 14919 reportOriginalDsa(*this, DSAStack, D, DVar); 14920 continue; 14921 } 14922 14923 DeclRefExpr *Ref = nullptr; 14924 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 14925 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 14926 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 14927 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 14928 ? RefExpr->IgnoreParens() 14929 : Ref); 14930 } 14931 14932 if (Vars.empty()) 14933 return nullptr; 14934 14935 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 14936 } 14937 14938 namespace { 14939 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 14940 DSAStackTy *Stack; 14941 14942 public: 14943 bool VisitDeclRefExpr(DeclRefExpr *E) { 14944 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 14945 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 14946 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 14947 return false; 14948 if (DVar.CKind != OMPC_unknown) 14949 return true; 14950 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 14951 VD, 14952 [](OpenMPClauseKind C, bool AppliedToPointee) { 14953 return isOpenMPPrivate(C) && !AppliedToPointee; 14954 }, 14955 [](OpenMPDirectiveKind) { return true; }, 14956 /*FromParent=*/true); 14957 return DVarPrivate.CKind != OMPC_unknown; 14958 } 14959 return false; 14960 } 14961 bool VisitStmt(Stmt *S) { 14962 for (Stmt *Child : S->children()) { 14963 if (Child && Visit(Child)) 14964 return true; 14965 } 14966 return false; 14967 } 14968 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 14969 }; 14970 } // namespace 14971 14972 namespace { 14973 // Transform MemberExpression for specified FieldDecl of current class to 14974 // DeclRefExpr to specified OMPCapturedExprDecl. 14975 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 14976 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 14977 ValueDecl *Field = nullptr; 14978 DeclRefExpr *CapturedExpr = nullptr; 14979 14980 public: 14981 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 14982 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 14983 14984 ExprResult TransformMemberExpr(MemberExpr *E) { 14985 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 14986 E->getMemberDecl() == Field) { 14987 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 14988 return CapturedExpr; 14989 } 14990 return BaseTransform::TransformMemberExpr(E); 14991 } 14992 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 14993 }; 14994 } // namespace 14995 14996 template <typename T, typename U> 14997 static T filterLookupForUDReductionAndMapper( 14998 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) { 14999 for (U &Set : Lookups) { 15000 for (auto *D : Set) { 15001 if (T Res = Gen(cast<ValueDecl>(D))) 15002 return Res; 15003 } 15004 } 15005 return T(); 15006 } 15007 15008 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 15009 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 15010 15011 for (auto RD : D->redecls()) { 15012 // Don't bother with extra checks if we already know this one isn't visible. 15013 if (RD == D) 15014 continue; 15015 15016 auto ND = cast<NamedDecl>(RD); 15017 if (LookupResult::isVisible(SemaRef, ND)) 15018 return ND; 15019 } 15020 15021 return nullptr; 15022 } 15023 15024 static void 15025 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id, 15026 SourceLocation Loc, QualType Ty, 15027 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 15028 // Find all of the associated namespaces and classes based on the 15029 // arguments we have. 15030 Sema::AssociatedNamespaceSet AssociatedNamespaces; 15031 Sema::AssociatedClassSet AssociatedClasses; 15032 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 15033 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 15034 AssociatedClasses); 15035 15036 // C++ [basic.lookup.argdep]p3: 15037 // Let X be the lookup set produced by unqualified lookup (3.4.1) 15038 // and let Y be the lookup set produced by argument dependent 15039 // lookup (defined as follows). If X contains [...] then Y is 15040 // empty. Otherwise Y is the set of declarations found in the 15041 // namespaces associated with the argument types as described 15042 // below. The set of declarations found by the lookup of the name 15043 // is the union of X and Y. 15044 // 15045 // Here, we compute Y and add its members to the overloaded 15046 // candidate set. 15047 for (auto *NS : AssociatedNamespaces) { 15048 // When considering an associated namespace, the lookup is the 15049 // same as the lookup performed when the associated namespace is 15050 // used as a qualifier (3.4.3.2) except that: 15051 // 15052 // -- Any using-directives in the associated namespace are 15053 // ignored. 15054 // 15055 // -- Any namespace-scope friend functions declared in 15056 // associated classes are visible within their respective 15057 // namespaces even if they are not visible during an ordinary 15058 // lookup (11.4). 15059 DeclContext::lookup_result R = NS->lookup(Id.getName()); 15060 for (auto *D : R) { 15061 auto *Underlying = D; 15062 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 15063 Underlying = USD->getTargetDecl(); 15064 15065 if (!isa<OMPDeclareReductionDecl>(Underlying) && 15066 !isa<OMPDeclareMapperDecl>(Underlying)) 15067 continue; 15068 15069 if (!SemaRef.isVisible(D)) { 15070 D = findAcceptableDecl(SemaRef, D); 15071 if (!D) 15072 continue; 15073 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 15074 Underlying = USD->getTargetDecl(); 15075 } 15076 Lookups.emplace_back(); 15077 Lookups.back().addDecl(Underlying); 15078 } 15079 } 15080 } 15081 15082 static ExprResult 15083 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 15084 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 15085 const DeclarationNameInfo &ReductionId, QualType Ty, 15086 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 15087 if (ReductionIdScopeSpec.isInvalid()) 15088 return ExprError(); 15089 SmallVector<UnresolvedSet<8>, 4> Lookups; 15090 if (S) { 15091 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 15092 Lookup.suppressDiagnostics(); 15093 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 15094 NamedDecl *D = Lookup.getRepresentativeDecl(); 15095 do { 15096 S = S->getParent(); 15097 } while (S && !S->isDeclScope(D)); 15098 if (S) 15099 S = S->getParent(); 15100 Lookups.emplace_back(); 15101 Lookups.back().append(Lookup.begin(), Lookup.end()); 15102 Lookup.clear(); 15103 } 15104 } else if (auto *ULE = 15105 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 15106 Lookups.push_back(UnresolvedSet<8>()); 15107 Decl *PrevD = nullptr; 15108 for (NamedDecl *D : ULE->decls()) { 15109 if (D == PrevD) 15110 Lookups.push_back(UnresolvedSet<8>()); 15111 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D)) 15112 Lookups.back().addDecl(DRD); 15113 PrevD = D; 15114 } 15115 } 15116 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 15117 Ty->isInstantiationDependentType() || 15118 Ty->containsUnexpandedParameterPack() || 15119 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 15120 return !D->isInvalidDecl() && 15121 (D->getType()->isDependentType() || 15122 D->getType()->isInstantiationDependentType() || 15123 D->getType()->containsUnexpandedParameterPack()); 15124 })) { 15125 UnresolvedSet<8> ResSet; 15126 for (const UnresolvedSet<8> &Set : Lookups) { 15127 if (Set.empty()) 15128 continue; 15129 ResSet.append(Set.begin(), Set.end()); 15130 // The last item marks the end of all declarations at the specified scope. 15131 ResSet.addDecl(Set[Set.size() - 1]); 15132 } 15133 return UnresolvedLookupExpr::Create( 15134 SemaRef.Context, /*NamingClass=*/nullptr, 15135 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 15136 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 15137 } 15138 // Lookup inside the classes. 15139 // C++ [over.match.oper]p3: 15140 // For a unary operator @ with an operand of a type whose 15141 // cv-unqualified version is T1, and for a binary operator @ with 15142 // a left operand of a type whose cv-unqualified version is T1 and 15143 // a right operand of a type whose cv-unqualified version is T2, 15144 // three sets of candidate functions, designated member 15145 // candidates, non-member candidates and built-in candidates, are 15146 // constructed as follows: 15147 // -- If T1 is a complete class type or a class currently being 15148 // defined, the set of member candidates is the result of the 15149 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 15150 // the set of member candidates is empty. 15151 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 15152 Lookup.suppressDiagnostics(); 15153 if (const auto *TyRec = Ty->getAs<RecordType>()) { 15154 // Complete the type if it can be completed. 15155 // If the type is neither complete nor being defined, bail out now. 15156 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 15157 TyRec->getDecl()->getDefinition()) { 15158 Lookup.clear(); 15159 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 15160 if (Lookup.empty()) { 15161 Lookups.emplace_back(); 15162 Lookups.back().append(Lookup.begin(), Lookup.end()); 15163 } 15164 } 15165 } 15166 // Perform ADL. 15167 if (SemaRef.getLangOpts().CPlusPlus) 15168 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 15169 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 15170 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 15171 if (!D->isInvalidDecl() && 15172 SemaRef.Context.hasSameType(D->getType(), Ty)) 15173 return D; 15174 return nullptr; 15175 })) 15176 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 15177 VK_LValue, Loc); 15178 if (SemaRef.getLangOpts().CPlusPlus) { 15179 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 15180 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 15181 if (!D->isInvalidDecl() && 15182 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 15183 !Ty.isMoreQualifiedThan(D->getType())) 15184 return D; 15185 return nullptr; 15186 })) { 15187 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 15188 /*DetectVirtual=*/false); 15189 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 15190 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 15191 VD->getType().getUnqualifiedType()))) { 15192 if (SemaRef.CheckBaseClassAccess( 15193 Loc, VD->getType(), Ty, Paths.front(), 15194 /*DiagID=*/0) != Sema::AR_inaccessible) { 15195 SemaRef.BuildBasePathArray(Paths, BasePath); 15196 return SemaRef.BuildDeclRefExpr( 15197 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 15198 } 15199 } 15200 } 15201 } 15202 } 15203 if (ReductionIdScopeSpec.isSet()) { 15204 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) 15205 << Ty << Range; 15206 return ExprError(); 15207 } 15208 return ExprEmpty(); 15209 } 15210 15211 namespace { 15212 /// Data for the reduction-based clauses. 15213 struct ReductionData { 15214 /// List of original reduction items. 15215 SmallVector<Expr *, 8> Vars; 15216 /// List of private copies of the reduction items. 15217 SmallVector<Expr *, 8> Privates; 15218 /// LHS expressions for the reduction_op expressions. 15219 SmallVector<Expr *, 8> LHSs; 15220 /// RHS expressions for the reduction_op expressions. 15221 SmallVector<Expr *, 8> RHSs; 15222 /// Reduction operation expression. 15223 SmallVector<Expr *, 8> ReductionOps; 15224 /// inscan copy operation expressions. 15225 SmallVector<Expr *, 8> InscanCopyOps; 15226 /// inscan copy temp array expressions for prefix sums. 15227 SmallVector<Expr *, 8> InscanCopyArrayTemps; 15228 /// inscan copy temp array element expressions for prefix sums. 15229 SmallVector<Expr *, 8> InscanCopyArrayElems; 15230 /// Taskgroup descriptors for the corresponding reduction items in 15231 /// in_reduction clauses. 15232 SmallVector<Expr *, 8> TaskgroupDescriptors; 15233 /// List of captures for clause. 15234 SmallVector<Decl *, 4> ExprCaptures; 15235 /// List of postupdate expressions. 15236 SmallVector<Expr *, 4> ExprPostUpdates; 15237 /// Reduction modifier. 15238 unsigned RedModifier = 0; 15239 ReductionData() = delete; 15240 /// Reserves required memory for the reduction data. 15241 ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) { 15242 Vars.reserve(Size); 15243 Privates.reserve(Size); 15244 LHSs.reserve(Size); 15245 RHSs.reserve(Size); 15246 ReductionOps.reserve(Size); 15247 if (RedModifier == OMPC_REDUCTION_inscan) { 15248 InscanCopyOps.reserve(Size); 15249 InscanCopyArrayTemps.reserve(Size); 15250 InscanCopyArrayElems.reserve(Size); 15251 } 15252 TaskgroupDescriptors.reserve(Size); 15253 ExprCaptures.reserve(Size); 15254 ExprPostUpdates.reserve(Size); 15255 } 15256 /// Stores reduction item and reduction operation only (required for dependent 15257 /// reduction item). 15258 void push(Expr *Item, Expr *ReductionOp) { 15259 Vars.emplace_back(Item); 15260 Privates.emplace_back(nullptr); 15261 LHSs.emplace_back(nullptr); 15262 RHSs.emplace_back(nullptr); 15263 ReductionOps.emplace_back(ReductionOp); 15264 TaskgroupDescriptors.emplace_back(nullptr); 15265 if (RedModifier == OMPC_REDUCTION_inscan) { 15266 InscanCopyOps.push_back(nullptr); 15267 InscanCopyArrayTemps.push_back(nullptr); 15268 InscanCopyArrayElems.push_back(nullptr); 15269 } 15270 } 15271 /// Stores reduction data. 15272 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 15273 Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp, 15274 Expr *CopyArrayElem) { 15275 Vars.emplace_back(Item); 15276 Privates.emplace_back(Private); 15277 LHSs.emplace_back(LHS); 15278 RHSs.emplace_back(RHS); 15279 ReductionOps.emplace_back(ReductionOp); 15280 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 15281 if (RedModifier == OMPC_REDUCTION_inscan) { 15282 InscanCopyOps.push_back(CopyOp); 15283 InscanCopyArrayTemps.push_back(CopyArrayTemp); 15284 InscanCopyArrayElems.push_back(CopyArrayElem); 15285 } else { 15286 assert(CopyOp == nullptr && CopyArrayTemp == nullptr && 15287 CopyArrayElem == nullptr && 15288 "Copy operation must be used for inscan reductions only."); 15289 } 15290 } 15291 }; 15292 } // namespace 15293 15294 static bool checkOMPArraySectionConstantForReduction( 15295 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 15296 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 15297 const Expr *Length = OASE->getLength(); 15298 if (Length == nullptr) { 15299 // For array sections of the form [1:] or [:], we would need to analyze 15300 // the lower bound... 15301 if (OASE->getColonLocFirst().isValid()) 15302 return false; 15303 15304 // This is an array subscript which has implicit length 1! 15305 SingleElement = true; 15306 ArraySizes.push_back(llvm::APSInt::get(1)); 15307 } else { 15308 Expr::EvalResult Result; 15309 if (!Length->EvaluateAsInt(Result, Context)) 15310 return false; 15311 15312 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 15313 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 15314 ArraySizes.push_back(ConstantLengthValue); 15315 } 15316 15317 // Get the base of this array section and walk up from there. 15318 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 15319 15320 // We require length = 1 for all array sections except the right-most to 15321 // guarantee that the memory region is contiguous and has no holes in it. 15322 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 15323 Length = TempOASE->getLength(); 15324 if (Length == nullptr) { 15325 // For array sections of the form [1:] or [:], we would need to analyze 15326 // the lower bound... 15327 if (OASE->getColonLocFirst().isValid()) 15328 return false; 15329 15330 // This is an array subscript which has implicit length 1! 15331 ArraySizes.push_back(llvm::APSInt::get(1)); 15332 } else { 15333 Expr::EvalResult Result; 15334 if (!Length->EvaluateAsInt(Result, Context)) 15335 return false; 15336 15337 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 15338 if (ConstantLengthValue.getSExtValue() != 1) 15339 return false; 15340 15341 ArraySizes.push_back(ConstantLengthValue); 15342 } 15343 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 15344 } 15345 15346 // If we have a single element, we don't need to add the implicit lengths. 15347 if (!SingleElement) { 15348 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 15349 // Has implicit length 1! 15350 ArraySizes.push_back(llvm::APSInt::get(1)); 15351 Base = TempASE->getBase()->IgnoreParenImpCasts(); 15352 } 15353 } 15354 15355 // This array section can be privatized as a single value or as a constant 15356 // sized array. 15357 return true; 15358 } 15359 15360 static bool actOnOMPReductionKindClause( 15361 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 15362 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 15363 SourceLocation ColonLoc, SourceLocation EndLoc, 15364 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 15365 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 15366 DeclarationName DN = ReductionId.getName(); 15367 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 15368 BinaryOperatorKind BOK = BO_Comma; 15369 15370 ASTContext &Context = S.Context; 15371 // OpenMP [2.14.3.6, reduction clause] 15372 // C 15373 // reduction-identifier is either an identifier or one of the following 15374 // operators: +, -, *, &, |, ^, && and || 15375 // C++ 15376 // reduction-identifier is either an id-expression or one of the following 15377 // operators: +, -, *, &, |, ^, && and || 15378 switch (OOK) { 15379 case OO_Plus: 15380 case OO_Minus: 15381 BOK = BO_Add; 15382 break; 15383 case OO_Star: 15384 BOK = BO_Mul; 15385 break; 15386 case OO_Amp: 15387 BOK = BO_And; 15388 break; 15389 case OO_Pipe: 15390 BOK = BO_Or; 15391 break; 15392 case OO_Caret: 15393 BOK = BO_Xor; 15394 break; 15395 case OO_AmpAmp: 15396 BOK = BO_LAnd; 15397 break; 15398 case OO_PipePipe: 15399 BOK = BO_LOr; 15400 break; 15401 case OO_New: 15402 case OO_Delete: 15403 case OO_Array_New: 15404 case OO_Array_Delete: 15405 case OO_Slash: 15406 case OO_Percent: 15407 case OO_Tilde: 15408 case OO_Exclaim: 15409 case OO_Equal: 15410 case OO_Less: 15411 case OO_Greater: 15412 case OO_LessEqual: 15413 case OO_GreaterEqual: 15414 case OO_PlusEqual: 15415 case OO_MinusEqual: 15416 case OO_StarEqual: 15417 case OO_SlashEqual: 15418 case OO_PercentEqual: 15419 case OO_CaretEqual: 15420 case OO_AmpEqual: 15421 case OO_PipeEqual: 15422 case OO_LessLess: 15423 case OO_GreaterGreater: 15424 case OO_LessLessEqual: 15425 case OO_GreaterGreaterEqual: 15426 case OO_EqualEqual: 15427 case OO_ExclaimEqual: 15428 case OO_Spaceship: 15429 case OO_PlusPlus: 15430 case OO_MinusMinus: 15431 case OO_Comma: 15432 case OO_ArrowStar: 15433 case OO_Arrow: 15434 case OO_Call: 15435 case OO_Subscript: 15436 case OO_Conditional: 15437 case OO_Coawait: 15438 case NUM_OVERLOADED_OPERATORS: 15439 llvm_unreachable("Unexpected reduction identifier"); 15440 case OO_None: 15441 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 15442 if (II->isStr("max")) 15443 BOK = BO_GT; 15444 else if (II->isStr("min")) 15445 BOK = BO_LT; 15446 } 15447 break; 15448 } 15449 SourceRange ReductionIdRange; 15450 if (ReductionIdScopeSpec.isValid()) 15451 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 15452 else 15453 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 15454 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 15455 15456 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 15457 bool FirstIter = true; 15458 for (Expr *RefExpr : VarList) { 15459 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 15460 // OpenMP [2.1, C/C++] 15461 // A list item is a variable or array section, subject to the restrictions 15462 // specified in Section 2.4 on page 42 and in each of the sections 15463 // describing clauses and directives for which a list appears. 15464 // OpenMP [2.14.3.3, Restrictions, p.1] 15465 // A variable that is part of another variable (as an array or 15466 // structure element) cannot appear in a private clause. 15467 if (!FirstIter && IR != ER) 15468 ++IR; 15469 FirstIter = false; 15470 SourceLocation ELoc; 15471 SourceRange ERange; 15472 Expr *SimpleRefExpr = RefExpr; 15473 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 15474 /*AllowArraySection=*/true); 15475 if (Res.second) { 15476 // Try to find 'declare reduction' corresponding construct before using 15477 // builtin/overloaded operators. 15478 QualType Type = Context.DependentTy; 15479 CXXCastPath BasePath; 15480 ExprResult DeclareReductionRef = buildDeclareReductionRef( 15481 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 15482 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 15483 Expr *ReductionOp = nullptr; 15484 if (S.CurContext->isDependentContext() && 15485 (DeclareReductionRef.isUnset() || 15486 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 15487 ReductionOp = DeclareReductionRef.get(); 15488 // It will be analyzed later. 15489 RD.push(RefExpr, ReductionOp); 15490 } 15491 ValueDecl *D = Res.first; 15492 if (!D) 15493 continue; 15494 15495 Expr *TaskgroupDescriptor = nullptr; 15496 QualType Type; 15497 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 15498 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 15499 if (ASE) { 15500 Type = ASE->getType().getNonReferenceType(); 15501 } else if (OASE) { 15502 QualType BaseType = 15503 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 15504 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 15505 Type = ATy->getElementType(); 15506 else 15507 Type = BaseType->getPointeeType(); 15508 Type = Type.getNonReferenceType(); 15509 } else { 15510 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 15511 } 15512 auto *VD = dyn_cast<VarDecl>(D); 15513 15514 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 15515 // A variable that appears in a private clause must not have an incomplete 15516 // type or a reference type. 15517 if (S.RequireCompleteType(ELoc, D->getType(), 15518 diag::err_omp_reduction_incomplete_type)) 15519 continue; 15520 // OpenMP [2.14.3.6, reduction clause, Restrictions] 15521 // A list item that appears in a reduction clause must not be 15522 // const-qualified. 15523 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 15524 /*AcceptIfMutable*/ false, ASE || OASE)) 15525 continue; 15526 15527 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 15528 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 15529 // If a list-item is a reference type then it must bind to the same object 15530 // for all threads of the team. 15531 if (!ASE && !OASE) { 15532 if (VD) { 15533 VarDecl *VDDef = VD->getDefinition(); 15534 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 15535 DSARefChecker Check(Stack); 15536 if (Check.Visit(VDDef->getInit())) { 15537 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 15538 << getOpenMPClauseName(ClauseKind) << ERange; 15539 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 15540 continue; 15541 } 15542 } 15543 } 15544 15545 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 15546 // in a Construct] 15547 // Variables with the predetermined data-sharing attributes may not be 15548 // listed in data-sharing attributes clauses, except for the cases 15549 // listed below. For these exceptions only, listing a predetermined 15550 // variable in a data-sharing attribute clause is allowed and overrides 15551 // the variable's predetermined data-sharing attributes. 15552 // OpenMP [2.14.3.6, Restrictions, p.3] 15553 // Any number of reduction clauses can be specified on the directive, 15554 // but a list item can appear only once in the reduction clauses for that 15555 // directive. 15556 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 15557 if (DVar.CKind == OMPC_reduction) { 15558 S.Diag(ELoc, diag::err_omp_once_referenced) 15559 << getOpenMPClauseName(ClauseKind); 15560 if (DVar.RefExpr) 15561 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 15562 continue; 15563 } 15564 if (DVar.CKind != OMPC_unknown) { 15565 S.Diag(ELoc, diag::err_omp_wrong_dsa) 15566 << getOpenMPClauseName(DVar.CKind) 15567 << getOpenMPClauseName(OMPC_reduction); 15568 reportOriginalDsa(S, Stack, D, DVar); 15569 continue; 15570 } 15571 15572 // OpenMP [2.14.3.6, Restrictions, p.1] 15573 // A list item that appears in a reduction clause of a worksharing 15574 // construct must be shared in the parallel regions to which any of the 15575 // worksharing regions arising from the worksharing construct bind. 15576 if (isOpenMPWorksharingDirective(CurrDir) && 15577 !isOpenMPParallelDirective(CurrDir) && 15578 !isOpenMPTeamsDirective(CurrDir)) { 15579 DVar = Stack->getImplicitDSA(D, true); 15580 if (DVar.CKind != OMPC_shared) { 15581 S.Diag(ELoc, diag::err_omp_required_access) 15582 << getOpenMPClauseName(OMPC_reduction) 15583 << getOpenMPClauseName(OMPC_shared); 15584 reportOriginalDsa(S, Stack, D, DVar); 15585 continue; 15586 } 15587 } 15588 } else { 15589 // Threadprivates cannot be shared between threads, so dignose if the base 15590 // is a threadprivate variable. 15591 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 15592 if (DVar.CKind == OMPC_threadprivate) { 15593 S.Diag(ELoc, diag::err_omp_wrong_dsa) 15594 << getOpenMPClauseName(DVar.CKind) 15595 << getOpenMPClauseName(OMPC_reduction); 15596 reportOriginalDsa(S, Stack, D, DVar); 15597 continue; 15598 } 15599 } 15600 15601 // Try to find 'declare reduction' corresponding construct before using 15602 // builtin/overloaded operators. 15603 CXXCastPath BasePath; 15604 ExprResult DeclareReductionRef = buildDeclareReductionRef( 15605 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 15606 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 15607 if (DeclareReductionRef.isInvalid()) 15608 continue; 15609 if (S.CurContext->isDependentContext() && 15610 (DeclareReductionRef.isUnset() || 15611 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 15612 RD.push(RefExpr, DeclareReductionRef.get()); 15613 continue; 15614 } 15615 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 15616 // Not allowed reduction identifier is found. 15617 S.Diag(ReductionId.getBeginLoc(), 15618 diag::err_omp_unknown_reduction_identifier) 15619 << Type << ReductionIdRange; 15620 continue; 15621 } 15622 15623 // OpenMP [2.14.3.6, reduction clause, Restrictions] 15624 // The type of a list item that appears in a reduction clause must be valid 15625 // for the reduction-identifier. For a max or min reduction in C, the type 15626 // of the list item must be an allowed arithmetic data type: char, int, 15627 // float, double, or _Bool, possibly modified with long, short, signed, or 15628 // unsigned. For a max or min reduction in C++, the type of the list item 15629 // must be an allowed arithmetic data type: char, wchar_t, int, float, 15630 // double, or bool, possibly modified with long, short, signed, or unsigned. 15631 if (DeclareReductionRef.isUnset()) { 15632 if ((BOK == BO_GT || BOK == BO_LT) && 15633 !(Type->isScalarType() || 15634 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 15635 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 15636 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 15637 if (!ASE && !OASE) { 15638 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 15639 VarDecl::DeclarationOnly; 15640 S.Diag(D->getLocation(), 15641 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15642 << D; 15643 } 15644 continue; 15645 } 15646 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 15647 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 15648 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 15649 << getOpenMPClauseName(ClauseKind); 15650 if (!ASE && !OASE) { 15651 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 15652 VarDecl::DeclarationOnly; 15653 S.Diag(D->getLocation(), 15654 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15655 << D; 15656 } 15657 continue; 15658 } 15659 } 15660 15661 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 15662 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 15663 D->hasAttrs() ? &D->getAttrs() : nullptr); 15664 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 15665 D->hasAttrs() ? &D->getAttrs() : nullptr); 15666 QualType PrivateTy = Type; 15667 15668 // Try if we can determine constant lengths for all array sections and avoid 15669 // the VLA. 15670 bool ConstantLengthOASE = false; 15671 if (OASE) { 15672 bool SingleElement; 15673 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 15674 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 15675 Context, OASE, SingleElement, ArraySizes); 15676 15677 // If we don't have a single element, we must emit a constant array type. 15678 if (ConstantLengthOASE && !SingleElement) { 15679 for (llvm::APSInt &Size : ArraySizes) 15680 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr, 15681 ArrayType::Normal, 15682 /*IndexTypeQuals=*/0); 15683 } 15684 } 15685 15686 if ((OASE && !ConstantLengthOASE) || 15687 (!OASE && !ASE && 15688 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 15689 if (!Context.getTargetInfo().isVLASupported()) { 15690 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) { 15691 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 15692 S.Diag(ELoc, diag::note_vla_unsupported); 15693 continue; 15694 } else { 15695 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 15696 S.targetDiag(ELoc, diag::note_vla_unsupported); 15697 } 15698 } 15699 // For arrays/array sections only: 15700 // Create pseudo array type for private copy. The size for this array will 15701 // be generated during codegen. 15702 // For array subscripts or single variables Private Ty is the same as Type 15703 // (type of the variable or single array element). 15704 PrivateTy = Context.getVariableArrayType( 15705 Type, 15706 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue), 15707 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 15708 } else if (!ASE && !OASE && 15709 Context.getAsArrayType(D->getType().getNonReferenceType())) { 15710 PrivateTy = D->getType().getNonReferenceType(); 15711 } 15712 // Private copy. 15713 VarDecl *PrivateVD = 15714 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 15715 D->hasAttrs() ? &D->getAttrs() : nullptr, 15716 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 15717 // Add initializer for private variable. 15718 Expr *Init = nullptr; 15719 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 15720 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 15721 if (DeclareReductionRef.isUsable()) { 15722 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 15723 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 15724 if (DRD->getInitializer()) { 15725 S.ActOnUninitializedDecl(PrivateVD); 15726 Init = DRDRef; 15727 RHSVD->setInit(DRDRef); 15728 RHSVD->setInitStyle(VarDecl::CallInit); 15729 } 15730 } else { 15731 switch (BOK) { 15732 case BO_Add: 15733 case BO_Xor: 15734 case BO_Or: 15735 case BO_LOr: 15736 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 15737 if (Type->isScalarType() || Type->isAnyComplexType()) 15738 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 15739 break; 15740 case BO_Mul: 15741 case BO_LAnd: 15742 if (Type->isScalarType() || Type->isAnyComplexType()) { 15743 // '*' and '&&' reduction ops - initializer is '1'. 15744 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 15745 } 15746 break; 15747 case BO_And: { 15748 // '&' reduction op - initializer is '~0'. 15749 QualType OrigType = Type; 15750 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 15751 Type = ComplexTy->getElementType(); 15752 if (Type->isRealFloatingType()) { 15753 llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue( 15754 Context.getFloatTypeSemantics(Type), 15755 Context.getTypeSize(Type)); 15756 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 15757 Type, ELoc); 15758 } else if (Type->isScalarType()) { 15759 uint64_t Size = Context.getTypeSize(Type); 15760 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 15761 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 15762 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 15763 } 15764 if (Init && OrigType->isAnyComplexType()) { 15765 // Init = 0xFFFF + 0xFFFFi; 15766 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 15767 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 15768 } 15769 Type = OrigType; 15770 break; 15771 } 15772 case BO_LT: 15773 case BO_GT: { 15774 // 'min' reduction op - initializer is 'Largest representable number in 15775 // the reduction list item type'. 15776 // 'max' reduction op - initializer is 'Least representable number in 15777 // the reduction list item type'. 15778 if (Type->isIntegerType() || Type->isPointerType()) { 15779 bool IsSigned = Type->hasSignedIntegerRepresentation(); 15780 uint64_t Size = Context.getTypeSize(Type); 15781 QualType IntTy = 15782 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 15783 llvm::APInt InitValue = 15784 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 15785 : llvm::APInt::getMinValue(Size) 15786 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 15787 : llvm::APInt::getMaxValue(Size); 15788 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 15789 if (Type->isPointerType()) { 15790 // Cast to pointer type. 15791 ExprResult CastExpr = S.BuildCStyleCastExpr( 15792 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 15793 if (CastExpr.isInvalid()) 15794 continue; 15795 Init = CastExpr.get(); 15796 } 15797 } else if (Type->isRealFloatingType()) { 15798 llvm::APFloat InitValue = llvm::APFloat::getLargest( 15799 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 15800 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 15801 Type, ELoc); 15802 } 15803 break; 15804 } 15805 case BO_PtrMemD: 15806 case BO_PtrMemI: 15807 case BO_MulAssign: 15808 case BO_Div: 15809 case BO_Rem: 15810 case BO_Sub: 15811 case BO_Shl: 15812 case BO_Shr: 15813 case BO_LE: 15814 case BO_GE: 15815 case BO_EQ: 15816 case BO_NE: 15817 case BO_Cmp: 15818 case BO_AndAssign: 15819 case BO_XorAssign: 15820 case BO_OrAssign: 15821 case BO_Assign: 15822 case BO_AddAssign: 15823 case BO_SubAssign: 15824 case BO_DivAssign: 15825 case BO_RemAssign: 15826 case BO_ShlAssign: 15827 case BO_ShrAssign: 15828 case BO_Comma: 15829 llvm_unreachable("Unexpected reduction operation"); 15830 } 15831 } 15832 if (Init && DeclareReductionRef.isUnset()) { 15833 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 15834 // Store initializer for single element in private copy. Will be used 15835 // during codegen. 15836 PrivateVD->setInit(RHSVD->getInit()); 15837 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 15838 } else if (!Init) { 15839 S.ActOnUninitializedDecl(RHSVD); 15840 // Store initializer for single element in private copy. Will be used 15841 // during codegen. 15842 PrivateVD->setInit(RHSVD->getInit()); 15843 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 15844 } 15845 if (RHSVD->isInvalidDecl()) 15846 continue; 15847 if (!RHSVD->hasInit() && 15848 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) { 15849 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 15850 << Type << ReductionIdRange; 15851 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 15852 VarDecl::DeclarationOnly; 15853 S.Diag(D->getLocation(), 15854 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15855 << D; 15856 continue; 15857 } 15858 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 15859 ExprResult ReductionOp; 15860 if (DeclareReductionRef.isUsable()) { 15861 QualType RedTy = DeclareReductionRef.get()->getType(); 15862 QualType PtrRedTy = Context.getPointerType(RedTy); 15863 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 15864 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 15865 if (!BasePath.empty()) { 15866 LHS = S.DefaultLvalueConversion(LHS.get()); 15867 RHS = S.DefaultLvalueConversion(RHS.get()); 15868 LHS = ImplicitCastExpr::Create( 15869 Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath, 15870 LHS.get()->getValueKind(), FPOptionsOverride()); 15871 RHS = ImplicitCastExpr::Create( 15872 Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath, 15873 RHS.get()->getValueKind(), FPOptionsOverride()); 15874 } 15875 FunctionProtoType::ExtProtoInfo EPI; 15876 QualType Params[] = {PtrRedTy, PtrRedTy}; 15877 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 15878 auto *OVE = new (Context) OpaqueValueExpr( 15879 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 15880 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 15881 Expr *Args[] = {LHS.get(), RHS.get()}; 15882 ReductionOp = 15883 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc, 15884 S.CurFPFeatureOverrides()); 15885 } else { 15886 ReductionOp = S.BuildBinOp( 15887 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE); 15888 if (ReductionOp.isUsable()) { 15889 if (BOK != BO_LT && BOK != BO_GT) { 15890 ReductionOp = 15891 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 15892 BO_Assign, LHSDRE, ReductionOp.get()); 15893 } else { 15894 auto *ConditionalOp = new (Context) 15895 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE, 15896 Type, VK_LValue, OK_Ordinary); 15897 ReductionOp = 15898 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 15899 BO_Assign, LHSDRE, ConditionalOp); 15900 } 15901 if (ReductionOp.isUsable()) 15902 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 15903 /*DiscardedValue*/ false); 15904 } 15905 if (!ReductionOp.isUsable()) 15906 continue; 15907 } 15908 15909 // Add copy operations for inscan reductions. 15910 // LHS = RHS; 15911 ExprResult CopyOpRes, TempArrayRes, TempArrayElem; 15912 if (ClauseKind == OMPC_reduction && 15913 RD.RedModifier == OMPC_REDUCTION_inscan) { 15914 ExprResult RHS = S.DefaultLvalueConversion(RHSDRE); 15915 CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE, 15916 RHS.get()); 15917 if (!CopyOpRes.isUsable()) 15918 continue; 15919 CopyOpRes = 15920 S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true); 15921 if (!CopyOpRes.isUsable()) 15922 continue; 15923 // For simd directive and simd-based directives in simd mode no need to 15924 // construct temp array, need just a single temp element. 15925 if (Stack->getCurrentDirective() == OMPD_simd || 15926 (S.getLangOpts().OpenMPSimd && 15927 isOpenMPSimdDirective(Stack->getCurrentDirective()))) { 15928 VarDecl *TempArrayVD = 15929 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 15930 D->hasAttrs() ? &D->getAttrs() : nullptr); 15931 // Add a constructor to the temp decl. 15932 S.ActOnUninitializedDecl(TempArrayVD); 15933 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc); 15934 } else { 15935 // Build temp array for prefix sum. 15936 auto *Dim = new (S.Context) 15937 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue); 15938 QualType ArrayTy = 15939 S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal, 15940 /*IndexTypeQuals=*/0, {ELoc, ELoc}); 15941 VarDecl *TempArrayVD = 15942 buildVarDecl(S, ELoc, ArrayTy, D->getName(), 15943 D->hasAttrs() ? &D->getAttrs() : nullptr); 15944 // Add a constructor to the temp decl. 15945 S.ActOnUninitializedDecl(TempArrayVD); 15946 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc); 15947 TempArrayElem = 15948 S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get()); 15949 auto *Idx = new (S.Context) 15950 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue); 15951 TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(), 15952 ELoc, Idx, ELoc); 15953 } 15954 } 15955 15956 // OpenMP [2.15.4.6, Restrictions, p.2] 15957 // A list item that appears in an in_reduction clause of a task construct 15958 // must appear in a task_reduction clause of a construct associated with a 15959 // taskgroup region that includes the participating task in its taskgroup 15960 // set. The construct associated with the innermost region that meets this 15961 // condition must specify the same reduction-identifier as the in_reduction 15962 // clause. 15963 if (ClauseKind == OMPC_in_reduction) { 15964 SourceRange ParentSR; 15965 BinaryOperatorKind ParentBOK; 15966 const Expr *ParentReductionOp = nullptr; 15967 Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr; 15968 DSAStackTy::DSAVarData ParentBOKDSA = 15969 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 15970 ParentBOKTD); 15971 DSAStackTy::DSAVarData ParentReductionOpDSA = 15972 Stack->getTopMostTaskgroupReductionData( 15973 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 15974 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 15975 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 15976 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 15977 (DeclareReductionRef.isUsable() && IsParentBOK) || 15978 (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) { 15979 bool EmitError = true; 15980 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 15981 llvm::FoldingSetNodeID RedId, ParentRedId; 15982 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 15983 DeclareReductionRef.get()->Profile(RedId, Context, 15984 /*Canonical=*/true); 15985 EmitError = RedId != ParentRedId; 15986 } 15987 if (EmitError) { 15988 S.Diag(ReductionId.getBeginLoc(), 15989 diag::err_omp_reduction_identifier_mismatch) 15990 << ReductionIdRange << RefExpr->getSourceRange(); 15991 S.Diag(ParentSR.getBegin(), 15992 diag::note_omp_previous_reduction_identifier) 15993 << ParentSR 15994 << (IsParentBOK ? ParentBOKDSA.RefExpr 15995 : ParentReductionOpDSA.RefExpr) 15996 ->getSourceRange(); 15997 continue; 15998 } 15999 } 16000 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 16001 } 16002 16003 DeclRefExpr *Ref = nullptr; 16004 Expr *VarsExpr = RefExpr->IgnoreParens(); 16005 if (!VD && !S.CurContext->isDependentContext()) { 16006 if (ASE || OASE) { 16007 TransformExprToCaptures RebuildToCapture(S, D); 16008 VarsExpr = 16009 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 16010 Ref = RebuildToCapture.getCapturedExpr(); 16011 } else { 16012 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 16013 } 16014 if (!S.isOpenMPCapturedDecl(D)) { 16015 RD.ExprCaptures.emplace_back(Ref->getDecl()); 16016 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 16017 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 16018 if (!RefRes.isUsable()) 16019 continue; 16020 ExprResult PostUpdateRes = 16021 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 16022 RefRes.get()); 16023 if (!PostUpdateRes.isUsable()) 16024 continue; 16025 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 16026 Stack->getCurrentDirective() == OMPD_taskgroup) { 16027 S.Diag(RefExpr->getExprLoc(), 16028 diag::err_omp_reduction_non_addressable_expression) 16029 << RefExpr->getSourceRange(); 16030 continue; 16031 } 16032 RD.ExprPostUpdates.emplace_back( 16033 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 16034 } 16035 } 16036 } 16037 // All reduction items are still marked as reduction (to do not increase 16038 // code base size). 16039 unsigned Modifier = RD.RedModifier; 16040 // Consider task_reductions as reductions with task modifier. Required for 16041 // correct analysis of in_reduction clauses. 16042 if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction) 16043 Modifier = OMPC_REDUCTION_task; 16044 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier, 16045 ASE || OASE); 16046 if (Modifier == OMPC_REDUCTION_task && 16047 (CurrDir == OMPD_taskgroup || 16048 ((isOpenMPParallelDirective(CurrDir) || 16049 isOpenMPWorksharingDirective(CurrDir)) && 16050 !isOpenMPSimdDirective(CurrDir)))) { 16051 if (DeclareReductionRef.isUsable()) 16052 Stack->addTaskgroupReductionData(D, ReductionIdRange, 16053 DeclareReductionRef.get()); 16054 else 16055 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 16056 } 16057 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 16058 TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(), 16059 TempArrayElem.get()); 16060 } 16061 return RD.Vars.empty(); 16062 } 16063 16064 OMPClause *Sema::ActOnOpenMPReductionClause( 16065 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 16066 SourceLocation StartLoc, SourceLocation LParenLoc, 16067 SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 16068 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 16069 ArrayRef<Expr *> UnresolvedReductions) { 16070 if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) { 16071 Diag(LParenLoc, diag::err_omp_unexpected_clause_value) 16072 << getListOfPossibleValues(OMPC_reduction, /*First=*/0, 16073 /*Last=*/OMPC_REDUCTION_unknown) 16074 << getOpenMPClauseName(OMPC_reduction); 16075 return nullptr; 16076 } 16077 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions 16078 // A reduction clause with the inscan reduction-modifier may only appear on a 16079 // worksharing-loop construct, a worksharing-loop SIMD construct, a simd 16080 // construct, a parallel worksharing-loop construct or a parallel 16081 // worksharing-loop SIMD construct. 16082 if (Modifier == OMPC_REDUCTION_inscan && 16083 (DSAStack->getCurrentDirective() != OMPD_for && 16084 DSAStack->getCurrentDirective() != OMPD_for_simd && 16085 DSAStack->getCurrentDirective() != OMPD_simd && 16086 DSAStack->getCurrentDirective() != OMPD_parallel_for && 16087 DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) { 16088 Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction); 16089 return nullptr; 16090 } 16091 16092 ReductionData RD(VarList.size(), Modifier); 16093 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 16094 StartLoc, LParenLoc, ColonLoc, EndLoc, 16095 ReductionIdScopeSpec, ReductionId, 16096 UnresolvedReductions, RD)) 16097 return nullptr; 16098 16099 return OMPReductionClause::Create( 16100 Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier, 16101 RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 16102 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps, 16103 RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems, 16104 buildPreInits(Context, RD.ExprCaptures), 16105 buildPostUpdate(*this, RD.ExprPostUpdates)); 16106 } 16107 16108 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 16109 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 16110 SourceLocation ColonLoc, SourceLocation EndLoc, 16111 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 16112 ArrayRef<Expr *> UnresolvedReductions) { 16113 ReductionData RD(VarList.size()); 16114 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 16115 StartLoc, LParenLoc, ColonLoc, EndLoc, 16116 ReductionIdScopeSpec, ReductionId, 16117 UnresolvedReductions, RD)) 16118 return nullptr; 16119 16120 return OMPTaskReductionClause::Create( 16121 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 16122 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 16123 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 16124 buildPreInits(Context, RD.ExprCaptures), 16125 buildPostUpdate(*this, RD.ExprPostUpdates)); 16126 } 16127 16128 OMPClause *Sema::ActOnOpenMPInReductionClause( 16129 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 16130 SourceLocation ColonLoc, SourceLocation EndLoc, 16131 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 16132 ArrayRef<Expr *> UnresolvedReductions) { 16133 ReductionData RD(VarList.size()); 16134 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 16135 StartLoc, LParenLoc, ColonLoc, EndLoc, 16136 ReductionIdScopeSpec, ReductionId, 16137 UnresolvedReductions, RD)) 16138 return nullptr; 16139 16140 return OMPInReductionClause::Create( 16141 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 16142 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 16143 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 16144 buildPreInits(Context, RD.ExprCaptures), 16145 buildPostUpdate(*this, RD.ExprPostUpdates)); 16146 } 16147 16148 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 16149 SourceLocation LinLoc) { 16150 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 16151 LinKind == OMPC_LINEAR_unknown) { 16152 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 16153 return true; 16154 } 16155 return false; 16156 } 16157 16158 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 16159 OpenMPLinearClauseKind LinKind, QualType Type, 16160 bool IsDeclareSimd) { 16161 const auto *VD = dyn_cast_or_null<VarDecl>(D); 16162 // A variable must not have an incomplete type or a reference type. 16163 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 16164 return true; 16165 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 16166 !Type->isReferenceType()) { 16167 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 16168 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 16169 return true; 16170 } 16171 Type = Type.getNonReferenceType(); 16172 16173 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 16174 // A variable that is privatized must not have a const-qualified type 16175 // unless it is of class type with a mutable member. This restriction does 16176 // not apply to the firstprivate clause, nor to the linear clause on 16177 // declarative directives (like declare simd). 16178 if (!IsDeclareSimd && 16179 rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 16180 return true; 16181 16182 // A list item must be of integral or pointer type. 16183 Type = Type.getUnqualifiedType().getCanonicalType(); 16184 const auto *Ty = Type.getTypePtrOrNull(); 16185 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() && 16186 !Ty->isIntegralType(Context) && !Ty->isPointerType())) { 16187 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 16188 if (D) { 16189 bool IsDecl = 16190 !VD || 16191 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 16192 Diag(D->getLocation(), 16193 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16194 << D; 16195 } 16196 return true; 16197 } 16198 return false; 16199 } 16200 16201 OMPClause *Sema::ActOnOpenMPLinearClause( 16202 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 16203 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 16204 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 16205 SmallVector<Expr *, 8> Vars; 16206 SmallVector<Expr *, 8> Privates; 16207 SmallVector<Expr *, 8> Inits; 16208 SmallVector<Decl *, 4> ExprCaptures; 16209 SmallVector<Expr *, 4> ExprPostUpdates; 16210 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 16211 LinKind = OMPC_LINEAR_val; 16212 for (Expr *RefExpr : VarList) { 16213 assert(RefExpr && "NULL expr in OpenMP linear clause."); 16214 SourceLocation ELoc; 16215 SourceRange ERange; 16216 Expr *SimpleRefExpr = RefExpr; 16217 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16218 if (Res.second) { 16219 // It will be analyzed later. 16220 Vars.push_back(RefExpr); 16221 Privates.push_back(nullptr); 16222 Inits.push_back(nullptr); 16223 } 16224 ValueDecl *D = Res.first; 16225 if (!D) 16226 continue; 16227 16228 QualType Type = D->getType(); 16229 auto *VD = dyn_cast<VarDecl>(D); 16230 16231 // OpenMP [2.14.3.7, linear clause] 16232 // A list-item cannot appear in more than one linear clause. 16233 // A list-item that appears in a linear clause cannot appear in any 16234 // other data-sharing attribute clause. 16235 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 16236 if (DVar.RefExpr) { 16237 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 16238 << getOpenMPClauseName(OMPC_linear); 16239 reportOriginalDsa(*this, DSAStack, D, DVar); 16240 continue; 16241 } 16242 16243 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 16244 continue; 16245 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 16246 16247 // Build private copy of original var. 16248 VarDecl *Private = 16249 buildVarDecl(*this, ELoc, Type, D->getName(), 16250 D->hasAttrs() ? &D->getAttrs() : nullptr, 16251 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 16252 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 16253 // Build var to save initial value. 16254 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 16255 Expr *InitExpr; 16256 DeclRefExpr *Ref = nullptr; 16257 if (!VD && !CurContext->isDependentContext()) { 16258 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 16259 if (!isOpenMPCapturedDecl(D)) { 16260 ExprCaptures.push_back(Ref->getDecl()); 16261 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 16262 ExprResult RefRes = DefaultLvalueConversion(Ref); 16263 if (!RefRes.isUsable()) 16264 continue; 16265 ExprResult PostUpdateRes = 16266 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 16267 SimpleRefExpr, RefRes.get()); 16268 if (!PostUpdateRes.isUsable()) 16269 continue; 16270 ExprPostUpdates.push_back( 16271 IgnoredValueConversions(PostUpdateRes.get()).get()); 16272 } 16273 } 16274 } 16275 if (LinKind == OMPC_LINEAR_uval) 16276 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 16277 else 16278 InitExpr = VD ? SimpleRefExpr : Ref; 16279 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 16280 /*DirectInit=*/false); 16281 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 16282 16283 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 16284 Vars.push_back((VD || CurContext->isDependentContext()) 16285 ? RefExpr->IgnoreParens() 16286 : Ref); 16287 Privates.push_back(PrivateRef); 16288 Inits.push_back(InitRef); 16289 } 16290 16291 if (Vars.empty()) 16292 return nullptr; 16293 16294 Expr *StepExpr = Step; 16295 Expr *CalcStepExpr = nullptr; 16296 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 16297 !Step->isInstantiationDependent() && 16298 !Step->containsUnexpandedParameterPack()) { 16299 SourceLocation StepLoc = Step->getBeginLoc(); 16300 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 16301 if (Val.isInvalid()) 16302 return nullptr; 16303 StepExpr = Val.get(); 16304 16305 // Build var to save the step value. 16306 VarDecl *SaveVar = 16307 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 16308 ExprResult SaveRef = 16309 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 16310 ExprResult CalcStep = 16311 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 16312 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 16313 16314 // Warn about zero linear step (it would be probably better specified as 16315 // making corresponding variables 'const'). 16316 if (Optional<llvm::APSInt> Result = 16317 StepExpr->getIntegerConstantExpr(Context)) { 16318 if (!Result->isNegative() && !Result->isStrictlyPositive()) 16319 Diag(StepLoc, diag::warn_omp_linear_step_zero) 16320 << Vars[0] << (Vars.size() > 1); 16321 } else if (CalcStep.isUsable()) { 16322 // Calculate the step beforehand instead of doing this on each iteration. 16323 // (This is not used if the number of iterations may be kfold-ed). 16324 CalcStepExpr = CalcStep.get(); 16325 } 16326 } 16327 16328 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 16329 ColonLoc, EndLoc, Vars, Privates, Inits, 16330 StepExpr, CalcStepExpr, 16331 buildPreInits(Context, ExprCaptures), 16332 buildPostUpdate(*this, ExprPostUpdates)); 16333 } 16334 16335 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 16336 Expr *NumIterations, Sema &SemaRef, 16337 Scope *S, DSAStackTy *Stack) { 16338 // Walk the vars and build update/final expressions for the CodeGen. 16339 SmallVector<Expr *, 8> Updates; 16340 SmallVector<Expr *, 8> Finals; 16341 SmallVector<Expr *, 8> UsedExprs; 16342 Expr *Step = Clause.getStep(); 16343 Expr *CalcStep = Clause.getCalcStep(); 16344 // OpenMP [2.14.3.7, linear clause] 16345 // If linear-step is not specified it is assumed to be 1. 16346 if (!Step) 16347 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 16348 else if (CalcStep) 16349 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 16350 bool HasErrors = false; 16351 auto CurInit = Clause.inits().begin(); 16352 auto CurPrivate = Clause.privates().begin(); 16353 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 16354 for (Expr *RefExpr : Clause.varlists()) { 16355 SourceLocation ELoc; 16356 SourceRange ERange; 16357 Expr *SimpleRefExpr = RefExpr; 16358 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 16359 ValueDecl *D = Res.first; 16360 if (Res.second || !D) { 16361 Updates.push_back(nullptr); 16362 Finals.push_back(nullptr); 16363 HasErrors = true; 16364 continue; 16365 } 16366 auto &&Info = Stack->isLoopControlVariable(D); 16367 // OpenMP [2.15.11, distribute simd Construct] 16368 // A list item may not appear in a linear clause, unless it is the loop 16369 // iteration variable. 16370 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 16371 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 16372 SemaRef.Diag(ELoc, 16373 diag::err_omp_linear_distribute_var_non_loop_iteration); 16374 Updates.push_back(nullptr); 16375 Finals.push_back(nullptr); 16376 HasErrors = true; 16377 continue; 16378 } 16379 Expr *InitExpr = *CurInit; 16380 16381 // Build privatized reference to the current linear var. 16382 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 16383 Expr *CapturedRef; 16384 if (LinKind == OMPC_LINEAR_uval) 16385 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 16386 else 16387 CapturedRef = 16388 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 16389 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 16390 /*RefersToCapture=*/true); 16391 16392 // Build update: Var = InitExpr + IV * Step 16393 ExprResult Update; 16394 if (!Info.first) 16395 Update = buildCounterUpdate( 16396 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step, 16397 /*Subtract=*/false, /*IsNonRectangularLB=*/false); 16398 else 16399 Update = *CurPrivate; 16400 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 16401 /*DiscardedValue*/ false); 16402 16403 // Build final: Var = InitExpr + NumIterations * Step 16404 ExprResult Final; 16405 if (!Info.first) 16406 Final = 16407 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 16408 InitExpr, NumIterations, Step, /*Subtract=*/false, 16409 /*IsNonRectangularLB=*/false); 16410 else 16411 Final = *CurPrivate; 16412 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 16413 /*DiscardedValue*/ false); 16414 16415 if (!Update.isUsable() || !Final.isUsable()) { 16416 Updates.push_back(nullptr); 16417 Finals.push_back(nullptr); 16418 UsedExprs.push_back(nullptr); 16419 HasErrors = true; 16420 } else { 16421 Updates.push_back(Update.get()); 16422 Finals.push_back(Final.get()); 16423 if (!Info.first) 16424 UsedExprs.push_back(SimpleRefExpr); 16425 } 16426 ++CurInit; 16427 ++CurPrivate; 16428 } 16429 if (Expr *S = Clause.getStep()) 16430 UsedExprs.push_back(S); 16431 // Fill the remaining part with the nullptr. 16432 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr); 16433 Clause.setUpdates(Updates); 16434 Clause.setFinals(Finals); 16435 Clause.setUsedExprs(UsedExprs); 16436 return HasErrors; 16437 } 16438 16439 OMPClause *Sema::ActOnOpenMPAlignedClause( 16440 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 16441 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 16442 SmallVector<Expr *, 8> Vars; 16443 for (Expr *RefExpr : VarList) { 16444 assert(RefExpr && "NULL expr in OpenMP linear clause."); 16445 SourceLocation ELoc; 16446 SourceRange ERange; 16447 Expr *SimpleRefExpr = RefExpr; 16448 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16449 if (Res.second) { 16450 // It will be analyzed later. 16451 Vars.push_back(RefExpr); 16452 } 16453 ValueDecl *D = Res.first; 16454 if (!D) 16455 continue; 16456 16457 QualType QType = D->getType(); 16458 auto *VD = dyn_cast<VarDecl>(D); 16459 16460 // OpenMP [2.8.1, simd construct, Restrictions] 16461 // The type of list items appearing in the aligned clause must be 16462 // array, pointer, reference to array, or reference to pointer. 16463 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 16464 const Type *Ty = QType.getTypePtrOrNull(); 16465 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 16466 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 16467 << QType << getLangOpts().CPlusPlus << ERange; 16468 bool IsDecl = 16469 !VD || 16470 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 16471 Diag(D->getLocation(), 16472 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16473 << D; 16474 continue; 16475 } 16476 16477 // OpenMP [2.8.1, simd construct, Restrictions] 16478 // A list-item cannot appear in more than one aligned clause. 16479 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 16480 Diag(ELoc, diag::err_omp_used_in_clause_twice) 16481 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange; 16482 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 16483 << getOpenMPClauseName(OMPC_aligned); 16484 continue; 16485 } 16486 16487 DeclRefExpr *Ref = nullptr; 16488 if (!VD && isOpenMPCapturedDecl(D)) 16489 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 16490 Vars.push_back(DefaultFunctionArrayConversion( 16491 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 16492 .get()); 16493 } 16494 16495 // OpenMP [2.8.1, simd construct, Description] 16496 // The parameter of the aligned clause, alignment, must be a constant 16497 // positive integer expression. 16498 // If no optional parameter is specified, implementation-defined default 16499 // alignments for SIMD instructions on the target platforms are assumed. 16500 if (Alignment != nullptr) { 16501 ExprResult AlignResult = 16502 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 16503 if (AlignResult.isInvalid()) 16504 return nullptr; 16505 Alignment = AlignResult.get(); 16506 } 16507 if (Vars.empty()) 16508 return nullptr; 16509 16510 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 16511 EndLoc, Vars, Alignment); 16512 } 16513 16514 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 16515 SourceLocation StartLoc, 16516 SourceLocation LParenLoc, 16517 SourceLocation EndLoc) { 16518 SmallVector<Expr *, 8> Vars; 16519 SmallVector<Expr *, 8> SrcExprs; 16520 SmallVector<Expr *, 8> DstExprs; 16521 SmallVector<Expr *, 8> AssignmentOps; 16522 for (Expr *RefExpr : VarList) { 16523 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 16524 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 16525 // It will be analyzed later. 16526 Vars.push_back(RefExpr); 16527 SrcExprs.push_back(nullptr); 16528 DstExprs.push_back(nullptr); 16529 AssignmentOps.push_back(nullptr); 16530 continue; 16531 } 16532 16533 SourceLocation ELoc = RefExpr->getExprLoc(); 16534 // OpenMP [2.1, C/C++] 16535 // A list item is a variable name. 16536 // OpenMP [2.14.4.1, Restrictions, p.1] 16537 // A list item that appears in a copyin clause must be threadprivate. 16538 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 16539 if (!DE || !isa<VarDecl>(DE->getDecl())) { 16540 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 16541 << 0 << RefExpr->getSourceRange(); 16542 continue; 16543 } 16544 16545 Decl *D = DE->getDecl(); 16546 auto *VD = cast<VarDecl>(D); 16547 16548 QualType Type = VD->getType(); 16549 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 16550 // It will be analyzed later. 16551 Vars.push_back(DE); 16552 SrcExprs.push_back(nullptr); 16553 DstExprs.push_back(nullptr); 16554 AssignmentOps.push_back(nullptr); 16555 continue; 16556 } 16557 16558 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 16559 // A list item that appears in a copyin clause must be threadprivate. 16560 if (!DSAStack->isThreadPrivate(VD)) { 16561 Diag(ELoc, diag::err_omp_required_access) 16562 << getOpenMPClauseName(OMPC_copyin) 16563 << getOpenMPDirectiveName(OMPD_threadprivate); 16564 continue; 16565 } 16566 16567 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 16568 // A variable of class type (or array thereof) that appears in a 16569 // copyin clause requires an accessible, unambiguous copy assignment 16570 // operator for the class type. 16571 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 16572 VarDecl *SrcVD = 16573 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 16574 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 16575 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 16576 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 16577 VarDecl *DstVD = 16578 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 16579 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 16580 DeclRefExpr *PseudoDstExpr = 16581 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 16582 // For arrays generate assignment operation for single element and replace 16583 // it by the original array element in CodeGen. 16584 ExprResult AssignmentOp = 16585 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 16586 PseudoSrcExpr); 16587 if (AssignmentOp.isInvalid()) 16588 continue; 16589 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 16590 /*DiscardedValue*/ false); 16591 if (AssignmentOp.isInvalid()) 16592 continue; 16593 16594 DSAStack->addDSA(VD, DE, OMPC_copyin); 16595 Vars.push_back(DE); 16596 SrcExprs.push_back(PseudoSrcExpr); 16597 DstExprs.push_back(PseudoDstExpr); 16598 AssignmentOps.push_back(AssignmentOp.get()); 16599 } 16600 16601 if (Vars.empty()) 16602 return nullptr; 16603 16604 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 16605 SrcExprs, DstExprs, AssignmentOps); 16606 } 16607 16608 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 16609 SourceLocation StartLoc, 16610 SourceLocation LParenLoc, 16611 SourceLocation EndLoc) { 16612 SmallVector<Expr *, 8> Vars; 16613 SmallVector<Expr *, 8> SrcExprs; 16614 SmallVector<Expr *, 8> DstExprs; 16615 SmallVector<Expr *, 8> AssignmentOps; 16616 for (Expr *RefExpr : VarList) { 16617 assert(RefExpr && "NULL expr in OpenMP linear clause."); 16618 SourceLocation ELoc; 16619 SourceRange ERange; 16620 Expr *SimpleRefExpr = RefExpr; 16621 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16622 if (Res.second) { 16623 // It will be analyzed later. 16624 Vars.push_back(RefExpr); 16625 SrcExprs.push_back(nullptr); 16626 DstExprs.push_back(nullptr); 16627 AssignmentOps.push_back(nullptr); 16628 } 16629 ValueDecl *D = Res.first; 16630 if (!D) 16631 continue; 16632 16633 QualType Type = D->getType(); 16634 auto *VD = dyn_cast<VarDecl>(D); 16635 16636 // OpenMP [2.14.4.2, Restrictions, p.2] 16637 // A list item that appears in a copyprivate clause may not appear in a 16638 // private or firstprivate clause on the single construct. 16639 if (!VD || !DSAStack->isThreadPrivate(VD)) { 16640 DSAStackTy::DSAVarData DVar = 16641 DSAStack->getTopDSA(D, /*FromParent=*/false); 16642 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 16643 DVar.RefExpr) { 16644 Diag(ELoc, diag::err_omp_wrong_dsa) 16645 << getOpenMPClauseName(DVar.CKind) 16646 << getOpenMPClauseName(OMPC_copyprivate); 16647 reportOriginalDsa(*this, DSAStack, D, DVar); 16648 continue; 16649 } 16650 16651 // OpenMP [2.11.4.2, Restrictions, p.1] 16652 // All list items that appear in a copyprivate clause must be either 16653 // threadprivate or private in the enclosing context. 16654 if (DVar.CKind == OMPC_unknown) { 16655 DVar = DSAStack->getImplicitDSA(D, false); 16656 if (DVar.CKind == OMPC_shared) { 16657 Diag(ELoc, diag::err_omp_required_access) 16658 << getOpenMPClauseName(OMPC_copyprivate) 16659 << "threadprivate or private in the enclosing context"; 16660 reportOriginalDsa(*this, DSAStack, D, DVar); 16661 continue; 16662 } 16663 } 16664 } 16665 16666 // Variably modified types are not supported. 16667 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 16668 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 16669 << getOpenMPClauseName(OMPC_copyprivate) << Type 16670 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 16671 bool IsDecl = 16672 !VD || 16673 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 16674 Diag(D->getLocation(), 16675 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16676 << D; 16677 continue; 16678 } 16679 16680 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 16681 // A variable of class type (or array thereof) that appears in a 16682 // copyin clause requires an accessible, unambiguous copy assignment 16683 // operator for the class type. 16684 Type = Context.getBaseElementType(Type.getNonReferenceType()) 16685 .getUnqualifiedType(); 16686 VarDecl *SrcVD = 16687 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 16688 D->hasAttrs() ? &D->getAttrs() : nullptr); 16689 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 16690 VarDecl *DstVD = 16691 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 16692 D->hasAttrs() ? &D->getAttrs() : nullptr); 16693 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 16694 ExprResult AssignmentOp = BuildBinOp( 16695 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 16696 if (AssignmentOp.isInvalid()) 16697 continue; 16698 AssignmentOp = 16699 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 16700 if (AssignmentOp.isInvalid()) 16701 continue; 16702 16703 // No need to mark vars as copyprivate, they are already threadprivate or 16704 // implicitly private. 16705 assert(VD || isOpenMPCapturedDecl(D)); 16706 Vars.push_back( 16707 VD ? RefExpr->IgnoreParens() 16708 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 16709 SrcExprs.push_back(PseudoSrcExpr); 16710 DstExprs.push_back(PseudoDstExpr); 16711 AssignmentOps.push_back(AssignmentOp.get()); 16712 } 16713 16714 if (Vars.empty()) 16715 return nullptr; 16716 16717 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16718 Vars, SrcExprs, DstExprs, AssignmentOps); 16719 } 16720 16721 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 16722 SourceLocation StartLoc, 16723 SourceLocation LParenLoc, 16724 SourceLocation EndLoc) { 16725 if (VarList.empty()) 16726 return nullptr; 16727 16728 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 16729 } 16730 16731 /// Tries to find omp_depend_t. type. 16732 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack, 16733 bool Diagnose = true) { 16734 QualType OMPDependT = Stack->getOMPDependT(); 16735 if (!OMPDependT.isNull()) 16736 return true; 16737 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t"); 16738 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 16739 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 16740 if (Diagnose) 16741 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t"; 16742 return false; 16743 } 16744 Stack->setOMPDependT(PT.get()); 16745 return true; 16746 } 16747 16748 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 16749 SourceLocation LParenLoc, 16750 SourceLocation EndLoc) { 16751 if (!Depobj) 16752 return nullptr; 16753 16754 bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack); 16755 16756 // OpenMP 5.0, 2.17.10.1 depobj Construct 16757 // depobj is an lvalue expression of type omp_depend_t. 16758 if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() && 16759 !Depobj->isInstantiationDependent() && 16760 !Depobj->containsUnexpandedParameterPack() && 16761 (OMPDependTFound && 16762 !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(), 16763 /*CompareUnqualified=*/true))) { 16764 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 16765 << 0 << Depobj->getType() << Depobj->getSourceRange(); 16766 } 16767 16768 if (!Depobj->isLValue()) { 16769 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 16770 << 1 << Depobj->getSourceRange(); 16771 } 16772 16773 return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj); 16774 } 16775 16776 OMPClause * 16777 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, 16778 SourceLocation DepLoc, SourceLocation ColonLoc, 16779 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 16780 SourceLocation LParenLoc, SourceLocation EndLoc) { 16781 if (DSAStack->getCurrentDirective() == OMPD_ordered && 16782 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 16783 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 16784 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 16785 return nullptr; 16786 } 16787 if ((DSAStack->getCurrentDirective() != OMPD_ordered || 16788 DSAStack->getCurrentDirective() == OMPD_depobj) && 16789 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 16790 DepKind == OMPC_DEPEND_sink || 16791 ((LangOpts.OpenMP < 50 || 16792 DSAStack->getCurrentDirective() == OMPD_depobj) && 16793 DepKind == OMPC_DEPEND_depobj))) { 16794 SmallVector<unsigned, 3> Except; 16795 Except.push_back(OMPC_DEPEND_source); 16796 Except.push_back(OMPC_DEPEND_sink); 16797 if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj) 16798 Except.push_back(OMPC_DEPEND_depobj); 16799 std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier) 16800 ? "depend modifier(iterator) or " 16801 : ""; 16802 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 16803 << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0, 16804 /*Last=*/OMPC_DEPEND_unknown, 16805 Except) 16806 << getOpenMPClauseName(OMPC_depend); 16807 return nullptr; 16808 } 16809 if (DepModifier && 16810 (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) { 16811 Diag(DepModifier->getExprLoc(), 16812 diag::err_omp_depend_sink_source_with_modifier); 16813 return nullptr; 16814 } 16815 if (DepModifier && 16816 !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator)) 16817 Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator); 16818 16819 SmallVector<Expr *, 8> Vars; 16820 DSAStackTy::OperatorOffsetTy OpsOffs; 16821 llvm::APSInt DepCounter(/*BitWidth=*/32); 16822 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 16823 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 16824 if (const Expr *OrderedCountExpr = 16825 DSAStack->getParentOrderedRegionParam().first) { 16826 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 16827 TotalDepCount.setIsUnsigned(/*Val=*/true); 16828 } 16829 } 16830 for (Expr *RefExpr : VarList) { 16831 assert(RefExpr && "NULL expr in OpenMP shared clause."); 16832 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 16833 // It will be analyzed later. 16834 Vars.push_back(RefExpr); 16835 continue; 16836 } 16837 16838 SourceLocation ELoc = RefExpr->getExprLoc(); 16839 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 16840 if (DepKind == OMPC_DEPEND_sink) { 16841 if (DSAStack->getParentOrderedRegionParam().first && 16842 DepCounter >= TotalDepCount) { 16843 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 16844 continue; 16845 } 16846 ++DepCounter; 16847 // OpenMP [2.13.9, Summary] 16848 // depend(dependence-type : vec), where dependence-type is: 16849 // 'sink' and where vec is the iteration vector, which has the form: 16850 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 16851 // where n is the value specified by the ordered clause in the loop 16852 // directive, xi denotes the loop iteration variable of the i-th nested 16853 // loop associated with the loop directive, and di is a constant 16854 // non-negative integer. 16855 if (CurContext->isDependentContext()) { 16856 // It will be analyzed later. 16857 Vars.push_back(RefExpr); 16858 continue; 16859 } 16860 SimpleExpr = SimpleExpr->IgnoreImplicit(); 16861 OverloadedOperatorKind OOK = OO_None; 16862 SourceLocation OOLoc; 16863 Expr *LHS = SimpleExpr; 16864 Expr *RHS = nullptr; 16865 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 16866 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 16867 OOLoc = BO->getOperatorLoc(); 16868 LHS = BO->getLHS()->IgnoreParenImpCasts(); 16869 RHS = BO->getRHS()->IgnoreParenImpCasts(); 16870 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 16871 OOK = OCE->getOperator(); 16872 OOLoc = OCE->getOperatorLoc(); 16873 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 16874 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 16875 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 16876 OOK = MCE->getMethodDecl() 16877 ->getNameInfo() 16878 .getName() 16879 .getCXXOverloadedOperator(); 16880 OOLoc = MCE->getCallee()->getExprLoc(); 16881 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 16882 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 16883 } 16884 SourceLocation ELoc; 16885 SourceRange ERange; 16886 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 16887 if (Res.second) { 16888 // It will be analyzed later. 16889 Vars.push_back(RefExpr); 16890 } 16891 ValueDecl *D = Res.first; 16892 if (!D) 16893 continue; 16894 16895 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 16896 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 16897 continue; 16898 } 16899 if (RHS) { 16900 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 16901 RHS, OMPC_depend, /*StrictlyPositive=*/false); 16902 if (RHSRes.isInvalid()) 16903 continue; 16904 } 16905 if (!CurContext->isDependentContext() && 16906 DSAStack->getParentOrderedRegionParam().first && 16907 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 16908 const ValueDecl *VD = 16909 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 16910 if (VD) 16911 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 16912 << 1 << VD; 16913 else 16914 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 16915 continue; 16916 } 16917 OpsOffs.emplace_back(RHS, OOK); 16918 } else { 16919 bool OMPDependTFound = LangOpts.OpenMP >= 50; 16920 if (OMPDependTFound) 16921 OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack, 16922 DepKind == OMPC_DEPEND_depobj); 16923 if (DepKind == OMPC_DEPEND_depobj) { 16924 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 16925 // List items used in depend clauses with the depobj dependence type 16926 // must be expressions of the omp_depend_t type. 16927 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 16928 !RefExpr->isInstantiationDependent() && 16929 !RefExpr->containsUnexpandedParameterPack() && 16930 (OMPDependTFound && 16931 !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(), 16932 RefExpr->getType()))) { 16933 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 16934 << 0 << RefExpr->getType() << RefExpr->getSourceRange(); 16935 continue; 16936 } 16937 if (!RefExpr->isLValue()) { 16938 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 16939 << 1 << RefExpr->getType() << RefExpr->getSourceRange(); 16940 continue; 16941 } 16942 } else { 16943 // OpenMP 5.0 [2.17.11, Restrictions] 16944 // List items used in depend clauses cannot be zero-length array 16945 // sections. 16946 QualType ExprTy = RefExpr->getType().getNonReferenceType(); 16947 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 16948 if (OASE) { 16949 QualType BaseType = 16950 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 16951 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 16952 ExprTy = ATy->getElementType(); 16953 else 16954 ExprTy = BaseType->getPointeeType(); 16955 ExprTy = ExprTy.getNonReferenceType(); 16956 const Expr *Length = OASE->getLength(); 16957 Expr::EvalResult Result; 16958 if (Length && !Length->isValueDependent() && 16959 Length->EvaluateAsInt(Result, Context) && 16960 Result.Val.getInt().isNullValue()) { 16961 Diag(ELoc, 16962 diag::err_omp_depend_zero_length_array_section_not_allowed) 16963 << SimpleExpr->getSourceRange(); 16964 continue; 16965 } 16966 } 16967 16968 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 16969 // List items used in depend clauses with the in, out, inout or 16970 // mutexinoutset dependence types cannot be expressions of the 16971 // omp_depend_t type. 16972 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 16973 !RefExpr->isInstantiationDependent() && 16974 !RefExpr->containsUnexpandedParameterPack() && 16975 (OMPDependTFound && 16976 DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) { 16977 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 16978 << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1 16979 << RefExpr->getSourceRange(); 16980 continue; 16981 } 16982 16983 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 16984 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 16985 (ASE && !ASE->getBase()->isTypeDependent() && 16986 !ASE->getBase() 16987 ->getType() 16988 .getNonReferenceType() 16989 ->isPointerType() && 16990 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 16991 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 16992 << (LangOpts.OpenMP >= 50 ? 1 : 0) 16993 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 16994 continue; 16995 } 16996 16997 ExprResult Res; 16998 { 16999 Sema::TentativeAnalysisScope Trap(*this); 17000 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, 17001 RefExpr->IgnoreParenImpCasts()); 17002 } 17003 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 17004 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 17005 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 17006 << (LangOpts.OpenMP >= 50 ? 1 : 0) 17007 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 17008 continue; 17009 } 17010 } 17011 } 17012 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 17013 } 17014 17015 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 17016 TotalDepCount > VarList.size() && 17017 DSAStack->getParentOrderedRegionParam().first && 17018 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 17019 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 17020 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 17021 } 17022 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 17023 Vars.empty()) 17024 return nullptr; 17025 17026 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 17027 DepModifier, DepKind, DepLoc, ColonLoc, 17028 Vars, TotalDepCount.getZExtValue()); 17029 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 17030 DSAStack->isParentOrderedRegion()) 17031 DSAStack->addDoacrossDependClause(C, OpsOffs); 17032 return C; 17033 } 17034 17035 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 17036 Expr *Device, SourceLocation StartLoc, 17037 SourceLocation LParenLoc, 17038 SourceLocation ModifierLoc, 17039 SourceLocation EndLoc) { 17040 assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) && 17041 "Unexpected device modifier in OpenMP < 50."); 17042 17043 bool ErrorFound = false; 17044 if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) { 17045 std::string Values = 17046 getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown); 17047 Diag(ModifierLoc, diag::err_omp_unexpected_clause_value) 17048 << Values << getOpenMPClauseName(OMPC_device); 17049 ErrorFound = true; 17050 } 17051 17052 Expr *ValExpr = Device; 17053 Stmt *HelperValStmt = nullptr; 17054 17055 // OpenMP [2.9.1, Restrictions] 17056 // The device expression must evaluate to a non-negative integer value. 17057 ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 17058 /*StrictlyPositive=*/false) || 17059 ErrorFound; 17060 if (ErrorFound) 17061 return nullptr; 17062 17063 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 17064 OpenMPDirectiveKind CaptureRegion = 17065 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP); 17066 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 17067 ValExpr = MakeFullExpr(ValExpr).get(); 17068 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 17069 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 17070 HelperValStmt = buildPreInits(Context, Captures); 17071 } 17072 17073 return new (Context) 17074 OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 17075 LParenLoc, ModifierLoc, EndLoc); 17076 } 17077 17078 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 17079 DSAStackTy *Stack, QualType QTy, 17080 bool FullCheck = true) { 17081 NamedDecl *ND; 17082 if (QTy->isIncompleteType(&ND)) { 17083 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 17084 return false; 17085 } 17086 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 17087 !QTy.isTriviallyCopyableType(SemaRef.Context)) 17088 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 17089 return true; 17090 } 17091 17092 /// Return true if it can be proven that the provided array expression 17093 /// (array section or array subscript) does NOT specify the whole size of the 17094 /// array whose base type is \a BaseQTy. 17095 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 17096 const Expr *E, 17097 QualType BaseQTy) { 17098 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 17099 17100 // If this is an array subscript, it refers to the whole size if the size of 17101 // the dimension is constant and equals 1. Also, an array section assumes the 17102 // format of an array subscript if no colon is used. 17103 if (isa<ArraySubscriptExpr>(E) || 17104 (OASE && OASE->getColonLocFirst().isInvalid())) { 17105 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 17106 return ATy->getSize().getSExtValue() != 1; 17107 // Size can't be evaluated statically. 17108 return false; 17109 } 17110 17111 assert(OASE && "Expecting array section if not an array subscript."); 17112 const Expr *LowerBound = OASE->getLowerBound(); 17113 const Expr *Length = OASE->getLength(); 17114 17115 // If there is a lower bound that does not evaluates to zero, we are not 17116 // covering the whole dimension. 17117 if (LowerBound) { 17118 Expr::EvalResult Result; 17119 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 17120 return false; // Can't get the integer value as a constant. 17121 17122 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 17123 if (ConstLowerBound.getSExtValue()) 17124 return true; 17125 } 17126 17127 // If we don't have a length we covering the whole dimension. 17128 if (!Length) 17129 return false; 17130 17131 // If the base is a pointer, we don't have a way to get the size of the 17132 // pointee. 17133 if (BaseQTy->isPointerType()) 17134 return false; 17135 17136 // We can only check if the length is the same as the size of the dimension 17137 // if we have a constant array. 17138 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 17139 if (!CATy) 17140 return false; 17141 17142 Expr::EvalResult Result; 17143 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 17144 return false; // Can't get the integer value as a constant. 17145 17146 llvm::APSInt ConstLength = Result.Val.getInt(); 17147 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 17148 } 17149 17150 // Return true if it can be proven that the provided array expression (array 17151 // section or array subscript) does NOT specify a single element of the array 17152 // whose base type is \a BaseQTy. 17153 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 17154 const Expr *E, 17155 QualType BaseQTy) { 17156 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 17157 17158 // An array subscript always refer to a single element. Also, an array section 17159 // assumes the format of an array subscript if no colon is used. 17160 if (isa<ArraySubscriptExpr>(E) || 17161 (OASE && OASE->getColonLocFirst().isInvalid())) 17162 return false; 17163 17164 assert(OASE && "Expecting array section if not an array subscript."); 17165 const Expr *Length = OASE->getLength(); 17166 17167 // If we don't have a length we have to check if the array has unitary size 17168 // for this dimension. Also, we should always expect a length if the base type 17169 // is pointer. 17170 if (!Length) { 17171 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 17172 return ATy->getSize().getSExtValue() != 1; 17173 // We cannot assume anything. 17174 return false; 17175 } 17176 17177 // Check if the length evaluates to 1. 17178 Expr::EvalResult Result; 17179 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 17180 return false; // Can't get the integer value as a constant. 17181 17182 llvm::APSInt ConstLength = Result.Val.getInt(); 17183 return ConstLength.getSExtValue() != 1; 17184 } 17185 17186 // The base of elements of list in a map clause have to be either: 17187 // - a reference to variable or field. 17188 // - a member expression. 17189 // - an array expression. 17190 // 17191 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 17192 // reference to 'r'. 17193 // 17194 // If we have: 17195 // 17196 // struct SS { 17197 // Bla S; 17198 // foo() { 17199 // #pragma omp target map (S.Arr[:12]); 17200 // } 17201 // } 17202 // 17203 // We want to retrieve the member expression 'this->S'; 17204 17205 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2] 17206 // If a list item is an array section, it must specify contiguous storage. 17207 // 17208 // For this restriction it is sufficient that we make sure only references 17209 // to variables or fields and array expressions, and that no array sections 17210 // exist except in the rightmost expression (unless they cover the whole 17211 // dimension of the array). E.g. these would be invalid: 17212 // 17213 // r.ArrS[3:5].Arr[6:7] 17214 // 17215 // r.ArrS[3:5].x 17216 // 17217 // but these would be valid: 17218 // r.ArrS[3].Arr[6:7] 17219 // 17220 // r.ArrS[3].x 17221 namespace { 17222 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> { 17223 Sema &SemaRef; 17224 OpenMPClauseKind CKind = OMPC_unknown; 17225 OpenMPDirectiveKind DKind = OMPD_unknown; 17226 OMPClauseMappableExprCommon::MappableExprComponentList &Components; 17227 bool IsNonContiguous = false; 17228 bool NoDiagnose = false; 17229 const Expr *RelevantExpr = nullptr; 17230 bool AllowUnitySizeArraySection = true; 17231 bool AllowWholeSizeArraySection = true; 17232 bool AllowAnotherPtr = true; 17233 SourceLocation ELoc; 17234 SourceRange ERange; 17235 17236 void emitErrorMsg() { 17237 // If nothing else worked, this is not a valid map clause expression. 17238 if (SemaRef.getLangOpts().OpenMP < 50) { 17239 SemaRef.Diag(ELoc, 17240 diag::err_omp_expected_named_var_member_or_array_expression) 17241 << ERange; 17242 } else { 17243 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 17244 << getOpenMPClauseName(CKind) << ERange; 17245 } 17246 } 17247 17248 public: 17249 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 17250 if (!isa<VarDecl>(DRE->getDecl())) { 17251 emitErrorMsg(); 17252 return false; 17253 } 17254 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 17255 RelevantExpr = DRE; 17256 // Record the component. 17257 Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous); 17258 return true; 17259 } 17260 17261 bool VisitMemberExpr(MemberExpr *ME) { 17262 Expr *E = ME; 17263 Expr *BaseE = ME->getBase()->IgnoreParenCasts(); 17264 17265 if (isa<CXXThisExpr>(BaseE)) { 17266 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 17267 // We found a base expression: this->Val. 17268 RelevantExpr = ME; 17269 } else { 17270 E = BaseE; 17271 } 17272 17273 if (!isa<FieldDecl>(ME->getMemberDecl())) { 17274 if (!NoDiagnose) { 17275 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 17276 << ME->getSourceRange(); 17277 return false; 17278 } 17279 if (RelevantExpr) 17280 return false; 17281 return Visit(E); 17282 } 17283 17284 auto *FD = cast<FieldDecl>(ME->getMemberDecl()); 17285 17286 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 17287 // A bit-field cannot appear in a map clause. 17288 // 17289 if (FD->isBitField()) { 17290 if (!NoDiagnose) { 17291 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 17292 << ME->getSourceRange() << getOpenMPClauseName(CKind); 17293 return false; 17294 } 17295 if (RelevantExpr) 17296 return false; 17297 return Visit(E); 17298 } 17299 17300 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 17301 // If the type of a list item is a reference to a type T then the type 17302 // will be considered to be T for all purposes of this clause. 17303 QualType CurType = BaseE->getType().getNonReferenceType(); 17304 17305 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 17306 // A list item cannot be a variable that is a member of a structure with 17307 // a union type. 17308 // 17309 if (CurType->isUnionType()) { 17310 if (!NoDiagnose) { 17311 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 17312 << ME->getSourceRange(); 17313 return false; 17314 } 17315 return RelevantExpr || Visit(E); 17316 } 17317 17318 // If we got a member expression, we should not expect any array section 17319 // before that: 17320 // 17321 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 17322 // If a list item is an element of a structure, only the rightmost symbol 17323 // of the variable reference can be an array section. 17324 // 17325 AllowUnitySizeArraySection = false; 17326 AllowWholeSizeArraySection = false; 17327 17328 // Record the component. 17329 Components.emplace_back(ME, FD, IsNonContiguous); 17330 return RelevantExpr || Visit(E); 17331 } 17332 17333 bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) { 17334 Expr *E = AE->getBase()->IgnoreParenImpCasts(); 17335 17336 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 17337 if (!NoDiagnose) { 17338 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 17339 << 0 << AE->getSourceRange(); 17340 return false; 17341 } 17342 return RelevantExpr || Visit(E); 17343 } 17344 17345 // If we got an array subscript that express the whole dimension we 17346 // can have any array expressions before. If it only expressing part of 17347 // the dimension, we can only have unitary-size array expressions. 17348 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, 17349 E->getType())) 17350 AllowWholeSizeArraySection = false; 17351 17352 if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) { 17353 Expr::EvalResult Result; 17354 if (!AE->getIdx()->isValueDependent() && 17355 AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) && 17356 !Result.Val.getInt().isNullValue()) { 17357 SemaRef.Diag(AE->getIdx()->getExprLoc(), 17358 diag::err_omp_invalid_map_this_expr); 17359 SemaRef.Diag(AE->getIdx()->getExprLoc(), 17360 diag::note_omp_invalid_subscript_on_this_ptr_map); 17361 } 17362 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 17363 RelevantExpr = TE; 17364 } 17365 17366 // Record the component - we don't have any declaration associated. 17367 Components.emplace_back(AE, nullptr, IsNonContiguous); 17368 17369 return RelevantExpr || Visit(E); 17370 } 17371 17372 bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) { 17373 assert(!NoDiagnose && "Array sections cannot be implicitly mapped."); 17374 Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 17375 QualType CurType = 17376 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 17377 17378 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 17379 // If the type of a list item is a reference to a type T then the type 17380 // will be considered to be T for all purposes of this clause. 17381 if (CurType->isReferenceType()) 17382 CurType = CurType->getPointeeType(); 17383 17384 bool IsPointer = CurType->isAnyPointerType(); 17385 17386 if (!IsPointer && !CurType->isArrayType()) { 17387 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 17388 << 0 << OASE->getSourceRange(); 17389 return false; 17390 } 17391 17392 bool NotWhole = 17393 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType); 17394 bool NotUnity = 17395 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType); 17396 17397 if (AllowWholeSizeArraySection) { 17398 // Any array section is currently allowed. Allowing a whole size array 17399 // section implies allowing a unity array section as well. 17400 // 17401 // If this array section refers to the whole dimension we can still 17402 // accept other array sections before this one, except if the base is a 17403 // pointer. Otherwise, only unitary sections are accepted. 17404 if (NotWhole || IsPointer) 17405 AllowWholeSizeArraySection = false; 17406 } else if (DKind == OMPD_target_update && 17407 SemaRef.getLangOpts().OpenMP >= 50) { 17408 if (IsPointer && !AllowAnotherPtr) 17409 SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined) 17410 << /*array of unknown bound */ 1; 17411 else 17412 IsNonContiguous = true; 17413 } else if (AllowUnitySizeArraySection && NotUnity) { 17414 // A unity or whole array section is not allowed and that is not 17415 // compatible with the properties of the current array section. 17416 SemaRef.Diag( 17417 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 17418 << OASE->getSourceRange(); 17419 return false; 17420 } 17421 17422 if (IsPointer) 17423 AllowAnotherPtr = false; 17424 17425 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 17426 Expr::EvalResult ResultR; 17427 Expr::EvalResult ResultL; 17428 if (!OASE->getLength()->isValueDependent() && 17429 OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) && 17430 !ResultR.Val.getInt().isOneValue()) { 17431 SemaRef.Diag(OASE->getLength()->getExprLoc(), 17432 diag::err_omp_invalid_map_this_expr); 17433 SemaRef.Diag(OASE->getLength()->getExprLoc(), 17434 diag::note_omp_invalid_length_on_this_ptr_mapping); 17435 } 17436 if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() && 17437 OASE->getLowerBound()->EvaluateAsInt(ResultL, 17438 SemaRef.getASTContext()) && 17439 !ResultL.Val.getInt().isNullValue()) { 17440 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 17441 diag::err_omp_invalid_map_this_expr); 17442 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 17443 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 17444 } 17445 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 17446 RelevantExpr = TE; 17447 } 17448 17449 // Record the component - we don't have any declaration associated. 17450 Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false); 17451 return RelevantExpr || Visit(E); 17452 } 17453 bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) { 17454 Expr *Base = E->getBase(); 17455 17456 // Record the component - we don't have any declaration associated. 17457 Components.emplace_back(E, nullptr, IsNonContiguous); 17458 17459 return Visit(Base->IgnoreParenImpCasts()); 17460 } 17461 17462 bool VisitUnaryOperator(UnaryOperator *UO) { 17463 if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() || 17464 UO->getOpcode() != UO_Deref) { 17465 emitErrorMsg(); 17466 return false; 17467 } 17468 if (!RelevantExpr) { 17469 // Record the component if haven't found base decl. 17470 Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false); 17471 } 17472 return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts()); 17473 } 17474 bool VisitBinaryOperator(BinaryOperator *BO) { 17475 if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) { 17476 emitErrorMsg(); 17477 return false; 17478 } 17479 17480 // Pointer arithmetic is the only thing we expect to happen here so after we 17481 // make sure the binary operator is a pointer type, the we only thing need 17482 // to to is to visit the subtree that has the same type as root (so that we 17483 // know the other subtree is just an offset) 17484 Expr *LE = BO->getLHS()->IgnoreParenImpCasts(); 17485 Expr *RE = BO->getRHS()->IgnoreParenImpCasts(); 17486 Components.emplace_back(BO, nullptr, false); 17487 assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() || 17488 RE->getType().getTypePtr() == BO->getType().getTypePtr()) && 17489 "Either LHS or RHS have base decl inside"); 17490 if (BO->getType().getTypePtr() == LE->getType().getTypePtr()) 17491 return RelevantExpr || Visit(LE); 17492 return RelevantExpr || Visit(RE); 17493 } 17494 bool VisitCXXThisExpr(CXXThisExpr *CTE) { 17495 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 17496 RelevantExpr = CTE; 17497 Components.emplace_back(CTE, nullptr, IsNonContiguous); 17498 return true; 17499 } 17500 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) { 17501 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 17502 Components.emplace_back(COCE, nullptr, IsNonContiguous); 17503 return true; 17504 } 17505 bool VisitStmt(Stmt *) { 17506 emitErrorMsg(); 17507 return false; 17508 } 17509 const Expr *getFoundBase() const { 17510 return RelevantExpr; 17511 } 17512 explicit MapBaseChecker( 17513 Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, 17514 OMPClauseMappableExprCommon::MappableExprComponentList &Components, 17515 bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange) 17516 : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components), 17517 NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {} 17518 }; 17519 } // namespace 17520 17521 /// Return the expression of the base of the mappable expression or null if it 17522 /// cannot be determined and do all the necessary checks to see if the expression 17523 /// is valid as a standalone mappable expression. In the process, record all the 17524 /// components of the expression. 17525 static const Expr *checkMapClauseExpressionBase( 17526 Sema &SemaRef, Expr *E, 17527 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 17528 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) { 17529 SourceLocation ELoc = E->getExprLoc(); 17530 SourceRange ERange = E->getSourceRange(); 17531 MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc, 17532 ERange); 17533 if (Checker.Visit(E->IgnoreParens())) { 17534 // Check if the highest dimension array section has length specified 17535 if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() && 17536 (CKind == OMPC_to || CKind == OMPC_from)) { 17537 auto CI = CurComponents.rbegin(); 17538 auto CE = CurComponents.rend(); 17539 for (; CI != CE; ++CI) { 17540 const auto *OASE = 17541 dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression()); 17542 if (!OASE) 17543 continue; 17544 if (OASE && OASE->getLength()) 17545 break; 17546 SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length) 17547 << ERange; 17548 } 17549 } 17550 return Checker.getFoundBase(); 17551 } 17552 return nullptr; 17553 } 17554 17555 // Return true if expression E associated with value VD has conflicts with other 17556 // map information. 17557 static bool checkMapConflicts( 17558 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 17559 bool CurrentRegionOnly, 17560 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 17561 OpenMPClauseKind CKind) { 17562 assert(VD && E); 17563 SourceLocation ELoc = E->getExprLoc(); 17564 SourceRange ERange = E->getSourceRange(); 17565 17566 // In order to easily check the conflicts we need to match each component of 17567 // the expression under test with the components of the expressions that are 17568 // already in the stack. 17569 17570 assert(!CurComponents.empty() && "Map clause expression with no components!"); 17571 assert(CurComponents.back().getAssociatedDeclaration() == VD && 17572 "Map clause expression with unexpected base!"); 17573 17574 // Variables to help detecting enclosing problems in data environment nests. 17575 bool IsEnclosedByDataEnvironmentExpr = false; 17576 const Expr *EnclosingExpr = nullptr; 17577 17578 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 17579 VD, CurrentRegionOnly, 17580 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 17581 ERange, CKind, &EnclosingExpr, 17582 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 17583 StackComponents, 17584 OpenMPClauseKind Kind) { 17585 if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50) 17586 return false; 17587 assert(!StackComponents.empty() && 17588 "Map clause expression with no components!"); 17589 assert(StackComponents.back().getAssociatedDeclaration() == VD && 17590 "Map clause expression with unexpected base!"); 17591 (void)VD; 17592 17593 // The whole expression in the stack. 17594 const Expr *RE = StackComponents.front().getAssociatedExpression(); 17595 17596 // Expressions must start from the same base. Here we detect at which 17597 // point both expressions diverge from each other and see if we can 17598 // detect if the memory referred to both expressions is contiguous and 17599 // do not overlap. 17600 auto CI = CurComponents.rbegin(); 17601 auto CE = CurComponents.rend(); 17602 auto SI = StackComponents.rbegin(); 17603 auto SE = StackComponents.rend(); 17604 for (; CI != CE && SI != SE; ++CI, ++SI) { 17605 17606 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 17607 // At most one list item can be an array item derived from a given 17608 // variable in map clauses of the same construct. 17609 if (CurrentRegionOnly && 17610 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 17611 isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) || 17612 isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) && 17613 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 17614 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) || 17615 isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) { 17616 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 17617 diag::err_omp_multiple_array_items_in_map_clause) 17618 << CI->getAssociatedExpression()->getSourceRange(); 17619 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 17620 diag::note_used_here) 17621 << SI->getAssociatedExpression()->getSourceRange(); 17622 return true; 17623 } 17624 17625 // Do both expressions have the same kind? 17626 if (CI->getAssociatedExpression()->getStmtClass() != 17627 SI->getAssociatedExpression()->getStmtClass()) 17628 break; 17629 17630 // Are we dealing with different variables/fields? 17631 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 17632 break; 17633 } 17634 // Check if the extra components of the expressions in the enclosing 17635 // data environment are redundant for the current base declaration. 17636 // If they are, the maps completely overlap, which is legal. 17637 for (; SI != SE; ++SI) { 17638 QualType Type; 17639 if (const auto *ASE = 17640 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 17641 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 17642 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 17643 SI->getAssociatedExpression())) { 17644 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 17645 Type = 17646 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 17647 } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>( 17648 SI->getAssociatedExpression())) { 17649 Type = OASE->getBase()->getType()->getPointeeType(); 17650 } 17651 if (Type.isNull() || Type->isAnyPointerType() || 17652 checkArrayExpressionDoesNotReferToWholeSize( 17653 SemaRef, SI->getAssociatedExpression(), Type)) 17654 break; 17655 } 17656 17657 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 17658 // List items of map clauses in the same construct must not share 17659 // original storage. 17660 // 17661 // If the expressions are exactly the same or one is a subset of the 17662 // other, it means they are sharing storage. 17663 if (CI == CE && SI == SE) { 17664 if (CurrentRegionOnly) { 17665 if (CKind == OMPC_map) { 17666 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 17667 } else { 17668 assert(CKind == OMPC_to || CKind == OMPC_from); 17669 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 17670 << ERange; 17671 } 17672 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 17673 << RE->getSourceRange(); 17674 return true; 17675 } 17676 // If we find the same expression in the enclosing data environment, 17677 // that is legal. 17678 IsEnclosedByDataEnvironmentExpr = true; 17679 return false; 17680 } 17681 17682 QualType DerivedType = 17683 std::prev(CI)->getAssociatedDeclaration()->getType(); 17684 SourceLocation DerivedLoc = 17685 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 17686 17687 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 17688 // If the type of a list item is a reference to a type T then the type 17689 // will be considered to be T for all purposes of this clause. 17690 DerivedType = DerivedType.getNonReferenceType(); 17691 17692 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 17693 // A variable for which the type is pointer and an array section 17694 // derived from that variable must not appear as list items of map 17695 // clauses of the same construct. 17696 // 17697 // Also, cover one of the cases in: 17698 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 17699 // If any part of the original storage of a list item has corresponding 17700 // storage in the device data environment, all of the original storage 17701 // must have corresponding storage in the device data environment. 17702 // 17703 if (DerivedType->isAnyPointerType()) { 17704 if (CI == CE || SI == SE) { 17705 SemaRef.Diag( 17706 DerivedLoc, 17707 diag::err_omp_pointer_mapped_along_with_derived_section) 17708 << DerivedLoc; 17709 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 17710 << RE->getSourceRange(); 17711 return true; 17712 } 17713 if (CI->getAssociatedExpression()->getStmtClass() != 17714 SI->getAssociatedExpression()->getStmtClass() || 17715 CI->getAssociatedDeclaration()->getCanonicalDecl() == 17716 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 17717 assert(CI != CE && SI != SE); 17718 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 17719 << DerivedLoc; 17720 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 17721 << RE->getSourceRange(); 17722 return true; 17723 } 17724 } 17725 17726 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 17727 // List items of map clauses in the same construct must not share 17728 // original storage. 17729 // 17730 // An expression is a subset of the other. 17731 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 17732 if (CKind == OMPC_map) { 17733 if (CI != CE || SI != SE) { 17734 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 17735 // a pointer. 17736 auto Begin = 17737 CI != CE ? CurComponents.begin() : StackComponents.begin(); 17738 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 17739 auto It = Begin; 17740 while (It != End && !It->getAssociatedDeclaration()) 17741 std::advance(It, 1); 17742 assert(It != End && 17743 "Expected at least one component with the declaration."); 17744 if (It != Begin && It->getAssociatedDeclaration() 17745 ->getType() 17746 .getCanonicalType() 17747 ->isAnyPointerType()) { 17748 IsEnclosedByDataEnvironmentExpr = false; 17749 EnclosingExpr = nullptr; 17750 return false; 17751 } 17752 } 17753 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 17754 } else { 17755 assert(CKind == OMPC_to || CKind == OMPC_from); 17756 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 17757 << ERange; 17758 } 17759 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 17760 << RE->getSourceRange(); 17761 return true; 17762 } 17763 17764 // The current expression uses the same base as other expression in the 17765 // data environment but does not contain it completely. 17766 if (!CurrentRegionOnly && SI != SE) 17767 EnclosingExpr = RE; 17768 17769 // The current expression is a subset of the expression in the data 17770 // environment. 17771 IsEnclosedByDataEnvironmentExpr |= 17772 (!CurrentRegionOnly && CI != CE && SI == SE); 17773 17774 return false; 17775 }); 17776 17777 if (CurrentRegionOnly) 17778 return FoundError; 17779 17780 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 17781 // If any part of the original storage of a list item has corresponding 17782 // storage in the device data environment, all of the original storage must 17783 // have corresponding storage in the device data environment. 17784 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 17785 // If a list item is an element of a structure, and a different element of 17786 // the structure has a corresponding list item in the device data environment 17787 // prior to a task encountering the construct associated with the map clause, 17788 // then the list item must also have a corresponding list item in the device 17789 // data environment prior to the task encountering the construct. 17790 // 17791 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 17792 SemaRef.Diag(ELoc, 17793 diag::err_omp_original_storage_is_shared_and_does_not_contain) 17794 << ERange; 17795 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 17796 << EnclosingExpr->getSourceRange(); 17797 return true; 17798 } 17799 17800 return FoundError; 17801 } 17802 17803 // Look up the user-defined mapper given the mapper name and mapped type, and 17804 // build a reference to it. 17805 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 17806 CXXScopeSpec &MapperIdScopeSpec, 17807 const DeclarationNameInfo &MapperId, 17808 QualType Type, 17809 Expr *UnresolvedMapper) { 17810 if (MapperIdScopeSpec.isInvalid()) 17811 return ExprError(); 17812 // Get the actual type for the array type. 17813 if (Type->isArrayType()) { 17814 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type"); 17815 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType(); 17816 } 17817 // Find all user-defined mappers with the given MapperId. 17818 SmallVector<UnresolvedSet<8>, 4> Lookups; 17819 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); 17820 Lookup.suppressDiagnostics(); 17821 if (S) { 17822 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { 17823 NamedDecl *D = Lookup.getRepresentativeDecl(); 17824 while (S && !S->isDeclScope(D)) 17825 S = S->getParent(); 17826 if (S) 17827 S = S->getParent(); 17828 Lookups.emplace_back(); 17829 Lookups.back().append(Lookup.begin(), Lookup.end()); 17830 Lookup.clear(); 17831 } 17832 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) { 17833 // Extract the user-defined mappers with the given MapperId. 17834 Lookups.push_back(UnresolvedSet<8>()); 17835 for (NamedDecl *D : ULE->decls()) { 17836 auto *DMD = cast<OMPDeclareMapperDecl>(D); 17837 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation."); 17838 Lookups.back().addDecl(DMD); 17839 } 17840 } 17841 // Defer the lookup for dependent types. The results will be passed through 17842 // UnresolvedMapper on instantiation. 17843 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() || 17844 Type->isInstantiationDependentType() || 17845 Type->containsUnexpandedParameterPack() || 17846 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 17847 return !D->isInvalidDecl() && 17848 (D->getType()->isDependentType() || 17849 D->getType()->isInstantiationDependentType() || 17850 D->getType()->containsUnexpandedParameterPack()); 17851 })) { 17852 UnresolvedSet<8> URS; 17853 for (const UnresolvedSet<8> &Set : Lookups) { 17854 if (Set.empty()) 17855 continue; 17856 URS.append(Set.begin(), Set.end()); 17857 } 17858 return UnresolvedLookupExpr::Create( 17859 SemaRef.Context, /*NamingClass=*/nullptr, 17860 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId, 17861 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end()); 17862 } 17863 SourceLocation Loc = MapperId.getLoc(); 17864 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 17865 // The type must be of struct, union or class type in C and C++ 17866 if (!Type->isStructureOrClassType() && !Type->isUnionType() && 17867 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) { 17868 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type); 17869 return ExprError(); 17870 } 17871 // Perform argument dependent lookup. 17872 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet()) 17873 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups); 17874 // Return the first user-defined mapper with the desired type. 17875 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 17876 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * { 17877 if (!D->isInvalidDecl() && 17878 SemaRef.Context.hasSameType(D->getType(), Type)) 17879 return D; 17880 return nullptr; 17881 })) 17882 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 17883 // Find the first user-defined mapper with a type derived from the desired 17884 // type. 17885 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 17886 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * { 17887 if (!D->isInvalidDecl() && 17888 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) && 17889 !Type.isMoreQualifiedThan(D->getType())) 17890 return D; 17891 return nullptr; 17892 })) { 17893 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 17894 /*DetectVirtual=*/false); 17895 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) { 17896 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 17897 VD->getType().getUnqualifiedType()))) { 17898 if (SemaRef.CheckBaseClassAccess( 17899 Loc, VD->getType(), Type, Paths.front(), 17900 /*DiagID=*/0) != Sema::AR_inaccessible) { 17901 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 17902 } 17903 } 17904 } 17905 } 17906 // Report error if a mapper is specified, but cannot be found. 17907 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") { 17908 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper) 17909 << Type << MapperId.getName(); 17910 return ExprError(); 17911 } 17912 return ExprEmpty(); 17913 } 17914 17915 namespace { 17916 // Utility struct that gathers all the related lists associated with a mappable 17917 // expression. 17918 struct MappableVarListInfo { 17919 // The list of expressions. 17920 ArrayRef<Expr *> VarList; 17921 // The list of processed expressions. 17922 SmallVector<Expr *, 16> ProcessedVarList; 17923 // The mappble components for each expression. 17924 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 17925 // The base declaration of the variable. 17926 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 17927 // The reference to the user-defined mapper associated with every expression. 17928 SmallVector<Expr *, 16> UDMapperList; 17929 17930 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 17931 // We have a list of components and base declarations for each entry in the 17932 // variable list. 17933 VarComponents.reserve(VarList.size()); 17934 VarBaseDeclarations.reserve(VarList.size()); 17935 } 17936 }; 17937 } 17938 17939 // Check the validity of the provided variable list for the provided clause kind 17940 // \a CKind. In the check process the valid expressions, mappable expression 17941 // components, variables, and user-defined mappers are extracted and used to 17942 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a 17943 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec, 17944 // and \a MapperId are expected to be valid if the clause kind is 'map'. 17945 static void checkMappableExpressionList( 17946 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, 17947 MappableVarListInfo &MVLI, SourceLocation StartLoc, 17948 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId, 17949 ArrayRef<Expr *> UnresolvedMappers, 17950 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 17951 bool IsMapTypeImplicit = false) { 17952 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 17953 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 17954 "Unexpected clause kind with mappable expressions!"); 17955 17956 // If the identifier of user-defined mapper is not specified, it is "default". 17957 // We do not change the actual name in this clause to distinguish whether a 17958 // mapper is specified explicitly, i.e., it is not explicitly specified when 17959 // MapperId.getName() is empty. 17960 if (!MapperId.getName() || MapperId.getName().isEmpty()) { 17961 auto &DeclNames = SemaRef.getASTContext().DeclarationNames; 17962 MapperId.setName(DeclNames.getIdentifier( 17963 &SemaRef.getASTContext().Idents.get("default"))); 17964 MapperId.setLoc(StartLoc); 17965 } 17966 17967 // Iterators to find the current unresolved mapper expression. 17968 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end(); 17969 bool UpdateUMIt = false; 17970 Expr *UnresolvedMapper = nullptr; 17971 17972 // Keep track of the mappable components and base declarations in this clause. 17973 // Each entry in the list is going to have a list of components associated. We 17974 // record each set of the components so that we can build the clause later on. 17975 // In the end we should have the same amount of declarations and component 17976 // lists. 17977 17978 for (Expr *RE : MVLI.VarList) { 17979 assert(RE && "Null expr in omp to/from/map clause"); 17980 SourceLocation ELoc = RE->getExprLoc(); 17981 17982 // Find the current unresolved mapper expression. 17983 if (UpdateUMIt && UMIt != UMEnd) { 17984 UMIt++; 17985 assert( 17986 UMIt != UMEnd && 17987 "Expect the size of UnresolvedMappers to match with that of VarList"); 17988 } 17989 UpdateUMIt = true; 17990 if (UMIt != UMEnd) 17991 UnresolvedMapper = *UMIt; 17992 17993 const Expr *VE = RE->IgnoreParenLValueCasts(); 17994 17995 if (VE->isValueDependent() || VE->isTypeDependent() || 17996 VE->isInstantiationDependent() || 17997 VE->containsUnexpandedParameterPack()) { 17998 // Try to find the associated user-defined mapper. 17999 ExprResult ER = buildUserDefinedMapperRef( 18000 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 18001 VE->getType().getCanonicalType(), UnresolvedMapper); 18002 if (ER.isInvalid()) 18003 continue; 18004 MVLI.UDMapperList.push_back(ER.get()); 18005 // We can only analyze this information once the missing information is 18006 // resolved. 18007 MVLI.ProcessedVarList.push_back(RE); 18008 continue; 18009 } 18010 18011 Expr *SimpleExpr = RE->IgnoreParenCasts(); 18012 18013 if (!RE->isLValue()) { 18014 if (SemaRef.getLangOpts().OpenMP < 50) { 18015 SemaRef.Diag( 18016 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 18017 << RE->getSourceRange(); 18018 } else { 18019 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 18020 << getOpenMPClauseName(CKind) << RE->getSourceRange(); 18021 } 18022 continue; 18023 } 18024 18025 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 18026 ValueDecl *CurDeclaration = nullptr; 18027 18028 // Obtain the array or member expression bases if required. Also, fill the 18029 // components array with all the components identified in the process. 18030 const Expr *BE = checkMapClauseExpressionBase( 18031 SemaRef, SimpleExpr, CurComponents, CKind, DSAS->getCurrentDirective(), 18032 /*NoDiagnose=*/false); 18033 if (!BE) 18034 continue; 18035 18036 assert(!CurComponents.empty() && 18037 "Invalid mappable expression information."); 18038 18039 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 18040 // Add store "this" pointer to class in DSAStackTy for future checking 18041 DSAS->addMappedClassesQualTypes(TE->getType()); 18042 // Try to find the associated user-defined mapper. 18043 ExprResult ER = buildUserDefinedMapperRef( 18044 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 18045 VE->getType().getCanonicalType(), UnresolvedMapper); 18046 if (ER.isInvalid()) 18047 continue; 18048 MVLI.UDMapperList.push_back(ER.get()); 18049 // Skip restriction checking for variable or field declarations 18050 MVLI.ProcessedVarList.push_back(RE); 18051 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 18052 MVLI.VarComponents.back().append(CurComponents.begin(), 18053 CurComponents.end()); 18054 MVLI.VarBaseDeclarations.push_back(nullptr); 18055 continue; 18056 } 18057 18058 // For the following checks, we rely on the base declaration which is 18059 // expected to be associated with the last component. The declaration is 18060 // expected to be a variable or a field (if 'this' is being mapped). 18061 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 18062 assert(CurDeclaration && "Null decl on map clause."); 18063 assert( 18064 CurDeclaration->isCanonicalDecl() && 18065 "Expecting components to have associated only canonical declarations."); 18066 18067 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 18068 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 18069 18070 assert((VD || FD) && "Only variables or fields are expected here!"); 18071 (void)FD; 18072 18073 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 18074 // threadprivate variables cannot appear in a map clause. 18075 // OpenMP 4.5 [2.10.5, target update Construct] 18076 // threadprivate variables cannot appear in a from clause. 18077 if (VD && DSAS->isThreadPrivate(VD)) { 18078 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 18079 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 18080 << getOpenMPClauseName(CKind); 18081 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 18082 continue; 18083 } 18084 18085 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 18086 // A list item cannot appear in both a map clause and a data-sharing 18087 // attribute clause on the same construct. 18088 18089 // Check conflicts with other map clause expressions. We check the conflicts 18090 // with the current construct separately from the enclosing data 18091 // environment, because the restrictions are different. We only have to 18092 // check conflicts across regions for the map clauses. 18093 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 18094 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 18095 break; 18096 if (CKind == OMPC_map && 18097 (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) && 18098 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 18099 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 18100 break; 18101 18102 // OpenMP 4.5 [2.10.5, target update Construct] 18103 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 18104 // If the type of a list item is a reference to a type T then the type will 18105 // be considered to be T for all purposes of this clause. 18106 auto I = llvm::find_if( 18107 CurComponents, 18108 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 18109 return MC.getAssociatedDeclaration(); 18110 }); 18111 assert(I != CurComponents.end() && "Null decl on map clause."); 18112 QualType Type; 18113 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens()); 18114 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens()); 18115 auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens()); 18116 if (ASE) { 18117 Type = ASE->getType().getNonReferenceType(); 18118 } else if (OASE) { 18119 QualType BaseType = 18120 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 18121 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 18122 Type = ATy->getElementType(); 18123 else 18124 Type = BaseType->getPointeeType(); 18125 Type = Type.getNonReferenceType(); 18126 } else if (OAShE) { 18127 Type = OAShE->getBase()->getType()->getPointeeType(); 18128 } else { 18129 Type = VE->getType(); 18130 } 18131 18132 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 18133 // A list item in a to or from clause must have a mappable type. 18134 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 18135 // A list item must have a mappable type. 18136 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 18137 DSAS, Type)) 18138 continue; 18139 18140 if (CKind == OMPC_map) { 18141 // target enter data 18142 // OpenMP [2.10.2, Restrictions, p. 99] 18143 // A map-type must be specified in all map clauses and must be either 18144 // to or alloc. 18145 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 18146 if (DKind == OMPD_target_enter_data && 18147 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 18148 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 18149 << (IsMapTypeImplicit ? 1 : 0) 18150 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 18151 << getOpenMPDirectiveName(DKind); 18152 continue; 18153 } 18154 18155 // target exit_data 18156 // OpenMP [2.10.3, Restrictions, p. 102] 18157 // A map-type must be specified in all map clauses and must be either 18158 // from, release, or delete. 18159 if (DKind == OMPD_target_exit_data && 18160 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 18161 MapType == OMPC_MAP_delete)) { 18162 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 18163 << (IsMapTypeImplicit ? 1 : 0) 18164 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 18165 << getOpenMPDirectiveName(DKind); 18166 continue; 18167 } 18168 18169 // target, target data 18170 // OpenMP 5.0 [2.12.2, Restrictions, p. 163] 18171 // OpenMP 5.0 [2.12.5, Restrictions, p. 174] 18172 // A map-type in a map clause must be to, from, tofrom or alloc 18173 if ((DKind == OMPD_target_data || 18174 isOpenMPTargetExecutionDirective(DKind)) && 18175 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from || 18176 MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) { 18177 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 18178 << (IsMapTypeImplicit ? 1 : 0) 18179 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 18180 << getOpenMPDirectiveName(DKind); 18181 continue; 18182 } 18183 18184 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 18185 // A list item cannot appear in both a map clause and a data-sharing 18186 // attribute clause on the same construct 18187 // 18188 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 18189 // A list item cannot appear in both a map clause and a data-sharing 18190 // attribute clause on the same construct unless the construct is a 18191 // combined construct. 18192 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 && 18193 isOpenMPTargetExecutionDirective(DKind)) || 18194 DKind == OMPD_target)) { 18195 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 18196 if (isOpenMPPrivate(DVar.CKind)) { 18197 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 18198 << getOpenMPClauseName(DVar.CKind) 18199 << getOpenMPClauseName(OMPC_map) 18200 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 18201 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 18202 continue; 18203 } 18204 } 18205 } 18206 18207 // Try to find the associated user-defined mapper. 18208 ExprResult ER = buildUserDefinedMapperRef( 18209 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 18210 Type.getCanonicalType(), UnresolvedMapper); 18211 if (ER.isInvalid()) 18212 continue; 18213 MVLI.UDMapperList.push_back(ER.get()); 18214 18215 // Save the current expression. 18216 MVLI.ProcessedVarList.push_back(RE); 18217 18218 // Store the components in the stack so that they can be used to check 18219 // against other clauses later on. 18220 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 18221 /*WhereFoundClauseKind=*/OMPC_map); 18222 18223 // Save the components and declaration to create the clause. For purposes of 18224 // the clause creation, any component list that has has base 'this' uses 18225 // null as base declaration. 18226 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 18227 MVLI.VarComponents.back().append(CurComponents.begin(), 18228 CurComponents.end()); 18229 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 18230 : CurDeclaration); 18231 } 18232 } 18233 18234 OMPClause *Sema::ActOnOpenMPMapClause( 18235 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 18236 ArrayRef<SourceLocation> MapTypeModifiersLoc, 18237 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 18238 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, 18239 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 18240 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 18241 OpenMPMapModifierKind Modifiers[] = { 18242 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 18243 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown}; 18244 SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers]; 18245 18246 // Process map-type-modifiers, flag errors for duplicate modifiers. 18247 unsigned Count = 0; 18248 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 18249 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 18250 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) { 18251 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 18252 continue; 18253 } 18254 assert(Count < NumberOfOMPMapClauseModifiers && 18255 "Modifiers exceed the allowed number of map type modifiers"); 18256 Modifiers[Count] = MapTypeModifiers[I]; 18257 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 18258 ++Count; 18259 } 18260 18261 MappableVarListInfo MVLI(VarList); 18262 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc, 18263 MapperIdScopeSpec, MapperId, UnresolvedMappers, 18264 MapType, IsMapTypeImplicit); 18265 18266 // We need to produce a map clause even if we don't have variables so that 18267 // other diagnostics related with non-existing map clauses are accurate. 18268 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList, 18269 MVLI.VarBaseDeclarations, MVLI.VarComponents, 18270 MVLI.UDMapperList, Modifiers, ModifiersLoc, 18271 MapperIdScopeSpec.getWithLocInContext(Context), 18272 MapperId, MapType, IsMapTypeImplicit, MapLoc); 18273 } 18274 18275 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 18276 TypeResult ParsedType) { 18277 assert(ParsedType.isUsable()); 18278 18279 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 18280 if (ReductionType.isNull()) 18281 return QualType(); 18282 18283 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 18284 // A type name in a declare reduction directive cannot be a function type, an 18285 // array type, a reference type, or a type qualified with const, volatile or 18286 // restrict. 18287 if (ReductionType.hasQualifiers()) { 18288 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 18289 return QualType(); 18290 } 18291 18292 if (ReductionType->isFunctionType()) { 18293 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 18294 return QualType(); 18295 } 18296 if (ReductionType->isReferenceType()) { 18297 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 18298 return QualType(); 18299 } 18300 if (ReductionType->isArrayType()) { 18301 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 18302 return QualType(); 18303 } 18304 return ReductionType; 18305 } 18306 18307 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 18308 Scope *S, DeclContext *DC, DeclarationName Name, 18309 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 18310 AccessSpecifier AS, Decl *PrevDeclInScope) { 18311 SmallVector<Decl *, 8> Decls; 18312 Decls.reserve(ReductionTypes.size()); 18313 18314 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 18315 forRedeclarationInCurContext()); 18316 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 18317 // A reduction-identifier may not be re-declared in the current scope for the 18318 // same type or for a type that is compatible according to the base language 18319 // rules. 18320 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 18321 OMPDeclareReductionDecl *PrevDRD = nullptr; 18322 bool InCompoundScope = true; 18323 if (S != nullptr) { 18324 // Find previous declaration with the same name not referenced in other 18325 // declarations. 18326 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 18327 InCompoundScope = 18328 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 18329 LookupName(Lookup, S); 18330 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 18331 /*AllowInlineNamespace=*/false); 18332 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 18333 LookupResult::Filter Filter = Lookup.makeFilter(); 18334 while (Filter.hasNext()) { 18335 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 18336 if (InCompoundScope) { 18337 auto I = UsedAsPrevious.find(PrevDecl); 18338 if (I == UsedAsPrevious.end()) 18339 UsedAsPrevious[PrevDecl] = false; 18340 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 18341 UsedAsPrevious[D] = true; 18342 } 18343 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 18344 PrevDecl->getLocation(); 18345 } 18346 Filter.done(); 18347 if (InCompoundScope) { 18348 for (const auto &PrevData : UsedAsPrevious) { 18349 if (!PrevData.second) { 18350 PrevDRD = PrevData.first; 18351 break; 18352 } 18353 } 18354 } 18355 } else if (PrevDeclInScope != nullptr) { 18356 auto *PrevDRDInScope = PrevDRD = 18357 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 18358 do { 18359 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 18360 PrevDRDInScope->getLocation(); 18361 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 18362 } while (PrevDRDInScope != nullptr); 18363 } 18364 for (const auto &TyData : ReductionTypes) { 18365 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 18366 bool Invalid = false; 18367 if (I != PreviousRedeclTypes.end()) { 18368 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 18369 << TyData.first; 18370 Diag(I->second, diag::note_previous_definition); 18371 Invalid = true; 18372 } 18373 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 18374 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 18375 Name, TyData.first, PrevDRD); 18376 DC->addDecl(DRD); 18377 DRD->setAccess(AS); 18378 Decls.push_back(DRD); 18379 if (Invalid) 18380 DRD->setInvalidDecl(); 18381 else 18382 PrevDRD = DRD; 18383 } 18384 18385 return DeclGroupPtrTy::make( 18386 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 18387 } 18388 18389 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 18390 auto *DRD = cast<OMPDeclareReductionDecl>(D); 18391 18392 // Enter new function scope. 18393 PushFunctionScope(); 18394 setFunctionHasBranchProtectedScope(); 18395 getCurFunction()->setHasOMPDeclareReductionCombiner(); 18396 18397 if (S != nullptr) 18398 PushDeclContext(S, DRD); 18399 else 18400 CurContext = DRD; 18401 18402 PushExpressionEvaluationContext( 18403 ExpressionEvaluationContext::PotentiallyEvaluated); 18404 18405 QualType ReductionType = DRD->getType(); 18406 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 18407 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 18408 // uses semantics of argument handles by value, but it should be passed by 18409 // reference. C lang does not support references, so pass all parameters as 18410 // pointers. 18411 // Create 'T omp_in;' variable. 18412 VarDecl *OmpInParm = 18413 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 18414 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 18415 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 18416 // uses semantics of argument handles by value, but it should be passed by 18417 // reference. C lang does not support references, so pass all parameters as 18418 // pointers. 18419 // Create 'T omp_out;' variable. 18420 VarDecl *OmpOutParm = 18421 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 18422 if (S != nullptr) { 18423 PushOnScopeChains(OmpInParm, S); 18424 PushOnScopeChains(OmpOutParm, S); 18425 } else { 18426 DRD->addDecl(OmpInParm); 18427 DRD->addDecl(OmpOutParm); 18428 } 18429 Expr *InE = 18430 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 18431 Expr *OutE = 18432 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 18433 DRD->setCombinerData(InE, OutE); 18434 } 18435 18436 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 18437 auto *DRD = cast<OMPDeclareReductionDecl>(D); 18438 DiscardCleanupsInEvaluationContext(); 18439 PopExpressionEvaluationContext(); 18440 18441 PopDeclContext(); 18442 PopFunctionScopeInfo(); 18443 18444 if (Combiner != nullptr) 18445 DRD->setCombiner(Combiner); 18446 else 18447 DRD->setInvalidDecl(); 18448 } 18449 18450 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 18451 auto *DRD = cast<OMPDeclareReductionDecl>(D); 18452 18453 // Enter new function scope. 18454 PushFunctionScope(); 18455 setFunctionHasBranchProtectedScope(); 18456 18457 if (S != nullptr) 18458 PushDeclContext(S, DRD); 18459 else 18460 CurContext = DRD; 18461 18462 PushExpressionEvaluationContext( 18463 ExpressionEvaluationContext::PotentiallyEvaluated); 18464 18465 QualType ReductionType = DRD->getType(); 18466 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 18467 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 18468 // uses semantics of argument handles by value, but it should be passed by 18469 // reference. C lang does not support references, so pass all parameters as 18470 // pointers. 18471 // Create 'T omp_priv;' variable. 18472 VarDecl *OmpPrivParm = 18473 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 18474 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 18475 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 18476 // uses semantics of argument handles by value, but it should be passed by 18477 // reference. C lang does not support references, so pass all parameters as 18478 // pointers. 18479 // Create 'T omp_orig;' variable. 18480 VarDecl *OmpOrigParm = 18481 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 18482 if (S != nullptr) { 18483 PushOnScopeChains(OmpPrivParm, S); 18484 PushOnScopeChains(OmpOrigParm, S); 18485 } else { 18486 DRD->addDecl(OmpPrivParm); 18487 DRD->addDecl(OmpOrigParm); 18488 } 18489 Expr *OrigE = 18490 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 18491 Expr *PrivE = 18492 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 18493 DRD->setInitializerData(OrigE, PrivE); 18494 return OmpPrivParm; 18495 } 18496 18497 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 18498 VarDecl *OmpPrivParm) { 18499 auto *DRD = cast<OMPDeclareReductionDecl>(D); 18500 DiscardCleanupsInEvaluationContext(); 18501 PopExpressionEvaluationContext(); 18502 18503 PopDeclContext(); 18504 PopFunctionScopeInfo(); 18505 18506 if (Initializer != nullptr) { 18507 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 18508 } else if (OmpPrivParm->hasInit()) { 18509 DRD->setInitializer(OmpPrivParm->getInit(), 18510 OmpPrivParm->isDirectInit() 18511 ? OMPDeclareReductionDecl::DirectInit 18512 : OMPDeclareReductionDecl::CopyInit); 18513 } else { 18514 DRD->setInvalidDecl(); 18515 } 18516 } 18517 18518 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 18519 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 18520 for (Decl *D : DeclReductions.get()) { 18521 if (IsValid) { 18522 if (S) 18523 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 18524 /*AddToContext=*/false); 18525 } else { 18526 D->setInvalidDecl(); 18527 } 18528 } 18529 return DeclReductions; 18530 } 18531 18532 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 18533 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18534 QualType T = TInfo->getType(); 18535 if (D.isInvalidType()) 18536 return true; 18537 18538 if (getLangOpts().CPlusPlus) { 18539 // Check that there are no default arguments (C++ only). 18540 CheckExtraCXXDefaultArguments(D); 18541 } 18542 18543 return CreateParsedType(T, TInfo); 18544 } 18545 18546 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 18547 TypeResult ParsedType) { 18548 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 18549 18550 QualType MapperType = GetTypeFromParser(ParsedType.get()); 18551 assert(!MapperType.isNull() && "Expect valid mapper type"); 18552 18553 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 18554 // The type must be of struct, union or class type in C and C++ 18555 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 18556 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 18557 return QualType(); 18558 } 18559 return MapperType; 18560 } 18561 18562 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective( 18563 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 18564 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 18565 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) { 18566 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 18567 forRedeclarationInCurContext()); 18568 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 18569 // A mapper-identifier may not be redeclared in the current scope for the 18570 // same type or for a type that is compatible according to the base language 18571 // rules. 18572 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 18573 OMPDeclareMapperDecl *PrevDMD = nullptr; 18574 bool InCompoundScope = true; 18575 if (S != nullptr) { 18576 // Find previous declaration with the same name not referenced in other 18577 // declarations. 18578 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 18579 InCompoundScope = 18580 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 18581 LookupName(Lookup, S); 18582 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 18583 /*AllowInlineNamespace=*/false); 18584 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 18585 LookupResult::Filter Filter = Lookup.makeFilter(); 18586 while (Filter.hasNext()) { 18587 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 18588 if (InCompoundScope) { 18589 auto I = UsedAsPrevious.find(PrevDecl); 18590 if (I == UsedAsPrevious.end()) 18591 UsedAsPrevious[PrevDecl] = false; 18592 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 18593 UsedAsPrevious[D] = true; 18594 } 18595 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 18596 PrevDecl->getLocation(); 18597 } 18598 Filter.done(); 18599 if (InCompoundScope) { 18600 for (const auto &PrevData : UsedAsPrevious) { 18601 if (!PrevData.second) { 18602 PrevDMD = PrevData.first; 18603 break; 18604 } 18605 } 18606 } 18607 } else if (PrevDeclInScope) { 18608 auto *PrevDMDInScope = PrevDMD = 18609 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 18610 do { 18611 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 18612 PrevDMDInScope->getLocation(); 18613 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 18614 } while (PrevDMDInScope != nullptr); 18615 } 18616 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 18617 bool Invalid = false; 18618 if (I != PreviousRedeclTypes.end()) { 18619 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 18620 << MapperType << Name; 18621 Diag(I->second, diag::note_previous_definition); 18622 Invalid = true; 18623 } 18624 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, 18625 MapperType, VN, Clauses, PrevDMD); 18626 if (S) 18627 PushOnScopeChains(DMD, S); 18628 else 18629 DC->addDecl(DMD); 18630 DMD->setAccess(AS); 18631 if (Invalid) 18632 DMD->setInvalidDecl(); 18633 18634 auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl(); 18635 VD->setDeclContext(DMD); 18636 VD->setLexicalDeclContext(DMD); 18637 DMD->addDecl(VD); 18638 DMD->setMapperVarRef(MapperVarRef); 18639 18640 return DeclGroupPtrTy::make(DeclGroupRef(DMD)); 18641 } 18642 18643 ExprResult 18644 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, 18645 SourceLocation StartLoc, 18646 DeclarationName VN) { 18647 TypeSourceInfo *TInfo = 18648 Context.getTrivialTypeSourceInfo(MapperType, StartLoc); 18649 auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(), 18650 StartLoc, StartLoc, VN.getAsIdentifierInfo(), 18651 MapperType, TInfo, SC_None); 18652 if (S) 18653 PushOnScopeChains(VD, S, /*AddToContext=*/false); 18654 Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 18655 DSAStack->addDeclareMapperVarRef(E); 18656 return E; 18657 } 18658 18659 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const { 18660 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 18661 const Expr *Ref = DSAStack->getDeclareMapperVarRef(); 18662 if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) 18663 return VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl(); 18664 return true; 18665 } 18666 18667 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const { 18668 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 18669 return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl(); 18670 } 18671 18672 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 18673 SourceLocation StartLoc, 18674 SourceLocation LParenLoc, 18675 SourceLocation EndLoc) { 18676 Expr *ValExpr = NumTeams; 18677 Stmt *HelperValStmt = nullptr; 18678 18679 // OpenMP [teams Constrcut, Restrictions] 18680 // The num_teams expression must evaluate to a positive integer value. 18681 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 18682 /*StrictlyPositive=*/true)) 18683 return nullptr; 18684 18685 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 18686 OpenMPDirectiveKind CaptureRegion = 18687 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP); 18688 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 18689 ValExpr = MakeFullExpr(ValExpr).get(); 18690 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 18691 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 18692 HelperValStmt = buildPreInits(Context, Captures); 18693 } 18694 18695 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 18696 StartLoc, LParenLoc, EndLoc); 18697 } 18698 18699 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 18700 SourceLocation StartLoc, 18701 SourceLocation LParenLoc, 18702 SourceLocation EndLoc) { 18703 Expr *ValExpr = ThreadLimit; 18704 Stmt *HelperValStmt = nullptr; 18705 18706 // OpenMP [teams Constrcut, Restrictions] 18707 // The thread_limit expression must evaluate to a positive integer value. 18708 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 18709 /*StrictlyPositive=*/true)) 18710 return nullptr; 18711 18712 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 18713 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause( 18714 DKind, OMPC_thread_limit, LangOpts.OpenMP); 18715 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 18716 ValExpr = MakeFullExpr(ValExpr).get(); 18717 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 18718 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 18719 HelperValStmt = buildPreInits(Context, Captures); 18720 } 18721 18722 return new (Context) OMPThreadLimitClause( 18723 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 18724 } 18725 18726 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 18727 SourceLocation StartLoc, 18728 SourceLocation LParenLoc, 18729 SourceLocation EndLoc) { 18730 Expr *ValExpr = Priority; 18731 Stmt *HelperValStmt = nullptr; 18732 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 18733 18734 // OpenMP [2.9.1, task Constrcut] 18735 // The priority-value is a non-negative numerical scalar expression. 18736 if (!isNonNegativeIntegerValue( 18737 ValExpr, *this, OMPC_priority, 18738 /*StrictlyPositive=*/false, /*BuildCapture=*/true, 18739 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 18740 return nullptr; 18741 18742 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion, 18743 StartLoc, LParenLoc, EndLoc); 18744 } 18745 18746 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 18747 SourceLocation StartLoc, 18748 SourceLocation LParenLoc, 18749 SourceLocation EndLoc) { 18750 Expr *ValExpr = Grainsize; 18751 Stmt *HelperValStmt = nullptr; 18752 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 18753 18754 // OpenMP [2.9.2, taskloop Constrcut] 18755 // The parameter of the grainsize clause must be a positive integer 18756 // expression. 18757 if (!isNonNegativeIntegerValue( 18758 ValExpr, *this, OMPC_grainsize, 18759 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 18760 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 18761 return nullptr; 18762 18763 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion, 18764 StartLoc, LParenLoc, EndLoc); 18765 } 18766 18767 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 18768 SourceLocation StartLoc, 18769 SourceLocation LParenLoc, 18770 SourceLocation EndLoc) { 18771 Expr *ValExpr = NumTasks; 18772 Stmt *HelperValStmt = nullptr; 18773 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 18774 18775 // OpenMP [2.9.2, taskloop Constrcut] 18776 // The parameter of the num_tasks clause must be a positive integer 18777 // expression. 18778 if (!isNonNegativeIntegerValue( 18779 ValExpr, *this, OMPC_num_tasks, 18780 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 18781 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 18782 return nullptr; 18783 18784 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion, 18785 StartLoc, LParenLoc, EndLoc); 18786 } 18787 18788 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 18789 SourceLocation LParenLoc, 18790 SourceLocation EndLoc) { 18791 // OpenMP [2.13.2, critical construct, Description] 18792 // ... where hint-expression is an integer constant expression that evaluates 18793 // to a valid lock hint. 18794 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 18795 if (HintExpr.isInvalid()) 18796 return nullptr; 18797 return new (Context) 18798 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 18799 } 18800 18801 /// Tries to find omp_event_handle_t type. 18802 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc, 18803 DSAStackTy *Stack) { 18804 QualType OMPEventHandleT = Stack->getOMPEventHandleT(); 18805 if (!OMPEventHandleT.isNull()) 18806 return true; 18807 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t"); 18808 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 18809 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 18810 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t"; 18811 return false; 18812 } 18813 Stack->setOMPEventHandleT(PT.get()); 18814 return true; 18815 } 18816 18817 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 18818 SourceLocation LParenLoc, 18819 SourceLocation EndLoc) { 18820 if (!Evt->isValueDependent() && !Evt->isTypeDependent() && 18821 !Evt->isInstantiationDependent() && 18822 !Evt->containsUnexpandedParameterPack()) { 18823 if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack)) 18824 return nullptr; 18825 // OpenMP 5.0, 2.10.1 task Construct. 18826 // event-handle is a variable of the omp_event_handle_t type. 18827 auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts()); 18828 if (!Ref) { 18829 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 18830 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 18831 return nullptr; 18832 } 18833 auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl()); 18834 if (!VD) { 18835 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 18836 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 18837 return nullptr; 18838 } 18839 if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(), 18840 VD->getType()) || 18841 VD->getType().isConstant(Context)) { 18842 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 18843 << "omp_event_handle_t" << 1 << VD->getType() 18844 << Evt->getSourceRange(); 18845 return nullptr; 18846 } 18847 // OpenMP 5.0, 2.10.1 task Construct 18848 // [detach clause]... The event-handle will be considered as if it was 18849 // specified on a firstprivate clause. 18850 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false); 18851 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 18852 DVar.RefExpr) { 18853 Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa) 18854 << getOpenMPClauseName(DVar.CKind) 18855 << getOpenMPClauseName(OMPC_firstprivate); 18856 reportOriginalDsa(*this, DSAStack, VD, DVar); 18857 return nullptr; 18858 } 18859 } 18860 18861 return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc); 18862 } 18863 18864 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 18865 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 18866 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 18867 SourceLocation EndLoc) { 18868 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 18869 std::string Values; 18870 Values += "'"; 18871 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 18872 Values += "'"; 18873 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 18874 << Values << getOpenMPClauseName(OMPC_dist_schedule); 18875 return nullptr; 18876 } 18877 Expr *ValExpr = ChunkSize; 18878 Stmt *HelperValStmt = nullptr; 18879 if (ChunkSize) { 18880 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 18881 !ChunkSize->isInstantiationDependent() && 18882 !ChunkSize->containsUnexpandedParameterPack()) { 18883 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 18884 ExprResult Val = 18885 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 18886 if (Val.isInvalid()) 18887 return nullptr; 18888 18889 ValExpr = Val.get(); 18890 18891 // OpenMP [2.7.1, Restrictions] 18892 // chunk_size must be a loop invariant integer expression with a positive 18893 // value. 18894 if (Optional<llvm::APSInt> Result = 18895 ValExpr->getIntegerConstantExpr(Context)) { 18896 if (Result->isSigned() && !Result->isStrictlyPositive()) { 18897 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 18898 << "dist_schedule" << ChunkSize->getSourceRange(); 18899 return nullptr; 18900 } 18901 } else if (getOpenMPCaptureRegionForClause( 18902 DSAStack->getCurrentDirective(), OMPC_dist_schedule, 18903 LangOpts.OpenMP) != OMPD_unknown && 18904 !CurContext->isDependentContext()) { 18905 ValExpr = MakeFullExpr(ValExpr).get(); 18906 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 18907 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 18908 HelperValStmt = buildPreInits(Context, Captures); 18909 } 18910 } 18911 } 18912 18913 return new (Context) 18914 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 18915 Kind, ValExpr, HelperValStmt); 18916 } 18917 18918 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 18919 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 18920 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 18921 SourceLocation KindLoc, SourceLocation EndLoc) { 18922 if (getLangOpts().OpenMP < 50) { 18923 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || 18924 Kind != OMPC_DEFAULTMAP_scalar) { 18925 std::string Value; 18926 SourceLocation Loc; 18927 Value += "'"; 18928 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 18929 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 18930 OMPC_DEFAULTMAP_MODIFIER_tofrom); 18931 Loc = MLoc; 18932 } else { 18933 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 18934 OMPC_DEFAULTMAP_scalar); 18935 Loc = KindLoc; 18936 } 18937 Value += "'"; 18938 Diag(Loc, diag::err_omp_unexpected_clause_value) 18939 << Value << getOpenMPClauseName(OMPC_defaultmap); 18940 return nullptr; 18941 } 18942 } else { 18943 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown); 18944 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) || 18945 (LangOpts.OpenMP >= 50 && KindLoc.isInvalid()); 18946 if (!isDefaultmapKind || !isDefaultmapModifier) { 18947 StringRef KindValue = "'scalar', 'aggregate', 'pointer'"; 18948 if (LangOpts.OpenMP == 50) { 18949 StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', " 18950 "'firstprivate', 'none', 'default'"; 18951 if (!isDefaultmapKind && isDefaultmapModifier) { 18952 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 18953 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 18954 } else if (isDefaultmapKind && !isDefaultmapModifier) { 18955 Diag(MLoc, diag::err_omp_unexpected_clause_value) 18956 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 18957 } else { 18958 Diag(MLoc, diag::err_omp_unexpected_clause_value) 18959 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 18960 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 18961 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 18962 } 18963 } else { 18964 StringRef ModifierValue = 18965 "'alloc', 'from', 'to', 'tofrom', " 18966 "'firstprivate', 'none', 'default', 'present'"; 18967 if (!isDefaultmapKind && isDefaultmapModifier) { 18968 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 18969 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 18970 } else if (isDefaultmapKind && !isDefaultmapModifier) { 18971 Diag(MLoc, diag::err_omp_unexpected_clause_value) 18972 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 18973 } else { 18974 Diag(MLoc, diag::err_omp_unexpected_clause_value) 18975 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 18976 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 18977 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 18978 } 18979 } 18980 return nullptr; 18981 } 18982 18983 // OpenMP [5.0, 2.12.5, Restrictions, p. 174] 18984 // At most one defaultmap clause for each category can appear on the 18985 // directive. 18986 if (DSAStack->checkDefaultmapCategory(Kind)) { 18987 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category); 18988 return nullptr; 18989 } 18990 } 18991 if (Kind == OMPC_DEFAULTMAP_unknown) { 18992 // Variable category is not specified - mark all categories. 18993 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc); 18994 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc); 18995 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc); 18996 } else { 18997 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc); 18998 } 18999 19000 return new (Context) 19001 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 19002 } 19003 19004 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 19005 DeclContext *CurLexicalContext = getCurLexicalContext(); 19006 if (!CurLexicalContext->isFileContext() && 19007 !CurLexicalContext->isExternCContext() && 19008 !CurLexicalContext->isExternCXXContext() && 19009 !isa<CXXRecordDecl>(CurLexicalContext) && 19010 !isa<ClassTemplateDecl>(CurLexicalContext) && 19011 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 19012 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 19013 Diag(Loc, diag::err_omp_region_not_file_context); 19014 return false; 19015 } 19016 DeclareTargetNesting.push_back(Loc); 19017 return true; 19018 } 19019 19020 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 19021 assert(!DeclareTargetNesting.empty() && 19022 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 19023 DeclareTargetNesting.pop_back(); 19024 } 19025 19026 NamedDecl * 19027 Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, 19028 const DeclarationNameInfo &Id, 19029 NamedDeclSetType &SameDirectiveDecls) { 19030 LookupResult Lookup(*this, Id, LookupOrdinaryName); 19031 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 19032 19033 if (Lookup.isAmbiguous()) 19034 return nullptr; 19035 Lookup.suppressDiagnostics(); 19036 19037 if (!Lookup.isSingleResult()) { 19038 VarOrFuncDeclFilterCCC CCC(*this); 19039 if (TypoCorrection Corrected = 19040 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 19041 CTK_ErrorRecovery)) { 19042 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 19043 << Id.getName()); 19044 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 19045 return nullptr; 19046 } 19047 19048 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 19049 return nullptr; 19050 } 19051 19052 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 19053 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) && 19054 !isa<FunctionTemplateDecl>(ND)) { 19055 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 19056 return nullptr; 19057 } 19058 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 19059 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 19060 return ND; 19061 } 19062 19063 void Sema::ActOnOpenMPDeclareTargetName( 19064 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, 19065 OMPDeclareTargetDeclAttr::DevTypeTy DT) { 19066 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 19067 isa<FunctionTemplateDecl>(ND)) && 19068 "Expected variable, function or function template."); 19069 19070 // Diagnose marking after use as it may lead to incorrect diagnosis and 19071 // codegen. 19072 if (LangOpts.OpenMP >= 50 && 19073 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced())) 19074 Diag(Loc, diag::warn_omp_declare_target_after_first_use); 19075 19076 auto *VD = cast<ValueDecl>(ND); 19077 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 19078 OMPDeclareTargetDeclAttr::getDeviceType(VD); 19079 Optional<SourceLocation> AttrLoc = OMPDeclareTargetDeclAttr::getLocation(VD); 19080 if (DevTy.hasValue() && *DevTy != DT && 19081 (DeclareTargetNesting.empty() || 19082 *AttrLoc != DeclareTargetNesting.back())) { 19083 Diag(Loc, diag::err_omp_device_type_mismatch) 19084 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT) 19085 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy); 19086 return; 19087 } 19088 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 19089 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 19090 if (!Res || (!DeclareTargetNesting.empty() && 19091 *AttrLoc == DeclareTargetNesting.back())) { 19092 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 19093 Context, MT, DT, DeclareTargetNesting.size() + 1, 19094 SourceRange(Loc, Loc)); 19095 ND->addAttr(A); 19096 if (ASTMutationListener *ML = Context.getASTMutationListener()) 19097 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 19098 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc); 19099 } else if (*Res != MT) { 19100 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND; 19101 } 19102 } 19103 19104 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 19105 Sema &SemaRef, Decl *D) { 19106 if (!D || !isa<VarDecl>(D)) 19107 return; 19108 auto *VD = cast<VarDecl>(D); 19109 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = 19110 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 19111 if (SemaRef.LangOpts.OpenMP >= 50 && 19112 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) || 19113 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) && 19114 VD->hasGlobalStorage()) { 19115 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = 19116 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 19117 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) { 19118 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions 19119 // If a lambda declaration and definition appears between a 19120 // declare target directive and the matching end declare target 19121 // directive, all variables that are captured by the lambda 19122 // expression must also appear in a to clause. 19123 SemaRef.Diag(VD->getLocation(), 19124 diag::err_omp_lambda_capture_in_declare_target_not_to); 19125 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here) 19126 << VD << 0 << SR; 19127 return; 19128 } 19129 } 19130 if (MapTy.hasValue()) 19131 return; 19132 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 19133 SemaRef.Diag(SL, diag::note_used_here) << SR; 19134 } 19135 19136 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 19137 Sema &SemaRef, DSAStackTy *Stack, 19138 ValueDecl *VD) { 19139 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) || 19140 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 19141 /*FullCheck=*/false); 19142 } 19143 19144 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 19145 SourceLocation IdLoc) { 19146 if (!D || D->isInvalidDecl()) 19147 return; 19148 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 19149 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 19150 if (auto *VD = dyn_cast<VarDecl>(D)) { 19151 // Only global variables can be marked as declare target. 19152 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 19153 !VD->isStaticDataMember()) 19154 return; 19155 // 2.10.6: threadprivate variable cannot appear in a declare target 19156 // directive. 19157 if (DSAStack->isThreadPrivate(VD)) { 19158 Diag(SL, diag::err_omp_threadprivate_in_target); 19159 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 19160 return; 19161 } 19162 } 19163 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 19164 D = FTD->getTemplatedDecl(); 19165 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 19166 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 19167 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 19168 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 19169 Diag(IdLoc, diag::err_omp_function_in_link_clause); 19170 Diag(FD->getLocation(), diag::note_defined_here) << FD; 19171 return; 19172 } 19173 } 19174 if (auto *VD = dyn_cast<ValueDecl>(D)) { 19175 // Problem if any with var declared with incomplete type will be reported 19176 // as normal, so no need to check it here. 19177 if ((E || !VD->getType()->isIncompleteType()) && 19178 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 19179 return; 19180 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 19181 // Checking declaration inside declare target region. 19182 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 19183 isa<FunctionTemplateDecl>(D)) { 19184 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 19185 Context, OMPDeclareTargetDeclAttr::MT_To, 19186 OMPDeclareTargetDeclAttr::DT_Any, DeclareTargetNesting.size(), 19187 SourceRange(DeclareTargetNesting.back(), 19188 DeclareTargetNesting.back())); 19189 D->addAttr(A); 19190 if (ASTMutationListener *ML = Context.getASTMutationListener()) 19191 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 19192 } 19193 return; 19194 } 19195 } 19196 if (!E) 19197 return; 19198 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 19199 } 19200 19201 OMPClause *Sema::ActOnOpenMPToClause( 19202 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 19203 ArrayRef<SourceLocation> MotionModifiersLoc, 19204 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 19205 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 19206 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 19207 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 19208 OMPC_MOTION_MODIFIER_unknown}; 19209 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 19210 19211 // Process motion-modifiers, flag errors for duplicate modifiers. 19212 unsigned Count = 0; 19213 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 19214 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 19215 llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) { 19216 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 19217 continue; 19218 } 19219 assert(Count < NumberOfOMPMotionModifiers && 19220 "Modifiers exceed the allowed number of motion modifiers"); 19221 Modifiers[Count] = MotionModifiers[I]; 19222 ModifiersLoc[Count] = MotionModifiersLoc[I]; 19223 ++Count; 19224 } 19225 19226 MappableVarListInfo MVLI(VarList); 19227 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc, 19228 MapperIdScopeSpec, MapperId, UnresolvedMappers); 19229 if (MVLI.ProcessedVarList.empty()) 19230 return nullptr; 19231 19232 return OMPToClause::Create( 19233 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 19234 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 19235 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 19236 } 19237 19238 OMPClause *Sema::ActOnOpenMPFromClause( 19239 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 19240 ArrayRef<SourceLocation> MotionModifiersLoc, 19241 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 19242 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 19243 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 19244 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 19245 OMPC_MOTION_MODIFIER_unknown}; 19246 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 19247 19248 // Process motion-modifiers, flag errors for duplicate modifiers. 19249 unsigned Count = 0; 19250 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 19251 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 19252 llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) { 19253 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 19254 continue; 19255 } 19256 assert(Count < NumberOfOMPMotionModifiers && 19257 "Modifiers exceed the allowed number of motion modifiers"); 19258 Modifiers[Count] = MotionModifiers[I]; 19259 ModifiersLoc[Count] = MotionModifiersLoc[I]; 19260 ++Count; 19261 } 19262 19263 MappableVarListInfo MVLI(VarList); 19264 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc, 19265 MapperIdScopeSpec, MapperId, UnresolvedMappers); 19266 if (MVLI.ProcessedVarList.empty()) 19267 return nullptr; 19268 19269 return OMPFromClause::Create( 19270 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 19271 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 19272 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 19273 } 19274 19275 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 19276 const OMPVarListLocTy &Locs) { 19277 MappableVarListInfo MVLI(VarList); 19278 SmallVector<Expr *, 8> PrivateCopies; 19279 SmallVector<Expr *, 8> Inits; 19280 19281 for (Expr *RefExpr : VarList) { 19282 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 19283 SourceLocation ELoc; 19284 SourceRange ERange; 19285 Expr *SimpleRefExpr = RefExpr; 19286 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 19287 if (Res.second) { 19288 // It will be analyzed later. 19289 MVLI.ProcessedVarList.push_back(RefExpr); 19290 PrivateCopies.push_back(nullptr); 19291 Inits.push_back(nullptr); 19292 } 19293 ValueDecl *D = Res.first; 19294 if (!D) 19295 continue; 19296 19297 QualType Type = D->getType(); 19298 Type = Type.getNonReferenceType().getUnqualifiedType(); 19299 19300 auto *VD = dyn_cast<VarDecl>(D); 19301 19302 // Item should be a pointer or reference to pointer. 19303 if (!Type->isPointerType()) { 19304 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 19305 << 0 << RefExpr->getSourceRange(); 19306 continue; 19307 } 19308 19309 // Build the private variable and the expression that refers to it. 19310 auto VDPrivate = 19311 buildVarDecl(*this, ELoc, Type, D->getName(), 19312 D->hasAttrs() ? &D->getAttrs() : nullptr, 19313 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 19314 if (VDPrivate->isInvalidDecl()) 19315 continue; 19316 19317 CurContext->addDecl(VDPrivate); 19318 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 19319 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 19320 19321 // Add temporary variable to initialize the private copy of the pointer. 19322 VarDecl *VDInit = 19323 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 19324 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 19325 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 19326 AddInitializerToDecl(VDPrivate, 19327 DefaultLvalueConversion(VDInitRefExpr).get(), 19328 /*DirectInit=*/false); 19329 19330 // If required, build a capture to implement the privatization initialized 19331 // with the current list item value. 19332 DeclRefExpr *Ref = nullptr; 19333 if (!VD) 19334 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 19335 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 19336 PrivateCopies.push_back(VDPrivateRefExpr); 19337 Inits.push_back(VDInitRefExpr); 19338 19339 // We need to add a data sharing attribute for this variable to make sure it 19340 // is correctly captured. A variable that shows up in a use_device_ptr has 19341 // similar properties of a first private variable. 19342 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 19343 19344 // Create a mappable component for the list item. List items in this clause 19345 // only need a component. 19346 MVLI.VarBaseDeclarations.push_back(D); 19347 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 19348 MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D, 19349 /*IsNonContiguous=*/false); 19350 } 19351 19352 if (MVLI.ProcessedVarList.empty()) 19353 return nullptr; 19354 19355 return OMPUseDevicePtrClause::Create( 19356 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits, 19357 MVLI.VarBaseDeclarations, MVLI.VarComponents); 19358 } 19359 19360 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 19361 const OMPVarListLocTy &Locs) { 19362 MappableVarListInfo MVLI(VarList); 19363 19364 for (Expr *RefExpr : VarList) { 19365 assert(RefExpr && "NULL expr in OpenMP use_device_addr clause."); 19366 SourceLocation ELoc; 19367 SourceRange ERange; 19368 Expr *SimpleRefExpr = RefExpr; 19369 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 19370 /*AllowArraySection=*/true); 19371 if (Res.second) { 19372 // It will be analyzed later. 19373 MVLI.ProcessedVarList.push_back(RefExpr); 19374 } 19375 ValueDecl *D = Res.first; 19376 if (!D) 19377 continue; 19378 auto *VD = dyn_cast<VarDecl>(D); 19379 19380 // If required, build a capture to implement the privatization initialized 19381 // with the current list item value. 19382 DeclRefExpr *Ref = nullptr; 19383 if (!VD) 19384 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 19385 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 19386 19387 // We need to add a data sharing attribute for this variable to make sure it 19388 // is correctly captured. A variable that shows up in a use_device_addr has 19389 // similar properties of a first private variable. 19390 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 19391 19392 // Create a mappable component for the list item. List items in this clause 19393 // only need a component. 19394 MVLI.VarBaseDeclarations.push_back(D); 19395 MVLI.VarComponents.emplace_back(); 19396 Expr *Component = SimpleRefExpr; 19397 if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) || 19398 isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts()))) 19399 Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get(); 19400 MVLI.VarComponents.back().emplace_back(Component, D, 19401 /*IsNonContiguous=*/false); 19402 } 19403 19404 if (MVLI.ProcessedVarList.empty()) 19405 return nullptr; 19406 19407 return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList, 19408 MVLI.VarBaseDeclarations, 19409 MVLI.VarComponents); 19410 } 19411 19412 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 19413 const OMPVarListLocTy &Locs) { 19414 MappableVarListInfo MVLI(VarList); 19415 for (Expr *RefExpr : VarList) { 19416 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 19417 SourceLocation ELoc; 19418 SourceRange ERange; 19419 Expr *SimpleRefExpr = RefExpr; 19420 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 19421 if (Res.second) { 19422 // It will be analyzed later. 19423 MVLI.ProcessedVarList.push_back(RefExpr); 19424 } 19425 ValueDecl *D = Res.first; 19426 if (!D) 19427 continue; 19428 19429 QualType Type = D->getType(); 19430 // item should be a pointer or array or reference to pointer or array 19431 if (!Type.getNonReferenceType()->isPointerType() && 19432 !Type.getNonReferenceType()->isArrayType()) { 19433 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 19434 << 0 << RefExpr->getSourceRange(); 19435 continue; 19436 } 19437 19438 // Check if the declaration in the clause does not show up in any data 19439 // sharing attribute. 19440 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 19441 if (isOpenMPPrivate(DVar.CKind)) { 19442 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 19443 << getOpenMPClauseName(DVar.CKind) 19444 << getOpenMPClauseName(OMPC_is_device_ptr) 19445 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 19446 reportOriginalDsa(*this, DSAStack, D, DVar); 19447 continue; 19448 } 19449 19450 const Expr *ConflictExpr; 19451 if (DSAStack->checkMappableExprComponentListsForDecl( 19452 D, /*CurrentRegionOnly=*/true, 19453 [&ConflictExpr]( 19454 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 19455 OpenMPClauseKind) -> bool { 19456 ConflictExpr = R.front().getAssociatedExpression(); 19457 return true; 19458 })) { 19459 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 19460 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 19461 << ConflictExpr->getSourceRange(); 19462 continue; 19463 } 19464 19465 // Store the components in the stack so that they can be used to check 19466 // against other clauses later on. 19467 OMPClauseMappableExprCommon::MappableComponent MC( 19468 SimpleRefExpr, D, /*IsNonContiguous=*/false); 19469 DSAStack->addMappableExpressionComponents( 19470 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 19471 19472 // Record the expression we've just processed. 19473 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 19474 19475 // Create a mappable component for the list item. List items in this clause 19476 // only need a component. We use a null declaration to signal fields in 19477 // 'this'. 19478 assert((isa<DeclRefExpr>(SimpleRefExpr) || 19479 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 19480 "Unexpected device pointer expression!"); 19481 MVLI.VarBaseDeclarations.push_back( 19482 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 19483 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 19484 MVLI.VarComponents.back().push_back(MC); 19485 } 19486 19487 if (MVLI.ProcessedVarList.empty()) 19488 return nullptr; 19489 19490 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList, 19491 MVLI.VarBaseDeclarations, 19492 MVLI.VarComponents); 19493 } 19494 19495 OMPClause *Sema::ActOnOpenMPAllocateClause( 19496 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, 19497 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 19498 if (Allocator) { 19499 // OpenMP [2.11.4 allocate Clause, Description] 19500 // allocator is an expression of omp_allocator_handle_t type. 19501 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack)) 19502 return nullptr; 19503 19504 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator); 19505 if (AllocatorRes.isInvalid()) 19506 return nullptr; 19507 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(), 19508 DSAStack->getOMPAllocatorHandleT(), 19509 Sema::AA_Initializing, 19510 /*AllowExplicit=*/true); 19511 if (AllocatorRes.isInvalid()) 19512 return nullptr; 19513 Allocator = AllocatorRes.get(); 19514 } else { 19515 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions. 19516 // allocate clauses that appear on a target construct or on constructs in a 19517 // target region must specify an allocator expression unless a requires 19518 // directive with the dynamic_allocators clause is present in the same 19519 // compilation unit. 19520 if (LangOpts.OpenMPIsDevice && 19521 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 19522 targetDiag(StartLoc, diag::err_expected_allocator_expression); 19523 } 19524 // Analyze and build list of variables. 19525 SmallVector<Expr *, 8> Vars; 19526 for (Expr *RefExpr : VarList) { 19527 assert(RefExpr && "NULL expr in OpenMP private clause."); 19528 SourceLocation ELoc; 19529 SourceRange ERange; 19530 Expr *SimpleRefExpr = RefExpr; 19531 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 19532 if (Res.second) { 19533 // It will be analyzed later. 19534 Vars.push_back(RefExpr); 19535 } 19536 ValueDecl *D = Res.first; 19537 if (!D) 19538 continue; 19539 19540 auto *VD = dyn_cast<VarDecl>(D); 19541 DeclRefExpr *Ref = nullptr; 19542 if (!VD && !CurContext->isDependentContext()) 19543 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 19544 Vars.push_back((VD || CurContext->isDependentContext()) 19545 ? RefExpr->IgnoreParens() 19546 : Ref); 19547 } 19548 19549 if (Vars.empty()) 19550 return nullptr; 19551 19552 if (Allocator) 19553 DSAStack->addInnerAllocatorExpr(Allocator); 19554 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator, 19555 ColonLoc, EndLoc, Vars); 19556 } 19557 19558 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 19559 SourceLocation StartLoc, 19560 SourceLocation LParenLoc, 19561 SourceLocation EndLoc) { 19562 SmallVector<Expr *, 8> Vars; 19563 for (Expr *RefExpr : VarList) { 19564 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 19565 SourceLocation ELoc; 19566 SourceRange ERange; 19567 Expr *SimpleRefExpr = RefExpr; 19568 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 19569 if (Res.second) 19570 // It will be analyzed later. 19571 Vars.push_back(RefExpr); 19572 ValueDecl *D = Res.first; 19573 if (!D) 19574 continue; 19575 19576 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions. 19577 // A list-item cannot appear in more than one nontemporal clause. 19578 if (const Expr *PrevRef = 19579 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) { 19580 Diag(ELoc, diag::err_omp_used_in_clause_twice) 19581 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange; 19582 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 19583 << getOpenMPClauseName(OMPC_nontemporal); 19584 continue; 19585 } 19586 19587 Vars.push_back(RefExpr); 19588 } 19589 19590 if (Vars.empty()) 19591 return nullptr; 19592 19593 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc, 19594 Vars); 19595 } 19596 19597 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 19598 SourceLocation StartLoc, 19599 SourceLocation LParenLoc, 19600 SourceLocation EndLoc) { 19601 SmallVector<Expr *, 8> Vars; 19602 for (Expr *RefExpr : VarList) { 19603 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 19604 SourceLocation ELoc; 19605 SourceRange ERange; 19606 Expr *SimpleRefExpr = RefExpr; 19607 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 19608 /*AllowArraySection=*/true); 19609 if (Res.second) 19610 // It will be analyzed later. 19611 Vars.push_back(RefExpr); 19612 ValueDecl *D = Res.first; 19613 if (!D) 19614 continue; 19615 19616 const DSAStackTy::DSAVarData DVar = 19617 DSAStack->getTopDSA(D, /*FromParent=*/true); 19618 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 19619 // A list item that appears in the inclusive or exclusive clause must appear 19620 // in a reduction clause with the inscan modifier on the enclosing 19621 // worksharing-loop, worksharing-loop SIMD, or simd construct. 19622 if (DVar.CKind != OMPC_reduction || 19623 DVar.Modifier != OMPC_REDUCTION_inscan) 19624 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 19625 << RefExpr->getSourceRange(); 19626 19627 if (DSAStack->getParentDirective() != OMPD_unknown) 19628 DSAStack->markDeclAsUsedInScanDirective(D); 19629 Vars.push_back(RefExpr); 19630 } 19631 19632 if (Vars.empty()) 19633 return nullptr; 19634 19635 return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 19636 } 19637 19638 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 19639 SourceLocation StartLoc, 19640 SourceLocation LParenLoc, 19641 SourceLocation EndLoc) { 19642 SmallVector<Expr *, 8> Vars; 19643 for (Expr *RefExpr : VarList) { 19644 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 19645 SourceLocation ELoc; 19646 SourceRange ERange; 19647 Expr *SimpleRefExpr = RefExpr; 19648 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 19649 /*AllowArraySection=*/true); 19650 if (Res.second) 19651 // It will be analyzed later. 19652 Vars.push_back(RefExpr); 19653 ValueDecl *D = Res.first; 19654 if (!D) 19655 continue; 19656 19657 OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective(); 19658 DSAStackTy::DSAVarData DVar; 19659 if (ParentDirective != OMPD_unknown) 19660 DVar = DSAStack->getTopDSA(D, /*FromParent=*/true); 19661 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 19662 // A list item that appears in the inclusive or exclusive clause must appear 19663 // in a reduction clause with the inscan modifier on the enclosing 19664 // worksharing-loop, worksharing-loop SIMD, or simd construct. 19665 if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction || 19666 DVar.Modifier != OMPC_REDUCTION_inscan) { 19667 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 19668 << RefExpr->getSourceRange(); 19669 } else { 19670 DSAStack->markDeclAsUsedInScanDirective(D); 19671 } 19672 Vars.push_back(RefExpr); 19673 } 19674 19675 if (Vars.empty()) 19676 return nullptr; 19677 19678 return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 19679 } 19680 19681 /// Tries to find omp_alloctrait_t type. 19682 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) { 19683 QualType OMPAlloctraitT = Stack->getOMPAlloctraitT(); 19684 if (!OMPAlloctraitT.isNull()) 19685 return true; 19686 IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t"); 19687 ParsedType PT = S.getTypeName(II, Loc, S.getCurScope()); 19688 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 19689 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t"; 19690 return false; 19691 } 19692 Stack->setOMPAlloctraitT(PT.get()); 19693 return true; 19694 } 19695 19696 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause( 19697 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, 19698 ArrayRef<UsesAllocatorsData> Data) { 19699 // OpenMP [2.12.5, target Construct] 19700 // allocator is an identifier of omp_allocator_handle_t type. 19701 if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack)) 19702 return nullptr; 19703 // OpenMP [2.12.5, target Construct] 19704 // allocator-traits-array is an identifier of const omp_alloctrait_t * type. 19705 if (llvm::any_of( 19706 Data, 19707 [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) && 19708 !findOMPAlloctraitT(*this, StartLoc, DSAStack)) 19709 return nullptr; 19710 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators; 19711 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 19712 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 19713 StringRef Allocator = 19714 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 19715 DeclarationName AllocatorName = &Context.Idents.get(Allocator); 19716 PredefinedAllocators.insert(LookupSingleName( 19717 TUScope, AllocatorName, StartLoc, Sema::LookupAnyName)); 19718 } 19719 19720 SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData; 19721 for (const UsesAllocatorsData &D : Data) { 19722 Expr *AllocatorExpr = nullptr; 19723 // Check allocator expression. 19724 if (D.Allocator->isTypeDependent()) { 19725 AllocatorExpr = D.Allocator; 19726 } else { 19727 // Traits were specified - need to assign new allocator to the specified 19728 // allocator, so it must be an lvalue. 19729 AllocatorExpr = D.Allocator->IgnoreParenImpCasts(); 19730 auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr); 19731 bool IsPredefinedAllocator = false; 19732 if (DRE) 19733 IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl()); 19734 if (!DRE || 19735 !(Context.hasSameUnqualifiedType( 19736 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) || 19737 Context.typesAreCompatible(AllocatorExpr->getType(), 19738 DSAStack->getOMPAllocatorHandleT(), 19739 /*CompareUnqualified=*/true)) || 19740 (!IsPredefinedAllocator && 19741 (AllocatorExpr->getType().isConstant(Context) || 19742 !AllocatorExpr->isLValue()))) { 19743 Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected) 19744 << "omp_allocator_handle_t" << (DRE ? 1 : 0) 19745 << AllocatorExpr->getType() << D.Allocator->getSourceRange(); 19746 continue; 19747 } 19748 // OpenMP [2.12.5, target Construct] 19749 // Predefined allocators appearing in a uses_allocators clause cannot have 19750 // traits specified. 19751 if (IsPredefinedAllocator && D.AllocatorTraits) { 19752 Diag(D.AllocatorTraits->getExprLoc(), 19753 diag::err_omp_predefined_allocator_with_traits) 19754 << D.AllocatorTraits->getSourceRange(); 19755 Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator) 19756 << cast<NamedDecl>(DRE->getDecl())->getName() 19757 << D.Allocator->getSourceRange(); 19758 continue; 19759 } 19760 // OpenMP [2.12.5, target Construct] 19761 // Non-predefined allocators appearing in a uses_allocators clause must 19762 // have traits specified. 19763 if (!IsPredefinedAllocator && !D.AllocatorTraits) { 19764 Diag(D.Allocator->getExprLoc(), 19765 diag::err_omp_nonpredefined_allocator_without_traits); 19766 continue; 19767 } 19768 // No allocator traits - just convert it to rvalue. 19769 if (!D.AllocatorTraits) 19770 AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get(); 19771 DSAStack->addUsesAllocatorsDecl( 19772 DRE->getDecl(), 19773 IsPredefinedAllocator 19774 ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator 19775 : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator); 19776 } 19777 Expr *AllocatorTraitsExpr = nullptr; 19778 if (D.AllocatorTraits) { 19779 if (D.AllocatorTraits->isTypeDependent()) { 19780 AllocatorTraitsExpr = D.AllocatorTraits; 19781 } else { 19782 // OpenMP [2.12.5, target Construct] 19783 // Arrays that contain allocator traits that appear in a uses_allocators 19784 // clause must be constant arrays, have constant values and be defined 19785 // in the same scope as the construct in which the clause appears. 19786 AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts(); 19787 // Check that traits expr is a constant array. 19788 QualType TraitTy; 19789 if (const ArrayType *Ty = 19790 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe()) 19791 if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty)) 19792 TraitTy = ConstArrayTy->getElementType(); 19793 if (TraitTy.isNull() || 19794 !(Context.hasSameUnqualifiedType(TraitTy, 19795 DSAStack->getOMPAlloctraitT()) || 19796 Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(), 19797 /*CompareUnqualified=*/true))) { 19798 Diag(D.AllocatorTraits->getExprLoc(), 19799 diag::err_omp_expected_array_alloctraits) 19800 << AllocatorTraitsExpr->getType(); 19801 continue; 19802 } 19803 // Do not map by default allocator traits if it is a standalone 19804 // variable. 19805 if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr)) 19806 DSAStack->addUsesAllocatorsDecl( 19807 DRE->getDecl(), 19808 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait); 19809 } 19810 } 19811 OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back(); 19812 NewD.Allocator = AllocatorExpr; 19813 NewD.AllocatorTraits = AllocatorTraitsExpr; 19814 NewD.LParenLoc = D.LParenLoc; 19815 NewD.RParenLoc = D.RParenLoc; 19816 } 19817 return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc, 19818 NewData); 19819 } 19820 19821 OMPClause *Sema::ActOnOpenMPAffinityClause( 19822 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 19823 SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) { 19824 SmallVector<Expr *, 8> Vars; 19825 for (Expr *RefExpr : Locators) { 19826 assert(RefExpr && "NULL expr in OpenMP shared clause."); 19827 if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) { 19828 // It will be analyzed later. 19829 Vars.push_back(RefExpr); 19830 continue; 19831 } 19832 19833 SourceLocation ELoc = RefExpr->getExprLoc(); 19834 Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts(); 19835 19836 if (!SimpleExpr->isLValue()) { 19837 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19838 << 1 << 0 << RefExpr->getSourceRange(); 19839 continue; 19840 } 19841 19842 ExprResult Res; 19843 { 19844 Sema::TentativeAnalysisScope Trap(*this); 19845 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr); 19846 } 19847 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 19848 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 19849 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19850 << 1 << 0 << RefExpr->getSourceRange(); 19851 continue; 19852 } 19853 Vars.push_back(SimpleExpr); 19854 } 19855 19856 return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 19857 EndLoc, Modifier, Vars); 19858 } 19859